From 76a0ed09a952ee296ba8c25a99d438ce5989e872 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:44:44 +0200 Subject: [PATCH 001/133] docs(grouping): normative spec, implementation plan and the working rules Extracts the design from CLAUDE.md into the repo's spec/plan convention: the invariants C1-C7, the acknowledgement contract, the selection and fan-out rules of sec. 7.7, and acceptance criteria for both. Adds the multi-replica warning to the deployment guide, and the rule that this feature is worked one reviewable change at a time. Co-Authored-By: Claude Opus 5 (1M context) --- CLAUDE.md | 19 + docs/guides/deployment.md | 26 +- docs/plans/2026-08-28-multi-agent-grouping.md | 998 ++++++++++++++++++ docs/specs/2026-08-28-multi-agent-grouping.md | 741 +++++++++++++ 4 files changed, 1782 insertions(+), 2 deletions(-) create mode 100644 docs/plans/2026-08-28-multi-agent-grouping.md create mode 100644 docs/specs/2026-08-28-multi-agent-grouping.md diff --git a/CLAUDE.md b/CLAUDE.md index fccdab0c..e2a2ed51 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -62,3 +62,22 @@ cp dist/* ~/local-pypi/ # In consumer project: uv pip install --no-cache-dir --find-links file:///home/pajoma/pypi/ avs-blueprint-agents== ``` + +--- + +## Multi-Agent Grouping + +- **Spec (normative):** `docs/specs/2026-08-28-multi-agent-grouping.md` -- invariants C1-C7, API + surface, config reference, acceptance criteria. Where any other document disagrees with the + spec, the spec wins. +- **Implementation plan:** `docs/plans/2026-08-28-multi-agent-grouping.md` -- prerequisites P0-P6 + (blocking defects) and phases 0-9. + +**Work this feature in reviewable steps.** Make one change, then stop and report what changed and +why before starting the next. Do not chain phases together, and do not chain the work items within +a phase, into a single unreviewed run -- each step is meant to be looked at before the next one +begins. This rule applies to every prerequisite and phase in that plan, and only to this feature. + +Read the spec before changing `component/registry.py`, `app_builder.py`, `handler/`, +`services/eventing/`, `io/api/eventing/`, `clients/io/nats_client.py`, the schedulers or +telemetry: those paths carry invariants that are not visible from the code. diff --git a/docs/guides/deployment.md b/docs/guides/deployment.md index 622d3851..e64d4abb 100644 --- a/docs/guides/deployment.md +++ b/docs/guides/deployment.md @@ -2,6 +2,24 @@ This guide covers packaging, deploying, and operating Blueprint Agents applications in production environments using Docker, Kubernetes, and Helm. +> **Running more than one replica is not safe in the current release.** Three defects make +> horizontal scaling incorrect rather than merely inefficient: +> +> - **Every replica processes every message.** Core NATS subscriptions are created without a queue +> group (`clients/io/nats_client.py`), and JetStream is off by default (`nats_use_jetstream`), so +> two replicas silently double every side effect and every inference bill. +> - **JetStream messages are never acknowledged.** Subscriptions use `manual_ack=True` and no +> `msg.ack()` call exists anywhere, so every event redelivers until `max_deliver` — already +> true at a single replica. +> - **Every replica runs its own scheduler.** `SchedulerBase` starts an `AsyncIOScheduler` per +> process with no leader election, so each cron tick fires once per replica. +> +> Until these are fixed, deploy one replica with `autoscaling.enabled: false`. The HPA example +> below shows the chart's shape; it is not a recommendation. Required behaviour is specified in +> `docs/specs/2026-08-28-multi-agent-grouping.md`, sec. 7.1, 7.2 and 7.5; the fixes are P1, P2 and +> P5 in `docs/plans/2026-08-28-multi-agent-grouping.md`. This guide also assumes one Deployment +> per agent, and will be rewritten when group-based deployment lands. + --- ## Docker @@ -103,7 +121,7 @@ helm/ ### values.yaml ```yaml -replicaCount: 2 +replicaCount: 1 # multi-replica is unsafe in this release; see the warning at the top image: repository: myregistry.azurecr.io/my-ai-service @@ -256,7 +274,7 @@ helm install my-ai-service ./helm \ helm install my-ai-service ./helm \ --namespace ai-services \ --set image.tag="v1.2.3" \ - --set replicaCount=3 + --set replicaCount=1 # see the warning at the top: more than one is unsafe in this release # Upgrade an existing release helm upgrade my-ai-service ./helm \ @@ -386,6 +404,10 @@ This means environment variables always take precedence over file-based configur ### Horizontal Pod Autoscaling +Leave autoscaling disabled in the current release — see the warning at the top of this guide. +Scaling past one replica multiplies event processing, acknowledgement loss and cron ticks +rather than throughput. + Enable automatic scaling based on CPU utilization: ```yaml diff --git a/docs/plans/2026-08-28-multi-agent-grouping.md b/docs/plans/2026-08-28-multi-agent-grouping.md new file mode 100644 index 00000000..a824d649 --- /dev/null +++ b/docs/plans/2026-08-28-multi-agent-grouping.md @@ -0,0 +1,998 @@ +# Plan -- Multi-Agent Grouping + +| | | +|---|---| +| **Status** | not started -- no phase implemented | +| **Spec (normative)** | `docs/specs/2026-08-28-multi-agent-grouping.md` | + +This is the phased work breakdown. The spec is normative: it carries the MUST/SHOULD requirements, +the API surface, the config reference and the acceptance criteria, and where the two documents +disagree the spec wins. + +**Issues:** resolves #75; unblocks #32, #35, #20; #73 is P5 below. Related: #33, #34, #36, #43, #74. + +**Deployment model:** the namespace model below is implemented in full, but *which* agents share a +process is not hardcoded — it is selected at runtime from a group configuration +(`BLUEPRINT_GROUP` env var), and Kubernetes runs one Deployment per group. Group size 1 gives +per-agent process isolation; group size 20 gives the shared-process memory profile. Nothing in +Phases 0-7 changes because of this; Phases 8-9 add the loader and the deployment-facing +constraints. + +The spec (sec. 3) defines seven invariants (C1-C7) that this plan must satisfy. They are +referenced by number in the phases below. C1-C6 keep regrouping invisible from outside the process; C7 (no +silent failure at agent granularity) keeps the isolation cost grouping *does* incur attributable, +and is therefore what makes the group-size dial usable in response to a real failure. + +## Goals + +- One app, one port, one health endpoint, one NATS/Dapr connection — shared infrastructure + is never duplicated. +- Components gain an optional **namespace** (`""` by default). Empty namespace = today's + single-agent world. Zero migration required for existing projects. +- **Opt-in multi-agent capability per agent.** A developer who wants their agent to + participate in a multi-agent system makes exactly two changes: `main.py` and `Dockerfile`. + Developers who do not opt in keep their current code and deployment unchanged. +- **Multiple named `CacheService` instances** can be registered independently, looked up + by name from any namespace, and added at runtime after startup. +- Every phase is independently shippable and backwards compatible. +- **Per-namespace I/O isolation.** Each namespace gets its own `ThreadPoolExecutor` + (for blocking `DiskCacheService`/SQLite calls via `run_in_executor`) and its own + `AIClientBase` instance (separate async HTTP connection pool), so one agent's I/O + load cannot stall another's. +- **Grouping is a deployment parameter, not an architectural commitment.** Regrouping an agent + must never change its broker-side consumer identity (C1) or its telemetry identity (C2). + If a change makes regrouping observable to the broker or to a dashboard, it is wrong. + +--- + +## Prerequisites (blocking defects in the current code) + +These are independent of the namespace work and would need fixing under any option. **They block +scaling any group past one replica** and must land before the multi-agent phases ship. + +**P0 — Transport lifecycle: managed subscription, retry, reconnect, readiness.** Lands as part +of this work, ahead of everything else in this list, because the rest of it sits on top: + +- `ClientBase.subscribe(topic_callbacks)` replaces `subscribe(topic, callback)` — one call + carrying the whole `{topic: callback}` map, non-blocking, backed by a background retry task. + P6's per-namespace clients need exactly this shape. +- `subscriptions_ready` plus health-check gating. C4 and C7 read it, and Phase 9 drives + `blueprint_namespace_up` from it. +- `disconnected_cb` / `reconnected_cb`, re-subscribing JetStream durables on reconnect. P2's + correctness depends on this path: the server redelivers everything unacked after a reconnect. +- Config keys `event_client_max_retries` (default `-1`, indefinite) and `event_client_retry_delay` + (default `5.0`). + +Three gaps to close while landing it, none of which the original PR addressed: + +- **No shutdown drain.** `close()` cancels the retry task and unsubscribes under + `contextlib.suppress(Exception)`, so in-flight handlers lose their acknowledgement on every + deploy — duplicates on the next start are certain, not merely possible. Drain in-flight work + before unsubscribing, bounded by a timeout. +- **The `except Exception` swallow in `message_handler` must not survive the port** (see P2). +- **`DaprEventing` registers a callback map with `DaprClient` while delivery still arrives on + `POST /events/{topic}`,** so that callback appears unused for delivery and exists only to drive + readiness. Settle its role or remove it. + +**P1 — Core NATS subscriptions have no queue group.** `clients/io/nats_client.py:250` calls +`client.subscribe(topic, cb=...)` with no `queue=`. JetStream is off by default +(`nats_use_jetstream`, `nats_client.py:102`), so the default path today is: *every replica +processes every message*. Setting `replicas: 2` silently doubles every side effect and every +inference bill. Fix: `queue=` — derived from the namespace, never from the group or +container (C1). + +**P2 — JetStream messages are never acknowledged.** `clients/io/nats_client.py:242-247` +subscribes with `manual_ack=True`, and there is no `msg.ack()` call anywhere in the codebase. +Every message redelivers after `ack_wait` until `max_deliver`. This is already a defect at one +replica — each event is processed repeatedly — and at N replicas it presents as a scaling +problem but is not one. + +The contract is normative in spec sec. 7.2: **a normal return acks, a raised exception does not.** +`ProcessingStatus` has exactly two values, `PROCESSED` and `NO_HANDLER_FOUND`, so no failure can +reach the transport as a returned value. That is why the transport edge never inspects +`ProcessingResult` — it would learn nothing — and why an event that matches no handler's +conditions acks like any other completed dispatch instead of being redelivered until +`max_deliver`. + +What blocks this today is not the missing `msg.ack()` call but two layers that discard the +classification before it can reach one: + +| Layer | Behaviour | +|---|---| +| `_process_cloud_event` (`io/api/eventing/event_handling_base.py`) | logs and **re-raises** — correct, keep | +| `_process_event` (`io/api/eventing/nats.py`) | catches `RetryableHandlerError`, `InvalidEventError`, `CriticalHandlerError`, logs, returns `None` | +| `message_handler` (`clients/io/nats_client.py`) | catches `Exception`, logs, returns | + +Work items: + +- Remove the `except` block from `_process_event` so classified exceptions reach the transport. +- In `message_handler`, ack on normal return and map exception type to `nak()` / `term()` per the + spec table. Distinguish *before* dispatch from *during* dispatch: a payload that fails JSON or + CloudEvent parsing terms, because it will not parse on redelivery either. +- Leave the callback type `Callable[[CloudEvent[Any]], Awaitable[None]]` unchanged. The + classification travels as an exception, so no signature widens and P0's nine callback-type + declarations stay untouched. Widen it only if P4's dedup or C7's in-flight gauge later needs the + result object at the transport edge — and then once, deliberately, not twice. +- Bring Dapr into line (spec sec. 7.2): `NO_HANDLER_FOUND` → `SUCCESS` (`dapr.py:75`), + `CriticalHandlerError` → `DROP` (`dapr.py:102`), and the same in + `event_handling_base.handle_event`, whose returned dict *is* Dapr's acknowledgement. +- Add the unhandled-event counter and the first-occurrence WARNING per (namespace, topic), so + acking an unmatched event does not hide a topic nobody handles. +- Configure `max_deliver` and a dead-letter destination (with P3), since nak on an unexpected + exception otherwise redelivers forever. + +**P3 — Consumer tuning is not configurable.** Expose `ack_wait` (must exceed p99 handler +duration, or long LLM work is redelivered to another replica mid-flight) and `max_ack_pending` +(the real cross-replica concurrency cap). + +**P4 — Idempotency, flagged not enforced.** Competing consumers make at-least-once permanent, and +ack loss makes duplicate delivery *certain* rather than possible: a handler that finishes 60s of +inference and then cannot ack has already committed its side effects, and the broker redelivers +after `ack_wait`. But whether dedup is *correct* depends on the product built on the blueprint — +some operations are naturally idempotent, others need business-level reconciliation the framework +cannot see. So: provide an opt-in dedup mechanism (CloudEvent `id`, namespace cache, TTL, in the +handler chain before dispatch), default **off**, and surface the requirement explicitly to the +author — scaffolded handler comment, generated README, `asbs validate` notice. The author must +make a decision, not inherit one silently. + +**P5 — Cron becomes an event source (#73).** `SchedulerBase.on_startup` creates an +`AsyncIOScheduler` per process with no leader election, so every cron tick fires once per replica. +Grouping widens this: one pod with 20 agents runs 20 schedulers, and two replicas duplicate all +20 agents' crons at once. + +The fix is not leader election in production — it is removing the in-process timer: + +```toml +scheduler_mode = "event" # default: schedule lives outside; the tick arrives as an event + "in_process" # apscheduler + leader lease, for plain Docker and local dev +``` + +**`"event"`** — a Kubernetes `CronJob` publishes a NATS message; the agent handles it through the +event path it already has. A ~10 MB `nats-cli` container, not a pod re-paying the 154 MB baseline +(#32). The queue group already guarantees exactly one replica picks it up, so nothing is elected; +idempotency dedup, telemetry attribution and namespace routing all apply for free. One execution +model instead of two. + +The developer still **declares** the schedule in the agent; the build **generates** the `CronJob` +from that declaration, the same way manifests are generated from `deployment-groups.yaml`. Without +generation, code can expect a tick nobody scheduled. + +**`"in_process"`** — the existing timer plus a NATS KV or cache-backed lease. Needed for +un-orchestrated Docker and for local dev, where a `CronJob` is not available. Cheap to keep: event +mode is "do not start the timer", since the handler path already exists. + +Neither mode is exactly-once. `CronJob` is at-least-once (controller restart, missed +`startingDeadlineSeconds`) and a lease can briefly have two holders if it expires mid-tick, so P4 +applies either way. Set `concurrencyPolicy: Forbid` to prevent overlap, and watch that `CronJob` +`timeZone` and apscheduler timezone handling agree across modes. + +Note #43 — schedulers started twice *within* one process by two `build()` passes — is a distinct +defect; both touch scheduler startup and should be fixed together. + +**P6 — Transport topology: one connection per namespace.** Not a defect, but it belongs here +because it changes `NATSClient` ownership. Per-namespace clients confine ack loss and +slow-consumer disconnects to one agent, and give named connections in `/connz` — +`nats.connect()` is called today with no `name=` at all (`nats_client.py:93`). No config knob: a +socket plus buffers against ~65 MB for a separate process (#32). For a single-agent app it is a +no-op — one namespace, one connection. `EventPublishingService` becomes per-namespace too, or +outbound traffic stays unattributable. The connection name contains the pod and **must never** +feed C1 naming. + +Two scoping points, both easy to get wrong: + +- **NATS only.** Under Dapr the app holds no broker connection — `DaprClient` is an `httpx` client + against the sidecar (`dapr_client.py:89`), and the sidecar owns and multiplexes one broker + connection per pod. Connections track pods there, and the ack-loss and slow-consumer arguments + move into the sidecar. A per-namespace `DaprClient` is still useful for health attribution and + C4, but it does not confine either failure. +- **Not a durability mechanism.** JetStream pending state is the server's, keyed by consumer and + stream sequence; an ack is a publish to the per-delivery reply subject, not an entry in a + framework-side registry. A shared connection therefore has no in-flight state to lose when the + process dies. The topology decides how many namespaces *repeat* work after a connection drop — + nothing more. Durability is settled by P1/P2, not here. + +--- + +## Namespace model + +``` +Root Registry (namespace="") +├── nats_client ← shared IO transport (one connection) +├── event_publishing_service ← shared +├── actuator_api ← one health endpoint +│ +├── Named caches (flat, namespace-independent) +│ ├── "default" ← backwards-compat alias for registry.cache_service +│ └── "orders" ← any name, accessible from every namespace +│ +├── Namespace "invoice" +│ ├── invoice_agent (AgentRuntime) +│ ├── invoice_handler (EventHandlerBase) +│ ├── invoice_api (RestApiBase) → routes at /api/invoice/... +│ ├── invoice_ai_client (AIClientBase) ← isolated connection pool +│ └── _executor (ThreadPoolExecutor) ← blocking I/O isolation +│ +└── Namespace "order" + ├── order_agent (AgentRuntime) + ├── order_handler (EventHandlerBase) + ├── order_api (RestApiBase) → routes at /api/order/... + ├── order_ai_client (AIClientBase) ← isolated connection pool + └── _executor (ThreadPoolExecutor) ← blocking I/O isolation +``` + +**Component resolution rule** for `get_component(Type, namespace="invoice")`: +1. Search `"invoice"` namespace — if exactly one match, return it. +2. Fall back to root `""` — if exactly one match, return it. +3. Raise only if ambiguous within the same level. + +**Cache resolution** is by name only — no namespace dimension. +`registry.get_cache("orders")` works identically from any namespace. + +--- + +## Migration path for an existing agent + +**No change (stays standalone):** developer does nothing — existing `main.py` and +Dockerfile work as-is forever. + +**Opt in to multi-agent:** two file changes only. + +`main.py` before: +```python +app = ( + AppBuilder(config) + .with_service(OrderService) + .with_handler(OrderValidationHandler) + .with_handler(OrderEnrichmentHandler) + .with_rest_api(OrderApi) + .with_cache() + .build() +) +``` +Dockerfile before: `CMD uvicorn src.main:app --host 0.0.0.0 --port 8000` + +`main.py` after — **one declaration, no branches**: +```python +from blueprint.agents import AgentRegistration + +registration = ( + AgentRegistration() + .with_service(OrderService) + .with_handler(OrderValidationHandler) + .with_handler(OrderEnrichmentHandler) + .with_rest_api(OrderApi) +) +``` +Dockerfile after: `CMD python -m blueprint.agents.entrypoint` + +An earlier draft of this plan used a dual-branch `main.py` — +`if __name__ == "__main__": AppBuilder(...)...run_app()` / `else: registration = ...`. That is +**rejected**: it makes the developer write the component list twice and keep both copies in sync, +and it exposes the existence of two worlds. Running a single agent is `asbs dev agents/order`, +which wraps the registration as a group of one. No `AppBuilder`, no `Config`, no `run_app`, no +`if __name__` in agent code (C6). + +Because the module is imported into a shared runtime, it **must** contain only the registration — +no client construction at import time, no module-level mutable state, no `logging.basicConfig()`. +CI check: import each agent module, assert the registry is still empty and the root logger has no +handlers. + +The global orchestrating `main.py` (no uvicorn, just a FastAPI app): +```python +from blueprint.agents import AppBuilder, Config +from order_agent.src.main import registration as order_reg +from invoice_agent.src.main import registration as invoice_reg + +config = Config(settings_files=["settings.toml"]) + +app = ( + AppBuilder(config) + .with_cache("orders") + .with_namespace("order", registration=order_reg) + .with_namespace("invoice", registration=invoice_reg) + .build() +) +``` + +--- + +## API route namespacing + +`RestApiBase` subclasses require no changes. `_build_rest_endpoints` reads +`rest_api._namespace` and adjusts prefix and tags at router-inclusion time. + +| Mode | Declared tag | Route | OpenAPI tag | +|---|---|---|---| +| Standalone (`namespace=""`) | `"Orders"` | `/api/orders/{id}` | `Orders` | +| Multi-agent (`namespace="order"`) | `"Orders"` | `/api/order/orders/{id}` | `order.Orders` | + +--- + +## Component sharing rules + +| Component | Sharing | Notes | +|---|---|---| +| `NATSClient` / `DaprClient` | **Per-namespace** | One named connection per agent (P6). Confines ack loss and slow-consumer kicks; single-agent apps unchanged | +| `EventPublishingService` | **Per-namespace** | Must publish on its own namespace's client, or outbound traffic is unattributable | +| `EventProcessingService` | Shared (root) | Namespace passed per-call | +| `ActuatorApi` | Shared (root) | One health endpoint | +| `CacheService` | **Namespace-scoped by default** | Explicit opt-in for genuinely shared caches. A flat store lets two independently developed agents both call `get_cache("sessions")` and silently share it once grouped. Sync ops via `run_in_executor` + namespace executor | +| `AIClientBase` | Per-namespace strongly recommended | Shared async HTTP pool causes one agent's LLM calls to starve another's | +| `ThreadPoolExecutor` | Per-namespace | Provisioned by `with_namespace`; prevents blocking DiskCache/SQLite from stalling event loop of other namespaces | +| `EventHandlerBase` | Per-namespace | Core routing unit | +| `AgentRuntime` | Per-namespace | Each agent in its own namespace | +| `RestApiBase` | Per-namespace | Routes prefixed `/api/{namespace}/` | +| `ServiceBase` (user) | Per-namespace | Typical; can be root if truly stateless and shared | +| `SchedulerBase` | Per-namespace | Typical | +| `SessionsApiClient` | Shared (root) | One sessions backend | + +--- + +## Phase 0 — `run_app` utility + `AgentRegistration` (no breaking changes) + +**Files:** `utils/utils.py`, `app_builder.py`, `__init__.py` + +`run_app(app: FastAPI, config: Config) -> None` in `utils/utils.py`: +- Imports uvicorn and starts the server with dev/prod settings derived from config. +- `app_environment = "development"` → `reload=False` (reload requires a string reference, + not an object; developers who need reload use the uvicorn CLI directly), workers=1, + log level debug. +- `app_environment` anything else → workers from `app_workers` config (default 1), + log level from `log_level` config (default `"info"`). +- Config keys read: `app_host` (default `"0.0.0.0"`), `app_port` (default `8000`), + `app_environment`, `log_level`, `app_workers`. + +`AgentRegistration` class in `app_builder.py`: +- Fluent collector — same `with_handler`, `with_service`, `with_agent`, `with_rest_api`, + `with_scheduler` signatures as `AppBuilder` (and `NamespaceBuilder`), but stores + component classes instead of instantiating them. +- No `with_cache()` — caches are global and registered on the orchestrating `AppBuilder`. +- Internal `_apply(namespace_builder: NamespaceBuilder) -> None` iterates stored entries + and calls the corresponding `with_*` on the provided builder. Called by + `AppBuilder.with_namespace(..., registration=reg)`. +- **Namespace injection:** at the start of `_apply`, set a module-level + `ContextVar[str]` (defined in `component.py`) to `namespace_builder._namespace`; reset + it in a `finally` block after all `with_*` calls complete. `Component.__init__` reads + the ContextVar to determine its namespace — zero changes required to user-defined + constructors. In the standalone case the ContextVar default (`""`) is never overridden. + +Export both `run_app` and `AgentRegistration` from `blueprint.agents.__init__`. + +--- + +## Phase 1 — Registry namespace + named cache support + +**File:** `component/registry.py` + +**Namespace storage:** +- Change `_components: dict[str, Any]` to `dict[str, dict[str, Any]]` + (namespace → name → component). Root namespace key is `""`. +- Add `namespace: str = ""` param to `add_component`, `update_component_name`, + `get_component`, `get_components_by_type`, `get_component_names_by_type`, `has_component`. +- `get_component` implements two-level fallback: own namespace → root `""` → raise. +- All typed convenience getters (`get_event_handler`, `get_agents`, `get_services`, + `get_schedulers`, `get_rest_apis`, `get_clients`) accept optional `namespace=""`. +- `add_component` raises on name collision only within the same namespace. +- `get_known_namespaces() -> list[str]` returns all registered namespace keys + (used by `NatsEventing` and `build()` to iterate all namespaces). + +**Named cache storage (replaces the single `_cache_service`):** +- Replace `_cache_service: CacheService | None` with `_caches: dict[str, CacheService]`. +- `add_cache(name: str, service: CacheService) -> None` — upsert; no "already registered" + guard, so caches can be added at any time after startup. +- `get_cache(name: str = "default") -> CacheService` — raises `ValueError` if not found. +- `get_or_create_cache(name: str, factory: Callable[[], CacheService]) -> CacheService` — + atomic get-or-create protected by an `asyncio.Lock` for safe concurrent first-access. +- `has_cache(name: str = "default") -> bool`. +- `get_all_caches() -> dict[str, CacheService]` — returns a shallow copy of `_caches`. + Used by `ActuatorApi` (health checks) and `CacheManagementApi` (management endpoints) + instead of accessing `_caches` directly. +- `cache_service` property kept as alias for `get_cache("default")` — backwards compat. +- `cache_service` setter kept as alias for `add_cache("default", value)` — backwards compat. + +**Executor registry:** +- Add `_executors: dict[str, ThreadPoolExecutor]` (namespace → executor). +- `add_executor(namespace: str, executor: ThreadPoolExecutor) -> None`. +- `get_executor(namespace: str = "") -> ThreadPoolExecutor` — falls back to root `""` if + the namespace has no executor; raises `ValueError` if root is also missing. +- The root executor is provisioned in `AppBuilder.build()` (not in `with_namespace`) so + standalone apps always have one. + +**Backwards compatibility:** All callers omitting `namespace` use `""` and see today's flat +registry. Existing `registry.cache_service` access is unaffected. + +--- + +## Phase 2 — Component namespace awareness + +**File:** `component/component.py` + +- Add a module-level `_current_namespace: ContextVar[str] = ContextVar("_current_namespace", default="")`. +- `Component.__init__` reads `_current_namespace.get()` and stores it as `self._namespace`. +- Pass `self._namespace` to `registry.add_component(name, self, namespace=self._namespace)`. +- Add `executor` property: returns `registry.get_executor(self._namespace)`, falling back + to a root-level executor if none is registered for that namespace (root namespace always + has a default executor created in `build()`). Used by `CacheService` subclasses to + offload sync DiskCache/SQLite calls via `asyncio.get_event_loop().run_in_executor`. +- `Component.shared_registry` remains a single class-level singleton. + +**Backwards compatibility:** Default `namespace=""` — existing subclasses unchanged. + +--- + +## Phase 3 — NamespaceBuilder and AppBuilder extension + +**File:** `app_builder.py` + +- Add `NamespaceBuilder` class (same file): + - Holds reference to parent `AppBuilder` and its `namespace` string. + - Exposes `with_handler`, `with_agent`, `with_service`, `with_scheduler`, + `with_rest_api` — each delegates to parent with `namespace=self._namespace`. + - No `with_cache` — caches are always registered at root level. + - `end() -> AppBuilder` for explicit block-close style. + - All `with_*` methods return `self` for chaining. +- `AppBuilder.with_namespace(name: str, *, registration: AgentRegistration | None = None, config: Config | None = None) -> AppBuilder`: + - Creates a `NamespaceBuilder` for `name`. + - **C5 — namespace-scoped config.** `Config` already supports `agent_scope` + (`config/config.py`), which tries `.` before falling back to `` at root. + When `config` is omitted, `with_namespace` builds one with `agent_scope=name` from the root + config's settings files. Prompts, model selection and usage limits become per-agent while + infrastructure keys stay shared. Components in the namespace receive this scoped `Config`. + - Provisions a `ThreadPoolExecutor(max_workers=config.get("executor_workers", os.cpu_count() + 4))` + for the namespace and registers it in the registry under that namespace key. + - If `registration` is provided, calls `registration._apply(ns_builder)` and returns + `self` — no `.end()` needed. This is the primary multi-agent API. + - If omitted, returns the `NamespaceBuilder` for indent-and-`.end()` style. + - Executors are shut down gracefully (`.shutdown(wait=True)`) in the lifespan shutdown + sequence, after all components have stopped. +- Add `namespace: str = ""` to all existing `AppBuilder.with_*` methods (except + `with_cache`) for direct tagged calls. **Keyword-only** — `process_event` and friends already + have positional tails. +- `AppBuilder.with_cache(enabled=True, enable_locking=True, *, name="default")` creates a + `CacheService` via `CacheBackendFactory` with `cache_dir = {base_dir}/{name}` (when + `name != "default"`, else the configured `cache_dir`) and calls `registry.add_cache(name, service)`. + + **`name` must be keyword-only and must follow the two existing positional parameters.** The + current signature is `with_cache(enabled: bool = True, enable_locking: bool = True)` + (`app_builder.py:117`). Making `name` first would turn an existing `with_cache(False)` — which + *disables* caching — into a cache named `False`: caching silently switched on, no `TypeError`, + no warning. This is the only signature-level break in the whole plan; get it right here. +- Executors are created **lazily on first `Component.executor` access**, not eagerly in `build()`. + Eager creation would add ~`cpu_count + 4` idle threads to every existing single-agent app and + works against #36's thread-count budget. + +**Backwards compatibility:** `with_cache()`, `with_cache(False)` and `with_cache(True, False)` all +behave exactly as today. All existing `with_*` calls default to `namespace=""`. + +--- + +## Phase 4 — Namespace-scoped HandlerChain and EventProcessingService + +**Files:** `handler/handler_chain.py`, +`services/eventing/event_processing_service.py` + +`HandlerChain`: +- Constructor accepts `namespace: str = ""`. +- `process()` fetches `registry.get_event_handler(namespace=self._namespace)`. + +`EventProcessingService`: +- Add `namespace: str = ""` param to `process_event` and `process_rest_request`. +- Lazy-create one `HandlerChain` per namespace in a `dict[str, HandlerChain]`. +- Wire previously unused `runtime_name`: after chain picks winner, resolve agent via + `get_runtime_name()` (Phase 7) within the namespace. + +**Dispatch index (spec sec. 7.7).** `handler_chain.py:52-55` sorts every registered handler and +calls `can_handle` on each until one returns non-`None`. Build a `dict[event_type, list[handler]]` +once at startup from declared event types, priority-sorted, and evaluate only the candidates for +an event's type plus the wildcard bucket. The chain-of-responsibility fallthrough is preserved: +a candidate whose `handle` returns `None` still passes to the next. + +**Handlers that declare nothing MUST stay in the wildcard bucket** and be evaluated for every +event, which is today's behaviour. Nothing in the framework or in any scaffolded project declares +event types today — `get_subscribed_topics()` is overridden nowhere and the generated +`handler.txt` selects purely in `can_handle_event` — so an index that treats declarations as +authoritative silences every existing handler, and P2's ack contract then discards the events +instead of letting them pile up. `SessionsJobHandler` is the model case for opting in: its +`can_handle_event` is `event.type == f"sessions.job.created.{self.JOB_TYPE}"`, so the framework can +derive its declaration from `JOB_TYPE` without the author writing one. + +**Backwards compatibility:** Omitting `namespace` defaults to `""` — today's behaviour. The index +changes selection for no handler that has not opted in. + +--- + +## Phase 5 — NATS per-namespace topic routing + +**Files:** `io/api/eventing/nats.py`, +`io/api/eventing/cloud_event_processor_mixin.py`, +`io/api/eventing/event_handling_base.py` + +`NatsEventing.on_startup()`: +- Iterate `registry.get_known_namespaces()`, collect `(namespace, topic)` pairs from each + handler's `get_subscribed_topics()`. +- **Deduplicate within a namespace only.** Two agents subscribing to the same topic is + legitimate and expected — both want the event. A cross-namespace "first declaration wins" rule + silently disables one agent's subscription, and the author cannot observe it locally. Each + `(namespace, topic)` pair gets its own subscription and its own consumer. +- Each `_subscribe_to_topic(topic, namespace)` closure passes `namespace=` to + `_process_cloud_event`. + +**Broker-side filter derivation (spec sec. 7.7).** Give each namespace's JetStream consumer a +`filter_subjects` set, so a broad subject stops fanning every message out to every namespace. The +set is the union of that namespace's declared `get_subscribed_topics()` and the configured +`nats_subscriptions` — that is, exactly what is subscribed today, expressed one layer down. +**Never infer a narrower filter from handler code**: an agent on `orders.>` whose handler selects +by payload must keep receiving all of it. + +Collapse the derived set to the agent's domain prefix rather than tracking the exact handler list. +A durable's filter set is broker state, so a filter that follows handler churn turns adding one +handler into a consumer reconfiguration — and possibly a redelivery storm on deploy. + +`CloudEventProcessorMixin._dispatch_cloud_event`: +- Accept `namespace: str = ""`, forward to `EventProcessingService.process_event`. + +`NATSClient` consumer identity (**C1 — invariant, cover with a test**): +- JetStream durable: `f"{namespace}-{topic}-durable"` when namespace non-empty; config default + otherwise. +- Core NATS queue group: `queue=namespace` (see P1). +- Both derive from the **agent/namespace name only** — never from the group name, container + name, pod name or any deployment identifier. This is what makes replicas of a group compete + correctly *and* makes moving an agent between groups invisible to the broker. A durable name + that picks up the group name produces a fresh consumer on regrouping: replay from the start of + the stream, or a silent gap, depending on the delivery policy. + +**Migration note (spec sec. 7.7) — this rename is a consumer migration.** Today the durable is +`nats_durable_name` from config, or `f"{topic}-durable"`. On the first deploy of this phase every +pre-existing consumer becomes a new consumer, which resumes according to its delivery policy: +replay from the start of the stream, or a gap covering whatever arrived in between. The release +notes **must** state which, and the same applies to any later change of a filter set. Do not ship +this phase and a filter-set change in the same release — if something replays, you want to know +which change caused it. + +One `NATSClient` **per namespace** (P6), named `f"{namespace}.{group}.{pod}"`. The connection name +contains the pod, so it must never feed durable or queue naming. + +**Backwards compatibility:** No declared namespaces → single root namespace → one connection → +same as today. + +--- + +## Phase 6 — AppBuilder.build() multi-namespace awareness + API route namespacing + +**File:** `app_builder.py` + +- `_eventing_component` → `list[DaprEventing | NatsEventing]` (one element initially). +- `build()` scans all known namespaces when deciding whether to create an event bus client. +- Lifespan manager and `_build_rest_endpoints` iterate the list. +- **API route namespacing** in `_build_rest_endpoints`: when `rest_api._namespace` is + non-empty, rewrite `route.tags` to `[f"{ns}.{tag}" for tag in route.tags]` and include + the router with `prefix=f"/api/{ns}"`. Empty namespace → unchanged behaviour. +- `CacheManagementApi`: one router, endpoints accept optional `?name=` query param + (defaults to `"default"` for backwards compat). +- `ActuatorApi` cache health: iterates all entries in `registry._caches` at startup time. + +--- + +## Phase 7 — Handler → Agent binding (get_runtime_name) + +**Files:** `handler/event_handler_base.py`, +`services/eventing/event_processing_service.py` + +`EventHandlerBase`: +- Add `get_runtime_name(event, context) -> str | None`, default returns `None`. + +`EventProcessingService.process_event`: +- Call `winner.get_runtime_name(event, context)` after chain selects a handler. +- Non-`None` → `registry.get_agent(name, namespace=namespace)`. +- `None` + exactly one agent in namespace → use it (today's implicit behaviour). +- `None` + multiple agents + no name declared → raise a descriptive error. + +--- + +## Phase 8 — Group configuration + entry point + +**Files:** new `group_config.py` (`GroupConfig`), new `entrypoint.py` (runnable as +`python -m blueprint.agents.entrypoint`), `app_builder.py` (`with_group`, `from_group`), +`utils/utils.py` + +Turns the group configuration into a running app. Everything here is additive; standalone +`main.py` deployments are untouched. + +**Not a separate "orchestrator" component.** The split is resolution versus wiring, and the +looping-over-agents half belongs in `AppBuilder` — it already reads config to make wiring +decisions (`with_cache` picks a backend, `with_namespace` sizes an executor). What stays outside +is the I/O: env reads, file reads, `sys.exit`, and knowledge of the agent repo's file layout. +`AppBuilder` must remain a pure function of its call sequence so tests can construct exact +compositions without controlling env or filesystem — the same layering mistake as putting retry +logic in `EventHandlingBase` (see the event-client resilience decision record). + +Avoid the name "orchestrator": it names the App-of-Apps supervisor process that this design +rejected, and reusing it invites confusion with a component that deliberately does not exist. + +`deployment-groups.yaml` — single source of truth, read by the entry point at runtime, by the +CI gate, and by Kubernetes manifest generation (Argo CD `ApplicationSet` list generator over +`groups`, or Helm values), so the container and the cluster cannot drift: + +```yaml +groups: + - name: finance + agents: [invoice, order, dunning] + resources: {cpu: "2", memory: "2Gi"} + replicas: 2 + - name: contract-analysis # alone: CPU-heavy, isolated blast radius + agents: [contract-analysis] + replicas: 3 +``` + +Agent discovery — explicit map (`agents.toml`), no convention scanning. **This one is baked into +the image**; it changes only when an agent is added or removed, which is a rebuild anyway: + +```toml +[agents.invoice] +module = "agents.invoice.main:registration" +``` + +**Configuration delivery — both mechanisms, and they compose.** The group configuration is never +baked into the image. + +1. **YAML file at a configurable path.** `BLUEPRINT_GROUP_CONFIG` (default + `./deployment-groups.yaml`) plus `BLUEPRINT_GROUP` to pick the group. The path is + configuration, not a constant, so one image serves a ConfigMap mount in Kubernetes, a bind + mount in `docker run`, and the repo file in local dev. Falling back to the repo file is what + makes `python -m blueprint.agents.orchestrator` work with no cluster and no mount. + `BLUEPRINT_GROUP` may be omitted when the file declares exactly one group. What gets mounted + is the **resolved slice** for one group, not the full multi-group document. +2. **Environment variables injected directly.** `BLUEPRINT_AGENTS=invoice,order,dunning` and + `BLUEPRINT_CRITICAL_AGENTS=invoice` (feeds `readiness_policy = "critical"`, C3). No file, no + mount. Because these live in the pod template, changing them changes the template hash and + Kubernetes rolls automatically — a property the mounted file does not have. + +**Precedence: env vars override the file, key by key** (12-factor). The file supplies the +baseline; a single Deployment can override one field without editing or duplicating it. Log the +resolution at startup: which source each value came from, and the final agent list. + +Both are read **before** `Config` is constructed — group resolution decides which agents get a +`Config` at all, so it is a plain env read plus a small YAML parse, deliberately not routed +through Dynaconf. Hence the explicit `BLUEPRINT_` prefix rather than Dynaconf's `DYNACONF_` +override mechanism. + +Entry point, in full: + +```python +def main() -> None: + config = Config(settings_files=["settings.toml"]) + group = GroupConfig.resolve(config) # env + file, validated; the only I/O + app = AppBuilder(config).with_group(group).build() + run_app(app, config) +``` + +`AppBuilder.from_group(config)` collapses lines 2-3 for callers who want one call; `with_group` +takes an in-memory `GroupConfig` and performs no I/O, so tests construct one literally. + +Flow: +1. `GroupConfig.resolve`: read the YAML at `BLUEPRINT_GROUP_CONFIG` if present, apply env-var + overrides key by key, log the effective source of each value. +2. Validate every agent named in the group against the in-image `agents.toml` map. Fail fast, + naming the group and the missing agent — this seam turns a config typo into a crash-loop with + a readable message instead of a silently short-staffed pod. +3. Resolve each name via `importlib.import_module` + `getattr`, **lazily and per group** — only + the modules this group needs are imported, so cold start stays proportional to group size. +4. `with_group` calls `with_namespace(agent, registration=reg)` per agent; `build()`; `run_app`. + +**Resolution must complete before the first `Component.__init__`,** because namespace injection +happens through the ContextVar read during construction. No incremental resolution, no namespace +added once wiring has started. + +**Startup failure policy.** There is no partial build — one process, one `build()` — so the +`critical` flag is evaluated *before* a namespace is wired, not after an exception: + +| Failure | `critical: true` (default) | `critical: false` | +|---|---|---| +| Agent missing from `agents.toml` | exit non-zero | log ERROR, skip | +| Module import raises | exit non-zero | log ERROR, skip | +| `on_startup` raises | exit non-zero | mark namespace down, pause consumers (C4), continue | + +Exit before the port is bound, so Kubernetes crash-loops with a readable message. Default +`critical: true`: a partially loaded group whose missing agent's queue has no consumer is worse +than no pod at all. The same flag drives `readiness_policy = "critical"` — one concept, both +startup and runtime. + +**Startup log** must include the group name, the agent list, the source of each resolved config +value, and per namespace the queue group and durable names. That last item makes C1 verifiable by +diffing startup logs across a regrouping. + +**Settings fragment merge.** Each agent ships an unscoped `settings.toml` in its own directory +(`model_name = "..."`, not `[default.order] model_name`). The build merges each fragment under its +own scope so C5 resolves it, without the author knowing scopes exist. Collisions between a +fragment and a root key are reported at build time. + +One image for the whole platform; the group is injected at container start, not baked at build +time. Build-time dependency trimming is an opt-in optimisation for sharply diverging dependency +sets or hard tenant boundaries only — it does not change this format. + +**Deployment note (agent repo, not this repo):** when mounting a file, give the ConfigMap a +content-hashed name (`finance-group-a1b2c3`) — kustomize's `configMapGenerator` default, or a +Helm `checksum/config` annotation. A plain ConfigMap edit leaves the pod template unchanged, so +nothing restarts and the orchestrator keeps running the group it resolved at startup. One +ConfigMap per group, not one shared: a shared one rolls all twenty agents whenever any group +changes. + +--- + +## Phase 9 — Deployment-facing constraints (telemetry, probes) + +**Files:** `io/telemetry/telemetry.py`, `io/api/actuators/actuator_api.py`, +`io/api/actuators/health.py` + +**C2 — per-namespace telemetry identity.** `telemetry.py:39-41` currently builds one `Resource` +with one `service.name` for the whole process. Setting it to the group name would break every +dashboard, alert and SLO on the day of a regrouping. Instead: one `TracerProvider` and +`MeterProvider` per namespace, each with +`Resource({"service.name": , "deployment.group": , "service.instance.id": })`, +all sharing a single exporter and `BatchSpanProcessor`. Dashboards key on agent and stay blind +to grouping. + +**Empty-namespace path is mandatory.** Implemented naively, a single-agent app would get +`service.name = ""` and its dashboards would go dark on upgrade. Namespace `""` must keep +producing exactly one provider using `otel_service_name` from config, as today. + +**C3 — liveness is never namespace-dependent.** If one degraded namespace fails the pod's +liveness probe, Kubernetes restarts every agent in the group, reintroducing the blast radius the +grouping was paid for. +- Liveness: process and event loop only. +- Readiness: `readiness_policy` config — `"all"` (default; any degraded namespace → not ready), + `"critical"` (only namespaces flagged `critical` in the group config gate readiness), `"any"` + (ready while at least one namespace is up). +- Per-namespace degradation surfaces as a `blueprint_namespace_up{agent="..."}` gauge plus an + ERROR-level event. Alerting decides who is woken; the probe decides only where traffic goes. + +**C4 — a degraded namespace stops consuming.** Readiness gates HTTP only; a not-ready pod still +holds its NATS subscriptions and still consumes events, so for an event-driven agent readiness +alone is cosmetic. With per-namespace transports (P6) this is closing that namespace's client +rather than selective unsubscription, and `ClientHealthChecker` already yields the per-agent +health entries that `readiness_policy = "critical"` needs. + +**C6 — agent code cannot observe its grouping.** No supported API exposes the group name, its +membership, or the number of namespaces in the process. This is what makes regrouping incapable +of breaking agent code. `deployment.group` is set by the framework on telemetry resources and is +not readable through a public API. + +**C7 — failure is never silent at namespace granularity.** Every path that stops a namespace +serving emits an ERROR-level event carrying that namespace's telemetry identity, independently of +any pod-level symptom. This is what makes the residual isolation cost of grouping manageable rather +than merely accepted: the three failure classes that take a whole group down — memory limit +breached, native crash, blocked event loop — raise no catchable exception, so careful error +handling lowers how often a group dies without changing which failures kill it. Attribution is the +only lever left, so it is normative. Work items: + +- Extend the C3 gauge and ERROR event to *every* removal-from-service path, not only the ones + readiness reads. +- Audit every framework `ensure_future` / `create_task` for a done-callback that logs exceptions + with the namespace attached (`nats_client.py:77` is the pattern; a bare `ensure_future` is a + violation). +- Drive `blueprint_namespace_up = 0` from per-namespace `subscriptions_ready`, so a namespace that + silently stops consuming is visible while the process stays healthy. +- Tag in-flight handler spans with the namespace and emit a periodic per-namespace in-flight gauge, + so a process-terminating failure can be attributed post-mortem. Without this an OOM kill is + indistinguishable across a group's agents. + +Grouping removes the pod restart that used to serve as the alert, so the alert must be emitted +deliberately. + +**Dev-mode detection.** Three mistakes are harmless alone and fatal in a group, and none can be +hidden by API design — so they must be caught mechanically rather than documented: + +| Mistake | Detection | +|---|---| +| Blocking the event loop | dev mode sets `loop.set_debug(True)` with a slow-callback threshold; production keeps a higher-threshold watchdog naming the executing namespace (C7) | +| Module-level side effects | CI: import each agent module, assert registry empty and root logger has no handlers | +| Non-idempotent handlers | explicit flag at scaffold time and in `asbs validate` (P4) | + +--- + +## File change summary + +| File | Phase | +|---|---| +| `utils/utils.py` | 0 | +| `app_builder.py` | 0 (`AgentRegistration`), 3 (`NamespaceBuilder` + executor provisioning), 6 | +| `__init__.py` | 0 | +| `component/registry.py` | 1 (namespace storage, named caches, executor registry) | +| `component/component.py` | 2 (`namespace` param, `executor` property) | +| `handler/handler_chain.py` | 4 (namespace scope + dispatch index, spec sec. 7.7) | +| `services/eventing/event_processing_service.py` | 4, 7 | +| `services/infrastructure/cache_service.py` | 2 (sync ops via `run_in_executor(self.executor, ...)`) | +| `io/api/eventing/nats.py` | P2 (stop swallowing classified exceptions), 5 | +| `io/api/eventing/cloud_event_processor_mixin.py` | 5 | +| `io/api/eventing/event_handling_base.py` | P2 (ack parity in `handle_event`), 5 | +| `clients/client_base.py` | P0 (`subscribe(topic_callbacks)` abstract) | +| `clients/io/nats_client.py` | P0 (managed subscribe, retry, reconnect, drain), P1-P3 (queue group, ack/nak/term, consumer tuning), 5 (durable naming) | +| `clients/io/dapr_client.py` | P0 (same lifecycle, mirrored) | +| `io/api/eventing/dapr.py` | P2 (ack parity: `NO_HANDLER_FOUND` → SUCCESS, `CriticalHandlerError` → DROP) | +| `handler/event_handler_base.py` | 7 | +| `handler/handler_chain.py` | P4 (CloudEvent-id dedup before dispatch) | +| `io/api/scheduling/scheduler.py` | P5 (`scheduler_mode`; timer suppressed in event mode, lease in in-process mode) | +| `group_config.py` (new), `entrypoint.py` (new) | 8 | +| `io/telemetry/telemetry.py` | 9 (C2 — per-namespace providers + empty-namespace path) | +| `io/api/actuators/actuator_api.py`, `io/api/actuators/health.py` | 9 (C3, C4, C7 — gauge and ERROR event on every removal-from-service path) | +| `clients/io/nats_client.py`, `clients/io/dapr_client.py` | 9 (C7 — done-callbacks on detached tasks; `subscriptions_ready` drives the per-namespace gauge) | +| `config/config.py` | 3 (C5 — `agent_scope` wiring via `with_namespace`), 8 (fragment merge) | +| `services/eventing/event_publishing_service.py` | P6 (per-namespace client) | + +**Scaffolding changes (`blueprint/agent_generator`)** — none of this exists yet: + +| Piece | Change | +|---|---| +| `asbs create agent-module ` | new; today `asbs setup` scaffolds a whole project, one agent per repo | +| `asbs dev ` | extend; today hardcodes `src/main.py` and `uvicorn src.main:app` (`cli/commands/dev.py`) | +| `asbs validate` | extend with the group gates below | +| `base_files/Dockerfile` | root image for the agent monorepo; `ENTRYPOINT python -m blueprint.agents.entrypoint` | +| `base_files/src/main.txt` | reduce to the single `registration = ...` declaration | +| `base_files/settings.txt` | unscoped per-agent fragment | + +`asbs dev` runs one agent as a group of one using its **real** namespace, so local routes are +`/api/order/orders/{id}` — identical to production — and local consumer identity is the production +queue group. A dev mode at `namespace=""` would give every developer URLs and integration tests +that differ from production. Consequently `namespace=""` is reserved for pre-migration agents; +every newly scaffolded agent has a real namespace in every environment. + +**Per-agent migration (opt-in only):** +- `main.py`: wrap builder in `if __name__ == "__main__": ... run_app(app, config)`, + add `else: registration = AgentRegistration()...` +- `Dockerfile`: `CMD uvicorn src.main:app` → `CMD python src/main.py` + +## Testing expectations + +New test coverage required alongside the implementation: + +- **Registry:** namespace isolation (component in `"order"` not visible from `"invoice"`), + two-level fallback resolution, named cache CRUD, executor registry add/get/fallback. +- **`AppBuilder` / `NamespaceBuilder`:** `with_namespace` wires components into the + correct namespace; `AgentRegistration._apply` delegates all stored entries correctly; + ContextVar is reset after `_apply` (no namespace leak between calls). +- **Handler chain:** namespace-scoped handler selection — handlers registered under + namespace A are not invoked when processing events for namespace B. +- **NATS:** per-namespace subscription closures capture and forward the correct namespace + to `process_event`. +- **Consumer identity (C1):** durable name and queue group are a function of the namespace + alone — assert they are byte-identical across two builds where the same agent sits in + different groups. This is the test that keeps regrouping cheap; without it C1 rots silently. +- **Ack lifecycle (P2):** a handled message is acked exactly once; a retryable failure naks; a + poison message terms. Regression test that no message is redelivered after a successful handle. +- **Ack contract (P2):** an event no handler matches is **acked**, not naked — the transport edge + behaves identically for `PROCESSED` and `NO_HANDLER_FOUND`, proving it does not read + `ProcessingResult`; a payload that fails CloudEvent parsing terms without dispatching; and the + Dapr response mapping is asserted against the same outcome table as the NATS dispositions. +- **Transport lifecycle (P0):** shutdown acknowledges in-flight work before unsubscribing; + a reconnect re-establishes JetStream durables without double-acking; `subscriptions_ready` is + false until every topic in the map is subscribed. +- **Idempotency (P4):** the same CloudEvent `id` delivered twice dispatches to the handler once. +- **Scheduler (P5):** with three simulated replicas a cron job fires once in both modes; + `scheduler_mode = "event"` starts no timer and the generated `CronJob` matches the declared schedule. +- **Telemetry (C2):** each namespace's spans carry `service.name = `, not the group name. +- **Silent failure (C7):** every path that stops a namespace serving emits an ERROR event and + `blueprint_namespace_up{agent} = 0` under that namespace's identity; a namespace whose + subscriptions vanish while the process stays healthy is reported; failing a task in each + background path produces a logged exception carrying the namespace, never a swallowed one. +- **Probes (C3):** a degraded namespace never fails liveness; readiness follows + `readiness_policy` under all three settings. +- **Group config (Phase 8):** every declared group resolves, imports and `build()`s without + external I/O; an unknown agent name and a duplicate agent across groups both fail loudly. +- **Config delivery (Phase 8):** file-only, env-only, and both-together all resolve to the same + agent list; env vars override the file key by key; a missing `BLUEPRINT_GROUP_CONFIG` path falls + back to the repo file; an agent named in the group but absent from `agents.toml` fails at + startup with the group and agent name in the message. +- **Backwards compat:** all existing unit tests pass unchanged with default `namespace=""`. That + proves the API still compiles, not that behaviour is preserved — so add both of: + - a **frozen compat suite** exercising today's usage patterns, including `with_cache(False)` and + `with_cache(True, False)` positionally, never updated to the new API. If it needs editing, a + break shipped. **It must include a handler that declares no topics and no event types, and + assert it is still evaluated for every event** (spec sec. 7.7, rule 1). That single test is + what keeps the dispatch index from silently disabling every pre-existing handler. + - a **filter-derivation test** (spec sec. 7.7, rule 2): the derived `filter_subjects` for a + namespace is never narrower than its declared topics unioned with `nats_subscriptions`, and an + agent declaring `orders.>` still receives `orders.other.created`. + - a **generated-project smoke test**: `asbs setup`, then build and start the result unchanged + against the new framework version. Catches the Dockerfile and `main.py` paths unit tests miss. + +## CI gates + +Run against `deployment-groups.yaml` on every change, so a bad grouping fails in CI and not at +deploy: + +- Every agent appears in **exactly one** group per environment. Two groups consuming the same + agent is duplicate processing, not a scaling strategy. +- No duplicate namespace names; no conflicting topic declarations within a group. +- Every declared group builds (import + `build()`, no external I/O). + +Subject-breadth gates (spec sec. 7.7), which constrain projects rather than the framework and so +**ship as warnings first, errors a release later** — the frozen compat suite covers runtime API +and would not catch a build that newly fails: + +- No handler may declare a bare `>` or a root-level single-token wildcard. A declared subject + carries at least domain and entity tokens. +- Every declared subject is reachable from the publish-side `topic_mapping`, catching typos and + orphaned subscriptions at build time — the same error class the unhandled-event counter catches + at runtime. +- Report fan-out per subject: how many namespaces select it. Above a threshold, require an + explicit waiver rather than silent acceptance. + +--- + +## Out of scope for this plan + +- Multiple simultaneous transport types (e.g. NATS + Dapr in one app). +- Cross-namespace agent calls (orchestrator → worker patterns). +- Dynamic namespace registration *after* startup. The group is resolved at process start from + `BLUEPRINT_GROUP`; namespaces are not added or removed while the process runs. +- Ordering guarantees. Competing consumers provide no per-topic ordering; order-dependent work + needs a partition key and one subject (and consumer) per partition. +- Lazy agent instantiation and scale-to-zero — both evaluated and rejected (spec sec. 1, + *Non-goals*). Do not re-propose without new measurements. + +--- + +## Planned, not yet written + +Decided in discussion but not yet reflected anywhere in the repo. Each is a deliverable, not an +open question. + +**Documentation** +- `docs/development-workflow.md` — the end-to-end walkthrough: scaffold an agent inside the + monorepo, develop it, run it with `asbs dev`, test it, then how it reaches a cluster (CI gates -> + one image -> group config -> generated manifests -> pod startup -> regrouping later). The + per-piece changes are captured in *Scaffolding changes* above; the narrative is not. +- `docs/guides/deployment.md` **contradicts this plan and ships today.** It recommends + `replicaCount: 2` plus an HPA as normal scaling, documents the multi-replica cache caveat, and + says nothing about schedulers (#73) or duplicate event consumption (P1). It also assumes one + Deployment per agent. Must be rewritten alongside Phase 8, or it actively misleads. +- A downstream repo generates `supervisord` config for multi-agent hosts. Under this decision that + generator becomes dead code; whoever owns it needs telling. + +**Issue hygiene** (nothing has been posted yet — analysis only) +- Comment the decision on #75 (deployment model: neither Model A nor Model B) and #35 (prefork vs + multi-tenant host: multi-tenant host chosen, prefork dropped). +- Open issues for P1 and P2 — the missing queue group and the never-sent acknowledgement. They are + live defects independent of this plan and should not be buried inside it. +- #32's success metric needs restating: "per-agent RAM" is meaningless once the interpreter is + shared. The unit becomes *baseline per group + marginal per agent*, and its "as-is 160-250 MB per + agent" row describes the model being retired. +- #43 (schedulers started twice within one process) should be fixed together with P5 — same code + path, and they compound: #43 unfixed plus two replicas gives four ticks. +- #28 (resilient broker startup) looks delivered by the `event-client-resilience` work; check + whether it can be closed. +- An earlier implementation of P0 exists on `feature/event_handler_retries`. Reconciling it with + what lands here is its author's call, and deliberately out of scope for this plan. + +**Engineering spikes** +- **Ack-retry-on-reconnect.** Belongs in P0's `_on_reconnected`. Capture the acknowledgement reply subject and re-send after a + reconnect, narrowing the duplicate window from "certain on any connection blip" to "only if the + pod also dies". Two unknowns make this a prototype rather than a design commitment: a redelivery + may already be in flight when the retry lands, and the behaviour of acking a stale delivery + attempt depends on how the server keys pending state on stream sequence. **Validate against a + real broker before relying on it.** +- **Consumer-count budget.** One hundred agents times a few subjects each is several hundred + JetStream consumers, each carrying ack-pending state. The connection ceiling was closed as a + non-issue; this is the analogous number for consumers and is currently an assumption. Measure + before committing to per-subject filters at 100 agents. +- **Marginal RSS per namespace.** Build N namespaces, report the resident-size delta per namespace, + reusing #36's benchmark harness. #32 measures ~6 MB per forked child with shared libraries; a + namespace has no separate process at all and should come in materially below that. This is the + number that retires the lazy-agent idea for good, and it is currently an estimate. +- ~~**Broker connection ceiling.**~~ Closed, not a spike. 100 agents at 2 replicas is ~200 + connections against a self-operated broker whose default `max_connections` is orders of magnitude + higher, and no authentication is wired today (`nats.connect()` takes URL and reconnect parameters + only, `nats_client.py:93`). The number only needs checking where the cap is issued externally per + account — a managed broker, or an operator-mode account JWT carrying a `conn` limit. Keep as a + deployment note, not an engineering question. +- **`CronJob` generation.** P5 requires the schedule to stay declared in agent code and the + `CronJob` to be generated from it. The generation path is unspecified. + +--- + +## Open questions + +Owned by the spec, sec. 13 -- they constrain the design, not the work breakdown, and duplicating +them here would let the two copies drift. The two that most affect this plan: whether the target is +20 or 100 agents, and whether the 4 GB host budget is real. Both decide how many groups the +grouping dial actually has. diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md new file mode 100644 index 00000000..ef26ef3c --- /dev/null +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -0,0 +1,741 @@ +# Spec -- Multi-Agent Grouping + +| | | +|---|---| +| **Implementation plan** | `docs/plans/2026-08-28-multi-agent-grouping.md` | +| **Resolves** | #75 (deployment model decision), #73 (duplicate cron ticks) | +| **Unblocks** | #32 (100 agents in 4 GB), #35 (shared interpreter), #20 (worker scaling) | +| **Related** | #33 (lazy heavy imports), #34 / #74 (dependency slimming), #36 (concurrency bounds + benchmark), #43 (scheduler double-start), #6 (config service) | + +Requirement keywords (**MUST**, **MUST NOT**, **SHOULD**, **MAY**) are used in the RFC 2119 sense. + +--- + +## 1. Scope + +Allow one Python process to host several independent agents, and make the grouping of agents +into processes a deployment-time parameter rather than a code-time one. + +### In scope + +- A namespace dimension in the component registry, with per-namespace isolation of executors, + AI clients, event transports and configuration. +- Group composition resolved at process start from a file and/or environment variables. +- Event delivery that is correct under horizontal pod scaling. +- Telemetry and health identities that are invariant under regrouping. +- A development workflow in which an agent author never encounters namespaces or groups. + +### Non-goals + +- Multiple simultaneous transport types in one process (NATS *and* Dapr). +- Cross-namespace agent calls. +- Adding or removing namespaces after startup. +- Ordering guarantees across replicas. +- Lazy agent instantiation and scale-to-zero (evaluated and rejected; do not re-propose + without new measurements). +- Prefork / copy-on-write process sharing. #35 lists "prefork" and "multi-tenant host" as + alternatives; this spec implements **multi-tenant host** and does not pursue prefork. + +--- + +## 2. Terminology + +| Term | Meaning | +|---|---| +| **Agent** | A unit of business capability: handlers, services, prompts, optionally a REST API and scheduler. Authored as one directory. | +| **Namespace** | The registry partition an agent's components live in. Equal to the agent name. `""` is the root namespace and means "pre-migration single-agent app". | +| **Group** | The set of agents loaded into one process, and therefore into one pod. | +| **Registration** | An `AgentRegistration` -- component classes collected without instantiation. | +| **Root** | Namespace `""`, holding process-wide shared components. | + +--- + +## 3. Invariants + +These are normative. C1-C6 exist because violating them makes regrouping observable outside the +process, which would defeat the purpose of grouping. C7 exists for a different reason: it is what +keeps the isolation cost that grouping *does* incur attributable, and therefore adjustable. + +### C1 -- Consumer identity derives from the agent + +Queue group names and JetStream durable names **MUST** be a pure function of the namespace. +They **MUST NOT** incorporate the group name, container name, pod name, replica index, or any +other deployment identifier. + +- Queue group: `namespace`, or `nats_queue_group` (default `app_name`) when the namespace is `""`. + It **MUST NOT** be the empty string. +- JetStream durable: `f"{namespace}-{topic}-durable"`, or the configured `nats_durable_name` + when the namespace is `""`. +- The NATS **connection name** (sec. 6) is deployment-specific and **MUST NOT** be used to derive + either of the above. + +### C2 -- Telemetry identity derives from the agent + +Each namespace **MUST** have its own `TracerProvider` and `MeterProvider` with +`Resource({"service.name": , "deployment.group": , "service.instance.id": })`. +All providers **SHOULD** share one exporter and one `BatchSpanProcessor`. + +When the namespace is `""`, the provider **MUST** use `otel_service_name` from config, reproducing +current behaviour exactly (`io/telemetry/telemetry.py:39-41`). + +### C3 -- Liveness is never namespace-dependent + +The liveness probe **MUST** reflect only process and event-loop health. A degraded namespace +**MUST NOT** cause a liveness failure, because that restarts every agent in the group. + +Already satisfied: `io/api/actuators/actuator_api.py:126-143` returns `UP` unconditionally. This +invariant exists to stop the behaviour from being changed, not to change it. + +Readiness **MUST** follow `readiness_policy`: + +| Value | Behaviour | +|---|---| +| `"all"` | **Default.** Any degraded namespace makes the pod not ready. Reproduces current behaviour. | +| `"critical"` | Only namespaces marked `critical` gate readiness. | +| `"any"` | Ready while at least one namespace is up. | + +A degraded namespace **MUST** be reported as `blueprint_namespace_up{agent="..."} = 0` and an +ERROR-level event regardless of policy. Alerting is driven by that signal, not by the probe. C7 +generalises this to every path that stops a namespace serving, not only the ones readiness reads. + +### C4 -- A degraded namespace stops consuming + +Readiness gates HTTP only; a not-ready pod still holds subscriptions. A namespace that becomes +degraded **MUST** stop consuming its events so they redeliver to a healthy replica. With +per-namespace transports (sec. 6) this is closing that namespace's client. + +### C5 -- Configuration is namespace-scoped + +Each namespace **MUST** receive a `Config` with `agent_scope` set to its namespace name, so +`.` resolves before the root ``. Infrastructure keys stay at root; prompts, +model selection and usage limits become per-agent. + +### C6 -- Agent code cannot observe its grouping + +No API reachable from agent code **MUST** expose the group name, the group's membership, or the +number of namespaces in the process. This is what makes regrouping incapable of breaking agent +code. `deployment.group` on telemetry resources is set by the framework and is not readable +through a supported API. + +### C7 -- Failure is never silent at namespace granularity + +Every path that removes a namespace from service **MUST** emit an ERROR-level event carrying that +namespace's telemetry identity (C2), independently of any pod-level symptom. A failure observable +only as a pod restart, a latency regression, or a metric that stopped arriving does not satisfy +this invariant. + +C7 exists for a different reason than C1-C6. Those keep regrouping invisible from outside the +process; C7 is what makes the residual isolation cost of grouping *manageable*. Three failure +classes take a whole group down, and none of them raises a catchable exception: + +| Class | Why handler-level `try` / `except` cannot see it | +|---|---| +| Memory limit breached | The cgroup limit is per-pod; the kernel kills the process | +| Native extension crash | The process dies without unwinding | +| Event loop blocked | Not an error at all -- a latency and liveness symptom | + +Careful exception handling lowers how often a group dies; it cannot change which failures kill it. +What remains available is attribution, so attribution is normative: + +- **In-process degradation.** `blueprint_namespace_up{agent="..."} = 0` plus an ERROR event for + every path that stops a namespace serving -- not only the paths that gate readiness (C3). +- **Detached tasks.** Every task the framework creates via `ensure_future` / `create_task` + **MUST** carry a done-callback that logs exceptions with the namespace attached. The existing + `self._retry_task.add_done_callback(self._on_retry_done)` (`clients/io/nats_client.py:77`) is the + pattern; a bare `ensure_future` is a C7 violation. +- **Silent consumer loss.** A namespace whose subscriptions are gone while the process stays + healthy **MUST** drive `blueprint_namespace_up = 0`. `subscriptions_ready` + (`clients/io/nats_client.py:60`) already carries this per client; per-namespace clients (sec. 6) + make it per-agent. +- **Process-terminating failures.** These cannot report themselves, so the framework **MUST** emit + enough per-namespace context beforehand to attribute them post-mortem: the namespace on every + in-flight handler span, and a periodic per-namespace in-flight gauge. Without it an OOM kill is + indistinguishable across a group's agents, and the grouping dial cannot be turned in response. +- **Blocked loop.** The dev-mode slow-callback threshold (sec. 11.1) **SHOULD** also run in + production at a higher threshold, logging the namespace of the executing handler. This is the one + group-wide failure class that is detectable from inside the process. + +Grouping removes the pod restart that used to serve as the alert, so the alert **MUST** be emitted +deliberately rather than inferred from a restart. + +--- + +## 4. Public API + +### 4.1 New + +```python +class AgentRegistration: + """Fluent collector. Stores component classes; instantiates nothing.""" + def with_handler(self, handler, *, name=None, **kwargs) -> "AgentRegistration" + def with_service(self, service, *, name=None, **kwargs) -> "AgentRegistration" + def with_agent(self, agent, *, name=None, **kwargs) -> "AgentRegistration" + def with_scheduler(self, scheduler, *, name=None, **kwargs) -> "AgentRegistration" + def with_rest_api(self, api, *, name=None, **kwargs) -> "AgentRegistration" + # No with_cache -- caches are registered on the AppBuilder. + + +class GroupConfig: + """Resolved group composition. A value object; performs no I/O once constructed.""" + name: str + agents: tuple[AgentSpec, ...] # name, critical flag, module path + cache_names: tuple[str, ...] + + @classmethod + def resolve(cls, config: Config) -> "GroupConfig": + """Read file + env, validate against the agent map, or raise GroupConfigError.""" + + +def run_app(app: FastAPI, config: Config) -> None: ... +``` + +`GroupConfig.resolve` is the only member that touches the environment or the filesystem. +`with_group` **MUST NOT** perform I/O, so tests can construct a `GroupConfig` literally. + +### 4.2 Changed + +```python +class AppBuilder: + def with_namespace(self, name: str, *, registration: AgentRegistration | None = None, + config: Config | None = None) -> "AppBuilder | NamespaceBuilder" + def with_group(self, group: GroupConfig) -> "AppBuilder" + + @classmethod + def from_group(cls, config: Config) -> "AppBuilder" # resolve + with_group + + # namespace: str = "" added to with_handler / with_service / with_agent / + # with_scheduler / with_rest_api -- keyword-only. + + def with_cache(self, enabled: bool = True, enable_locking: bool = True, + *, name: str = "default") -> "AppBuilder" +``` + +**`with_cache` is the one place where the obvious design breaks compatibility.** The current +signature is `with_cache(enabled: bool = True, enable_locking: bool = True)` +(`app_builder.py:117`). Making `name` the first parameter would turn an existing +`with_cache(False)` -- meaning *disable caching* -- into a cache named `False`, silently enabling +the cache with no `TypeError`. `name` therefore **MUST** be keyword-only and **MUST** follow the +two existing positional parameters. + +### 4.3 Component + +`Component.__init__` **MUST NOT** gain a namespace parameter. The namespace is read from a +module-level `ContextVar` set by `AgentRegistration._apply`, so no user subclass constructor +signature changes and no positional argument shifts. + +`Component.executor` returns the namespace's `ThreadPoolExecutor`, falling back to root. The +executor **MUST** be created lazily on first access; an app that never performs blocking work +**MUST NOT** spawn one. (Eager creation in `build()` would add ~`cpu_count + 4` idle threads to +every existing single-agent app, and works against #36's thread-count budget.) + +--- + +## 5. Configuration + +### 5.1 Group resolution + +Read **before** `Config` is constructed -- group composition determines which agents get a +`Config` at all -- so these are plain environment reads plus one YAML parse, deliberately not +routed through Dynaconf. Hence the `BLUEPRINT_` prefix rather than Dynaconf's `DYNACONF_`. + +| Variable | Default | Meaning | +|---|---|---| +| `BLUEPRINT_GROUP_CONFIG` | `./deployment-groups.yaml` | Path to the group file. Absent file is not an error if env vars supply the group. | +| `BLUEPRINT_GROUP` | -- | Group to load. **MAY** be omitted when the file declares exactly one group. | +| `BLUEPRINT_AGENTS` | -- | Comma-separated agent names. Supplies the group without a file. | +| `BLUEPRINT_CRITICAL_AGENTS` | -- | Comma-separated subset marked `critical`. | + +**Precedence: environment variables override the file, key by key.** The resolved value of every +key, and its source, **MUST** be logged at startup. + +Both mechanisms **MUST** be supported; neither is preferred. The file suits ConfigMap mounts and +local development, env vars suit `docker run` and CI, and env values live in the pod template so +changing them triggers a rolling update on their own. + +### 5.2 Runtime keys + +| Key | Default | Meaning | +|---|---|---| +| `readiness_policy` | `"all"` | See C3. | +| `executor_workers` | `os.cpu_count() + 4` | Per-namespace thread pool size. Bounded per #36. | +| `nats_queue_group` | `app_name` | Queue group for the root namespace only. | +| `nats_ack_wait` | -- | **MUST** exceed p99 handler duration. See sec. 7.3. | +| `nats_max_ack_pending` | -- | Per-consumer, shared across replicas. | +| `idempotency_enabled` | `false` | Opt-in dedup. See sec. 7.4. | +| `idempotency_ttl` | -- | Dedup window. | +| `scheduler_mode` | `"event"` | `"event"` or `"in_process"`. See sec. 7.5. | + +### 5.3 Settings authoring + +An agent author writes plain top-level keys in their own directory's `settings.toml` +(`model_name = "..."`), not `[default.]`. The build **MUST** merge each agent's fragment +under its own scope so C5 resolves them, without the author knowing the scope exists. + +Collisions between an agent fragment and a root key **MUST** be reported at build time. + +--- + +## 6. Transport topology + +One `NATSClient` **per namespace**, not one per process. + +**This section applies to the direct-connection transport only.** Under Dapr the application holds +no broker connection at all: `DaprClient` is an `httpx` client against the sidecar +(`clients/io/dapr_client.py:89`), subscriptions are declarative (`GET /dapr/subscribe`, then the +sidecar posts to `POST /events/{topic}`), and the sidecar owns and multiplexes the one broker +connection per pod. Broker connections therefore track pods rather than agents on that path, and +reasons 1 and 2 below move into the sidecar and out of this spec's reach. A per-namespace +`DaprClient` **MAY** still be created for health attribution and for C4, but it **MUST NOT** be +described as confining ack loss or slow-consumer disconnects, because it does not. + +Per-namespace clients deliberately trade back part of the shared-connection advantage credited +to the namespace model. This is justified by three things, in order of weight: + +1. **Ack loss is confined.** A handler that completes 60 s of inference and then cannot ack + because the connection is down has already committed its side effects; the broker redelivers + after `ack_wait`. Duplicate processing is therefore *certain*, not merely possible. On a shared + connection one blip does this to every in-flight message across every agent in the group. +2. **Slow-consumer disconnects are confined.** The broker kicks a connection whose pending buffer + overflows. Shared, one flooding agent takes down the group's transport and triggers a + re-subscribe storm across all namespaces (`clients/io/nats_client.py:265-280`). +3. **Attribution.** `nats.connect()` is currently called with no `name=` + (`clients/io/nats_client.py:93`), so every connection this framework opens is anonymous in + `/connz`. Per-namespace named connections make a pod's contents legible in connection-oriented + tooling. + +**Durability is not among the three, and the topology MUST NOT be justified by it.** JetStream +pending state lives on the server, keyed by consumer and stream sequence; an ack is a message +published to the per-delivery `$JS.ACK...` reply subject, not an entry in a framework-side +registry. Nothing aggregates in-flight events on behalf of the namespaces sharing a process, so a +shared connection has no such state to lose when the process dies -- `ack_wait` expires and the +broker redelivers. What the topology decides is not whether work survives a failure, but **how many +namespaces repeat work** when a connection drops. The durability question is settled by sec. 7.1 +and 7.2 (JetStream on, acks actually sent), not here. + +Cost accepted without a config knob: connection count scales with agent count. A connection is a +socket plus buffers -- tens to low hundreds of KB -- against ~65 MB for the smallest possible +separate process (#32). Protecting a few MB with a knob nobody should use is not worth the +maintenance surface. 100 agents at 2 replicas is ~200 connections, which is not a practical +constraint against a self-operated broker's default `max_connections`. The number **SHOULD** be +checked before a large rollout only where the cap is issued externally per account -- a managed +broker, or an operator-mode account whose JWT carries a `conn` limit set by someone else. No such +authentication is currently wired: `nats.connect()` is called with URL and reconnect parameters +only (`clients/io/nats_client.py:93`). + +Connection name **MUST** be `f"{namespace}.{group}.{pod}"`, and **MUST NOT** feed C1 naming. + +`EventPublishingService` **MUST** publish on its own namespace's client; otherwise outbound +traffic is unattributable and reason 3 is defeated. + +Per-namespace clients also make C4 a client close rather than selective unsubscription, and give +`ClientHealthChecker` per-agent health entries that feed `readiness_policy = "critical"` directly. + +--- + +## 7. Event delivery + +### 7.1 Competing consumers + +With N replicas of a group, exactly one replica **MUST** process any given event. Core NATS +subscriptions **MUST** pass a queue group; JetStream consumers **MUST** share a durable per C1. + +The current code does neither: `nats_client.py:250` subscribes with no `queue=`, and JetStream is +off by default (`nats_client.py:102`). Setting `replicas: 2` today therefore doubles every side +effect and every inference bill. This is a defect independent of grouping (see #20, #35). + +### 7.2 Acknowledgement + +`nats_client.py:242-247` subscribes with `manual_ack=True` and **no `msg.ack()` call exists +anywhere in the codebase**, so every JetStream message redelivers until `max_deliver`. Already a +defect at one replica. + +**Decision: ack after the handler completes.** The alternative (ack first) converts a connection +blip from duplicate work into *lost* work, which is worse for expensive, side-effecting inference. +Consequently at-least-once is permanent, and sec. 7.4 applies. + +**The contract is that a normal return acknowledges and a raised exception does not.** +`ProcessingStatus` carries no failure value -- it is `PROCESSED` or `NO_HANDLER_FOUND` -- so every +failure already reaches the transport as an exception. The transport edge **MUST NOT** inspect +`ProcessingResult` to decide acknowledgement: `ProcessingResult` is a reporting object and **MUST** +remain independent of delivery control. + +| Outcome at the transport edge | NATS | Dapr response | +|---|---|---| +| Handler chain returned, any status | `ack()` | `SUCCESS` | +| `RetryableHandlerError` | `nak()` | `RETRY` | +| `InvalidEventError` | `term()` | `DROP` | +| `CriticalHandlerError` | `term()` | `DROP` | +| Any other exception raised during dispatch | `nak()`, bounded by `max_deliver` | `RETRY` | +| Payload fails JSON or CloudEvent parsing, before dispatch | `term()` | `DROP` | + +**`NO_HANDLER_FOUND` MUST acknowledge.** An event that matches no handler's conditions has nothing +to do, and redelivery cannot make a handler appear: a nak is a pointless loop until `max_deliver`, +and under a queue group a loop that visits every replica in turn. `dapr.py:75` returns `RETRY` for +this case today and **MUST** change. + +Acknowledging it **MUST NOT** make it invisible. A subscribed topic with no matching handler is +usually a declaration error, and the acknowledgement is what would otherwise hide it forever. The +framework **MUST** count unhandled events per namespace and topic, and **MUST** log at WARNING the +first time a given (namespace, topic) pair produces one. + +**Both transports MUST map the same outcome to the same disposition.** Dapr's response dict *is* +its acknowledgement, so the table above is normative for `dapr.py` and +`event_handling_base.handle_event` exactly as it is for `nats_client.py`. They disagree in two +places today: `NO_HANDLER_FOUND` as above, and `CriticalHandlerError`, which `dapr.py:102` retries +-- a critical error is not made less critical by being delivered again. + +`max_deliver` and a dead-letter destination **MUST** be configured, because nak on an unexpected +exception otherwise redelivers indefinitely. + +Implementations **SHOULD** capture the ack reply subject and retry the ack after a reconnect, +which narrows the duplicate window from "certain on any blip" to "only if the pod also dies". +Two caveats make this a prototype rather than a design commitment: a redelivery may already be in +flight when the retry lands, and the behaviour of acking a stale delivery attempt depends on how +the server keys pending state on stream sequence. **MUST** be validated against a real broker. + +### 7.3 Long handlers + +`ack_wait` **MUST** exceed p99 handler duration, or a slow handler is redelivered to another +replica while the first is still working. `in_progress()` heartbeats address slow handlers; they +do **not** address connection loss, since they travel over the same connection. + +### 7.4 Idempotency + +At-least-once is unavoidable: rebalance, eviction, node drain and every rolling deploy produce +redelivery, and ack loss guarantees it. + +This is a cost of *replication*, not of grouping. A single-agent process replicated twice faces the +same competing consumers, the same redelivery and the same lost ordering, so the requirement lands +identically on a pre-migration app that scales past one replica. It is specified here because +grouping is where the requirement becomes visible, not because grouping creates it. + +Whether deduplication is *correct* depends on the product built on the blueprint -- some +operations are naturally idempotent, others need business-level reconciliation the framework +cannot see. The framework therefore **MUST NOT** silently enforce dedup, and **MUST**: + +- provide an opt-in dedup mechanism keyed on the CloudEvent `id`, backed by the namespace's cache + with a TTL, applied in the handler chain before dispatch (`idempotency_enabled`); +- **flag the requirement explicitly to the agent author** -- a comment in the scaffolded handler, + a line in the generated README, and an `asbs validate` notice when a handler is registered with + `idempotency_enabled = false`. The author must make a decision, not inherit a default silently. + +### 7.5 Schedulers + +`SchedulerBase.on_startup` creates an `AsyncIOScheduler` per process with no leader election +(#73), so every cron tick fires once per replica. Grouping widens the exposure: one pod hosting 20 +agents runs 20 schedulers, and two replicas duplicate all 20 agents' crons simultaneously. + +Two modes, selected by `scheduler_mode`: + +| Mode | Behaviour | +|---|---| +| `"event"` | **Default.** No in-process timer. An external scheduler (Kubernetes `CronJob`) publishes an event; the agent handles it through its normal event path. | +| `"in_process"` | `AsyncIOScheduler` gated by a NATS KV or cache-backed leader lease. For un-orchestrated Docker and local development. | + +In `"event"` mode the framework **MUST NOT** start a timer, and the tick **MUST** be delivered as +an ordinary namespaced event, so the queue group already guarantees single execution across +replicas without electing anything. The publishing container **SHOULD** be a minimal NATS client +image, not the agent image -- a `CronJob` running the agent re-pays the ~154 MB baseline (#32) for +work that fires once a night. + +The schedule **MUST** remain declared in agent code, and the `CronJob` **MUST** be generated from +that declaration -- the same generation path as manifests from `deployment-groups.yaml`. Hand-authored +schedules let code expect a tick nobody scheduled. + +Neither mode is exactly-once: `CronJob` is at-least-once (controller restart, missed +`startingDeadlineSeconds`), and a lease can briefly have two holders if it expires mid-tick. +Sec. 7.4 therefore applies in both modes. `concurrencyPolicy: Forbid` **SHOULD** be set, and +`CronJob` `timeZone` **MUST** be reconciled with apscheduler's timezone handling so the two modes +do not diverge. + +Note #43 -- schedulers being started twice *within* one process by two `build()` passes -- is a +distinct defect. Both touch scheduler startup and **SHOULD** be fixed together. + +### 7.6 Topic subscription scope + +Two agents subscribing to the same topic is legitimate and expected: both want the event. Topic +deduplication **MUST** be scoped within a namespace. Each `(namespace, topic)` pair gets its own +subscription and its own consumer. A cross-namespace "first declaration wins" rule would silently +disable one agent's subscription, and the agent author could not observe it locally. + +### 7.7 Selection and fan-out + +Selection happens at two levels, and only one of them is enforced by the broker: + +| Level | Enforced by | Mechanism | +|---|---|---| +| Which subjects reach the process | broker | subscription subject, JetStream `filter_subjects` | +| Which event a handler wants | in-process | `can_handle()` | + +NATS filters on **subject only** -- there is no content or header predicate -- so any selection +finer than the subject is either encoded in the subject or paid for inside the process. Dapr can +evaluate CEL rules over the CloudEvent, but in the sidecar, after the broker has already +delivered. + +This matters at scale for a reason that is not CPU. With one consumer per `(namespace, topic)` +pair (sec. 7.6), a broad subject makes the **broker** copy every message once per namespace, each +copy carrying its own delivery, ack-pending state and redelivery timer. One hundred agents +subscribed to `events.>` is a hundredfold fan-out before any handler code runs. + +**Selection that the framework is expected to push down to the broker MUST be declared +statically.** `can_handle()` is imperative code and can never be pushed anywhere: it **MUST** +remain available as the final in-process selector, and **MUST NOT** be the only selector +available. Handlers **SHOULD** declare the subjects or event types they accept, and the framework +**SHOULD** resolve declared event types to subjects through the same `topic_mapping` it uses when +publishing, so publisher and consumer cannot drift. + +Two rules keep this non-breaking, and both are load-bearing, because **no handler in the framework +or in any scaffolded project declares anything today**: `get_subscribed_topics()` is overridden +nowhere, the generated handler template selects purely inside `can_handle_event`, and +`nats_subscriptions` appears in no generated settings file. Any design that treats declarations as +authoritative therefore describes an empty set. + +1. **A handler that declares nothing MUST continue to be evaluated for every event its namespace + receives.** An in-process dispatch index **MAY** be keyed on declared event types as an + optimisation, but undeclared handlers **MUST** fall into a wildcard bucket that is always + evaluated. Without this every existing handler silently stops firing -- and because + `NO_HANDLER_FOUND` acknowledges (sec. 7.2), the events would be consumed and discarded rather + than accumulating visibly. This is the most destructive failure mode available in this design. +2. **A broker-side filter MUST NOT be narrower than the union of the explicitly declared subjects + and the configured `nats_subscriptions` list.** Filters **MUST** derive from explicit + declarations only; the framework **MUST NOT** infer a narrower filter by reading handler code or + handler type checks. An agent subscribed to `orders.>` whose handler selects part of that space + on payload content has to keep receiving all of it. + +**Consumer reconfiguration is a migration, not a config change.** A durable's name and its filter +set are broker-side state. Depending on server version, changing the filter set is applied in place +or forces delete-and-recreate, and a recreated consumer resumes according to its delivery policy -- +replaying from the start of the stream, or skipping whatever arrived in between. Any release that +changes a durable's name or filter set **MUST** state the migration explicitly, including whether +replay or a gap is expected. This binds the durable renaming that C1 requires +(`{namespace}-{topic}-durable`, replacing today's `nats_durable_name` default) exactly as it binds +filter derivation: on first deploy, every pre-existing consumer becomes a new consumer. + +**Fan-out MUST be observable.** The framework **MUST** expose, per subject, how many namespaces +select it. With the unhandled-event counter of sec. 7.2 this covers both directions of the same +error: an event nobody wanted, and an event offered to far too many. + +Build-time gates on subject breadth belong to the implementation plan rather than here, because +they constrain projects rather than the framework. They **SHOULD** ship as warnings before they +become errors: the frozen compat suite and the generated-project smoke test cover runtime API and +would not catch a newly failing build. + +--- + +## 8. Caches + +Caches are looked up by name with no namespace dimension, which makes them a cross-agent +collision surface: two independently developed agents both calling `get_cache("sessions")` share +one cache the moment they are grouped, invisibly and only in production. + +Cache names **MUST** therefore be namespace-scoped by default, with an explicit opt-in for +genuinely shared caches. Agents share no cache by design, so isolation is the correct +default. + +`registry.cache_service` (getter and setter) **MUST** be retained as an alias for the `"default"` +cache in the root namespace. + +--- + +## 9. Startup + +1. `GroupConfig.resolve(config)` -- file, then env overrides; log provenance. +2. Validate every agent name against the in-image agent map. Fail with the group and the missing + agent named. +3. Import each agent module lazily; read its module-level `registration`. +4. `AppBuilder(config).with_group(group)` -- one `with_namespace` per agent. +5. `build()`, then `run_app(app, config)`. + +Resolution **MUST** complete before the first `Component.__init__`, because namespace injection +happens through a `ContextVar` read during construction. No incremental resolution. + +### 9.1 Failure policy + +There is no partial build: one process, one `build()`. The `critical` flag is therefore evaluated +**before** a namespace is wired, not after an exception. + +| Failure | `critical: true` | `critical: false` | +|---|---|---| +| Agent missing from the agent map | exit non-zero | log ERROR, skip | +| Module import raises | exit non-zero | log ERROR, skip | +| `on_startup` raises | exit non-zero | mark namespace down, pause consumers (C4), continue | + +Exit **MUST** happen before the port is bound, so Kubernetes crash-loops with a readable message +rather than reporting a healthy pod that is silently short-staffed. + +The default for an unflagged agent is `critical: true`: a partially loaded group whose missing +agent's queue has no consumer is a worse failure than no pod at all. + +### 9.2 Startup log + +**MUST** include: group name, agent list, the source of each resolved config value, and per +namespace the queue group and durable names. The last item makes C1 verifiable by diffing startup +logs across a regrouping. + +--- + +## 10. Backwards compatibility + +An existing single-agent project **MUST** continue to work with no source change, no Dockerfile +change, and `uvicorn src.main:app` as its entrypoint. Specifically: + +| Concern | Guarantee | +|---|---| +| `AppBuilder` fluent API | Unchanged; `namespace` added keyword-only. | +| `with_cache(False)` / `with_cache(True, False)` | Unchanged (sec. 4.2). | +| `Component` subclasses | No constructor change (sec. 4.3). | +| `registry.cache_service` | Retained as alias. | +| Liveness / readiness | `readiness_policy = "all"` reproduces today. | +| Telemetry | Namespace `""` keeps `otel_service_name`. | +| Threads | Executor lazy; no threads unless used. | +| `Phase 7 get_runtime_name` | Purely additive -- `process_event` resolves no agent today; `runtime_name` is only logged (`event_processing_service.py:74`). | + +`Registry._components` changes from `dict[str, Any]` to two levels. It is underscore-private, but +anything subclassing `Registry` or introspecting it breaks; this **MUST** be release-noted. + +### 10.1 The exception + +The transport fixes in sec. 7.1 and 7.2 change behaviour for already-deployed systems, without +changing any signature: + +- Multi-replica deployments stop double-processing. +- JetStream deployments stop redelivering every message forever. + +Both are bug fixes and neither is opt-out-able, since leaving them means the framework cannot be +scaled. They **MUST** ship as their own release with explicit notes, not folded quietly into the +grouping work. + +### 10.2 Enforcement + +- A **frozen compatibility suite** exercising today's usage patterns, including + `with_cache(False)` and `with_cache(True, False)` positionally. It is never updated to the new + API; if it needs editing, a break shipped. +- A **generated-project smoke test**: `asbs setup`, then build and start the result unchanged + against the new framework version. Catches the Dockerfile and `main.py` paths unit tests miss. + +--- + +## 11. Developer-facing surface + +An agent author's `main.py` is, in full: + +```python +registration = ( + AgentRegistration() + .with_service(OrderService) + .with_handler(OrderValidationHandler) + .with_rest_api(OrderApi) +) +``` + +No `AppBuilder`, no `Config`, no `run_app`, no `if __name__`, no namespace, no group. The +dual-branch `main.py` in the current plan -- which duplicates the component list under +`if __name__ == "__main__"` and `else:` -- **MUST** be collapsed to this single declaration; two +branches to keep in sync is itself a leak of the grouping model. + +`asbs dev agents/` runs one agent as a group of one, using its **real** namespace. Local +routes are therefore `/api/order/orders/{id}`, identical to production, and local consumer +identity is the production queue group. A dev mode that ran at `namespace=""` would give every +developer local URLs and integration tests that differ from production. + +Consequently `namespace=""` is reserved for pre-migration agents. Every newly scaffolded agent +**MUST** have a real namespace in every environment. + +### 11.1 What cannot be hidden + +Three mistakes are harmless in isolation and fatal in a group. They **MUST** be caught +mechanically, because a rule that cannot be violated locally will not be followed: + +| Mistake | Detection | +|---|---| +| Blocking the event loop | dev mode sets `loop.set_debug(True)` with a slow-callback threshold; production **SHOULD** keep a higher-threshold watchdog that names the executing namespace (C7) | +| Module-level side effects (clients built at import, `basicConfig()`) | CI: import each agent module, assert the registry is empty and the root logger has no handlers | +| Non-idempotent handlers | explicit flag at scaffold time and in `asbs validate` (sec. 7.4) | + +Two things an author still needs to know: their agent's name, and that handlers must not block. + +--- + +## 12. Acceptance criteria + +- [ ] Two agents in one process; an event on a topic both subscribe to reaches both, once each. +- [ ] Two replicas of a two-agent group: each event processed exactly once per agent. +- [ ] Durable and queue names byte-identical across two builds where the same agent sits in + different groups (C1). +- [ ] Spans from namespace `invoice` carry `service.name = "invoice"`; a `namespace=""` app keeps + `otel_service_name` (C2). +- [ ] A degraded namespace: liveness `UP`, readiness per policy, `blueprint_namespace_up = 0`, + that namespace's consumers stopped (C3, C4). +- [ ] `.model_name` overrides root `model_name` for that namespace only (C5). +- [ ] No supported API exposes group membership to agent code (C6). +- [ ] Every path that stops a namespace serving emits an ERROR event and + `blueprint_namespace_up{agent} = 0` carrying that namespace's identity; a namespace whose + subscriptions vanish while the process stays healthy is reported within one scrape interval + (C7). +- [ ] No framework-created task is detached without a done-callback that logs exceptions with the + namespace attached; asserted by a test that fails a task in each background path (C7). +- [ ] File-only, env-only and combined resolution produce identical groups; env overrides the file + key by key. +- [ ] The CI gate fails when an environment's group declaration omits an agent present in the + in-image agent map (sec. 13). +- [ ] Cron fires once across three replicas in both `scheduler_mode` values (#73). +- [ ] `scheduler_mode = "event"` starts no timer, and the generated `CronJob` matches the schedule + declared in agent code. +- [ ] An event that matches no handler is acknowledged, not redelivered: the transport edge + behaves identically for `PROCESSED` and `NO_HANDLER_FOUND` (sec. 7.2). +- [ ] The same outcome yields the same disposition on both transports -- `CriticalHandlerError` + drops on Dapr and terms on NATS, and a payload that fails to parse never naks (sec. 7.2). +- [ ] A handler declaring no topics and no event types is still evaluated for every event its + namespace receives (sec. 7.7). +- [ ] A namespace's derived `filter_subjects` is never narrower than its declared topics unioned + with `nats_subscriptions` (sec. 7.7). +- [ ] Unhandled events per (namespace, topic) and namespaces-per-subject fan-out are both exposed + (sec. 7.2, sec. 7.7). +- [ ] Frozen compat suite and generated-project smoke test both green (sec. 10.2). +- [ ] Idempotency off by default, with the requirement surfaced at scaffold time and in + `asbs validate`. +- [ ] Marginal RSS per additional idle namespace measured and published, reusing #36's benchmark + harness. #32 measures ~6 MB per forked child with shared libraries; a namespace should be + materially below that, and this number is what retires the lazy-agent idea for good. + +--- + +## 13. Open questions + +- **Is `deployment-groups.yaml` authored per environment, or one file with per-environment + overrides?** This is a trade-off rather than a gap: per-environment files are + readable without resolving inheritance and fit the difference actually being expressed + ("collapse every group into one" for dev is a different document, not a patch), while a single + overridden source avoids repeating the agent list and makes the *difference* the reviewable + artifact. Whichever is chosen, the duplication risk is *forgetting* an agent rather than the + duplication itself, and that is mechanically checkable -- the in-image agent map already + enumerates every agent, so the CI gate **SHOULD** require each environment's declaration to + account for all of them. Open: which shape, and how many environments actually differ. +- Is the dedup cache per-namespace or shared, and what TTL is defensible against the redelivery + window? +- **#32's metric needs restating.** "Per-agent RAM" stops being meaningful once the interpreter is + shared; the correct unit is *baseline per group + marginal per agent*. Its "as-is 160-250 MB per + agent" row describes the model being retired, and its acceptance criteria should be re-expressed + in the new unit before they are used to judge this work. +- **Is the 4 GB host budget real?** #32 says "100 agents on a 4 GB host"; this spec assumes + Kubernetes with one Deployment per group. If 4 GB is a hard constraint, group count is capped at + roughly 10 at today's 154 MB baseline (rising to ~20 if #33 lands), which materially narrows the + isolation this design sells. #75 flagged the same ambiguity and it remains unanswered. +- Earlier design context assumed "20+ agents"; #32 targets **100 agents in 4 GB**. Grouping + heuristics, connection totals and executor budgets all change materially at 100. Which figure + is the design target? +- **For `scheduler_mode = "in_process"`, is true failover required** (a dead leader taken over + within a bound), or is "one designated instance runs it, others no-op" enough? The cheap + ordinal-check answer does not work under a Deployment, which has no stable ordinal, so a lease + is likely needed either way. +- **Who owns the subject taxonomy?** Pushing selection into the subject (sec. 7.7) only works if + publishers encode the discriminator, and the publishers are other services. `topic_mapping` lets + the framework enforce symmetry once a scheme exists, but it cannot invent the token order. + `..` is the usual shape. Open: who ratifies it, and how a subject is + added. +- **What is the consumer-count budget?** One hundred agents times a few subjects each is several + hundred JetStream consumers, each with its own ack-pending state. The connection ceiling was + closed as a non-issue (sec. 6); consumer count is the analogous question and has not been asked. +- **Do agents eventually become separate distributions?** Build-time dependency trimming would + require it, which is when the agent-to-module map should migrate to entry points. Not needed + while trimming stays opt-in. \ No newline at end of file From 75529e1540e87101750d02c4b9a35a93316d52b2 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:44:45 +0200 Subject: [PATCH 002/133] fix(eventing): P0-P3, make the transport safe for more than one replica (#81) Nothing here is about grouping yet -- these are the defects that block running a second replica of anything. P0: subscribe() takes the whole topic map and is managed by the framework, with background retry, re-subscription after reconnect and subscriptions_ready gating readiness; in-flight handlers drain before the connection closes; an undecodable payload is distinguished from a failed dispatch. P1: Core NATS subscriptions join a queue group derived from the agent, so a second replica stops processing every message a second time. P2: a normal return acks and a raised exception naks or terms per the spec table, on both transports; NO_HANDLER_FOUND acks instead of looping to max_deliver; unmatched events are counted, not flagged. P3: ack_wait, max_ack_pending and max_deliver are configurable on a ConsumerConfig the client owns; the durable carries a deliver group so JetStream shares load; what the framework gives up on is republished to .dead-letter. Dapr: the subscription document is served, so declared topics actually subscribe and GET /dapr/subscribe stops answering 422. Co-Authored-By: Claude Opus 5 (1M context) --- CLAUDE.md | 49 + CONTRIBUTE.md | 22 +- docs/concepts/event-processing.md | 85 ++ docs/guides/deployment.md | 26 +- ...26-08-28-multi-agent-grouping-changelog.md | 627 ++++++++++ docs/plans/2026-08-28-multi-agent-grouping.md | 92 +- docs/reference/configuration-keys.md | 25 + docs/specs/2026-08-28-multi-agent-grouping.md | 37 +- .../agents/clients/ai/openai_client.py | 2 +- .../agents/clients/ai/vllm_client.py | 2 +- src/blueprint/agents/clients/client_base.py | 9 +- .../agents/clients/io/dapr_client.py | 125 +- .../agents/clients/io/nats_client.py | 867 +++++++++++++- src/blueprint/agents/io/api/eventing/dapr.py | 206 ++-- .../agents/io/api/eventing/dapr_response.py | 24 + .../io/api/eventing/event_handling_base.py | 96 +- src/blueprint/agents/io/api/eventing/nats.py | 112 +- src/blueprint/agents/io/api/rest_api_base.py | 12 +- src/blueprint/agents/models/__init__.py | 4 +- src/blueprint/agents/models/errors.py | 44 + .../agents/clients/ai/test_openai_client.py | 2 +- .../agents/clients/ai/test_vllm_client.py | 2 +- tests/unit/agents/clients/io/conftest.py | 15 +- .../agents/clients/io/test_dapr_client.py | 123 +- .../agents/clients/io/test_nats_client.py | 1063 ++++++++++++++++- tests/unit/agents/io/api/eventing/conftest.py | 10 +- .../unit/agents/io/api/eventing/test_dapr.py | 322 ++++- .../api/eventing/test_event_handling_base.py | 113 +- .../unit/agents/io/api/eventing/test_nats.py | 180 ++- tests/unit/agents/models/test_errors.py | 40 + 30 files changed, 3951 insertions(+), 385 deletions(-) create mode 100644 docs/plans/2026-08-28-multi-agent-grouping-changelog.md create mode 100644 src/blueprint/agents/io/api/eventing/dapr_response.py create mode 100644 tests/unit/agents/models/test_errors.py diff --git a/CLAUDE.md b/CLAUDE.md index e2a2ed51..a8e42668 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -78,6 +78,55 @@ why before starting the next. Do not chain phases together, and do not chain the a phase, into a single unreviewed run -- each step is meant to be looked at before the next one begins. This rule applies to every prerequisite and phase in that plan, and only to this feature. +**Record every change in the feature changelog.** `docs/plans/2026-08-28-multi-agent-grouping-changelog.md` +is updated as part of each change, not reconstructed at the end: it is the running record of what +was done and why, and it becomes the pull-request description. Smaller fixes found along the way +belong in it too -- they are the ones most easily lost. + +**Explain new code, not just its arrival.** When a change introduces real implementation -- new +behaviour, new control flow, a new abstraction -- report what was built and how it works, not only +which files changed and whether the checks passed. Formatting and lint fixes, type annotations, +tests and documentation need no walkthrough. + +**Report the production code in detail, and report it first.** The walkthrough is about +`src/`: name each function, branch and call site that changed, show the lines that matter, and say +what the code now does that it did not do before and what breaks if it is removed. A list of files +touched, a summary of intent, or "tests pass and lint is clean" is not a report of the code -- that +is the wrapper around it. Tests, documentation and the changelog are listed, not walked through: +they are how the change is verified and recorded, not the change itself. + +This is not satisfied by having reported the code in an earlier message. **Every message that +reports a step as done carries the walkthrough**, including the one that follows a background test +run finishing -- that message reports the step, so it repeats the code detail rather than shrinking +to a status line. Err towards showing the actual changed lines: a paraphrase of what a function now +does is weaker than the function. + +The rule has been missed repeatedly, so treat it as a checklist item before writing any completion +message: *have I shown the changed code, not described it?* + Read the spec before changing `component/registry.py`, `app_builder.py`, `handler/`, `services/eventing/`, `io/api/eventing/`, `clients/io/nats_client.py`, the schedulers or telemetry: those paths carry invariants that are not visible from the code. + +--- + +## Commits + +Commit messages follow **Conventional Commits** -- `.pre-commit-config.yaml` runs the commitizen +hook at the `commit-msg` stage, so the subject line must be `(): ` with +a type from `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, +`revert`. A prefix like `P0:` is not a type and will be rejected once the hook is installed. + +Install every hook stage, not just the default one: + +```bash +pre-commit install +pre-commit install --hook-type commit-msg +pre-commit install --hook-type pre-push +``` + +End every commit message with the repo's trailer: + +``` +Co-Authored-By: Claude Opus 5 (1M context) +``` diff --git a/CONTRIBUTE.md b/CONTRIBUTE.md index d69db65a..9986574b 100644 --- a/CONTRIBUTE.md +++ b/CONTRIBUTE.md @@ -206,16 +206,34 @@ mypy src/ black src/ tests/ && ruff check src/ tests/ && mypy src/ ``` -## Pre-commit & Pre-push Hooks +## Commit Messages -Set up both commit and push hooks: +Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/): a subject line +of `(): `, where the type is one of `feat`, `fix`, `docs`, `style`, +`refactor`, `perf`, `test`, `build`, `ci`, `chore` or `revert`. The commitizen hook configured in +`.pre-commit-config.yaml` checks this at the `commit-msg` stage, so it only runs if you install +that stage (see below). + +``` +fix(eventing): join a queue group on Core NATS subscriptions + +Without queue= every replica received every message, so two replicas +doubled every side effect. +``` + +## Pre-commit, Commit-msg & Pre-push Hooks + +Install all three hook stages -- `pre-commit install` on its own installs only the first, which +leaves the commit-message check inactive: ```bash pre-commit install +pre-commit install --hook-type commit-msg pre-commit install --hook-type pre-push ``` - **Pre-commit** runs linting and formatting checks on staged files before each commit. +- **Commit-msg** validates the commit message against Conventional Commits. - **Pre-push** runs the unit test suite before pushing, so CI won't fail on basic issues. ## Troubleshooting diff --git a/docs/concepts/event-processing.md b/docs/concepts/event-processing.md index 37d5473f..6c7da983 100644 --- a/docs/concepts/event-processing.md +++ b/docs/concepts/event-processing.md @@ -234,6 +234,91 @@ default_pubsub_name = "default" "document.summarized" = "documents.processed" ``` +### JetStream delivery + +With `nats_use_jetstream = true` the framework creates one **durable consumer per topic** on the +configured stream and binds every replica to it through the agent's queue group, so exactly one +replica handles each message. What happens to a delivery is decided at the transport edge: + +| Outcome | Disposition | +|---------|-------------| +| The handler chain returned, including "no handler matched" | `ack` | +| `RetryableHandlerError`, or any unexpected exception | `nak` -- redelivered after `nats_ack_wait` | +| `InvalidEventError` or `CriticalHandlerError` | dead-lettered, then `term` | +| The payload is not a parseable CloudEvent | dead-lettered, then `term` | +| The last delivery `nats_max_deliver` allows failed again | dead-lettered, then `term` | + +Dead-lettering republishes the **original bytes**, unchanged, to `nats_dead_letter_subject`, with +the reason, the original subject, the delivery count and the event id in headers. The subject is +added to the stream when the framework provisions it, so dead letters are persisted rather than +dropped on the floor, and consuming them is an ordinary subscription. + +Two settings interact and are worth choosing together: + +- **`nats_ack_wait` must exceed your slowest handler.** It is the broker's patience, not the + client's: when it expires the message is redelivered to another replica while the first one is + still working, so a model call that occasionally takes four minutes needs an `ack_wait` above + four minutes, not the NATS default of thirty seconds. +- **`nats_max_ack_pending` should stay close to the replica count.** A push subscription processes + its callbacks one at a time, so anything larger parks messages in the client's queue -- where + their `ack_wait` is already counting down, unhandled. + +An existing consumer is never rewritten. Its filter subject and deliver group are broker-side +state that the stream's redelivery bookkeeping hangs off, so changing them is a migration: the +client logs which settings differ and keeps consuming with the ones the broker already has. Apply +new values by deleting the consumer during a maintenance window. + +## 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: diff --git a/docs/guides/deployment.md b/docs/guides/deployment.md index e64d4abb..ede13d98 100644 --- a/docs/guides/deployment.md +++ b/docs/guides/deployment.md @@ -2,21 +2,25 @@ This guide covers packaging, deploying, and operating Blueprint Agents applications in production environments using Docker, Kubernetes, and Helm. -> **Running more than one replica is not safe in the current release.** Three defects make -> horizontal scaling incorrect rather than merely inefficient: +> **Running more than one replica is not safe in the current release.** Message distribution is +> now correct on both NATS paths -- Core NATS subscriptions join a queue group (`nats_queue_group`, +> default `app_name`), JetStream consumers are durable and share a deliver group, and every +> delivery is acknowledged, redelivered or dead-lettered explicitly. Two problems remain: > -> - **Every replica processes every message.** Core NATS subscriptions are created without a queue -> group (`clients/io/nats_client.py`), and JetStream is off by default (`nats_use_jetstream`), so -> two replicas silently double every side effect and every inference bill. -> - **JetStream messages are never acknowledged.** Subscriptions use `manual_ack=True` and no -> `msg.ack()` call exists anywhere, so every event redelivers until `max_deliver` — already -> true at a single replica. > - **Every replica runs its own scheduler.** `SchedulerBase` starts an `AsyncIOScheduler` per > process with no leader election, so each cron tick fires once per replica. +> - **Duplicate delivery is not handled.** Competing consumers make at-least-once permanent, and a +> handler that finishes its work and then fails to acknowledge -- a connection blip, a pod killed +> mid-handler -- has already committed its side effects when the message is redelivered. The +> framework offers no deduplication yet, so a handler that is not naturally idempotent will repeat +> itself. > -> Until these are fixed, deploy one replica with `autoscaling.enabled: false`. The HPA example +> The delivery behaviour above is covered by unit tests against mocked transports, and has not yet +> been exercised against a real broker. +> +> Until these are addressed, deploy one replica with `autoscaling.enabled: false`. The HPA example > below shows the chart's shape; it is not a recommendation. Required behaviour is specified in -> `docs/specs/2026-08-28-multi-agent-grouping.md`, sec. 7.1, 7.2 and 7.5; the fixes are P1, P2 and +> `docs/specs/2026-08-28-multi-agent-grouping.md`, sec. 7.4 and 7.5; the remaining fixes are P4 and > P5 in `docs/plans/2026-08-28-multi-agent-grouping.md`. This guide also assumes one Deployment > per agent, and will be rewritten when group-based deployment lands. @@ -315,6 +319,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. diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md new file mode 100644 index 00000000..35f30e5b --- /dev/null +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -0,0 +1,627 @@ +# Change Log -- Multi-Agent Grouping + +| | | +|---|---| +| **Spec (normative)** | `docs/specs/2026-08-28-multi-agent-grouping.md` | +| **Implementation plan** | `docs/plans/2026-08-28-multi-agent-grouping.md` | +| **Branch** | `feature/multi-agent-namespaces` | + +Running record of every change on this branch, in the order it landed, with the reasoning behind +it. It doubles as the pull-request description, so it is updated as part of each change rather +than reconstructed at the end. At release time a condensed entry goes into `CHANGELOG.md` under +`[Unreleased]`; this file keeps the detail that would not fit there. + +--- + +## What this feature does + +Today one agent means one process, one port, one broker connection and one container image, so a +platform of 100 agents pays the ~154 MB Python and library baseline 100 times. This feature makes +**which agents share a process a deployment parameter rather than an architectural commitment.** + +Components gain an optional **namespace** (`""` by default, so nothing existing changes). A +namespace owns its own handlers, agent runtime, REST routes, AI client, thread pool and broker +connection, while genuinely shared infrastructure -- the port, the health endpoint, the caches -- +stays single. Which namespaces a process hosts is resolved at startup from a group configuration, +and Kubernetes runs one Deployment per group: a group of one gives today's process isolation, a +group of twenty gives the shared-interpreter memory profile, and moving an agent between groups +changes neither its broker-side consumer identity nor its telemetry identity. + +Reaching that requires fixing several defects that block running more than one replica of +*anything* today, which is what the prerequisites (P0-P6) cover and where the work starts. + +--- + +## TL;DR + +Design and specification: + +- Normative spec and phased implementation plan, extracted from `CLAUDE.md` into the repo's + spec/plan convention (`4233933`) +- **Acknowledgement contract**: a normal return acks, a raised exception does not; `NO_HANDLER_FOUND` + acks (`b6ab1c9`) +- **Selection and fan-out rules** (spec sec. 7.7), including the two rules that keep a dispatch + index and broker-side filters non-breaking (`13e4d28`) +- Acceptance criteria for both of the above (`b94f60c`) + +Code: + +- **P0 -- transport lifecycle**: managed whole-map `subscribe()`, background retry, reconnect + re-subscription, `subscriptions_ready` readiness gating (`77af507`) +- **P0 -- shutdown drain**: in-flight handlers finish before the connection closes (`585e58c`) +- **P0 -- message boundary**: an undecodable payload is distinguished from a failed dispatch + (`3843abf`) +- **Dapr subscription discovery fixed** -- declared topics now actually subscribe; `GET + /dapr/subscribe` no longer answers 422 (#81, `fac528b`) +- **P1 -- queue groups**: Core NATS subscriptions join a queue group derived from the agent, so a + second replica no longer processes every message a second time (`05083c8`) +- **P2 (NATS half) -- acknowledgement**: a normal return acks, a raised exception naks or terms per + the spec table; the two layers that swallowed the classification are gone (`ce17f87`) +- **P2 (Dapr half) -- parity**: `NO_HANDLER_FOUND` answers `SUCCESS` instead of looping until + `max_deliver`, a critical error drops instead of retrying, and an unparseable body drops instead + of answering 422; both transports now render one shared decision (`ce17f87`) +- **P2 -- unhandled events are counted, not flagged**: `blueprint.events.unhandled` per + (namespace, topic), read as a ratio; finding no work in an event is normal behaviour +- **P3 -- consumer tuning**: `ack_wait`, `max_ack_pending` and `max_deliver` are configurable and + are enforced by the broker, on a `ConsumerConfig` the client creates itself +- **P3 -- JetStream shares load**: the durable carries a deliver group, so JetStream stops being + single-subscriber; this was P1's other half +- **P3 -- dead letters**: a message the framework gives up on is republished, payload unchanged, + to `.dead-letter` before it is termed +- **P3 -- three defects found on the way**: the stream never covered the subject its consumer + filtered on, only the first topic was ever added to it, and the derived durable name was illegal + for any dotted subject + +Documentation and process: + +- Deployment guide now warns that multi-replica is unsafe, and its examples default to one replica + (`2d80b63`) +- New config keys documented: `event_client_drain_timeout`, `dapr_pubsub_name`, + `dapr_declarative_subscriptions` +- Feature working rules in `CLAUDE.md`: one reviewable change at a time (`4cf2d51`), and a + walkthrough whenever real code is written (`7735251`) + +Issues opened along the way: + +- **#80** -- 28 failing example tests assert on removed examples; the unit/integration split is + unenforced +- **#81** -- Dapr declared topics never subscribe (fixed here) + +**Breaking changes: none so far.** See *Compatibility* at the end. + +--- + +## Changes in detail + +### Spec and plan extracted into the repo's conventions (`4233933`) + +The multi-agent work breakdown lived as a 900-line section inside `CLAUDE.md`. It is now +`docs/specs/2026-08-28-multi-agent-grouping.md` (normative: scope, invariants C1-C7, public API, +configuration, transport topology, event delivery, caches, startup, backwards compatibility, +acceptance criteria, open questions) and +`docs/plans/2026-08-28-multi-agent-grouping.md` (the phased breakdown: prerequisites P0-P6 and +phases 0-9). `CLAUDE.md` keeps pointers plus the list of paths that require reading the spec first. + +**Motivation.** `CLAUDE.md` is loaded into every session, so a 900-line plan costs context on every +task regardless of relevance, and it cannot be reviewed the way a document under `docs/` can. The +repo already separated spec from plan (`docs/specs/2026-07-06-...-design.md` against +`docs/plans/2026-07-06-...md`), so this follows an existing convention rather than inventing one. +Open questions live in the spec alone, so the two documents cannot drift. + +### Acknowledgement contract (`b6ab1c9`) + +Spec sec. 7.2 now states: **a normal return acknowledges, a raised exception does not.** The +transport edge must not inspect `ProcessingResult` to decide delivery, and `NO_HANDLER_FOUND` +acknowledges like any other completed dispatch. Both transports must map the same outcome to the +same disposition, so `CriticalHandlerError` drops on Dapr rather than retrying, and a payload that +fails to parse terms rather than naks. Acknowledging an unmatched event must not hide it: unhandled +events are counted per namespace and topic, with a warning on the first occurrence of each pair. + +**Motivation.** `ProcessingStatus` has exactly two values, `PROCESSED` and `NO_HANDLER_FOUND` -- +there is no failure status, so every real failure already arrives as an exception and inspecting the +result buys nothing. It does actively harm: `dapr.py` mapped `NO_HANDLER_FOUND` to `RETRY`, so an +event no handler wanted was redelivered until `max_deliver`, and under a queue group that loop +visits every replica in turn. The contract removes a check rather than adding one. + +### Selection and fan-out (`13e4d28`) + +Spec sec. 7.7 records that selection happens at two levels and only the subject level is enforced +by the broker: NATS has no content or header predicate, and Dapr's CEL rules are evaluated in the +sidecar after delivery. With one consumer per `(namespace, topic)` pair, a broad subject makes the +broker copy every message once per namespace. + +Two rules are normative, and both exist to keep the optimisation non-breaking: + +1. A handler that declares nothing must still be evaluated for every event its namespace receives. + A dispatch index may key on declared event types, but undeclared handlers must fall into an + always-evaluated wildcard bucket. +2. A broker-side filter must never be narrower than the declared topics unioned with + `nats_subscriptions`, and must never be inferred from handler code. + +Also normative: consumer reconfiguration is a migration, because a durable's name and filter set +are broker-side state and a recreated consumer either replays or gaps. + +**Motivation.** 100 agents each evaluating every event is the wrong shape, and the fix has to go +into the subject rather than into Python. The two rules are load-bearing because **nothing declares +anything today** -- `get_subscribed_topics()` is overridden nowhere in the framework or in any +scaffolded project -- so a design that treats declarations as authoritative describes an empty set +and would silence every existing handler. Combined with the ack contract, the events would then be +acknowledged and discarded rather than accumulating visibly. + +The migration rule surfaced that **Phase 5 was already a consumer migration and was not documented +as one**: renaming durables to `{namespace}-{topic}-durable` makes every pre-existing consumer a new +consumer on first deploy. + +### Acceptance criteria for the above (`b94f60c`) + +Five criteria added to spec sec. 12, covering the ack contract, cross-transport parity, the +undeclared-handler rule, filter derivation, and the two observability counters. + +**Motivation.** Sections 7.2 and 7.7 were normative but had no entry in the acceptance criteria, so +"done" did not include them. + +### P0 -- transport lifecycle (`77af507`) + +Connection, retry and subscription lifecycle moved out of the eventing APIs and into the transport +clients. `ClientBase.subscribe(topic_callbacks)` replaces `subscribe(topic, callback)`: one +non-blocking call carrying the whole `{topic: callback}` map, backed by a background retry task. +Adds `subscriptions_ready` with health-check gating, `disconnected_cb`/`reconnected_cb` with +JetStream durable re-subscription, and the `event_client_max_retries` / `event_client_retry_delay` +keys. The imperative `POST /nats/subscribe/{topic}` endpoint and the `EventHandlingBase.subscribe` +abstract are removed. + +**Motivation.** Previously `NatsEventing.on_startup` subscribed imperatively, so a broker that was +down at startup left the app running with no subscriptions and no record of what it had wanted. +Everything later in the plan depends on this shape: P2's acknowledgement correctness needs the +reconnect path to exist, C4 and C7 read `subscriptions_ready`, and per-namespace clients (P6) need a +single subscribe call carrying the whole map. + +Originally written as PR #27; applied here as one commit without that branch's CI and version +changes, so this update can land first. + +### P0 -- shutdown drain (`585e58c`) + +`close()` now cancels the retry task, drains subscriptions so already-queued messages still reach +their handler, waits for running handlers, and only then closes the connection. One deadline from +`event_client_drain_timeout` (default 30 s) bounds the whole sequence. A drain that fails or +outlives the deadline falls back to an immediate unsubscribe. In-flight work is counted in +`message_handler`'s `try/finally` and exposed as `inflight_handlers`. + +**Motivation.** The order is the fix. An acknowledgement is published to the delivering +connection's reply subject, so closing the connection first strands it and the broker redelivers -- +every deploy guaranteed duplicate work for whatever was in flight, and P2 would have inherited that +as a permanent duplicate source. `inflight_handlers` is public because Phase 9 needs exactly that +number for the per-namespace in-flight gauge (C7). + +### P0 -- message boundary (`3843abf`) + +Decoding moved into `_decode_message`, which returns `None` for a payload that cannot become a +CloudEvent and logs it as discarded, naming the topic. Dispatch keeps its own catch, logging the +event id, the topic and a traceback. + +**Motivation.** One `except Exception` covered both decoding and dispatch and logged a single +message for both -- no topic, no event id, no traceback. Those two failures have opposite +dispositions under spec sec. 7.2 (term versus nak), and P2 cannot act on a distinction that has +already been erased. Each failure is now logged exactly once, by the layer that knows what it means. + +The boundary still catches both: a broker callback that raises into `nats-py` loses our context and +gains nothing while no code yet decides what to do with a failure. In P2 the catch becomes the +disposition. + +### Dapr subscription discovery (#81, `fac528b`) + +`GET /dapr/subscribe` now takes no parameters and returns a subscription array built from +`get_subscribed_topics()` -- one entry per declared topic, routed to `/events/{topic}`, using the +`dapr_pubsub_name` key the publisher already reads. `dapr_declarative_subscriptions` (default +`false`) serves an empty document for deployments that declare subscriptions as Kubernetes +resources. + +**Motivation.** Three defects, found while resolving P0's last gap. The endpoint's signature was +`subscribe(self, topic: str, queue_group: str | None = None)`, and since the path holds no +`{topic}`, that was a **required query parameter** -- so the sidecar's parameter-less GET was +answered 422 by FastAPI before any framework code ran. The body returned `{}` where Dapr expects an +array. And the declarations were collected into a callback map handed to `DaprClient`, which only +pings `/v1.0/healthz` and never reads it, because Dapr delivers over HTTP rather than through a +client-side callback. Net effect: under Dapr, a handler's declared topics subscribed to nothing. + +The callback map is kept deliberately and documented for what it is -- the input that starts the +sidecar-reachability retry and feeds `subscriptions_ready`. Removing it, which "delete the unused +map" invites, would have silently disabled the readiness gating added in P0. + +### P1 -- queue groups on Core NATS subscriptions (`05083c8`) + +Every Core NATS subscription now passes `queue=`, so the server delivers each message to exactly +one member of the group instead of to every subscriber. The name is resolved once, in +`subscribe()`, from `nats_queue_group` falling back to `app_name`, and is exposed as the public +`queue_group` property; the resolved name is logged with each subscription, which is what makes C1 +checkable by diffing two deployments' startup logs. + +Three details carry the invariant: + +- **The name identifies the agent, not the process.** C1 requires the queue group to be a pure + function of the agent's own identity, so that regrouping is invisible to the broker. Only + `nats_queue_group` and `app_name` feed it -- never a pod, container or replica name. When + namespaces land, the namespace supplies the name directly and these keys stay as the root-namespace + fallback. +- **An underivable name raises rather than defaults.** NATS reads `queue=""` as *no queue group*, so + any silent fallback would reintroduce exactly the fan-out being fixed, and would do it invisibly. + `subscribe()` raises `ValueError` instead, naming both keys. +- **It is resolved in `subscribe()`, not at subscription time.** `subscribe()` is called by the + caller's startup path, while the actual subscribing happens inside the background retry task. A + config error raised in that task would be retried indefinitely (`event_client_max_retries` + defaults to `-1`) and would surface only as a readiness probe that never goes green. Raising in + `subscribe()` fails startup where a human is looking. + +**Motivation.** JetStream is off by default, so the default transport path was plain Core NATS with +no queue group: `replicas: 2` meant both replicas received and processed every event -- every side +effect twice, every inference billed twice. This is a defect at any replica count above one, +independent of grouping, and it is what makes the deployment guide's multi-replica warning +removable later. + +**JetStream is deliberately untouched, and still single-subscriber.** nats-py rejects a queue +subscription whose durable name differs from the queue name +(`cannot create queue subscription '' to consumer ''`), so passing the queue group +next to the existing per-topic durable would raise at subscribe time. A durable shared across +replicas needs its deliver group set on an explicitly constructed `ConsumerConfig` and bound with +`subscribe_bind`, which is the same object P3 has to build anyway for `ack_wait` and +`max_ack_pending`. Doing it there is one change instead of two, and the constraint is recorded as a +comment at the call site so it does not read as an oversight. Until then a second replica on +JetStream fails to subscribe loudly (`consumer is already bound to a subscription`) rather than +double-processing silently -- the safer of the two failures, and readiness gating keeps such a pod +out of rotation. + +New config key: `nats_queue_group` (default: `app_name`), documented in +`docs/reference/configuration-keys.md`. + +**What this buys, and what it depends on.** The group key is *(subject, queue name)*, so with the +name set per agent the two properties a multi-agent platform needs hold together: different agents +on one subject are different groups and each receives its own copy (fan-out), while replicas of one +agent share a group and one of them handles each message (round-robin). Adding a replica never adds +a copy; adding an agent always does. Plain non-queue subscribers, such as a monitoring tap, are +unaffected and still receive everything. + +Both properties rest on the names being distinct per agent, and two things can break that: + +- **Default-valued `app_name`.** Scaffolding writes the project name + (`settings_part_generator.py:11`), but the config validator falls back to `agent_blueprint` if the + key is removed, and `asbs create agent` outside a scaffolded project writes `generated-agent` + (`create.py:580`). Two services on either default would join one group and steal each other's + events -- the failure this fixes, moved from replicas to agents. Candidate for an `asbs validate` + notice when `event_bus = "nats"`. +- **JetStream durables are keyed by topic, not by agent** (`nats_durable_name`, default + `f"{topic}-durable"`). Two agents subscribing to the same topic both try to bind one durable and + the second fails. Cross-agent fan-out under JetStream therefore does not work until the Phase 5 + rename to `f"{namespace}-{topic}-durable"`, which is the functional reason that rename is + load-bearing rather than cosmetic. Separately, a project that sets `nats_durable_name` explicitly + collapses all its topics onto one durable name; pre-existing, and worth fixing where Phase 5 + touches that line. + +### P2 -- acknowledgement at the NATS transport edge (`ce17f87`) + +JetStream messages were subscribed with `manual_ack=True` and never acknowledged, so every event +redelivered until `max_deliver` -- a defect at a single replica, not just at scale. The transport +edge now settles every delivery, and the classification needed to settle it correctly survives the +trip from the handler. + +**The disposition table lives in one place.** `models/errors.py` gains `DeliveryDisposition` +(`ACK`/`NAK`/`TERM`) and `disposition_for(exc)`, next to the exceptions it classifies. Spec sec. 7.2 +requires both transports to map the same outcome to the same disposition, so encoding the table once +is what makes that checkable rather than aspirational -- and a new `HandlerError` subclass is now +added in the same file that decides what its failures do to a delivery. Matching is by `isinstance`, +so a project's own subclass inherits its parent's disposition. The function never returns `ACK`: +acknowledgement is what a *normal return* means, and the edge decides that without asking. + +**`NATSClient._settle` applies it.** `message_handler` acks on normal return, terms an undecodable +payload before dispatch, and otherwise settles with whatever `disposition_for` says. Two details: + +- It gates on `_use_jetstream`, not on `msg.reply`. Core NATS is fire-and-forget and `msg.ack()` + raises `NotJSMessageError` there, but a Core NATS *request/reply* message does carry a reply + subject -- gating on the subject would publish `+ACK` to a waiting requester. +- A failure to settle is logged and swallowed. The acknowledgement is published to the delivering + connection's reply subject, so it fails exactly when that connection is gone; raising into the + `nats-py` callback would neither deliver it nor recover it. The message redelivers after + `ack_wait`, which is the at-least-once behaviour sec. 7.4 already requires handlers to tolerate. + +**Two swallowing layers removed.** `NatsEventing._process_event` caught the three classified handler +errors, logged them and returned normally -- which, once the edge acks on normal return, would have +acknowledged every failed event as processed. `EventHandlingBase._process_cloud_event` logged each +exception and re-raised it; the logging is gone and the exception now passes through untouched. Both +transports already log at their own edge, where the topic and the disposition are known, so the +removed logging was duplicate output that knew less than the line beside it. It also brings the +method in line with the repo's log-or-raise rule. + +**Still open in P2**, each its own step: Dapr parity (`NO_HANDLER_FOUND` -> `SUCCESS`, +`CriticalHandlerError` -> `DROP`, and the same in `handle_event`), the unhandled-event counter with +its first-occurrence warning, and `max_deliver` plus a dead-letter destination, which lands with P3 +because a nak on an unexpected exception otherwise redelivers forever. + +### P2 -- Dapr parity (`ce17f87`) + +Dapr acknowledges by response body, so `POST /events/{topic}` is its `_settle`. It disagreed with +the spec table in two places, and both disagreements were live defects: + +- **`NO_HANDLER_FOUND` returned `RETRY`.** An event no handler wanted was redelivered until + `max_deliver`, and now that P1 puts every replica in a queue group, that loop visits each replica + in turn before giving up. It answers `SUCCESS`. +- **`CriticalHandlerError` returned `RETRY`.** A critical error is not made less critical by being + delivered again. It answers `DROP`, matching NATS's `term`. + +An unexpected exception previously raised `HTTPException(500)`. That is a third behaviour rather than +a disposition: the sidecar sees a failed call and applies whatever its own resiliency policy says, +which need not be retry and is not visible from this code. It now answers `RETRY` explicitly, as the +table requires. **The tradeoff is deliberate**: a 500 showed up in HTTP metrics and traces as a +failure, and a 200 with `RETRY` does not, so an unexpected handler exception is now visible only in +the log line and in Dapr's own retry counters until the P2 counters land. + +**One `except`, not four.** The four per-error-type blocks collapsed into a single one that calls +`disposition_for(exc)` and renders the result. The rendering lives in a new +`io/api/eventing/dapr_response.py` -- three lines of mapping from `DeliveryDisposition` to +`SUCCESS`/`RETRY`/`DROP`. It sits there rather than in `models` so Dapr's vocabulary does not leak +into the shared layer, and rather than in `dapr.py` so `EventHandlingBase.handle_event` can render +identically without importing a subclass. What an outcome deserves is decided once; each transport +only says it in its own words, and adding a new error type can no longer update one transport and +miss the other. + +`EventHandlingBase.handle_event` got the same treatment: acknowledge whatever status the chain +returned, warn when nothing matched, and let exceptions through to the edge. + +**Unparseable deliveries now drop, which changes an HTTP response.** A payload that cannot become a +CloudEvent must `DROP` (spec sec. 7.2), but under Dapr the body is parsed by FastAPI before any +framework code runs, so that payload was answered **422** and the sidecar retried it to +`max_deliver` -- the one row of the table where the transports disagreed for a structural reason +rather than a coding one. `DaprDeliveryRoute`, an `APIRoute` subclass, wraps the route handler and +converts `RequestValidationError` into `200 {"status": "DROP"}`. + +*This is a deliberate behaviour change*: `POST /events/{topic}` no longer answers 422 for a malformed +body under Dapr. That is the correct answer to a *REST caller* and the wrong answer to a *sidecar +delivery*, and the same path serves both roles. The wrapper is therefore scoped to the component +that asks for it via a new `RestApiBase.route_class` hook -- an application-wide +`RequestValidationError` handler would have answered `DROP` for ordinary REST endpoints too, where +422 is right. `NatsEventing`, which owns the same path for the outbound direction, keeps the default +route class and still answers 422; there is a test for exactly that. + +### P2 -- unhandled-event accounting, and a spec correction + +An event that matches no handler is acknowledged, and it is also **ordinary**. Deciding there is +nothing to do is the handler's job and an ordinary outcome of doing it: an agent reads an event, +finds no work in it, and says so. Why is the agent's business -- wrong tenant, wrong state, a +condition that is not met -- and none of it is the framework's concern. + +`_process_cloud_event` therefore does exactly two things with such a dispatch: increments +`blueprint.events.unhandled` with `namespace` and `topic` attributes, and logs at DEBUG. + +- **Counted, because the ratio is the signal.** A namespace declining nearly everything it receives + is subscribed too broadly (spec sec. 7.7). That is a question about the subject filter, and it is + only answerable against received volume -- so the count must not be deduplicated. +- **Not flagged, because nothing is wrong.** No WARNING, no error. +- **No state kept.** Under Dapr the topic comes from a URL path, so remembering distinct topics + would let a caller grow this process's memory. + +It lives in `_process_cloud_event`, shared by both transports, because an unmatched dispatch is a +property of the dispatch rather than of the transport carrying it -- and both edges keeping their +own copy of a delivery rule is how they came to disagree about `NO_HANDLER_FOUND` in the first +place. The interim per-event warnings the Dapr work left in `publish` and `handle_event` are gone. + +`_process_cloud_event` gains a `topic` parameter. The topic is already in `context`, but each +transport spells its key differently (`nats_topic`, `dapr_topic`) and those keys reach user +handlers, so they cannot be unified without breaking them. + +`EventHandlingBase.ROOT_NAMESPACE` is the one place the "no namespaces yet" assumption is written +down; phase 2 replaces it and the counter's `namespace` attribute starts varying. + +**The spec was wrong and is corrected.** Sec. 7.2 had required a WARNING on the first +(namespace, topic) pair and called an unmatched event "usually a declaration error"; sec. 7.7 called +it one of "both directions of the same error". That premise is false -- it treats a handler's +domain decision as a framework fault -- and it was implemented before being questioned. Sec. 7.2 now +forbids reporting it as a fault and forbids per-topic state, sec. 7.7 frames both counters as ratios +rather than faults, and the acceptance criterion carries the same conditions. A first +implementation with the tracker, the warning and an accumulating set was replaced rather than +committed. + +### P3 -- consumer tuning, deliver groups and dead letters + +Four settings, one object. `ack_wait`, `max_ack_pending`, `max_deliver` and the deliver group all +live on `ConsumerConfig`, so the client stops letting `js.subscribe` invent a consumer and builds +one itself: `_ensure_consumer` creates the durable through `add_consumer` and `_subscribe_one` binds +to it with `subscribe_bind`. That is the only route by which P1's queue group can reach JetStream -- +`nats-py` refuses a queue subscription whose durable name differs from the queue name, and the +durable is per topic while the queue group is per agent -- so **JetStream stops being +single-subscriber**, which was the half of P1 that had to wait. + +New keys, all defaulting to working behaviour: `nats_ack_wait` (300 s), `nats_max_ack_pending` (16), +`nats_max_deliver` (5), `nats_dead_letter_subject` (`.dead-letter`). They are resolved +and validated in `subscribe()` alongside the queue group, for the same reason: a config error must +fail the caller's startup rather than repeat forever inside the background retry task. + +**Two defaults are opinions, and the reasoning is worth keeping.** `ack_wait` is 300 s against a +NATS default of 30 s, because handlers here call models and a redelivery mid-inference costs the +work twice. `max_ack_pending` is 16 rather than the NATS default of 1000, because a `nats-py` push +subscription runs its callbacks one at a time: everything the broker pushes beyond what is actually +being processed sits in the client's queue with its `ack_wait` already running down. A large window +does not buy throughput here, it manufactures expiries. + +**Dead letters.** `_settle` gained one branch: a nak on the last delivery `max_deliver` permits is +turned into a dead letter plus a term. Naking there is a lie -- the broker will not redeliver it -- +and it differs from a term only in that the message leaves the consumer with no trace of why, one +`ack_wait` later than it needed to. `_dead_letter` republishes the **original bytes**, unchanged, so +a payload that never parsed as a CloudEvent survives; what went wrong travels in +`Blueprint-Dead-Letter-Reason`, `-Original-Subject`, `-Delivery-Count` and `-Event-Id` headers, where +it cannot corrupt a body some dead-letter consumer will try to read. Terminal failures -- +`InvalidEventError`, `CriticalHandlerError`, an unparseable payload -- take the same path. Setting +the subject to `""` disables it, and then each drop is logged as a lost payload rather than passing +silently. + +The dead-letter subject is derived from the queue group, so it follows the agent's identity exactly +as C1 requires, and it is validated at startup: a wildcard is rejected because it is published to, +and a subject the same client subscribes to is rejected because dead-lettering onto a consumed +subject turns one failure into an unbounded loop -- the kind that only shows up under load. + +**Three defects surfaced while building it**, none visible from P3's description, all of which +blocked explicit consumer creation: + +1. **The stream never covered the subject its consumer filtered on.** `add_stream` was called with + `subjects=[f"{topic}.>"]`, which does not match `topic` itself. `js.subscribe` had been papering + over it by letting the server pick; an explicitly created consumer filtering `orders.created` is + simply rejected by a stream that only captures `orders.created.>`. +2. **Only the first topic was ever added to the stream.** `add_stream` ran once per topic with the + same stream name; every call after the first answered "stream name already in use" and was logged + as a warning, leaving the remaining topics uncaptured. Provisioning now happens once per connect, + in `_provision_stream`, with the union of every subscribed subject plus the dead-letter subject, + and widens an existing stream additively rather than replacing it. +3. **The derived durable name was illegal for any dotted subject.** NATS allows no `.`, `*`, `>` or + whitespace in a consumer name, so `f"{topic}-durable"` could not work for `orders.created` -- that + is, for essentially every idiomatic NATS subject. `_durable_for` replaces those characters, and + `_resolve_durables` rejects at startup both the collision that substitution can create and + `nats_durable_name` set while several topics are subscribed, since one durable filters one + subject. + +**An existing consumer is never rewritten.** `_ensure_consumer` reads `consumer_info` first and, when +the durable already exists, binds to the server's config and logs which settings differ. A durable's +filter subject and deliver group are broker-side state that the stream's pending and redelivery +bookkeeping hangs off; rewriting one in place either replays messages it already handled or skips +ones it never saw. The spec already called consumer reconfiguration a migration, and this is that +rule in code -- a rolling restart must not perform one silently. The practical consequence is that +an existing deployment upgrading into this change keeps its old consumer, without a deliver group, +until someone deletes it deliberately; the warning names exactly which settings are not in force. + +The deliver subject is derived from the durable name rather than taken from a fresh inbox, because +every replica has to bind to the same one -- two replicas generating random inboxes would define two +consumers, which is the fan-out P1 removed. + +### Deployment guide corrected (`2d80b63`) + +The guide recommended `replicaCount: 2`, an HPA, and `--set replicaCount=3` as ordinary scaling. It +now opens with a warning naming the three defects that make multi-replica incorrect rather than +merely inefficient, its examples default to one replica, and the HPA section says to leave +autoscaling off for now. Also dropped the spec's ADR-derived `Status: draft` row, since `draft` +belongs to ADR vocabulary while this repo uses Status as a revision marker. + +**Motivation.** This is the only piece of *existing, shipped* documentation that could cause harm +before any code changes: following it doubles every side effect and every inference bill, and +duplicates every cron tick. + +### Working rules for this feature (`4cf2d51`, `7735251`) + +`CLAUDE.md` gained two rules scoped to this feature: work in reviewable steps, one change at a time, +reported before the next begins; and explain new code, not just its arrival -- a walkthrough of the +mechanism whenever real implementation lands, with lint, typing, tests and docs exempt. + +**Motivation.** The feature is delivered across many sessions and unreviewed batches are expensive +to unpick. + +--- + +## Compatibility + +No breaking change has landed. Specifically: + +- `ClientBase.subscribe`'s abstract signature changed from `(topic, callback)` to + `(topic_callbacks)` in P0. This is the one signature change in the feature so far; it affects + implementations of the transport-client interface, of which the repo contains two (`NATSClient`, + `DaprClient`), both updated. It must not change again -- a third-party transport would break. +- `EventHandlingBase.subscribe` (abstract) and `POST /nats/subscribe/{topic}` were removed. The + removed endpoint triggered subscription over HTTP, which the managed lifecycle makes meaningless. +- `DaprEventing.subscribe`'s signature changed, but no working caller can exist: the old signature + answered 422 to the only intended caller. Overrides are unaffected, because `_wire_routes` + registers `getattr(self, name)` walking the MRO subclass-first, so an override's own signature is + what FastAPI sees. +- The Dapr subscription document is empty for every project **in this repository**, since + `get_subscribed_topics()` is overridden nowhere here. That is not a guarantee about downstream + projects: the method is a documented override point (`event_handler_base.py:164`, with an example + in its docstring), so a consumer project may well override it. For such a project the discovery fix + changes Dapr behaviour by design -- declared topics went from subscribing to nothing to + subscribing -- and if it *also* declares the same topics as Kubernetes `Subscription` resources, + the sidecar now holds a declarative and a programmatic subscription for one topic. + `dapr_declarative_subscriptions = true` exists for exactly that case, but it defaults to `false`. + Whether Dapr merges the two or delivers twice needs checking against a real sidecar; it belongs on + the broker-test list. +- New config keys all default to current behaviour. +- **`EventHandlingBase._process_cloud_event` takes a third argument, `topic`.** A protected method, + so this affects only a third-party transport implementation that called it -- of which the repo + contains two, both updated. +- **`POST /events/{topic}` answers `200 {"status": "DROP"}` instead of `422` for a body that is not + a CloudEvent -- but only on `DaprEventing`.** Chosen so the two transports dispose of an + unparseable payload identically; NATS already terminated it. A caller that treated 422 from this + path as its error signal sees a 200 instead. The same path on `NatsEventing` is unchanged and + still answers 422, since there the caller is a REST client rather than a sidecar. +- `nats_queue_group` is new and defaults to `app_name`, so no deployment has to set it. It does + change broker-side behaviour for anyone already running more than one replica on Core NATS: + duplicate processing stops, which is the point. A deployment whose correctness depended on every + replica seeing every message would be affected, but that shape cannot be built on this framework + today -- there is no way to opt a subscription out of the queue group. +- **`app_name` values containing whitespace are now rejected at startup.** `nats-py` raises + `BadSubjectError` for a queue name containing a space, so an `app_name` like `"My Agent Service"` + -- legal, and working, before subscriptions carried a queue group -- would have failed inside the + background retry task and retried forever behind a red readiness probe. `_resolve_queue_group` + checks for whitespace and raises at startup naming the key and the value, so the cause is visible. + Affected projects set `nats_queue_group` to a whitespace-free name. This is the one case where a + single-replica deployment that worked before does not start after the upgrade. +- **Single-replica Core NATS behaviour is otherwise unchanged**: a group of one receives everything, + exactly as an ungrouped subscription did. The exception is an agent subscribing to overlapping + subjects (a wildcard plus a literal it covers), where the count of dispatches per message may drop + from two to one -- see the broker-test open point. +- **Dapr is untouched by P1.** The queue group is a NATS concept; `DaprClient` has no equivalent, and + no Dapr code path reads the new key. Delivery under Dapr is unchanged by this change. +- **Dapr is untouched by P3 as well.** Consumer tuning, deliver groups and dead-lettering are + JetStream concepts; under Dapr the sidecar owns retries and its own dead-letter topic, configured + on the Dapr component rather than here. No Dapr code path reads the new keys. +- **Core NATS is untouched by P3.** The new keys are read only when `nats_use_jetstream = true`, and + `_settle` still returns immediately on Core NATS, where there is nothing to acknowledge. +- **A JetStream deployment that already has a durable consumer keeps it, unchanged.** The client + binds to what the broker has and logs the difference. Until that consumer is deleted, the new + `ack_wait`, `max_ack_pending`, `max_deliver` and -- importantly -- the deliver group are not in + force, so such a deployment is still single-subscriber. This is deliberate: recreating a durable + replays or gaps. +- **The JetStream stream may gain subjects on startup.** An existing stream is widened to cover each + subscribed subject and the dead-letter subject. Widening is additive and never removes a subject, + but it is a write against a resource an operator may consider theirs. A stream the application + cannot update is reported as an error naming the missing subjects, and the consumer bind then + fails visibly rather than silently consuming nothing. +- **`nats_durable_name` set together with more than one subscribed topic now fails at startup.** It + could not have worked: a durable filters one subject, so the second consumer would have been + rejected by the broker. The error names both topics. +- **Durable names change for dotted topics** -- `orders.created` now yields `orders_created-durable` + rather than the illegal `orders.created-durable`. No migration is possible or needed, because a + consumer under the old name could never have been created. +- **JetStream now publishes to a second subject.** With dead-lettering enabled, which is the default, + the client publishes to `.dead-letter`. A deployment whose broker permissions allow + publishing only to specific subjects has to grant that one, or set `nats_dead_letter_subject = ""`. + +The spec's one deliberate future break is `with_cache`'s `name` parameter (sec. 10.1), which must +stay keyword-only and last, or an existing `with_cache(False)` would silently become a cache named +`False`. + +--- + +## Open points + +- **P4-P6 remain**, starting with P4 (opt-in idempotency). P0-P3 have all landed. +- **The dead-letter subject has no consumer.** Messages accumulate on it and are subject to the + stream's retention, so a deployment that never reads it will silently lose dead letters when the + stream ages them out. Draining it is an operational task the framework does not do, and no + guidance for it is written yet. +- **Nothing observes dead-lettering.** It is logged, but there is no counter, so "how many messages + did we give up on today" cannot be answered from metrics. It belongs with the telemetry work in + phase 9, next to `blueprint.events.unhandled`. +- **Local NATS and Dapr integration environment.** Everything above is covered by unit tests with + mocked transports. Once the feature is implemented, stand both brokers up locally (compose file + plus a CI job) and cover the behaviour that only a real broker exhibits: queue-group distribution + across replicas, ack/nak/term and redelivery after `ack_wait`, JetStream durable survival across + reconnect, the shutdown drain acknowledging in-flight work, `filter_subjects` behaviour on a + durable that already exists, and the Dapr sidecar actually fetching the discovery document and + delivering to `/events/{topic}`. Depends on the unit/integration split in #80 being settled first, + since `tests/integration/` is currently not run by CI at all. P3 adds several items that only a + real broker can settle: whether `subscribe_bind` against a shared durable actually distributes + across replicas, whether widening a live stream's subjects behaves as expected, what the server + does with an `add_consumer` whose config differs from an existing durable, and whether the + delivery count read from `msg.metadata.num_delivered` lines up with `max_deliver` the way the + dead-letter trigger assumes. Add to that list: **what a queue + group does when one agent's subjects overlap** -- a wildcard plus a literal it covers, both in the + same group, both matching one message. `nats-server` is expected to merge subscriptions by queue + name across matching nodes and deliver once (to either callback, non-deterministically), which + would also end the double dispatch such a pair caused before P1. If it does not merge, the agent + receives the event twice and P2 acks both copies as ordinary work, so the answer changes what P2 + has to handle. +- **The two design questions in spec sec. 13** that change the shape rather than the parameters: 20 + or 100 agents, and whether the 4 GB host budget is real. +- **#80** -- the failing example tests and the unenforced test split. diff --git a/docs/plans/2026-08-28-multi-agent-grouping.md b/docs/plans/2026-08-28-multi-agent-grouping.md index a824d649..f0c04bbf 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping.md +++ b/docs/plans/2026-08-28-multi-agent-grouping.md @@ -2,8 +2,9 @@ | | | |---|---| -| **Status** | not started -- no phase implemented | +| **Status** | P0, P1 and P2 landed on `feature/multi-agent-namespaces`; P3 is next. No phase (0-9) started. | | **Spec (normative)** | `docs/specs/2026-08-28-multi-agent-grouping.md` | +| **What landed, and why** | `docs/plans/2026-08-28-multi-agent-grouping-changelog.md` -- read before resuming | This is the phased work breakdown. The spec is normative: it carries the MUST/SHOULD requirements, the API surface, the config reference and the acceptance criteria, and where the two documents @@ -65,14 +66,25 @@ of this work, ahead of everything else in this list, because the rest of it sits Three gaps to close while landing it, none of which the original PR addressed: -- **No shutdown drain.** `close()` cancels the retry task and unsubscribes under - `contextlib.suppress(Exception)`, so in-flight handlers lose their acknowledgement on every - deploy — duplicates on the next start are certain, not merely possible. Drain in-flight work - before unsubscribing, bounded by a timeout. -- **The `except Exception` swallow in `message_handler` must not survive the port** (see P2). -- **`DaprEventing` registers a callback map with `DaprClient` while delivery still arrives on - `POST /events/{topic}`,** so that callback appears unused for delivery and exists only to drive - readiness. Settle its role or remove it. +- ~~**No shutdown drain.**~~ **Done.** `close()` now drains subscriptions, waits for in-flight + handlers, and only then closes the connection, bounded by `event_client_drain_timeout` + (default 30 s). The order matters: an acknowledgement travels over the delivering connection, so + closing first stranded it and made duplicates certain on every deploy. +- **Partly done: the `except Exception` swallow in `message_handler`.** The boundary now + separates an undecodable payload from a failed dispatch, logs each once with the topic and + event id, and keeps the two failures distinguishable for the dispositions P2 assigns them + (term vs nak). It still *catches* both, because a broker callback must not raise into the + library and because nothing yet decides what to do with a failure. Remaining, and listed + under P2: stop `_process_event` in `io/api/eventing/nats.py` swallowing the classified + handler errors, and stop `_process_cloud_event` logging *and* re-raising them, so the + transport boundary becomes the single place that both sees and handles failure. +- ~~**`DaprEventing` registers a callback map that Dapr delivery does not use.**~~ **Done**, and it + turned out to hide a live bug (issue #81): the discovery endpoint the sidecar fetches took a + required `topic` query parameter, so `GET /dapr/subscribe` answered 422 and no handler + declaration ever reached Dapr. The endpoint now renders `get_subscribed_topics()` as the + sidecar's subscription document, so one declaration drives both transports. The callback map is + kept deliberately — it is what starts the client's sidecar-reachability retry and feeds + `subscriptions_ready`, and removing it would silently disable readiness gating. **P1 — Core NATS subscriptions have no queue group.** `clients/io/nats_client.py:250` calls `client.subscribe(topic, cb=...)` with no `queue=`. JetStream is off by default @@ -121,9 +133,28 @@ Work items: - Configure `max_deliver` and a dead-letter destination (with P3), since nak on an unexpected exception otherwise redelivers forever. -**P3 — Consumer tuning is not configurable.** Expose `ack_wait` (must exceed p99 handler -duration, or long LLM work is redelivered to another replica mid-flight) and `max_ack_pending` -(the real cross-replica concurrency cap). +~~**P3 — Consumer tuning is not configurable.**~~ **Done.** `ack_wait`, `max_ack_pending`, +`max_deliver` and a dead-letter subject are configurable and are set on an explicitly constructed +`ConsumerConfig`, which the client creates through `add_consumer` and binds with `subscribe_bind`. +The two items deferred into P3 landed with it: + +- **`max_deliver` and a dead-letter destination** (from P2). The nak on the last delivery the + broker permits is now rendered as a dead letter plus a term, so a message the framework gives up + on keeps its payload instead of expiring silently out of the consumer. +- **A deliver group on the JetStream durable** (from P1). `nats-py` rejects a queue subscription + whose durable name differs from the queue name, so the queue group could not reach `js.subscribe`; + it is now `deliver_group` on the consumer config, bound with `subscribe_bind`, and JetStream is no + longer single-subscriber. + +Three defects had to be fixed to get there, none of them visible from the P3 description: + +- The stream was created per topic as `f"{topic}.>"`, which does not cover `topic` itself, so an + explicitly created consumer filtering that subject could not be bound at all. Provisioning now + happens once per connect with the union of every subscribed subject plus the dead-letter subject. +- Every `add_stream` call after the first hit "stream name already in use" and was logged as a + warning, so with more than one topic only the first was ever captured by the stream. +- The derived durable name `f"{topic}-durable"` is illegal for any dotted subject -- NATS allows no + `.`, `*`, `>` or whitespace in a consumer name -- which is every idiomatic NATS subject. **P4 — Idempotency, flagged not enforced.** Competing consumers make at-least-once permanent, and ack loss makes duplicate delivery *certain* rather than possible: a handler that finishes 60s of @@ -806,7 +837,7 @@ hidden by API design — so they must be caught mechanically rather than documen | `io/api/eventing/cloud_event_processor_mixin.py` | 5 | | `io/api/eventing/event_handling_base.py` | P2 (ack parity in `handle_event`), 5 | | `clients/client_base.py` | P0 (`subscribe(topic_callbacks)` abstract) | -| `clients/io/nats_client.py` | P0 (managed subscribe, retry, reconnect, drain), P1-P3 (queue group, ack/nak/term, consumer tuning), 5 (durable naming) | +| `clients/io/nats_client.py` | P0 (managed subscribe, retry, reconnect, drain), P1-P3 (queue group, ack/nak/term, consumer tuning, dead letters) -- **done**; 5 (durable naming) | | `clients/io/dapr_client.py` | P0 (same lifecycle, mirrored) | | `io/api/eventing/dapr.py` | P2 (ack parity: `NO_HANDLER_FOUND` → SUCCESS, `CriticalHandlerError` → DROP) | | `handler/event_handler_base.py` | 7 | @@ -819,7 +850,21 @@ hidden by API design — so they must be caught mechanically rather than documen | `config/config.py` | 3 (C5 — `agent_scope` wiring via `with_namespace`), 8 (fragment merge) | | `services/eventing/event_publishing_service.py` | P6 (per-namespace client) | -**Scaffolding changes (`blueprint/agent_generator`)** — none of this exists yet: +**Scaffolding tracks the framework, every step.** `blueprint/agent_generator` is part of this +feature's surface, not a follow-up to it. Any change that adds a config key, alters what a +generated `settings.toml` must contain, changes what `main.py` or the `Dockerfile` looks like, or +changes the meaning of a key a generated project already writes, carries a matching +`agent_generator` change in the same step — templates under `base_files/`, the CLI commands, and +the generated `claude_docs/CLAUDE.md`. A generated project that no longer matches the framework it +generates against is a defect, and it is invisible from the framework's own tests. + +Known outstanding item from P1: `app_name` now determines the NATS queue group, so it is broker +consumer identity rather than a display name. The generator writes it (`settings_part_generator.py`) +and documents it (`claude_docs/CLAUDE.md`), and neither says so; `nats_queue_group` appears in +neither. The fallback literal `"generated-agent"` in `cli/commands/create.py` is also now a +collision source between projects that hit it. + +**Scaffolding changes (`blueprint/agent_generator`)** -- none of this exists yet: | Piece | Change | |---|---| @@ -964,6 +1009,25 @@ open question. - An earlier implementation of P0 exists on `feature/event_handler_retries`. Reconciling it with what lands here is its author's call, and deliberately out of scope for this plan. +**Test environment** +- **Local NATS and Dapr, exercised as real integration tests.** Every prerequisite and phase here is + covered by unit tests against mocked transports, which cannot show queue-group distribution, + redelivery after `ack_wait`, durable survival across a reconnect, or a sidecar fetching the + subscription document. Once the feature is implemented, stand both brokers up locally (a compose + file plus a CI job) and cover what only a real broker exhibits: + - queue-group distribution: N replicas, each event handled once (P1); + - ack, nak and term, and that a handled message is not redelivered (P2); + - `ack_wait` expiry redelivering to another replica mid-handler (P3); + - JetStream durables surviving a reconnect, and the ack-retry-on-reconnect spike (P0, P2); + - `close()` acknowledging in-flight work before exit (P0); + - `filter_subjects` applied to a durable that already exists — in place, or delete-and-recreate, + which is the migration question spec sec. 7.7 raises; + - the Dapr sidecar fetching `GET /dapr/subscribe` and delivering to `POST /events/{topic}`, + including the SUCCESS/RETRY/DROP mapping. + + Blocked on the unit/integration split in #80: `tests/integration/` is not run by CI at all today, + so integration tests added now would be invisible. + **Engineering spikes** - **Ack-retry-on-reconnect.** Belongs in P0's `_on_reconnected`. Capture the acknowledgement reply subject and re-send after a reconnect, narrowing the duplicate window from "certain on any connection blip" to "only if the diff --git a/docs/reference/configuration-keys.md b/docs/reference/configuration-keys.md index 42737664..a38a36bb 100644 --- a/docs/reference/configuration-keys.md +++ b/docs/reference/configuration-keys.md @@ -28,6 +28,19 @@ 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"`. | +| `dapr_pubsub_name` | `str` | `"pubsub"` | Dapr pub/sub component name, used when publishing and in the subscription document served at `GET /dapr/subscribe`. Only used when `event_bus = "dapr"`. | +| `dapr_declarative_subscriptions` | `bool` | `false` | Set `true` when Dapr subscriptions are declared outside the application (Kubernetes `Subscription` resources or YAML). The discovery endpoint then serves an empty document, so the sidecar cannot subscribe twice. | +| `nats_queue_group` | `str` | value of `app_name` | Queue group joined by every NATS subscription, so exactly one replica processes any given message. Identifies the agent, not the process: it must not contain a pod, container or replica name, or moving the agent between deployments would change which consumer it is. Startup fails if neither this key nor `app_name` yields a name. 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. | +| `event_client_drain_timeout` | `float` | `30.0` | Seconds allowed at shutdown for in-flight message handlers to finish before the broker connection is closed. Bounds the whole shutdown sequence, so keep it below the pod's termination grace period. | +| `nats_use_jetstream` | `bool` | `false` | Consume through a durable JetStream consumer instead of Core NATS. The keys below apply only when this is `true`. | +| `nats_stream_name` | `str` | `"EVENTS"` | Stream the durable consumers are created on. The framework creates it if it is missing, and widens an existing one to cover every subscribed subject plus the dead-letter subject; it never removes a subject. | +| `nats_durable_name` | `str` | `"-durable"` | Name of the durable consumer. Derived from the topic by default, with `.`, `*`, `>` and whitespace replaced by `_` because NATS rejects them in a consumer name. Setting it explicitly is only valid with a single subscribed topic: a durable filters one subject. | +| `nats_ack_wait` | `float` | `300.0` | Seconds the broker waits for an acknowledgement before redelivering. **Must exceed the p99 duration of your slowest handler**, or long inference is redelivered to another replica while the first is still working. The default is deliberately far above the NATS default of 30 s because handlers in this framework call models. | +| `nats_max_ack_pending` | `int` | `16` | Unacknowledged messages the consumer may have outstanding at once, counted across every replica sharing it. `-1` is unlimited. Keep it close to the number of replicas: a push subscription runs its callbacks one at a time, so anything much larger queues messages inside the client while their `nats_ack_wait` is already running down. | +| `nats_max_deliver` | `int` | `5` | Delivery attempts before the message is dead-lettered. `-1` is unlimited, which means a permanently failing message is retried forever and never dead-lettered; the client logs a warning at startup if you set it. | +| `nats_dead_letter_subject` | `str` | `".dead-letter"` | Subject a message is republished to when the framework gives up on it -- either a terminal failure (`InvalidEventError`, `CriticalHandlerError`, or a payload that is not a CloudEvent) or `nats_max_deliver` attempts spent. The original bytes are republished unchanged, with `Blueprint-Dead-Letter-Reason`, `Blueprint-Original-Subject`, `Blueprint-Delivery-Count` and `Blueprint-Event-Id` headers. Set to `""` to disable, which drops those messages and loses their payloads. Startup fails if the subject is a wildcard or is itself one of the subscribed subjects, since that would loop. | --- @@ -126,6 +139,18 @@ log_format = "text" # Event Bus event_bus = "nats" nats_url = "nats://localhost:4222" +# nats_queue_group = "my_agent_service" # defaults to app_name +event_client_max_retries = -1 # retry indefinitely +event_client_retry_delay = 5.0 # seconds between attempts +event_client_drain_timeout = 30.0 # shutdown budget for in-flight handlers + +# JetStream consumer (only when nats_use_jetstream = true) +nats_use_jetstream = false +nats_stream_name = "EVENTS" +nats_ack_wait = 300.0 # must exceed the p99 handler duration +nats_max_ack_pending = 16 # outstanding messages across all replicas +nats_max_deliver = 5 # attempts before the message is dead-lettered +# nats_dead_letter_subject = "my_agent_service.dead-letter" # defaults to .dead-letter # Prompts prompt_directory = "prompts" diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md index ef26ef3c..100cc4da 100644 --- a/docs/specs/2026-08-28-multi-agent-grouping.md +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -259,8 +259,10 @@ changing them triggers a rolling update on their own. | `readiness_policy` | `"all"` | See C3. | | `executor_workers` | `os.cpu_count() + 4` | Per-namespace thread pool size. Bounded per #36. | | `nats_queue_group` | `app_name` | Queue group for the root namespace only. | -| `nats_ack_wait` | -- | **MUST** exceed p99 handler duration. See sec. 7.3. | -| `nats_max_ack_pending` | -- | Per-consumer, shared across replicas. | +| `nats_ack_wait` | `300.0` | Seconds. **MUST** exceed p99 handler duration. See sec. 7.3. | +| `nats_max_ack_pending` | `16` | Per-consumer, shared across replicas. `-1` unlimited. A push subscription dispatches its callbacks serially, so a value far above the replica count queues messages client-side while their `ack_wait` runs. | +| `nats_max_deliver` | `5` | Attempts before the message is dead-lettered. `-1` unlimited, and then nothing is ever dead-lettered. | +| `nats_dead_letter_subject` | `.dead-letter` | Where a message the framework gives up on is republished. Derived from the agent's identity, as the queue group is (C1). `""` disables it and loses those payloads. **MUST NOT** be a wildcard or a subject the same namespace consumes. | | `idempotency_enabled` | `false` | Opt-in dedup. See sec. 7.4. | | `idempotency_ttl` | -- | Dedup window. | | `scheduler_mode` | `"event"` | `"event"` or `"in_process"`. See sec. 7.5. | @@ -373,10 +375,16 @@ to do, and redelivery cannot make a handler appear: a nak is a pointless loop un and under a queue group a loop that visits every replica in turn. `dapr.py:75` returns `RETRY` for this case today and **MUST** change. -Acknowledging it **MUST NOT** make it invisible. A subscribed topic with no matching handler is -usually a declaration error, and the acknowledgement is what would otherwise hide it forever. The -framework **MUST** count unhandled events per namespace and topic, and **MUST** log at WARNING the -first time a given (namespace, topic) pair produces one. +**An unmatched event is normal, and the framework MUST treat it as normal.** Deciding there is +nothing to do is the handler's job and an ordinary outcome of doing it: an agent reads an event, +finds no work in it for whatever domain reason, and says so. Why is the agent's business and not +the framework's. The framework therefore **MUST NOT** log it at WARNING or otherwise present it as +a fault, and **MUST NOT** accumulate per-topic state about it -- under Dapr the topic arrives from a +URL path, so remembering each distinct value lets a caller grow the process's memory. + +It **MUST** be counted per namespace and topic, for one purpose: the *proportion* of received +events a namespace declines is how a too-broad subscription shows up (sec. 7.7). A high count is a +question about the subject filter, not about the handler. **Both transports MUST map the same outcome to the same disposition.** Dapr's response dict *is* its acknowledgement, so the table above is normative for `dapr.py` and @@ -387,6 +395,13 @@ places today: `NO_HANDLER_FOUND` as above, and `CriticalHandlerError`, which `da `max_deliver` and a dead-letter destination **MUST** be configured, because nak on an unexpected exception otherwise redelivers indefinitely. +The nak on the last delivery `max_deliver` permits **MUST** be rendered as a dead letter followed +by a term, not as a nak. The broker will not redeliver it, so a nak there differs from a term only +in that the message leaves the consumer without a trace of why, and one `ack_wait` later than it +had to. A dead letter **MUST** carry the original payload bytes unchanged -- a payload that failed +to parse is the one most worth keeping -- with the reason, origin subject, delivery count and event +id in headers rather than in the body. + Implementations **SHOULD** capture the ack reply subject and retry the ack after a reconnect, which narrows the duplicate window from "certain on any blip" to "only if the pod also dies". Two caveats make this a prototype rather than a design commitment: a redelivery may already be in @@ -512,8 +527,10 @@ replay or a gap is expected. This binds the durable renaming that C1 requires filter derivation: on first deploy, every pre-existing consumer becomes a new consumer. **Fan-out MUST be observable.** The framework **MUST** expose, per subject, how many namespaces -select it. With the unhandled-event counter of sec. 7.2 this covers both directions of the same -error: an event nobody wanted, and an event offered to far too many. +select it. Together with the unhandled-event counter of sec. 7.2 this covers both directions of a +subscription that is shaped wrongly: a subject delivered to namespaces that find no work in it, and +a subject copied to far more namespaces than need it. Neither counter reports a fault on its own -- +they are read as ratios against the volume a namespace receives. Build-time gates on subject breadth belong to the implementation plan rather than here, because they constrain projects rather than the framework. They **SHOULD** ship as warnings before they @@ -689,8 +706,8 @@ Two things an author still needs to know: their agent's name, and that handlers namespace receives (sec. 7.7). - [ ] A namespace's derived `filter_subjects` is never narrower than its declared topics unioned with `nats_subscriptions` (sec. 7.7). -- [ ] Unhandled events per (namespace, topic) and namespaces-per-subject fan-out are both exposed - (sec. 7.2, sec. 7.7). +- [ ] Unhandled events per (namespace, topic) and namespaces-per-subject fan-out are both exposed, + neither reported as a fault and neither keeping per-topic state (sec. 7.2, sec. 7.7). - [ ] Frozen compat suite and generated-project smoke test both green (sec. 10.2). - [ ] Idempotency off by default, with the requirement surfaced at scaffold time and in `asbs validate`. diff --git a/src/blueprint/agents/clients/ai/openai_client.py b/src/blueprint/agents/clients/ai/openai_client.py index ce124c3d..944f197c 100644 --- a/src/blueprint/agents/clients/ai/openai_client.py +++ b/src/blueprint/agents/clients/ai/openai_client.py @@ -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: diff --git a/src/blueprint/agents/clients/ai/vllm_client.py b/src/blueprint/agents/clients/ai/vllm_client.py index 5048648e..ce8d5d5a 100644 --- a/src/blueprint/agents/clients/ai/vllm_client.py +++ b/src/blueprint/agents/clients/ai/vllm_client.py @@ -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: diff --git a/src/blueprint/agents/clients/client_base.py b/src/blueprint/agents/clients/client_base.py index c6507dda..6b2720ff 100644 --- a/src/blueprint/agents/clients/client_base.py +++ b/src/blueprint/agents/clients/client_base.py @@ -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 diff --git a/src/blueprint/agents/clients/io/dapr_client.py b/src/blueprint/agents/clients/io/dapr_client.py index 5ae75c69..1ee16dc4 100644 --- a/src/blueprint/agents/clients/io/dapr_client.py +++ b/src/blueprint/agents/clients/io/dapr_client.py @@ -1,5 +1,7 @@ """Dapr client implementation for eventing.""" +import asyncio +import contextlib import json import logging from collections.abc import Awaitable, Callable @@ -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 @@ -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, @@ -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 @@ -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() diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 0c15680c..d104c910 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -1,23 +1,103 @@ """NATS client implementation for eventing.""" +import asyncio +import contextlib import json import logging -from typing import Any +import re from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from typing import Any import nats from nats.aio.client import Client as NatsClient +from nats.js import api as js_api from nats.js.client import JetStreamContext +from nats.js.errors import NotFoundError from ...models.api import ComponentHealth +from ...models.errors import DeliveryDisposition, disposition_for from ...models.events import CloudEvent from .io_client_base import IOClientBase logger = logging.getLogger(__name__) +@dataclass(frozen=True) +class ConsumerTuning: + """JetStream consumer settings, resolved once from config (spec sec. 7.3). + + Held as one object because the four values only make sense together: ``ack_wait`` + decides when an unacknowledged message comes back, ``max_ack_pending`` decides how + many can be waiting at once, ``max_deliver`` decides how often it comes back before + the framework gives up, and ``dead_letter_subject`` decides where it goes when that + happens. + """ + + ack_wait: float + max_ack_pending: int + max_deliver: int + dead_letter_subject: str + + class NATSClient(IOClientBase): - """NATS client for subscribing to and publishing CloudEvents.""" + """NATS client for subscribing to and publishing CloudEvents. + + Managed subscription lifecycle + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + Call ``subscribe(topic_callbacks)`` once at startup with the full + ``{topic: callback}`` mapping. The client fires a background retry + task that connects to the broker and subscribes to every topic. + ``subscriptions_ready`` becomes ``True`` once all subscriptions are + active; ``health_check()`` reflects this state so the readiness probe + keeps the pod out of service rotation until then. + + On disconnect the NATS library fires ``_on_disconnected``, which clears + the ready flag. On reconnect ``_on_reconnected`` re-subscribes (JetStream + only — Core NATS re-subscribes automatically) and restores the flag. + + Queue group + ~~~~~~~~~~~ + Every Core NATS subscription joins a queue group, so exactly one replica + receives any given message. The name is resolved once in ``subscribe()`` + and is a pure function of the agent's own identity -- never of the pod, + container or replica it happens to run in. + + One name covers every topic because a group is keyed by *(subject, queue + name)*: subscriptions sharing this name on different subjects are separate + groups, so unrelated event types never compete for the same delivery. The + exception is a subject overlapping another of this client's own subjects + (a wildcard plus a literal it covers), where one message matches two of its + subscriptions -- the server is expected to merge them into one group and + deliver once, to either callback. Unverified against a real broker; see the + feature changelog's broker-test open point. + + JetStream consumer + ~~~~~~~~~~~~~~~~~~ + Under JetStream the durable consumer is created explicitly rather than left to + ``js.subscribe``, because every setting that makes a consumer safe to share lives on + ``ConsumerConfig``: the deliver group that stops each replica seeing every message, + the ``ack_wait`` that must outlast a slow handler, the ``max_ack_pending`` window and + the ``max_deliver`` limit after which a message is dead-lettered rather than dropped. + An existing consumer is never rewritten -- a durable's filter and deliver group are + broker-side state, and recreating one either replays or gaps. + + 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. + ``event_client_drain_timeout`` (float, default 30.0): seconds allowed for in-flight + handlers to finish during shutdown. + ``nats_ack_wait`` (float, default 300.0): seconds the broker waits for an + acknowledgement before redelivering. Must exceed p99 handler duration. + ``nats_max_ack_pending`` (int, default 16): unacknowledged messages allowed at once + across every replica sharing the consumer; ``-1`` = unlimited. + ``nats_max_deliver`` (int, default 5): delivery attempts before a message is + dead-lettered; ``-1`` = unlimited, which disables dead-lettering on exhaustion. + ``nats_dead_letter_subject`` (str, default ``".dead-letter"``): where a + message goes when the framework gives up on it; ``""`` disables it and loses the payload. + """ def __init__(self) -> None: super().__init__() @@ -25,12 +105,253 @@ def __init__(self) -> None: self._js: JetStreamContext | None = None self._use_jetstream: bool = False self._subscriptions: list[Any] = [] + self._topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = {} + self._queue_group: str = "" + self._tuning: ConsumerTuning | None = None + self._durables: dict[str, str] = {} + self._subscriptions_ready: bool = False + self._subscriptions_managed: bool = False + self._retry_task: asyncio.Task[None] | None = None + self._inflight: int = 0 + self._idle: asyncio.Event = asyncio.Event() + self._idle.set() + + # ------------------------------------------------------------------ + # Public state + # ------------------------------------------------------------------ + + @property + def subscriptions_ready(self) -> bool: + """``True`` once all managed subscriptions are active.""" + return self._subscriptions_ready + + @property + def queue_group(self) -> str: + """Queue group joined by this client's subscriptions; ``""`` before ``subscribe()``.""" + return self._queue_group + + @property + def inflight_handlers(self) -> int: + """Number of message handlers currently executing.""" + return self._inflight + + @property + def consumer_tuning(self) -> ConsumerTuning | None: + """JetStream consumer settings resolved by ``subscribe()``; ``None`` on Core NATS.""" + return self._tuning + + # ------------------------------------------------------------------ + # Managed subscription API + # ------------------------------------------------------------------ + + async def subscribe(self, topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]]) -> None: + """Register all topic→callback mappings and start the background retry task. + + Returns immediately; connection and subscription happen in the background. + """ + self._topic_callbacks = topic_callbacks + self._queue_group = self._resolve_queue_group() + if self.config.get("nats_use_jetstream", False): + self._durables = self._resolve_durables(list(topic_callbacks)) + self._tuning = self._resolve_consumer_tuning(list(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) + + def _resolve_queue_group(self) -> str: + """Return the queue group name, or raise if none can be derived. + + The name identifies the *agent*, not the process that hosts it: moving an agent + into a different deployment group must not change which broker-side consumer it + is (spec C1). Today every component lives in the root namespace, so the name comes + from ``nats_queue_group`` and falls back to ``app_name``. + + Resolved here rather than at subscription time so that a misconfiguration fails + the caller's startup instead of disappearing into the background retry loop, which + would retry a config error forever. + + Raises: + ValueError: if neither key yields a non-empty name. NATS reads ``queue=""`` as + "no queue group", which is precisely the every-replica-processes-every-message + fan-out this exists to prevent, so there is no usable fallback. + ValueError: if the name contains whitespace. ``nats-py`` rejects such a queue + name with ``BadSubjectError``, and an ``app_name`` like ``"My Service"`` was + perfectly legal before subscriptions carried a queue group. Reported here, + naming the key and the value, rather than left to surface as a repeating + ``BadSubjectError`` inside the background retry task. + """ + for key in ("nats_queue_group", "app_name"): + name = str(self.config.get(key, "") or "").strip() + if not name: + continue + if any(char.isspace() for char in name): + raise ValueError( + f"Queue group name '{name}' (from '{key}') contains whitespace, which NATS does not accept. " + "Set 'nats_queue_group' to a name without whitespace." + ) + return name + raise ValueError( + "NATS subscriptions require a queue group: set 'nats_queue_group' or 'app_name'. " + "Without one every replica processes every message." + ) + + # ------------------------------------------------------------------ + # Consumer settings (P3) + # ------------------------------------------------------------------ + + def _resolve_consumer_tuning(self, topics: list[str]) -> ConsumerTuning: + """Read and validate the JetStream consumer settings (spec sec. 7.3). + + Resolved in ``subscribe()`` for the same reason the queue group is: a bad value + must fail the caller's startup rather than disappear into the background retry + task, which would retry a config error forever. + + Raises: + ValueError: if a value is not a number, is zero, or is a negative value other + than ``-1``. + """ + ack_wait = self._read_float("nats_ack_wait", 300.0) + if ack_wait <= 0: + raise ValueError(f"'nats_ack_wait' must be greater than 0, got {ack_wait}. It is the redelivery timeout, in seconds.") + + max_ack_pending = self._read_int("nats_max_ack_pending", 16) + if max_ack_pending == 0 or max_ack_pending < -1: + raise ValueError(f"'nats_max_ack_pending' must be a positive count or -1 for unlimited, got {max_ack_pending}.") + + max_deliver = self._read_int("nats_max_deliver", 5) + if max_deliver == 0 or max_deliver < -1: + raise ValueError(f"'nats_max_deliver' must be a positive count or -1 for unlimited, got {max_deliver}.") + if max_deliver == -1: + logger.warning( + "'nats_max_deliver' is -1, so a message that keeps failing is redelivered forever " + "and never reaches the dead-letter subject. Set a positive limit to bound it." + ) + + return ConsumerTuning( + ack_wait=ack_wait, + max_ack_pending=max_ack_pending, + max_deliver=max_deliver, + dead_letter_subject=self._resolve_dead_letter_subject(topics), + ) + + def _resolve_dead_letter_subject(self, topics: list[str]) -> str: + """Return the subject a given-up-on message is republished to, or ``""`` if disabled. + + Defaults to ``".dead-letter"``, so it is derived from the agent's own + identity exactly as the queue group is (C1) and moving the agent between deployment + groups does not move its dead letters. + + Raises: + ValueError: if the subject contains whitespace or a wildcard -- it is published + to, and neither is publishable. + ValueError: if one of this client's own subscriptions would deliver it back. + Dead-lettering onto a subject the same client consumes turns one failure + into an unbounded loop, and the loop only appears under load. + """ + configured = self.config.get("nats_dead_letter_subject", None) + subject = f"{self._queue_group}.dead-letter" if configured is None else str(configured).strip() + if not subject: + return "" + + if any(char.isspace() for char in subject) or "*" in subject or ">" in subject: + raise ValueError( + f"Dead-letter subject '{subject}' contains whitespace or a wildcard. " + "It is a subject the client publishes to, so it must name exactly one." + ) + for topic in topics: + if self._subject_matches(topic, subject): + raise ValueError( + f"Dead-letter subject '{subject}' is delivered by this client's own subscription " + f"to '{topic}', so a dead-lettered message would come straight back and be " + "dead-lettered again. Set 'nats_dead_letter_subject' outside the subscribed subjects." + ) + return subject + + def _resolve_durables(self, topics: list[str]) -> dict[str, str]: + """Map every topic to the durable consumer name that will carry it. + + A durable belongs to one filter subject, so each topic needs its own name and no + two topics may resolve to the same one. Both failure modes are config errors and + are raised here rather than left to surface as a JetStream API error inside the + retry loop. + + Raises: + ValueError: if ``nats_durable_name`` is set while more than one topic is + subscribed, or if two topics sanitise to the same durable name. + """ + configured = str(self.config.get("nats_durable_name", "") or "").strip() + if configured and len(topics) > 1: + raise ValueError( + f"'nats_durable_name' is set to '{configured}' but {len(topics)} topics are subscribed. " + "A JetStream durable filters one subject, so one name cannot serve them all. " + "Remove the key to derive a durable per topic." + ) + + durables: dict[str, str] = {} + for topic in topics: + name = configured or self._durable_for(topic) + clash = next((other for other, existing in durables.items() if existing == name), None) + if clash is not None: + raise ValueError( + f"Topics '{clash}' and '{topic}' both resolve to durable name '{name}'. " + "NATS allows no '.', '*', '>' or whitespace in a consumer name, so those " + "characters are replaced with '_'. Rename one of the topics." + ) + durables[topic] = name + return durables + + @staticmethod + def _durable_for(topic: str) -> str: + """Derive a legal durable consumer name from a subject. + + NATS rejects ``.``, ``*``, ``>`` and whitespace in a consumer name, so the dotted + subjects that are idiomatic in NATS -- ``orders.created`` -- cannot serve as one + directly. + """ + return f"{re.sub(r'[.*>\s]', '_', topic)}-durable" + + @staticmethod + def _subject_matches(pattern: str, subject: str) -> bool: + """Return whether a NATS subject filter would deliver a given subject. + + ``*`` matches exactly one token, ``>`` matches one or more and only as the final + token. Used to prove the dead-letter subject is outside what this client consumes. + """ + pattern_tokens = pattern.split(".") + subject_tokens = subject.split(".") + for index, token in enumerate(pattern_tokens): + if token == ">": + return index < len(subject_tokens) + if index >= len(subject_tokens): + return False + if token != "*" and token != subject_tokens[index]: + return False + return len(pattern_tokens) == len(subject_tokens) + + def _read_float(self, key: str, default: float) -> float: + raw = self.config.get(key, default) + try: + return float(raw) + except (TypeError, ValueError) as exc: + raise ValueError(f"Config key '{key}' must be a number, got {raw!r}.") from exc + + def _read_int(self, key: str, default: int) -> int: + raw = self.config.get(key, default) + try: + return int(raw) + except (TypeError, ValueError) as exc: + raise ValueError(f"Config key '{key}' must be an integer, got {raw!r}.") from exc + + # ------------------------------------------------------------------ + # Connection + # ------------------------------------------------------------------ def _is_connected(self) -> bool: return self._nats_client is not None and not self._nats_client.is_closed and self._nats_client.is_connected async def connect(self) -> None: - """Connect to NATS server.""" + """Connect to the NATS server, registering disconnect/reconnect callbacks.""" if self._nats_client is not None and not self._nats_client.is_closed: return @@ -41,6 +362,8 @@ async def connect(self) -> None: max_reconnect_attempts=self.config.get("nats_max_reconnect_attempts", 5), reconnect_time_wait=self.config.get("nats_reconnect_time_wait", 2), connect_timeout=10, + disconnected_cb=self._on_disconnected, + reconnected_cb=self._on_reconnected, ) self._client = self._nats_client self._use_jetstream = self.config.get("nats_use_jetstream", False) @@ -59,56 +382,103 @@ async def connect(self) -> None: raise async def close(self) -> None: - """Close NATS connection and clean up resources.""" + """Stop consuming, let in-flight handlers finish, then close the connection. + + The order is load-bearing. An acknowledgement travels over the same connection + that delivered the message, so closing the connection while a handler is still + running strands that acknowledgement and guarantees redelivery. Subscriptions + are drained first, in-flight handlers then get until ``event_client_drain_timeout`` + to finish, and only then is the connection closed. The timeout bounds the whole + sequence, so shutdown stays inside a pod's termination grace period. + """ + self._subscriptions_ready = False + + 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._nats_client is not None: - for sub in self._subscriptions: - await sub.unsubscribe() - self._subscriptions.clear() + timeout = float(self.config.get("event_client_drain_timeout", 30.0)) + deadline = asyncio.get_running_loop().time() + timeout + await self._drain_subscriptions(deadline) + await self._await_inflight(deadline) await self._nats_client.close() self._nats_client = None self._js = None self._client = None - async def subscribe(self, topic: str, callback: Callable[[CloudEvent[Any]], Awaitable[None]]) -> None: - """Subscribe to a topic and call callback with parsed CloudEvents.""" - client = await self.client + # ------------------------------------------------------------------ + # Internal -- shutdown + # ------------------------------------------------------------------ - async def message_handler(msg: Any) -> None: + async def _drain_subscriptions(self, deadline: float) -> None: + """Stop new deliveries while letting already-queued messages reach their handler. + + Falls back to an immediate unsubscribe if a drain fails or outlives the deadline, + so one stuck subscription cannot hold up shutdown. + """ + for sub in self._subscriptions: + remaining = max(0.0, deadline - asyncio.get_running_loop().time()) try: - event_data = json.loads(msg.data.decode()) - cloud_event: CloudEvent[Any] = CloudEvent(**event_data) - await callback(cloud_event) - except Exception as ex: - logger.error("Failed to handle NATS message: %s", str(ex)) + await asyncio.wait_for(sub.drain(), timeout=remaining) + except TimeoutError: + logger.warning("Draining a NATS subscription outlived the shutdown deadline; unsubscribing instead") + await self._force_unsubscribe(sub) + except Exception as e: + logger.warning("Failed to drain a NATS subscription (%s); unsubscribing instead", e) + await self._force_unsubscribe(sub) + self._subscriptions.clear() + + @staticmethod + def _decode_message(msg: Any, topic: str) -> CloudEvent[Any] | None: + """Decode a broker message into a CloudEvent, or ``None`` if the payload is unusable. + Kept separate from dispatch because the two failures have opposite dispositions. A + payload that cannot become a CloudEvent will not become one on redelivery either, so + it is terminal for that message rather than retryable: P2 terms here, and naks a + dispatch failure (spec sec. 7.2). + """ try: - if self._use_jetstream and client.jetstream(): - stream_name = self.config.get("nats_stream_name", "EVENTS") - durable_name = self.config.get("nats_durable_name", f"{topic}-durable") + event_data = json.loads(msg.data.decode()) + return CloudEvent(**event_data) + except Exception as ex: + logger.error("Discarding unparseable message on topic '%s': %s", topic, ex) + return None - try: - await client.jetstream().add_stream(name=stream_name, subjects=[f"{topic}.>"]) - except Exception as e: - if "stream name already in use" not in str(e).lower(): - logger.warning("Could not create stream: %s", str(e)) + @staticmethod + async def _force_unsubscribe(sub: Any) -> None: + with contextlib.suppress(Exception): + await sub.unsubscribe() - sub = await client.jetstream().subscribe( - topic, - durable=durable_name, - manual_ack=True, - cb=message_handler, - ) - logger.info("Subscribed to JetStream topic '%s'", topic) - else: - sub = await client.subscribe(topic, cb=message_handler) - logger.info("Subscribed to Core NATS topic '%s'", topic) + async def _await_inflight(self, deadline: float) -> None: + """Give handlers that are still running a bounded chance to finish.""" + if self._inflight == 0: + return - self._subscriptions.append(sub) + remaining = max(0.0, deadline - asyncio.get_running_loop().time()) + logger.debug("Waiting up to %.1fs for %d in-flight NATS handler(s)", remaining, self._inflight) + try: + await asyncio.wait_for(self._idle.wait(), timeout=remaining) + except TimeoutError: + logger.error( + "Shutdown deadline reached with %d NATS handler(s) still running; their messages will be redelivered", + self._inflight, + ) - except Exception as e: - logger.error("Failed to subscribe to topic '%s': %s", topic, str(e)) - raise + def _enter_handler(self) -> None: + self._inflight += 1 + self._idle.clear() + + def _exit_handler(self) -> None: + self._inflight = max(0, self._inflight - 1) + if self._inflight == 0: + self._idle.set() + + # ------------------------------------------------------------------ + # Publish + # ------------------------------------------------------------------ async def publish(self, topic: str, event: CloudEvent[Any], routing_key: str | None = None) -> None: """Publish a CloudEvent to a topic. @@ -116,7 +486,7 @@ async def publish(self, topic: str, event: CloudEvent[Any], routing_key: str | N Args: topic: The topic, used for event routing. event: The CloudEvent to publish. - routing_key: Ignored — NATS does not use routing keys + routing_key: Ignored — NATS does not use routing keys. """ client = await self.client @@ -134,10 +504,419 @@ async def publish(self, topic: str, event: CloudEvent[Any], routing_key: str | N logger.error("Failed to publish event to topic '%s': %s", topic, str(e)) raise + # ------------------------------------------------------------------ + # Health + # ------------------------------------------------------------------ + async def health_check(self) -> ComponentHealth: - """Check the health of the NATS connection.""" - if self._nats_client and not self._nats_client.is_closed and self._nats_client.is_connected: - server_info = self._nats_client.connected_url - return ComponentHealth(status="healthy", message=f"Connected to NATS server at {server_info}") - else: + """Return healthy only when connected and all managed subscriptions are active.""" + if not self._is_connected(): return ComponentHealth(status="unhealthy", message="NATS client not connected") + if self._subscriptions_managed and not self._subscriptions_ready: + return ComponentHealth(status="unhealthy", message="connected but subscriptions not yet established") + server_info = self._nats_client.connected_url # type: ignore[union-attr] + sub_info = f" ({len(self._subscriptions)} subscriptions active)" if self._subscriptions else "" + return ComponentHealth(status="healthy", message=f"Connected to NATS server at {server_info}{sub_info}") + + # ------------------------------------------------------------------ + # 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("NATSClient connected and subscribed successfully") + return + except Exception as e: + attempt += 1 + self._subscriptions_ready = False + if max_retries != -1 and attempt > max_retries: + raise + logger.warning("NATSClient 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("NATSClient permanently failed to connect after exhausting retries: %s", exc, exc_info=exc) + + async def _connect_and_subscribe(self) -> None: + await self.connect() + # Clean up any partial subscriptions from a previous failed attempt + for sub in self._subscriptions: + with contextlib.suppress(Exception): + await sub.unsubscribe() + self._subscriptions.clear() + await self._subscribe_all() + + async def _subscribe_all(self) -> None: + """Provision the stream once, then subscribe every topic. + + Shared by first connect and by reconnect, so a stream that was recreated while the + client was away -- or a failover to a cluster peer that never had it -- is restored + before any consumer tries to bind to it. + """ + if self._use_jetstream: + await self._provision_stream() + for topic, callback in self._topic_callbacks.items(): + await self._subscribe_one(topic, callback) + + # ------------------------------------------------------------------ + # Internal -- JetStream stream and consumer + # ------------------------------------------------------------------ + + def _stream_subjects(self) -> set[str]: + """Subjects the stream must carry for this client's consumers to bind. + + Each topic is included literally, because that is what a consumer filters on. The + previous code stored only ``f"{topic}.>"``, which does *not* cover ``topic`` itself, + so an explicitly created consumer filtering ``orders.created`` would be rejected by + a stream that only captured ``orders.created.>``. The wildcard form is kept as well, + so a stream provisioned by an earlier version keeps every subject it already had. + """ + subjects: set[str] = set() + for topic in self._topic_callbacks: + subjects.add(topic) + if "*" not in topic and ">" not in topic: + subjects.add(f"{topic}.>") + if self._tuning and self._tuning.dead_letter_subject: + subjects.add(self._tuning.dead_letter_subject) + return subjects + + async def _provision_stream(self) -> None: + """Create the stream, or widen an existing one to cover every needed subject. + + Called once per (re)connect rather than once per topic. The previous per-topic + ``add_stream`` could only ever create the stream for whichever topic happened to be + subscribed first: every later call hit "stream name already in use" and was logged + as a warning, leaving the remaining topics uncaptured. + + Widening is additive -- subjects already on the stream are kept -- so this never + removes a subject an operator added. A failure to update is logged rather than + raised: the consumer that needs the subject fails immediately afterwards, and that + failure names the consumer as well as the stream. + """ + js = self._nats_client.jetstream() # type: ignore[union-attr] + stream = self.config.get("nats_stream_name", "EVENTS") + wanted = self._stream_subjects() + + try: + info = await js.stream_info(stream) + except NotFoundError: + await js.add_stream(name=stream, subjects=sorted(wanted)) + logger.info("Created JetStream stream '%s' with subjects %s", stream, sorted(wanted)) + return + + existing = set(info.config.subjects or []) + missing = wanted - existing + if not missing: + return + + info.config.subjects = sorted(existing | missing) + try: + await js.update_stream(info.config) + logger.info("Added subject(s) %s to existing JetStream stream '%s'", sorted(missing), stream) + except Exception as exc: + logger.error( + "JetStream stream '%s' does not carry subject(s) %s and could not be updated (%s); " + "consumers filtering those subjects will fail to bind", + stream, + sorted(missing), + exc, + ) + + def _consumer_config(self, topic: str, durable: str) -> js_api.ConsumerConfig: + """Build the durable consumer this client wants for one topic. + + ``deliver_subject`` is derived from the durable name rather than taken from a fresh + inbox, because every replica must bind to the *same* one: a push consumer delivers + to one subject, and its deliver group is the queue group on that subject. Two + replicas generating random inboxes would create two different consumers, which is + the fan-out P1 removed. + """ + tuning = self._tuning or self._resolve_consumer_tuning(list(self._topic_callbacks)) + return js_api.ConsumerConfig( + durable_name=durable, + filter_subject=topic, + deliver_subject=f"_DELIVER.{durable}", + deliver_group=self._queue_group or None, + ack_policy=js_api.AckPolicy.EXPLICIT, + ack_wait=tuning.ack_wait, + max_ack_pending=tuning.max_ack_pending, + max_deliver=tuning.max_deliver, + ) + + async def _ensure_consumer(self, topic: str, durable: str) -> js_api.ConsumerConfig: + """Return the consumer config to bind to, creating the durable if it is absent. + + An existing consumer is left exactly as it is, and the difference is reported + instead. A durable's name, filter subject and deliver group are broker-side state + that the stream's pending and redelivery bookkeeping hangs off; rewriting it in + place either replays messages the consumer already handled or skips ones it never + saw. That makes reconfiguration a migration -- delete the consumer deliberately -- + rather than something a rolling restart should do silently. + + The returned config is the server's, so replicas that start after the first one + join the deliver group already in force rather than defining a competing one. + """ + js = self._nats_client.jetstream() # type: ignore[union-attr] + stream = self.config.get("nats_stream_name", "EVENTS") + desired = self._consumer_config(topic, durable) + + try: + info = await js.consumer_info(stream, durable) + except NotFoundError: + await js.add_consumer(stream, config=desired) + logger.info( + "Created JetStream consumer '%s' on stream '%s': filter '%s', deliver group '%s', " + "ack_wait %.1fs, max_ack_pending %s, max_deliver %s", + durable, + stream, + topic, + desired.deliver_group, + desired.ack_wait, + desired.max_ack_pending, + desired.max_deliver, + ) + return desired + + drift = self._consumer_drift(info.config, desired) + if drift: + logger.warning( + "JetStream consumer '%s' on stream '%s' already exists with different settings (%s). " + "It is left unchanged: changing a durable's filter or deliver group is a migration, " + "not a restart. Delete the consumer during a maintenance window to apply the new values.", + durable, + stream, + "; ".join(drift), + ) + return info.config + + @staticmethod + def _consumer_drift(actual: js_api.ConsumerConfig, desired: js_api.ConsumerConfig) -> list[str]: + """Name the settings on which an existing consumer differs from the wanted one.""" + return [ + f"{field}: broker has {getattr(actual, field)!r}, config asks for {getattr(desired, field)!r}" + for field in ("filter_subject", "deliver_group", "ack_wait", "max_ack_pending", "max_deliver") + if getattr(actual, field) != getattr(desired, field) + ] + + # ------------------------------------------------------------------ + # Internal — per-topic subscription + # ------------------------------------------------------------------ + + async def _subscribe_one(self, topic: str, callback: Callable[[CloudEvent[Any]], Awaitable[None]]) -> None: + client = await self.client + + async def message_handler(msg: Any) -> None: + self._enter_handler() + try: + cloud_event = self._decode_message(msg, topic) + if cloud_event is None: + # A payload that will not parse now will not parse on redelivery either. + await self._settle(msg, DeliveryDisposition.TERM, topic, None) + return + + try: + await callback(cloud_event) + except Exception as ex: + disposition = disposition_for(ex) + logger.error( + "Handler failed for event %s on topic '%s', will %s: %s", + cloud_event.id, + topic, + disposition.value, + ex, + exc_info=True, + ) + await self._settle(msg, disposition, topic, cloud_event.id) + else: + await self._settle(msg, DeliveryDisposition.ACK, topic, cloud_event.id) + finally: + self._exit_handler() + + try: + if self._use_jetstream and client.jetstream(): + stream_name = self.config.get("nats_stream_name", "EVENTS") + durable_name = self._durables.get(topic) or self._durable_for(topic) + + # subscribe_bind rather than subscribe, because the queue group cannot reach a + # durable any other way: nats-py rejects a queue subscription whose durable name + # differs from the queue name, and the durable is per topic while the queue group + # is per agent. Binding to a consumer we create ourselves also puts ack_wait, + # max_ack_pending and max_deliver where the broker can enforce them. + consumer_config = await self._ensure_consumer(topic, durable_name) + sub = await client.jetstream().subscribe_bind( + stream=stream_name, + config=consumer_config, + consumer=durable_name, + cb=message_handler, + manual_ack=True, + ) + logger.info( + "Subscribed to JetStream topic '%s' via durable '%s' in deliver group '%s'", + topic, + durable_name, + consumer_config.deliver_group or "", + ) + else: + sub = await client.subscribe(topic, queue=self._queue_group, cb=message_handler) + logger.info("Subscribed to Core NATS topic '%s' in queue group '%s'", topic, self._queue_group) + + self._subscriptions.append(sub) + + except Exception as e: + logger.error("Failed to subscribe to topic '%s': %s", topic, str(e)) + raise + + # ------------------------------------------------------------------ + # Internal — acknowledgement + # ------------------------------------------------------------------ + + async def _settle(self, msg: Any, disposition: DeliveryDisposition, topic: str, event_id: str | None) -> None: + """Tell the broker what became of a delivery (spec sec. 7.2). + + Only JetStream deliveries can be settled. Core NATS is fire-and-forget and + ``msg.ack()`` raises ``NotJSMessageError`` there, so the JetStream flag gates the + whole method. It gates on ``_use_jetstream`` rather than on ``msg.reply`` because a + Core NATS request/reply message also carries a reply subject, and publishing ``+ACK`` + to a waiting requester would be worse than not acknowledging at all. + + A failure to settle is logged and swallowed. An acknowledgement is published to the + delivering connection's reply subject, so it fails precisely when that connection is + gone -- raising into the ``nats-py`` callback would neither deliver it nor recover it. + The message is redelivered after ``ack_wait`` instead, which is the at-least-once + behaviour sec. 7.4 already requires handlers to tolerate. + + A nak on the delivery the broker will not repeat is turned into a dead letter and a + term. Naking there would be a lie: ``max_deliver`` is already reached, so nothing + redelivers and the message leaves the consumer with no trace of why. Terming it here + keeps the payload, on the dead-letter subject, and releases the consumer's pending + slot immediately instead of one more ``ack_wait`` later. + """ + if not self._use_jetstream: + return + + try: + if disposition is DeliveryDisposition.ACK: + await msg.ack() + elif disposition is DeliveryDisposition.NAK and not self._deliveries_exhausted(msg): + await msg.nak() + else: + await self._dead_letter(msg, disposition, topic, event_id) + await msg.term() + except Exception as exc: + logger.error( + "Could not %s event %s on topic '%s' (%s); it will be redelivered after ack_wait", + disposition.value, + event_id or "", + topic, + exc, + ) + + def _deliveries_exhausted(self, msg: Any) -> bool: + """Whether the broker has no redelivery left for this message. + + ``max_deliver`` counts attempts, so the last one the broker makes is attempt + ``max_deliver`` itself: naking *that* delivery buys nothing. ``-1`` means unlimited + and is never exhausted. A message whose JetStream metadata cannot be read is treated + as not exhausted, so an unreadable header can only cost a retry, never a payload. + """ + max_deliver = self._tuning.max_deliver if self._tuning else -1 + if max_deliver < 0: + return False + delivered = self._delivery_count(msg) + return delivered is not None and delivered >= max_deliver + + @staticmethod + def _delivery_count(msg: Any) -> int | None: + """Number of times the broker has delivered this message, or ``None`` if unknown.""" + try: + return int(msg.metadata.num_delivered) + except Exception: + return None + + async def _dead_letter(self, msg: Any, disposition: DeliveryDisposition, topic: str, event_id: str | None) -> None: + """Republish a message the framework has given up on, before the delivery is termed. + + Both terminal outcomes arrive here: a payload rejected as unprocessable, and one + whose redeliveries are spent. This is the last point at which the payload still + exists -- the ``term()`` that follows removes it from the consumer -- so the original + bytes are republished unchanged, including a payload that never parsed as a + CloudEvent. What went wrong travels in headers instead, where it cannot corrupt a + body a dead-letter consumer will try to read. + """ + subject = self._tuning.dead_letter_subject if self._tuning else "" + delivered = self._delivery_count(msg) + reason = "deliveries-exhausted" if disposition is DeliveryDisposition.NAK else "terminal-failure" + + if not subject: + logger.warning( + "Dropping event %s from topic '%s' after %s delivery attempt(s) (%s): no dead-letter " + "subject is configured, so its payload is lost. Set 'nats_dead_letter_subject' to keep it.", + event_id or "", + topic, + delivered if delivered is not None else "an unknown number of", + reason, + ) + return + + headers = { + "Blueprint-Dead-Letter-Reason": reason, + "Blueprint-Original-Subject": topic, + "Blueprint-Delivery-Count": str(delivered) if delivered is not None else "unknown", + } + if event_id: + headers["Blueprint-Event-Id"] = event_id + + try: + await self._nats_client.jetstream().publish(subject, msg.data, headers=headers) # type: ignore[union-attr] + except Exception as exc: + logger.error( + "Could not move event %s from topic '%s' to dead-letter subject '%s' (%s); its payload is lost", + event_id or "", + topic, + subject, + exc, + ) + return + + logger.warning( + "Moved event %s from topic '%s' to dead-letter subject '%s' after %s delivery attempt(s) (%s)", + event_id or "", + topic, + subject, + delivered if delivered is not None else "an unknown number of", + reason, + ) + + # ------------------------------------------------------------------ + # Internal — reconnect callbacks + # ------------------------------------------------------------------ + + async def _on_disconnected(self) -> None: + self._subscriptions_ready = False + logger.warning("NATSClient disconnected") + + async def _on_reconnected(self) -> None: + logger.info("NATSClient reconnected") + if not self._subscriptions_managed: + return + if self._use_jetstream and self._topic_callbacks: + # JetStream durable consumers do not survive reconnects; re-subscribe manually. + # Core NATS re-subscribes automatically via the client library. + self._subscriptions.clear() + try: + await self._subscribe_all() + except Exception as e: + logger.error("NATSClient failed to re-establish JetStream subscriptions after reconnect: %s", e) + return + self._subscriptions_ready = True + logger.info("NATSClient subscriptions ready after reconnect") diff --git a/src/blueprint/agents/io/api/eventing/dapr.py b/src/blueprint/agents/io/api/eventing/dapr.py index d7511b98..b7896d72 100644 --- a/src/blueprint/agents/io/api/eventing/dapr.py +++ b/src/blueprint/agents/io/api/eventing/dapr.py @@ -1,114 +1,172 @@ """Generic Dapr pub/sub endpoints for the agent service (framework-level).""" import logging +from collections.abc import Awaitable, Callable, Coroutine from typing import Any -from fastapi import HTTPException, status +from fastapi import Request, Response +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse +from fastapi.routing import APIRoute -from ....models.errors import CriticalHandlerError, InvalidEventError, RetryableHandlerError from ....clients.io.dapr_client import DaprClient -from ....models import ProcessingStatus +from ....models.errors import DeliveryDisposition, HandlerError, disposition_for from ....models.events import CloudEvent -from .event_handling_base import EventHandlingBase from ..rest_api_base import RestApiBase +from .dapr_response import dapr_status +from .event_handling_base import EventHandlingBase logger = logging.getLogger(__name__) +class DaprDeliveryRoute(APIRoute): + """Answer an unparseable delivery with ``DROP`` instead of letting FastAPI answer 422. + + Under NATS the framework decodes the payload itself, so a body that cannot become a + CloudEvent is terminated by ``NATSClient._settle`` -- it will not parse on redelivery + either. Under Dapr the body is parsed by FastAPI before any framework code runs, so + that same payload produced a 422 the sidecar reads as a failed call and retries to + ``max_deliver``: the one row of the spec sec. 7.2 table where the two transports + disagreed for a structural reason rather than a coding one. + + Wrapping the route handler is what makes the answer route-scoped. An application-wide + ``RequestValidationError`` handler would also answer for ordinary REST endpoints, where + 422 is the correct reply and ``{"status": "DROP"}`` would be nonsense. + """ + + def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: + handle = super().get_route_handler() + + async def drop_unparseable_delivery(request: Request) -> Response: + try: + return await handle(request) + except RequestValidationError as exc: + logger.error("Discarding unparseable delivery on '%s': %s", request.url.path, exc) + return JSONResponse({"status": dapr_status(DeliveryDisposition.TERM), "reason": "payload is not a CloudEvent"}) + + return drop_unparseable_delivery + + class DaprEventing(EventHandlingBase): - """Encapsulates all Dapr-related endpoints and logic.""" + """Implements event handling using Dapr pub/sub. + + The application holds no broker connection -- the sidecar does. The sidecar discovers + what to deliver by calling ``GET /dapr/subscribe``, then pushes each message to + ``POST /events/{topic}``, whose response body is the acknowledgement. + + Both halves are driven by the same ``get_subscribed_topics()`` declarations the NATS + transport uses: + + - ``subscribe()`` renders them as the sidecar's subscription document, which is what + actually causes delivery. + - ``on_startup`` also hands them to ``DaprClient``, which uses them only to start the + sidecar-reachability retry and to report ``subscriptions_ready`` through + ``health_check()``. The client never invokes those callbacks, because delivery arrives + over HTTP rather than through a client-side subscription. + + Config keys + ~~~~~~~~~~~ + ``dapr_pubsub_name`` (str, default ``"pubsub"``): the Dapr pub/sub component to bind to. + ``dapr_declarative_subscriptions`` (bool, default ``False``): set ``True`` when + subscriptions are declared outside the application (CRD or YAML) so the discovery + endpoint returns an empty document and the sidecar cannot subscribe twice. + """ + + route_class = DaprDeliveryRoute def __init__(self) -> None: super().__init__(should_register=False) self._client: DaprClient | None = None async def on_startup(self) -> None: - """Fetch the registered DaprClient from the registry.""" self._client = self.registry.get_component(DaprClient) + # Delivery is driven by the subscription document in subscribe(); this handing-over + # exists so the client starts its sidecar-reachability retry and can report + # subscriptions_ready. Removing it would silently disable readiness gating. + topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = { + topic: self._make_event_callback(topic) for topic in self._declared_topics() + } + + if topic_callbacks: + await self._client.subscribe(topic_callbacks) + else: + logger.debug("DaprEventing: no handler declared a topic; nothing to report as ready") + async def on_shutdown(self) -> None: - """No shutdown actions required — DaprClient lifecycle is managed separately.""" + pass + + def _make_event_callback(self, topic: str) -> Callable[[CloudEvent[Any]], Awaitable[None]]: + """Return an async callback that routes an incoming Dapr event through the handler chain.""" + + async def _process_event(event: CloudEvent[Any]) -> None: + try: + context = {"dapr_topic": topic} + await self._process_cloud_event(event, context, topic) + except Exception as exc: + logger.error("Event processing failed on topic %s: %s", topic, str(exc), exc_info=True) + + return _process_event @RestApiBase.get("/dapr/subscribe", tags=["dapr"]) - async def subscribe(self, topic: str, queue_group: str | None = None) -> dict[str, Any]: - """ - Dapr subscription discovery endpoint. + async def subscribe(self) -> list[dict[str, Any]]: + """Return the subscription document the Dapr sidecar fetches at startup. - Implementations can override this by adding their own router with the same - path to provide real topics and routes. + One entry per topic declared by a registered handler, routed to this service's + ``POST /events/{topic}`` endpoint. The sidecar calls this with no parameters, so the + signature takes none: a required query parameter here answers 422 and the service + receives nothing. - Note: this complements subscription resources defined in kubernetes - (you can choose your approach) + Returns an empty document when ``dapr_declarative_subscriptions`` is set, so a + deployment that declares its subscriptions as Kubernetes resources does not end up + subscribed twice. + Overriding this in user code is supported, but the override must re-apply + ``@RestApiBase.get("/dapr/subscribe")`` -- route discovery walks the MRO subclass-first + and an undecorated override claims the name without registering a route. """ - - # Framework default: no subscriptions declared. - # Example structure: - # return [ - # {"pubsubname": "pubsub", "topic": "events.topic1", "route": "/events/topic1"} - # ] - return {} + if self.config.get("dapr_declarative_subscriptions", False): + logger.debug("DaprEventing: subscriptions are declared externally, returning an empty document") + return [] + + pubsub_name = self.config.get("dapr_pubsub_name", "pubsub") + return [{"pubsubname": pubsub_name, "topic": topic, "route": f"/events/{topic}"} for topic in self._declared_topics()] + + def _declared_topics(self) -> list[str]: + """Return every topic declared by a registered handler, in declaration order.""" + topics: dict[str, None] = {} + for handler in self.registry.get_event_handler(): + for topic in handler.get_subscribed_topics(): + if topic: + topics[topic] = None + return list(topics) @RestApiBase.post("/events/{topic}", tags=["dapr"]) async def publish(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[str, Any]: - """ - Generic Dapr event handler that processes events through the unified service. + """Receive an event from the sidecar and answer with its acknowledgement. + + The returned dict is the acknowledgement, so this method is Dapr's equivalent of + ``NATSClient._settle`` and follows the same table (spec sec. 7.2): a handler chain + that returned answers ``SUCCESS`` whatever its status, and a raised exception is + classified by ``disposition_for`` and rendered into Dapr's words. One ``except`` + rather than one per error type, so the two transports cannot drift apart. """ try: - context = { - "dapr_topic": topic, - } - - processing_result = await self._process_cloud_event(cloud_event, context) - - # Return Dapr-compatible response based on result status - if processing_result.status == ProcessingStatus.PROCESSED: - return {"status": "SUCCESS"} - - logger.warning( - "Processing service returned non-success status %s for topic %s", - processing_result.status.value, - topic, - ) - failure_reason = processing_result.message or processing_result.status.value or "unknown_status" - return {"status": "RETRY", "reason": failure_reason} - - except RetryableHandlerError as exc: + await self._process_cloud_event(cloud_event, {"dapr_topic": topic}, topic) + except Exception as exc: + disposition = disposition_for(exc) + reason = exc.reason if isinstance(exc, HandlerError) else str(exc) logger.error( - "Retrying message for topic %s: %s", + "Handler failed for event %s on topic '%s', answering %s: %s", + cloud_event.id, topic, - str(exc), + dapr_status(disposition), + exc, exc_info=True, ) - return {"status": "RETRY", "reason": exc.reason} + return {"status": dapr_status(disposition), "reason": reason} - except InvalidEventError as exc: - logger.error( - "Dropping message for topic %s: %s", - topic, - str(exc), - exc_info=True, - ) - return {"status": "DROP", "reason": exc.reason} - - except CriticalHandlerError as exc: - logger.error( - "Critical error for topic %s: %s", - topic, - str(exc), - exc_info=True, - ) - return {"status": "RETRY", "reason": exc.reason} - - except Exception as exc: # pragma: no cover - integration behaviour - logger.error( - "Processing service failed for Dapr topic %s: %s", - topic, - str(exc), - exc_info=True, - ) - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="Dapr event handling failed", - ) from exc + # An unmatched event acknowledges like any other completed dispatch; the accounting + # that keeps it visible lives in _process_cloud_event, shared with the NATS edge. + return {"status": dapr_status(DeliveryDisposition.ACK)} diff --git a/src/blueprint/agents/io/api/eventing/dapr_response.py b/src/blueprint/agents/io/api/eventing/dapr_response.py new file mode 100644 index 00000000..6ad2d079 --- /dev/null +++ b/src/blueprint/agents/io/api/eventing/dapr_response.py @@ -0,0 +1,24 @@ +"""Rendering of a delivery disposition into Dapr's response vocabulary. + +Dapr acknowledges by response body rather than by a call on the message, so the dict a +route returns *is* the acknowledgement. Spec sec. 7.2 fixes one outcome table for every +transport: what an outcome deserves is decided once, by +:func:`blueprint.agents.models.errors.disposition_for`, and each transport only renders +that decision in its own words. Keeping the words here rather than in ``models`` stops +Dapr's vocabulary from leaking into the shared layer, and keeping them out of ``dapr.py`` +lets ``EventHandlingBase.handle_event`` render identically without importing a subclass. +""" + +from ....models.errors import DeliveryDisposition + +_STATUS_BY_DISPOSITION: dict[DeliveryDisposition, str] = { + DeliveryDisposition.ACK: "SUCCESS", + DeliveryDisposition.NAK: "RETRY", + DeliveryDisposition.TERM: "DROP", +} + + +def dapr_status(disposition: DeliveryDisposition) -> str: + """Return the Dapr status word for a delivery disposition.""" + + return _STATUS_BY_DISPOSITION[disposition] diff --git a/src/blueprint/agents/io/api/eventing/event_handling_base.py b/src/blueprint/agents/io/api/eventing/event_handling_base.py index 18c159c2..3a3532b7 100644 --- a/src/blueprint/agents/io/api/eventing/event_handling_base.py +++ b/src/blueprint/agents/io/api/eventing/event_handling_base.py @@ -6,15 +6,24 @@ from abc import ABC, abstractmethod from typing import Any +from opentelemetry import metrics + from ....component.component import traced from ....models import ProcessingResult, ProcessingStatus -from ....models.errors import CriticalHandlerError, InvalidEventError, RetryableHandlerError +from ....models.errors import DeliveryDisposition from ....models.events import CloudEvent from ..rest_api_base import RestApiBase from .cloud_event_processor_mixin import CloudEventProcessorMixin +from .dapr_response import dapr_status logger = logging.getLogger(__name__) +_UNHANDLED_EVENTS = metrics.get_meter(__name__).create_counter( + name="blueprint.events.unhandled", + description="Events a namespace received and found nothing to do with", + unit="{event}", +) + class EventHandlingBase(RestApiBase, CloudEventProcessorMixin, ABC): """Base class for event-driven REST API components. @@ -22,60 +31,67 @@ class EventHandlingBase(RestApiBase, CloudEventProcessorMixin, ABC): Combines REST API routing (RestApiBase) with CloudEvent processing (CloudEventProcessorMixin) and adds structured error-handling and logging around the dispatch pipeline. + + Transport connection, topic subscriptions, and retry logic live entirely + in the transport client (NATSClient, DaprClient). Subclasses implement + ``on_startup`` to wire the client's managed subscription flow and declare + their own REST endpoints via concrete ``publish`` implementations. + """ + + ROOT_NAMESPACE = "" + """Namespace this component's events belong to. + + Components gain a real namespace in phase 2; until then every one of them lives in the + root namespace, and this constant is the single place that assumption is written down. """ @traced("topic", "cloud_event") async def handle_event(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[str, Any]: - processing_result = await self._process_cloud_event(cloud_event, {"topic": topic}) - if processing_result.status == ProcessingStatus.PROCESSED: - return {"status": "SUCCESS"} - else: - failure_reason = processing_result.message or processing_result.status.value or "unknown_status" - return {"status": "RETRY", "reason": failure_reason} + """Dispatch an event and return the acknowledgement dict Dapr reads. - @abstractmethod - async def publish(self, topic: str, event: CloudEvent[Any]) -> dict[str, Any]: - """Abstract method for publishing events (output)""" - raise NotImplementedError() + A handler chain that returned acknowledges whatever its status, per spec sec. 7.2: + ``ProcessingStatus`` carries no failure value, so ``NO_HANDLER_FOUND`` means the + dispatch completed and found nothing to do -- and no amount of redelivery makes a + handler appear. Exceptions are not caught here; the transport edge classifies them. + """ + await self._process_cloud_event(cloud_event, {"topic": topic}, topic) + return {"status": dapr_status(DeliveryDisposition.ACK)} @abstractmethod - async def subscribe(self, topic: str, queue_group: str | None = None) -> dict[str, Any]: - """Abstract method for subscribing for events (input)""" + async def publish(self, topic: str, event: CloudEvent[Any]) -> dict[str, Any]: + """Publish a CloudEvent to the broker (output path).""" raise NotImplementedError() async def _process_cloud_event( self, cloud_event: CloudEvent[Any], context: dict[str, Any], + topic: str, ) -> ProcessingResult: - """Process a CloudEvent with error handling and logging. - - Wraps ``_dispatch_cloud_event`` with structured logging and exception - handling for the four known error types. All exceptions are re-raised - after logging. + """Dispatch a CloudEvent through the handler chain, letting failures propagate. - Args: - cloud_event: The CloudEvent to process - context: Additional context for processing + Deliberately does not log those failures. Every caller of this method is a transport + edge that must both decide the delivery disposition and report the failure (spec + sec. 7.2), so logging here duplicated each error in the caller's output while adding + nothing the edge does not already know -- and the edge knows the topic and the + disposition, which this layer does not. - Returns: - The processing result + A dispatch that matched no handler is counted, not reported. Deciding there is + nothing to do is a handler's job and an ordinary outcome of it: an agent reads an + event, finds no work in it, and says so. The count exists so an operator can see the + *proportion* -- a namespace that declines nearly everything it receives is subscribed + too broadly (spec sec. 7.7) -- and for no other reason. Nothing about it is an error, + so it is not logged as one, and no per-topic state is kept: the topic arrives from a + URL path under Dapr, and remembering each distinct value would let a caller grow this + process's memory. - Raises: - Exception: Re-raises all exceptions after logging + ``topic`` is passed separately from ``context`` because each transport spells its + own key there (``nats_topic``, ``dapr_topic``), and those keys reach user handlers, + so they cannot be unified without breaking them. """ - try: - logger.debug("Processing CloudEvent: %s", cloud_event.id) - return await self._dispatch_cloud_event(cloud_event, context) - except RetryableHandlerError as exc: - logger.error("Retrying event: %s", str(exc), exc_info=True) - raise - except InvalidEventError as exc: - logger.error("Dropping invalid event: %s", str(exc), exc_info=True) - raise - except CriticalHandlerError as exc: - logger.error("Critical error processing event: %s", str(exc), exc_info=True) - raise - except Exception as exc: - logger.error("Processing service failed: %s", str(exc), exc_info=True) - raise + logger.debug("Processing CloudEvent: %s", cloud_event.id) + processing_result = await self._dispatch_cloud_event(cloud_event, context) + if processing_result.status is ProcessingStatus.NO_HANDLER_FOUND: + _UNHANDLED_EVENTS.add(1, {"namespace": self.ROOT_NAMESPACE, "topic": topic}) + logger.debug("No handler had work for event %s on topic '%s'", cloud_event.id, topic) + return processing_result diff --git a/src/blueprint/agents/io/api/eventing/nats.py b/src/blueprint/agents/io/api/eventing/nats.py index 319f0700..fabf708a 100644 --- a/src/blueprint/agents/io/api/eventing/nats.py +++ b/src/blueprint/agents/io/api/eventing/nats.py @@ -1,10 +1,10 @@ """NATS eventing implementation using NATSClient.""" import logging +from collections.abc import Awaitable, Callable from typing import Any from ....clients.io.nats_client import NATSClient -from ....models.errors import CriticalHandlerError, InvalidEventError, RetryableHandlerError from ....models.events import CloudEvent from ..rest_api_base import RestApiBase from .event_handling_base import EventHandlingBase @@ -13,107 +13,67 @@ class NatsEventing(EventHandlingBase): - """Implements event handling using NATS via NATSClient.""" + """Implements event handling using NATS via NATSClient. + + ``on_startup`` collects the full topic→callback mapping from all registered + handlers and config, then hands it to ``NATSClient.subscribe()``. The client + owns connection, retry, reconnect, and subscription-readiness tracking. + + The callback lets every exception through. A handler failure is the only way a + failure reaches the transport -- ``ProcessingStatus`` has no failure value -- and + the transport edge is what turns it into a nak or a term (spec sec. 7.2). Catching + one here would acknowledge the event as successfully processed. + """ def __init__(self) -> None: super().__init__(should_register=False) self._client: NATSClient | None = None async def on_startup(self) -> None: - """Fetch the registered NATSClient and auto-subscribe to declared topics. - - Topics are collected from two sources (handler-declared topics first, - then config-declared topics). Duplicates are silently dropped — the - first occurrence wins, so handler declarations take priority. - """ self._client = self.registry.get_component(NATSClient) - seen: dict[str, None] = {} + topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = {} for handler in self.registry.get_event_handler(): for topic in handler.get_subscribed_topics(): - if topic and topic not in seen: - seen[topic] = None + if topic and topic not in topic_callbacks: + topic_callbacks[topic] = self._make_event_callback(topic) for topic in self.config.get_nats_subscription_config(): - if topic and topic not in seen: - seen[topic] = None + if topic and topic not in topic_callbacks: + topic_callbacks[topic] = self._make_event_callback(topic) - if not seen: + if topic_callbacks: + await self._client.subscribe(topic_callbacks) + else: logger.info("NatsEventing: no auto-subscriptions configured") - return - - for topic in seen: - await self._subscribe_to_topic(topic) - - async def _subscribe_to_topic(self, topic: str) -> None: - """Subscribe to a single NATS topic using the standard processing callback. - - Extracted as a method so the closure correctly captures ``topic`` by - value at call time, avoiding the loop late-binding pitfall. - """ - if not self._client: - raise RuntimeError("NATS client not initialized") - - async def _process_event(event: CloudEvent[Any]) -> None: - try: - context = {"nats_topic": topic} - processing_result = await self._process_cloud_event(event, context) - logger.debug( - "Processed CloudEvent %s on topic %s with status %s", - event.id, - topic, - processing_result.status.value, - ) - except (RetryableHandlerError, InvalidEventError, CriticalHandlerError) as exc: - logger.error("Event processing failed: %s", str(exc), exc_info=True) - - await self._client.subscribe(topic, _process_event) - logger.info("NatsEventing: auto-subscribed to topic '%s'", topic) async def on_shutdown(self) -> None: - """No shutdown actions required — NATSClient lifecycle is managed separately.""" - - @RestApiBase.post("/nats/subscribe/{topic}", tags=["nats"]) - async def subscribe(self, topic: str, queue_group: str | None = None) -> dict[str, Any]: - """Subscribe to a NATS topic. - - Args: - topic: The topic to subscribe to - queue_group: Optional queue group + pass - Returns: - Success message - """ - if not self._client: - raise RuntimeError("NATS client not initialized") + def _make_event_callback(self, topic: str) -> Callable[[CloudEvent[Any]], Awaitable[None]]: + """Return an async callback that routes an incoming event through the handler chain.""" - # Callback to process incoming events async def _process_event(event: CloudEvent[Any]) -> None: - try: - context = {"nats_topic": topic} - processing_result = await self._process_cloud_event(event, context) - logger.debug( - "Processed CloudEvent %s on topic %s with status %s", - event.id, - topic, - processing_result.status.value, - ) - except (RetryableHandlerError, InvalidEventError, CriticalHandlerError) as exc: - logger.error("Event processing failed: %s", str(exc), exc_info=True) - # NATS handles retries/acks via client - - await self._client.subscribe(topic, _process_event) - return {"message": f"Subscribed to topic {topic}"} + context = {"nats_topic": topic} + processing_result = await self._process_cloud_event(event, context, topic) + logger.debug( + "Processed CloudEvent %s on topic %s with status %s", + event.id, + topic, + processing_result.status.value, + ) + + return _process_event @RestApiBase.post("/events/{topic}", tags=["nats"]) async def publish(self, topic: str, event: CloudEvent[Any]) -> dict[str, Any]: """Publish a CloudEvent to a NATS topic. Args: - topic: The topic to publish to - event: The CloudEvent to publish + topic: The topic to publish to. + event: The CloudEvent to publish. Returns: - Success message + Success message. """ if not self._client: raise RuntimeError("NATS client not initialized") diff --git a/src/blueprint/agents/io/api/rest_api_base.py b/src/blueprint/agents/io/api/rest_api_base.py index 6c2f8b49..1bb09e04 100644 --- a/src/blueprint/agents/io/api/rest_api_base.py +++ b/src/blueprint/agents/io/api/rest_api_base.py @@ -30,6 +30,7 @@ async def create_item(self, payload: ItemRequest) -> Item: from uuid import uuid4 from fastapi import APIRouter, HTTPException, Request, status +from fastapi.routing import APIRoute from fastapi.responses import JSONResponse from opentelemetry import trace @@ -50,9 +51,18 @@ class RestApiBase(IOBase, ABC): never need to call ``_wire_routes()`` or touch the router directly. """ + route_class: type[APIRoute] = APIRoute + """Route class for this component's router. + + Override in a subclass whose routes need behaviour FastAPI applies per route rather + than per application -- turning a request-validation failure into a domain response, + for instance. An application-wide exception handler cannot do that without knowing + which routes it is allowed to answer for. + """ + def __init__(self, should_register: bool = True) -> None: super().__init__(should_register) - self._router = APIRouter() + self._router = APIRouter(route_class=type(self).route_class) self._wire_routes() @property diff --git a/src/blueprint/agents/models/__init__.py b/src/blueprint/agents/models/__init__.py index 4b715c16..73ccce55 100644 --- a/src/blueprint/agents/models/__init__.py +++ b/src/blueprint/agents/models/__init__.py @@ -13,7 +13,7 @@ ProcessResourceResponse, ) from .config import AIConfig, CacheConfig, EventPublishingConfig, ObservabilityConfig, PromptConfig, RuntimeConfig, TopicConfig, UsageLimits -from .errors import CriticalHandlerError, HandlerError, InvalidEventError, RetryableHandlerError +from .errors import CriticalHandlerError, DeliveryDisposition, HandlerError, InvalidEventError, RetryableHandlerError, disposition_for from .events import CloudEvent, GenericCloudEvent, HandlerResult, create_cloud_event from .result import AgentOutput, Evidence, ProcessingResult, ProcessingStatus from .status import BuildStatus, EnvironmentStatus, LLMStatus, ServiceInfo, VLLMInfo @@ -41,6 +41,7 @@ "InvalidEventError", "RetryableHandlerError", "CriticalHandlerError", + "DeliveryDisposition", "LLMStatus", "ObservabilityConfig", "ProcessResourceRequest", @@ -54,4 +55,5 @@ "CacheStatsResponse", "CacheEvictRequest", "create_cloud_event", + "disposition_for", ] diff --git a/src/blueprint/agents/models/errors.py b/src/blueprint/agents/models/errors.py index 718f3b8e..1bee354b 100644 --- a/src/blueprint/agents/models/errors.py +++ b/src/blueprint/agents/models/errors.py @@ -1,3 +1,8 @@ +"""Handler exceptions, and the delivery disposition each one implies.""" + +from enum import Enum + + class HandlerError(Exception): """Domain-specific exception raised by handlers.""" @@ -27,3 +32,42 @@ class InvalidEventError(HandlerError): def __init__(self, *, status: str, reason: str, code: str | None = None): super().__init__(status=status, reason=reason, code=code) + + +class DeliveryDisposition(Enum): + """What a transport does with a delivery once dispatch has finished. + + Spec sec. 7.2 fixes one outcome table for every transport, so the mapping lives + beside the exceptions it classifies rather than inside any one transport: NATS + renders these as ``ack``/``nak``/``term`` and Dapr as ``SUCCESS``/``RETRY``/``DROP``, + but they must never disagree about which one an outcome deserves. + """ + + ACK = "ack" + NAK = "nak" + TERM = "term" + + +_DISPOSITION_BY_ERROR: tuple[tuple[type[BaseException], DeliveryDisposition], ...] = ( + (RetryableHandlerError, DeliveryDisposition.NAK), + (InvalidEventError, DeliveryDisposition.TERM), + (CriticalHandlerError, DeliveryDisposition.TERM), +) + + +def disposition_for(exc: BaseException) -> DeliveryDisposition: + """Return the delivery disposition a failed dispatch earns (spec sec. 7.2). + + Never returns ``ACK``: acknowledgement is what a *normal return* means, and the + transport edge decides that without consulting this function. An unrecognised + exception is treated as retryable, on the grounds that an unexpected failure is + more often transient than permanent -- which is why ``max_deliver`` and a + dead-letter destination are required alongside it. + + Matching is by ``isinstance``, so a project's own subclass of one of these errors + inherits its disposition. + """ + for error_type, disposition in _DISPOSITION_BY_ERROR: + if isinstance(exc, error_type): + return disposition + return DeliveryDisposition.NAK diff --git a/tests/unit/agents/clients/ai/test_openai_client.py b/tests/unit/agents/clients/ai/test_openai_client.py index bb961076..e8e999b8 100644 --- a/tests/unit/agents/clients/ai/test_openai_client.py +++ b/tests/unit/agents/clients/ai/test_openai_client.py @@ -36,7 +36,7 @@ async def test_close_is_safe_when_client_already_none(self, openai_client: OpenA class TestOpenAIClientPubSub: async def test_subscribe_is_noop(self, openai_client: OpenAIClient) -> None: - await openai_client.subscribe("topic", AsyncMock()) # must not raise + await openai_client.subscribe({"topic": AsyncMock()}) # must not raise async def test_publish_is_noop(self, openai_client: OpenAIClient) -> None: await openai_client.publish("topic", MagicMock()) # must not raise diff --git a/tests/unit/agents/clients/ai/test_vllm_client.py b/tests/unit/agents/clients/ai/test_vllm_client.py index 25c73575..a4515534 100644 --- a/tests/unit/agents/clients/ai/test_vllm_client.py +++ b/tests/unit/agents/clients/ai/test_vllm_client.py @@ -36,7 +36,7 @@ async def test_close_is_safe_when_client_already_none(self, vllm_client: VLLMCli class TestVLLMClientPubSub: async def test_subscribe_is_noop(self, vllm_client: VLLMClient) -> None: - await vllm_client.subscribe("topic", AsyncMock()) + await vllm_client.subscribe({"topic": AsyncMock()}) async def test_publish_is_noop(self, vllm_client: VLLMClient) -> None: await vllm_client.publish("topic", MagicMock()) diff --git a/tests/unit/agents/clients/io/conftest.py b/tests/unit/agents/clients/io/conftest.py index c89dd3e9..36124885 100644 --- a/tests/unit/agents/clients/io/conftest.py +++ b/tests/unit/agents/clients/io/conftest.py @@ -3,6 +3,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest +from nats.js.errors import NotFoundError from blueprint.agents.clients.io.dapr_client import DaprClient from blueprint.agents.clients.io.nats_client import NATSClient @@ -15,12 +16,14 @@ } _NATS_CONFIG = { + "app_name": "test-agent", "nats_url": "nats://localhost:4222", "nats_max_reconnect_attempts": 5, "nats_reconnect_time_wait": 2, "nats_use_jetstream": False, "nats_stream_name": "EVENTS", "nats_durable_name": "test-durable", + "event_client_drain_timeout": 5.0, } @@ -87,11 +90,21 @@ def mock_nats_core() -> MagicMock: @pytest.fixture def mock_nats_jetstream() -> tuple[MagicMock, MagicMock]: - """Return a (nats_client_mock, jetstream_mock) pair with JetStream enabled.""" + """Return a (nats_client_mock, jetstream_mock) pair with JetStream enabled. + + Neither the stream nor the consumer exists by default: ``stream_info`` and + ``consumer_info`` raise ``NotFoundError``, which is what the broker answers for an + unprovisioned name, so the create path is what a test exercises unless it says otherwise. + """ mock_js = MagicMock() mock_js.subscribe = AsyncMock(return_value=MagicMock(unsubscribe=AsyncMock())) + mock_js.subscribe_bind = AsyncMock(return_value=MagicMock(unsubscribe=AsyncMock(), drain=AsyncMock())) mock_js.publish = AsyncMock(return_value=MagicMock(seq=1)) mock_js.add_stream = AsyncMock() + mock_js.stream_info = AsyncMock(side_effect=NotFoundError()) + mock_js.update_stream = AsyncMock() + mock_js.add_consumer = AsyncMock() + mock_js.consumer_info = AsyncMock(side_effect=NotFoundError()) mock_nc = MagicMock() mock_nc.is_closed = False diff --git a/tests/unit/agents/clients/io/test_dapr_client.py b/tests/unit/agents/clients/io/test_dapr_client.py index bf8f95e1..0fc58ee9 100644 --- a/tests/unit/agents/clients/io/test_dapr_client.py +++ b/tests/unit/agents/clients/io/test_dapr_client.py @@ -1,6 +1,7 @@ """Unit tests for DaprClient.""" import json +import logging from unittest.mock import AsyncMock, MagicMock, patch import httpx @@ -38,10 +39,35 @@ async def test_close_calls_aclose_and_clears_client(self, connected_dapr_client: async def test_close_is_safe_when_client_none(self, dapr_client: DaprClient) -> None: await dapr_client.close() # must not raise + async def test_close_cancels_retry_task(self, dapr_client: DaprClient) -> None: + import asyncio + + async def _never() -> None: + await asyncio.sleep(9999) + + task = asyncio.create_task(_never()) + dapr_client._retry_task = task + await dapr_client.close() + assert task.cancelled() + class TestDaprClientSubscribe: - async def test_subscribe_logs_warning_and_does_not_raise(self, connected_dapr_client: DaprClient) -> None: - await connected_dapr_client.subscribe("topic", AsyncMock()) + async def test_subscribe_stores_mapping_and_starts_task(self, dapr_client: DaprClient) -> None: + callback = AsyncMock() + with patch.object(dapr_client, "_start_with_retry", new_callable=AsyncMock) as mock_retry: + await dapr_client.subscribe({"topic.a": callback}) + assert dapr_client._topic_callbacks == {"topic.a": callback} + assert dapr_client._subscriptions_managed is True + mock_retry.assert_called_once() # coroutine was created and scheduled, not directly awaited + + async def test_subscribe_returns_immediately(self, dapr_client: DaprClient) -> None: + with patch.object(dapr_client, "_start_with_retry", new_callable=AsyncMock): + await dapr_client.subscribe({"t": AsyncMock()}) + + async def test_subscriptions_ready_false_before_retry_completes(self, dapr_client: DaprClient) -> None: + with patch.object(dapr_client, "_start_with_retry", new_callable=AsyncMock): + await dapr_client.subscribe({"t": AsyncMock()}) + assert dapr_client.subscriptions_ready is False class TestDaprClientPublish: @@ -140,3 +166,96 @@ async def test_healthy_when_health_check_disabled(self, dapr_client: DaprClient, result = await dapr_client.health_check() assert result.status == "healthy" assert "disabled" in result.message + + async def test_unhealthy_when_subscriptions_managed_but_not_ready(self, connected_dapr_client: DaprClient) -> None: + connected_dapr_client._subscriptions_managed = True + connected_dapr_client._subscriptions_ready = False + result = await connected_dapr_client.health_check() + assert result.status == "unhealthy" + assert "subscriptions" in result.message + + async def test_healthy_when_subscriptions_ready_and_sidecar_up( + self, connected_dapr_client: DaprClient, mock_httpx_client: MagicMock + ) -> None: + connected_dapr_client._subscriptions_managed = True + connected_dapr_client._subscriptions_ready = True + result = await connected_dapr_client.health_check() + assert result.status == "healthy" + + +class TestDaprClientRetryLoop: + async def test_success_on_first_attempt_sets_ready(self, dapr_client: DaprClient) -> None: + dapr_client._subscriptions_managed = True + with patch.object(dapr_client, "_connect_and_subscribe", new_callable=AsyncMock): + await dapr_client._start_with_retry() + assert dapr_client.subscriptions_ready is True + + async def test_max_retries_zero_raises_immediately_on_failure(self, dapr_client: DaprClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda k, d=None: {"event_client_max_retries": 0, "event_client_retry_delay": 0.0}.get(k, d) + dapr_client._subscriptions_managed = True + with patch.object(dapr_client, "_connect_and_subscribe", new_callable=AsyncMock, side_effect=OSError("refused")): + with pytest.raises(OSError): + await dapr_client._start_with_retry() + assert dapr_client.subscriptions_ready is False + + async def test_max_retries_2_calls_connect_three_times_then_raises(self, dapr_client: DaprClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda k, d=None: {"event_client_max_retries": 2, "event_client_retry_delay": 0.0}.get(k, d) + dapr_client._subscriptions_managed = True + mock_connect = AsyncMock(side_effect=OSError("refused")) + with patch.object(dapr_client, "_connect_and_subscribe", mock_connect): + with pytest.raises(OSError): + await dapr_client._start_with_retry() + assert mock_connect.await_count == 3 + + async def test_max_retries_2_succeeds_on_third_attempt(self, dapr_client: DaprClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda k, d=None: {"event_client_max_retries": 2, "event_client_retry_delay": 0.0}.get(k, d) + dapr_client._subscriptions_managed = True + mock_connect = AsyncMock(side_effect=[OSError("fail"), OSError("fail"), None]) + with patch.object(dapr_client, "_connect_and_subscribe", mock_connect): + await dapr_client._start_with_retry() + assert mock_connect.await_count == 3 + assert dapr_client.subscriptions_ready is True + + async def test_done_callback_logs_error_on_permanent_failure(self, dapr_client: DaprClient) -> None: + task = MagicMock() + task.cancelled.return_value = False + task.exception.return_value = OSError("final failure") + with patch.object(logging.getLogger("blueprint.agents.clients.io.dapr_client"), "error") as mock_log: + dapr_client._on_retry_done(task) + mock_log.assert_called_once() + + async def test_done_callback_silent_on_cancellation(self, dapr_client: DaprClient) -> None: + task = MagicMock() + task.cancelled.return_value = True + with patch.object(logging.getLogger("blueprint.agents.clients.io.dapr_client"), "error") as mock_log: + dapr_client._on_retry_done(task) + mock_log.assert_not_called() + + async def test_connect_and_subscribe_pings_sidecar( + self, dapr_client: DaprClient, mock_config: MagicMock, mock_httpx_client: MagicMock + ) -> None: + mock_config.get.side_effect = lambda k, d=None: { + "health_check_dapr": True, + "dapr_url": "http://localhost:3500", + }.get(k, d) + dapr_client._client = mock_httpx_client + await dapr_client._connect_and_subscribe() + mock_httpx_client.get.assert_awaited_once_with("http://localhost:3500/v1.0/healthz") + + async def test_sidecar_unreachable_leaves_ready_false( + self, dapr_client: DaprClient, mock_config: MagicMock, mock_httpx_client: MagicMock + ) -> None: + """Sidecar ping fails → _connect_and_subscribe raises → subscriptions_ready stays False.""" + mock_config.get.side_effect = lambda k, d=None: { + "event_client_max_retries": 0, + "event_client_retry_delay": 0.0, + "health_check_dapr": True, + "dapr_url": "http://localhost:3500", + }.get(k, d) + mock_httpx_client.get.return_value.raise_for_status.side_effect = Exception("503") + dapr_client._client = mock_httpx_client + dapr_client._subscriptions_managed = True + with patch.object(dapr_client, "_connect_and_subscribe", side_effect=OSError("sidecar down")): + with pytest.raises(OSError): + await dapr_client._start_with_retry() + assert dapr_client.subscriptions_ready is False diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index cffb2037..ece44d74 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -1,11 +1,14 @@ """Unit tests for NATSClient.""" +import asyncio import json from unittest.mock import AsyncMock, MagicMock, patch import pytest +from nats.js import api as js_api -from blueprint.agents.clients.io.nats_client import NATSClient +from blueprint.agents.clients.io.nats_client import ConsumerTuning, NATSClient +from blueprint.agents.models.errors import CriticalHandlerError, InvalidEventError, RetryableHandlerError from blueprint.agents.models.events import CloudEvent @@ -22,6 +25,12 @@ def test_use_jetstream_initialises_as_false(self, nats_client: NATSClient) -> No def test_subscriptions_initialises_as_empty_list(self, nats_client: NATSClient) -> None: assert nats_client._subscriptions == [] + def test_subscriptions_ready_initialises_as_false(self, nats_client: NATSClient) -> None: + assert nats_client.subscriptions_ready is False + + def test_subscriptions_managed_initialises_as_false(self, nats_client: NATSClient) -> None: + assert nats_client._subscriptions_managed is False + class TestNATSClientIsConnected: def test_false_when_nats_client_none(self, nats_client: NATSClient) -> None: @@ -59,6 +68,18 @@ async def test_connect_calls_nats_connect_with_url(self, nats_client: NATSClient mock_connect.assert_awaited_once() assert mock_connect.call_args[0][0] == "nats://localhost:4222" + async def test_connect_passes_disconnect_and_reconnect_callbacks(self, nats_client: NATSClient) -> None: + mock_nc = MagicMock(is_closed=False, is_connected=True) + mock_nc.jetstream = MagicMock(return_value=None) + with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock) as mock_connect: + mock_connect.return_value = mock_nc + await nats_client.connect() + kwargs = mock_connect.call_args[1] + assert callable(kwargs["disconnected_cb"]) + assert kwargs["disconnected_cb"].__func__.__name__ == "_on_disconnected" + assert callable(kwargs["reconnected_cb"]) + assert kwargs["reconnected_cb"].__func__.__name__ == "_on_reconnected" + async def test_connect_sets_nats_client_and_client(self, nats_client: NATSClient) -> None: mock_nc = MagicMock(is_closed=False, is_connected=True) mock_nc.jetstream = MagicMock(return_value=None) @@ -101,17 +122,17 @@ async def test_connect_raises_on_nats_error(self, nats_client: NATSClient) -> No class TestNATSClientClose: - async def test_close_unsubscribes_all_subscriptions(self, connected_nats_client: NATSClient) -> None: - sub = MagicMock() - sub.unsubscribe = AsyncMock() + async def test_close_drains_all_subscriptions(self, connected_nats_client: NATSClient) -> None: + sub = MagicMock(drain=AsyncMock(), unsubscribe=AsyncMock()) connected_nats_client._subscriptions = [sub] await connected_nats_client.close() - sub.unsubscribe.assert_awaited_once() + sub.drain.assert_awaited_once() + sub.unsubscribe.assert_not_awaited() async def test_close_clears_subscriptions_list(self, connected_nats_client: NATSClient) -> None: - connected_nats_client._subscriptions = [MagicMock(unsubscribe=AsyncMock())] + connected_nats_client._subscriptions = [MagicMock(drain=AsyncMock())] await connected_nats_client.close() assert connected_nats_client._subscriptions == [] @@ -125,6 +146,308 @@ async def test_close_clears_client_references(self, connected_nats_client: NATSC assert connected_nats_client._client is None assert connected_nats_client._js is None + async def test_close_cancels_retry_task(self, nats_client: NATSClient) -> None: + + async def _never() -> None: + await asyncio.sleep(9999) + + task = asyncio.create_task(_never()) + nats_client._retry_task = task + nats_client._nats_client = None + await nats_client.close() + assert task.cancelled() + + +class TestNATSClientMessageBoundary: + """The transport boundary distinguishes an unusable payload from a failed dispatch. + + The two have opposite dispositions once P2 lands: a payload that cannot be decoded is + terminal for that message, while a dispatch failure is retryable. + """ + + @staticmethod + async def _handler_for(nats_client: NATSClient, mock_nats_core: MagicMock, callback) -> object: + nats_client._nats_client = mock_nats_core + nats_client._client = mock_nats_core + await nats_client._subscribe_one("orders.created", callback) + return mock_nats_core.subscribe.await_args.kwargs["cb"] + + async def test_undecodable_payload_is_not_dispatched( + self, nats_client: NATSClient, mock_nats_core: MagicMock, caplog: pytest.LogCaptureFixture + ) -> None: + dispatched = [] + + async def _callback(event: CloudEvent) -> None: + dispatched.append(event) + + handler = await self._handler_for(nats_client, mock_nats_core, _callback) + + with caplog.at_level("ERROR"): + await handler(MagicMock(data=b"not json at all")) + + assert dispatched == [] + assert "unparseable" in caplog.text + assert "orders.created" in caplog.text + + async def test_valid_json_that_is_not_a_cloud_event_is_not_dispatched(self, nats_client: NATSClient, mock_nats_core: MagicMock) -> None: + dispatched = [] + + async def _callback(event: CloudEvent) -> None: + dispatched.append(event) + + handler = await self._handler_for(nats_client, mock_nats_core, _callback) + + await handler(MagicMock(data=json.dumps({"not": "an event"}).encode())) + + assert dispatched == [] + + async def test_dispatch_failure_is_logged_with_event_and_topic( + self, + nats_client: NATSClient, + mock_nats_core: MagicMock, + cloud_event: CloudEvent, + caplog: pytest.LogCaptureFixture, + ) -> None: + async def _callback(event: CloudEvent) -> None: + raise RuntimeError("handler exploded") + + handler = await self._handler_for(nats_client, mock_nats_core, _callback) + + with caplog.at_level("ERROR"): + await handler(MagicMock(data=json.dumps(dict(cloud_event)).encode())) + + assert "Handler failed" in caplog.text + assert cloud_event.id in caplog.text + assert "orders.created" in caplog.text + + async def test_neither_failure_escapes_into_the_broker_callback( + self, nats_client: NATSClient, mock_nats_core: MagicMock, cloud_event: CloudEvent + ) -> None: + async def _callback(event: CloudEvent) -> None: + raise RuntimeError("handler exploded") + + handler = await self._handler_for(nats_client, mock_nats_core, _callback) + + await handler(MagicMock(data=b"garbage")) + await handler(MagicMock(data=json.dumps(dict(cloud_event)).encode())) + + assert nats_client.inflight_handlers == 0 + + async def test_undecodable_payload_releases_the_inflight_slot(self, nats_client: NATSClient, mock_nats_core: MagicMock) -> None: + async def _callback(event: CloudEvent) -> None: + pass + + handler = await self._handler_for(nats_client, mock_nats_core, _callback) + + await handler(MagicMock(data=b"garbage")) + + assert nats_client.inflight_handlers == 0 + + +class TestNATSClientAcknowledgement: + """P2 -- a normal return acks, a raised exception does not (spec sec. 7.2).""" + + @staticmethod + async def _js_handler(nats_client: NATSClient, mock_nats_jetstream: tuple, callback) -> object: + mock_nc, _ = mock_nats_jetstream + nats_client._nats_client = mock_nc + nats_client._client = mock_nc + nats_client._use_jetstream = True + await nats_client._subscribe_one("orders.created", callback) + return mock_nc.jetstream().subscribe_bind.await_args.kwargs["cb"] + + @staticmethod + def _msg(cloud_event: CloudEvent) -> MagicMock: + return MagicMock( + data=json.dumps(dict(cloud_event)).encode(), + reply="$JS.ACK.x", + ack=AsyncMock(), + nak=AsyncMock(), + term=AsyncMock(), + ) + + async def test_normal_return_acks(self, nats_client: NATSClient, mock_nats_jetstream: tuple, cloud_event: CloudEvent) -> None: + handler = await self._js_handler(nats_client, mock_nats_jetstream, AsyncMock()) + msg = self._msg(cloud_event) + await handler(msg) + msg.ack.assert_awaited_once() + msg.nak.assert_not_awaited() + msg.term.assert_not_awaited() + + async def test_no_handler_found_still_acks(self, nats_client: NATSClient, mock_nats_jetstream: tuple, cloud_event: CloudEvent) -> None: + """An unmatched event has nothing to do, and redelivery cannot make a handler appear.""" + handler = await self._js_handler(nats_client, mock_nats_jetstream, AsyncMock(return_value=None)) + msg = self._msg(cloud_event) + await handler(msg) + msg.ack.assert_awaited_once() + + async def test_retryable_error_naks(self, nats_client: NATSClient, mock_nats_jetstream: tuple, cloud_event: CloudEvent) -> None: + async def _callback(event: CloudEvent) -> None: + raise RetryableHandlerError(status="error", reason="upstream down") + + handler = await self._js_handler(nats_client, mock_nats_jetstream, _callback) + msg = self._msg(cloud_event) + await handler(msg) + msg.nak.assert_awaited_once() + msg.ack.assert_not_awaited() + + async def test_invalid_event_error_terms(self, nats_client: NATSClient, mock_nats_jetstream: tuple, cloud_event: CloudEvent) -> None: + async def _callback(event: CloudEvent) -> None: + raise InvalidEventError(status="error", reason="no payload") + + handler = await self._js_handler(nats_client, mock_nats_jetstream, _callback) + msg = self._msg(cloud_event) + await handler(msg) + msg.term.assert_awaited_once() + msg.nak.assert_not_awaited() + + async def test_critical_error_terms(self, nats_client: NATSClient, mock_nats_jetstream: tuple, cloud_event: CloudEvent) -> None: + """A critical error is not made less critical by being delivered again.""" + + async def _callback(event: CloudEvent) -> None: + raise CriticalHandlerError(status="error", reason="corrupt state") + + handler = await self._js_handler(nats_client, mock_nats_jetstream, _callback) + msg = self._msg(cloud_event) + await handler(msg) + msg.term.assert_awaited_once() + + async def test_unexpected_exception_naks(self, nats_client: NATSClient, mock_nats_jetstream: tuple, cloud_event: CloudEvent) -> None: + async def _callback(event: CloudEvent) -> None: + raise RuntimeError("boom") + + handler = await self._js_handler(nats_client, mock_nats_jetstream, _callback) + msg = self._msg(cloud_event) + await handler(msg) + msg.nak.assert_awaited_once() + + async def test_undecodable_payload_terms_without_dispatching(self, nats_client: NATSClient, mock_nats_jetstream: tuple) -> None: + dispatched = [] + handler = await self._js_handler(nats_client, mock_nats_jetstream, lambda e: dispatched.append(e)) + msg = MagicMock(data=b"not json", reply="$JS.ACK.x", ack=AsyncMock(), nak=AsyncMock(), term=AsyncMock()) + await handler(msg) + msg.term.assert_awaited_once() + msg.ack.assert_not_awaited() + assert dispatched == [] + + async def test_core_nats_settles_nothing(self, nats_client: NATSClient, mock_nats_core: MagicMock, cloud_event: CloudEvent) -> None: + """Core NATS is fire-and-forget; msg.ack() would raise NotJSMessageError there.""" + nats_client._nats_client = mock_nats_core + nats_client._client = mock_nats_core + await nats_client._subscribe_one("orders.created", AsyncMock()) + handler = mock_nats_core.subscribe.await_args.kwargs["cb"] + msg = self._msg(cloud_event) + await handler(msg) + msg.ack.assert_not_awaited() + msg.nak.assert_not_awaited() + msg.term.assert_not_awaited() + + async def test_failure_to_ack_does_not_escape_the_callback( + self, nats_client: NATSClient, mock_nats_jetstream: tuple, cloud_event: CloudEvent, caplog: pytest.LogCaptureFixture + ) -> None: + """The ack travels over the delivering connection, so it fails when that is gone.""" + handler = await self._js_handler(nats_client, mock_nats_jetstream, AsyncMock()) + msg = self._msg(cloud_event) + msg.ack = AsyncMock(side_effect=Exception("connection closed")) + with caplog.at_level("ERROR"): + await handler(msg) + assert "Could not ack" in caplog.text + assert nats_client.inflight_handlers == 0 + + async def test_dispatch_failure_log_names_the_disposition( + self, nats_client: NATSClient, mock_nats_jetstream: tuple, cloud_event: CloudEvent, caplog: pytest.LogCaptureFixture + ) -> None: + async def _callback(event: CloudEvent) -> None: + raise InvalidEventError(status="error", reason="no payload") + + handler = await self._js_handler(nats_client, mock_nats_jetstream, _callback) + with caplog.at_level("ERROR"): + await handler(self._msg(cloud_event)) + assert "will term" in caplog.text + assert cloud_event.id in caplog.text + + +class TestNATSClientShutdownDrain: + async def test_close_unsubscribes_when_drain_fails(self, connected_nats_client: NATSClient) -> None: + sub = MagicMock(drain=AsyncMock(side_effect=Exception("broken")), unsubscribe=AsyncMock()) + connected_nats_client._subscriptions = [sub] + + await connected_nats_client.close() + + sub.unsubscribe.assert_awaited_once() + + async def test_close_marks_subscriptions_not_ready(self, connected_nats_client: NATSClient) -> None: + connected_nats_client._subscriptions_ready = True + await connected_nats_client.close() + assert connected_nats_client.subscriptions_ready is False + + async def test_connection_stays_open_until_inflight_handler_finishes( + self, connected_nats_client: NATSClient, mock_nats_core: MagicMock + ) -> None: + connected_nats_client._enter_handler() + connection_closed_during_handler = [] + + async def _finish_handler() -> None: + await asyncio.sleep(0.05) + connection_closed_during_handler.append(mock_nats_core.close.await_count > 0) + connected_nats_client._exit_handler() + + finishing = asyncio.create_task(_finish_handler()) + await connected_nats_client.close() + await finishing + + assert connection_closed_during_handler == [False] + mock_nats_core.close.assert_awaited_once() + + async def test_close_gives_up_after_drain_timeout_and_still_closes( + self, connected_nats_client: NATSClient, mock_nats_core: MagicMock + ) -> None: + connected_nats_client.config.get.side_effect = lambda key, default=None: 0.01 if key == "event_client_drain_timeout" else default + connected_nats_client._enter_handler() + + await connected_nats_client.close() + + assert connected_nats_client.inflight_handlers == 1 + mock_nats_core.close.assert_awaited_once() + + async def test_close_does_not_wait_when_no_handler_is_running(self, connected_nats_client: NATSClient) -> None: + assert connected_nats_client.inflight_handlers == 0 + await asyncio.wait_for(connected_nats_client.close(), timeout=1.0) + + async def test_handler_execution_is_counted_and_released( + self, nats_client: NATSClient, mock_nats_core: MagicMock, cloud_event: CloudEvent + ) -> None: + seen_during_handler = [] + + async def _callback(event: CloudEvent) -> None: + seen_during_handler.append(nats_client.inflight_handlers) + + nats_client._nats_client = mock_nats_core + nats_client._client = mock_nats_core + await nats_client._subscribe_one("orders.created", _callback) + message_handler = mock_nats_core.subscribe.await_args.kwargs["cb"] + + msg = MagicMock(data=json.dumps(dict(cloud_event)).encode()) + await message_handler(msg) + + assert seen_during_handler == [1] + assert nats_client.inflight_handlers == 0 + + async def test_handler_count_is_released_when_callback_raises( + self, nats_client: NATSClient, mock_nats_core: MagicMock, cloud_event: CloudEvent + ) -> None: + async def _callback(event: CloudEvent) -> None: + raise RuntimeError("handler exploded") + + nats_client._nats_client = mock_nats_core + nats_client._client = mock_nats_core + await nats_client._subscribe_one("orders.created", _callback) + message_handler = mock_nats_core.subscribe.await_args.kwargs["cb"] + + await message_handler(MagicMock(data=json.dumps(dict(cloud_event)).encode())) + + assert nats_client.inflight_handlers == 0 + class TestNATSClientPublish: async def test_publish_sends_json_encoded_event_via_core_nats( @@ -170,7 +493,7 @@ async def test_publish_raises_on_nats_error( class TestNATSClientHealthCheck: - async def test_healthy_when_connected(self, connected_nats_client: NATSClient) -> None: + async def test_healthy_when_connected_without_managed_subscriptions(self, connected_nats_client: NATSClient) -> None: result = await connected_nats_client.health_check() assert result.status == "healthy" @@ -187,3 +510,729 @@ async def test_unhealthy_when_client_closed(self, nats_client: NATSClient) -> No nats_client._nats_client = mock_nc result = await nats_client.health_check() assert result.status == "unhealthy" + + async def test_unhealthy_when_connected_but_subscriptions_not_ready(self, connected_nats_client: NATSClient) -> None: + connected_nats_client._subscriptions_managed = True + connected_nats_client._subscriptions_ready = False + result = await connected_nats_client.health_check() + assert result.status == "unhealthy" + assert "subscriptions" in result.message + + async def test_healthy_when_connected_and_subscriptions_ready(self, connected_nats_client: NATSClient) -> None: + connected_nats_client._subscriptions_managed = True + connected_nats_client._subscriptions_ready = True + result = await connected_nats_client.health_check() + assert result.status == "healthy" + + +class TestNATSClientManagedSubscriptions: + async def test_subscribe_stores_mapping_and_starts_task(self, nats_client: NATSClient) -> None: + callback = AsyncMock() + with patch.object(nats_client, "_start_with_retry", new_callable=AsyncMock) as mock_retry: + await nats_client.subscribe({"topic.a": callback}) + assert nats_client._topic_callbacks == {"topic.a": callback} + assert nats_client._subscriptions_managed is True + mock_retry.assert_called_once() # coroutine was created and scheduled, not directly awaited + + async def test_subscribe_returns_immediately(self, nats_client: NATSClient) -> None: + """subscribe() must be non-blocking — the retry runs as a background task.""" + with patch.object(nats_client, "_start_with_retry", new_callable=AsyncMock): + await nats_client.subscribe({"t": AsyncMock()}) + # reaching here means subscribe() returned without awaiting the retry + + async def test_subscriptions_ready_false_before_retry_completes(self, nats_client: NATSClient) -> None: + with patch.object(nats_client, "_start_with_retry", new_callable=AsyncMock): + await nats_client.subscribe({"t": AsyncMock()}) + assert nats_client.subscriptions_ready is False + + +class TestNATSClientQueueGroup: + """P1 -- every Core NATS subscription joins a queue group (spec C1, sec. 7.1).""" + + async def test_core_subscription_passes_queue_group(self, connected_nats_client: NATSClient, mock_nats_core: MagicMock) -> None: + connected_nats_client._queue_group = "test-agent" + await connected_nats_client._subscribe_one("topic.a", AsyncMock()) + assert mock_nats_core.subscribe.await_args.kwargs["queue"] == "test-agent" + + async def test_all_topics_share_one_queue_group(self, connected_nats_client: NATSClient, mock_nats_core: MagicMock) -> None: + connected_nats_client._queue_group = "test-agent" + await connected_nats_client._subscribe_one("topic.a", AsyncMock()) + await connected_nats_client._subscribe_one("topic.b", AsyncMock()) + queues = {call.kwargs["queue"] for call in mock_nats_core.subscribe.await_args_list} + assert queues == {"test-agent"} + + async def test_subscribe_resolves_queue_group_from_app_name(self, nats_client: NATSClient) -> None: + with patch.object(nats_client, "_start_with_retry", new_callable=AsyncMock): + await nats_client.subscribe({"topic.a": AsyncMock()}) + assert nats_client.queue_group == "test-agent" + + async def test_explicit_queue_group_wins_over_app_name(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda key, default=None: {"app_name": "test-agent", "nats_queue_group": "orders"}.get(key, default) + with patch.object(nats_client, "_start_with_retry", new_callable=AsyncMock): + await nats_client.subscribe({"topic.a": AsyncMock()}) + assert nats_client.queue_group == "orders" + + async def test_subscribe_raises_when_no_name_can_be_derived(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda key, default=None: default + with pytest.raises(ValueError, match="queue group"): + await nats_client.subscribe({"topic.a": AsyncMock()}) + + async def test_subscribe_raises_when_configured_name_is_blank(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """A blank name would reach NATS as no queue group at all -- silent fan-out.""" + mock_config.get.side_effect = lambda key, default=None: {"app_name": " ", "nats_queue_group": ""}.get(key, default) + with pytest.raises(ValueError, match="queue group"): + await nats_client.subscribe({"topic.a": AsyncMock()}) + + async def test_whitespace_in_name_raises_instead_of_reaching_nats(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """nats-py rejects a queue name containing a space; an app_name like this was legal before P1.""" + mock_config.get.side_effect = lambda key, default=None: {"app_name": "My Agent Service"}.get(key, default) + with pytest.raises(ValueError, match="whitespace"): + await nats_client.subscribe({"topic.a": AsyncMock()}) + + async def test_whitespace_error_names_the_key_and_value(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda key, default=None: {"app_name": "My Agent Service"}.get(key, default) + with pytest.raises(ValueError, match="'My Agent Service'.*'app_name'"): + await nats_client.subscribe({"topic.a": AsyncMock()}) + + async def test_surrounding_whitespace_is_trimmed_not_rejected(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda key, default=None: {"app_name": " orders "}.get(key, default) + with patch.object(nats_client, "_start_with_retry", new_callable=AsyncMock): + await nats_client.subscribe({"topic.a": AsyncMock()}) + assert nats_client.queue_group == "orders" + + async def test_dots_and_dashes_are_accepted(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """Only whitespace is rejected -- NATS accepts these, and existing app_names use them.""" + mock_config.get.side_effect = lambda key, default=None: {"app_name": "my-agent_service.v1"}.get(key, default) + with patch.object(nats_client, "_start_with_retry", new_callable=AsyncMock): + await nats_client.subscribe({"topic.a": AsyncMock()}) + assert nats_client.queue_group == "my-agent_service.v1" + + async def test_failed_resolution_starts_no_retry_task(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """A config error must fail startup, not spin in the background retry loop forever.""" + mock_config.get.side_effect = lambda key, default=None: default + with pytest.raises(ValueError): + await nats_client.subscribe({"topic.a": AsyncMock()}) + assert nats_client._retry_task is None + + async def test_queue_group_is_empty_before_subscribe(self, nats_client: NATSClient) -> None: + assert nats_client.queue_group == "" + + +# --------------------------------------------------------------------------- +# P3 -- consumer tuning, stream/consumer provisioning, dead-lettering +# --------------------------------------------------------------------------- + +_JS_CONFIG = { + "app_name": "test-agent", + "nats_use_jetstream": True, + "nats_stream_name": "EVENTS", +} + + +def _js_config(**overrides: object): + """Return a config.get side effect with JetStream on and the given keys overridden.""" + merged = {**_JS_CONFIG, **overrides} + return lambda key, default=None: merged.get(key, default) + + +async def _prepare_js_client( + nats_client: NATSClient, + mock_config: MagicMock, + mock_nats_jetstream: tuple, + topics: list[str], + **overrides: object, +) -> MagicMock: + """Run subscribe() so tuning and durables resolve, then attach the JetStream mocks.""" + mock_config.get.side_effect = _js_config(**overrides) + mock_nc, mock_js = mock_nats_jetstream + with patch.object(nats_client, "_start_with_retry", new_callable=AsyncMock): + await nats_client.subscribe({topic: AsyncMock() for topic in topics}) + nats_client._nats_client = mock_nc + nats_client._client = mock_nc + nats_client._use_jetstream = True + return mock_js + + +class TestNATSClientConsumerTuning: + """P3 -- ack_wait, max_ack_pending and max_deliver are configurable (spec sec. 7.3).""" + + async def test_core_nats_resolves_no_tuning(self, nats_client: NATSClient) -> None: + """The settings describe a JetStream consumer; Core NATS has none.""" + with patch.object(nats_client, "_start_with_retry", new_callable=AsyncMock): + await nats_client.subscribe({"topic.a": AsyncMock()}) + assert nats_client.consumer_tuning is None + + async def test_defaults_are_resolved_when_jetstream_is_on( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + assert nats_client.consumer_tuning == ConsumerTuning( + ack_wait=300.0, + max_ack_pending=16, + max_deliver=5, + dead_letter_subject="test-agent.dead-letter", + ) + + async def test_configured_values_win(self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple) -> None: + await _prepare_js_client( + nats_client, + mock_config, + mock_nats_jetstream, + ["orders.created"], + nats_ack_wait=45.0, + nats_max_ack_pending=4, + nats_max_deliver=2, + ) + tuning = nats_client.consumer_tuning + assert (tuning.ack_wait, tuning.max_ack_pending, tuning.max_deliver) == (45.0, 4, 2) + + async def test_zero_ack_wait_raises(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = _js_config(nats_ack_wait=0) + with pytest.raises(ValueError, match="nats_ack_wait"): + await nats_client.subscribe({"orders.created": AsyncMock()}) + + async def test_non_numeric_ack_wait_names_the_key(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = _js_config(nats_ack_wait="soon") + with pytest.raises(ValueError, match="'nats_ack_wait' must be a number"): + await nats_client.subscribe({"orders.created": AsyncMock()}) + + async def test_zero_max_ack_pending_raises(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = _js_config(nats_max_ack_pending=0) + with pytest.raises(ValueError, match="nats_max_ack_pending"): + await nats_client.subscribe({"orders.created": AsyncMock()}) + + async def test_negative_max_ack_pending_other_than_unlimited_raises(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = _js_config(nats_max_ack_pending=-2) + with pytest.raises(ValueError, match="nats_max_ack_pending"): + await nats_client.subscribe({"orders.created": AsyncMock()}) + + async def test_unlimited_max_ack_pending_is_accepted( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"], nats_max_ack_pending=-1) + assert nats_client.consumer_tuning.max_ack_pending == -1 + + async def test_zero_max_deliver_raises(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = _js_config(nats_max_deliver=0) + with pytest.raises(ValueError, match="nats_max_deliver"): + await nats_client.subscribe({"orders.created": AsyncMock()}) + + async def test_unlimited_max_deliver_warns_that_nothing_is_dead_lettered( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, caplog: pytest.LogCaptureFixture + ) -> None: + with caplog.at_level("WARNING"): + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"], nats_max_deliver=-1) + assert "redelivered forever" in caplog.text + + async def test_a_bad_value_starts_no_retry_task(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """Same reason as the queue group: a config error must fail startup, not loop in the background.""" + mock_config.get.side_effect = _js_config(nats_ack_wait=-1) + with pytest.raises(ValueError): + await nats_client.subscribe({"orders.created": AsyncMock()}) + assert nats_client._retry_task is None + + +class TestNATSClientDeadLetterSubject: + """P3 -- where a message goes once the framework gives up on it (spec sec. 7.2).""" + + async def test_defaults_to_the_queue_group(self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple) -> None: + """Derived from the agent's identity, exactly as the queue group is (C1).""" + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"], nats_queue_group="orders-agent") + assert nats_client.consumer_tuning.dead_letter_subject == "orders-agent.dead-letter" + + async def test_configured_subject_wins(self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple) -> None: + await _prepare_js_client( + nats_client, mock_config, mock_nats_jetstream, ["orders.created"], nats_dead_letter_subject="graveyard.orders" + ) + assert nats_client.consumer_tuning.dead_letter_subject == "graveyard.orders" + + async def test_empty_string_disables_dead_lettering( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"], nats_dead_letter_subject="") + assert nats_client.consumer_tuning.dead_letter_subject == "" + + async def test_wildcard_subject_raises(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """It is published to, and a wildcard names no single subject to publish to.""" + mock_config.get.side_effect = _js_config(nats_dead_letter_subject="dead.*") + with pytest.raises(ValueError, match="wildcard"): + await nats_client.subscribe({"orders.created": AsyncMock()}) + + async def test_whitespace_subject_raises(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = _js_config(nats_dead_letter_subject="dead letters") + with pytest.raises(ValueError, match="whitespace"): + await nats_client.subscribe({"orders.created": AsyncMock()}) + + async def test_subject_this_client_subscribes_to_raises(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """Dead-lettering onto a consumed subject turns one failure into an unbounded loop.""" + mock_config.get.side_effect = _js_config(nats_queue_group="orders") + with pytest.raises(ValueError, match="come straight back"): + await nats_client.subscribe({"orders.>": AsyncMock()}) + + def test_subject_match_honours_single_token_wildcard(self, nats_client: NATSClient) -> None: + assert nats_client._subject_matches("orders.*", "orders.created") is True + assert nats_client._subject_matches("orders.*", "orders.created.v1") is False + + def test_subject_match_honours_multi_token_wildcard(self, nats_client: NATSClient) -> None: + assert nats_client._subject_matches("orders.>", "orders.created.v1") is True + assert nats_client._subject_matches("orders.>", "orders") is False + + def test_subject_match_is_exact_without_wildcards(self, nats_client: NATSClient) -> None: + assert nats_client._subject_matches("orders.created", "orders.created") is True + assert nats_client._subject_matches("orders.created", "orders") is False + + +class TestNATSClientDurableNames: + """P3 -- a durable belongs to one filter subject, and NATS restricts what it may be called.""" + + def test_dotted_topic_becomes_a_legal_consumer_name(self, nats_client: NATSClient) -> None: + """NATS rejects '.' in a consumer name, so 'orders.created-durable' never worked.""" + assert nats_client._durable_for("orders.created") == "orders_created-durable" + + def test_wildcards_and_whitespace_are_replaced(self, nats_client: NATSClient) -> None: + assert nats_client._durable_for("orders.*.v1") == "orders___v1-durable" + assert nats_client._durable_for("orders.>") == "orders__-durable" + + async def test_each_topic_gets_its_own_durable( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created", "orders.shipped"]) + assert nats_client._durables == { + "orders.created": "orders_created-durable", + "orders.shipped": "orders_shipped-durable", + } + + async def test_configured_durable_with_several_topics_raises(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = _js_config(nats_durable_name="shared") + with pytest.raises(ValueError, match="one name cannot serve them all"): + await nats_client.subscribe({"orders.created": AsyncMock(), "orders.shipped": AsyncMock()}) + + async def test_configured_durable_with_one_topic_is_used( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"], nats_durable_name="shared") + assert nats_client._durables == {"orders.created": "shared"} + + async def test_topics_colliding_after_sanitising_raise(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """'orders.created' and 'orders_created' both sanitise to one name.""" + mock_config.get.side_effect = _js_config() + with pytest.raises(ValueError, match="both resolve to durable name"): + await nats_client.subscribe({"orders.created": AsyncMock(), "orders_created": AsyncMock()}) + + +class TestNATSClientStreamProvisioning: + """P3 -- the stream must carry every subject a consumer filters on.""" + + async def test_creates_stream_with_the_topic_itself( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + """The old code stored only 'topic.>', which does not cover 'topic'.""" + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + await nats_client._provision_stream() + subjects = mock_js.add_stream.await_args.kwargs["subjects"] + assert "orders.created" in subjects + assert "orders.created.>" in subjects + + async def test_created_stream_carries_the_dead_letter_subject( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + """A dead letter published to a subject no stream captures is not persisted at all.""" + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + await nats_client._provision_stream() + assert "test-agent.dead-letter" in mock_js.add_stream.await_args.kwargs["subjects"] + + async def test_every_topic_reaches_one_stream( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + """Per-topic add_stream calls left every topic after the first uncaptured.""" + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created", "orders.shipped"]) + await nats_client._provision_stream() + subjects = mock_js.add_stream.await_args.kwargs["subjects"] + assert {"orders.created", "orders.shipped"} <= set(subjects) + assert mock_js.add_stream.await_count == 1 + + async def test_wildcard_topic_gets_no_suffixed_form( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + """'orders.>.>' is not a valid subject.""" + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.>"]) + await nats_client._provision_stream() + assert mock_js.add_stream.await_args.kwargs["subjects"] == ["orders.>", "test-agent.dead-letter"] + + async def test_existing_stream_is_widened_not_replaced( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + mock_js.stream_info = AsyncMock(return_value=MagicMock(config=js_api.StreamConfig(name="EVENTS", subjects=["legacy.subject"]))) + await nats_client._provision_stream() + updated = mock_js.update_stream.await_args.args[0].subjects + assert "legacy.subject" in updated + assert "orders.created" in updated + mock_js.add_stream.assert_not_awaited() + + async def test_covered_stream_is_left_alone(self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple) -> None: + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + mock_js.stream_info = AsyncMock( + return_value=MagicMock( + config=js_api.StreamConfig(name="EVENTS", subjects=["orders.created", "orders.created.>", "test-agent.dead-letter"]) + ) + ) + await nats_client._provision_stream() + mock_js.update_stream.assert_not_awaited() + + async def test_failed_widening_is_reported_not_raised( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, caplog: pytest.LogCaptureFixture + ) -> None: + """The consumer bind that follows fails anyway, and names the consumer too.""" + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + mock_js.stream_info = AsyncMock(return_value=MagicMock(config=js_api.StreamConfig(name="EVENTS", subjects=[]))) + mock_js.update_stream = AsyncMock(side_effect=Exception("no permission")) + with caplog.at_level("ERROR"): + await nats_client._provision_stream() + assert "could not be updated" in caplog.text + + async def test_subscribe_all_provisions_before_subscribing( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + await nats_client._subscribe_all() + mock_js.add_stream.assert_awaited_once() + mock_js.subscribe_bind.assert_awaited_once() + + +class TestNATSClientJetStreamConsumer: + """P3 -- the durable is created explicitly so its deliver group and limits are enforced.""" + + async def test_consumer_joins_the_queue_group( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + """A durable without a deliver group hands every message to every replica.""" + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + await nats_client._subscribe_one("orders.created", AsyncMock()) + assert mock_js.add_consumer.await_args.kwargs["config"].deliver_group == "test-agent" + + async def test_consumer_carries_the_tuning(self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple) -> None: + mock_js = await _prepare_js_client( + nats_client, + mock_config, + mock_nats_jetstream, + ["orders.created"], + nats_ack_wait=45.0, + nats_max_ack_pending=4, + nats_max_deliver=2, + ) + await nats_client._subscribe_one("orders.created", AsyncMock()) + config = mock_js.add_consumer.await_args.kwargs["config"] + assert (config.ack_wait, config.max_ack_pending, config.max_deliver) == (45.0, 4, 2) + assert config.filter_subject == "orders.created" + assert config.ack_policy is js_api.AckPolicy.EXPLICIT + + async def test_deliver_subject_is_derived_from_the_durable( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + """Every replica must bind to the same deliver subject, so it cannot be a fresh inbox.""" + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + await nats_client._subscribe_one("orders.created", AsyncMock()) + assert mock_js.add_consumer.await_args.kwargs["config"].deliver_subject == "_DELIVER.orders_created-durable" + + async def test_subscription_binds_to_the_named_consumer( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + await nats_client._subscribe_one("orders.created", AsyncMock()) + kwargs = mock_js.subscribe_bind.await_args.kwargs + assert kwargs["stream"] == "EVENTS" + assert kwargs["consumer"] == "orders_created-durable" + assert kwargs["manual_ack"] is True + + async def test_existing_consumer_is_not_rewritten( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + """A durable's filter and deliver group are broker state; recreating one replays or gaps.""" + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + existing = js_api.ConsumerConfig( + durable_name="orders_created-durable", filter_subject="orders.created", deliver_subject="_DELIVER.old" + ) + mock_js.consumer_info = AsyncMock(return_value=MagicMock(config=existing)) + await nats_client._subscribe_one("orders.created", AsyncMock()) + mock_js.add_consumer.assert_not_awaited() + assert mock_js.subscribe_bind.await_args.kwargs["config"] is existing + + async def test_drift_from_an_existing_consumer_is_reported( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, caplog: pytest.LogCaptureFixture + ) -> None: + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + existing = js_api.ConsumerConfig( + durable_name="orders_created-durable", filter_subject="orders.created", deliver_subject="_DELIVER.old", ack_wait=30.0 + ) + mock_js.consumer_info = AsyncMock(return_value=MagicMock(config=existing)) + with caplog.at_level("WARNING"): + await nats_client._subscribe_one("orders.created", AsyncMock()) + assert "already exists with different settings" in caplog.text + assert "deliver_group" in caplog.text + assert "ack_wait" in caplog.text + + async def test_matching_existing_consumer_is_silent( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, caplog: pytest.LogCaptureFixture + ) -> None: + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + existing = nats_client._consumer_config("orders.created", "orders_created-durable") + mock_js.consumer_info = AsyncMock(return_value=MagicMock(config=existing)) + with caplog.at_level("WARNING"): + await nats_client._subscribe_one("orders.created", AsyncMock()) + assert "already exists" not in caplog.text + + +class TestNATSClientDeadLettering: + """P3 -- a message the framework gives up on keeps its payload (spec sec. 7.2).""" + + @staticmethod + def _msg(payload: bytes, num_delivered: int = 1) -> MagicMock: + return MagicMock( + data=payload, + metadata=MagicMock(num_delivered=num_delivered), + ack=AsyncMock(), + nak=AsyncMock(), + term=AsyncMock(), + ) + + @staticmethod + async def _handler(nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, callback, **overrides): + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"], **overrides) + await nats_client._subscribe_one("orders.created", callback) + mock_nc, _ = mock_nats_jetstream + return mock_nc.jetstream().subscribe_bind.await_args.kwargs["cb"] + + async def test_terminal_failure_is_dead_lettered_then_termed( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + async def _callback(event: CloudEvent) -> None: + raise InvalidEventError(status="error", reason="no payload") + + _, mock_js = mock_nats_jetstream + handler = await self._handler(nats_client, mock_config, mock_nats_jetstream, _callback) + msg = self._msg(json.dumps(dict(cloud_event)).encode()) + await handler(msg) + assert mock_js.publish.await_args.args[0] == "test-agent.dead-letter" + msg.term.assert_awaited_once() + + async def test_original_bytes_are_republished_unchanged( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + """An undecodable payload is exactly the one worth keeping, and it is not a CloudEvent.""" + _, mock_js = mock_nats_jetstream + handler = await self._handler(nats_client, mock_config, mock_nats_jetstream, AsyncMock()) + await handler(self._msg(b"not json")) + assert mock_js.publish.await_args.args[1] == b"not json" + + async def test_headers_name_the_reason_and_origin( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + async def _callback(event: CloudEvent) -> None: + raise CriticalHandlerError(status="error", reason="corrupt state") + + _, mock_js = mock_nats_jetstream + handler = await self._handler(nats_client, mock_config, mock_nats_jetstream, _callback) + await handler(self._msg(json.dumps(dict(cloud_event)).encode(), num_delivered=3)) + headers = mock_js.publish.await_args.kwargs["headers"] + assert headers["Blueprint-Dead-Letter-Reason"] == "terminal-failure" + assert headers["Blueprint-Original-Subject"] == "orders.created" + assert headers["Blueprint-Delivery-Count"] == "3" + assert headers["Blueprint-Event-Id"] == cloud_event.id + + async def test_retry_below_the_limit_naks_without_dead_lettering( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + async def _callback(event: CloudEvent) -> None: + raise RetryableHandlerError(status="error", reason="upstream down") + + _, mock_js = mock_nats_jetstream + handler = await self._handler(nats_client, mock_config, mock_nats_jetstream, _callback, nats_max_deliver=3) + msg = self._msg(json.dumps(dict(cloud_event)).encode(), num_delivered=2) + await handler(msg) + msg.nak.assert_awaited_once() + msg.term.assert_not_awaited() + mock_js.publish.assert_not_awaited() + + async def test_final_attempt_is_dead_lettered_instead_of_naked( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + """Naking the last attempt drops the message silently at max_deliver.""" + + async def _callback(event: CloudEvent) -> None: + raise RetryableHandlerError(status="error", reason="upstream down") + + _, mock_js = mock_nats_jetstream + handler = await self._handler(nats_client, mock_config, mock_nats_jetstream, _callback, nats_max_deliver=3) + msg = self._msg(json.dumps(dict(cloud_event)).encode(), num_delivered=3) + await handler(msg) + msg.nak.assert_not_awaited() + msg.term.assert_awaited_once() + assert mock_js.publish.await_args.kwargs["headers"]["Blueprint-Dead-Letter-Reason"] == "deliveries-exhausted" + + async def test_unlimited_max_deliver_never_exhausts( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + async def _callback(event: CloudEvent) -> None: + raise RetryableHandlerError(status="error", reason="upstream down") + + handler = await self._handler(nats_client, mock_config, mock_nats_jetstream, _callback, nats_max_deliver=-1) + msg = self._msg(json.dumps(dict(cloud_event)).encode(), num_delivered=99) + await handler(msg) + msg.nak.assert_awaited_once() + + async def test_unreadable_metadata_costs_a_retry_not_a_payload( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + async def _callback(event: CloudEvent) -> None: + raise RetryableHandlerError(status="error", reason="upstream down") + + handler = await self._handler(nats_client, mock_config, mock_nats_jetstream, _callback, nats_max_deliver=1) + msg = self._msg(json.dumps(dict(cloud_event)).encode()) + msg.metadata = MagicMock(num_delivered="not a number") + await handler(msg) + msg.nak.assert_awaited_once() + + async def test_disabled_dead_lettering_warns_about_the_lost_payload( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, caplog: pytest.LogCaptureFixture + ) -> None: + _, mock_js = mock_nats_jetstream + handler = await self._handler(nats_client, mock_config, mock_nats_jetstream, AsyncMock(), nats_dead_letter_subject="") + msg = self._msg(b"not json") + with caplog.at_level("WARNING"): + await handler(msg) + assert "payload is lost" in caplog.text + mock_js.publish.assert_not_awaited() + msg.term.assert_awaited_once() + + async def test_failed_republish_still_settles_the_delivery( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, caplog: pytest.LogCaptureFixture + ) -> None: + """Leaving it unsettled would redeliver a message already known to be unprocessable.""" + _, mock_js = mock_nats_jetstream + handler = await self._handler(nats_client, mock_config, mock_nats_jetstream, AsyncMock()) + mock_js.publish = AsyncMock(side_effect=Exception("stream gone")) + msg = self._msg(b"not json") + with caplog.at_level("ERROR"): + await handler(msg) + assert "its payload is lost" in caplog.text + msg.term.assert_awaited_once() + + async def test_a_normal_return_is_never_dead_lettered( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + _, mock_js = mock_nats_jetstream + handler = await self._handler(nats_client, mock_config, mock_nats_jetstream, AsyncMock()) + msg = self._msg(json.dumps(dict(cloud_event)).encode()) + await handler(msg) + msg.ack.assert_awaited_once() + mock_js.publish.assert_not_awaited() + + +class TestNATSClientRetryLoop: + async def test_success_on_first_attempt_sets_ready(self, nats_client: NATSClient) -> None: + nats_client._subscriptions_managed = True + with patch.object(nats_client, "_connect_and_subscribe", new_callable=AsyncMock): + await nats_client._start_with_retry() + assert nats_client.subscriptions_ready is True + + async def test_max_retries_zero_raises_immediately_on_failure(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda k, d=None: {"event_client_max_retries": 0, "event_client_retry_delay": 0.0}.get(k, d) + nats_client._subscriptions_managed = True + with patch.object(nats_client, "_connect_and_subscribe", new_callable=AsyncMock, side_effect=OSError("refused")): + with pytest.raises(OSError, match="refused"): + await nats_client._start_with_retry() + assert nats_client.subscriptions_ready is False + + async def test_max_retries_2_calls_connect_three_times_then_raises(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda k, d=None: {"event_client_max_retries": 2, "event_client_retry_delay": 0.0}.get(k, d) + nats_client._subscriptions_managed = True + mock_connect = AsyncMock(side_effect=OSError("refused")) + with patch.object(nats_client, "_connect_and_subscribe", mock_connect): + with pytest.raises(OSError): + await nats_client._start_with_retry() + assert mock_connect.await_count == 3 + + async def test_max_retries_2_succeeds_on_third_attempt(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda k, d=None: {"event_client_max_retries": 2, "event_client_retry_delay": 0.0}.get(k, d) + nats_client._subscriptions_managed = True + mock_connect = AsyncMock(side_effect=[OSError("fail"), OSError("fail"), None]) + with patch.object(nats_client, "_connect_and_subscribe", mock_connect): + await nats_client._start_with_retry() + assert mock_connect.await_count == 3 + assert nats_client.subscriptions_ready is True + + async def test_done_callback_logs_error_on_permanent_failure(self, nats_client: NATSClient) -> None: + task = MagicMock() + task.cancelled.return_value = False + task.exception.return_value = OSError("final failure") + import logging + + with patch.object(logging.getLogger("blueprint.agents.clients.io.nats_client"), "error") as mock_log: + nats_client._on_retry_done(task) + mock_log.assert_called_once() + + async def test_done_callback_silent_on_cancellation(self, nats_client: NATSClient) -> None: + task = MagicMock() + task.cancelled.return_value = True + import logging + + with patch.object(logging.getLogger("blueprint.agents.clients.io.nats_client"), "error") as mock_log: + nats_client._on_retry_done(task) + mock_log.assert_not_called() + + async def test_broker_connects_but_subscription_fails_leaves_ready_false(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """Connect succeeds; subscribe raises — readiness must stay False.""" + mock_config.get.side_effect = lambda k, d=None: {"event_client_max_retries": 0, "event_client_retry_delay": 0.0}.get(k, d) + nats_client._subscriptions_managed = True + + async def connect_ok_subscribe_fails() -> None: + # Simulate a successful broker connect without a real network call + nats_client._nats_client = MagicMock(is_closed=False, is_connected=True) + nats_client._client = nats_client._nats_client + raise OSError("subscription failed") + + with patch.object(nats_client, "_connect_and_subscribe", side_effect=connect_ok_subscribe_fails): + with pytest.raises(OSError): + await nats_client._start_with_retry() + assert nats_client.subscriptions_ready is False + + +class TestNATSClientReconnect: + async def test_disconnected_callback_clears_ready_flag(self, connected_nats_client: NATSClient) -> None: + connected_nats_client._subscriptions_ready = True + await connected_nats_client._on_disconnected() + assert connected_nats_client.subscriptions_ready is False + + async def test_reconnected_callback_restores_ready_flag_for_core_nats(self, connected_nats_client: NATSClient) -> None: + connected_nats_client._subscriptions_managed = True + connected_nats_client._subscriptions_ready = False + connected_nats_client._use_jetstream = False + await connected_nats_client._on_reconnected() + assert connected_nats_client.subscriptions_ready is True + + async def test_reconnected_callback_no_op_without_managed_subscriptions(self, connected_nats_client: NATSClient) -> None: + connected_nats_client._subscriptions_managed = False + connected_nats_client._subscriptions_ready = False + await connected_nats_client._on_reconnected() + assert connected_nats_client.subscriptions_ready is False + + async def test_reconnected_resubscribes_jetstream_topics(self, connected_nats_client: NATSClient, mock_nats_jetstream: tuple) -> None: + mock_nc, mock_js = mock_nats_jetstream + connected_nats_client._nats_client = mock_nc + connected_nats_client._client = mock_nc + connected_nats_client._use_jetstream = True + connected_nats_client._subscriptions_managed = True + connected_nats_client._subscriptions_ready = False + connected_nats_client._topic_callbacks = {"topic.a": AsyncMock(), "topic.b": AsyncMock()} + + with patch.object(connected_nats_client, "_subscribe_one", new_callable=AsyncMock) as mock_sub: + await connected_nats_client._on_reconnected() + + assert mock_sub.await_count == 2 + assert connected_nats_client.subscriptions_ready is True + + +# --------------------------------------------------------------------------- +# asyncio import needed by the non-blocking subscribe test +# --------------------------------------------------------------------------- diff --git a/tests/unit/agents/io/api/eventing/conftest.py b/tests/unit/agents/io/api/eventing/conftest.py index 19cbca73..295ec8bb 100644 --- a/tests/unit/agents/io/api/eventing/conftest.py +++ b/tests/unit/agents/io/api/eventing/conftest.py @@ -33,8 +33,14 @@ def unhandled_result() -> ProcessingResult: @pytest.fixture -def dapr_eventing(mock_registry: MagicMock) -> DaprEventing: - """DaprEventing instance with a mocked registry.""" +def dapr_eventing(mock_registry: MagicMock, mock_config: MagicMock) -> DaprEventing: + """DaprEventing instance with a mocked registry and a config that yields its defaults. + + The default ``side_effect`` returns whatever default the caller passed, so component + code sees real defaults instead of a truthy MagicMock. Tests that need a specific + value replace the ``side_effect``. + """ + mock_config.get.side_effect = lambda key, default=None: default return DaprEventing() diff --git a/tests/unit/agents/io/api/eventing/test_dapr.py b/tests/unit/agents/io/api/eventing/test_dapr.py index 15d3d9ca..a26bab6c 100644 --- a/tests/unit/agents/io/api/eventing/test_dapr.py +++ b/tests/unit/agents/io/api/eventing/test_dapr.py @@ -2,9 +2,20 @@ from unittest.mock import AsyncMock, MagicMock +import pytest +from fastapi import FastAPI +from httpx import ASGITransport, AsyncClient -from blueprint.agents.io.api.eventing.dapr import DaprEventing -from blueprint.agents.models.errors import CriticalHandlerError, InvalidEventError, RetryableHandlerError +from blueprint.agents.io.api.eventing.dapr import DaprDeliveryRoute, DaprEventing +from blueprint.agents.io.api.eventing.dapr_response import dapr_status +from blueprint.agents.io.api.eventing.nats import NatsEventing +from blueprint.agents.models.errors import ( + CriticalHandlerError, + DeliveryDisposition, + InvalidEventError, + RetryableHandlerError, + disposition_for, +) from blueprint.agents.models.events import CloudEvent from blueprint.agents.models.result import ProcessingResult @@ -27,27 +38,31 @@ async def test_processed_result_returns_success( result = await dapr_eventing.publish("topic", cloud_event) assert result == {"status": "SUCCESS"} - async def test_no_handler_result_returns_retry( + async def test_no_handler_result_returns_success( self, dapr_eventing: DaprEventing, mock_registry: MagicMock, cloud_event: CloudEvent, unhandled_result: ProcessingResult, ) -> None: + """Redelivery cannot make a handler appear, and under a queue group RETRY walks every replica.""" _wire_processing_result(mock_registry, unhandled_result) result = await dapr_eventing.publish("topic", cloud_event) - assert result["status"] == "RETRY" + assert result == {"status": "SUCCESS"} - async def test_no_handler_retry_includes_reason( + async def test_no_handler_result_is_not_reported_as_a_fault( self, dapr_eventing: DaprEventing, mock_registry: MagicMock, cloud_event: CloudEvent, unhandled_result: ProcessingResult, + caplog: pytest.LogCaptureFixture, ) -> None: + """An agent finding no work in an event is normal, not a problem the blueprint reports.""" _wire_processing_result(mock_registry, unhandled_result) - result = await dapr_eventing.publish("topic", cloud_event) - assert "reason" in result + with caplog.at_level("DEBUG"): + await dapr_eventing.publish("topic", cloud_event) + assert [r for r in caplog.records if r.levelname in {"WARNING", "ERROR", "CRITICAL"}] == [] async def test_retryable_error_returns_retry( self, @@ -77,20 +92,303 @@ async def test_invalid_event_error_returns_drop( assert result["status"] == "DROP" assert result["reason"] == "bad schema" - async def test_critical_error_returns_retry( + async def test_critical_error_returns_drop( self, dapr_eventing: DaprEventing, mock_registry: MagicMock, cloud_event: CloudEvent, ) -> None: + """A critical error is not made less critical by being delivered again.""" mock_registry.get_service.return_value.process_event = AsyncMock(side_effect=CriticalHandlerError(status="critical", reason="oom")) mock_registry.correlation_context.set.return_value = MagicMock() result = await dapr_eventing.publish("topic", cloud_event) - assert result["status"] == "RETRY" + assert result["status"] == "DROP" assert result["reason"] == "oom" + async def test_unexpected_exception_returns_retry( + self, + dapr_eventing: DaprEventing, + mock_registry: MagicMock, + cloud_event: CloudEvent, + ) -> None: + """Previously a 500, which left the disposition to the sidecar's own policy.""" + mock_registry.get_service.return_value.process_event = AsyncMock(side_effect=RuntimeError("boom")) + mock_registry.correlation_context.set.return_value = MagicMock() + result = await dapr_eventing.publish("topic", cloud_event) + assert result["status"] == "RETRY" + assert result["reason"] == "boom" + + @pytest.mark.parametrize( + ("error", "expected"), + [ + (RetryableHandlerError(status="e", reason="r"), "RETRY"), + (InvalidEventError(status="e", reason="r"), "DROP"), + (CriticalHandlerError(status="e", reason="r"), "DROP"), + (RuntimeError("boom"), "RETRY"), + ], + ids=["retryable", "invalid", "critical", "unexpected"], + ) + async def test_matches_the_nats_disposition_for_the_same_error( + self, + dapr_eventing: DaprEventing, + mock_registry: MagicMock, + cloud_event: CloudEvent, + error: Exception, + expected: str, + ) -> None: + """Both transports render one shared decision; this pins the rendering.""" + assert dapr_status(disposition_for(error)) == expected + + mock_registry.get_service.return_value.process_event = AsyncMock(side_effect=error) + mock_registry.correlation_context.set.return_value = MagicMock() + result = await dapr_eventing.publish("topic", cloud_event) + assert result["status"] == expected + class TestDaprEventingSubscribe: - async def test_subscribe_returns_empty_dict(self, dapr_eventing: DaprEventing) -> None: - result = await dapr_eventing.subscribe("some-topic") - assert result == {} + async def test_subscription_document_is_empty_without_declarations(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: + mock_registry.get_event_handler.return_value = [] + assert await dapr_eventing.subscribe() == [] + + async def test_subscription_document_lists_declared_topics(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: + handler = MagicMock() + handler.get_subscribed_topics.return_value = ["orders.created", "orders.cancelled"] + mock_registry.get_event_handler.return_value = [handler] + + assert await dapr_eventing.subscribe() == [ + {"pubsubname": "pubsub", "topic": "orders.created", "route": "/events/orders.created"}, + {"pubsubname": "pubsub", "topic": "orders.cancelled", "route": "/events/orders.cancelled"}, + ] + + async def test_subscription_document_deduplicates_across_handlers(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: + first = MagicMock() + first.get_subscribed_topics.return_value = ["orders.created"] + second = MagicMock() + second.get_subscribed_topics.return_value = ["orders.created"] + mock_registry.get_event_handler.return_value = [first, second] + + document = await dapr_eventing.subscribe() + + assert [entry["topic"] for entry in document] == ["orders.created"] + + async def test_subscription_document_uses_configured_pubsub_name(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: + handler = MagicMock() + handler.get_subscribed_topics.return_value = ["orders.created"] + mock_registry.get_event_handler.return_value = [handler] + dapr_eventing.config.get.side_effect = lambda key, default=None: "orders-bus" if key == "dapr_pubsub_name" else default + + document = await dapr_eventing.subscribe() + + assert document[0]["pubsubname"] == "orders-bus" + + async def test_subscription_document_is_empty_when_declared_externally( + self, dapr_eventing: DaprEventing, mock_registry: MagicMock + ) -> None: + handler = MagicMock() + handler.get_subscribed_topics.return_value = ["orders.created"] + mock_registry.get_event_handler.return_value = [handler] + dapr_eventing.config.get.side_effect = lambda key, default=None: True if key == "dapr_declarative_subscriptions" else default + + assert await dapr_eventing.subscribe() == [] + + async def test_sidecar_can_fetch_the_document_without_query_parameters( + self, dapr_eventing: DaprEventing, mock_registry: MagicMock + ) -> None: + """Regression: a required query parameter here answered 422 to every sidecar call.""" + handler = MagicMock() + handler.get_subscribed_topics.return_value = ["orders.created"] + mock_registry.get_event_handler.return_value = [handler] + + app = FastAPI() + app.include_router(dapr_eventing.router) + + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://sidecar") as client: + response = await client.get("/dapr/subscribe") + + assert response.status_code == 200 + assert response.json() == [{"pubsubname": "pubsub", "topic": "orders.created", "route": "/events/orders.created"}] + + +class TestDaprEventingUnparseableDelivery: + """P2 -- a body that cannot become a CloudEvent drops, as it terms under NATS.""" + + @staticmethod + def _app(dapr_eventing: DaprEventing) -> FastAPI: + app = FastAPI() + app.include_router(dapr_eventing.router) + return app + + async def test_malformed_body_answers_drop_not_422(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: + async with AsyncClient(transport=ASGITransport(app=self._app(dapr_eventing)), base_url="http://sidecar") as client: + response = await client.post("/events/orders.created", json={"not": "a cloud event"}) + + assert response.status_code == 200 + assert response.json()["status"] == "DROP" + + async def test_malformed_body_is_not_dispatched(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: + process_event = AsyncMock() + mock_registry.get_service.return_value.process_event = process_event + + async with AsyncClient(transport=ASGITransport(app=self._app(dapr_eventing)), base_url="http://sidecar") as client: + await client.post("/events/orders.created", json={"not": "a cloud event"}) + + process_event.assert_not_awaited() + + async def test_drop_matches_what_nats_does_with_the_same_payload(self, dapr_eventing: DaprEventing) -> None: + """NATS terms an undecodable payload; DROP is the same disposition in Dapr's words.""" + assert dapr_status(DeliveryDisposition.TERM) == "DROP" + + async def test_unparseable_delivery_is_logged( + self, dapr_eventing: DaprEventing, mock_registry: MagicMock, caplog: pytest.LogCaptureFixture + ) -> None: + async with AsyncClient(transport=ASGITransport(app=self._app(dapr_eventing)), base_url="http://sidecar") as client: + with caplog.at_level("ERROR"): + await client.post("/events/orders.created", json={"not": "a cloud event"}) + + assert "unparseable delivery" in caplog.text + + async def test_a_valid_delivery_is_unaffected( + self, dapr_eventing: DaprEventing, mock_registry: MagicMock, cloud_event: CloudEvent, processed_result: ProcessingResult + ) -> None: + _wire_processing_result(mock_registry, processed_result) + + async with AsyncClient(transport=ASGITransport(app=self._app(dapr_eventing)), base_url="http://sidecar") as client: + response = await client.post("/events/orders.created", json=dict(cloud_event)) + + assert response.status_code == 200 + assert response.json() == {"status": "SUCCESS"} + + +class TestDaprEventingManualInjection: + """POST /events/{topic} is also the hand-injection path used when no broker is running. + + The sidecar is one caller of this endpoint; `curl` is another. Nothing on the delivery + path touches the transport client, so an event posted by hand runs the same handler + chain a delivered one does. These tests exist to keep that true -- the endpoint is the + only way to exercise a handler without a broker, and every change to the delivery path + so far has been able to break it. + """ + + @staticmethod + def _app(dapr_eventing: DaprEventing) -> FastAPI: + app = FastAPI() + app.include_router(dapr_eventing.router) + return app + + async def test_no_transport_client_is_needed( + self, dapr_eventing: DaprEventing, mock_registry: MagicMock, cloud_event: CloudEvent, processed_result: ProcessingResult + ) -> None: + """on_startup never ran, so there is no DaprClient -- and the endpoint does not want one.""" + _wire_processing_result(mock_registry, processed_result) + assert dapr_eventing._client is None + + async with AsyncClient(transport=ASGITransport(app=self._app(dapr_eventing)), base_url="http://local") as client: + response = await client.post("/events/orders.created", json=dict(cloud_event)) + + assert response.status_code == 200 + assert response.json() == {"status": "SUCCESS"} + + async def test_the_posted_event_reaches_the_handler_chain( + self, dapr_eventing: DaprEventing, mock_registry: MagicMock, cloud_event: CloudEvent, processed_result: ProcessingResult + ) -> None: + _wire_processing_result(mock_registry, processed_result) + + async with AsyncClient(transport=ASGITransport(app=self._app(dapr_eventing)), base_url="http://local") as client: + await client.post("/events/orders.created", json=dict(cloud_event)) + + dispatched = mock_registry.get_service.return_value.process_event.await_args.args[0] + assert dispatched.id == cloud_event.id + assert dispatched.type == cloud_event.type + + async def test_the_topic_comes_from_the_url( + self, dapr_eventing: DaprEventing, mock_registry: MagicMock, cloud_event: CloudEvent, processed_result: ProcessingResult + ) -> None: + """So posting to a different path exercises a different subscription's handlers.""" + _wire_processing_result(mock_registry, processed_result) + + async with AsyncClient(transport=ASGITransport(app=self._app(dapr_eventing)), base_url="http://local") as client: + await client.post("/events/inventory.updated", json=dict(cloud_event)) + + context = mock_registry.get_service.return_value.process_event.await_args.args[1] + assert context["dapr_topic"] == "inventory.updated" + + async def test_a_handler_failure_is_reported_back_to_the_caller( + self, dapr_eventing: DaprEventing, mock_registry: MagicMock, cloud_event: CloudEvent + ) -> None: + """Injecting by hand is only useful if the response says what the handler did.""" + mock_registry.get_service.return_value.process_event = AsyncMock(side_effect=InvalidEventError(status="error", reason="no payload")) + mock_registry.correlation_context.set.return_value = MagicMock() + + async with AsyncClient(transport=ASGITransport(app=self._app(dapr_eventing)), base_url="http://local") as client: + response = await client.post("/events/orders.created", json=dict(cloud_event)) + + assert response.status_code == 200 + assert response.json() == {"status": "DROP", "reason": "no payload"} + + +class TestRestApiBaseRouteClass: + """The route wrapper must stay scoped to the component that asks for it.""" + + def test_dapr_eventing_uses_the_delivery_route(self, dapr_eventing: DaprEventing) -> None: + assert all(isinstance(route, DaprDeliveryRoute) for route in dapr_eventing.router.routes) + + def test_other_components_keep_the_default_route(self, nats_eventing: NatsEventing) -> None: + assert not any(isinstance(route, DaprDeliveryRoute) for route in nats_eventing.router.routes) + + async def test_an_ordinary_endpoint_still_answers_422(self, nats_eventing: NatsEventing) -> None: + """422 is the right answer for a REST caller; only a Dapr delivery earns DROP.""" + app = FastAPI() + app.include_router(nats_eventing.router) + + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://caller") as client: + response = await client.post("/events/orders.created", json={"not": "a cloud event"}) + + assert response.status_code == 422 + + +class TestDaprEventingOnStartup: + async def test_fetches_dapr_client_from_registry(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client + mock_registry.get_event_handler.return_value = [] + + await dapr_eventing.on_startup() + + assert dapr_eventing._client is mock_client + + async def test_no_handlers_skips_client_subscribe(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client + mock_registry.get_event_handler.return_value = [] + + await dapr_eventing.on_startup() + + mock_client.subscribe.assert_not_called() + + async def test_handler_topics_passed_to_client_subscribe(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: + handler = MagicMock() + handler.get_subscribed_topics.return_value = ["orders.created"] + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client + mock_registry.get_event_handler.return_value = [handler] + + await dapr_eventing.on_startup() + + mock_client.subscribe.assert_awaited_once() + mapping = mock_client.subscribe.call_args[0][0] + assert "orders.created" in mapping + assert callable(mapping["orders.created"]) + + async def test_on_startup_returns_without_raising(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: + """on_startup must return immediately; subscribe() starts a background task.""" + handler = MagicMock() + handler.get_subscribed_topics.return_value = ["t"] + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client + mock_registry.get_event_handler.return_value = [handler] + + await dapr_eventing.on_startup() # must not raise or hang diff --git a/tests/unit/agents/io/api/eventing/test_event_handling_base.py b/tests/unit/agents/io/api/eventing/test_event_handling_base.py index 1529cdf8..f616488d 100644 --- a/tests/unit/agents/io/api/eventing/test_event_handling_base.py +++ b/tests/unit/agents/io/api/eventing/test_event_handling_base.py @@ -1,8 +1,9 @@ """Unit tests for EventHandlingBase._unwrap_nested_cloud_event and handle_event.""" import json -from unittest.mock import AsyncMock, MagicMock +from unittest.mock import AsyncMock, MagicMock, patch +import pytest from blueprint.agents.io.api.eventing.dapr import DaprEventing from blueprint.agents.models.events import CloudEvent @@ -104,28 +105,128 @@ async def test_processed_status_returns_success( result = await dapr_eventing.handle_event("topic", cloud_event) assert result["status"] == "SUCCESS" - async def test_non_processed_status_returns_retry( + async def test_non_processed_status_also_returns_success( self, dapr_eventing: DaprEventing, mock_registry: MagicMock, cloud_event: CloudEvent, unhandled_result: ProcessingResult, ) -> None: + """A handler chain that returned acknowledges whatever its status (spec sec. 7.2).""" mock_registry.get_service.return_value.process_event = AsyncMock(return_value=unhandled_result) mock_registry.correlation_context.set.return_value = MagicMock() result = await dapr_eventing.handle_event("topic", cloud_event) - assert result["status"] == "RETRY" + assert result == {"status": "SUCCESS"} - async def test_retry_result_includes_reason( + async def test_non_processed_status_is_not_reported_as_a_fault( self, dapr_eventing: DaprEventing, mock_registry: MagicMock, cloud_event: CloudEvent, unhandled_result: ProcessingResult, + caplog: pytest.LogCaptureFixture, ) -> None: mock_registry.get_service.return_value.process_event = AsyncMock(return_value=unhandled_result) mock_registry.correlation_context.set.return_value = MagicMock() - result = await dapr_eventing.handle_event("topic", cloud_event) - assert "reason" in result + with caplog.at_level("DEBUG"): + await dapr_eventing.handle_event("topic", cloud_event) + assert [r for r in caplog.records if r.levelname in {"WARNING", "ERROR", "CRITICAL"}] == [] + + async def test_exceptions_are_not_caught_here( + self, + dapr_eventing: DaprEventing, + mock_registry: MagicMock, + cloud_event: CloudEvent, + ) -> None: + """The transport edge classifies failures; catching one here would acknowledge it.""" + mock_registry.get_service.return_value.process_event = AsyncMock(side_effect=RuntimeError("boom")) + mock_registry.correlation_context.set.return_value = MagicMock() + + with pytest.raises(RuntimeError, match="boom"): + await dapr_eventing.handle_event("topic", cloud_event) + + +class TestProcessCloudEventDoesNotLogAndReraise: + """P2 -- the transport edge is the single place that logs a failure and settles it.""" + + async def test_exception_propagates(self, dapr_eventing: DaprEventing, cloud_event: CloudEvent) -> None: + dapr_eventing._dispatch_cloud_event = AsyncMock(side_effect=RuntimeError("boom")) # type: ignore[method-assign] + with pytest.raises(RuntimeError, match="boom"): + await dapr_eventing._process_cloud_event(cloud_event, {}, "orders.created") + + async def test_exception_is_not_logged_here( + self, dapr_eventing: DaprEventing, cloud_event: CloudEvent, caplog: pytest.LogCaptureFixture + ) -> None: + dapr_eventing._dispatch_cloud_event = AsyncMock(side_effect=RuntimeError("boom")) # type: ignore[method-assign] + with caplog.at_level("ERROR"), pytest.raises(RuntimeError): + await dapr_eventing._process_cloud_event(cloud_event, {}, "orders.created") + assert caplog.records == [] + + +class TestUnhandledEventAccounting: + """P2 -- an unmatched event is ordinary: counted for ratio, never reported as a fault.""" + + @staticmethod + def _returning(dapr_eventing: DaprEventing, result: ProcessingResult) -> None: + dapr_eventing._dispatch_cloud_event = AsyncMock(return_value=result) # type: ignore[method-assign] + + async def test_unmatched_event_is_counted( + self, dapr_eventing: DaprEventing, cloud_event: CloudEvent, unhandled_result: ProcessingResult + ) -> None: + self._returning(dapr_eventing, unhandled_result) + + with patch("blueprint.agents.io.api.eventing.event_handling_base._UNHANDLED_EVENTS") as counter: + await dapr_eventing._process_cloud_event(cloud_event, {}, "orders.created") + + counter.add.assert_called_once_with(1, {"namespace": "", "topic": "orders.created"}) + + async def test_matched_event_is_not_counted( + self, dapr_eventing: DaprEventing, cloud_event: CloudEvent, processed_result: ProcessingResult + ) -> None: + self._returning(dapr_eventing, processed_result) + + with patch("blueprint.agents.io.api.eventing.event_handling_base._UNHANDLED_EVENTS") as counter: + await dapr_eventing._process_cloud_event(cloud_event, {}, "orders.created") + + counter.add.assert_not_called() + + async def test_every_unmatched_event_is_counted( + self, dapr_eventing: DaprEventing, cloud_event: CloudEvent, unhandled_result: ProcessingResult + ) -> None: + """The count is read as a ratio against received volume, so it must not be deduplicated.""" + self._returning(dapr_eventing, unhandled_result) + + with patch("blueprint.agents.io.api.eventing.event_handling_base._UNHANDLED_EVENTS") as counter: + for _ in range(5): + await dapr_eventing._process_cloud_event(cloud_event, {}, "orders.created") + + assert counter.add.call_count == 5 + + async def test_unmatched_event_is_not_reported_as_a_fault( + self, + dapr_eventing: DaprEventing, + cloud_event: CloudEvent, + unhandled_result: ProcessingResult, + caplog: pytest.LogCaptureFixture, + ) -> None: + """Finding no work in an event is the handler doing its job, not an error.""" + self._returning(dapr_eventing, unhandled_result) + + with caplog.at_level("DEBUG"): + await dapr_eventing._process_cloud_event(cloud_event, {}, "orders.created") + + assert [r for r in caplog.records if r.levelname in {"WARNING", "ERROR", "CRITICAL"}] == [] + + async def test_many_distinct_topics_leave_no_state_behind( + self, dapr_eventing: DaprEventing, cloud_event: CloudEvent, unhandled_result: ProcessingResult + ) -> None: + """Under Dapr the topic comes from a URL path, so remembering each one is caller-controlled growth.""" + self._returning(dapr_eventing, unhandled_result) + before = len(dapr_eventing.__dict__) + + for index in range(100): + await dapr_eventing._process_cloud_event(cloud_event, {}, f"topic.{index}") + + assert len(dapr_eventing.__dict__) == before diff --git a/tests/unit/agents/io/api/eventing/test_nats.py b/tests/unit/agents/io/api/eventing/test_nats.py index b3a37195..58dd4e60 100644 --- a/tests/unit/agents/io/api/eventing/test_nats.py +++ b/tests/unit/agents/io/api/eventing/test_nats.py @@ -1,32 +1,14 @@ """Unit tests for NatsEventing.""" -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import AsyncMock, MagicMock import pytest from blueprint.agents.io.api.eventing.nats import NatsEventing +from blueprint.agents.models.errors import CriticalHandlerError, InvalidEventError, RetryableHandlerError from blueprint.agents.models.events import CloudEvent -class TestNatsEventingSubscribe: - async def test_subscribe_delegates_to_client(self, connected_nats_eventing: NatsEventing) -> None: - await connected_nats_eventing.subscribe("events.topic") - connected_nats_eventing._client.subscribe.assert_awaited_once() - - async def test_subscribe_passes_correct_topic(self, connected_nats_eventing: NatsEventing) -> None: - await connected_nats_eventing.subscribe("my.topic") - topic_arg = connected_nats_eventing._client.subscribe.call_args[0][0] - assert topic_arg == "my.topic" - - async def test_subscribe_returns_success_message(self, connected_nats_eventing: NatsEventing) -> None: - result = await connected_nats_eventing.subscribe("topic") - assert "Subscribed" in result["message"] or "topic" in result["message"] - - async def test_subscribe_raises_when_client_none(self, nats_eventing: NatsEventing) -> None: - with pytest.raises(RuntimeError, match="NATS client not initialized"): - await nats_eventing.subscribe("topic") - - class TestNatsEventingPublish: async def test_publish_delegates_to_client( self, @@ -64,15 +46,41 @@ async def test_publish_raises_when_client_none( # --------------------------------------------------------------------------- -# on_startup — auto-subscription logic +# on_startup — topic collection and client.subscribe() delegation # --------------------------------------------------------------------------- +class TestNatsEventingPublishIsNotInjection: + """On the NATS transport POST /events/{topic} publishes; it does not inject. + + Worth pinning down, because the same path on DaprEventing dispatches straight into the + handler chain. Here the event goes to the broker and comes back through a subscription, + so this endpoint needs a reachable NATS server -- it is not the no-broker escape hatch + the Dapr one is. + """ + + async def test_the_event_goes_to_the_broker(self, connected_nats_eventing: NatsEventing, cloud_event: CloudEvent) -> None: + await connected_nats_eventing.publish("orders.created", cloud_event) + connected_nats_eventing._client.publish.assert_awaited_once_with("orders.created", cloud_event) + + async def test_the_handler_chain_is_not_called_directly( + self, connected_nats_eventing: NatsEventing, mock_registry: MagicMock, cloud_event: CloudEvent + ) -> None: + await connected_nats_eventing.publish("orders.created", cloud_event) + mock_registry.get_service.assert_not_called() + + async def test_without_a_client_it_says_so(self, nats_eventing: NatsEventing, cloud_event: CloudEvent) -> None: + """A publish before on_startup has no broker connection to use.""" + with pytest.raises(RuntimeError, match="not initialized"): + await nats_eventing.publish("orders.created", cloud_event) + + class TestNatsEventingOnStartup: async def test_fetches_nats_client_from_registry( self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock ) -> None: mock_client = MagicMock() + mock_client.subscribe = AsyncMock() mock_registry.get_component.return_value = mock_client mock_registry.get_event_handler.return_value = [] mock_config.get_nats_subscription_config.return_value = [] @@ -81,88 +89,128 @@ async def test_fetches_nats_client_from_registry( assert nats_eventing._client is mock_client - async def test_no_topics_skips_subscribing(self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock) -> None: - mock_registry.get_component.return_value = MagicMock() + async def test_no_topics_skips_client_subscribe( + self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock + ) -> None: + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client mock_registry.get_event_handler.return_value = [] mock_config.get_nats_subscription_config.return_value = [] - mock_sub = AsyncMock() - with patch.object(nats_eventing, "_subscribe_to_topic", mock_sub): - await nats_eventing.on_startup() - mock_sub.assert_not_called() + await nats_eventing.on_startup() + + mock_client.subscribe.assert_not_called() - async def test_handler_declared_topics_are_subscribed( + async def test_handler_declared_topics_passed_to_client_subscribe( self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock ) -> None: handler = MagicMock() handler.get_subscribed_topics.return_value = ["events.created"] - mock_registry.get_component.return_value = MagicMock() + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client mock_registry.get_event_handler.return_value = [handler] mock_config.get_nats_subscription_config.return_value = [] - mock_sub = AsyncMock() - with patch.object(nats_eventing, "_subscribe_to_topic", mock_sub): - await nats_eventing.on_startup() - mock_sub.assert_awaited_once_with("events.created") + await nats_eventing.on_startup() + + mock_client.subscribe.assert_awaited_once() + mapping = mock_client.subscribe.call_args[0][0] + assert "events.created" in mapping + assert callable(mapping["events.created"]) - async def test_config_declared_topics_are_subscribed( + async def test_config_declared_topics_passed_to_client_subscribe( self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock ) -> None: - mock_registry.get_component.return_value = MagicMock() + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client mock_registry.get_event_handler.return_value = [] mock_config.get_nats_subscription_config.return_value = ["orders.created", "orders.updated"] - mock_sub = AsyncMock() - with patch.object(nats_eventing, "_subscribe_to_topic", mock_sub): - await nats_eventing.on_startup() - assert mock_sub.await_count == 2 + await nats_eventing.on_startup() + + mapping = mock_client.subscribe.call_args[0][0] + assert set(mapping.keys()) == {"orders.created", "orders.updated"} - async def test_duplicate_topic_subscribed_only_once( + async def test_duplicate_topic_appears_once_in_mapping( self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock ) -> None: handler = MagicMock() handler.get_subscribed_topics.return_value = ["shared.topic"] - mock_registry.get_component.return_value = MagicMock() + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client mock_registry.get_event_handler.return_value = [handler] mock_config.get_nats_subscription_config.return_value = ["shared.topic", "other.topic"] - mock_sub = AsyncMock() - with patch.object(nats_eventing, "_subscribe_to_topic", mock_sub): - await nats_eventing.on_startup() - subscribed = [c.args[0] for c in mock_sub.call_args_list] - assert subscribed.count("shared.topic") == 1 - assert "other.topic" in subscribed + await nats_eventing.on_startup() + + mapping = mock_client.subscribe.call_args[0][0] + assert list(mapping.keys()).count("shared.topic") == 1 + assert "other.topic" in mapping async def test_handler_topics_precede_config_topics( self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock ) -> None: handler = MagicMock() handler.get_subscribed_topics.return_value = ["handler.topic"] - mock_registry.get_component.return_value = MagicMock() + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client mock_registry.get_event_handler.return_value = [handler] mock_config.get_nats_subscription_config.return_value = ["config.topic"] - mock_sub = AsyncMock() - with patch.object(nats_eventing, "_subscribe_to_topic", mock_sub): - await nats_eventing.on_startup() - subscribed = [c.args[0] for c in mock_sub.call_args_list] - assert subscribed == ["handler.topic", "config.topic"] + await nats_eventing.on_startup() + mapping = mock_client.subscribe.call_args[0][0] + assert list(mapping.keys()) == ["handler.topic", "config.topic"] -# --------------------------------------------------------------------------- -# _subscribe_to_topic — client guard and delegation -# --------------------------------------------------------------------------- + async def test_on_startup_returns_without_raising_when_client_subscribe_is_non_blocking( + self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock + ) -> None: + """on_startup must return immediately; subscribe() starts a background task.""" + handler = MagicMock() + handler.get_subscribed_topics.return_value = ["t"] + mock_client = MagicMock() + mock_client.subscribe = AsyncMock() + mock_registry.get_component.return_value = mock_client + mock_registry.get_event_handler.return_value = [handler] + mock_config.get_nats_subscription_config.return_value = [] + await nats_eventing.on_startup() # must not raise or hang -class TestSubscribeToTopic: - async def test_raises_when_client_is_none(self, nats_eventing: NatsEventing) -> None: - with pytest.raises(RuntimeError, match="NATS client not initialized"): - await nats_eventing._subscribe_to_topic("events.topic") - async def test_calls_client_subscribe_with_topic_and_callback(self, connected_nats_eventing: NatsEventing) -> None: - await connected_nats_eventing._subscribe_to_topic("test.topic") +# --------------------------------------------------------------------------- +# the callback must let failures reach the transport (spec sec. 7.2) +# --------------------------------------------------------------------------- + - connected_nats_eventing._client.subscribe.assert_awaited_once() - call_args = connected_nats_eventing._client.subscribe.call_args[0] - assert call_args[0] == "test.topic" - assert callable(call_args[1]) +class TestNatsEventingCallbackPropagatesFailures: + """P2 -- catching here would acknowledge a failed event as processed.""" + + @staticmethod + def _callback(nats_eventing: NatsEventing, result_or_error) -> object: + nats_eventing._process_cloud_event = AsyncMock(side_effect=result_or_error) # type: ignore[method-assign] + return nats_eventing._make_event_callback("orders.created") + + @pytest.mark.parametrize( + "error", + [ + RetryableHandlerError(status="e", reason="upstream down"), + InvalidEventError(status="e", reason="no payload"), + CriticalHandlerError(status="e", reason="corrupt state"), + RuntimeError("boom"), + ], + ids=["retryable", "invalid", "critical", "unexpected"], + ) + async def test_handler_errors_reach_the_caller(self, nats_eventing: NatsEventing, cloud_event: CloudEvent, error: Exception) -> None: + callback = self._callback(nats_eventing, error) + with pytest.raises(type(error)): + await callback(cloud_event) + + async def test_successful_dispatch_returns_none(self, nats_eventing: NatsEventing, cloud_event: CloudEvent, processed_result) -> None: + callback = self._callback(nats_eventing, None) + nats_eventing._process_cloud_event = AsyncMock(return_value=processed_result) # type: ignore[method-assign] + assert await callback(cloud_event) is None diff --git a/tests/unit/agents/models/test_errors.py b/tests/unit/agents/models/test_errors.py new file mode 100644 index 00000000..99ba6508 --- /dev/null +++ b/tests/unit/agents/models/test_errors.py @@ -0,0 +1,40 @@ +"""Unit tests for the delivery disposition mapping (spec sec. 7.2).""" + +from blueprint.agents.models.errors import ( + CriticalHandlerError, + DeliveryDisposition, + InvalidEventError, + RetryableHandlerError, + disposition_for, +) + + +class TestDispositionFor: + def test_retryable_error_naks(self) -> None: + assert disposition_for(RetryableHandlerError(status="e", reason="r")) is DeliveryDisposition.NAK + + def test_invalid_event_error_terms(self) -> None: + assert disposition_for(InvalidEventError(status="e", reason="r")) is DeliveryDisposition.TERM + + def test_critical_error_terms(self) -> None: + assert disposition_for(CriticalHandlerError(status="e", reason="r")) is DeliveryDisposition.TERM + + def test_unrecognised_exception_naks(self) -> None: + assert disposition_for(RuntimeError("boom")) is DeliveryDisposition.NAK + + def test_subclass_inherits_its_parents_disposition(self) -> None: + class ProjectSpecificError(InvalidEventError): + pass + + assert disposition_for(ProjectSpecificError(status="e", reason="r")) is DeliveryDisposition.TERM + + def test_never_returns_ack(self) -> None: + """Acknowledgement is what a normal return means; this function only sees failures.""" + failures = [ + RetryableHandlerError(status="e", reason="r"), + InvalidEventError(status="e", reason="r"), + CriticalHandlerError(status="e", reason="r"), + RuntimeError("boom"), + ValueError("nope"), + ] + assert all(disposition_for(exc) is not DeliveryDisposition.ACK for exc in failures) From 54eed9d2c1c59fdfb7b1a81ea187751f74a270c3 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:44:46 +0200 Subject: [PATCH 003/133] feat(eventing): P4, deduplicate events on request and never by default The handler chain skips an event whose id and source it has already dispatched, keyed in the cache under a required TTL. Off unless idempotency_enabled is set, and a failed dispatch releases its claim so the nak's redelivery still runs. Duplicates are counted apart from unmatched events, so a redelivery storm does not read as a namespace subscribed too broadly. The scaffold, the generated settings and asbs validate all make the author decide. Co-Authored-By: Claude Opus 5 (1M context) --- ...26-08-28-multi-agent-grouping-changelog.md | 171 ++++++++++++- .../agent_generator/base_files/settings.txt | 8 + .../base_files/src/handlers/handler.txt | 16 ++ .../agent_generator/claude_docs/CLAUDE.md | 5 + .../agent_generator/cli/commands/validate.py | 65 +++++ src/blueprint/agents/handler/handler_chain.py | 214 +++++++++++++++- .../io/api/eventing/event_handling_base.py | 19 +- .../eventing/event_processing_service.py | 12 +- .../cli/commands/test_validate.py | 48 ++++ .../unit/agents/handler/test_handler_chain.py | 230 +++++++++++++++++- .../api/eventing/test_event_handling_base.py | 73 ++++++ .../unit/agents/services/eventing/conftest.py | 7 +- .../eventing/test_event_processing_service.py | 18 +- 13 files changed, 871 insertions(+), 15 deletions(-) create mode 100644 tests/unit/agent_generator/cli/commands/test_validate.py diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 35f30e5b..9bfb0339 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -71,13 +71,21 @@ Code: - **P3 -- three defects found on the way**: the stream never covered the subject its consumer filtered on, only the first topic was ever added to it, and the derived durable name was illegal for any dotted subject +- **P4 -- opt-in deduplication**: the handler chain skips an event whose id and source it has + already dispatched, keyed in the cache with a required TTL. Off by default, and a failed + dispatch releases its claim so the nak's redelivery still runs +- **P4 -- the author is made to decide**: a `DECIDE:` comment in the scaffolded handler, both + keys in the generated `settings.toml` and `CLAUDE.md`, and an `asbs validate` notice when a + project has handlers and has declared neither +- **P4 -- duplicates are counted apart from unmatched events**: `blueprint.events.duplicate`, + so a redelivery storm does not read as a namespace subscribed too broadly Documentation and process: - Deployment guide now warns that multi-replica is unsafe, and its examples default to one replica (`2d80b63`) - New config keys documented: `event_client_drain_timeout`, `dapr_pubsub_name`, - `dapr_declarative_subscriptions` + `dapr_declarative_subscriptions`, `idempotency_enabled`, `idempotency_ttl` - Feature working rules in `CLAUDE.md`: one reviewable change at a time (`4cf2d51`), and a walkthrough whenever real code is written (`7735251`) @@ -418,7 +426,7 @@ rather than faults, and the acceptance criterion carries the same conditions. A implementation with the tracker, the warning and an accumulating set was replaced rather than committed. -### P3 -- consumer tuning, deliver groups and dead letters +### P3 -- consumer tuning, deliver groups and dead letters (`8ce9600`) Four settings, one object. `ack_wait`, `max_ack_pending`, `max_deliver` and the deliver group all live on `ConsumerConfig`, so the client stops letting `js.subscribe` invent a consumer and builds @@ -488,6 +496,129 @@ The deliver subject is derived from the durable name rather than taken from a fr every replica has to bind to the same one -- two replicas generating random inboxes would define two consumers, which is the fan-out P1 removed. +### P4 -- opt-in deduplication, and the decision forced on the author (`d127843`) + +At-least-once delivery is permanent (spec sec. 7.4). P2 and P3 made acknowledgement correct, which +narrows redelivery to the cases where it is unavoidable -- a lost ack, a pod restart, a rolling +deploy -- but does not remove them: a handler that finishes 60 s of inference and then cannot ack +has already committed its side effects, and the broker sends the event again. Whether replaying +those side effects is *correct* is a property of the product, not of the framework, so P4 provides +the mechanism and refuses to make the choice. + +**The chain claims before it dispatches.** `HandlerChain.process` no longer runs the handler loop +directly; it calls `_claim`, and only then `_dispatch` (the loop, moved verbatim). `_claim` returns +whether to dispatch: with dedup off it always returns `True`, and with dedup on it asks the cache +whether a marker for this event exists, writes one with the configured TTL if it does not, and +returns `False` if it does. A `False` makes `process` set `DUPLICATE_CONTEXT_KEY` in the context, +stamp `event.duplicate` on the span, and return `None` without touching a handler. + +**A failed dispatch releases the claim.** This is the part that is easy to leave out and expensive +to leave out: + +```python +try: + return await self._dispatch(event, context) +except Exception: + self._release(event, policy) + raise +``` + +The claim has to be taken *before* dispatch -- that is the only point at which it can stop a +concurrent duplicate -- which means a dispatch that raises has left a marker behind for an event +that was never processed. The exception it re-raises is what P2 turns into a nak, and the broker +sends the same event back. Without `_release`, that redelivery is swallowed as a duplicate, and so +is the next one, until `max_deliver` is exhausted and the message is dead-lettered having never +reached a handler. The test that pins this asserts the handler is entered on both attempts. + +**The key carries the source as well as the id.** `_idempotency_key` returns +`{"id": ..., "source": ...}`. The spec says "keyed on the CloudEvent `id`", but the CloudEvents +specification requires an id to be unique only *within* a source, so two producers may both legally +emit id `"1"` and keying on the id alone would let one publisher's event suppress another's. It is +sent as a dict because the cache sorts a dict by key before hashing it, which a two-element list -- +which the cache sorts by *value* -- would not preserve. An event missing either field is dispatched +untracked with a warning rather than dropped. + +**`idempotency_ttl` is required, and deliberately has no default.** `_resolve_idempotency_policy` +raises at startup if dedup is enabled without it. The window has to outlast the redelivery window it +exists to cover -- `nats_ack_wait * nats_max_deliver` under JetStream, whatever the component's +retry policy says under Dapr -- and neither number is one the dispatch layer can read without +reaching into a transport it must not know about. A default here would ship a dedup window that +silently expires before the last redelivery arrives, which presents exactly like dedup not working +at all. So enabling dedup is two keys, and the second one is the decision spec sec. 7.4 asks the +author to make. The same method rejects a non-boolean `idempotency_enabled`, a non-positive or +non-numeric TTL, and -- the one that would otherwise fail silently -- dedup enabled with no cache +registered, where there is nowhere to keep the markers. + +**Startup runs, because something now calls it.** `HandlerChain` is created by +`EventProcessingService` with `should_register=False`, so nothing in the lifespan ever called its +lifecycle hooks; its `on_startup` was a no-op and could stay one. It resolves the policy now, so +`EventProcessingService.on_startup`/`on_shutdown` delegate to the chain -- a bad dedup setting has +to fail the pod, not the first event that arrives on it. `process` also resolves the policy on first +use if startup never ran, because a chain constructed outside `AppBuilder` inheriting "dedup is off" +from a missed wiring step is the one failure this feature must not have. + +**A duplicate is counted apart from an unmatched event.** At the transport edge, +`_process_cloud_event` checks the context flag before it looks at the status: + +```python +if context.get(DUPLICATE_CONTEXT_KEY): + _DUPLICATE_EVENTS.add(1, {"namespace": self.ROOT_NAMESPACE, "topic": topic}) +elif processing_result.status is ProcessingStatus.NO_HANDLER_FOUND: + _UNHANDLED_EVENTS.add(1, {"namespace": self.ROOT_NAMESPACE, "topic": topic}) +``` + +A deduplicated event arrives here looking exactly like an unmatched one -- no handler ran, so no +result came back -- but the two say opposite things about the subscription. An unmatched event is +one this namespace had no use for, and `blueprint.events.unhandled` is read as a ratio to spot a +namespace subscribed too broadly (spec sec. 7.7); a duplicate is an event it *did* use, once. +Counting them together would make a redelivery storm read as a bad subscription. The flag travels in +`context` rather than as a third `ProcessingStatus` value because that enum is normative in spec +sec. 7.2 -- it carries two values precisely so that no failure can reach the transport as a returned +value, and adding to it invites exactly that. `context` is already the channel handlers use to pass +information along the chain, and it is mutated in place all the way down. + +**Both dispositions are unchanged.** A duplicate acks, like any completed dispatch. Redelivering it +forever would be the one outcome worse than processing it twice. + +**The claim is not a lock, and this is written into the class docstring.** `exists` then `set` is +not atomic on either cache backend, so two replicas handed the same event at the same instant can +both pass the check; a cache that is unreachable fails open, because both `DiskCacheService` and +`RedisCacheService` swallow their own errors and return `False`/`None`. Dedup narrows the duplicate +window, it does not close it, and a handler whose side effects must never repeat still needs its own +reconciliation. The cache calls are also synchronous inside an async method, like every other cache +call in the framework today; phase 2 moves them onto the namespace executor. + +**Surfacing the requirement (spec sec. 7.4, the second half).** The mechanism is only half of P4 -- +the author has to be told the choice exists: + +- **Scaffolded handler** (`base_files/src/handlers/handler.txt`): a `DECIDE:` comment at the top of + `handle_event` explaining that redelivery is normal behaviour rather than an edge case, naming + both ways out (write a repeatable handler, or set the two keys), and asking to be deleted once the + decision is made. `asbs setup` and `asbs create handler` share this template, so one edit covers + both. +- **Generated `settings.toml`** (`base_files/settings.txt`): both keys, commented, inside `[default]` + -- not after `[default.logging]`, where uncommenting them would silently put them in the wrong + table. +- **Generated project docs** (`claude_docs/CLAUDE.md`): a bullet under EventHandler and the two keys + in the settings example. +- **`asbs validate`**: a new `Notices` section. `_idempotency_notice` reports when a project has + handlers and its `settings.toml` does not declare `idempotency_enabled` -- in any environment + table, since dynaconf environments are top-level tables. Declaring it `false` silences the notice + as much as `true` does: the point is that a decision was made, not which one. A project with no + handlers is not notified, and an unparseable `settings.toml` is left to the check that already + reports it rather than guessed at. + +There is no generated README to put the spec's third line in -- `asbs setup` does not write one -- +so the generated `CLAUDE.md` and `settings.toml` carry it instead. Listed under *Open points*. + +Tests: dedup off by default and repeat deliveries dispatching twice; the same event dispatching once +and the second delivery flagged in context; the claim written with the configured TTL into its own +cache namespace; the same id from a different source not being a duplicate; a failed dispatch +releasing the claim and the retry reaching the handler; an event missing a source dispatching +untracked; six policy-resolution failures and the string form an environment variable delivers; the +duplicate counter firing while the unhandled counter does not, and the reverse; and seven cases for +the `asbs validate` notice. + ### Deployment guide corrected (`2d80b63`) The guide recommended `replicaCount: 2`, an HPA, and `--set replicaCount=3` as ordinary scaling. It @@ -587,6 +718,22 @@ No breaking change has landed. Specifically: the client publishes to `.dead-letter`. A deployment whose broker permissions allow publishing only to specific subjects has to grant that one, or set `nats_dead_letter_subject = ""`. +- **P4 changes nothing for a project that does not opt in.** `idempotency_enabled` defaults to + `false`, and with it off `_claim` returns immediately and the cache is never touched. The handler + loop itself is unchanged -- it moved from `process` into `_dispatch` verbatim. +- **`EventProcessingService.on_startup` and `on_shutdown` are no longer no-ops.** They delegate to + the handler chain's hooks. A subclass overriding either without calling `super()` now skips the + chain's startup, and with dedup enabled would run with an unresolved policy -- which `process` + then resolves on first use, so it degrades to a late error rather than a silent one. +- **Enabling dedup without `idempotency_ttl`, or without a cache, fails at startup.** Both are + deliberate: the first is the decision the spec requires the author to make, and the second would + otherwise disable dedup silently at the moment it was switched on. +- **`blueprint.events.duplicate` is a new counter.** `blueprint.events.unhandled` no longer counts a + deduplicated event, but it could not have: nothing could be deduplicated before this change. +- **The `idempotency` cache namespace is new.** It shares the registered cache with application + data but not its namespace, so nothing an application stores can collide with a marker. A + deployment sizing its cache should account for one small entry per event within the TTL window. + The spec's one deliberate future break is `with_cache`'s `name` parameter (sec. 10.1), which must stay keyword-only and last, or an existing `with_cache(False)` would silently become a cache named `False`. @@ -595,7 +742,25 @@ stay keyword-only and last, or an existing `with_cache(False)` would silently be ## Open points -- **P4-P6 remain**, starting with P4 (opt-in idempotency). P0-P3 have all landed. +- **P5-P6 remain**, starting with P5 (cron as an event source, #73). P0-P4 have all landed. +- **There is no generated README**, so the third surfacing channel spec sec. 7.4 asks for has + nowhere to go. `asbs setup` writes a Dockerfile, settings, secrets and source, and the + generated `CLAUDE.md` and `settings.toml` carry the idempotency note instead. If a README is + ever generated, the note belongs in it too. +- **Dedup is best-effort and unverified against a real broker.** `exists` then `set` is not + atomic on either cache backend, so two replicas handed the same event simultaneously can both + dispatch, and a cache error fails open. Whether that window is ever hit in practice depends on + how the broker distributes a redelivery, which belongs on the broker-test list below. A + compare-and-set primitive on `CacheService` (Redis `SET NX`) would close most of it and is not + written yet. +- **Nothing bounds the dedup cache.** Every dispatched event writes one entry for `idempotency_ttl` + seconds. `DiskCacheService` expires lazily -- an entry is removed when it is next read, so + markers nobody asks about again stay on disk. A long TTL on a high-volume topic grows the cache + directory without limit, and no metric reports its size. +- **The dedup TTL question in spec sec. 13 is not answered, it is delegated.** Requiring the key + puts the number in the deployment that knows its own redelivery window; it does not tell that + deployment what the number is. Guidance -- worked from `nats_ack_wait * nats_max_deliver` -- + belongs in the deployment guide and is not written. - **The dead-letter subject has no consumer.** Messages accumulate on it and are subject to the stream's retention, so a deployment that never reads it will silently lose dead letters when the stream ages them out. Draining it is an operational task the framework does not do, and no diff --git a/src/blueprint/agent_generator/base_files/settings.txt b/src/blueprint/agent_generator/base_files/settings.txt index b2c1b3ee..a69295c1 100644 --- a/src/blueprint/agent_generator/base_files/settings.txt +++ b/src/blueprint/agent_generator/base_files/settings.txt @@ -6,6 +6,14 @@ debug = true model_provider = "vllm" model_base_url = "https://avs-vllm.q14.net/v1" +# Event deduplication is off by default: a handler may be run more than once for the +# same event, because delivery is at-least-once and an acknowledgement can always be +# lost. Turn it on only after deciding it is what your handlers need -- see the DECIDE +# comment in src/handlers/. idempotency_ttl is required when it is enabled, and must +# outlast the broker redelivery window (nats_ack_wait * nats_max_deliver on JetStream). +# idempotency_enabled = true +# idempotency_ttl = 1500 + [default.logging] level = "DEBUG" format = "json" diff --git a/src/blueprint/agent_generator/base_files/src/handlers/handler.txt b/src/blueprint/agent_generator/base_files/src/handlers/handler.txt index ae1095c6..a5d731c4 100644 --- a/src/blueprint/agent_generator/base_files/src/handlers/handler.txt +++ b/src/blueprint/agent_generator/base_files/src/handlers/handler.txt @@ -47,6 +47,22 @@ on_shutdown Returns: HandlerResult: The resulting event to publish, when the handlers work is done. """ + # DECIDE: can this handler run twice on the same event? + # + # Delivery is at-least-once. A redelivery arrives whenever an acknowledgement is + # lost -- a pod restart, a rolling deploy, a connection blip mid-handler -- and the + # side effects of the first attempt have already happened by then. Running twice is + # not an edge case; it is the normal behaviour of the transport. + # + # Either make this method safe to repeat (upsert instead of insert, key the outbound + # request on event.id, check before you charge), or switch the framework dedup on: + # + # settings.toml + # idempotency_enabled = true + # idempotency_ttl = 1500 # seconds; must outlast the redelivery window + # + # Dedup keys on the event id and source and is best-effort: it narrows the window, + # it does not close it. Whichever you choose, delete this comment once you have. logger.info("MyHandler processing event '%s'", event.type) raise NotImplementedError() diff --git a/src/blueprint/agent_generator/claude_docs/CLAUDE.md b/src/blueprint/agent_generator/claude_docs/CLAUDE.md index b7f30aef..5c07146c 100644 --- a/src/blueprint/agent_generator/claude_docs/CLAUDE.md +++ b/src/blueprint/agent_generator/claude_docs/CLAUDE.md @@ -89,6 +89,7 @@ class OrderHandler(EventHandlerBase): ``` - Return `None` → pass to next handler. Return `HandlerResult` → publish event, stop chain. +- **Delivery is at-least-once.** The same event can reach `handle_event` more than once (lost ack, pod restart, rolling deploy). Either make the method safe to repeat, or set `idempotency_enabled = true` **and** `idempotency_ttl = ` in `settings.toml` -- the framework then skips an event whose id and source it has already dispatched, within that window. Off by default on purpose: only you know whether replaying your side effects is acceptable. - **`self.extract_payload(event, ModelType)`** — validates `event.data` against a Pydantic model and returns a typed instance. Raises `InvalidEventError` if data is missing or invalid (the framework handles this automatically). ### Service @@ -213,6 +214,10 @@ model_provider = "openai" model_name = "gpt-4" model_max_tokens = 2000 +# Event deduplication -- off by default, both keys required to switch it on. +# idempotency_enabled = true +# idempotency_ttl = 1500 # seconds; must outlast the broker redelivery window + [default.runtimes.my_agent] # Per-agent overrides model_name = "gpt-4-turbo" model_temperature = 0.5 diff --git a/src/blueprint/agent_generator/cli/commands/validate.py b/src/blueprint/agent_generator/cli/commands/validate.py index 46f57f7f..7972c88f 100644 --- a/src/blueprint/agent_generator/cli/commands/validate.py +++ b/src/blueprint/agent_generator/cli/commands/validate.py @@ -2,11 +2,26 @@ import logging import sys +import tomllib from argparse import Namespace from pathlib import Path +from typing import Any logger = logging.getLogger(__name__) +IDEMPOTENCY_NOTICE = "\n".join( + [ + "Event deduplication is off ('idempotency_enabled' is not set), so every handler in", + " this project can be run more than once for the same event. Delivery is at-least-once:", + " a lost acknowledgement, a pod restart or a rolling deploy each produce a redelivery,", + " after the first attempt has already committed its side effects.", + " Decide which one this project needs:", + " - handlers that are safe to repeat -- nothing to change; or", + " - set 'idempotency_enabled = true' and 'idempotency_ttl = ' in settings.toml,", + " with a window that outlasts the broker redelivery window.", + ] +) + def run(args: Namespace) -> None: """Execute the validate command. @@ -25,6 +40,7 @@ def run(args: Namespace) -> None: issues = [] warnings = [] + notices = [] # Check for required directories required_dirs = ["src", "tests"] @@ -98,10 +114,21 @@ def run(args: Namespace) -> None: if docker_compose.is_file(): print("✓ Found docker-compose.yml") + # Idempotency decision (spec sec. 7.4): the framework must not choose for the author, + # so it says nothing at all only when the project has no handlers to run twice. + notice = _idempotency_notice(project_dir) + if notice: + notices.append(notice) + # Print summary print() print("=" * 60) + if notices: + print(f"\nNotices ({len(notices)}):") + for item in notices: + print(f" - {item}") + if not issues and not warnings: print("✓ Validation passed! Project structure looks good.") sys.exit(0) @@ -120,3 +147,41 @@ def run(args: Namespace) -> None: else: print("\n✓ Validation passed with warnings.") sys.exit(0) + + +def _idempotency_notice(project_dir: Path) -> str | None: + """Return the dedup notice if this project has handlers and has not opted into dedup. + + Returns ``None`` when the project declares ``idempotency_enabled``, whichever way it + declares it: the author has then made the decision spec sec. 7.4 asks for, and saying + it again on every run is how a notice stops being read. Also ``None`` when there are no + handlers, since nothing can be dispatched twice. + """ + handlers_dir = project_dir / "src" / "handlers" + if not handlers_dir.is_dir() or not any(handlers_dir.glob("*_handler.py")): + return None + + settings_file = project_dir / "settings.toml" + if not settings_file.is_file(): + return IDEMPOTENCY_NOTICE + + try: + with settings_file.open("rb") as handle: + settings = tomllib.load(handle) + except (OSError, tomllib.TOMLDecodeError) as exc: + # A settings file that cannot be read is reported by its own check; guessing at the + # dedup setting from an unparseable file would be worse than staying quiet. + logger.debug("Could not read settings.toml for the idempotency check: %s", exc) + return None + + # Dynaconf environments are top-level tables, and the key is valid in any of them. + if _declares_idempotency(settings): + return None + return IDEMPOTENCY_NOTICE + + +def _declares_idempotency(settings: dict[str, Any]) -> bool: + """Report whether ``idempotency_enabled`` appears at the top level or in any environment.""" + if "idempotency_enabled" in settings: + return True + return any(isinstance(value, dict) and "idempotency_enabled" in value for value in settings.values()) diff --git a/src/blueprint/agents/handler/handler_chain.py b/src/blueprint/agents/handler/handler_chain.py index e0fdfdba..1999acfc 100644 --- a/src/blueprint/agents/handler/handler_chain.py +++ b/src/blueprint/agents/handler/handler_chain.py @@ -1,6 +1,8 @@ """Handler chain for executing event handlers in priority order.""" import logging +import time +from dataclasses import dataclass from typing import Any from opentelemetry import trace @@ -10,6 +12,32 @@ logger = logging.getLogger(__name__) +DUPLICATE_CONTEXT_KEY = "idempotency_duplicate" +"""Context key set to ``True`` when dispatch was skipped because the event was seen before. + +The chain returns ``None`` for a duplicate exactly as it does for an event no handler +wanted, and both acknowledge -- but they are not the same outcome, and the transport edge +counts them apart. It travels in ``context`` rather than in ``ProcessingStatus`` because +that enum is normative in spec sec. 7.2: it carries two values so that no failure can +reach the transport as a returned value, and a third one would invite exactly that. +""" + +IDEMPOTENCY_CACHE_NAMESPACE = "idempotency" +"""Cache namespace holding the seen-event markers, kept away from application data.""" + + +@dataclass(frozen=True) +class IdempotencyPolicy: + """Resolved dedup settings (spec sec. 7.4). + + ``ttl`` is meaningless while ``enabled`` is ``False`` and is then zero. The two are + held together because a dedup window without a lifetime is not a policy: entries that + never expire turn the cache into an unbounded log of every event the agent ever saw. + """ + + enabled: bool + ttl: int + class HandlerChain(Component): """Executes registered event handlers in priority order. @@ -18,14 +46,42 @@ class HandlerChain(Component): through them using the chain-of-responsibility pattern. Stops at the first handler that returns a non-None result. Re-raises any exception from handler execution. + + Idempotency + ~~~~~~~~~~~ + At-least-once delivery is permanent (spec sec. 7.4): a handler that finishes and then + cannot acknowledge has already committed its side effects, and the broker redelivers. + Whether replaying that is *correct* is a property of the product, not of the framework, + so dedup is opt-in and off by default -- ``idempotency_enabled``, with the window in + ``idempotency_ttl``. + + When it is on, the chain claims a marker keyed on the event before dispatching and + skips the dispatch if the marker is already there. A failed dispatch releases the + claim, because the failure naks and the redelivery must be allowed to run: a claim + kept across a failure would turn every retry into a silent no-op. + + The claim is check-then-set, not a lock. Two replicas handed the same event at the + same instant can both pass the check, and a cache that is unreachable fails open -- + both dispatch. This narrows the duplicate window; it does not close it, and a handler + whose side effects must never repeat still needs its own reconciliation. + + Config keys + ~~~~~~~~~~~ + ``idempotency_enabled`` (bool, default ``False``): opt into dedup. + ``idempotency_ttl`` (int, no default): seconds a seen-event marker is kept. Required + when dedup is enabled, and deliberately without a default -- see ``_resolve_idempotency_policy``. """ def __init__(self) -> None: """Initialize the handler chain.""" super().__init__(should_register=False) + self._policy: IdempotencyPolicy | None = None async def on_startup(self) -> None: - """No startup actions required.""" + """Resolve the idempotency policy so a bad setting fails startup, not a delivery.""" + self._policy = self._resolve_idempotency_policy() + if self._policy.enabled: + logger.info("Event deduplication is enabled with a %d second window", self._policy.ttl) async def on_shutdown(self) -> None: """No shutdown actions required.""" @@ -39,11 +95,37 @@ async def process(self, event: CloudEvent[Any], context: dict[str, Any]) -> Any context: Processing context dictionary Returns: - Result from first handler that returns non-None, or None + Result from first handler that returns non-None, or None -- including when the + event was already seen and dispatch was skipped Raises: Exception: Re-raises any exception from handler execution """ + # Resolved here as well as in on_startup because a chain used outside AppBuilder + # never has its startup called, and inheriting "dedup is off" from a missed wiring + # step is the one failure this feature must not have. + policy = self._policy + if policy is None: + policy = self._policy = self._resolve_idempotency_policy() + + if not self._claim(event, policy): + context[DUPLICATE_CONTEXT_KEY] = True + trace.get_current_span().set_attribute("event.duplicate", True) + logger.info("Skipping event '%s' from '%s': already processed within the dedup window", event.id, event.source) + return None + + try: + return await self._dispatch(event, context) + except Exception: + self._release(event, policy) + raise + + # ------------------------------------------------------------------ + # Dispatch + # ------------------------------------------------------------------ + + async def _dispatch(self, event: CloudEvent[Any], context: dict[str, Any]) -> Any | HandlerResult | list[HandlerResult] | None: + """Run the registered handlers in priority order until one returns a result.""" handlers = sorted(self.registry.get_event_handler()) span = trace.get_current_span() span.set_attribute("handlers.count", len(handlers)) @@ -67,3 +149,131 @@ async def process(self, event: CloudEvent[Any], context: dict[str, Any]) -> Any logger.warning("No handler processed event '%s'", event.type) return None + + # ------------------------------------------------------------------ + # Idempotency (P4) + # ------------------------------------------------------------------ + + def _claim(self, event: CloudEvent[Any], policy: IdempotencyPolicy) -> bool: + """Record that this event is being processed, and report whether to dispatch it. + + Returns: + ``True`` if the event should be dispatched -- dedup is off, the event cannot be + keyed, or this is the first time it has been seen. ``False`` if a marker for it + is already in the cache, meaning some earlier delivery already ran the chain. + """ + if not policy.enabled: + return True + + key = self._idempotency_key(event) + if key is None: + return True + + cache = self.registry.cache_service + if cache.exists(key, namespace=IDEMPOTENCY_CACHE_NAMESPACE): + return False + + cache.set( + key, + {"seen_at": time.time(), "event_type": event.type}, + namespace=IDEMPOTENCY_CACHE_NAMESPACE, + ttl=policy.ttl, + ) + return True + + def _release(self, event: CloudEvent[Any], policy: IdempotencyPolicy) -> None: + """Drop the marker after a failed dispatch so the redelivery is allowed to run. + + The claim is taken before dispatch, which is the only point at which it can stop a + concurrent duplicate. That means a dispatch that raises leaves a marker behind for + an event that was *not* processed, and the nak this failure produces sends the very + same event back. Without this the retry would be swallowed as a duplicate and the + message would be lost after ``max_deliver`` attempts that never ran a handler. + """ + if not policy.enabled: + return + + key = self._idempotency_key(event) + if key is None: + return + + self.registry.cache_service.delete(key, namespace=IDEMPOTENCY_CACHE_NAMESPACE) + logger.debug("Released the dedup marker for event '%s' after a failed dispatch", event.id) + + @staticmethod + def _idempotency_key(event: CloudEvent[Any]) -> dict[str, str] | None: + """Build the dedup key, or ``None`` if the event cannot be identified. + + Keyed on ``source`` as well as ``id``. The CloudEvents specification requires an + ``id`` to be unique only *within* a source, so two producers may legitimately both + emit id ``"1"``, and keying on the id alone would let one agent's event suppress + another's. Sent as a dict because the cache sorts a dict by key before hashing it, + which a list of the two values would not preserve. + """ + event_id = str(getattr(event, "id", "") or "").strip() + source = str(getattr(event, "source", "") or "").strip() + if not event_id or not source: + logger.warning( + "Cannot deduplicate an event without both an id and a source (id=%r, source=%r); dispatching it", + event_id, + source, + ) + return None + return {"id": event_id, "source": source} + + def _resolve_idempotency_policy(self) -> IdempotencyPolicy: + """Read and validate the dedup settings (spec sec. 7.4). + + ``idempotency_ttl`` has no default on purpose. The window has to outlast the + redelivery window it is there to cover -- under JetStream that is + ``nats_ack_wait * nats_max_deliver``, under Dapr it is whatever the component's + retry policy says -- and neither number is one this layer can read. Choosing a + value here would mean shipping a dedup window that silently expires before the last + redelivery arrives, which looks exactly like dedup not working. Enabling dedup is + therefore two keys, and the second one is the decision spec sec. 7.4 requires the + author to make. + + Raises: + ValueError: if ``idempotency_enabled`` is not a boolean, if it is on without a + positive ``idempotency_ttl``, or if it is on with no cache registered -- + there would be nowhere to keep the markers, and dedup would be silently off. + """ + enabled = self._read_bool("idempotency_enabled", False) + if not enabled: + return IdempotencyPolicy(enabled=False, ttl=0) + + raw_ttl = self.config.get("idempotency_ttl", None) + if raw_ttl is None: + raise ValueError( + "'idempotency_enabled' is true but 'idempotency_ttl' is not set. It is the number of " + "seconds a processed event is remembered, and it must outlast the broker's redelivery " + "window ('nats_ack_wait' * 'nats_max_deliver' on JetStream), or a redelivery arrives " + "after the marker has expired and is processed again." + ) + try: + ttl = int(raw_ttl) + except (TypeError, ValueError) as exc: + raise ValueError(f"Config key 'idempotency_ttl' must be an integer number of seconds, got {raw_ttl!r}.") from exc + if ttl <= 0: + raise ValueError(f"'idempotency_ttl' must be greater than 0, got {ttl}. It is the dedup window, in seconds.") + + if not self.registry.has_cache(): + raise ValueError( + "'idempotency_enabled' is true but no cache is registered, so there is nowhere to record " + "the events already processed. Add '.with_cache()' to the AppBuilder chain." + ) + + return IdempotencyPolicy(enabled=True, ttl=ttl) + + def _read_bool(self, key: str, default: bool) -> bool: + """Read a boolean config key, accepting the strings an environment variable delivers.""" + raw = self.config.get(key, default) + if isinstance(raw, bool): + return raw + if isinstance(raw, str): + normalized = raw.strip().lower() + if normalized in ("true", "1", "yes"): + return True + if normalized in ("false", "0", "no"): + return False + raise ValueError(f"Config key '{key}' must be a boolean, got {raw!r}.") diff --git a/src/blueprint/agents/io/api/eventing/event_handling_base.py b/src/blueprint/agents/io/api/eventing/event_handling_base.py index 3a3532b7..2ac4f5dc 100644 --- a/src/blueprint/agents/io/api/eventing/event_handling_base.py +++ b/src/blueprint/agents/io/api/eventing/event_handling_base.py @@ -9,6 +9,7 @@ from opentelemetry import metrics from ....component.component import traced +from ....handler.handler_chain import DUPLICATE_CONTEXT_KEY from ....models import ProcessingResult, ProcessingStatus from ....models.errors import DeliveryDisposition from ....models.events import CloudEvent @@ -24,6 +25,12 @@ unit="{event}", ) +_DUPLICATE_EVENTS = metrics.get_meter(__name__).create_counter( + name="blueprint.events.duplicate", + description="Events a namespace recognised as already processed and did not dispatch", + unit="{event}", +) + class EventHandlingBase(RestApiBase, CloudEventProcessorMixin, ABC): """Base class for event-driven REST API components. @@ -85,13 +92,23 @@ async def _process_cloud_event( URL path under Dapr, and remembering each distinct value would let a caller grow this process's memory. + A dispatch the chain skipped as a duplicate is counted apart from both (spec + sec. 7.4). It reaches here looking exactly like an unmatched event -- no handler + ran, so no result came back -- but the two say opposite things about the + subscription: an unmatched event is one this namespace had no use for, while a + duplicate is one it did use, once. Counting them together would make a redelivery + storm read as a namespace subscribed too broadly. + ``topic`` is passed separately from ``context`` because each transport spells its own key there (``nats_topic``, ``dapr_topic``), and those keys reach user handlers, so they cannot be unified without breaking them. """ logger.debug("Processing CloudEvent: %s", cloud_event.id) processing_result = await self._dispatch_cloud_event(cloud_event, context) - if processing_result.status is ProcessingStatus.NO_HANDLER_FOUND: + if context.get(DUPLICATE_CONTEXT_KEY): + _DUPLICATE_EVENTS.add(1, {"namespace": self.ROOT_NAMESPACE, "topic": topic}) + logger.debug("Event %s on topic '%s' was already processed", cloud_event.id, topic) + elif processing_result.status is ProcessingStatus.NO_HANDLER_FOUND: _UNHANDLED_EVENTS.add(1, {"namespace": self.ROOT_NAMESPACE, "topic": topic}) logger.debug("No handler had work for event %s on topic '%s'", cloud_event.id, topic) return processing_result diff --git a/src/blueprint/agents/services/eventing/event_processing_service.py b/src/blueprint/agents/services/eventing/event_processing_service.py index 6ab16e4d..53ddfdc5 100644 --- a/src/blueprint/agents/services/eventing/event_processing_service.py +++ b/src/blueprint/agents/services/eventing/event_processing_service.py @@ -30,10 +30,18 @@ def __init__(self) -> None: self._correlation_context = self.registry.correlation_context async def on_startup(self) -> None: - """No startup actions required.""" + """Start the handler chain. + + The chain is not a registered component, so nothing else calls its lifecycle + hooks. Its startup resolves the idempotency policy, and that has to happen while + the application is starting: a misconfigured dedup window must fail the pod, not + the first event that arrives on it. + """ + await self._handler_chain.on_startup() async def on_shutdown(self) -> None: - """No shutdown actions required.""" + """Stop the handler chain, for the same reason startup starts it.""" + await self._handler_chain.on_shutdown() @traced("event") async def process_event( diff --git a/tests/unit/agent_generator/cli/commands/test_validate.py b/tests/unit/agent_generator/cli/commands/test_validate.py new file mode 100644 index 00000000..c903efb0 --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_validate.py @@ -0,0 +1,48 @@ +"""Unit tests for the `asbs validate` idempotency notice (P4, spec sec. 7.4).""" + +from pathlib import Path + +from blueprint.agent_generator.cli.commands.validate import IDEMPOTENCY_NOTICE, _idempotency_notice + + +def _project(tmp_path: Path, settings: str | None = None, *, with_handler: bool = True) -> Path: + """Build the smallest project shape the notice looks at.""" + handlers = tmp_path / "src" / "handlers" + handlers.mkdir(parents=True) + if with_handler: + (handlers / "order_handler.py").write_text("# handler", encoding="utf-8") + if settings is not None: + (tmp_path / "settings.toml").write_text(settings, encoding="utf-8") + return tmp_path + + +class TestIdempotencyNotice: + def test_handlers_without_the_key_are_notified(self, tmp_path: Path) -> None: + project = _project(tmp_path, '[default]\napp_name = "demo"\n') + assert _idempotency_notice(project) == IDEMPOTENCY_NOTICE + + def test_opting_in_silences_the_notice(self, tmp_path: Path) -> None: + project = _project(tmp_path, "[default]\nidempotency_enabled = true\nidempotency_ttl = 1500\n") + assert _idempotency_notice(project) is None + + def test_opting_out_explicitly_also_silences_it(self, tmp_path: Path) -> None: + """Declaring the key is the decision spec sec. 7.4 asks for, whichever way it goes.""" + project = _project(tmp_path, "[default]\nidempotency_enabled = false\n") + assert _idempotency_notice(project) is None + + def test_top_level_key_without_an_environment_table_counts(self, tmp_path: Path) -> None: + project = _project(tmp_path, "idempotency_enabled = true\nidempotency_ttl = 60\n") + assert _idempotency_notice(project) is None + + def test_a_project_with_no_handlers_is_not_notified(self, tmp_path: Path) -> None: + project = _project(tmp_path, '[default]\napp_name = "demo"\n', with_handler=False) + assert _idempotency_notice(project) is None + + def test_missing_settings_file_is_notified(self, tmp_path: Path) -> None: + project = _project(tmp_path) + assert _idempotency_notice(project) == IDEMPOTENCY_NOTICE + + def test_unparseable_settings_file_stays_quiet(self, tmp_path: Path) -> None: + """A broken settings.toml has its own report; guessing at the key would add noise.""" + project = _project(tmp_path, "[default\nthis is not toml\n") + assert _idempotency_notice(project) is None diff --git a/tests/unit/agents/handler/test_handler_chain.py b/tests/unit/agents/handler/test_handler_chain.py index d33d4296..169d2ab7 100644 --- a/tests/unit/agents/handler/test_handler_chain.py +++ b/tests/unit/agents/handler/test_handler_chain.py @@ -1,17 +1,28 @@ """Unit tests for HandlerChain.""" +from typing import Any from unittest.mock import MagicMock import pytest -from blueprint.agents.handler.handler_chain import HandlerChain +from blueprint.agents.handler.handler_chain import ( + DUPLICATE_CONTEXT_KEY, + IDEMPOTENCY_CACHE_NAMESPACE, + HandlerChain, + IdempotencyPolicy, +) from blueprint.agents.models.events import GenericCloudEvent, HandlerResult from tests.unit.agents.handler.conftest import StubHandler @pytest.fixture def chain(mock_registry: MagicMock, mock_config: MagicMock) -> HandlerChain: - """HandlerChain with mocked registry (does not self-register).""" + """HandlerChain with mocked registry (does not self-register). + + ``config.get`` returns the caller's default so unset keys read as unset rather than + as a truthy MagicMock; the chain validates the type of ``idempotency_enabled``. + """ + mock_config.get.side_effect = lambda key, default=None: default return HandlerChain() @@ -26,8 +37,9 @@ def _wire_handlers(mock_registry: MagicMock, handlers: list) -> None: class TestLifecycle: - async def test_on_startup_is_noop(self, chain: HandlerChain) -> None: + async def test_on_startup_resolves_idempotency_policy(self, chain: HandlerChain) -> None: await chain.on_startup() + assert chain._policy == IdempotencyPolicy(enabled=False, ttl=0) async def test_on_shutdown_is_noop(self, chain: HandlerChain) -> None: await chain.on_shutdown() @@ -117,3 +129,215 @@ async def handle_event(self, event, context): _wire_handlers(mock_registry, [BrokenHandler()]) with pytest.raises(RuntimeError, match="handler exploded"): await chain.process(cloud_event, {}) + + +# --------------------------------------------------------------------------- +# Idempotency (P4, spec sec. 7.4) +# --------------------------------------------------------------------------- + + +class _StubCache: + """In-memory stand-in for the registered CacheService, recording its calls.""" + + def __init__(self) -> None: + self.store: dict[str, Any] = {} + self.namespaces: list[str] = [] + self.ttls: list[int | None] = [] + + @staticmethod + def _key(key: Any) -> str: + return repr(sorted(key.items())) if isinstance(key, dict) else repr(key) + + def exists(self, key: Any, namespace: str = "default") -> bool: + return self._key(key) in self.store + + def set(self, key: Any, value: Any, namespace: str = "default", ttl: int | None = None) -> None: + self.store[self._key(key)] = value + self.namespaces.append(namespace) + self.ttls.append(ttl) + + def delete(self, key: Any, namespace: str = "default") -> bool: + return self.store.pop(self._key(key), None) is not None + + +def _enable_dedup(mock_config: MagicMock, mock_registry: MagicMock, ttl: int = 60) -> _StubCache: + """Turn dedup on with a working cache, and return that cache.""" + settings = {"idempotency_enabled": True, "idempotency_ttl": ttl} + mock_config.get.side_effect = lambda key, default=None: settings.get(key, default) + cache = _StubCache() + mock_registry.has_cache.return_value = True + mock_registry.cache_service = cache + return cache + + +class TestIdempotencyDisabled: + async def test_dedup_is_off_by_default(self, chain: HandlerChain, mock_registry: MagicMock, cloud_event: GenericCloudEvent) -> None: + _wire_handlers(mock_registry, [StubHandler(result=None)]) + + await chain.process(cloud_event, {}) + + assert chain._policy == IdempotencyPolicy(enabled=False, ttl=0) + + async def test_repeat_delivery_dispatches_again_when_disabled( + self, chain: HandlerChain, mock_registry: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + seen: list[str] = [] + + class Counting(StubHandler): + async def can_handle_event(self, event, context): + seen.append(event.id) + return False + + _wire_handlers(mock_registry, [Counting()]) + + await chain.process(cloud_event, {}) + await chain.process(cloud_event, {}) + + assert seen == ["evt-001", "evt-001"] + + +class TestIdempotencyEnabled: + async def test_same_event_delivered_twice_dispatches_once( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + _enable_dedup(mock_config, mock_registry) + seen: list[str] = [] + + class Counting(StubHandler): + async def can_handle_event(self, event, context): + seen.append(event.id) + return False + + _wire_handlers(mock_registry, [Counting()]) + + await chain.process(cloud_event, {}) + await chain.process(cloud_event, {}) + + assert seen == ["evt-001"] + + async def test_duplicate_is_flagged_in_context_and_returns_none( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + _enable_dedup(mock_config, mock_registry) + _wire_handlers(mock_registry, [StubHandler(result=HandlerResult(event_type="out", data={}))]) + + first_context: dict[str, Any] = {} + await chain.process(cloud_event, first_context) + second_context: dict[str, Any] = {} + result = await chain.process(cloud_event, second_context) + + assert result is None + assert DUPLICATE_CONTEXT_KEY not in first_context + assert second_context[DUPLICATE_CONTEXT_KEY] is True + + async def test_claim_is_written_with_the_configured_ttl_and_namespace( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + cache = _enable_dedup(mock_config, mock_registry, ttl=1500) + _wire_handlers(mock_registry, []) + + await chain.process(cloud_event, {}) + + assert cache.ttls == [1500] + assert cache.namespaces == [IDEMPOTENCY_CACHE_NAMESPACE] + + async def test_same_id_from_another_source_is_not_a_duplicate( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + """The CloudEvents id is unique only within a source, so the key carries both.""" + _enable_dedup(mock_config, mock_registry) + seen: list[str] = [] + + class Counting(StubHandler): + async def can_handle_event(self, event, context): + seen.append(event.source) + return False + + _wire_handlers(mock_registry, [Counting()]) + other = GenericCloudEvent(id="evt-001", type="test.event", source="other-source") + + await chain.process(cloud_event, {}) + await chain.process(other, {}) + + assert seen == ["test-source", "other-source"] + + async def test_failed_dispatch_releases_the_claim( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + """A failure naks, so the redelivery must be allowed to run rather than be deduped.""" + cache = _enable_dedup(mock_config, mock_registry) + attempts: list[str] = [] + + class Broken(StubHandler): + async def handle_event(self, event, context): + attempts.append(event.id) + raise RuntimeError("handler exploded") + + _wire_handlers(mock_registry, [Broken()]) + + with pytest.raises(RuntimeError): + await chain.process(cloud_event, {}) + assert cache.store == {} + + with pytest.raises(RuntimeError): + await chain.process(cloud_event, {}) + assert attempts == ["evt-001", "evt-001"] + + async def test_event_without_a_source_is_dispatched_untracked( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock + ) -> None: + cache = _enable_dedup(mock_config, mock_registry) + _wire_handlers(mock_registry, []) + event = GenericCloudEvent.model_construct(id="evt-002", type="test.event", source="") + + await chain.process(event, {}) + + assert cache.store == {} + + +class TestIdempotencyPolicyResolution: + async def test_enabled_without_ttl_fails_startup(self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda key, default=None: True if key == "idempotency_enabled" else default + + with pytest.raises(ValueError, match="idempotency_ttl"): + await chain.on_startup() + + async def test_non_positive_ttl_fails_startup(self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock) -> None: + settings = {"idempotency_enabled": True, "idempotency_ttl": 0} + mock_config.get.side_effect = lambda key, default=None: settings.get(key, default) + + with pytest.raises(ValueError, match="greater than 0"): + await chain.on_startup() + + async def test_non_numeric_ttl_fails_startup(self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock) -> None: + settings = {"idempotency_enabled": True, "idempotency_ttl": "soon"} + mock_config.get.side_effect = lambda key, default=None: settings.get(key, default) + + with pytest.raises(ValueError, match="must be an integer"): + await chain.on_startup() + + async def test_enabled_without_a_cache_fails_startup( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock + ) -> None: + settings = {"idempotency_enabled": True, "idempotency_ttl": 60} + mock_config.get.side_effect = lambda key, default=None: settings.get(key, default) + mock_registry.has_cache.return_value = False + + with pytest.raises(ValueError, match="no cache is registered"): + await chain.on_startup() + + async def test_non_boolean_enabled_fails_startup(self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda key, default=None: 3 if key == "idempotency_enabled" else default + + with pytest.raises(ValueError, match="must be a boolean"): + await chain.on_startup() + + async def test_enabled_as_a_string_is_accepted(self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock) -> None: + """Environment variables deliver booleans as text.""" + settings = {"idempotency_enabled": "true", "idempotency_ttl": "900"} + mock_config.get.side_effect = lambda key, default=None: settings.get(key, default) + mock_registry.has_cache.return_value = True + + await chain.on_startup() + + assert chain._policy == IdempotencyPolicy(enabled=True, ttl=900) diff --git a/tests/unit/agents/io/api/eventing/test_event_handling_base.py b/tests/unit/agents/io/api/eventing/test_event_handling_base.py index f616488d..79de04e6 100644 --- a/tests/unit/agents/io/api/eventing/test_event_handling_base.py +++ b/tests/unit/agents/io/api/eventing/test_event_handling_base.py @@ -5,6 +5,7 @@ import pytest +from blueprint.agents.handler.handler_chain import DUPLICATE_CONTEXT_KEY from blueprint.agents.io.api.eventing.dapr import DaprEventing from blueprint.agents.models.events import CloudEvent from blueprint.agents.models.result import ProcessingResult @@ -230,3 +231,75 @@ async def test_many_distinct_topics_leave_no_state_behind( await dapr_eventing._process_cloud_event(cloud_event, {}, f"topic.{index}") assert len(dapr_eventing.__dict__) == before + + +# --------------------------------------------------------------------------- +# Duplicate accounting (P4, spec sec. 7.4) +# --------------------------------------------------------------------------- + + +class TestDuplicateAccounting: + """A deduplicated event reaches the edge looking unmatched; it must not be counted as one.""" + + @staticmethod + def _flagging_process_event(result: ProcessingResult) -> AsyncMock: + """Stand in for the handler chain marking the context as a duplicate.""" + + async def _process_event(event, context, *args, **kwargs): + context[DUPLICATE_CONTEXT_KEY] = True + return result + + return AsyncMock(side_effect=_process_event) + + async def test_duplicate_is_counted_as_a_duplicate_not_as_unhandled( + self, + dapr_eventing: DaprEventing, + mock_registry: MagicMock, + cloud_event: CloudEvent, + unhandled_result: ProcessingResult, + ) -> None: + mock_registry.get_service.return_value.process_event = self._flagging_process_event(unhandled_result) + mock_registry.correlation_context.set.return_value = MagicMock() + + with ( + patch("blueprint.agents.io.api.eventing.event_handling_base._DUPLICATE_EVENTS") as duplicates, + patch("blueprint.agents.io.api.eventing.event_handling_base._UNHANDLED_EVENTS") as unhandled, + ): + await dapr_eventing.handle_event("orders", cloud_event) + + duplicates.add.assert_called_once_with(1, {"namespace": "", "topic": "orders"}) + unhandled.add.assert_not_called() + + async def test_duplicate_still_acknowledges( + self, + dapr_eventing: DaprEventing, + mock_registry: MagicMock, + cloud_event: CloudEvent, + unhandled_result: ProcessingResult, + ) -> None: + """Redelivering a duplicate forever would be the one thing worse than processing it twice.""" + mock_registry.get_service.return_value.process_event = self._flagging_process_event(unhandled_result) + mock_registry.correlation_context.set.return_value = MagicMock() + + result = await dapr_eventing.handle_event("orders", cloud_event) + + assert result == {"status": "SUCCESS"} + + async def test_unmatched_event_is_still_counted_as_unhandled( + self, + dapr_eventing: DaprEventing, + mock_registry: MagicMock, + cloud_event: CloudEvent, + unhandled_result: ProcessingResult, + ) -> None: + mock_registry.get_service.return_value.process_event = AsyncMock(return_value=unhandled_result) + mock_registry.correlation_context.set.return_value = MagicMock() + + with ( + patch("blueprint.agents.io.api.eventing.event_handling_base._DUPLICATE_EVENTS") as duplicates, + patch("blueprint.agents.io.api.eventing.event_handling_base._UNHANDLED_EVENTS") as unhandled, + ): + await dapr_eventing.handle_event("orders", cloud_event) + + unhandled.add.assert_called_once_with(1, {"namespace": "", "topic": "orders"}) + duplicates.add.assert_not_called() diff --git a/tests/unit/agents/services/eventing/conftest.py b/tests/unit/agents/services/eventing/conftest.py index cf8a2e17..b9d53ac3 100644 --- a/tests/unit/agents/services/eventing/conftest.py +++ b/tests/unit/agents/services/eventing/conftest.py @@ -54,5 +54,10 @@ def event_publishing_service( @pytest.fixture def event_processing_service(mock_registry: MagicMock, mock_config: MagicMock) -> EventProcessingService: - """EventProcessingService with mocked registry and config.""" + """EventProcessingService with mocked registry and config. + + ``config.get`` returns the caller's default so the handler chain's startup reads + ``idempotency_enabled`` as unset rather than as a truthy MagicMock. + """ + mock_config.get.side_effect = lambda key, default=None: default return EventProcessingService() 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 df3bf721..6d944225 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,6 @@ """Unit tests for EventProcessingService.""" -from unittest.mock import AsyncMock +from unittest.mock import AsyncMock, MagicMock import pytest @@ -120,12 +120,24 @@ def test_dapr_event_with_non_dict_non_event_inner_raises(self, event_processing_ class TestLifecycle: - async def test_on_startup_is_noop(self, event_processing_service: EventProcessingService) -> None: + async def test_on_startup_starts_the_handler_chain(self, event_processing_service: EventProcessingService) -> None: + chain = MagicMock() + chain.on_startup = AsyncMock() + event_processing_service._handler_chain = chain + await event_processing_service.on_startup() - async def test_on_shutdown_is_noop(self, event_processing_service: EventProcessingService) -> None: + chain.on_startup.assert_awaited_once() + + async def test_on_shutdown_stops_the_handler_chain(self, event_processing_service: EventProcessingService) -> None: + chain = MagicMock() + chain.on_shutdown = AsyncMock() + event_processing_service._handler_chain = chain + await event_processing_service.on_shutdown() + chain.on_shutdown.assert_awaited_once() + # --------------------------------------------------------------------------- # process_rest_request From ced9f7f1e28287fa6ddd223e3b91ff69236400ff Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:44:47 +0200 Subject: [PATCH 004/133] feat(scheduling): P5, make the scheduler mode a stated choice and fire ticks once (#43, #73) scheduler_mode is required and has no default. "event" starts no in-process timer -- the tick arrives as an ordinary event on the scheduler's own topic, so the queue group picks one replica and nothing is elected. "in_process" keeps the timer and claims each tick in the shared cache, so one replica runs it; not a lease, so there is no renewal task and no takeover bound. Fixes both causes of #43: a second build() pass no longer starts a second timer, and SchedulerBase sitting in the REST-API lifespan loop as well as the scheduler loop no longer starts two AsyncIOScheduler instances per scheduler. Adds CacheService.claim -- set-if-absent, atomic on both backends. Co-Authored-By: Claude Opus 5 (1M context) --- ...26-08-28-multi-agent-grouping-changelog.md | 694 +++++++++++++++++- docs/reference/configuration-keys.md | 30 + docs/specs/2026-08-28-multi-agent-grouping.md | 107 ++- examples/health_monitor/settings.toml | 3 + .../agent_generator/base_files/settings.txt | 14 + .../agent_generator/claude_docs/CLAUDE.md | 20 +- .../agent_generator/cli/commands/create.py | 38 +- src/blueprint/agents/app_builder.py | 119 ++- .../agents/clients/io/io_client_base.py | 11 + src/blueprint/agents/handler/handler_chain.py | 12 +- .../agents/io/api/scheduling/__init__.py | 12 +- .../agents/io/api/scheduling/scheduler.py | 500 ++++++++++++- .../services/infrastructure/cache_service.py | 72 ++ .../infrastructure/redis_cache_service.py | 20 + src/blueprint/agents/utils/__init__.py | 4 +- src/blueprint/agents/utils/utils.py | 29 + .../integration/test_scheduler_event_mode.py | 205 ++++++ .../cli/commands/test_create_scheduler.py | 62 ++ tests/unit/agents/app_builder/TESTS.md | 2 +- tests/unit/agents/app_builder/conftest.py | 1 + .../agents/app_builder/test_app_builder.py | 183 +++++ tests/unit/agents/io/TESTS.md | 2 +- .../io/api/scheduling/test_scheduler.py | 485 +++++++++++- tests/unit/agents/services/TESTS.md | 4 +- .../infrastructure/test_disk_cache_service.py | 60 ++ .../test_redis_cache_service.py | 32 + tests/unit/agents/utils/TESTS.md | 3 +- tests/unit/agents/utils/test_parse_bool.py | 30 + 28 files changed, 2654 insertions(+), 100 deletions(-) create mode 100644 tests/integration/test_scheduler_event_mode.py create mode 100644 tests/unit/agent_generator/cli/commands/test_create_scheduler.py create mode 100644 tests/unit/agents/utils/test_parse_bool.py diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 9bfb0339..c793d1ae 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -79,13 +79,38 @@ Code: project has handlers and has declared neither - **P4 -- duplicates are counted apart from unmatched events**: `blueprint.events.duplicate`, so a redelivery storm does not read as a namespace subscribed too broadly +- **P5 (`662f7b5`) -- the cron timer becomes a stated choice**: `scheduler_mode` is **required** and has no + default. `"event"` starts no in-process timer -- the tick arrives as an ordinary event on the + scheduler's own topic, so the queue group picks a single replica and nothing is elected; + `"in_process"` keeps the timer for local development and plain Docker. Registering a scheduler + without the key, or choosing `"event"` with no usable `event_bus`, fails at startup +- **P5 -- a second `build()` pass no longer starts a second timer** (#43), and the manual trigger + route is registered before `include_router` copies it, so it is actually served +- **P5 -- two defects in the generated scheduler**: the scaffold emitted a file that did not + parse, and its `on_startup` override never called `super()`, so a scaffolded scheduler never ran +- **P5 -- publishing no longer requires consuming**: `event_publishing_enabled` gives an + application that only emits events a transport client and no subscription. Off by default, + because a project that wants only a timer may have no broker access +- **P5 -- #43's other cause**: `SchedulerBase` extends `RestApiBase`, so every scheduler sat in the + REST-API lifespan loop *and* the scheduler loop. A single lifespan started two + `AsyncIOScheduler` instances per scheduler, and `on_shutdown` could reach only one +- **P5 -- an event-mode crontab is validated at startup**: nothing else parses it in that mode, so + a typo used to surface as a tick that never arrives. Manifest generation itself is deliberately + deferred, and the renderer written for it was removed rather than carried as dead code +- **P5 -- `"in_process"` fires a tick once across replicas**: every replica's timer fires and each + tick is claimed in the shared cache, so one replica runs it. Not a leader lease: nothing is held, + so there is no renewal task and no takeover bound -- which answers the open question the spec + left on that mode +- **New cache primitive `CacheService.claim`**: set-if-absent, atomic on both backends (`add` on + disk, `SET NX EX` on Redis). This is the compare-and-set operation P4 flagged as missing Documentation and process: - Deployment guide now warns that multi-replica is unsafe, and its examples default to one replica (`2d80b63`) - New config keys documented: `event_client_drain_timeout`, `dapr_pubsub_name`, - `dapr_declarative_subscriptions`, `idempotency_enabled`, `idempotency_ttl` + `dapr_declarative_subscriptions`, `idempotency_enabled`, `idempotency_ttl`, `scheduler_mode`, + `event_publishing_enabled` - Feature working rules in `CLAUDE.md`: one reviewable change at a time (`4cf2d51`), and a walkthrough whenever real code is written (`7735251`) @@ -95,7 +120,9 @@ Issues opened along the way: unenforced - **#81** -- Dapr declared topics never subscribe (fixed here) -**Breaking changes: none so far.** See *Compatibility* at the end. +**Breaking changes: one, and it is loud.** `scheduler_mode` is required, so an existing project +with a scheduler fails at startup until it states which mode it wants. Nothing changes behaviour +silently. See *Compatibility* at the end. --- @@ -619,6 +646,506 @@ untracked; six policy-resolution failures and the string form an environment var duplicate counter firing while the unhandled counter does not, and the reverse; and seven cases for the `asbs validate` notice. +### P5 -- the cron timer becomes a stated choice, and the tick becomes an event (`662f7b5`) + +`SchedulerBase.on_startup` created an `AsyncIOScheduler` per process with no leader election +(#73), so every replica fired every cron tick. Grouping widens that: one pod hosting 20 agents +runs 20 timers, and two replicas duplicate all 20 agents' crons at once. The fix spec sec. 7.5 +asks for is not leader election -- it is taking the timer off the path nobody chose. + +**`scheduler_mode` selects what calls `tick()`, and it has no default.** `_resolve_mode` reads the +key, lower-cases and strips it, rejects an absent or empty value, and then accepts only `"event"` +or `"in_process"`: + +```python +raw = self.config.get("scheduler_mode", None) +mode = str(raw or "").strip().lower() +if not mode: + raise ValueError( + f"Scheduler '{self.name}' is registered but 'scheduler_mode' is not set, and it has no default. " + f"Set it to '{SCHEDULER_MODE_EVENT}' to take the tick as an event on '{self.tick_topic}', published " + f"by an external CronJob -- exactly one replica then runs it. Set it to '{SCHEDULER_MODE_IN_PROCESS}' " + "to run an APScheduler timer inside the process, which is correct for local development and plain " + "Docker but fires once per replica." + ) +if mode not in SCHEDULER_MODES: + raise ValueError(f"Config key 'scheduler_mode' must be one of {', '.join(SCHEDULER_MODES)}, got {raw!r}.") +``` + +The error names both values and what each one costs, because it is the only thing an existing +project sees. The result is cached on the instance, so the mode cannot change under a running +scheduler. *Why there is no default* is argued below -- it is a deliberate departure from spec +sec. 7.5, which names `"event"` as the default. + +**Event mode without a transport fails too.** `_require_event_transport`, called from `wire()` +before the handler is created, insists on `event_bus` being one of `EVENT_MODE_TRANSPORTS = +("dapr", "nats")`. `"sessions"` is excluded on purpose: `SessionsBus` consumes SSE job +notifications and never reads `get_subscribed_topics()`, so a tick published to a topic would not +arrive. Without this check, event mode with no broker is the one failure that is pure silence -- +the scheduler starts, subscribes to nothing, and never ticks. + +**In event mode nothing in the process keeps time.** `on_startup` now branches: + +```python +if self._started: + logger.warning("Scheduler '%s' is already started; ignoring the repeated startup", self.name) + return +self._started = True +self.wire() + +if self.scheduler_mode == SCHEDULER_MODE_EVENT: + logger.info(..., self.name, self.tick_topic, self._crontab) + return + +trigger = CronTrigger.from_crontab(self._crontab) +self._scheduler = AsyncIOScheduler() +self._scheduler.add_job(self.tick, trigger, name=self.name) +self._scheduler.start() +``` + +The `AsyncIOScheduler` block is unchanged and now runs only under `"in_process"`. `on_shutdown` +clears `_scheduler` and `_started` after shutting the timer down, so a stop/start cycle in one +process starts one timer again rather than none. + +**`SchedulerTickHandler` is what turns an external tick into a `tick()`.** A new +`EventHandlerBase` subclass in the same module, holding a scheduler and a topic: + +```python +def get_subscribed_topics(self) -> list[str]: + return [self._topic] + +async def can_handle_event(self, event, context) -> bool: + return any(context.get(key) == self._topic for key in _TOPIC_CONTEXT_KEYS) + +async def handle_event(self, event, context) -> dict[str, Any]: + logger.info("Scheduler '%s' ticking from event '%s' on topic '%s'", self._scheduler.name, event.id, self._topic) + await self._scheduler.tick() + return {"status": "ticked", "scheduler": self._scheduler.name} +``` + +That is the entire event mode. Declaring the topic is what makes the transport subscribe -- +`NatsEventing.on_startup` and `DaprEventing._declared_topics` both walk +`registry.get_event_handler()` and call `get_subscribed_topics()` -- so the tick arrives on the +path the framework already has, and the queue group is what guarantees a single replica runs it. +Nothing is elected. Dedup, the unhandled/duplicate counters and the P2 acknowledgement contract +apply to a tick exactly as they do to any other event: a `tick()` that raises reaches the +transport edge and is naked or termed there, which is why `handle_event` does not catch. + +Three details in that class are load-bearing: + +- **It matches the topic, not the event type.** `_TOPIC_CONTEXT_KEYS = ("nats_topic", + "dapr_topic", "topic")` -- every key a transport spells the delivery topic with. Those keys + reach user handlers and were deliberately left un-unified + (`EventHandlingBase._process_cloud_event` says so), so a consumer that wants the topic has to + read all three. Matching the topic rather than a type string also means a hand-published tick + during development works with any body. +- **`PRIORITY = 10`, ahead of the default 100.** A handler that declares nothing is still + evaluated for every event its namespace receives (spec sec. 7.7, rule 1), so a permissive + `can_handle_event` in user code would otherwise claim the tick first. +- **It renames itself in `__init__`.** `Component.__init__` registers under the class-derived + name, and `Registry.add_component` raises on a duplicate, so a second scheduler's handler would + collide with the first on `scheduler_tick_handler`. Assigning `self.name = f"{scheduler.name}_tick"` + immediately pops that key back out of the registry, which is what leaves it free for the next + instance. A test builds two schedulers against a real `Registry` to pin it. + +**The tick topic derives from the agent, not the deployment.** `_resolve_topic` returns +`f"{namespace}.scheduler.{self.name}"`, falling back to `app_name` while `ROOT_NAMESPACE` is still +`""` -- the same identity the queue group derives from, so moving a scheduler between deployment +groups does not change the subject a `CronJob` publishes to (C1). It raises if no identity is +available, and rejects `*` and `>` in either the derived or the `topic=`-overridden form -- a +wildcard would subscribe the scheduler to traffic that is not its tick. Whitespace is treated +asymmetrically: rejected in an explicitly named topic, but rewritten to `_` in a derived one, the +way `NATSClient._durable_for` already rewrites a subject into a legal durable name. +`app_name = "Health Monitor"` is legal and common -- `examples/health_monitor` uses exactly that -- +and since the topic is derived rather than typed there is no author mistake to catch, only a name +to make usable. The `topic=` override exists because the subject taxonomy is still unratified +(spec sec. 13): an agent whose ticks are already published on someone else's subject can name it. + +**`wire()` runs at build time, and that placement is the fix for two silent failures.** + +```python +def wire(self) -> SchedulerTickHandler | None: + self.register_trigger_route() + if self.scheduler_mode != SCHEDULER_MODE_EVENT: + return None + if self._tick_handler is None: + self._tick_handler = SchedulerTickHandler(self, self.tick_topic) + return self._tick_handler +``` + +`AppBuilder.build()` calls it in a new step 2, before the existing `if registry.get_event_handler():` +block that creates the transport and the eventing endpoint: + +```python +for scheduler in registry.get_schedulers(): + tick_handler = scheduler.wire() + if tick_handler is not None: + logger.info( + "Scheduler '%s' is in event mode; its tick arrives on topic '%s' (crontab '%s')", + scheduler.name, tick_handler.topic, scheduler.crontab, + ) +``` + +- **Without that ordering, an application whose only event consumer is a scheduler gets no + transport.** `build()` creates `NATSClient`/`DaprClient` and the eventing component only when a + handler is registered. A tick handler created during `on_startup` would arrive after that + decision, so the scheduler would be registered, subscribed to nothing, and never ticked. +- **The manual trigger route was already broken, and this is where it gets fixed.** + `POST /{name}/trigger` was added to `self.router` inside `on_startup`, but + `_build_rest_endpoints` calls `app.include_router` during `build()`, and `include_router` copies + the routes a router holds *at that moment*. Every route added during startup therefore existed + on the scheduler's own router and was served by nothing. `register_trigger_route` is idempotent + and now runs from `wire()`, before the copy. It stays out of `__init__` because + `with_scheduler(name=...)` can rename the component afterwards and the path carries the name. + +`on_startup` still calls `wire()` itself, so a scheduler driven without `AppBuilder` gets its +handler and its route; both calls are no-ops the second time. + +**#43 -- and it had a second cause, worse than the one on record.** The plan describes two +`build()` passes driving the lifespan hooks twice over the same registry; the `_started` guard +covers that. But it happens in a *single* pass too, and it always has: + +```python +print([x.name for x in registry.get_schedulers()]) # ['nightly_scheduler'] +print([x.name for x in registry.get_rest_apis()]) # ['nightly_scheduler'] +``` + +`SchedulerBase` extends `RestApiBase` -- that is how `POST /{name}/trigger` reaches the app -- so +every scheduler is in `get_rest_apis()` as well as in `get_schedulers()`, and the lifespan iterates +both lists. `on_startup` therefore ran twice on the same object in one startup, and the old +implementation created a fresh `AsyncIOScheduler` each time and overwrote `self._scheduler`. The +first one was already started and stayed started, holding the same job, while the attribute pointed +at the second -- so **every cron job fired twice in a single replica, and `on_shutdown` could only +ever stop one of the two timers.** `on_shutdown` was likewise called twice, which for a subclass +doing anything non-idempotent in either hook is its own problem. + +Two changes, because the two failures are different: + +- `SchedulerBase.on_startup` guards on `_started` and warns on a repeated call. That absorbs both + causes and is the safety net. +- `AppBuilder._lifecycle_rest_apis` removes schedulers from the REST-API lifespan loops, so the + double drive stops happening at all: + + ```python + return [rest_api for rest_api in registry.get_rest_apis() if not isinstance(rest_api, SchedulerBase)] + ``` + + Their routers are still mounted from `get_rest_apis()` in `_build_rest_endpoints`, which is where + that inheritance is wanted. Without this the guard would fire a warning on every startup of every + scheduler, which is a fix that reports itself as a fault forever. + +An integration test asserts a scheduler's hooks run once per lifespan and that no "already started" +warning is emitted. + +**Publishing no longer requires consuming.** Both transport clients were constructed only inside +`build()`'s `if registry.get_event_handler():` branch, and `EventPublishingService` only when an IO +client existed -- so a scheduler-only application could not publish an event at all, whatever its +`event_bus` said. A nightly job that emits `reconciliation.completed` had no way to do it. The two +decisions are now separate: + +```python +consumes = bool(registry.get_event_handler()) +publishes = self._publishing_requested() +event_bus_type = str(self._config.get("event_bus", "") or "").strip().lower() + +if publishes and event_bus_type not in TOPIC_TRANSPORTS: + raise ValueError(...) + +if consumes or publishes: + if event_bus_type == "dapr": + DaprClient() + if consumes: + self._eventing_component = DaprEventing() + elif event_bus_type == "nats": + NATSClient() + if consumes: + self._eventing_component = NatsEventing() + ... +``` + +`event_publishing_enabled` (bool, default `False`) is the opt-in, and it stays opt-in on purpose: a +project that wants only a timer may have no broker access at all, and a client created on its +behalf becomes a readiness dependency on infrastructure it does not run. An absent or empty value +both mean off -- an unset environment override arrives as `""` -- while a non-empty non-boolean +raises, through a new shared `parse_bool` in `utils` that `HandlerChain._read_bool` had implemented +privately for `idempotency_enabled`. + +The publish-only shape gets a client and **nothing else**: no eventing component, so no +`GET /dapr/subscribe`, no `POST /events/{topic}`, no subscription and no consumer. That is the +property that makes it safe for an agent that was never meant to consume -- it cannot accidentally +receive anything, because nothing was subscribed. `EventProcessingService` is still keyed on +`consumes`, and `EventPublishingService` still on the client existing, so a consuming application +keeps the publishing it has always had without touching the new key. + +`TOPIC_TRANSPORTS = ("dapr", "nats")` now lives next to `IOClientBase` -- the class that exists only +for those two -- rather than in the scheduler module, because two callers need the same fact: +publishing needs a client, and an event-mode scheduler needs a subscription. `"sessions"` is +excluded from both; it wires `SessionsApiClient` and `SessionsBus`, which consumes SSE job +notifications and never reads `get_subscribed_topics()`. + +**Two defects in the generated scheduler, found on the way.** + +- **`asbs create scheduler` emitted a file that does not parse.** The template's `tick` body was a + `try:` containing only comments, followed by `except Exception as e:` -- a `SyntaxError`, so the + scaffolded module could not even be imported. The `try` is gone; `tick` is now a documented + TODO that lets its exceptions out, which is also what the acknowledgement contract needs (and + the old body logged *and* re-raised). +- **The scaffolded `on_startup` never called `super().on_startup()`.** It overrode the base method + with a comment-only body, so a scaffolded scheduler that did parse would have started no timer + and registered no trigger route -- in either mode. Both hooks now call `super()`, with a comment + saying what breaks without it. The same omission was in the scheduler example in the generated + `CLAUDE.md` and is fixed there too. + +**Why `scheduler_mode` has no default (a departure from spec sec. 7.5).** The spec names `"event"` +as the default. It is not implemented that way, and the reasoning belongs on the record because it +is the first question a reviewer will ask. + +Neither value is a defensible thing to inherit silently: + +- **`"in_process"` as the default would ship the defect.** It *is* #73 -- a timer in every replica, + so scaling past one fires every tick N times, and a pod hosting 20 grouped agents runs 20 timers. + Defaulting to it means only the projects that read the release notes closely enough to opt in get + the fix, and the ones that do not are precisely the multi-replica production deployments that can + least afford duplicated side effects. +- **`"event"` as the default would ship silence.** It is correct under an orchestrator, but it needs + something outside the process to publish the tick and a transport to receive it. A service whose + only job is periodic work may have neither -- `examples/health_monitor` registers two schedulers + and configures no `event_bus` at all -- and for those, event mode is not a line of config but a + broker they do not have. On upgrade they would simply stop ticking. + +Which value is right depends on facts this layer cannot read: whether a broker is reachable, +whether more than one replica runs, whether an orchestrator exists at all. That is the same shape +as `idempotency_ttl` in sec. 7.4, and it gets the same answer -- the framework provides the +mechanism and the author states the choice. The cost is one line of config per existing project, +paid once, against a startup error that names both options. + +The counter-argument, for the record: `"in_process"` as the default would have made this change +fully backward-compatible, and a required key does break every existing project with a scheduler. +That is accepted deliberately -- the break is loud, one-time and actionable, where the alternative +is a wrong default that stays wrong. It should be an amendment to spec sec. 7.5 rather than an +implementation detail that quietly contradicts it. + +**What is surfaced to the author.** `scheduler_mode = "event"` is written explicitly into the +scaffolded `settings.toml` as `"in_process"` -- the right value for the local `asbs dev` loop a new +project starts in -- with the trade-off and the requirement in a comment, the generated `CLAUDE.md` +gains three bullets on the two modes and the `super()` requirement, and +`docs/reference/configuration-keys.md` gains a `## Scheduling` section. +`examples/health_monitor`, the one project in this repository with schedulers, states +`"in_process"` and says why in a comment. That reference was also missing `idempotency_enabled` and +`idempotency_ttl` from P4 -- documented there now, in a `## Event Deduplication` section, together +with both keys in the example `settings.toml`. + +Tests: both modes read back, case tolerance, an absent/empty/whitespace value and an absent key +each rejected with both values named, rejection of an unknown value, single resolution; topic +derivation from `app_name` and from a renamed scheduler, the `topic=` override, a missing identity, +two wildcards, whitespace rejected in an explicit topic and rewritten in a derived one; `wire()` +creating a handler in event mode only, its idempotency, one trigger route in both modes, event mode +refusing three unusable `event_bus` values and accepting both broker transports, and in-process +mode needing no transport; `parse_bool` accepting a bool, the four true/false strings and rejecting +anything else; `on_startup` starting no timer in event mode, starting and +scheduling one in in-process mode, and starting no second timer or route when called twice (#43); +shutdown allowing a restart; the tick handler's declared topic, priority, name, the three context +keys it accepts, the topics it declines, the tick it runs, the absence of a published event, a +failing tick reaching the transport edge, and two schedulers registering distinct names against a +real `Registry`; `build()` wiring an event-mode scheduler before the transport decision and +creating no transport for an in-process one; and six assertions on the generated scaffold, +including that it parses. + +One offline integration test (`tests/integration/test_scheduler_event_mode.py`) exercises the +whole of event mode with nothing listening anywhere, which the Dapr transport makes possible: a +real `Config`, a real `build()`, the tick topic appearing in `GET /dapr/subscribe`, a CloudEvent +posted to `POST /events/` answering `SUCCESS` and the scheduler's `tick()` having run +once. It also pins the two things a unit test cannot see, both about what `build()` hands to +FastAPI: `POST /api//trigger` answering 200, and an in-process scheduler producing no +subscription document at all. Two more assert the loud failures at `build()`: a scheduler with no +`scheduler_mode`, and `"event"` with no `event_bus`. Three more cover the publish-only shape end to +end -- a pure scheduler that opts in gets a client and a publishing service while +`GET /dapr/subscribe` and `POST /events/...` both answer 404, one that does not opt in gets +neither, and a scheduler's lifecycle hooks run exactly once per lifespan (#43). + +Seven unit tests on `build()` cover the publish/consume split: no client without the opt-in, the +opt-in creating a client but no eventing component and no `EventProcessingService`, the string form +an environment variable delivers, and three rejections -- no transport, `"sessions"`, and a +non-boolean value -- plus the regression that a consuming application still publishes without the +key. + +### P5 -- the event-mode crontab is validated, and the manifest generator was tried and dropped (`662f7b5`) + +Event mode has no publisher yet: the schedule is declared in agent code and something outside the +process has to fire it. A `CronJob` renderer was written for that, reviewed, and then **removed +before it was ever committed** -- the image and entrypoint model is about to change what a manifest +even belongs to (see *Open points*), and an unused module in the framework would only mislead the +next reader. What survives is the one part that was not specific to generating manifests, plus a +record of what the attempt established. + +**`validate_crontab` stays, in `scheduler.py`, called from `wire()`.** In `"in_process"` mode +`CronTrigger.from_crontab` parses the expression, so a typo fails the pod. In `"event"` mode +nothing parsed it at all -- the tick arrives from outside -- so a bad expression surfaced as a +scheduler that reported itself healthy and never ticked: + +```python +if not croniter.is_valid(expression): + raise ValueError(f"The declared crontab '{crontab}' is not a valid cron expression.") + +fields = expression.split() +if len(fields) != 5: + raise ValueError( + f"The declared crontab '{crontab}' has {len(fields)} fields. An external scheduler reads the five standard " + "ones (minute hour day-of-month month day-of-week); seconds and year are apscheduler extensions it will not " + "understand." + ) +``` + +`croniter` rather than apscheduler's parser, because the consumer is an external cron reading the +five standard fields and apscheduler accepts extensions -- a leading seconds field among them -- +that no cron implementation does. That six-field form is rejected explicitly, since it is the +mistake an author familiar with apscheduler would actually make. + +**What the removed renderer established**, kept here because each of these is a trap that will have +to be avoided again wherever the generation ends up living: + +- **A Dapr publisher has to shut its own sidecar down.** The injected sidecar never exits, so the + Job stays `Running` -- and with `concurrencyPolicy: Forbid`, which the spec requires, every later + tick is then suppressed. A nightly job would fire exactly once and afterwards look like a broken + scheduler. `POST /v1.0/shutdown` after the publish is what lets the Job complete. +- **The tick's CloudEvent `id` must vary per run, and the shell quoting is where that breaks.** A + fixed id makes every tick after the first a duplicate once `idempotency_enabled` is on, so the + scheduler runs once and never again. Writing `$TICK_ID` inside a single-quoted JSON body -- the + obvious way to write it -- publishes the literal characters, because a single-quoted shell string + expands nothing. The quote has to be closed, the variable inserted double-quoted, and the quote + reopened. String assertions did not catch this; executing the generated script did. +- **The tick needs a `source`.** The dedup key is `(id, source)` and an event missing either is + dispatched untracked (sec. 7.4). +- **`time` is better left out.** The CloudEvent model defaults it correctly; a shell-formatted + timestamp can fail its ISO-8601-with-timezone validator. +- **A NATS URL can carry credentials, and a manifest is a repository file.** `nats://user:pass@host` + in `settings.toml` would be committed verbatim by any generator that inlines the configured URL. + It has to be detected and replaced with a secret reference. +- **Derived Kubernetes names must fail rather than truncate.** 63 characters minus the job and pod + suffixes leaves 52; truncating lets two schedulers differing only past the cut collapse into one + object, where the second silently overwrites the first. + +### P5 -- `"in_process"` fires once across replicas, and the cache gains a claim primitive (`662f7b5`) + +`"in_process"` mode was still #73 exactly as reported: an `AsyncIOScheduler` per replica, so three +replicas fired every cron job three times. Event mode was fixed by the queue group; this is the +other half, and it is the last thing that stood between the feature and the acceptance criterion +*cron fires once across three replicas in **both** `scheduler_mode` values*. + +**`CacheService.claim` -- set-if-absent, and the reason it had to exist.** P4's dedup and this +tick guard both use the cache to decide *which one of several processes does a piece of work*, and +`exists` followed by `set` cannot do that: two callers racing on one key both pass the check before +either write lands, and both believe they hold it. P4 recorded that as an open point ("a +compare-and-set primitive on `CacheService` (Redis `SET NX`) would close most of it and is not +written yet"). It is written now, as a new abstract method with an implementation per backend. + +Redis is the easy half -- one server-side operation, and expiry is the server's job: + +```python +stored = self._client.set(full_key, json.dumps(value), nx=True, ex=effective_ttl) +return bool(stored) +``` + +The disk backend needed a measurement first. `diskcache_rs.Cache.add` is set-if-absent and atomic +across processes sharing the directory, because the cache is opened with file locking. But its +`expire` argument is **not honoured**: an entry added with `expire=1` was still readable minutes +later. That is presumably why `DiskCacheService` already keeps TTLs in a parallel metadata entry, +and it is what shapes the implementation: + +```python +if not self._cache.add(namespaced_key, value): + if not self._logically_expired(ttl_key): + return False + self._cache.set(namespaced_key, value) + +if effective_ttl is not None: + self._cache.set(ttl_key, str(time.time() + effective_ttl)) +``` + +Had the backend's own expiry been trusted, a claim would never have expired and the scheduler would +have ticked exactly once and then never again -- the same shape of failure as a fixed CloudEvent id +under dedup. The stale branch is the one non-atomic path: `add` refuses a key whose *logical* TTL +has passed because physically it is still there, and taking it over is a read then a write. It is +only reached by a caller that reuses a key beyond its TTL, which the scheduler never does -- see +the key choice below. Both implementations fail **open** on an unreachable cache, matching every +other operation on the service: a cache that cannot answer must not stop the caller from working. + +**The scheduler claims the slot, not a lease.** The timer now runs a wrapper rather than `tick`: + +```python +async def _claimed_tick(self) -> None: + if not self._claim_tick_slot(): + logger.debug("Scheduler '%s' did not win this tick; another replica is running it", self.name) + return + await self.tick() + +def _claim_tick_slot(self) -> bool: + if not self.registry.has_cache(): + return True + slot = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M") + return self.registry.cache_service.claim( + {"scheduler": self.name, "slot": slot}, + {"claimed_at": time.time()}, + namespace=TICK_CACHE_NAMESPACE, + ttl=TICK_CLAIM_TTL_SECONDS, + ) +``` + +`add_job(self._claimed_tick, ...)` replaces `add_job(self.tick, ...)`, so nothing else about the +timer changes. + +**Why a slot claim instead of the leader lease the spec asked for.** This is a deliberate +departure, argued because it *removes* the question rather than answering it. Spec sec. 13 asked +whether that mode needs true failover -- a dead leader taken over within a bound -- or whether "one +designated instance runs it, others no-op" is enough, and noted that the cheap ordinal answer does +not work under a Deployment. With a per-tick claim there is no leader: + +- Nothing is held, so there is **no renewal task** to schedule -- and therefore no framework-created + background task to leak, which C7 exists to prevent -- and no lease left behind by a replica that + dies holding one. +- There is **no takeover bound to specify**, because the next slot is claimed from scratch by + whoever is alive. The failover question dissolves; the spec's open item is deleted rather than + answered. + +**The key is the slot, and that is what keeps set-if-absent sufficient.** `(scheduler, minute)`, +not `scheduler`. Cron granularity is one minute, so every replica firing for the same scheduled +time derives the same key and the next scheduled time derives a different one. Keying on the +scheduler alone would need a compare-*and-swap* on every tick after the first -- read the stored +slot, decide it is stale, write yours -- which is the racy path all over again. With a fresh key +per slot, the atomic `add` path is the normal path and the stale branch is never taken. + +The consequence, stated because it is real: replicas whose clocks differ enough to straddle a +minute boundary derive different slots and both tick. Container clock skew is milliseconds, and +sec. 7.4 covers a repeated tick as it covers every other repeat. + +**No cache means the mode behaves as it did before, loudly.** There is nothing to claim with, so +`_claim_tick_slot` returns `True` and every replica ticks. That is deliberate -- `"in_process"` +exists for local development, and demanding `.with_cache()` there would be gratuitous -- so +`on_startup` warns once, at startup, rather than per tick: + +``` +Scheduler 'x' started an in-process timer with crontab '...' and NO cache is registered, so its +ticks cannot be coordinated: every replica of this process will run every tick. Add '.with_cache()' +to the AppBuilder chain, or use 'scheduler_mode = "event"' where an orchestrator schedules the tick. +``` + +Event mode does **not** claim. The queue group already delivers a published tick to one replica, so +a claim there would be a second mechanism doing the same job; a test pins that the event path +touches the cache not at all. + +**Spec amended** (sec. 7.5): the modes table and the coordination paragraph now describe a per-tick +claim, the set-if-absent requirement and the slot-derived key are normative, the no-cache warning +is required, and the sec. 13 failover question is deleted. Three acceptance criteria were added -- +the three-replica case for both modes, `claim` being set-if-absent on both backends, and the +no-cache warning. + +Tests: the tick claim (winner ticks, loser does not, the key carries scheduler and minute, the +namespace and TTL are passed, **three replicas sharing a real `DiskCacheService` run one tick +between them**, a later slot is claimable again, no cache means every replica ticks, startup warns, +the timer is wired to the wrapper, and event mode claims nothing); and `claim` on both backends +(first wins, second refused, the loser does not overwrite, exactly one of five concurrent callers +wins, TTL behaviour, namespace isolation, stale takeover on disk, and failing open). + ### Deployment guide corrected (`2d80b63`) The guide recommended `replicaCount: 2`, an HPA, and `--set replicaCount=3` as ordinary scaling. It @@ -644,7 +1171,27 @@ to unpick. ## Compatibility -No breaking change has landed. Specifically: +**One breaking change has landed: `scheduler_mode` is required.** A project that registers a +scheduler and does not set it fails at `build()` with an error naming both values and what each +one costs. Nothing changes behaviour silently: the alternative -- defaulting the key -- would +either keep firing a timer per replica (#73) or stop ticking a service that has no broker, and +neither is safe to inherit. The reasoning, including the counter-argument, is under *P5* above; it +is a deliberate departure from spec sec. 7.5 and needs a spec amendment. + +**Migrating an existing service with a scheduler** is one line, and which line depends on the +deployment: + +| Situation | Set | +|---|---| +| No `event_bus`, or plain Docker, or local development | `scheduler_mode = "in_process"` | +| Kubernetes with `event_bus = "dapr"` / `"nats"`, more than one replica | `scheduler_mode = "event"`, plus a `CronJob` publishing to `.scheduler.` | + +`"in_process"` reproduces today's behaviour exactly, including its once-per-replica firing -- it is +the no-op migration. `"event"` is the one that fixes #73, and until P5's second half generates the +`CronJob` the publisher has to be written by hand, which is why the second row is not yet the +recommended answer for anyone. + +Everything else remains non-breaking. Specifically: - `ClientBase.subscribe`'s abstract signature changed from `(topic, callback)` to `(topic_callbacks)` in P0. This is the one signature change in the feature so far; it affects @@ -734,6 +1281,56 @@ No breaking change has landed. Specifically: data but not its namespace, so nothing an application stores can collide with a marker. A deployment sizing its cache should account for one small entry per event within the TTL window. +- **A spaced `app_name` no longer breaks an event-mode scheduler.** Whitespace in a *derived* tick + topic is rewritten to `_`, so `app_name = "Health Monitor"` yields + `Health_Monitor.scheduler.`. An explicitly passed `topic=` is not rewritten and still + fails on whitespace, and a wildcard fails in either form. +- **P5 adds a subscription and a publish permission an event-mode scheduler needs.** The scheduler + subscribes to `.scheduler.`, and whatever publishes its tick has to be + allowed to publish there. Under JetStream that subject also has to be covered by the stream, which + the client widens on startup. +- **A registered scheduler now makes the application create a transport, in event mode only.** The + scheduler contributes a tick handler, and `build()` creates `NATSClient`/`DaprClient` and the + eventing endpoint when any handler is registered. A project that had a scheduler and no handlers + previously started no transport at all; in event mode it now requires `event_bus`, enforced by + `_require_event_transport` rather than left to the generic "no valid event_bus configured" + warning. In `"in_process"` mode nothing is contributed and no transport is created. +- **`POST /api/{scheduler_name}/trigger` starts working.** It was added to the router during startup, + after `include_router` had already copied it, so it was never served. Anything relying on it + answering 404 sees a behaviour change. +- **A subclass overriding `on_startup` without calling `super()` was already broken and still is.** + The base method is what starts the timer, wires the tick handler and registers the trigger route. + The scaffold and the generated docs no longer show an override without the `super()` call. +- **`SchedulerBase.__init__` gained a keyword-only `topic` parameter.** Positional callers are + unaffected; `crontab` is still the first positional argument. +- **A scheduler's `on_startup` and `on_shutdown` now run once per lifespan instead of twice.** A + subclass that relied on the second call -- for instance by counting on an idempotent resolve + happening twice -- changes behaviour. Every scheduler in this repository and in the scaffold is + unaffected. The visible effect is the opposite of a regression: an in-process scheduler now runs + one timer where it used to run two. +- **`event_publishing_enabled` is new and defaults to off**, so no existing application creates a + client it did not create before. A consuming application is unaffected: its handler already + implies the client, and `EventPublishingService` is still keyed on the client existing rather + than on the new key. Setting it with no `event_bus`, or with `event_bus = "sessions"`, fails at + startup rather than at the first publish. +- **`parse_bool` is new in `blueprint.agents.utils`** and is exported from that package. Nothing + was removed: `HandlerChain._read_bool` keeps its signature and behaviour. +- **`CacheService` gained an abstract method, `claim`.** Both bundled backends implement it. A + third-party subclass of `CacheService` outside this repository will not instantiate until it + does too -- the one signature change in this step, and it is additive to the interface rather + than a change to an existing method. +- **An `"in_process"` scheduler now consults the cache on every tick.** With a cache registered + the tick fires once per scheduled slot across all replicas instead of once per replica, which is + the fix; a deployment that was (knowingly or not) relying on N replicas each doing the work will + see it done once. With no cache registered nothing changes except a startup warning. +- **An event-mode scheduler's crontab is now validated at startup.** A project whose declared + expression is not a five-field cron -- including an apscheduler six-field form with seconds -- + fails `build()` where it previously started and waited for a tick. In `"in_process"` mode nothing + changes: `CronTrigger.from_crontab` already rejected the same expressions. +- **`blueprint.agents.io.api.scheduling` exports exactly what it did before**, plus + `SchedulerTickHandler` and the three `SCHEDULER_MODE*` names. `validate_crontab` is importable + from `...scheduling.scheduler` but is not part of the package's public surface. + The spec's one deliberate future break is `with_cache`'s `name` parameter (sec. 10.1), which must stay keyword-only and last, or an existing `with_cache(False)` would silently become a cache named `False`. @@ -742,7 +1339,78 @@ stay keyword-only and last, or an existing `with_cache(False)` would silently be ## Open points -- **P5-P6 remain**, starting with P5 (cron as an event source, #73). P0-P4 have all landed. +- **P0-P5 have landed. P6 is next**, and two requirements for it were settled during P5 (see the + namespace bullet below). What remains open from P5 is deferred work rather than unfinished work: + both modes now fire a cron once across three replicas, which was P5's acceptance criterion. + Still open, in rough order of how much it matters: + - **Manifest generation is deliberately deferred** (decided 2026-09-04), and the renderer + written for it was removed rather than left unused. Two constraints settled the shape of the + missing caller and then removed the ground it would stand on: + - **Nothing may import a project's `src/main.py`.** Stated as an absolute rule. The + declaration is readable without it -- configure `Config` from the project's + `settings.toml`, import the leaf modules under `src/schedulers/`, instantiate each + `SchedulerBase` subclass and read its `crontab`, `scheduler_mode` and `tick_topic` -- + verified against + `examples/health_monitor`. What that cannot see is a `with_scheduler(Klass, name=...)` + rename, which changes both the tick topic and the object name, and a scheduler whose + `__init__` takes arguments passed at registration. + - **The image and entrypoint model is about to change underneath it.** Phase work turns + `main.py` into a pure `AgentRegistration` declaration with no `build()` call and the + Dockerfile's command into `python -m blueprint.agents.entrypoint`, with one image for the + platform and the group injected at container start. Manifests then belong to a *group*, + not to a project, and the agent-to-schedule map falls out of the in-image agent map the + entrypoint already has to construct. A per-project CLI written now would target a project + shape that is being replaced. + + The design decisions to carry forward when it resumes: **generate at scaffolding time**, + where the tool authored the registrations itself and therefore knows them; **a developer who + then edits the registration by hand owns the drift**; and **fail loudly** on anything the + generator cannot see rather than emitting a manifest that publishes to a subject nobody + subscribes to. The six traps the removed renderer surfaced are listed in the *P5* section + above, so they do not have to be rediscovered. + - **Timezone is not reconciled between the two modes.** Spec sec. 7.5 requires them not to + diverge. `"in_process"` uses apscheduler's timezone handling for the declared crontab; whatever + ends up publishing the tick in `"event"` mode will have its own. A scheduler tested locally in + one zone and deployed in another fires at a different hour, and nothing would notice. Dormant + while manifest generation is parked, since there is no second timezone to disagree with yet. + - **The tick claim is verified against a real cache but not a real cluster.** Three replicas + are simulated in one process against one `DiskCacheService` directory, which exercises the + set-if-absent path but not file locking across genuinely separate processes, nor Redis under + contention. Both belong on the broker/integration list below. + - **`asbs validate` says nothing about schedulers.** A project in `"event"` mode with no + generated `CronJob` is the remaining silent-failure case -- the missing `event_bus` and the + missing mode both fail at startup now, but a mode and a transport with nothing publishing + does not. Validate is where it should be caught. +- **Two requirements this raised for later phases, now written into the spec.** + `scheduler_mode` **must** resolve per namespace through C5 rather than once per process, or a + group cannot host a pure-scheduler agent on `"in_process"` next to an event-driven agent on + `"event"` -- which is precisely the deployment freedom grouping exists to provide. Today + `Config` is scope-aware only when `agent_scope` is set on the single shared instance, so every + scheduler in a process shares one mode. And P6 **must not** create a client for a namespace that + neither subscribes nor publishes: sec. 6 argues connection count is cheap and refuses a knob, + which is right per namespace that uses a connection and wrong for one that does not. Both are + recorded in spec sec. 7.5 and sec. 6 with acceptance criteria; neither is implemented. +- **Exclusivity between scheduling and event consumption is not enforced, and deliberately so.** + `scheduler_mode = "in_process"` with no handlers already produces a process that subscribes to + nothing and opens no connection, and publish-only produces one that subscribes to nothing while + still emitting -- so the shapes are expressible without a new switch. A third key would only + overlap `event_bus` and `scheduler_mode` and create a contradiction to resolve. What is *not* + covered is making it observable: spec sec. 9.2 already requires the startup log to carry each + namespace's queue group and durable names, and extending that to "namespace X consumes: nothing" + is what would let a regrouping be checked by diffing logs. If a hard guarantee is wanted later, + the right form is an opt-in per-namespace declaration validated at build time, not an execution + mode. +- **The tick subject is provisional.** `.scheduler.` is a choice this + change had to make, and the subject taxonomy is explicitly unratified (spec sec. 13: who owns + `..`, and how a subject is added). Changing it later moves a subscription, + which under JetStream means a durable's filter changes -- a migration, not a config change + (sec. 7.7). The `topic=` override exists so an agent can opt out of the guess, but the default is + what the generated `CronJob` will encode. +- **Nothing observes a tick.** A tick is counted as an ordinary event, so a `CronJob` that stopped + publishing looks like silence, not a fault: no metric says "this scheduler has not ticked within + two intervals". The declared crontab is in the process and the last tick is knowable, so this is + cheap, and it belongs with the telemetry work in phase 9. Until it exists, event mode trades a + duplicated tick for a possibly missing one, and only the second failure is invisible. - **There is no generated README**, so the third surfacing channel spec sec. 7.4 asks for has nowhere to go. `asbs setup` writes a Dockerfile, settings, secrets and source, and the generated `CLAUDE.md` and `settings.toml` carry the idempotency note instead. If a README is @@ -753,8 +1421,13 @@ stay keyword-only and last, or an existing `with_cache(False)` would silently be how the broker distributes a redelivery, which belongs on the broker-test list below. A compare-and-set primitive on `CacheService` (Redis `SET NX`) would close most of it and is not written yet. -- **Nothing bounds the dedup cache.** Every dispatched event writes one entry for `idempotency_ttl` - seconds. `DiskCacheService` expires lazily -- an entry is removed when it is next read, so +- **Nothing bounds the dedup cache, and the same now applies to tick claims.** Every dispatched + event writes one entry for `idempotency_ttl` seconds, and every scheduler tick writes one for + `TICK_CLAIM_TTL_SECONDS`. On Redis both expire server-side. On disk they expire *logically* -- + `exists` and `get` honour the TTL metadata -- but the bytes are reclaimed only when the entry is + read again, and a slot key is never read again. One small entry per tick is negligible next to a + per-event marker, but it is unbounded on the same terms. Every dispatched event writes one entry + for `idempotency_ttl` `DiskCacheService` expires lazily -- an entry is removed when it is next read, so markers nobody asks about again stay on disk. A long TTL on a high-volume topic grows the cache directory without limit, and no metric reports its size. - **The dedup TTL question in spec sec. 13 is not answered, it is delegated.** Requiring the key @@ -786,7 +1459,14 @@ stay keyword-only and last, or an existing `with_cache(False)` would silently be name across matching nodes and deliver once (to either callback, non-deterministically), which would also end the double dispatch such a pair caused before P1. If it does not merge, the agent receives the event twice and P2 acks both copies as ordinary work, so the answer changes what P2 - has to handle. + has to handle. P5's in-process claim adds two that no unit test reaches: whether + `diskcache-rs` file locking actually makes `add` atomic across separate processes sharing a + volume, and whether Redis `SET NX` holds up under real contention from several replicas firing in + the same instant. P5 adds two more: whether a `CronJob` publishing to the scheduler's + subject is in fact delivered to exactly one replica through the queue group, and what a + `CronJob` restart or a missed `startingDeadlineSeconds` actually produces -- both modes are + at-least-once, so the answer decides whether an event-mode scheduler needs `idempotency_enabled` + on by default in the generated settings. - **The two design questions in spec sec. 13** that change the shape rather than the parameters: 20 or 100 agents, and whether the 4 GB host budget is real. - **#80** -- the failing example tests and the unenforced test split. diff --git a/docs/reference/configuration-keys.md b/docs/reference/configuration-keys.md index a38a36bb..00a9618a 100644 --- a/docs/reference/configuration-keys.md +++ b/docs/reference/configuration-keys.md @@ -44,6 +44,27 @@ Settings for the event bus transport layer. --- +## Event Deduplication + +Delivery is at-least-once on both transports, so a handler can be run twice for the same +event. Deduplication is opt-in and off by default: whether replaying a handler's side +effects is acceptable is a property of the product, not of the framework. + +| Key | Type | Default | Description | +|-----|------|---------|-------------| +| `idempotency_enabled` | `bool` | `false` | Skip an event whose `id` and `source` were already dispatched within the window. Requires `idempotency_ttl` and a registered cache (`.with_cache()`); startup fails if either is missing, rather than leaving deduplication silently off. Best-effort: the claim is check-then-set, so two replicas handed the same event at the same instant can both dispatch, and a cache error fails open. | +| `idempotency_ttl` | `int` | -- | Seconds a processed event is remembered. No default on purpose -- it must outlast the broker's redelivery window (`nats_ack_wait` * `nats_max_deliver` on JetStream, the component's retry policy under Dapr), and a window that expires before the last redelivery looks exactly like deduplication not working. | + +--- + +## Scheduling + +| Key | Type | Default | Description | +|-----|------|---------|-------------| +| `scheduler_mode` | `str` | -- (**required** when a scheduler is registered) | Where a scheduler's tick comes from. `"event"` starts no in-process timer: the tick arrives as an ordinary event on the scheduler's own topic (`.scheduler.` unless overridden with `topic=` in the scheduler's constructor), published by an external `CronJob`, so the queue group already picks exactly one replica and nothing is elected -- it requires `event_bus` to be `"dapr"` or `"nats"`, since `"sessions"` cannot deliver a topic. `"in_process"` runs an APScheduler timer inside every replica and coordinates them through the registered cache: each tick is claimed under a key derived from the scheduler and the scheduled minute, and only the replica that stores the marker runs it. Intended for local development and un-orchestrated Docker, where no `CronJob` exists. **With no cache registered the ticks cannot be coordinated and every replica runs every tick**; startup warns about it. **No default:** neither value is safe to inherit silently, and which one applies depends on the deployment (is a broker reachable, does more than one replica run, is there an orchestrator at all) rather than on the code, so the author states it -- the same reasoning as `idempotency_ttl`. An absent, empty or unrecognised value fails startup. | + +--- + ## Event Publishing Section: `[default.event_publishing]` @@ -52,6 +73,7 @@ Controls how outbound events are published to topics. | Key | Type | Default | Description | |-----|------|---------|-------------| +| `event_publishing_enabled` | `bool` | `false` | Top-level key (not in this section). Opt into publishing events **without consuming any**. A registered handler already implies a transport client, so a consuming application never needs this key; an application that only emits -- a scheduler reporting what it did, a REST API handing work on -- had no way to get a client at all before it existed. When set, the client is created and **nothing is subscribed**: no eventing endpoint, no subscription document, no `/events/{topic}` route. Off by default because publishing needs broker access a scheduler-only project may not have, and a client it never asked for becomes a readiness dependency on infrastructure it does not run. Requires `event_bus` to be `"dapr"` or `"nats"`; startup fails otherwise. | | `default_pubsub_name` | `str` | `"pubsub"` | Default pub/sub component name (used with Dapr). | | `topic_mapping` | `dict` | `{}` | Maps event type strings to topic names. Events not in this mapping use the event type as the topic. | @@ -152,6 +174,14 @@ nats_max_ack_pending = 16 # outstanding messages across all replicas nats_max_deliver = 5 # attempts before the message is dead-lettered # nats_dead_letter_subject = "my_agent_service.dead-letter" # defaults to .dead-letter +# Event deduplication (off by default; both keys are needed to turn it on) +# idempotency_enabled = true +# idempotency_ttl = 1500 # seconds; must outlast the redelivery window + +# Scheduling -- required once a scheduler is registered, no default +scheduler_mode = "in_process" # or "event", which needs event_bus set +# event_publishing_enabled = true # publish without consuming; needs event_bus + # Prompts prompt_directory = "prompts" prompt_search_paths = ["shared/prompts"] diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md index 100cc4da..f384fc22 100644 --- a/docs/specs/2026-08-28-multi-agent-grouping.md +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -265,7 +265,8 @@ changing them triggers a rolling update on their own. | `nats_dead_letter_subject` | `.dead-letter` | Where a message the framework gives up on is republished. Derived from the agent's identity, as the queue group is (C1). `""` disables it and loses those payloads. **MUST NOT** be a wildcard or a subject the same namespace consumes. | | `idempotency_enabled` | `false` | Opt-in dedup. See sec. 7.4. | | `idempotency_ttl` | -- | Dedup window. | -| `scheduler_mode` | `"event"` | `"event"` or `"in_process"`. See sec. 7.5. | +| `scheduler_mode` | -- (**required** with a scheduler) | `"event"` or `"in_process"`. Deliberately without a default; per namespace. See sec. 7.5. | +| `event_publishing_enabled` | `false` | Opt into publishing without consuming. Requires `event_bus`. See sec. 7.5. | ### 5.3 Settings authoring @@ -324,6 +325,13 @@ broker, or an operator-mode account whose JWT carries a `conn` limit set by some authentication is currently wired: `nats.connect()` is called with URL and reconnect parameters only (`clients/io/nats_client.py:93`). +A namespace that neither subscribes to anything nor publishes anything **MUST NOT** be given a +client. A pure-scheduler agent on `scheduler_mode = "in_process"` that does not opt into publishing +(sec. 7.5) is that case: a connection for it is a socket, a readiness dependency and a `/connz` +entry for traffic that does not exist, and it would put a pod on a broker that the agent's own +deployment may have no access to. The cost argument above justifies a connection *per namespace +that uses one*; it does not justify one per namespace that does not. + Connection name **MUST** be `f"{namespace}.{group}.{pod}"`, and **MUST NOT** feed C1 naming. `EventPublishingService` **MUST** publish on its own namespace's client; otherwise outbound @@ -445,7 +453,22 @@ Two modes, selected by `scheduler_mode`: | Mode | Behaviour | |---|---| | `"event"` | **Default.** No in-process timer. An external scheduler (Kubernetes `CronJob`) publishes an event; the agent handles it through its normal event path. | -| `"in_process"` | `AsyncIOScheduler` gated by a NATS KV or cache-backed leader lease. For un-orchestrated Docker and local development. | +| `"in_process"` | `AsyncIOScheduler` in every replica, with each tick claimed in the shared cache so one replica runs it. For un-orchestrated Docker and local development. | + +`scheduler_mode` **MUST NOT** have a default: registering a scheduler without it **MUST** fail +before the port is bound. Neither value is safe to inherit. `"in_process"` is the defect of #73 -- +one timer per replica, multiplied by every grouped agent in the pod -- and `"event"` needs a +publisher and a transport that a service whose only job is periodic work may not have, so +defaulting to it silences that service instead. Which value is correct depends on the deployment +rather than the code: whether a broker is reachable, whether more than one replica runs, whether an +orchestrator exists at all. The author therefore states it, exactly as sec. 7.4 requires for +`idempotency_ttl`. `"event"` **MUST** additionally fail unless `event_bus` names a transport that +carries topics, since a scheduler subscribed to nothing never ticks and reports no fault. + +`scheduler_mode` **MUST** resolve per namespace through C5, not once per process. A group may host +a pure-scheduler agent that has to run `"in_process"` alongside an event-driven agent on `"event"`, +and one process-wide value cannot express that -- which is exactly the deployment freedom grouping +exists to provide. In `"event"` mode the framework **MUST NOT** start a timer, and the tick **MUST** be delivered as an ordinary namespaced event, so the queue group already guarantees single execution across @@ -457,14 +480,62 @@ The schedule **MUST** remain declared in agent code, and the `CronJob` **MUST** that declaration -- the same generation path as manifests from `deployment-groups.yaml`. Hand-authored schedules let code expect a tick nobody scheduled. +That generation path **MUST NOT** import a project's `src/main.py`. The declaration is reachable +without it: configure from the project's settings and import the modules that define the +schedulers. Generation **SHOULD** happen where the registrations are authored, and anything the +generator cannot observe -- a registration-time rename, a scheduler needing constructor arguments +-- **MUST** be reported rather than guessed at. + +Because manifests belong to a deployment group rather than to a single project once one image +serves the platform (sec. 6, and the entrypoint model), the generator's input **SHOULD** be the +group's agent map rather than one project's source tree. + +Independently of the manifest, the declared crontab **MUST** be validated in `"event"` mode. That +mode builds no `CronTrigger`, so nothing else parses the expression, and an invalid one otherwise +presents as a scheduler that reports itself healthy and never ticks. It **MUST** be the five +standard cron fields: an external scheduler reads those, and apscheduler's extensions -- a leading +seconds field in particular -- are not portable to one. + +**In-process coordination is a per-tick claim, not a leader lease.** An earlier form of this +section called for a NATS KV or cache-backed leader lease. A slot claim satisfies the same +requirement and is preferred, because it removes rather than answers the failover question: every +replica's timer fires, each tries to store a marker keyed on `(scheduler, minute)` in the shared +cache, and the one that stores it runs the tick. Nothing is elected and nothing is held, so there +is no renewal task to schedule (and therefore none to leak, C7), no lease left behind by a replica +that dies holding one, and no takeover bound to specify -- the next slot is claimed from scratch by +whoever is alive. + +The claim **MUST** use a set-if-absent primitive rather than a read followed by a write: +`CacheService.claim`. Two replicas racing on an `exists`-then-`set` pair both pass the check and +both tick, which is the failure this mechanism exists to prevent. + +The key **MUST** be derived from the scheduled slot rather than from the scheduler alone. Cron +granularity is one minute, so replicas firing for the same scheduled time derive the same key and +the next scheduled time derives a different one -- which is what keeps set-if-absent sufficient. +Replicas whose clocks differ enough to straddle a minute boundary derive different slots and both +tick; sec. 7.4 covers that, as it covers every other repeat. + +With no cache registered there is nothing to claim with. The timer **MUST** still run -- the mode +exists for local development, where requiring a cache would be gratuitous -- and startup **MUST** +warn that ticks are uncoordinated, naming both remedies. + Neither mode is exactly-once: `CronJob` is at-least-once (controller restart, missed -`startingDeadlineSeconds`), and a lease can briefly have two holders if it expires mid-tick. -Sec. 7.4 therefore applies in both modes. `concurrencyPolicy: Forbid` **SHOULD** be set, and +`startingDeadlineSeconds`), and a claim fails open when the cache is unreachable, so every replica +ticks. Sec. 7.4 therefore applies in both modes. `concurrencyPolicy: Forbid` **SHOULD** be set, and `CronJob` `timeZone` **MUST** be reconciled with apscheduler's timezone handling so the two modes do not diverge. -Note #43 -- schedulers being started twice *within* one process by two `build()` passes -- is a -distinct defect. Both touch scheduler startup and **SHOULD** be fixed together. +**Publishing and consuming are separate decisions.** A scheduler that emits a result event is a +legitimate shape and **MUST NOT** require the agent to consume anything: an application that opts +into publishing gets a transport client and no subscription, and its `event_bus` is what says a +broker exists. Publishing **MUST** stay opt-in, because a project that wants only a timer may have +no broker access at all, and a client created on its behalf becomes a readiness dependency on +infrastructure it does not run. + +Note #43 -- schedulers being started twice *within* one process -- is a distinct defect with two +causes, and both **MUST** be fixed: two `build()` passes driving the lifespan hooks twice, and +`SchedulerBase` extending `RestApiBase` for its trigger route, which puts every scheduler in the +REST-API lifespan loop *and* the scheduler loop within a single pass. ### 7.6 Topic subscription scope @@ -696,8 +767,20 @@ Two things an author still needs to know: their agent's name, and that handlers - [ ] The CI gate fails when an environment's group declaration omits an agent present in the in-image agent map (sec. 13). - [ ] Cron fires once across three replicas in both `scheduler_mode` values (#73). +- [ ] `CacheService.claim` is set-if-absent on both backends: of N concurrent callers on one key + exactly one is told it stored the value (sec. 7.5). +- [ ] An `"in_process"` scheduler with no cache still ticks, and warns at startup that its ticks + are uncoordinated (sec. 7.5). - [ ] `scheduler_mode = "event"` starts no timer, and the generated `CronJob` matches the schedule declared in agent code. +- [ ] A registered scheduler with no `scheduler_mode` fails before the port is bound, and so does + `"event"` with no topic-carrying `event_bus` (sec. 7.5). +- [ ] Two namespaces in one group resolve different `scheduler_mode` values, and only the + `"in_process"` one starts a timer (sec. 7.5, C5). +- [ ] A pure-scheduler namespace that neither subscribes nor publishes is given no transport client + (sec. 6), and one that opts into publishing is given a client and no subscription (sec. 7.5). +- [ ] A scheduler's `on_startup` and `on_shutdown` each run exactly once per lifespan, asserted + against both lifespan loops a `SchedulerBase` appears in (#43). - [ ] An event that matches no handler is acknowledged, not redelivered: the transport edge behaves identically for `PROCESSED` and `NO_HANDLER_FOUND` (sec. 7.2). - [ ] The same outcome yields the same disposition on both transports -- `CriticalHandlerError` @@ -741,10 +824,14 @@ Two things an author still needs to know: their agent's name, and that handlers - Earlier design context assumed "20+ agents"; #32 targets **100 agents in 4 GB**. Grouping heuristics, connection totals and executor budgets all change materially at 100. Which figure is the design target? -- **For `scheduler_mode = "in_process"`, is true failover required** (a dead leader taken over - within a bound), or is "one designated instance runs it, others no-op" enough? The cheap - ordinal-check answer does not work under a Deployment, which has no stable ordinal, so a lease - is likely needed either way. +- **Do the services running schedulers today have `event_bus` configured?** It decides how much + weight the `"in_process"` lease carries. If some have no broker at all they are permanently + `"in_process"`, and the lease stops being a development convenience and becomes the only thing + standing between them and duplicated ticks. +- **Does the deployment path regenerate manifests from the build?** If it does, the generated + `CronJob` arrives with the upgrade and `"event"` costs an existing service nothing. If manifests + are hand-maintained, the generator emits a file someone has to notice and apply, which is where a + tick quietly stops. - **Who owns the subject taxonomy?** Pushing selection into the subject (sec. 7.7) only works if publishers encode the discriminator, and the publishers are other services. `topic_mapping` lets the framework enforce symmetry once a scheme exists, but it cannot invent the token order. diff --git a/examples/health_monitor/settings.toml b/examples/health_monitor/settings.toml index 00036931..5e3997b3 100644 --- a/examples/health_monitor/settings.toml +++ b/examples/health_monitor/settings.toml @@ -3,6 +3,9 @@ app_name = "Health Monitor" app_port = 8000 app_environment = "development" log_level = "INFO" +# Required: two schedulers are registered and this service has no event_bus, so its +# ticks have to come from an in-process timer. Single replica by design. +scheduler_mode = "in_process" [default.monitor] check_timeout_seconds = 10 diff --git a/src/blueprint/agent_generator/base_files/settings.txt b/src/blueprint/agent_generator/base_files/settings.txt index a69295c1..8cd52b71 100644 --- a/src/blueprint/agent_generator/base_files/settings.txt +++ b/src/blueprint/agent_generator/base_files/settings.txt @@ -14,6 +14,20 @@ model_base_url = "https://avs-vllm.q14.net/v1" # idempotency_enabled = true # idempotency_ttl = 1500 +# Required as soon as a scheduler is registered -- it has no default, because neither +# value is safe to inherit. "event" starts no in-process timer: the tick arrives as an +# event on .scheduler., published by an external CronJob, so +# exactly one replica runs it -- and it needs event_bus set. "in_process" runs an +# APScheduler timer in the process and claims each tick in the cache so one replica +# runs it; it is right for local development and plain Docker, and it needs +# .with_cache() or every replica runs every tick. +scheduler_mode = "in_process" + +# Set this to publish events without consuming any -- a scheduler that reports what +# it did, for instance. A handler already implies a client, so only publish-only +# applications need it. Needs event_bus, and subscribes to nothing. +# event_publishing_enabled = true + [default.logging] level = "DEBUG" format = "json" diff --git a/src/blueprint/agent_generator/claude_docs/CLAUDE.md b/src/blueprint/agent_generator/claude_docs/CLAUDE.md index 5c07146c..d37d12d7 100644 --- a/src/blueprint/agent_generator/claude_docs/CLAUDE.md +++ b/src/blueprint/agent_generator/claude_docs/CLAUDE.md @@ -156,15 +156,29 @@ class CleanupScheduler(SchedulerBase): async def on_startup(self) -> None: self._service = self.registry.get_service(CleanupService) + await super().on_startup() # required: without it the scheduler never runs async def on_shutdown(self) -> None: - pass + await super().on_shutdown() async def tick(self) -> None: """Called on each cron interval.""" await self._service.cleanup() ``` +- **Override `on_startup` only if you also call `super().on_startup()`.** The base class is + what starts the timer, wires the tick handler and registers `POST /api//trigger`. +- **`scheduler_mode` decides what calls `tick()`, and it is required.** It has no default: + registering a scheduler without setting it fails at startup, because neither value is safe to + inherit silently. `"event"` starts no timer in the process -- the tick arrives as an ordinary + event on `.scheduler.`, published by an external `CronJob`, so the + queue group already guarantees that exactly one replica runs it; it needs `event_bus` set to + `"dapr"` or `"nats"`. `"in_process"` runs an APScheduler timer in **every** replica and + claims each tick in the cache so one replica runs it -- so it needs `.with_cache()` to fire a + tick once. Without a cache every replica runs every tick, and startup says so. +- The crontab stays declared here in both modes; it is what the `CronJob` is generated from. +- **A scheduler that wants to *publish* an event needs `event_publishing_enabled = true`.** Consuming and publishing are separate: a handler implies a transport client, a scheduler does not. The key creates the client and subscribes to nothing, and it needs `event_bus` set. + ### AgentRuntime (via AgentBuilder) ```python @@ -218,6 +232,10 @@ model_max_tokens = 2000 # idempotency_enabled = true # idempotency_ttl = 1500 # seconds; must outlast the broker redelivery window +# Required once a scheduler is registered; no default. "in_process" runs a timer in +# every replica; "event" takes the tick as an event and needs event_bus set. +scheduler_mode = "in_process" + [default.runtimes.my_agent] # Per-agent overrides model_name = "gpt-4-turbo" model_temperature = 0.5 diff --git a/src/blueprint/agent_generator/cli/commands/create.py b/src/blueprint/agent_generator/cli/commands/create.py index c90fbd99..fd9d1284 100644 --- a/src/blueprint/agent_generator/cli/commands/create.py +++ b/src/blueprint/agent_generator/cli/commands/create.py @@ -699,34 +699,44 @@ class {class_name}(SchedulerBase): """Scheduler for {snake_name.replace("_scheduler", "")} operations.""" def __init__(self) -> None: - """Initialize the scheduler. - - Args: - name: Component name for registry (optional) - crontab: Cron expression for scheduling + """Declare the schedule. + + The crontab is declared here in both scheduler modes, and 'scheduler_mode' in + settings.toml decides what calls tick(). It is required and has no default: with + 'event' nothing in this process keeps time -- the tick arrives as an event on this + scheduler's own topic, published by an external CronJob generated from this + declaration, and 'event_bus' has to be set. With 'in_process' an APScheduler timer + runs here, which is right for local development and un-orchestrated Docker but + fires once per replica. """ super().__init__(crontab="{args.cron}") async def on_startup(self) -> None: - """Initialize the scheduler.""" + """Resolve dependencies, then let the base class wire the scheduler.""" # TODO: Get services from registry # Example: self._service = self.registry.get_service(MyService) + # Required. The base class starts the timer (in_process mode), wires the tick + # handler (event mode) and registers the manual trigger route. Drop this call + # and the scheduler is registered but never runs. + await super().on_startup() + async def on_shutdown(self) -> None: """Cleanup when shutting down.""" - async def tick(self) -> None: - """Execute scheduled task.""" + await super().on_shutdown() - try: - # TODO: Implement your scheduled task here - # Example: await self._service.do_work() + async def tick(self) -> None: + """Execute scheduled task. + Let exceptions out. In event mode the transport edge decides the delivery + disposition from them; catching and logging one here acknowledges the tick as + successful work. + """ - except Exception as e: - logger.exception("Error during %s scheduler tick: %s", __name__, e) - raise + # TODO: Implement your scheduled task here + # Example: await self._service.do_work() ''' output_file.write_text(code) diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index d157c96e..65cd2039 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -24,6 +24,7 @@ from .io.api.utilities.root import RootApi from .io.api.utilities.cache import CacheManagementApi from .clients.io.dapr_client import DaprClient +from .clients.io.io_client_base import TOPIC_TRANSPORTS from .clients.io.nats_client import NATSClient from .services.service_base import ServiceBase from .services.eventing.event_processing_service import EventProcessingService @@ -31,6 +32,7 @@ from .services.sessions import SessionKeyProvider, SessionsApiClient from .services.infrastructure.cache_backend_factory import CacheBackendFactory from .config import Config, TelemetryManager +from .utils import parse_bool HandlerT = TypeVar("HandlerT", bound=EventHandlerBase) ServiceT = TypeVar("ServiceT", bound=ServiceBase) @@ -159,24 +161,61 @@ def build(self) -> FastAPI: This method: 1. Injects Config into the Component class hierarchy - 2. Creates IO clients and internal services based on configuration - 3. Wires health checkers from all registered clients - 4. Returns a FastAPI app with lifespan management + 2. Wires each registered scheduler for its scheduler_mode + 3. Creates the IO client, and the eventing endpoint only if something consumes + 4. Wires health checkers from all registered clients + 5. Returns a FastAPI app with lifespan management """ # 1. Inject config — enforced once-only by metaclass guard Component.configure(self._config) registry: Registry = Component.shared_registry # type: ignore[assignment] - # 2. Create IO transport client and eventing endpoint if handlers registered - if registry.get_event_handler(): - event_bus_type = self._config.get("event_bus", "").lower() + # 2. Wire the schedulers, before step 3 decides whether this application needs a + # transport at all. A scheduler in 'event' mode has no in-process timer: + # its tick arrives as an event, so its tick handler must be registered by now or an + # application whose only event consumer is a scheduler gets no transport and is never + # ticked. wire() also adds the trigger route while the router can still be copied. + for scheduler in registry.get_schedulers(): + tick_handler = scheduler.wire() + if tick_handler is not None: + logger.info( + "Scheduler '%s' is in event mode; its tick arrives on topic '%s' (crontab '%s')", + scheduler.name, + tick_handler.topic, + scheduler.crontab, + ) + + # 3. Create the IO transport client, and the eventing endpoint only if something + # consumes. Publishing and consuming are decided separately: an application that + # only emits events -- a scheduler that reports what it did, a REST API that hands + # work on -- needs a client but must not be subscribed to anything it never asked + # for. Consuming still implies publishing, because a handler returning a + # HandlerResult with an event_type has always published through the same client. + consumes = bool(registry.get_event_handler()) + publishes = self._publishing_requested() + event_bus_type = str(self._config.get("event_bus", "") or "").strip().lower() + + if publishes and event_bus_type not in TOPIC_TRANSPORTS: + # Strict where the handler branch below only warns: 'event_publishing_enabled' is + # a new key, and setting it is an explicit statement that this application emits + # events. Honouring that with no transport would mean the first publish fails at + # runtime, inside whatever business operation produced the event. + raise ValueError( + f"'event_publishing_enabled' is true but 'event_bus' is {event_bus_type or 'not set'!r}, so there is " + f"no client to publish through. Set 'event_bus' to one of {', '.join(TOPIC_TRANSPORTS)}, or remove " + "'event_publishing_enabled'." + ) + + if consumes or publishes: if event_bus_type == "dapr": DaprClient() # auto-registers - self._eventing_component = DaprEventing() + if consumes: + self._eventing_component = DaprEventing() elif event_bus_type == "nats": NATSClient() # auto-registers - self._eventing_component = NatsEventing() + if consumes: + self._eventing_component = NatsEventing() elif event_bus_type == "sessions": SessionsApiClient() # ServiceBase → auto-registers SessionKeyProvider() # ServiceBase → auto-registers @@ -190,16 +229,24 @@ def build(self) -> FastAPI: "('dapr', 'nats', or 'sessions'). Event handling will be disabled." ) - # 3. Create internal services (auto-register) + if publishes and not consumes: + logger.info( + "Event publishing is enabled without any handler: a '%s' client is created, and nothing is subscribed", + event_bus_type, + ) + + # 4. Create internal services (auto-register) # EventProcessingService is only useful when there's a handler to route - # requests to — whether via an eventing endpoint (see step 2) or a REST + # requests to -- whether via an eventing endpoint (see step 3) or a REST # API calling RestApiBase._process_resource() directly. - if registry.get_event_handler(): + if consumes: EventProcessingService() + # Keyed on the client rather than on 'publishes', so a consuming application keeps + # the publishing service it has always had without opting in. if registry.get_io_clients(): EventPublishingService() - # 4. Create ActuatorApi and wire health checkers from all registered clients + # 5. Create ActuatorApi and wire health checkers from all registered clients self._actuator_api = ActuatorApi() health_providers: dict[str, HealthCheckerBase] = {client.name: ClientHealthChecker([client]) for client in registry.get_clients()} # Pull the registered cache (if any) into the readiness probe so a Redis @@ -212,7 +259,7 @@ def build(self) -> FastAPI: if health_providers: self._actuator_api.add_health_providers(health_providers) - # 5. Build FastAPI app + # 6. Build FastAPI app app = FastAPI( title=self._config.get("app_name", "blueprint-service"), description=self._config.get("app_description", ""), @@ -226,6 +273,39 @@ def build(self) -> FastAPI: self._build_rest_endpoints(app, registry) return app + @staticmethod + def _lifecycle_rest_apis(registry: Registry) -> list[RestApiBase]: + """Return the REST APIs the lifespan owns, which is every one that is not a scheduler. + + A scheduler is a ``RestApiBase`` -- that is how ``POST /{name}/trigger`` reaches the + app -- so it appears in ``get_rest_apis()`` as well as in ``get_schedulers()``. The + lifespan drives both lists, so without this filter every scheduler's ``on_startup`` + and ``on_shutdown`` run twice. + """ + return [rest_api for rest_api in registry.get_rest_apis() if not isinstance(rest_api, SchedulerBase)] + + def _publishing_requested(self) -> bool: + """Report whether this application has opted into publishing events. + + ``event_publishing_enabled`` (bool, default ``False``). Off by default because + publishing needs broker access, and a project that only wants a scheduler or a REST + API may have none -- creating a client it never asked for would fail its readiness + probe on a broker it does not run. Consuming applications never need the key: a + registered handler already implies a client. + + An absent or empty value both mean "off". Empty is not treated as a typo because an + unset environment override arrives as ``""``, and an operator writing + ``BLUEPRINT_EVENT_PUBLISHING_ENABLED=`` means the key is not set. Anything else that + is not a boolean does raise. + + Raises: + ValueError: if the key holds a non-empty value that is not a boolean. + """ + raw = self._config.get("event_publishing_enabled", False) + if raw is None or (isinstance(raw, str) and not raw.strip()): + return False + return parse_bool(raw, "event_publishing_enabled") + def _build_rest_endpoints(self, app: FastAPI, registry: Registry) -> None: """Include all routers into the FastAPI app.""" app.include_router(RootApi(app=app).router, tags=["root"]) @@ -305,8 +385,15 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: logger.error("Agent %s startup failed: %s", agent_name, e, exc_info=True) raise - # User REST APIs - for rest_api in registry.get_rest_apis(): + # User REST APIs. Schedulers are excluded because SchedulerBase extends + # RestApiBase for its trigger route, so every scheduler is in this list *and* in + # get_schedulers() below -- driving both loops called on_startup twice on the same + # object. Before the guard in SchedulerBase.on_startup that meant two + # AsyncIOScheduler instances per scheduler, only one of which on_shutdown could + # reach: every cron job fired twice in a single replica, and one timer could never + # be stopped (#43). Their routers are still mounted from get_rest_apis() in + # _build_rest_endpoints, which is where that inheritance is wanted. + for rest_api in self._lifecycle_rest_apis(registry): try: await rest_api.on_startup() logger.info("REST API %s startup completed", rest_api.name) @@ -377,7 +464,7 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: except Exception as e: logger.error("Scheduler %s shutdown failed: %s", scheduler.name, e, exc_info=True) - for rest_api in registry.get_rest_apis(): + for rest_api in self._lifecycle_rest_apis(registry): try: await rest_api.on_shutdown() except Exception as e: diff --git a/src/blueprint/agents/clients/io/io_client_base.py b/src/blueprint/agents/clients/io/io_client_base.py index 484c0323..c2f3ac7c 100644 --- a/src/blueprint/agents/clients/io/io_client_base.py +++ b/src/blueprint/agents/clients/io/io_client_base.py @@ -12,3 +12,14 @@ class IOClientBase(ClientBase, ABC): Used by EventPublishingService and eventing endpoints to find the active transport client via the registry without matching AI clients. """ + + +TOPIC_TRANSPORTS = ("dapr", "nats") +"""Values of ``event_bus`` that produce an :class:`IOClientBase`, and therefore carry topics. + +``"sessions"`` is not one of them: it wires ``SessionsApiClient`` (a service) and +``SessionsBus``, which consumes SSE job notifications and never reads +``get_subscribed_topics()``. Anything that needs to publish to a topic or subscribe to one -- +``EventPublishingService``, the eventing endpoints, an event-mode scheduler -- needs one of +these two. +""" diff --git a/src/blueprint/agents/handler/handler_chain.py b/src/blueprint/agents/handler/handler_chain.py index 1999acfc..89e8cd71 100644 --- a/src/blueprint/agents/handler/handler_chain.py +++ b/src/blueprint/agents/handler/handler_chain.py @@ -9,6 +9,7 @@ from ..component.component import Component, traced from ..models.events import CloudEvent, HandlerResult +from ..utils import parse_bool logger = logging.getLogger(__name__) @@ -267,13 +268,4 @@ def _resolve_idempotency_policy(self) -> IdempotencyPolicy: def _read_bool(self, key: str, default: bool) -> bool: """Read a boolean config key, accepting the strings an environment variable delivers.""" - raw = self.config.get(key, default) - if isinstance(raw, bool): - return raw - if isinstance(raw, str): - normalized = raw.strip().lower() - if normalized in ("true", "1", "yes"): - return True - if normalized in ("false", "0", "no"): - return False - raise ValueError(f"Config key '{key}' must be a boolean, got {raw!r}.") + return parse_bool(self.config.get(key, default), key) diff --git a/src/blueprint/agents/io/api/scheduling/__init__.py b/src/blueprint/agents/io/api/scheduling/__init__.py index 2196caad..64b23819 100644 --- a/src/blueprint/agents/io/api/scheduling/__init__.py +++ b/src/blueprint/agents/io/api/scheduling/__init__.py @@ -1,5 +1,15 @@ -from .scheduler import SchedulerBase +from .scheduler import ( + SCHEDULER_MODE_EVENT, + SCHEDULER_MODE_IN_PROCESS, + SCHEDULER_MODES, + SchedulerBase, + SchedulerTickHandler, +) __all__ = [ + "SCHEDULER_MODES", + "SCHEDULER_MODE_EVENT", + "SCHEDULER_MODE_IN_PROCESS", "SchedulerBase", + "SchedulerTickHandler", ] diff --git a/src/blueprint/agents/io/api/scheduling/scheduler.py b/src/blueprint/agents/io/api/scheduling/scheduler.py index b28c1dbd..db8b0097 100644 --- a/src/blueprint/agents/io/api/scheduling/scheduler.py +++ b/src/blueprint/agents/io/api/scheduling/scheduler.py @@ -1,10 +1,29 @@ """Abstract base class for scheduled background tasks. Subclasses implement :meth:`tick` and are registered with :class:`AppBuilder` -via ``with_scheduler()``. The scheduler runs via APScheduler and calls -``tick()`` according to the configured crontab expression. A REST endpoint -for manual triggering is registered dynamically under ``/{name}/trigger`` -during startup. +via ``with_scheduler()``. What calls ``tick()`` depends on ``scheduler_mode`` +(spec sec. 7.5): + +``"event"`` + Nothing in this process keeps time. The schedule is declared here and lives + outside -- an external scheduler publishes to the scheduler's own topic and + :class:`SchedulerTickHandler` turns that delivery into a ``tick()``. The queue + group already picks exactly one replica, so no leader is elected. Requires + ``event_bus``. + +``"in_process"`` + An APScheduler timer in every replica, for un-orchestrated Docker and local + development where no external scheduler exists. Every replica's timer fires, and + each tick is claimed in the shared cache so exactly one replica runs it. With no + cache registered there is nothing to claim with and every replica runs every tick, + which startup warns about. + +The key has **no default**: registering a scheduler without it fails at startup. Neither +value is safe to inherit silently, and which one applies depends on the deployment rather +than on the code -- see :meth:`SchedulerBase._resolve_mode`. + +A REST endpoint for manual triggering is registered under ``/{name}/trigger`` in +both modes. Example:: @@ -19,17 +38,165 @@ async def tick(self) -> None: from __future__ import annotations import logging +import re +import time from abc import abstractmethod +from datetime import UTC, datetime from typing import Any from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.triggers.cron import CronTrigger +from ....clients.io.io_client_base import TOPIC_TRANSPORTS from ....component.component import traced +from ....handler.event_handler_base import EventHandlerBase +from ....models.events import GenericCloudEvent from ..rest_api_base import RestApiBase logger = logging.getLogger(__name__) +SCHEDULER_MODE_EVENT = "event" +"""No in-process timer; the tick arrives as an ordinary namespaced event.""" + +SCHEDULER_MODE_IN_PROCESS = "in_process" +"""An APScheduler timer inside every replica of the process.""" + +SCHEDULER_MODES = (SCHEDULER_MODE_EVENT, SCHEDULER_MODE_IN_PROCESS) + +ROOT_NAMESPACE = "" +"""Namespace a scheduler's tick topic is derived from. + +Components gain a real namespace in phase 2; until then every one of them lives in the +root namespace, and the tick topic falls back to ``app_name`` exactly as the queue group +does (C1). Mirrors ``EventHandlingBase.ROOT_NAMESPACE``. +""" + + +TICK_CACHE_NAMESPACE = "scheduler_tick" +"""Cache namespace holding the per-tick claims, kept away from application data.""" + +TICK_CLAIM_TTL_SECONDS = 300 +"""How long a claimed tick slot is remembered. + +It only has to outlast the spread between replicas firing for the *same* slot, which is +clock skew plus scheduler jitter -- seconds. Five minutes is generous. It does not have to +outlast the interval between ticks, because the next tick claims a different key. +""" + + +def validate_crontab(crontab: str) -> str: + """Return the crontab if an external cron can read it, else raise. + + In ``"in_process"`` mode ``CronTrigger.from_crontab`` parses the expression, so a typo + fails the pod. In ``"event"`` mode nothing parses it at all -- the tick arrives from + outside -- so without this a typo surfaces as a tick that never comes, long after the + process reported itself healthy. + + ``croniter`` is used rather than apscheduler's parser because the consumer of this + expression is an external scheduler reading the five standard fields, and apscheduler + accepts extensions such as a leading seconds field that no cron implementation does. + + Raises: + ValueError: if the expression is empty, is not a valid cron expression, or does not + have exactly the five standard fields. + """ + expression = crontab.strip() + if not expression: + raise ValueError("The declared crontab is empty.") + + from croniter import croniter + + if not croniter.is_valid(expression): + raise ValueError(f"The declared crontab '{crontab}' is not a valid cron expression.") + + fields = expression.split() + if len(fields) != 5: + raise ValueError( + f"The declared crontab '{crontab}' has {len(fields)} fields. An external scheduler reads the five standard " + "ones (minute hour day-of-month month day-of-week); seconds and year are apscheduler extensions it will not " + "understand." + ) + return expression + + +_TOPIC_CONTEXT_KEYS = ("nats_topic", "dapr_topic", "topic") +"""Every key a transport spells the delivery topic with. + +``NatsEventing`` writes ``nats_topic``, ``DaprEventing`` writes ``dapr_topic`` and the +REST path writes ``topic``. Those keys reach user handlers, so they cannot be unified +(see ``EventHandlingBase._process_cloud_event``) -- a consumer that wants the topic has +to accept all three. +""" + + +class SchedulerTickHandler(EventHandlerBase): + """Routes an externally scheduled tick to one scheduler's :meth:`SchedulerBase.tick`. + + This is the whole of ``scheduler_mode = "event"``: the schedule lives outside the + process and the tick is an ordinary event, so the queue group picks exactly one + replica (spec sec. 7.5) and dedup, telemetry and the acknowledgement contract all + apply to it unchanged. Nothing is elected because nothing keeps time here. + + The handler claims an event only when the delivery arrived on the scheduler's own + topic, which no other component subscribes to. Matching the topic rather than the + event type is deliberate: it makes a hand-published tick (``POST /events/`` + during development) work without the publisher having to know a type string. + """ + + PRIORITY = 10 + """Ahead of the default handler priority of 100. + + A handler that declares nothing is still evaluated for every event its namespace + receives (spec sec. 7.7, rule 1), so a permissive ``can_handle_event`` in user code + would otherwise claim the tick before the scheduler ever saw it. + """ + + def __init__(self, scheduler: SchedulerBase, topic: str) -> None: + """Bind this handler to one scheduler and the topic its ticks arrive on.""" + super().__init__(priority=self.PRIORITY) + # Renamed here rather than by the caller, and not for readability: Component.__init__ + # registers under the class-derived name, so a second scheduler's handler would + # collide with the first one on "scheduler_tick_handler". Renaming pops that key + # out of the registry again, which is what leaves it free for the next instance. + self.name = f"{scheduler.name}_tick" + self._scheduler = scheduler + self._topic = topic + + @property + def topic(self) -> str: + """The topic a tick for this scheduler arrives on.""" + return self._topic + + @property + def scheduler(self) -> SchedulerBase: + """The scheduler this handler ticks.""" + return self._scheduler + + async def on_startup(self) -> None: + """No startup of its own; the scheduler it ticks owns the lifecycle.""" + + async def on_shutdown(self) -> None: + """No shutdown actions required.""" + + def get_subscribed_topics(self) -> list[str]: + """Declare the tick topic so the transport actually subscribes to it.""" + return [self._topic] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + """Accept anything delivered on this scheduler's own topic.""" + return any(context.get(key) == self._topic for key in _TOPIC_CONTEXT_KEYS) + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> dict[str, Any]: + """Run the scheduler's tick, letting a failure reach the transport edge. + + Returns a plain dict rather than a :class:`HandlerResult`: it is non-``None``, so + the chain stops here and the tick is not counted as an unhandled event, and it + carries no ``event_type``, so nothing is published downstream. + """ + logger.info("Scheduler '%s' ticking from event '%s' on topic '%s'", self._scheduler.name, event.id, self._topic) + await self._scheduler.tick() + return {"status": "ticked", "scheduler": self._scheduler.name} + class SchedulerBase(RestApiBase): """Abstract base class for cron-based background schedulers. @@ -37,18 +204,33 @@ class SchedulerBase(RestApiBase): Extends :class:`RestApiBase` so subclasses have access to ``self.registry``, ``self.config``, and a REST endpoint for manual triggering. - The trigger route ``POST /{name}/trigger`` is registered dynamically in - :meth:`on_startup`, after all ``__init__`` code (including any - ``self.name`` overrides) has completed. + Config keys + ~~~~~~~~~~~ + ``scheduler_mode`` (str, **required**, no default): ``"event"`` starts no timer and + expects the tick as an event on :attr:`tick_topic`, which needs ``event_bus`` set to + one of ``TOPIC_TRANSPORTS``; ``"in_process"`` runs an APScheduler timer in every + replica, with each tick claimed in the cache so one replica runs it. See + :meth:`_resolve_mode` for why there is no default. Args: - crontab: Standard cron expression (e.g. ``"*/5 * * * *"``). + crontab: Standard cron expression (e.g. ``"*/5 * * * *"``). Declared here in both + modes: the schedule stays in agent code even when an external scheduler is what + fires it (spec sec. 7.5), and it is validated in event mode because nothing else + parses it there. + topic: Overrides the derived :attr:`tick_topic`. For an agent whose ticks are + already published on a subject someone else owns. """ - def __init__(self, crontab: str) -> None: + def __init__(self, crontab: str, *, topic: str | None = None) -> None: super().__init__() self._crontab = crontab + self._topic_override = topic.strip() if topic else None + self._tick_topic: str | None = None + self._mode: str | None = None + self._tick_handler: SchedulerTickHandler | None = None self._scheduler: AsyncIOScheduler | None = None + self._started = False + self._trigger_route_registered = False @abstractmethod async def tick(self) -> None: @@ -60,31 +242,315 @@ async def tick(self) -> None: raise NotImplementedError # ------------------------------------------------------------------ - # Lifecycle + # Declaration # ------------------------------------------------------------------ - async def on_startup(self) -> None: - """Start the APScheduler and register the manual trigger endpoint.""" - trigger = CronTrigger.from_crontab(self._crontab) + @property + def crontab(self) -> str: + """The declared cron expression, in both modes.""" + return self._crontab - self._scheduler = AsyncIOScheduler() - self._scheduler.add_job(self.tick, trigger, name=self.name) - self._scheduler.start() + @property + def scheduler_mode(self) -> str: + """The resolved ``scheduler_mode``, read from config on first access. + + Raises: + ValueError: if the key is unset or unrecognised. It has no default. + """ + if self._mode is None: + self._mode = self._resolve_mode() + return self._mode + + @property + def tick_topic(self) -> str: + """The topic a tick for this scheduler arrives on, resolved on first access.""" + if self._tick_topic is None: + self._tick_topic = self._resolve_topic() + return self._tick_topic + + @property + def tick_handler(self) -> SchedulerTickHandler | None: + """The handler routing ticks to this scheduler, or ``None`` outside event mode.""" + return self._tick_handler + + # ------------------------------------------------------------------ + # Wiring + # ------------------------------------------------------------------ + + def wire(self) -> SchedulerTickHandler | None: + """Resolve the mode and create what it needs, before the application is built. + + Called from :meth:`AppBuilder.build` rather than from :meth:`on_startup`, for two + reasons that both produce a scheduler that looks registered and does nothing: + + - ``build()`` creates a transport and an eventing endpoint only when a handler is + registered. A project whose only event consumer is an event-mode scheduler would + otherwise get no transport at all, and nothing could ever tick it. + - ``include_router`` copies the routes a router holds *at that moment*. The trigger + route was added during startup, which is after the copy, so it lived on the + scheduler's own router and was served by nothing. + + Idempotent: a second call returns the same handler and adds no second route. + + Returns: + The tick handler in event mode, ``None`` in in-process mode. + + Raises: + ValueError: if ``scheduler_mode`` is unset or unrecognised, if event mode has no + transport that can deliver the tick, or if the tick topic is unusable. + """ + self.register_trigger_route() + + if self.scheduler_mode != SCHEDULER_MODE_EVENT: + return None + + self._require_event_transport() + # Nothing else ever parses the crontab in event mode -- no CronTrigger is built -- so a + # typo would otherwise surface as a tick that never arrives, long after this process + # reported itself healthy. + validate_crontab(self._crontab) + if self._tick_handler is None: + self._tick_handler = SchedulerTickHandler(self, self.tick_topic) + return self._tick_handler + + def register_trigger_route(self) -> None: + """Add ``POST /{name}/trigger`` to this scheduler's router, once. + + Registered outside ``__init__`` because ``with_scheduler(name=...)`` may rename the + component afterwards, and the route path carries the name. + """ + if self._trigger_route_registered: + return self.router.post( f"/{self.name}/trigger", tags=["Scheduler"], summary=f"Manually trigger {self.name}", )(self._trigger_tick) + self._trigger_route_registered = True + + def _resolve_mode(self) -> str: + """Read and validate ``scheduler_mode``, which has no default (spec sec. 7.5). - logger.info("Scheduler '%s' started with crontab '%s'", self.name, self._crontab) + Registering a scheduler without stating the mode is a startup failure, and neither + value is a defensible thing to inherit silently. ``"in_process"`` runs a timer in + every replica and coordinates them through the cache, so it fires a tick once only + where a cache is registered (#73), and a pod hosting 20 grouped agents runs 20 + timers. ``"event"`` is correct under an + orchestrator but needs something outside the process to publish the tick and a + transport to receive it -- a service whose only job is periodic work may have + neither, and would simply go quiet. Which one applies depends on facts this layer + cannot read: whether a broker is reachable, whether more than one replica runs, + whether an orchestrator exists at all. So the author states it, exactly as + ``idempotency_ttl`` is stated rather than defaulted (sec. 7.4). + + Raises: + ValueError: if the key is absent or empty, or holds any other value. A typo must + not fall back to either mode. + """ + raw = self.config.get("scheduler_mode", None) + mode = str(raw or "").strip().lower() + if not mode: + raise ValueError( + f"Scheduler '{self.name}' is registered but 'scheduler_mode' is not set, and it has no default. " + f"Set it to '{SCHEDULER_MODE_EVENT}' to take the tick as an event on '{self.tick_topic}', published " + f"by an external CronJob -- exactly one replica then runs it. Set it to '{SCHEDULER_MODE_IN_PROCESS}' " + "to run an APScheduler timer inside the process, which is correct for local development and plain " + "Docker but fires once per replica." + ) + if mode not in SCHEDULER_MODES: + raise ValueError(f"Config key 'scheduler_mode' must be one of {', '.join(SCHEDULER_MODES)}, got {raw!r}.") + return mode + + def _require_event_transport(self) -> None: + """Fail unless a transport that can deliver a tick is configured. + + In event mode the tick is an ordinary event, so without ``event_bus`` there is + nothing to subscribe to and the scheduler would run forever without ticking -- + the one failure mode of event mode that is otherwise pure silence. + + Raises: + ValueError: if ``event_bus`` is unset or set to a transport that cannot carry + a topic subscription. + """ + bus = str(self.config.get("event_bus", "") or "").strip().lower() + if bus not in TOPIC_TRANSPORTS: + raise ValueError( + f"Scheduler '{self.name}' is in '{SCHEDULER_MODE_EVENT}' mode, which delivers its tick as an event on " + f"'{self.tick_topic}', but 'event_bus' is {bus or 'not set'!r}. Set 'event_bus' to one of " + f"{', '.join(TOPIC_TRANSPORTS)}, or set 'scheduler_mode = \"{SCHEDULER_MODE_IN_PROCESS}\"' to run " + "an in-process timer instead." + ) + + def _resolve_topic(self) -> str: + """Derive the tick topic from the agent's own identity, or take the override. + + ``f"{namespace}.scheduler.{name}"``, falling back to ``app_name`` while the + namespace is the root one -- the same identity the queue group derives from, so + moving the scheduler between deployment groups does not change the subject a + ``CronJob`` has to publish to (C1). + + Whitespace in a *derived* topic is replaced with ``_`` rather than rejected, the way + ``NATSClient._durable_for`` already rewrites a subject into a legal durable name. + ``app_name = "Health Monitor"`` is legal and common, the topic is derived rather than + typed, so there is no author mistake to catch -- only a name to make usable. A + wildcard is still an error in either form: it would subscribe the scheduler to + traffic that is not its tick. + + Raises: + ValueError: if no identity is available, if an explicit ``topic`` contains + whitespace, or if either form contains ``*`` or ``>``. All are startup + failures rather than a silently unsubscribed scheduler. + """ + if self._topic_override: + topic = self._topic_override + if any(char.isspace() for char in topic): + raise ValueError( + f"Scheduler '{self.name}' was given the tick topic '{topic}', which contains whitespace. " + "A NATS subject cannot, and an explicitly named topic is not rewritten." + ) + else: + # ROOT_NAMESPACE is still "" for every component; phase 2 is what gives this a value. + identity = ROOT_NAMESPACE or str(self.config.get("app_name", "") or "").strip() + if not identity: + raise ValueError( + f"Scheduler '{self.name}' runs in event mode but its tick topic cannot be derived: " + "set 'app_name', or pass topic=... to SchedulerBase.__init__." + ) + topic = re.sub(r"\s+", "_", f"{identity}.scheduler.{self.name}") + + if "*" in topic or ">" in topic: + raise ValueError( + f"Scheduler '{self.name}' resolved the tick topic '{topic}', which is not a usable subject: " + "the wildcards '*' and '>' would subscribe it to traffic that is not its tick." + ) + return topic + + # ------------------------------------------------------------------ + # Lifecycle + # ------------------------------------------------------------------ + + async def on_startup(self) -> None: + """Start the in-process timer, or leave the tick to the event path. + + Guarded against a repeated call (#43). Two ``build()`` passes in one process drive + the lifespan hooks twice over the same registry, and an unguarded second call + started a second ``AsyncIOScheduler`` on the same crontab -- one process firing + every tick twice, which no amount of broker-side grouping can fix, because both + timers sit behind the same queue-group member. + + A subclass overriding this **must** call ``super().on_startup()``, or the scheduler + is registered and never runs. + """ + if self._started: + logger.warning("Scheduler '%s' is already started; ignoring the repeated startup", self.name) + return + self._started = True + + # Normally already done by AppBuilder.build(); repeated here so a scheduler driven + # without the builder still gets its handler and its route. + self.wire() + + if self.scheduler_mode == SCHEDULER_MODE_EVENT: + logger.info( + "Scheduler '%s' is in event mode: no in-process timer. Its tick arrives as an event on topic '%s', " + "on the declared crontab '%s'.", + self.name, + self.tick_topic, + self._crontab, + ) + return + + trigger = CronTrigger.from_crontab(self._crontab) + + self._scheduler = AsyncIOScheduler() + self._scheduler.add_job(self._claimed_tick, trigger, name=self.name) + self._scheduler.start() + + if self.registry.has_cache(): + logger.info( + "Scheduler '%s' started an in-process timer with crontab '%s'; each tick is claimed in the cache, " + "so one replica runs it", + self.name, + self._crontab, + ) + else: + logger.warning( + "Scheduler '%s' started an in-process timer with crontab '%s' and NO cache is registered, so its ticks " + "cannot be coordinated: every replica of this process will run every tick. Add '.with_cache()' to the " + "AppBuilder chain, or use 'scheduler_mode = \"event\"' where an orchestrator schedules the tick.", + self.name, + self._crontab, + ) async def on_shutdown(self) -> None: """Shut down APScheduler, waiting for any running tick to finish.""" if self._scheduler and self._scheduler.running: self._scheduler.shutdown(wait=True) + self._scheduler = None + self._started = False logger.info("Scheduler '%s' stopped", self.name) + # ------------------------------------------------------------------ + # In-process coordination + # ------------------------------------------------------------------ + + async def _claimed_tick(self) -> None: + """Run ``tick`` if this replica wins the slot, otherwise do nothing. + + This is what the timer calls in ``"in_process"`` mode, and it is what makes that + mode survive more than one replica (#73). Every replica's own timer fires, and each + one tries to claim the same slot in the shared cache; the one that stores the marker + runs the tick and the rest return. + + Spec sec. 7.5 calls for a leader lease. A *slot claim* is used instead, and it is a + better fit for the same requirement: + + - Nothing is elected and nothing is held, so there is no renewal task to schedule -- + and therefore no framework-created background task to leak (C7) -- and no lease to + be left behind by a replica that dies holding it. + - It answers the question spec sec. 13 leaves open, whether that mode needs true + failover or "one designated instance runs it, others no-op", by removing it: a + dead replica takes nothing with it, because the next slot is claimed from scratch + by whoever is alive. There is no takeover bound to specify. + - The failure it cannot prevent is the one the spec already accepts either way: a + cache that cannot be reached fails open, so every replica ticks. Deduplication + (sec. 7.4) is what makes a repeated tick safe, and it applies to both modes. + + With no cache registered there is nothing to claim with, so the tick runs + unconditionally. That is the behaviour this mode had before, and ``on_startup`` warns + about it once rather than on every tick. + """ + if not self._claim_tick_slot(): + logger.debug("Scheduler '%s' did not win this tick; another replica is running it", self.name) + return + await self.tick() + + def _claim_tick_slot(self) -> bool: + """Claim the current tick slot, reporting whether this replica may run it. + + The key is the *slot*, not the scheduler: ``(scheduler, minute)``. Cron granularity + is one minute, so every replica firing for the same scheduled time derives the same + key, and the next scheduled time derives a different one. Keying on the scheduler + alone would need a compare-and-swap on every tick after the first; keying on the + slot needs only set-if-absent, which is what :meth:`CacheService.claim` provides + atomically. + + The consequence to be aware of: replicas whose clocks differ enough to straddle a + minute boundary derive different slots and both tick. Container clock skew is + milliseconds, and a repeated tick is what dedup covers. + """ + if not self.registry.has_cache(): + return True + + slot = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M") + return self.registry.cache_service.claim( + {"scheduler": self.name, "slot": slot}, + {"claimed_at": time.time()}, + namespace=TICK_CACHE_NAMESPACE, + ttl=TICK_CLAIM_TTL_SECONDS, + ) + # ------------------------------------------------------------------ # Manual trigger # ------------------------------------------------------------------ diff --git a/src/blueprint/agents/services/infrastructure/cache_service.py b/src/blueprint/agents/services/infrastructure/cache_service.py index 37621718..4bd41f92 100644 --- a/src/blueprint/agents/services/infrastructure/cache_service.py +++ b/src/blueprint/agents/services/infrastructure/cache_service.py @@ -93,6 +93,26 @@ def exists(self, key: str | list[str] | dict[str, Any], namespace: str = "defaul True if key exists and is not expired """ + @abstractmethod + def claim(self, key: str | list[str] | dict[str, Any], value: Any, namespace: str = "default", ttl: int | None = None) -> bool: + """Store a value only if the key is absent, and report whether this caller stored it. + + The set-if-absent primitive that ``exists`` followed by ``set`` cannot provide: two + callers racing on the same key both pass an ``exists`` check before either ``set`` + lands, and both then believe they hold the key. Anything that uses the cache to + decide *which one of several processes does a piece of work* needs this instead -- + the scheduler tick claim, and event deduplication. + + Args: + key: Cache key (string, list of strings, or dict). Will be hashed internally. + value: Value to store if the claim succeeds + namespace: Namespace for the key (default: "default") + ttl: Time-to-live in seconds (None = the cache-wide default) + + Returns: + True if this caller stored the value, False if the key was already held. + """ + @abstractmethod def hash(self, value: str | list[str] | dict[str, Any]) -> str: """Generate a hash of a value for use as a cache key. @@ -313,6 +333,58 @@ def set( except Exception as e: logger.warning("Error setting cache: %s", e) + def claim(self, key: str | list[str] | dict[str, Any], value: Any, namespace: str = "default", ttl: int | None = None) -> bool: + """Store a value only if the key is absent (atomic), and report whether we stored it. + + ``diskcache_rs.Cache.add`` is the set-if-absent operation, and it is atomic across + processes sharing the directory because the cache is opened with file locking. Its + own ``expire`` argument is **not** honoured by that backend -- an entry added with + ``expire=1`` is still readable minutes later -- so the TTL is kept in the parallel + metadata entry this service already maintains, exactly as ``set`` does. + + That split is what the stale branch below is for: ``add`` refuses a key whose logical + TTL has passed, because physically it is still there. Taking such a key over is a + read followed by a write, so two callers can both take over one expired claim. This + is the one non-atomic path, and it is only reached by a caller that reuses a key + beyond its TTL rather than deriving a fresh one. + """ + try: + with self._acquire_lock(): + namespaced_key = self._make_key(key, namespace) + ttl_key = self._make_ttl_key(namespaced_key) + effective_ttl = ttl if ttl is not None else self._default_ttl + + if not self._cache.add(namespaced_key, value): + if not self._logically_expired(ttl_key): + return False + self._cache.set(namespaced_key, value) + + if effective_ttl is not None: + self._cache.set(ttl_key, str(time.time() + effective_ttl)) + elif ttl_key in self._cache: + del self._cache[ttl_key] + logger.debug("Cache claimed: %s (ttl=%s)", namespaced_key, effective_ttl) + return True + except Exception as e: + # Fails open, as every other operation on this service does: a cache that cannot + # be reached must not stop the caller from doing its work. + logger.warning("Error claiming cache key: %s", e) + return True + + def _logically_expired(self, ttl_key: str) -> bool: + """Report whether the TTL metadata for an entry says it has expired. + + A missing or unparseable timestamp means "no expiry recorded", so the entry is + treated as live -- the same reading ``exists`` and ``get`` take. + """ + ttl_timestamp = self._cache.get(ttl_key) + if ttl_timestamp is None: + return False + try: + return time.time() > float(ttl_timestamp) + except (ValueError, TypeError): + return False + def delete(self, key: str | list[str] | dict[str, Any], namespace: str = "default") -> bool: """Delete a value from cache.""" try: diff --git a/src/blueprint/agents/services/infrastructure/redis_cache_service.py b/src/blueprint/agents/services/infrastructure/redis_cache_service.py index ce15e5b0..e20944ff 100644 --- a/src/blueprint/agents/services/infrastructure/redis_cache_service.py +++ b/src/blueprint/agents/services/infrastructure/redis_cache_service.py @@ -147,6 +147,26 @@ def set( except Exception as e: logger.warning("Error setting Redis cache: %s", e) + def claim(self, key: str | list[str] | dict[str, Any], value: Any, namespace: str = "default", ttl: int | None = None) -> bool: + """Store a value only if the key is absent, and report whether we stored it. + + ``SET key value NX EX ttl`` is a single server-side operation, so unlike the disk + backend there is no stale-takeover branch: expiry is the server's job and an expired + key simply is not there. Redis returns ``None`` rather than ``False`` when ``NX`` + refuses, hence the truthiness check. + """ + try: + full_key = self._full_key(key, namespace) + effective_ttl = ttl if ttl is not None else self._default_ttl + stored = self._client.set(full_key, json.dumps(value), nx=True, ex=effective_ttl) + logger.debug("Cache claim on %s: %s", full_key, bool(stored)) + return bool(stored) + except Exception as e: + # Fails open, matching every other operation here: an unreachable cache must not + # stop the caller from doing its work. + logger.warning("Error claiming Redis cache key: %s", e) + return True + def delete(self, key: str | list[str] | dict[str, Any], namespace: str = "default") -> bool: try: full_key = self._full_key(key, namespace) diff --git a/src/blueprint/agents/utils/__init__.py b/src/blueprint/agents/utils/__init__.py index a0cd0b5c..6430a8d6 100644 --- a/src/blueprint/agents/utils/__init__.py +++ b/src/blueprint/agents/utils/__init__.py @@ -1,3 +1,3 @@ -from .utils import camel_to_snake +from .utils import camel_to_snake, parse_bool -__all__ = ["camel_to_snake"] +__all__ = ["camel_to_snake", "parse_bool"] diff --git a/src/blueprint/agents/utils/utils.py b/src/blueprint/agents/utils/utils.py index 1be0400a..add303f6 100644 --- a/src/blueprint/agents/utils/utils.py +++ b/src/blueprint/agents/utils/utils.py @@ -14,3 +14,32 @@ def camel_to_snake(name: str) -> str: # Handle the case of multiple uppercase letters at the end of the string s3 = re.sub("([A-Z])([A-Z][a-z])", r"\1_\2", s2) return s3.lower() + + +def parse_bool(value: object, key: str) -> bool: + """Coerce a config value to a bool, accepting the strings an environment variable delivers. + + Dynaconf returns a real bool for ``key = true`` in a TOML file, but an environment + override arrives as text, so ``"true"`` has to mean the same thing as ``True``. + Anything else raises rather than being treated as falsy: a typo that silently disables + a feature is the failure this exists to prevent. + + Args: + value: The raw config value. + key: The config key, used only in the error message. + + Returns: + The parsed boolean. + + Raises: + ValueError: If the value is neither a bool nor a recognised boolean string. + """ + if isinstance(value, bool): + return value + if isinstance(value, str): + normalized = value.strip().lower() + if normalized in ("true", "1", "yes"): + return True + if normalized in ("false", "0", "no"): + return False + raise ValueError(f"Config key '{key}' must be a boolean, got {value!r}.") diff --git a/tests/integration/test_scheduler_event_mode.py b/tests/integration/test_scheduler_event_mode.py new file mode 100644 index 00000000..c0e9ce14 --- /dev/null +++ b/tests/integration/test_scheduler_event_mode.py @@ -0,0 +1,205 @@ +"""Integration test: an event-mode scheduler is ticked through the ordinary event path. + +Offline by design. Under Dapr the application holds no broker connection -- the sidecar +pushes to ``POST /events/{topic}`` -- so the whole of ``scheduler_mode = "event"`` can be +exercised with nothing listening anywhere: build the app, post a CloudEvent to the +scheduler's tick topic, and the scheduler's ``tick()`` runs. + +Two claims that unit tests cannot make are pinned here, because both are about what +``build()`` hands to FastAPI: + +- ``POST /api/{scheduler_name}/trigger`` is actually served. The route used to be added to + the scheduler's router during ``on_startup``, which is after ``include_router`` copied it. +- The tick topic reaches the Dapr subscription document, so a sidecar would be told to + deliver it. +""" + +import logging + +import pytest +from fastapi.testclient import TestClient + +from blueprint.agents.app_builder import AppBuilder +from blueprint.agents.component.component import Component +from blueprint.agents.config import Config +from blueprint.agents.io.api.scheduling import SchedulerBase + + +class NightlyScheduler(SchedulerBase): + """Records its ticks so the test can count them.""" + + def __init__(self) -> None: + super().__init__(crontab="0 3 * * *") + self.ticks = 0 + + async def tick(self) -> None: + self.ticks += 1 + + +@pytest.fixture(autouse=True) +def _reset_component_state(): + Component.shared_config = None + Component.shared_registry = None + yield + Component.shared_config = None + Component.shared_registry = None + + +def _config(tmp_path, mode: str) -> Config: + settings = tmp_path / "settings.toml" + settings.write_text( + "\n".join( + [ + "[default]", + 'app_name = "cron-test"', + 'event_bus = "dapr"', + f'scheduler_mode = "{mode}"', + ] + ) + ) + return Config(settings_files=[str(settings)]) + + +# Not marked @pytest.mark.integration -- nothing here reaches the network, so these must run +# in the offline CI matrix alongside test_sessions_startup_resilience.py. +def test_event_mode_tick_arrives_as_an_event(tmp_path): + scheduler = NightlyScheduler() + app = AppBuilder(_config(tmp_path, "event")).with_scheduler(scheduler).build() + + topic = scheduler.tick_topic + assert topic == "cron-test.scheduler.nightly_scheduler" + + with TestClient(app) as client: + # The sidecar would be told to deliver this topic. + subscriptions = client.get("/dapr/subscribe").json() + assert {entry["topic"] for entry in subscriptions} == {topic} + assert [entry["route"] for entry in subscriptions] == [f"/events/{topic}"] + + response = client.post( + f"/events/{topic}", + json={ + "id": "tick-1", + "source": "cronjob/cron-test", + "type": "cron.tick", + "specversion": "1.0", + "data": {}, + }, + ) + + assert response.status_code == 200 + assert response.json()["status"] == "SUCCESS" + assert scheduler.ticks == 1 + + +def test_event_mode_starts_no_in_process_timer(tmp_path): + scheduler = NightlyScheduler() + app = AppBuilder(_config(tmp_path, "event")).with_scheduler(scheduler).build() + + with TestClient(app): + assert scheduler._scheduler is None + + assert scheduler.ticks == 0 + + +def test_manual_trigger_route_is_served(tmp_path): + """It was added to the router after include_router had already copied it.""" + scheduler = NightlyScheduler() + app = AppBuilder(_config(tmp_path, "event")).with_scheduler(scheduler).build() + + with TestClient(app) as client: + response = client.post(f"/api/{scheduler.name}/trigger") + + assert response.status_code == 200 + assert response.json() == {"status": "triggered", "scheduler": scheduler.name} + assert scheduler.ticks == 1 + + +def test_in_process_mode_declares_no_tick_topic(tmp_path): + """No tick handler, so nothing is subscribed and the sidecar is told nothing.""" + scheduler = NightlyScheduler() + app = AppBuilder(_config(tmp_path, "in_process")).with_scheduler(scheduler).build() + + assert scheduler.tick_handler is None + assert Component.shared_registry.get_event_handler() == [] + + with TestClient(app) as client: + # No handler was registered, so build() created no eventing endpoint at all. + assert client.get("/dapr/subscribe").status_code == 404 + assert scheduler._scheduler is not None + + +def test_a_registered_scheduler_without_a_mode_fails_the_build(tmp_path): + """scheduler_mode has no default: neither value is safe to inherit silently.""" + settings = tmp_path / "settings.toml" + settings.write_text('[default]\napp_name = "cron-test"\nevent_bus = "dapr"\n') + + with pytest.raises(ValueError, match="'scheduler_mode' is not set") as excinfo: + AppBuilder(Config(settings_files=[str(settings)])).with_scheduler(NightlyScheduler()).build() + + assert "event" in str(excinfo.value) + assert "in_process" in str(excinfo.value) + + +def test_event_mode_without_a_transport_fails_the_build(tmp_path): + """Otherwise the scheduler would run forever without ticking, in silence.""" + settings = tmp_path / "settings.toml" + settings.write_text('[default]\napp_name = "cron-test"\nscheduler_mode = "event"\n') + + with pytest.raises(ValueError, match="'event_bus'"): + AppBuilder(Config(settings_files=[str(settings)])).with_scheduler(NightlyScheduler()).build() + + +def test_a_pure_scheduler_can_opt_into_publishing(tmp_path): + """The scheduler-only shape that wants to emit a result but consume nothing.""" + settings = tmp_path / "settings.toml" + settings.write_text( + "\n".join( + [ + "[default]", + 'app_name = "cron-test"', + 'event_bus = "dapr"', + 'scheduler_mode = "in_process"', + "event_publishing_enabled = true", + ] + ) + ) + + app = AppBuilder(Config(settings_files=[str(settings)])).with_scheduler(NightlyScheduler()).build() + registry = Component.shared_registry + + # A client to publish through, and a publishing service to publish with... + assert registry.get_io_clients() != [] + assert "event_publishing_service" in [service.name for service in registry.get_services()] + # ...but nothing that consumes: no handler, no subscription document, no /events route. + assert registry.get_event_handler() == [] + with TestClient(app) as client: + assert client.get("/dapr/subscribe").status_code == 404 + assert client.post("/events/anything", json={}).status_code == 404 + + +def test_a_pure_scheduler_publishes_nothing_by_default(tmp_path): + """Opt-in: a project that only wants a timer may have no broker access at all.""" + app = AppBuilder(_config(tmp_path, "in_process")).with_scheduler(NightlyScheduler()).build() + registry = Component.shared_registry + + assert registry.get_io_clients() == [] + with TestClient(app): + pass + assert "event_publishing_service" not in [service.name for service in registry.get_services()] + + +def test_a_scheduler_lifecycle_runs_once_per_lifespan(tmp_path, caplog): + """#43, in-process half: a scheduler is a RestApiBase, so it was in both lifespan loops. + + Before the fix that started two AsyncIOScheduler instances per scheduler in a single + replica, only one of which on_shutdown could reach. + """ + scheduler = NightlyScheduler() + app = AppBuilder(_config(tmp_path, "in_process")).with_scheduler(scheduler).build() + + with caplog.at_level(logging.WARNING): + with TestClient(app): + assert scheduler._scheduler is not None + + assert "already started" not in caplog.text + assert scheduler._scheduler is None diff --git a/tests/unit/agent_generator/cli/commands/test_create_scheduler.py b/tests/unit/agent_generator/cli/commands/test_create_scheduler.py new file mode 100644 index 00000000..f3daa346 --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_create_scheduler.py @@ -0,0 +1,62 @@ +"""Unit tests for the scheduler scaffold emitted by ``asbs create scheduler``.""" + +import ast +from argparse import Namespace +from pathlib import Path + +import pytest + +from blueprint.agent_generator.cli.commands.create import create_scheduler + + +@pytest.fixture +def scaffold(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> str: + """Generate a scheduler into a temporary directory and return its source.""" + create_scheduler(Namespace(name="cleanup", output_dir=str(tmp_path), cron="0 * * * *")) + capsys.readouterr() + return (tmp_path / "cleanup_scheduler.py").read_text(encoding="utf-8") + + +def _method(source: str, name: str) -> ast.AsyncFunctionDef: + tree = ast.parse(source) + for node in ast.walk(tree): + if isinstance(node, ast.AsyncFunctionDef) and node.name == name: + return node + raise AssertionError(f"the scaffold has no '{name}' method") + + +def _calls_super(method: ast.AsyncFunctionDef) -> bool: + for node in ast.walk(method): + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == method.name + and isinstance(node.func.value, ast.Call) + and isinstance(node.func.value.func, ast.Name) + and node.func.value.func.id == "super" + ): + return True + return False + + +class TestSchedulerScaffold: + def test_scaffold_is_valid_python(self, scaffold: str) -> None: + """The previous template left an empty ``try:`` block, so it did not even parse.""" + ast.parse(scaffold) + + def test_declared_crontab_is_carried_through(self, scaffold: str) -> None: + assert 'crontab="0 * * * *"' in scaffold + + def test_on_startup_calls_super(self, scaffold: str) -> None: + """Without it the base class never starts the timer or wires the tick handler.""" + assert _calls_super(_method(scaffold, "on_startup")) + + def test_on_shutdown_calls_super(self, scaffold: str) -> None: + assert _calls_super(_method(scaffold, "on_shutdown")) + + def test_tick_does_not_swallow_its_own_failure(self, scaffold: str) -> None: + """A caught tick failure acknowledges the delivery as successful work.""" + assert not [node for node in ast.walk(_method(scaffold, "tick")) if isinstance(node, ast.Try)] + + def test_scheduler_mode_is_explained(self, scaffold: str) -> None: + assert "scheduler_mode" in scaffold diff --git a/tests/unit/agents/app_builder/TESTS.md b/tests/unit/agents/app_builder/TESTS.md index 860a0670..d8c04d89 100644 --- a/tests/unit/agents/app_builder/TESTS.md +++ b/tests/unit/agents/app_builder/TESTS.md @@ -8,7 +8,7 @@ Test coverage for `src/blueprint/agents/app_builder.py`. | File | Class under test | What is covered | |---|---|---| -| `test_app_builder.py` | `AppBuilder` | `with_handler` (TypeError for non-subclass, class instantiated, instance accepted without re-instantiation, name propagated, returns self); `with_service`/`with_agent`/`with_scheduler`/`with_rest_api` (instance accepted, returns self); `with_cache` (enabled creates DiskCacheService, disabled skips config read); `with_health_checker` (stored pending before build, added immediately after build, multiple checkers accumulated, returns self); `build()` (event_bus=dapr/nats/unknown/no-handlers routing, EventPublishingService conditional on IO clients, pending health checkers wired, returns FastAPI instance) | +| `test_app_builder.py` | `AppBuilder` | `with_handler` (TypeError for non-subclass, class instantiated, instance accepted without re-instantiation, name propagated, returns self); `with_service`/`with_agent`/`with_scheduler`/`with_rest_api` (instance accepted, returns self); `with_cache` (enabled creates DiskCacheService, disabled skips config read); `with_health_checker` (stored pending before build, added immediately after build, multiple checkers accumulated, returns self); `build()` (event_bus=dapr/nats/unknown/no-handlers routing, EventPublishingService conditional on IO clients, pending health checkers wired, returns FastAPI instance); scheduler wiring (an event-mode scheduler is wired before the transport decision, so its tick handler is what causes a NATS client and eventing endpoint to be created; an in-process scheduler alone creates neither); the publish/consume split (`event_publishing_enabled` off means no client; on means a client with no eventing component and no `EventProcessingService`; the string form an environment variable delivers; rejections for no transport, `"sessions"` and a non-boolean; and a consuming application still publishing without the key) | --- diff --git a/tests/unit/agents/app_builder/conftest.py b/tests/unit/agents/app_builder/conftest.py index b01f2a3f..57ff032e 100644 --- a/tests/unit/agents/app_builder/conftest.py +++ b/tests/unit/agents/app_builder/conftest.py @@ -126,4 +126,5 @@ def wire_empty_registry(mock_registry: MagicMock) -> None: mock_registry.get_io_clients.return_value = [] mock_registry.get_clients.return_value = [] mock_registry.get_rest_apis.return_value = [] + mock_registry.get_schedulers.return_value = [] mock_registry.has_cache.return_value = False diff --git a/tests/unit/agents/app_builder/test_app_builder.py b/tests/unit/agents/app_builder/test_app_builder.py index 8aa187e7..ccca33dc 100644 --- a/tests/unit/agents/app_builder/test_app_builder.py +++ b/tests/unit/agents/app_builder/test_app_builder.py @@ -466,3 +466,186 @@ def test_version_falls_back_to_0_0_0_not_hardcoded( _, kwargs = all_build_mocks.fastapi.call_args assert kwargs["version"] == "0.0.0" assert kwargs["description"] == "" + + +# --------------------------------------------------------------------------- +# build -- scheduler wiring (P5) +# --------------------------------------------------------------------------- + + +class TestBuildSchedulerWiring: + """build() must wire the schedulers before it decides on a transport. + + A scheduler in event mode has no in-process timer: its tick arrives as an event. If + its tick handler is not registered by the time build() checks for handlers, an + application whose only event consumer is a scheduler gets no transport at all and can + never be ticked. + """ + + def _config(self, build_config: MagicMock, **values: object) -> None: + build_config.get.side_effect = lambda key, default=None: values.get(key, default) + + def test_event_mode_scheduler_is_wired_before_the_transport_decision( + self, + builder_for_build: AppBuilder, + mock_registry: MagicMock, + all_build_mocks: types.SimpleNamespace, + build_config: MagicMock, + ) -> None: + wire_empty_registry(mock_registry) + scheduler = MagicMock() + mock_registry.get_schedulers.return_value = [scheduler] + # The tick handler wire() registers is what makes get_event_handler() non-empty. + mock_registry.get_event_handler.side_effect = lambda: [MagicMock()] if scheduler.wire.called else [] + self._config(build_config, event_bus="nats") + + builder_for_build.build() + + scheduler.wire.assert_called_once() + all_build_mocks.nats_client.assert_called_once() + all_build_mocks.nats_eventing.assert_called_once() + + def test_in_process_scheduler_alone_creates_no_transport( + self, + builder_for_build: AppBuilder, + mock_registry: MagicMock, + all_build_mocks: types.SimpleNamespace, + build_config: MagicMock, + ) -> None: + wire_empty_registry(mock_registry) + scheduler = MagicMock() + scheduler.wire.return_value = None + mock_registry.get_schedulers.return_value = [scheduler] + self._config(build_config, event_bus="nats") + + builder_for_build.build() + + scheduler.wire.assert_called_once() + all_build_mocks.nats_client.assert_not_called() + all_build_mocks.nats_eventing.assert_not_called() + + +# --------------------------------------------------------------------------- +# build -- publishing without consuming +# --------------------------------------------------------------------------- + + +class TestBuildPublishOnly: + """Publishing and consuming are separate decisions. + + An application that only emits events -- a scheduler reporting what it did, a REST API + handing work on -- needs a transport client but must not be subscribed to anything. The + opt-in exists because publishing needs broker access a scheduler-only project may not + have, so no client is created unless it is asked for. + """ + + def _config(self, build_config: MagicMock, **values: object) -> None: + build_config.get.side_effect = lambda key, default=None: values.get(key, default) + + def test_no_client_without_the_opt_in( + self, + builder_for_build: AppBuilder, + mock_registry: MagicMock, + all_build_mocks: types.SimpleNamespace, + build_config: MagicMock, + ) -> None: + wire_empty_registry(mock_registry) + self._config(build_config, event_bus="nats") + + builder_for_build.build() + + all_build_mocks.nats_client.assert_not_called() + all_build_mocks.epubs.assert_not_called() + + def test_opt_in_creates_a_client_but_subscribes_to_nothing( + self, + builder_for_build: AppBuilder, + mock_registry: MagicMock, + all_build_mocks: types.SimpleNamespace, + build_config: MagicMock, + ) -> None: + wire_empty_registry(mock_registry) + mock_registry.get_io_clients.return_value = [MagicMock()] + self._config(build_config, event_bus="nats", event_publishing_enabled=True) + + builder_for_build.build() + + all_build_mocks.nats_client.assert_called_once() + all_build_mocks.nats_eventing.assert_not_called() + all_build_mocks.eps.assert_not_called() + all_build_mocks.epubs.assert_called_once() + assert builder_for_build._eventing_component is None + + def test_opt_in_accepts_the_string_an_environment_variable_delivers( + self, + builder_for_build: AppBuilder, + mock_registry: MagicMock, + all_build_mocks: types.SimpleNamespace, + build_config: MagicMock, + ) -> None: + wire_empty_registry(mock_registry) + self._config(build_config, event_bus="dapr", event_publishing_enabled="true") + + builder_for_build.build() + + all_build_mocks.dapr_client.assert_called_once() + all_build_mocks.dapr_eventing.assert_not_called() + + def test_opt_in_without_a_transport_raises( + self, + builder_for_build: AppBuilder, + mock_registry: MagicMock, + all_build_mocks: types.SimpleNamespace, + build_config: MagicMock, + ) -> None: + wire_empty_registry(mock_registry) + self._config(build_config, event_publishing_enabled=True) + + with pytest.raises(ValueError, match="event_publishing_enabled"): + builder_for_build.build() + + def test_opt_in_with_sessions_raises( + self, + builder_for_build: AppBuilder, + mock_registry: MagicMock, + all_build_mocks: types.SimpleNamespace, + build_config: MagicMock, + ) -> None: + """SessionsBus carries no topics, so it cannot publish one.""" + wire_empty_registry(mock_registry) + self._config(build_config, event_bus="sessions", event_publishing_enabled=True) + + with pytest.raises(ValueError, match="event_bus"): + builder_for_build.build() + + def test_non_boolean_opt_in_raises( + self, + builder_for_build: AppBuilder, + mock_registry: MagicMock, + all_build_mocks: types.SimpleNamespace, + build_config: MagicMock, + ) -> None: + wire_empty_registry(mock_registry) + self._config(build_config, event_bus="nats", event_publishing_enabled="maybe") + + with pytest.raises(ValueError, match="must be a boolean"): + builder_for_build.build() + + def test_consuming_still_publishes_without_the_opt_in( + self, + builder_for_build: AppBuilder, + mock_registry: MagicMock, + all_build_mocks: types.SimpleNamespace, + build_config: MagicMock, + ) -> None: + """A handler returning a HandlerResult has always published through the same client.""" + wire_empty_registry(mock_registry) + mock_registry.get_event_handler.return_value = [MagicMock()] + mock_registry.get_io_clients.return_value = [MagicMock()] + self._config(build_config, event_bus="nats") + + builder_for_build.build() + + all_build_mocks.nats_eventing.assert_called_once() + all_build_mocks.eps.assert_called_once() + all_build_mocks.epubs.assert_called_once() diff --git a/tests/unit/agents/io/TESTS.md b/tests/unit/agents/io/TESTS.md index 7824d054..1cb61486 100644 --- a/tests/unit/agents/io/TESTS.md +++ b/tests/unit/agents/io/TESTS.md @@ -17,7 +17,7 @@ Test coverage for `src/blueprint/agents/io/`. | `api/eventing/test_dapr.py` | `DaprEventing` | `publish` PROCESSED→SUCCESS, no-handler→RETRY, `RetryableHandlerError`→RETRY, `InvalidEventError`→DROP, `CriticalHandlerError`→RETRY; `subscribe` returns empty dict | | `api/eventing/test_nats.py` | `NatsEventing` | `subscribe`/`publish` delegate to `_client`, RuntimeError when client is None; `on_startup` fetches client, subscribes to handler-declared and config-declared topics, deduplicates, preserves handler-first order, skips when no topics; `_subscribe_to_topic` RuntimeError when client None, calls `_client.subscribe` with topic and callback | | `api/eventing/test_sessions_bus.py` | `SessionsBus` | `on_startup` validation (no config/base_url/agent_id/api_key, already started, task created); `on_shutdown` (no task, running task cancelled); `_convert_to_cloud_event` (type/id/subject/source/data); `_process_job_notification` (no handler logged, `InvalidEventError`→cancel job, cancel failure swallowed, `RetryableHandlerError`→log, 403→invalidate+retry, 403 retry failure propagates `InvalidEventError`, non-403 propagates) | -| `api/scheduling/test_scheduler.py` | `SchedulerBase` | `_trigger_tick` calls `tick()`, returns `{"status": "triggered"}`, `on_shutdown` calls `shutdown(wait=True)`, `on_startup` registers trigger endpoint | +| `api/scheduling/test_scheduler.py` | `SchedulerBase`, `SchedulerTickHandler` | `_trigger_tick` calls `tick()` and returns `{"status": "triggered"}`; `scheduler_mode` reads both values case-insensitively, has no default so an absent, empty or missing key raises with both values named, rejects an unrecognised value and resolves once; `tick_topic` derives from `app_name` and the (possibly renamed) scheduler name, honours the `topic=` override, rejects a missing identity and a wildcard, rejects whitespace in an explicit topic and rewrites it in a derived one; `wire()` creates the tick handler in event mode only, is idempotent, registers the trigger route once in both modes, refuses event mode without a topic-carrying `event_bus` and accepts both broker transports; `on_startup` starts no timer in event mode, creates and starts `AsyncIOScheduler` on the declared crontab in in-process mode, and starts no second timer or route when called twice (#43); `on_shutdown` calls `shutdown(wait=True)` only when running and allows a later restart; the in-process tick claim -- the winner ticks and a loser does not, the key carries the scheduler and the minute, the claim carries the tick TTL and its own namespace, three replicas sharing a real `DiskCacheService` run one tick between them, a later slot is claimable again, no cache means every replica ticks and startup warns, the timer is wired to the claimed wrapper rather than to `tick`, and event mode claims nothing; `validate_crontab` accepting the five standard fields, stripping whitespace and rejecting empty, nonsense and six-field (apscheduler) expressions, with event-mode wiring failing on a bad crontab and in-process wiring not reaching the check; the tick handler declares its topic, outranks the default handler priority, claims a delivery under `nats_topic`/`dapr_topic`/`topic`, declines other or absent topics, ticks its scheduler without publishing an event, lets a failing tick reach the transport edge, and two schedulers register under distinct names in a real `Registry` | | `api/utilities/test_cache.py` | `CacheManagementApi` | 503 when no cache, `get_cache_stats`/`list_cache_namespaces`/`evict_cache_entry` delegate to registry cache service | | `api/utilities/test_root.py` | `RootApi` | Service name/version/description from config (and defaults when `None`); both/one/neither doc links rendered; non-`APIRoute` routes skipped; `GET` route → direct link; non-`GET` route with `docs_url` → Swagger anchor link, without `docs_url` → plain path; route summary and sorted methods in row; cache hit skips config on second call | | `telemetry/test_telemetry.py` | `TelemetryManager`, `TracingContext` | `configure_tracing` raises when config None, no-op when disabled, creates TracerProvider when enabled; `_build_exporters` OTLP/empty; `TracingContext` span lifecycle + attribute filtering | diff --git a/tests/unit/agents/io/api/scheduling/test_scheduler.py b/tests/unit/agents/io/api/scheduling/test_scheduler.py index a197f82d..76b22272 100644 --- a/tests/unit/agents/io/api/scheduling/test_scheduler.py +++ b/tests/unit/agents/io/api/scheduling/test_scheduler.py @@ -1,10 +1,26 @@ -"""Unit tests for SchedulerBase.""" +"""Unit tests for SchedulerBase and SchedulerTickHandler.""" +import logging +from pathlib import Path +from typing import Any from unittest.mock import MagicMock, patch import pytest -from blueprint.agents.io.api.scheduling.scheduler import SchedulerBase +from blueprint.agents.component.component import Component +from blueprint.agents.component.registry import Registry +from blueprint.agents.io.api.scheduling.scheduler import ( + SCHEDULER_MODE_EVENT, + SCHEDULER_MODE_IN_PROCESS, + TICK_CACHE_NAMESPACE, + TICK_CLAIM_TTL_SECONDS, + SchedulerBase, + SchedulerTickHandler, + validate_crontab, +) +from blueprint.agents.services.infrastructure.cache_service import DiskCacheService + +_SCHEDULER_MODULE = "blueprint.agents.io.api.scheduling.scheduler" class _TestScheduler(SchedulerBase): @@ -12,8 +28,8 @@ class _TestScheduler(SchedulerBase): tick_call_count: int = 0 - def __init__(self) -> None: - super().__init__(crontab="*/5 * * * *") + def __init__(self, **kwargs: Any) -> None: + super().__init__(crontab="*/5 * * * *", **kwargs) self.tick_call_count = 0 async def tick(self) -> None: @@ -26,9 +42,39 @@ async def on_shutdown(self) -> None: await super().on_shutdown() +class _FailingScheduler(SchedulerBase): + """Scheduler whose tick always fails, for the transport-edge contract.""" + + def __init__(self) -> None: + super().__init__(crontab="*/5 * * * *") + + async def tick(self) -> None: + raise RuntimeError("tick exploded") + + +@pytest.fixture +def settings(mock_config: MagicMock) -> dict[str, Any]: + """Back ``config.get`` with a mutable dict so a test can set its own keys. + + ``scheduler_mode`` is deliberately absent: it has no default, so every test that needs + a mode states it, exactly as a project must. + """ + values: dict[str, Any] = {"app_name": "cleanup_service", "event_bus": "nats"} + mock_config.get.side_effect = lambda key, default=None: values.get(key, default) + return values + + +@pytest.fixture +def scheduler(settings: dict[str, Any], mock_registry: MagicMock) -> _TestScheduler: + """Return a concrete SchedulerBase instance in event mode.""" + settings["scheduler_mode"] = SCHEDULER_MODE_EVENT + return _TestScheduler() + + @pytest.fixture -def scheduler(mock_config: MagicMock, mock_registry: MagicMock) -> _TestScheduler: - """Return a concrete SchedulerBase instance.""" +def in_process_scheduler(settings: dict[str, Any], mock_registry: MagicMock) -> _TestScheduler: + """Return a concrete SchedulerBase instance with the in-process timer selected.""" + settings["scheduler_mode"] = SCHEDULER_MODE_IN_PROCESS return _TestScheduler() @@ -51,6 +97,234 @@ async def test_trigger_tick_calls_tick_once_per_call(self, scheduler: _TestSched assert scheduler.tick_call_count == 2 +class TestSchedulerMode: + def test_mode_reads_event(self, scheduler: _TestScheduler) -> None: + assert scheduler.scheduler_mode == SCHEDULER_MODE_EVENT + + def test_mode_reads_in_process(self, in_process_scheduler: _TestScheduler) -> None: + assert in_process_scheduler.scheduler_mode == SCHEDULER_MODE_IN_PROCESS + + def test_mode_tolerates_case_and_whitespace(self, settings: dict[str, Any], scheduler: _TestScheduler) -> None: + settings["scheduler_mode"] = " IN_PROCESS " + assert scheduler.scheduler_mode == SCHEDULER_MODE_IN_PROCESS + + @pytest.mark.parametrize("absent", [None, "", " "]) + def test_absent_mode_raises_naming_both_values(self, absent: str | None, settings: dict[str, Any], scheduler: _TestScheduler) -> None: + """The key has no default -- neither value is safe to inherit silently.""" + settings["scheduler_mode"] = absent + with pytest.raises(ValueError, match="'scheduler_mode' is not set") as excinfo: + _ = scheduler.scheduler_mode + message = str(excinfo.value) + assert SCHEDULER_MODE_EVENT in message + assert SCHEDULER_MODE_IN_PROCESS in message + + def test_missing_mode_key_raises(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + settings.pop("scheduler_mode", None) + with pytest.raises(ValueError, match="'scheduler_mode' is not set"): + _ = _TestScheduler().scheduler_mode + + def test_unknown_mode_raises(self, settings: dict[str, Any], scheduler: _TestScheduler) -> None: + settings["scheduler_mode"] = "leader_election" + with pytest.raises(ValueError, match="scheduler_mode"): + _ = scheduler.scheduler_mode + + def test_mode_is_resolved_once(self, settings: dict[str, Any], scheduler: _TestScheduler) -> None: + assert scheduler.scheduler_mode == SCHEDULER_MODE_EVENT + settings["scheduler_mode"] = SCHEDULER_MODE_IN_PROCESS + assert scheduler.scheduler_mode == SCHEDULER_MODE_EVENT + + +class TestValidateCrontab: + """Event mode parses the crontab nowhere else, so a typo has to fail here.""" + + @pytest.mark.parametrize("crontab", ["0 3 * * *", "*/15 * * * *", "0 0 1 * 1"]) + def test_accepts_the_five_standard_fields(self, crontab: str) -> None: + assert validate_crontab(crontab) == crontab + + def test_strips_surrounding_whitespace(self) -> None: + assert validate_crontab(" 0 3 * * * ") == "0 3 * * *" + + @pytest.mark.parametrize("crontab", ["", " "]) + def test_empty_raises(self, crontab: str) -> None: + with pytest.raises(ValueError, match="empty"): + validate_crontab(crontab) + + def test_nonsense_raises(self) -> None: + with pytest.raises(ValueError, match="not a valid cron expression"): + validate_crontab("every tuesday") + + def test_a_six_field_expression_raises(self) -> None: + """A leading seconds field is an apscheduler extension no cron reads.""" + with pytest.raises(ValueError, match="five standard"): + validate_crontab("0 0 3 * * *") + + def test_event_mode_wiring_rejects_a_bad_crontab(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + settings["scheduler_mode"] = SCHEDULER_MODE_EVENT + + class _BadCrontabScheduler(SchedulerBase): + def __init__(self) -> None: + super().__init__(crontab="0 3 * *") + + async def tick(self) -> None: + """Never called.""" + + with pytest.raises(ValueError, match="cron"): + _BadCrontabScheduler().wire() + + def test_in_process_wiring_does_not_reach_the_check(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + """apscheduler validates it there, at the point it builds the trigger.""" + settings["scheduler_mode"] = SCHEDULER_MODE_IN_PROCESS + + class _LooseCrontabScheduler(SchedulerBase): + def __init__(self) -> None: + super().__init__(crontab="0 3 * *") + + async def tick(self) -> None: + """Never called.""" + + assert _LooseCrontabScheduler().wire() is None + + +class TestTickTopic: + def test_topic_derives_from_app_name_and_scheduler_name(self, scheduler: _TestScheduler) -> None: + assert scheduler.tick_topic == f"cleanup_service.scheduler.{scheduler.name}" + + def test_topic_follows_a_renamed_scheduler(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + renamed = _TestScheduler() + renamed.name = "nightly" + assert renamed.tick_topic == "cleanup_service.scheduler.nightly" + + def test_explicit_topic_overrides_the_derived_one(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + overridden = _TestScheduler(topic="ops.cron.nightly") + assert overridden.tick_topic == "ops.cron.nightly" + + def test_missing_identity_raises(self, settings: dict[str, Any], scheduler: _TestScheduler) -> None: + settings["app_name"] = "" + with pytest.raises(ValueError, match="tick topic cannot be derived"): + _ = scheduler.tick_topic + + @pytest.mark.parametrize("topic", ["ops.cron.*", "ops.cron.>"]) + def test_wildcard_topic_raises(self, topic: str, settings: dict[str, Any], mock_registry: MagicMock) -> None: + unusable = _TestScheduler(topic=topic) + with pytest.raises(ValueError, match="not a usable subject"): + _ = unusable.tick_topic + + def test_whitespace_in_an_explicit_topic_raises(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + unusable = _TestScheduler(topic="ops cron nightly") + with pytest.raises(ValueError, match="contains whitespace"): + _ = unusable.tick_topic + + def test_whitespace_in_the_identity_is_rewritten_not_rejected(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + """A spaced app_name is legal and common, and the topic is derived, not typed.""" + settings["app_name"] = "Health Monitor" + derived = _TestScheduler() + assert derived.tick_topic == f"Health_Monitor.scheduler.{derived.name}" + + +class TestWire: + def test_event_mode_creates_a_tick_handler_on_the_tick_topic(self, scheduler: _TestScheduler) -> None: + handler = scheduler.wire() + assert isinstance(handler, SchedulerTickHandler) + assert handler.topic == scheduler.tick_topic + assert handler.scheduler is scheduler + assert scheduler.tick_handler is handler + + def test_in_process_mode_creates_no_tick_handler(self, in_process_scheduler: _TestScheduler) -> None: + assert in_process_scheduler.wire() is None + assert in_process_scheduler.tick_handler is None + + def test_wire_is_idempotent(self, scheduler: _TestScheduler) -> None: + first = scheduler.wire() + second = scheduler.wire() + assert first is second + + def test_wire_registers_the_trigger_route(self, scheduler: _TestScheduler) -> None: + scheduler.wire() + paths = [route.path for route in scheduler.router.routes if hasattr(route, "path")] + assert paths == [f"/{scheduler.name}/trigger"] + + def test_wire_registers_the_trigger_route_once(self, scheduler: _TestScheduler) -> None: + scheduler.wire() + scheduler.wire() + paths = [route.path for route in scheduler.router.routes if hasattr(route, "path")] + assert paths == [f"/{scheduler.name}/trigger"] + + def test_in_process_mode_still_registers_the_trigger_route(self, in_process_scheduler: _TestScheduler) -> None: + in_process_scheduler.wire() + paths = [route.path for route in in_process_scheduler.router.routes if hasattr(route, "path")] + assert paths == [f"/{in_process_scheduler.name}/trigger"] + + @pytest.mark.parametrize("bus", [None, "", "sessions"]) + def test_event_mode_without_a_usable_transport_raises( + self, bus: str | None, settings: dict[str, Any], mock_registry: MagicMock + ) -> None: + """Event mode with nothing to subscribe to would run forever without ticking.""" + settings["event_bus"] = bus + settings["scheduler_mode"] = SCHEDULER_MODE_EVENT + with pytest.raises(ValueError, match="'event_bus'"): + _TestScheduler().wire() + + @pytest.mark.parametrize("bus", ["dapr", "NATS"]) + def test_event_mode_accepts_either_broker_transport(self, bus: str, settings: dict[str, Any], mock_registry: MagicMock) -> None: + settings["event_bus"] = bus + settings["scheduler_mode"] = SCHEDULER_MODE_EVENT + assert _TestScheduler().wire() is not None + + def test_in_process_mode_needs_no_transport(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + settings["event_bus"] = "" + settings["scheduler_mode"] = SCHEDULER_MODE_IN_PROCESS + assert _TestScheduler().wire() is None + + +class TestSchedulerOnStartup: + async def test_event_mode_starts_no_timer(self, scheduler: _TestScheduler) -> None: + with patch("blueprint.agents.io.api.scheduling.scheduler.AsyncIOScheduler") as mock_sched_cls: + await scheduler.on_startup() + mock_sched_cls.assert_not_called() + assert scheduler._scheduler is None + + async def test_event_mode_wires_the_tick_handler(self, scheduler: _TestScheduler) -> None: + await scheduler.on_startup() + assert scheduler.tick_handler is not None + + async def test_in_process_mode_creates_apscheduler(self, in_process_scheduler: _TestScheduler) -> None: + with patch("blueprint.agents.io.api.scheduling.scheduler.AsyncIOScheduler") as mock_sched_cls: + mock_sched = MagicMock() + mock_sched_cls.return_value = mock_sched + await in_process_scheduler.on_startup() + mock_sched_cls.assert_called_once() + mock_sched.start.assert_called_once() + assert in_process_scheduler._scheduler is mock_sched + + async def test_in_process_mode_schedules_the_tick_on_the_crontab(self, in_process_scheduler: _TestScheduler) -> None: + with patch("blueprint.agents.io.api.scheduling.scheduler.AsyncIOScheduler") as mock_sched_cls: + mock_sched = MagicMock() + mock_sched_cls.return_value = mock_sched + await in_process_scheduler.on_startup() + job_args, job_kwargs = mock_sched.add_job.call_args + assert job_args[0] == in_process_scheduler._claimed_tick + assert job_kwargs["name"] == in_process_scheduler.name + + async def test_on_startup_registers_trigger_endpoint(self, scheduler: _TestScheduler) -> None: + await scheduler.on_startup() + paths = [route.path for route in scheduler.router.routes if hasattr(route, "path")] + assert paths == [f"/{scheduler.name}/trigger"] + + async def test_repeated_startup_starts_no_second_timer(self, in_process_scheduler: _TestScheduler) -> None: + """#43: two build() passes drive the lifespan twice over the same registry.""" + with patch("blueprint.agents.io.api.scheduling.scheduler.AsyncIOScheduler") as mock_sched_cls: + mock_sched_cls.return_value = MagicMock() + await in_process_scheduler.on_startup() + await in_process_scheduler.on_startup() + mock_sched_cls.assert_called_once() + + async def test_repeated_startup_adds_no_second_route(self, scheduler: _TestScheduler) -> None: + await scheduler.on_startup() + await scheduler.on_startup() + paths = [route.path for route in scheduler.router.routes if hasattr(route, "path")] + assert paths == [f"/{scheduler.name}/trigger"] + + class TestSchedulerOnShutdown: async def test_on_shutdown_calls_scheduler_shutdown(self, scheduler: _TestScheduler) -> None: mock_sched = MagicMock() @@ -70,20 +344,195 @@ async def test_on_shutdown_skips_shutdown_when_not_running(self, scheduler: _Tes await scheduler.on_shutdown() mock_sched.shutdown.assert_not_called() - -class TestSchedulerOnStartup: - async def test_on_startup_creates_apscheduler(self, scheduler: _TestScheduler) -> None: + async def test_shutdown_allows_a_later_restart(self, in_process_scheduler: _TestScheduler) -> None: with patch("blueprint.agents.io.api.scheduling.scheduler.AsyncIOScheduler") as mock_sched_cls: - mock_sched = MagicMock() - mock_sched_cls.return_value = mock_sched - await scheduler.on_startup() - mock_sched_cls.assert_called_once() - assert scheduler._scheduler is mock_sched + mock_sched_cls.return_value = MagicMock() + await in_process_scheduler.on_startup() + await in_process_scheduler.on_shutdown() + await in_process_scheduler.on_startup() + assert mock_sched_cls.call_count == 2 - async def test_on_startup_registers_trigger_endpoint(self, scheduler: _TestScheduler) -> None: + +class TestSchedulerTickHandler: + @pytest.fixture + def handler(self, scheduler: _TestScheduler) -> SchedulerTickHandler: + wired = scheduler.wire() + assert wired is not None + return wired + + def test_declares_the_tick_topic(self, handler: SchedulerTickHandler, scheduler: _TestScheduler) -> None: + assert handler.get_subscribed_topics() == [scheduler.tick_topic] + + def test_runs_ahead_of_the_default_handler_priority(self, handler: SchedulerTickHandler) -> None: + assert handler._priority < 100 + + def test_is_named_after_its_scheduler(self, handler: SchedulerTickHandler, scheduler: _TestScheduler) -> None: + assert handler.name == f"{scheduler.name}_tick" + + @pytest.mark.parametrize("context_key", ["nats_topic", "dapr_topic", "topic"]) + async def test_claims_a_delivery_on_its_own_topic( + self, context_key: str, handler: SchedulerTickHandler, scheduler: _TestScheduler + ) -> None: + assert await handler.can_handle_event(MagicMock(), {context_key: scheduler.tick_topic}) is True + + async def test_declines_another_topic(self, handler: SchedulerTickHandler) -> None: + assert await handler.can_handle_event(MagicMock(), {"nats_topic": "orders.created"}) is False + + async def test_declines_a_delivery_with_no_topic(self, handler: SchedulerTickHandler) -> None: + assert await handler.can_handle_event(MagicMock(), {}) is False + + async def test_handle_event_ticks_the_scheduler(self, handler: SchedulerTickHandler, scheduler: _TestScheduler) -> None: + result = await handler.handle_event(MagicMock(), {}) + assert scheduler.tick_call_count == 1 + assert result == {"status": "ticked", "scheduler": scheduler.name} + + async def test_handle_event_returns_no_event_to_publish(self, handler: SchedulerTickHandler) -> None: + """A plain dict stops the chain without publishing anything downstream.""" + result = await handler.handle_event(MagicMock(), {}) + assert "event_type" not in result + + async def test_a_failing_tick_reaches_the_transport_edge(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + settings["scheduler_mode"] = SCHEDULER_MODE_EVENT + failing = _FailingScheduler() + handler = failing.wire() + assert handler is not None + with pytest.raises(RuntimeError, match="tick exploded"): + await handler.handle_event(MagicMock(), {}) + + +class TestTickHandlerRegistration: + """Registration against a real Registry, where a name clash actually raises.""" + + def test_two_schedulers_register_distinct_tick_handlers(self, settings: dict[str, Any]) -> None: + settings["scheduler_mode"] = SCHEDULER_MODE_EVENT + Component.shared_registry = Registry(Component) + + class _FirstScheduler(_TestScheduler): + pass + + class _SecondScheduler(_TestScheduler): + pass + + first = _FirstScheduler().wire() + second = _SecondScheduler().wire() + + assert first is not None and second is not None + assert first.name != second.name + registered = Component.shared_registry.get_event_handler() + assert sorted(handler.name for handler in registered) == sorted([first.name, second.name]) + + +class TestClaimedTick: + """#73: every replica's timer fires, and the cache decides which one runs the tick.""" + + @pytest.fixture + def cached_scheduler(self, settings: dict[str, Any], mock_registry: MagicMock) -> _TestScheduler: + settings["scheduler_mode"] = SCHEDULER_MODE_IN_PROCESS + mock_registry.has_cache.return_value = True + return _TestScheduler() + + async def test_the_winner_ticks(self, cached_scheduler: _TestScheduler, mock_registry: MagicMock) -> None: + mock_registry.cache_service.claim.return_value = True + await cached_scheduler._claimed_tick() + assert cached_scheduler.tick_call_count == 1 + + async def test_a_loser_does_not_tick(self, cached_scheduler: _TestScheduler, mock_registry: MagicMock) -> None: + mock_registry.cache_service.claim.return_value = False + await cached_scheduler._claimed_tick() + assert cached_scheduler.tick_call_count == 0 + + async def test_the_claim_is_keyed_on_the_scheduler_and_the_minute( + self, cached_scheduler: _TestScheduler, mock_registry: MagicMock + ) -> None: + mock_registry.cache_service.claim.return_value = True + await cached_scheduler._claimed_tick() + + key = mock_registry.cache_service.claim.call_args[0][0] + assert key["scheduler"] == cached_scheduler.name + # Minute precision: cron granularity, so replicas firing for one slot agree on it. + assert len(key["slot"]) == len("2026-09-04T03:00") + + async def test_the_claim_carries_a_ttl_and_its_own_namespace(self, cached_scheduler: _TestScheduler, mock_registry: MagicMock) -> None: + mock_registry.cache_service.claim.return_value = True + await cached_scheduler._claimed_tick() + + kwargs = mock_registry.cache_service.claim.call_args.kwargs + assert kwargs["namespace"] == TICK_CACHE_NAMESPACE + assert kwargs["ttl"] == TICK_CLAIM_TTL_SECONDS + + async def test_three_replicas_run_one_tick(self, settings: dict[str, Any], tmp_path: Path) -> None: + """The acceptance criterion, against a real cache shared by three schedulers.""" + settings["scheduler_mode"] = SCHEDULER_MODE_IN_PROCESS + Component.shared_registry = Registry(Component) + cache = DiskCacheService(cache_dir=str(tmp_path / "cache")) + Component.shared_registry.cache_service = cache + try: + replicas = [] + for index in range(3): + replica = _TestScheduler() + # Three processes are simulated inside one registry, so each instance needs a + # distinct registry key -- while all three answer to the one agent name the + # slot key is derived from, which is the point of the test. + replica.name = f"replica-{index}" + replica._name = "nightly_scheduler" + replicas.append(replica) + + for replica in replicas: + await replica._claimed_tick() + + assert sum(replica.tick_call_count for replica in replicas) == 1 + finally: + cache.close() + + async def test_a_later_slot_is_claimable_again(self, settings: dict[str, Any], tmp_path: Path) -> None: + """The key carries the minute, so the next scheduled tick is a fresh claim.""" + settings["scheduler_mode"] = SCHEDULER_MODE_IN_PROCESS + Component.shared_registry = Registry(Component) + cache = DiskCacheService(cache_dir=str(tmp_path / "cache")) + Component.shared_registry.cache_service = cache + try: + scheduler = _TestScheduler() + with patch(f"{_SCHEDULER_MODULE}.datetime") as clock: + clock.now.return_value.strftime.return_value = "2026-09-04T03:00" + await scheduler._claimed_tick() + await scheduler._claimed_tick() + clock.now.return_value.strftime.return_value = "2026-09-04T04:00" + await scheduler._claimed_tick() + assert scheduler.tick_call_count == 2 + finally: + cache.close() + + async def test_without_a_cache_every_replica_ticks(self, in_process_scheduler: _TestScheduler, mock_registry: MagicMock) -> None: + """Nothing to claim with, so the mode behaves as it did before -- and startup warns.""" + mock_registry.has_cache.return_value = False + await in_process_scheduler._claimed_tick() + assert in_process_scheduler.tick_call_count == 1 + mock_registry.cache_service.claim.assert_not_called() + + async def test_the_timer_runs_the_claimed_tick_not_the_raw_one(self, cached_scheduler: _TestScheduler) -> None: with patch("blueprint.agents.io.api.scheduling.scheduler.AsyncIOScheduler") as mock_sched_cls: mock_sched = MagicMock() mock_sched_cls.return_value = mock_sched - await scheduler.on_startup() - route_paths = [r.path for r in scheduler.router.routes if hasattr(r, "path")] - assert any(scheduler.name in p for p in route_paths) + await cached_scheduler.on_startup() + + assert mock_sched.add_job.call_args[0][0] == cached_scheduler._claimed_tick + + async def test_startup_warns_when_ticks_cannot_be_coordinated( + self, in_process_scheduler: _TestScheduler, mock_registry: MagicMock, caplog: pytest.LogCaptureFixture + ) -> None: + mock_registry.has_cache.return_value = False + with patch("blueprint.agents.io.api.scheduling.scheduler.AsyncIOScheduler"): + with caplog.at_level(logging.WARNING): + await in_process_scheduler.on_startup() + + assert "every replica of this process will run every tick" in caplog.text + + async def test_event_mode_does_not_claim(self, scheduler: _TestScheduler, mock_registry: MagicMock) -> None: + """In event mode the queue group already picks one replica; a claim would be redundant.""" + mock_registry.has_cache.return_value = True + handler = scheduler.wire() + assert handler is not None + await handler.handle_event(MagicMock(), {}) + + assert scheduler.tick_call_count == 1 + mock_registry.cache_service.claim.assert_not_called() diff --git a/tests/unit/agents/services/TESTS.md b/tests/unit/agents/services/TESTS.md index 4f9f6260..dd98ba0d 100644 --- a/tests/unit/agents/services/TESTS.md +++ b/tests/unit/agents/services/TESTS.md @@ -10,7 +10,9 @@ Test coverage for `src/blueprint/agents/services/`. |---|---|---| | `eventing/test_event_processing_service.py` | `EventProcessingService` | `_extract_handler_results` (None/HandlerResult/list/dict variants), `_build_result` (message text, request_id, result list), `_unwrap_dapr_event` (passthrough / CloudEvent inner / dict inner / missing type / unexpected type), lifecycle no-ops, `process_rest_request` delegates to `process_event` with correct event shape | | `eventing/test_event_publishing_service.py` | `EventPublishingService` | `on_startup` wires client and config, `_get_pub_config` raises before startup, `get_topic_for_event_type` / `get_available_event_types`, `publish_event` (topic mapping, explicit topic override, missing mapping raises, sets default source, result shape), `publish_handler_event` (no mapping → skip, loop prevention → skip, normal → publishes), `publish_status_event` type format and delegation | -| `infrastructure/test_disk_cache_service.py` | `DiskCacheService` | `set`/`get` (string/dict/list keys, namespace isolation), `delete` (return values), `exists` (before/after set/delete), `clear` (namespace-scoped and full), TTL expiration via mocked `time.time`, `hash` consistency for string/list/dict inputs, `list_namespaces`, `list_values` (content, TTL-entry exclusion, limit), `get_stats` field presence, lifecycle, context-manager protocol | +| `infrastructure/test_disk_cache_service.py` | `DiskCacheService` | `set`/`get` (string/dict/list keys, namespace isolation), `delete` (return values), `exists` (before/after set/delete), `clear` (namespace-scoped and full), TTL expiration via mocked `time.time`, `hash` consistency for string/list/dict inputs, `list_namespaces`, `list_values` (content, TTL-entry exclusion, limit), `get_stats` field presence, lifecycle, context-manager protocol; `claim` set-if-absent (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, keys and namespaces independent, dict keys hashed consistently, TTL recorded so readers see expiry, a logically expired claim taken over, no TTL never expires, and an unreachable cache failing open) | +| `infrastructure/test_redis_cache_service.py` | `RedisCacheService` | Backed by `fakeredis`. `claim` via `SET NX EX` (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, the TTL is applied to the key, namespaces are independent, and an unreachable cache fails open). *The rest of this file's coverage predates this table and is not itemised here.* | +| `infrastructure/test_cache_backend_factory.py`, `infrastructure/test_cache_sharing_via_registry.py`, `infrastructure/test_redis_url_utils.py` | `CacheBackendFactory`, registry cache sharing, Redis URL helpers | Present but not itemised in this table. | | `sessions/test_api_client.py` | `SessionsApiClient` | `on_startup` (valid config, missing config/base_url/api_key → ValueError), `on_shutdown` (closes client, no-op when uninitialised), `get_job_detail`/`start_job`/`complete_job`/`cancel_job` (URL shape, required headers, payload contents, uninitialised guard) | | `sessions/test_key_provider.py` | `SessionKeyProvider` | `on_startup` (initialises cache, reads source/env_var from config, missing config → ValueError), `on_shutdown` (clears cache, no-op when uninitialised), `get_session_key` (env hit/miss, config source, vault → NotImplementedError, remote source via respx — happy path/caching/404/missing session_id/missing URL, unknown source, cache-hit bypass, result cached after fetch), `invalidate_cache` (default and per-session key removal, no-op when empty/uninitialised) | diff --git a/tests/unit/agents/services/infrastructure/test_disk_cache_service.py b/tests/unit/agents/services/infrastructure/test_disk_cache_service.py index d986dca8..22d146a0 100644 --- a/tests/unit/agents/services/infrastructure/test_disk_cache_service.py +++ b/tests/unit/agents/services/infrastructure/test_disk_cache_service.py @@ -244,3 +244,63 @@ async def test_on_shutdown_calls_close(self, cache_service: DiskCacheService) -> def test_context_manager_returns_self(self, tmp_path, mock_registry, mock_config) -> None: with DiskCacheService(cache_dir=str(tmp_path / "ctx-cache")) as svc: assert isinstance(svc, DiskCacheService) + + +# --------------------------------------------------------------------------- +# claim +# --------------------------------------------------------------------------- + + +class TestClaim: + """Set-if-absent, which `exists` then `set` cannot provide.""" + + def test_first_claim_succeeds(self, cache_service: DiskCacheService) -> None: + assert cache_service.claim("slot", {"by": "a"}) is True + + def test_second_claim_on_the_same_key_fails(self, cache_service: DiskCacheService) -> None: + cache_service.claim("slot", {"by": "a"}) + assert cache_service.claim("slot", {"by": "b"}) is False + + def test_the_loser_does_not_overwrite_the_winner(self, cache_service: DiskCacheService) -> None: + cache_service.claim("slot", {"by": "a"}) + cache_service.claim("slot", {"by": "b"}) + assert cache_service.get("slot") == {"by": "a"} + + def test_exactly_one_of_many_callers_wins(self, cache_service: DiskCacheService) -> None: + results = [cache_service.claim("slot", {"by": index}) for index in range(5)] + assert results.count(True) == 1 + + def test_different_keys_are_independent(self, cache_service: DiskCacheService) -> None: + assert cache_service.claim("slot-a", 1) is True + assert cache_service.claim("slot-b", 1) is True + + def test_namespace_isolates_claims(self, cache_service: DiskCacheService) -> None: + assert cache_service.claim("slot", 1, namespace="ns-a") is True + assert cache_service.claim("slot", 1, namespace="ns-b") is True + + def test_a_dict_key_claims_consistently(self, cache_service: DiskCacheService) -> None: + assert cache_service.claim({"scheduler": "nightly", "slot": "2026-09-04T03:00"}, 1) is True + assert cache_service.claim({"slot": "2026-09-04T03:00", "scheduler": "nightly"}, 1) is False + + def test_ttl_is_recorded_so_the_entry_expires_for_readers(self, cache_service: DiskCacheService) -> None: + """diskcache-rs ignores its own expire argument, so the TTL metadata carries it.""" + cache_service.claim("slot", 1, ttl=60) + with patch(f"{_TIME_MODULE}.time", return_value=9_999_999_999): + assert cache_service.exists("slot") is False + + def test_a_logically_expired_claim_can_be_taken_over(self, cache_service: DiskCacheService) -> None: + cache_service.claim("slot", {"by": "a"}, ttl=60) + with patch(f"{_TIME_MODULE}.time", return_value=9_999_999_999): + assert cache_service.claim("slot", {"by": "b"}, ttl=60) is True + assert cache_service.get("slot") == {"by": "b"} + + def test_a_claim_without_ttl_never_expires(self, cache_service: DiskCacheService) -> None: + cache_service.claim("slot", 1) + with patch(f"{_TIME_MODULE}.time", return_value=9_999_999_999): + assert cache_service.claim("slot", 2) is False + + def test_an_unreachable_cache_fails_open(self, cache_service: DiskCacheService) -> None: + """The caller must still do its work when the cache cannot answer.""" + with patch.object(cache_service, "_cache") as broken: + broken.add.side_effect = OSError("disk gone") + assert cache_service.claim("slot", 1) is True diff --git a/tests/unit/agents/services/infrastructure/test_redis_cache_service.py b/tests/unit/agents/services/infrastructure/test_redis_cache_service.py index ea2312a1..bea523db 100644 --- a/tests/unit/agents/services/infrastructure/test_redis_cache_service.py +++ b/tests/unit/agents/services/infrastructure/test_redis_cache_service.py @@ -333,3 +333,35 @@ def test_get_stats_redacts_credentials(self, redis_cache_service: RedisCacheServ stats = redis_cache_service.get_stats() assert stats["redis_url"] == "" assert "supersecret" not in stats["redis_url"] + + +class TestClaim: + """`SET NX EX` is one server-side operation, so there is no stale-takeover branch.""" + + def test_first_claim_succeeds(self, redis_cache_service: RedisCacheService) -> None: + assert redis_cache_service.claim("slot", {"by": "a"}) is True + + def test_second_claim_on_the_same_key_fails(self, redis_cache_service: RedisCacheService) -> None: + redis_cache_service.claim("slot", {"by": "a"}) + assert redis_cache_service.claim("slot", {"by": "b"}) is False + + def test_the_loser_does_not_overwrite_the_winner(self, redis_cache_service: RedisCacheService) -> None: + redis_cache_service.claim("slot", {"by": "a"}) + redis_cache_service.claim("slot", {"by": "b"}) + assert redis_cache_service.get("slot") == {"by": "a"} + + def test_exactly_one_of_many_callers_wins(self, redis_cache_service: RedisCacheService) -> None: + results = [redis_cache_service.claim("slot", {"by": index}) for index in range(5)] + assert results.count(True) == 1 + + def test_ttl_is_applied_to_the_claim(self, redis_cache_service: RedisCacheService) -> None: + redis_cache_service.claim("slot", 1, ttl=60) + assert 0 < redis_cache_service._client.ttl(redis_cache_service._full_key("slot", "default")) <= 60 + + def test_namespace_isolates_claims(self, redis_cache_service: RedisCacheService) -> None: + assert redis_cache_service.claim("slot", 1, namespace="ns-a") is True + assert redis_cache_service.claim("slot", 1, namespace="ns-b") is True + + def test_an_unreachable_cache_fails_open(self, redis_cache_service: RedisCacheService) -> None: + with patch.object(redis_cache_service._client, "set", side_effect=ConnectionError("redis gone")): + assert redis_cache_service.claim("slot", 1) is True diff --git a/tests/unit/agents/utils/TESTS.md b/tests/unit/agents/utils/TESTS.md index c117d8ec..5d7dfcb1 100644 --- a/tests/unit/agents/utils/TESTS.md +++ b/tests/unit/agents/utils/TESTS.md @@ -9,11 +9,12 @@ Test coverage for `src/blueprint/agents/utils/utils.py`. | File | Function under test | What is covered | |---|---|---| | `test_camel_to_snake.py` | `camel_to_snake` | Standard CamelCase, acronyms (leading/mid/trailing), numbers, edge cases | +| `test_parse_bool.py` | `parse_bool` | Real bools pass through; the truthy and falsy strings an environment override delivers (`true`/`1`/`yes`, `false`/`0`/`no`, case and whitespace tolerant); everything else raises rather than reading as false, including empty and whitespace-only; the error names the key | --- ## Decisions ### No conftest needed -`camel_to_snake` is a pure function with no dependencies or side effects. +`camel_to_snake` and `parse_bool` are pure functions with no dependencies or side effects. All inputs are inline string literals — no fixtures, no shared state. diff --git a/tests/unit/agents/utils/test_parse_bool.py b/tests/unit/agents/utils/test_parse_bool.py new file mode 100644 index 00000000..15e46a46 --- /dev/null +++ b/tests/unit/agents/utils/test_parse_bool.py @@ -0,0 +1,30 @@ +"""Unit tests for parse_bool.""" + +import pytest + +from blueprint.agents.utils import parse_bool + + +class TestParseBool: + @pytest.mark.parametrize("value", [True, False]) + def test_a_real_bool_passes_through(self, value: bool) -> None: + assert parse_bool(value, "some_key") is value + + @pytest.mark.parametrize("value", ["true", "TRUE", " True ", "1", "yes"]) + def test_truthy_strings(self, value: str) -> None: + """An environment override arrives as text, so "true" must mean True.""" + assert parse_bool(value, "some_key") is True + + @pytest.mark.parametrize("value", ["false", "FALSE", " False ", "0", "no"]) + def test_falsy_strings(self, value: str) -> None: + assert parse_bool(value, "some_key") is False + + @pytest.mark.parametrize("value", ["maybe", "", " ", None, 2, 1.5, [], {}]) + def test_anything_else_raises(self, value: object) -> None: + """A typo must not be read as false and silently disable a feature.""" + with pytest.raises(ValueError, match="must be a boolean"): + parse_bool(value, "some_key") + + def test_the_error_names_the_key(self) -> None: + with pytest.raises(ValueError, match="idempotency_enabled"): + parse_bool("nope", "idempotency_enabled") From 98546124302e295d59855e67010646cec29ac074 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:44:47 +0200 Subject: [PATCH 005/133] feat(namespaces): P6, the transport client belongs to a namespace Clients take a namespace, register under a namespace-qualified name so two can coexist in one registry, and derive queue group and durable from the namespace alone -- without which two co-hosted agents on one topic would share a queue group and each see half their events. Connections are named .., so a pod's contents are legible in /connz while nothing broker-side derives from the pod (C1). One definition of the root namespace, and one alphabet validated wherever a namespace enters the framework. Co-Authored-By: Claude Opus 5 (1M context) --- .gitignore | 3 + ...26-08-28-multi-agent-grouping-changelog.md | 246 ++++++++++++++++++ docs/plans/2026-08-28-multi-agent-grouping.md | 10 +- docs/reference/configuration-keys.md | 67 ++++- docs/specs/2026-08-28-multi-agent-grouping.md | 56 +++- src/blueprint/agents/clients/client_base.py | 14 +- .../agents/clients/io/dapr_client.py | 16 +- .../agents/clients/io/io_client_base.py | 74 ++++++ .../agents/clients/io/nats_client.py | 175 +++++++++++-- src/blueprint/agents/component/component.py | 39 ++- src/blueprint/agents/component/namespace.py | 187 +++++++++++++ .../io/api/eventing/event_handling_base.py | 12 +- .../agents/io/api/scheduling/scheduler.py | 65 ++--- .../eventing/event_publishing_service.py | 35 ++- src/blueprint/agents/services/service_base.py | 14 +- .../agents/clients/io/test_dapr_client.py | 30 +++ .../agents/clients/io/test_nats_client.py | 229 +++++++++++++++- tests/unit/agents/component/test_namespace.py | 129 +++++++++ .../io/api/scheduling/test_scheduler.py | 32 ++- .../unit/agents/services/eventing/conftest.py | 3 +- .../eventing/test_event_publishing_service.py | 76 +++++- 21 files changed, 1409 insertions(+), 103 deletions(-) create mode 100644 src/blueprint/agents/component/namespace.py create mode 100644 tests/unit/agents/component/test_namespace.py diff --git a/.gitignore b/.gitignore index 1c8ef79e..6b349575 100644 --- a/.gitignore +++ b/.gitignore @@ -158,3 +158,6 @@ uv.lock ARCHITECTURE_DECISIONS.md + +# Private, machine-local Claude Code instructions +CLAUDE.local.md diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index c793d1ae..40558e23 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -46,6 +46,9 @@ Design and specification: Code: +- **P6 review follow-up -- namespace identity**: one definition of the root namespace, one + alphabet validated where a namespace enters the framework, an unambiguous durable name and + unforgeable connection-name placeholders (`be5e489`) - **P0 -- transport lifecycle**: managed whole-map `subscribe()`, background retry, reconnect re-subscription, `subscriptions_ready` readiness gating (`77af507`) - **P0 -- shutdown drain**: in-flight handlers finish before the connection closes (`585e58c`) @@ -103,6 +106,15 @@ Code: left on that mode - **New cache primitive `CacheService.claim`**: set-if-absent, atomic on both backends (`add` on disk, `SET NX EX` on Redis). This is the compare-and-set operation P4 flagged as missing +- **P6 -- the transport client belongs to a namespace, not to the process**: clients take a + namespace, register under a namespace-qualified name so two can coexist in one registry, and + derive queue group and durable from the namespace alone -- without that, two co-hosted agents + subscribing to one topic would share a queue group and each see half its events +- **P6 -- connections are no longer anonymous**: `nats.connect()` is called with + `name=f"{namespace}.{group}.{pod}"`, which makes a pod's contents legible in `/connz`. The name + carries the pod, so nothing broker-side may derive from it (C1) -- asserted by test +- **P6 -- `EventPublishingService` publishes on its own namespace's client**, resolved namespace + first then root, raising rather than guessing when that is ambiguous Documentation and process: @@ -1146,6 +1158,214 @@ the timer is wired to the wrapper, and event mode claims nothing); and `claim` o (first wins, second refused, the loser does not overwrite, exactly one of five concurrent callers wins, TTL behaviour, namespace isolation, stale takeover on disk, and failing open). +### P6 -- one transport connection per namespace, and named connections (`be5e489`) + +The transport client stops being a process singleton and becomes namespace-owned. Nothing +creates a second one yet -- Phases 5 and 6 do that -- so for every application that exists +today this is a no-op with one visible change: connections are no longer anonymous. + +**`IOClientBase` takes a namespace, and derives the registry name from it.** +`IOClientBase.__init__(namespace="")` stores the namespace, exposes it as a public +`namespace` property, and registers the component as `qualified_component_name(namespace, +camel_to_snake(cls.__name__))` -- `nats_client` at the root, `orders_nats_client` under a +namespace. That last part is what makes the topology possible at all: `Registry.add_component` +raises on a duplicate name, so before this a second transport client of the same class raised +at construction. `NATSClient` and `DaprClient` both forward the parameter. + +Naming had to move *into* the constructor to work. `Component.__init__` registers the instance, +so the pre-existing pattern of renaming afterwards (`AIClientBase` still does it) cannot help: +the collision happens during `super().__init__()`, before any rename could run. `Component` +therefore gained a `name: str | None = None` parameter that overrides the class-derived name, +forwarded through `ClientBase` and `ServiceBase`. Both default to the old behaviour. + +**Connections are named `f"{namespace}.{group}.{pod}"`.** `nats.connect()` was called with no +`name=`, so every connection this framework opened was anonymous in `/connz` and a pod hosting +several agents was unreadable from the broker side. `_resolve_connection_name()` fills the three +positions from the namespace, `BLUEPRINT_GROUP` and `POD_NAME`/`HOSTNAME`/`socket.gethostname()`, +and `connect()` passes the result and records it on a public `connection_name` property. + +The group and pod are read from `os.environ` rather than through `Config`, because group +composition decides which agents get a `Config` at all (spec sec. 5.1) -- the group loader that +will own the variable arrives with the group configuration in Phase 8. Absent segments get a +placeholder (`root`, `ungrouped`, `unknown-pod`) rather than being left empty, so a name cannot +degenerate into `..pod-7` and "no group" stays distinguishable from a group whose name is empty. +The spec was amended to state that rule. + +**Consumer identity follows the namespace, which is the part that had to land with the +ownership change rather than after it.** Once two clients can share a process, the queue group +and the durable name can no longer come from process-wide config: + +- `_resolve_queue_group()` returns the namespace when there is one. Only the root namespace still + falls back to `nats_queue_group` then `app_name` -- which is what `nats_queue_group` is + documented to be, "the queue group for the root namespace only". Without the branch, every + client in a process resolves the same `app_name`, and two co-hosted agents subscribing to one + topic form a single queue group: the broker then hands each event to exactly one of the two + agents, so each silently sees about half of what it subscribed to. +- `_durable_for()` prefixes the namespace, so `orders` on `orders.created` binds + `orders-orders_created-durable`. Same failure otherwise, one layer down: two namespaces + resolving one durable name bind to the same JetStream consumer and consume each other's + events. The whole name is still sanitised, so a dotted namespace stays a legal consumer name. +- A configured `nats_durable_name` under a namespace now warns, naming the consequence. It is + legitimate when the key is scoped per namespace, and fatal when it is not, and the framework + cannot yet tell which -- config scoping (C5) is Phase 1. + +The durable prefix is Phase 5's item in the plan, taken early deliberately: P6 is what makes +co-hosted clients possible, so shipping it without namespace-qualified durables would ship a +latent cross-agent collision. It is dormant until a namespace exists -- the root namespace keeps +`-durable` -- so no deployment of this change is a consumer migration. Phase 5's own +migration note still applies to the filter-set work. + +**Deployment identity must never reach broker identity (C1).** The connection name contains the +pod, so a queue group or durable derived from it would change on every restart and every +regrouping. It is deliberately not stored where either is resolved, and a test asserts that a +junk `BLUEPRINT_GROUP` and `POD_NAME` leave both untouched. + +**`EventPublishingService` becomes per-namespace.** It takes a `namespace`, registers under the +qualified name, and `on_startup` resolves *its own* namespace's client instead of asking the +registry for "the" `IOClientBase`. Publishing another namespace's events down a shared +connection would make outbound traffic unattributable, which is the whole of reason 3. + +Resolution is the spec's rule -- own namespace, then root, raising rather than guessing -- and +lives in the new `component/namespace.py` alongside the naming helper, because the registry has +no namespace dimension yet (Phase 1) and both operations recur wherever a component becomes +namespace-owned. `resolve_for_namespace` raises on ambiguity instead of taking the first match: +picking one of two silently attaches an agent to another agent's transport. A namespace with no +client of its own falls back to the root one, so a namespaced agent in a process with a single +shared transport keeps working. + +**What P6 does not do, on purpose.** `DaprClient` accepts a namespace for health attribution and +C4, and its docstring says plainly that it confines neither ack loss nor slow-consumer +disconnects: it holds no broker connection, the sidecar owns and multiplexes one per pod, and +there is correspondingly nothing to name. Nothing in `app_builder.py` changed -- it still creates +one root-namespace client, which is exactly what a single-agent application should get, and the +rule that a namespace which neither subscribes nor publishes gets no client is already the +process-level behaviour there. `NatsEventing` still resolves the client by type; Phase 5 owns that +call site and reworks it per namespace. + +**Tests.** 50 new unit tests: namespace naming and resolution (`test_namespace.py`), client +ownership and coexistence, queue-group and durable derivation including the two-namespaces-on-one-topic +cases, the connection-name shape and every fallback in it, the C1 assertion that deployment identity +reaches neither, the Dapr namespace parameter, and the publishing service's resolution and its four +failure modes. Two existing publishing-service tests were updated: client resolution moved from +`get_component(IOClientBase)` to `get_io_clients()` plus the namespace filter. + +**Documentation.** `configuration-keys.md` gains a *Deployment Identity (environment only)* +section for `BLUEPRINT_GROUP`, `POD_NAME` and `HOSTNAME`, and the `nats_queue_group` and +`nats_durable_name` rows now say what a namespace does to them. Spec sec. 6 gains the placeholder +rule. + +### P6 review follow-up -- the namespace gets one definition, one alphabet, one gate (`be5e489`) + +Four defects found reviewing P6, all of which turned out to be the same defect: nothing said what +a namespace is allowed to look like, so each consumer of it decided separately. `component/namespace.py` +is now the single answer, and the four symptoms fall out of it. + +**One definition of the root namespace.** `ROOT_NAMESPACE` was declared three times -- in +`component/namespace.py`, as a class attribute on `EventHandlingBase` (`event_handling_base.py:48`) +and at module level in `scheduler.py:66`, the last two predating P6. Both now import the one in +`namespace.py`; the metric labels in `handle_event` read the imported constant instead of +`self.ROOT_NAMESPACE`. The constant's docstring now also says why it is not configurable: three +call sites branch on it being falsy, so a root namespace with a value renames every registry key +and every broker-side consumer, which is what C1 exists to prevent. + +**One alphabet, enforced at the point of entry.** New `validate_namespace()`: a namespace is `""` +or matches `[a-z][a-z0-9_]*`, and is rejected rather than repaired. It is called from +`IOClientBase.__init__` and `EventPublishingService.__init__`, replacing the `.strip()` that used +to silently repair `" orders "` while `"my orders"` blew up much later. Two exclusions carry +their reason in the error message: `-`, because it separates the fields of the durable name, and +`<`/`>`, because they are what make the connection-name placeholders unforgeable. + +The check it replaces was in `_resolve_queue_group()`, which is reached only by a NATS client that +subscribes -- so a publish-only namespace, or a Dapr one, kept an illegal name in its registry key, +its durable and (from C2) its telemetry resource without anything raising. Validation at +construction covers all of them, and the queue group now returns the namespace verbatim. + +**The durable name became unambiguous.** Forbidding `-` in a namespace is what makes +`f"{namespace}-{topic}-durable"` readable back: the first `-` is always the namespace boundary. +Before, namespace `orders-eu` on topic `created` and namespace `orders` on topic `eu-created` +produced the same durable, so two agents would have bound one JetStream consumer and consumed each +other's events -- the exact failure the namespace prefix was added to prevent. `_durable_for` now +rewrites only the topic (`f"{prefix}{re.sub(...)}-durable"` rather than sanitising the whole +string), because the namespace was already validated against an alphabet a consumer name accepts. + +**The connection-name placeholders became unforgeable.** `UNNAMED_NAMESPACE = "root"` collided with +a namespace actually called `root`, which is the ambiguity the placeholders were introduced to +remove. There is now one bracketed spelling -- `ROOT_LABEL` (`""`), reused for messages and +for the connection name -- plus `UNGROUPED_LABEL` and `UNKNOWN_POD_LABEL`. Since `<` and `>` are +outside the namespace alphabet, no namespace can spell one. + +The group and the pod are not ours to validate: they arrive from a pod template, and failing a +rollout over a display string is the wrong trade. New `display_segment()` sanitises them instead -- +`<`, `>`, `.` and whitespace become `_` -- so a group called `eu.west` cannot turn a three-segment +name into four (`.eu_west.pod-1`), an FQDN in `HOSTNAME` stays one segment, and nothing from +the environment can forge a placeholder. Sanitising is acceptable only because C1 forbids anything +deriving from the connection name, so a mangled segment loses no information downstream. + +**The gate moved from the two namespace-owned bases into `Component.__init__`, and `Component` +now owns the namespace.** `Component.__init__(should_register, name, namespace="")` validates the +namespace, then derives the registry name from it through `qualified_component_name`, and exposes a +public `namespace` property. `IOClientBase.__init__` collapsed to `super().__init__(namespace=namespace)` +-- its `_namespace` assignment, its `namespace` property and its `_base_component_name` classmethod +are all gone, and `EventPublishingService` lost the same three. `ClientBase` and `ServiceBase` +forward the parameter. + +Two reasons this is not `Registry.add_component`, which was the other candidate. Coverage: eight +components construct with `should_register=False` -- `agent_runtime`, `handler_chain`, +`actuator_api`, `cache`, `root`, `telemetry`, and the `nats.py` and `dapr.py` eventing endpoints, +the last two of which become namespace-owned in phase 2 -- and a gate in the registry never sees +them. Ordering: `Component.__init__` runs before the name is derived and before registration, so +the illegal namespace never becomes a registry key even transiently. Having `Component` own the +namespace outright is what makes the gate sound: reading it back off a subclass attribute would +have left the check dependent on every subclass assigning `_namespace` before calling +`super().__init__()`. + +**Names that cross the process boundary are validated, not repaired.** New +`validate_subject_segment(segment, *, source, subject)` in `io_client_base.py`, applied at three +call sites, replacing two silent rewrites and one partial check: + +- `SchedulerBase.tick_topic` derived the subject as `re.sub(r"\s+", "_", f"{identity}.scheduler.{self.name}")`. + That subject is the contract: a `CronJob`, usually in another repository, publishes to it. An + `app_name` of `"Health Monitor"` silently became `Health_Monitor.scheduler.nightly`, so the + manifest author -- who cannot see the rewrite -- publishes to a subject this scheduler does not + subscribe to, the tick never arrives, and neither side logs anything. Both derived parts are now + validated instead, and the error names the key, the value and the subject it would have produced. + The scheduler's own name is checked too, because `with_scheduler(name=...)` reaches the subject. +- The explicit `topic=` override kept its whitespace check but had a separate wildcard check below + it; both are now the one helper, so the two paths cannot drift apart again. +- `_resolve_queue_group()`'s root fallback checked whitespace only. A queue group is read in + `/connz` *and* seeds the default dead-letter subject `.dead-letter`, so an + `app_name` of `my*service` produced a wildcard subject that the framework then publishes to. + Now rejected with the rest. + +The two rewrites that stay are named in the helper's docstring and in the spec: the topic portion +of a durable name (dots are legal in subjects, illegal in consumer names, so there is no +alternative -- bounded by the existing collision error) and the connection name (attribution only, +and C1 forbids anything deriving from it, so nothing outside can depend on its spelling). + +**One defect introduced and caught during this change:** inserting the `namespace` property between +`Component.name`'s getter and its `@name.setter` silently deleted the setter, which +`with_agent(name=...)`, `with_scheduler(name=...)`, `with_rest_api(name=...)` and `AIClientBase` +all assign through. `mypy` caught it as eight errors across four files; the property now sits below +the setter. + +**Tests.** 1337 unit tests pass (up from 1323). `test_namespace.py` gains `TestValidateNamespace` +and `TestDisplaySegment`, including the assertion that `ROOT_LABEL` cannot be produced by a legal +namespace. Four NATS tests changed to match the new behaviour rather than the old: whitespace and +dotted namespaces are now rejected at construction instead of trimmed or rewritten, and a +hyphenated one is rejected with the collision named. Three new connection-name tests cover the +dotted group, the forged placeholder and the FQDN host name. Five scheduler tests changed or were +added around the tick subject: the spaced `app_name` case inverted from "is rewritten" to "is +rejected", plus a wildcard identity, a spaced scheduler name, and an assertion that the error names +the key, the value and the subject. One NATS test gained the wildcard queue group; another had its +message assertion reordered. + +**Documentation.** Spec sec. 6 gains the unforgeability rule and the sanitise-not-validate rule for +group and pod; C1 gains the namespace alphabet and both exclusions with their reasons. +`configuration-keys.md` gains a *Namespace names* table, a *Names that become subjects are never +rewritten for you* section and the corrected placeholder spellings. C1 also gains the +validate-never-repair rule for boundary-crossing names, the two permitted exceptions, and the +requirement that the namespace gate live in `Component.__init__`. + ### Deployment guide corrected (`2d80b63`) The guide recommended `replicaCount: 2`, an HPA, and `--set replicaCount=3` as ordinary scaling. It @@ -1191,8 +1411,34 @@ the no-op migration. `"event"` is the one that fixes #73, and until P5's second `CronJob` the publisher has to be written by hand, which is why the second row is not yet the recommended answer for anyone. +**A spaced `app_name` now fails an event-mode scheduler's startup instead of being rewritten.** +This is the one behaviour change here that can affect an existing project: `app_name = "Health +Monitor"` with `scheduler_mode = "event"` used to derive the tick subject +`Health_Monitor.scheduler.` and now raises at startup, naming the key, the value and that +subject. The rewrite was never safe -- the `CronJob` publishing the tick is written against the +subject by someone who cannot see the rewrite, so the failure it produced was a tick that never +arrived and no log line anywhere explaining it. Migration is either renaming `app_name` to a +subject-safe value or passing `topic=` explicitly. A wildcard in `app_name` or `nats_queue_group` +likewise now fails, where before it reached the broker as a queue name and seeded a wildcard +dead-letter subject. + +**The namespace alphabet is a constraint on code that does not exist yet.** Nothing constructs a +namespaced client today, so no name in any deployment is affected; a namespace must now be `""` or +`[a-z][a-z0-9_]*`, which is enforced before the first namespaced agent can be declared. Doing it +now is free -- after the first namespaced deployment, changing the alphabet would rename durables, +and renaming a durable is a consumer migration (spec sec. 7.7). + Everything else remains non-breaking. Specifically: +- `Component.__init__`, `ClientBase.__init__` and `ServiceBase.__init__` gained an optional + `name` parameter, and `IOClientBase.__init__`, `NATSClient.__init__`, `DaprClient.__init__` and + `EventPublishingService.__init__` an optional `namespace`. All default to the previous + behaviour, and the root namespace keeps every existing registry name, so no existing + construction site or lookup changes. +- `NATSClient._durable_for` became an instance method (it reads the namespace). It is private; + the public `nats_durable_name` behaviour is unchanged for the root namespace. +- `EventPublishingService.on_startup` now raises a different message when no transport client is + registered -- it names the namespace it looked in. It raised before too, so this is wording. - `ClientBase.subscribe`'s abstract signature changed from `(topic, callback)` to `(topic_callbacks)` in P0. This is the one signature change in the feature so far; it affects implementations of the transport-client interface, of which the repo contains two (`NATSClient`, diff --git a/docs/plans/2026-08-28-multi-agent-grouping.md b/docs/plans/2026-08-28-multi-agent-grouping.md index f0c04bbf..89aacc30 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping.md +++ b/docs/plans/2026-08-28-multi-agent-grouping.md @@ -2,7 +2,7 @@ | | | |---|---| -| **Status** | P0, P1 and P2 landed on `feature/multi-agent-namespaces`; P3 is next. No phase (0-9) started. | +| **Status** | P0-P6 landed on `feature/multi-agent-namespaces`; the prerequisites are done. No phase (0-9) started. | | **Spec (normative)** | `docs/specs/2026-08-28-multi-agent-grouping.md` | | **What landed, and why** | `docs/plans/2026-08-28-multi-agent-grouping-changelog.md` -- read before resuming | @@ -200,7 +200,13 @@ applies either way. Set `concurrencyPolicy: Forbid` to prevent overlap, and watc Note #43 — schedulers started twice *within* one process by two `build()` passes — is a distinct defect; both touch scheduler startup and should be fixed together. -**P6 — Transport topology: one connection per namespace.** Not a defect, but it belongs here +**P6 — Transport topology: one connection per namespace. Done.** Ownership, naming and +resolution are in place; Phases 5 and 6 are what actually *create* a second client, and they now +have somewhere to create it. Landed as part of this: clients take a `namespace`, register under a +namespace-qualified name so two can coexist, name their connection +`f"{namespace}.{group}.{pod}"`, and derive queue group and durable from the namespace alone. +`EventPublishingService` takes a namespace and resolves its own namespace's client, falling back +to the root one. Not a defect, but it belongs here because it changes `NATSClient` ownership. Per-namespace clients confine ack loss and slow-consumer disconnects to one agent, and give named connections in `/connz` — `nats.connect()` is called today with no `name=` at all (`nats_client.py:93`). No config knob: a diff --git a/docs/reference/configuration-keys.md b/docs/reference/configuration-keys.md index 00a9618a..501ecd40 100644 --- a/docs/reference/configuration-keys.md +++ b/docs/reference/configuration-keys.md @@ -30,13 +30,13 @@ Settings for the event bus transport layer. | `nats_url` | `str` | `"nats://localhost:4222"` | NATS server URL. Only used when `event_bus = "nats"`. | | `dapr_pubsub_name` | `str` | `"pubsub"` | Dapr pub/sub component name, used when publishing and in the subscription document served at `GET /dapr/subscribe`. Only used when `event_bus = "dapr"`. | | `dapr_declarative_subscriptions` | `bool` | `false` | Set `true` when Dapr subscriptions are declared outside the application (Kubernetes `Subscription` resources or YAML). The discovery endpoint then serves an empty document, so the sidecar cannot subscribe twice. | -| `nats_queue_group` | `str` | value of `app_name` | Queue group joined by every NATS subscription, so exactly one replica processes any given message. Identifies the agent, not the process: it must not contain a pod, container or replica name, or moving the agent between deployments would change which consumer it is. Startup fails if neither this key nor `app_name` yields a name. Only used when `event_bus = "nats"`. | +| `nats_queue_group` | `str` | value of `app_name` | Queue group joined by every NATS subscription, so exactly one replica processes any given message. Identifies the agent, not the process: it must not contain a pod, container or replica name, or moving the agent between deployments would change which consumer it is. Startup fails if neither this key nor `app_name` yields a name. Applies to the root namespace only -- a client that belongs to a namespace uses the namespace name, so two agents sharing a process never share a group. 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. | | `event_client_drain_timeout` | `float` | `30.0` | Seconds allowed at shutdown for in-flight message handlers to finish before the broker connection is closed. Bounds the whole shutdown sequence, so keep it below the pod's termination grace period. | | `nats_use_jetstream` | `bool` | `false` | Consume through a durable JetStream consumer instead of Core NATS. The keys below apply only when this is `true`. | | `nats_stream_name` | `str` | `"EVENTS"` | Stream the durable consumers are created on. The framework creates it if it is missing, and widens an existing one to cover every subscribed subject plus the dead-letter subject; it never removes a subject. | -| `nats_durable_name` | `str` | `"-durable"` | Name of the durable consumer. Derived from the topic by default, with `.`, `*`, `>` and whitespace replaced by `_` because NATS rejects them in a consumer name. Setting it explicitly is only valid with a single subscribed topic: a durable filters one subject. | +| `nats_durable_name` | `str` | `"-durable"` | Name of the durable consumer. Derived from the topic by default, with `.`, `*`, `>` and whitespace replaced by `_` because NATS rejects them in a consumer name. A client that belongs to a namespace prefixes it (`"--durable"`), so two agents subscribing to the same topic get a consumer each. Setting it explicitly is only valid with a single subscribed topic: a durable filters one subject, and under a namespace it must be scoped per namespace or every namespace binds to the same consumer. | | `nats_ack_wait` | `float` | `300.0` | Seconds the broker waits for an acknowledgement before redelivering. **Must exceed the p99 duration of your slowest handler**, or long inference is redelivered to another replica while the first is still working. The default is deliberately far above the NATS default of 30 s because handlers in this framework call models. | | `nats_max_ack_pending` | `int` | `16` | Unacknowledged messages the consumer may have outstanding at once, counted across every replica sharing it. `-1` is unlimited. Keep it close to the number of replicas: a push subscription runs its callbacks one at a time, so anything much larger queues messages inside the client while their `nats_ack_wait` is already running down. | | `nats_max_deliver` | `int` | `5` | Delivery attempts before the message is dead-lettered. `-1` is unlimited, which means a permanently failing message is retried forever and never dead-lettered; the client logs a warning at startup if you set it. | @@ -44,6 +44,69 @@ Settings for the event bus transport layer. --- +## Deployment Identity (environment only) + +These are read straight from the environment, not from `settings.toml`, and carry the +`BLUEPRINT_` prefix rather than Dynaconf's. They describe *where* the process runs, so they +are used for the NATS connection name and for nothing else: no queue group, durable name or +dead-letter subject may be derived from them, or moving an agent between deployments would +change which broker-side consumer it is. + +| Variable | Default | Description | +|-----|---------|-------------| +| `BLUEPRINT_GROUP` | `` in the connection name | Deployment group this process was started as. Appears in the middle position of the NATS connection name. | +| `POD_NAME` | -- | Replica identity, preferred over `HOSTNAME` because a deployment can set it explicitly through the Kubernetes downward API. Appears in the last position of the connection name. | +| `HOSTNAME` | the host name, else `` | Used when `POD_NAME` is unset; the kubelet sets it to the pod name. | + +Every NATS connection is named `..`, which is what makes a pod's +contents legible in the broker's `/connz` output. The namespace segment is `` for an +application that never names one -- that is, for every single-agent application. + +An absent value becomes a bracketed placeholder rather than an empty segment, so a name never +degenerates into `..pod-7`. The brackets are not decoration: they are excluded from the namespace +alphabet (below), so no real namespace can spell one. Because a group name and a pod name come +from the deployment and are not rejected on that ground, they are instead sanitised for display -- +`<`, `>`, `.` and whitespace become `_`. So a group called `eu.west` appears as `eu_west`, which +keeps the name at three segments; an FQDN in `HOSTNAME` is folded the same way. Nothing derives +from the connection name (a queue group or durable name that did would change on every restart), +so the sanitising costs nothing downstream. + +### Namespace names + +A namespace is the agent's name and is the only thing broker-side consumer identity derives +from, so it is validated once, where it enters the framework, and never rewritten afterwards. + +| Rule | Reason | +|-----|-------------| +| `""` (root) or `[a-z][a-z0-9_]*` | The namespace becomes a registry key prefix, a NATS queue group, part of a JetStream durable name and a telemetry service name. The alphabet is the intersection of what those accept. | +| No `-` | `-` separates the fields of the durable name `--durable`. Allowing it makes that name ambiguous: `orders-eu` on `created` and `orders` on `eu-created` would be one consumer, so two agents would consume each other's events. Use `_`. | +| No `.`, `*`, `>` | Subject separator and wildcards; illegal in a NATS consumer name. | +| No `<`, `>` | Reserved for the connection-name placeholders above. | +| No surrounding whitespace | Not trimmed for you: the trimmed and untrimmed forms would be one agent registered under one name and subscribed under another. | + +An illegal namespace fails in `Component.__init__` -- before the registry name is derived and +before registration, and for every component including those that never register. It is not +deferred to the first subscription, which a publish-only or Dapr-only agent never reaches. + +### Names that become subjects are never rewritten for you + +`app_name`, `nats_queue_group` and a scheduler's name all end up inside a NATS subject, a queue +group or a consumer name. Whitespace, `*` and `>` in any of them **fails startup**, naming the key, +the value and the subject that would have been derived. + +This is deliberately not forgiving. `app_name = "Health Monitor"` used to be rewritten into the +tick subject `Health_Monitor.scheduler.nightly`, which is a subject the `CronJob` publishing that +tick has to spell exactly -- and whoever writes that manifest has no way to know about the rewrite. +The tick then never arrives, with nothing in either log to explain it. A name that only lives +inside the process may be repaired; a name in a contract with something outside it may not. + +Two exceptions, both because nothing outside can depend on the spelling: the topic part of a +JetStream durable name (dots are legal in subjects and illegal in consumer names, so `.` becomes +`_`, and two topics colliding on one durable is an error), and the NATS connection name (see +above). + +--- + ## Event Deduplication Delivery is at-least-once on both transports, so a handler can be run twice for the same diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md index f384fc22..8c42b943 100644 --- a/docs/specs/2026-08-28-multi-agent-grouping.md +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -65,7 +65,42 @@ other deployment identifier. - Queue group: `namespace`, or `nats_queue_group` (default `app_name`) when the namespace is `""`. It **MUST NOT** be the empty string. - JetStream durable: `f"{namespace}-{topic}-durable"`, or the configured `nats_durable_name` - when the namespace is `""`. + when the namespace is `""`. Only the topic is rewritten to suit a consumer name; the namespace + reaches it as declared. +- Namespace alphabet: a namespace **MUST** be `""` or match `[a-z][a-z0-9_]*`, and **MUST** be + validated where it enters the framework rather than by each consumer of it. It becomes a + registry key prefix, a queue group, part of a durable name and a telemetry `service.name`, and + a value each of those repairs differently is one agent under four names. Two exclusions do not + follow from any single consumer: + - `-` is the separator in the durable name above. With it allowed, namespace `orders-eu` on + topic `created` and namespace `orders` on topic `eu-created` produce one durable name, so two + agents would bind one JetStream consumer and consume each other's events. + - `<` and `>` keep the sec. 6 connection-name placeholders unforgeable. `>` is a NATS wildcard + and illegal in a consumer name in any case. + +**A name that crosses the process boundary MUST be validated, never repaired.** This covers every +name that becomes part of a subject, a queue group or a consumer: the namespace, `app_name` and +`nats_queue_group` where they stand in for it, and a scheduler's name where it forms the tick +subject. Silently rewriting one -- an `app_name` of `"My Service"` becoming `My_Service` in a +subject -- leaves the party on the other side of the contract, typically a `CronJob` in another +repository written by someone who has never read this framework, publishing to a subject nothing +subscribes to. The tick simply never arrives, and no log on either side says why. The side that +knows the name is unusable **MUST** fail its own startup instead, naming the key, the value and +the subject that would have been derived. + +Two rewrites are permitted, and only these: + +- The **topic** portion of a durable name. Dots are idiomatic in subjects and illegal in consumer + names, so there is no alternative; it is bounded by the requirement that two topics resolving to + one durable name is an error, and the mapping is documented. +- The **connection name** (sec. 6), which exists for attribution and which C1 forbids anything + from deriving from, so no external party can depend on its spelling. + +**The namespace MUST be validated in `Component.__init__`**, not in `Registry.add_component` and +not per base class. Every component passes through that constructor, including the eight that +opt out of registration, and it runs before the registry name is derived. A gate in the registry +would miss unregistered components -- among them the eventing endpoints, which become +namespace-owned in phase 2. - The NATS **connection name** (sec. 6) is deployment-specific and **MUST NOT** be used to derive either of the above. @@ -333,6 +368,23 @@ deployment may have no access to. The cost argument above justifies a connection that uses one*; it does not justify one per namespace that does not. Connection name **MUST** be `f"{namespace}.{group}.{pod}"`, and **MUST NOT** feed C1 naming. +An absent segment **MUST** be filled with a placeholder rather than left empty -- `` for the +root namespace, `` for an unset `BLUEPRINT_GROUP`, `` when the replica +cannot be identified -- so all three positions always carry a value, a name never degenerates into +`..pod-7`, and "no group" stays distinguishable from a group whose name happens to be empty. + +The placeholders **MUST** be unproducible by a real value rather than merely unlikely, because a +placeholder that collides with a legitimate name reintroduces exactly the ambiguity it was +introduced to remove. Two rules give that: + +- The namespace alphabet (C1, below) excludes `<` and `>`, so no legal namespace can spell one. +- The group and the pod are supplied by the deployment and **MUST NOT** be rejected on this + ground -- failing a rollout over a display string is the wrong trade -- so they **MUST** be + sanitised for display instead: `<`, `>`, `.` and whitespace replaced. Replacing `.` is not + cosmetic; it keeps a group called `a.b` from turning a three-segment name into four and + misattributing the connection. Sanitising rather than validating is acceptable here only + because nothing derives from the connection name (C1), so a mangled segment loses no + information any consumer depends on. `EventPublishingService` **MUST** publish on its own namespace's client; otherwise outbound traffic is unattributable and reason 3 is defeated. @@ -842,4 +894,4 @@ Two things an author still needs to know: their agent's name, and that handlers closed as a non-issue (sec. 6); consumer count is the analogous question and has not been asked. - **Do agents eventually become separate distributions?** Build-time dependency trimming would require it, which is when the agent-to-module map should migrate to entry points. Not needed - while trimming stays opt-in. \ No newline at end of file + while trimming stays opt-in. diff --git a/src/blueprint/agents/clients/client_base.py b/src/blueprint/agents/clients/client_base.py index 6b2720ff..1324144f 100644 --- a/src/blueprint/agents/clients/client_base.py +++ b/src/blueprint/agents/clients/client_base.py @@ -5,6 +5,7 @@ from collections.abc import Awaitable, Callable from ..component.component import Component +from ..component.namespace import ROOT_NAMESPACE from ..models.events import CloudEvent if TYPE_CHECKING: @@ -26,9 +27,16 @@ class ClientBase(Component, ABC): config values), not establish the connection. """ - def __init__(self) -> None: - """Initialize the client.""" - super().__init__() + def __init__(self, name: str | None = None, namespace: str = ROOT_NAMESPACE) -> None: + """Initialize the client. + + Args: + name: Registry name to use instead of the derived one. Forwarded to + ``Component``, which registers under it. + namespace: The agent this client belongs to; ``""`` for the root namespace. + Forwarded to ``Component``, which validates it and qualifies the name. + """ + super().__init__(name=name, namespace=namespace) self._client: Any = None async def _get_connected_client(self) -> Any: diff --git a/src/blueprint/agents/clients/io/dapr_client.py b/src/blueprint/agents/clients/io/dapr_client.py index 1ee16dc4..40bf4044 100644 --- a/src/blueprint/agents/clients/io/dapr_client.py +++ b/src/blueprint/agents/clients/io/dapr_client.py @@ -9,6 +9,7 @@ import httpx +from ...component.namespace import ROOT_NAMESPACE from ...models.api import ComponentHealth from ...models.events import CloudEvent from .io_client_base import IOClientBase @@ -37,6 +38,17 @@ class DaprClient(IOClientBase): additionally pings the sidecar on every call so runtime availability is always reflected. + One client per namespace, and what that does *not* buy here + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + A Dapr client may be created per namespace, for health attribution and so that + stopping one agent is a client close rather than selective unsubscription. It + **does not** confine ack loss or slow-consumer disconnects, which is the reason + the NATS client is per namespace (spec sec. 6): this client holds no broker + connection at all. It is an ``httpx`` client against the sidecar, and the sidecar + owns and multiplexes the one broker connection per pod, so those two failures + live there and are out of this class's reach. There is likewise no connection + name to set -- broker connections track pods on this path, not agents. + Config keys ~~~~~~~~~~~ ``event_client_max_retries`` (int, default -1): retries after first @@ -44,8 +56,8 @@ class DaprClient(IOClientBase): ``event_client_retry_delay`` (float, default 5.0): seconds between retries. """ - def __init__(self) -> None: - super().__init__() + def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: + super().__init__(namespace=namespace) self._topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = {} self._subscriptions_ready: bool = False self._subscriptions_managed: bool = False diff --git a/src/blueprint/agents/clients/io/io_client_base.py b/src/blueprint/agents/clients/io/io_client_base.py index c2f3ac7c..8101fadd 100644 --- a/src/blueprint/agents/clients/io/io_client_base.py +++ b/src/blueprint/agents/clients/io/io_client_base.py @@ -1,7 +1,9 @@ """Base class for IO transport clients (Dapr, NATS, etc.).""" +import re from abc import ABC +from ...component.namespace import ROOT_NAMESPACE from ..client_base import ClientBase @@ -11,8 +13,41 @@ class IOClientBase(ClientBase, ABC): Extends ClientBase for message-bus and eventing transports (Dapr, NATS, etc.). Used by EventPublishingService and eventing endpoints to find the active transport client via the registry without matching AI clients. + + Namespace ownership + ~~~~~~~~~~~~~~~~~~~ + A transport client belongs to one namespace, not to the process (spec sec. 6). The + default is the root namespace ``""``, which is the whole of a single-agent + application and registers under the bare class-derived name -- so nothing changes + for an application that never names a namespace. + + A namespaced client registers as ``f"{namespace}_{base_name}"``, which is what + allows two of them to exist in one registry at all: ``Registry.add_component`` + rejects a duplicate name, so before this every second instance of a transport + client raised at construction. + + The namespace is the *agent's* identity, so it may derive broker-side consumer + identity (queue group, durable) -- see C1. Nothing about the process, the + deployment group or the pod may. + + Both the namespace's validation and the qualified registry name are ``Component``'s: it + is the one gate every component passes through, so an illegal namespace cannot reach a + registry key, a queue group, a durable name or a telemetry resource from any base class. + See :func:`~blueprint.agents.component.namespace.validate_namespace` for the alphabet and + why each exclusion is in it. """ + def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: + """Initialize the transport client for one namespace. + + Args: + namespace: The agent this client belongs to; ``""`` for the root namespace. + + Raises: + ValueError: if the namespace is not a legal namespace. + """ + super().__init__(namespace=namespace) + TOPIC_TRANSPORTS = ("dapr", "nats") """Values of ``event_bus`` that produce an :class:`IOClientBase`, and therefore carry topics. @@ -23,3 +58,42 @@ class IOClientBase(ClientBase, ABC): ``EventPublishingService``, the eventing endpoints, an event-mode scheduler -- needs one of these two. """ + + +_SUBJECT_UNUSABLE = re.compile(r"[*>\s]") +"""What a subject a component publishes to or subscribes to cannot contain.""" + + +def validate_subject_segment(segment: str, *, source: str, subject: str) -> str: + """Return ``segment`` unchanged, or raise if it cannot appear in a subject. + + Every name in this framework that ends up as part of a NATS subject or a queue group + goes through here rather than being repaired, because those names are the contract with + everything outside the process: a `CronJob` publishes to a scheduler's tick subject, and + an operator reads a queue group in `/connz`. A name that is silently rewritten -- an + ``app_name`` of ``"My Service"`` becoming ``My_Service`` in a subject -- leaves the + outside party publishing to a subject nobody subscribes to, with nothing to read that + says why. That is the one failure mode this cannot be allowed to produce, so the rule is + to fail the startup of the side that *knows* the name is wrong. + + Sanitising is only ever acceptable for a value nothing outside the process depends on: + the NATS connection name, which exists for attribution and which C1 forbids anything + deriving from. + + Args: + segment: The name to check -- a namespace, an ``app_name``, a scheduler name. + source: Where it came from, named in the error so the fix is obvious. + subject: The subject it would have become, for the same reason. + + Raises: + ValueError: if the segment is empty or contains whitespace, ``*`` or ``>``. + """ + if not segment: + raise ValueError(f"{source} is empty, so the subject '{subject}' cannot be derived from it.") + if _SUBJECT_UNUSABLE.search(segment): + raise ValueError( + f"{source} is '{segment}', which cannot appear in a NATS subject: whitespace, '*' and '>' are not " + f"usable in one. It would have produced the subject '{subject}', which nothing outside this process " + "could publish to or subscribe to correctly. Rename it rather than relying on it being rewritten." + ) + return segment diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index d104c910..0474cd74 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -4,7 +4,9 @@ import contextlib import json import logging +import os import re +import socket from collections.abc import Awaitable, Callable from dataclasses import dataclass from typing import Any @@ -15,13 +17,64 @@ from nats.js.client import JetStreamContext from nats.js.errors import NotFoundError +from ...component.namespace import ROOT_LABEL, ROOT_NAMESPACE, display_segment from ...models.api import ComponentHealth from ...models.errors import DeliveryDisposition, disposition_for from ...models.events import CloudEvent -from .io_client_base import IOClientBase +from .io_client_base import IOClientBase, validate_subject_segment logger = logging.getLogger(__name__) +UNGROUPED_LABEL = "" +"""Stands in for an unset ``BLUEPRINT_GROUP`` in a connection name, so its three positions stay filled. + +Bracketed for the same reason as ``ROOT_LABEL``: ``display_segment`` strips brackets from every +environment-supplied segment, so no real group can produce this string and "not deployed as part of +a group" cannot be confused with a group that happens to be called ``ungrouped``. +""" + +UNKNOWN_POD_LABEL = "" +"""Stands in when neither the environment nor the host can say which pod this is.""" + + +def _deployment_group() -> str: + """Return the deployment group this process was started as, or a placeholder. + + Read straight from the environment rather than through ``Config``: group composition + decides which agents get a ``Config`` at all, so it is resolved before Dynaconf exists + and carries the ``BLUEPRINT_`` prefix rather than Dynaconf's (spec sec. 5.1). The + group loader that will own this variable arrives with the group configuration; until + then an unset value simply means "not deployed as part of a group". + + The group is deployment identity, so it belongs in the connection name and nowhere + near the queue group or the durable (C1). + + Passed through ``display_segment`` because this value is owned by the deployment, not by + the framework: it keeps a group called ``a.b`` from turning a three-segment connection name + into four, and keeps any group from forging a placeholder. + """ + return display_segment(os.environ.get("BLUEPRINT_GROUP", ""), UNGROUPED_LABEL) + + +def _pod_identity() -> str: + """Return the replica this process runs in, for the connection name only. + + ``POD_NAME`` is the Kubernetes downward-API convention and is preferred because a + deployment can set it explicitly; ``HOSTNAME`` is what the kubelet sets anyway and is + the pod name in practice; the host name covers plain Docker and local runs. + + Sanitised on the same terms as the group: a host name is frequently an FQDN, and its dots + would otherwise split one segment into several. + """ + for variable in ("POD_NAME", "HOSTNAME"): + value = os.environ.get(variable, "").strip() + if value: + return display_segment(value, UNKNOWN_POD_LABEL) + try: + return display_segment(socket.gethostname(), UNKNOWN_POD_LABEL) + except OSError: + return UNKNOWN_POD_LABEL + @dataclass(frozen=True) class ConsumerTuning: @@ -56,6 +109,24 @@ class NATSClient(IOClientBase): the ready flag. On reconnect ``_on_reconnected`` re-subscribes (JetStream only — Core NATS re-subscribes automatically) and restores the flag. + One connection per namespace + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + A client belongs to one namespace (spec sec. 6), so a process hosting three + agents opens three connections rather than multiplexing one. That confines + the two failures that are per-connection: a dropped connection strands the + acknowledgements of only that namespace's in-flight messages, and a + slow-consumer kick removes only the namespace that flooded its buffer. It is + **not** a durability mechanism -- JetStream pending state lives on the server, + so what the topology decides is how many namespaces repeat work after a drop. + + Each connection is named ``f"{namespace}.{group}.{pod}"``, which is what makes + a pod's contents legible in ``/connz``; before this, every connection the + framework opened was anonymous. An absent segment becomes a bracketed placeholder + (````, ````, ````) that no real namespace, group or + pod can produce, so a missing value never reads as a present one. The name contains + the pod, so it must never reach queue-group or durable naming (C1) -- those two are + the only broker-side identifiers, and both derive from the namespace alone. + Queue group ~~~~~~~~~~~ Every Core NATS subscription joins a queue group, so exactly one replica @@ -99,8 +170,9 @@ class NATSClient(IOClientBase): message goes when the framework gives up on it; ``""`` disables it and loses the payload. """ - def __init__(self) -> None: - super().__init__() + def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: + super().__init__(namespace=namespace) + self._connection_name: str = "" self._nats_client: NatsClient | None = None self._js: JetStreamContext | None = None self._use_jetstream: bool = False @@ -140,6 +212,11 @@ def consumer_tuning(self) -> ConsumerTuning | None: """JetStream consumer settings resolved by ``subscribe()``; ``None`` on Core NATS.""" return self._tuning + @property + def connection_name(self) -> str: + """Name this connection reports to the broker; ``""`` before the first connect.""" + return self._connection_name + # ------------------------------------------------------------------ # Managed subscription API # ------------------------------------------------------------------ @@ -164,8 +241,16 @@ def _resolve_queue_group(self) -> str: The name identifies the *agent*, not the process that hosts it: moving an agent into a different deployment group must not change which broker-side consumer it - is (spec C1). Today every component lives in the root namespace, so the name comes - from ``nats_queue_group`` and falls back to ``app_name``. + is (spec C1). + + A namespaced client therefore uses its namespace verbatim -- it was validated at + construction, so it needs no checking or rewriting here -- and only the root namespace + falls back to ``nats_queue_group`` then ``app_name`` -- which is what + ``nats_queue_group`` is documented to be, "the queue group for the root namespace + only". Without that branch every client in a process would resolve the same + ``app_name``, and two co-hosted agents subscribing to one topic would form a + single group and steal each other's messages: exactly one of them would see any + given event. Resolved here rather than at subscription time so that a misconfiguration fails the caller's startup instead of disappearing into the background retry loop, which @@ -175,21 +260,22 @@ def _resolve_queue_group(self) -> str: ValueError: if neither key yields a non-empty name. NATS reads ``queue=""`` as "no queue group", which is precisely the every-replica-processes-every-message fan-out this exists to prevent, so there is no usable fallback. - ValueError: if the name contains whitespace. ``nats-py`` rejects such a queue - name with ``BadSubjectError``, and an ``app_name`` like ``"My Service"`` was - perfectly legal before subscriptions carried a queue group. Reported here, - naming the key and the value, rather than left to surface as a repeating - ``BadSubjectError`` inside the background retry task. + ValueError: if a configured name contains whitespace or a wildcard. ``nats-py`` + rejects such a queue name with ``BadSubjectError``, and an ``app_name`` like + ``"My Service"`` was perfectly legal before subscriptions carried a queue group. + A wildcard additionally reaches the default dead-letter subject, which is derived + from this name. Reported here, naming the key and the value, rather than left to + surface as a repeating ``BadSubjectError`` inside the background retry task. A + *namespace* cannot reach this check: it is rejected at construction instead. """ + if self.namespace: + return self.namespace + for key in ("nats_queue_group", "app_name"): name = str(self.config.get(key, "") or "").strip() if not name: continue - if any(char.isspace() for char in name): - raise ValueError( - f"Queue group name '{name}' (from '{key}') contains whitespace, which NATS does not accept. " - "Set 'nats_queue_group' to a name without whitespace." - ) + validate_subject_segment(name, source=f"The queue group (from '{key}')", subject=f"{name}.dead-letter") return name raise ValueError( "NATS subscriptions require a queue group: set 'nats_queue_group' or 'app_name'. " @@ -287,6 +373,14 @@ def _resolve_durables(self, topics: list[str]) -> dict[str, str]: "A JetStream durable filters one subject, so one name cannot serve them all. " "Remove the key to derive a durable per topic." ) + if configured and self.namespace: + logger.warning( + "Namespace '%s' is using the configured durable name '%s'. A durable is broker-side state " + "shared by everything that binds to it, so unless this key is scoped per namespace, every " + "namespace in this process binds to the same consumer and they consume each other's events.", + self.namespace, + configured, + ) durables: dict[str, str] = {} for topic in topics: @@ -301,15 +395,28 @@ def _resolve_durables(self, topics: list[str]) -> dict[str, str]: durables[topic] = name return durables - @staticmethod - def _durable_for(topic: str) -> str: + def _durable_for(self, topic: str) -> str: """Derive a legal durable consumer name from a subject. NATS rejects ``.``, ``*``, ``>`` and whitespace in a consumer name, so the dotted subjects that are idiomatic in NATS -- ``orders.created`` -- cannot serve as one - directly. + directly. Only the *topic* is rewritten: the namespace was validated against an + alphabet a consumer name already accepts, so it is used as it was declared. + + A namespaced client puts its namespace in front, for the same reason its queue + group is the namespace (C1): two co-hosted agents subscribing to one topic each + need their own consumer, or the broker hands every message to whichever of them + binds first. The root namespace keeps the bare ``-durable``, so no existing + consumer is renamed and no deployment of this change becomes a consumer migration. + + The result -- ``orders-orders_created-durable`` for namespace ``orders`` on topic + ``orders.created`` -- reads back unambiguously because ``-`` is excluded from the + namespace alphabet: the first ``-`` is always the boundary between the namespace and + the topic. Were it allowed, ``orders-eu`` on ``created`` and ``orders`` on + ``eu-created`` would name one consumer and two agents would share it. """ - return f"{re.sub(r'[.*>\s]', '_', topic)}-durable" + prefix = f"{self.namespace}-" if self.namespace else "" + return f"{prefix}{re.sub(r'[.*>\s]', '_', topic)}-durable" @staticmethod def _subject_matches(pattern: str, subject: str) -> bool: @@ -343,6 +450,30 @@ def _read_int(self, key: str, default: int) -> int: except (TypeError, ValueError) as exc: raise ValueError(f"Config key '{key}' must be an integer, got {raw!r}.") from exc + # ------------------------------------------------------------------ + # Connection identity (P6) + # ------------------------------------------------------------------ + + def _resolve_connection_name(self) -> str: + """Return the name this connection reports to the broker (spec sec. 6). + + ``f"{namespace}.{group}.{pod}"``: which agent, which deployment group, which + replica. It exists for attribution only -- ``nats.connect()`` was previously + called with no ``name=`` at all, so every connection the framework opened showed + up anonymous in ``/connz`` and a pod hosting several agents was unreadable. + + All three positions are always filled, using a placeholder where a value is + absent, so the name cannot degenerate into ``"..pod-7"`` and "no group" stays + distinguishable from "a group whose name is empty". + + **This value must never reach the queue group or the durable name.** It contains + the pod, so a consumer identity derived from it would change on every restart and + on every regrouping, which is precisely what C1 forbids. It is deliberately not + stored anywhere those two are resolved from. + """ + namespace = self.namespace or ROOT_LABEL + return f"{namespace}.{_deployment_group()}.{_pod_identity()}" + # ------------------------------------------------------------------ # Connection # ------------------------------------------------------------------ @@ -356,9 +487,11 @@ async def connect(self) -> None: return nats_url = self.config.get("nats_url", "nats://localhost:4222") + self._connection_name = self._resolve_connection_name() try: self._nats_client = await nats.connect( nats_url, + name=self._connection_name, max_reconnect_attempts=self.config.get("nats_max_reconnect_attempts", 5), reconnect_time_wait=self.config.get("nats_reconnect_time_wait", 2), connect_timeout=10, @@ -370,13 +503,13 @@ async def connect(self) -> None: if self._use_jetstream: try: self._js = self._nats_client.jetstream() - logger.info("Connected to NATS server with JetStream at %s", nats_url) + logger.info("Connected to NATS server with JetStream at %s as '%s'", nats_url, self._connection_name) except Exception as e: logger.warning("JetStream initialization failed, falling back to Core NATS: %s", str(e)) self._use_jetstream = False if not self._use_jetstream: - logger.info("Connected to NATS server (Core NATS) at %s", nats_url) + logger.info("Connected to NATS server (Core NATS) at %s as '%s'", nats_url, self._connection_name) except Exception as e: logger.error("Failed to connect to NATS: %s", str(e)) raise diff --git a/src/blueprint/agents/component/component.py b/src/blueprint/agents/component/component.py index 89c6cc0e..89d124bf 100644 --- a/src/blueprint/agents/component/component.py +++ b/src/blueprint/agents/component/component.py @@ -20,6 +20,7 @@ from ..config import Config from ..utils import camel_to_snake +from .namespace import ROOT_NAMESPACE, qualified_component_name, validate_namespace if TYPE_CHECKING: from .registry import Registry @@ -76,8 +77,30 @@ class Component(ABC, metaclass=_ComponentMeta): Components must NOT access self.config in __init__ — use on_startup() instead. """ - def __init__(self, should_register: bool = True) -> None: - """Initialize the component.""" + def __init__(self, should_register: bool = True, name: str | None = None, namespace: str = ROOT_NAMESPACE) -> None: + """Initialize the component. + + Args: + should_register: Whether to add this instance to the shared registry. + name: Registry name to use instead of the derived one. Passed by subclasses + whose instances are not unique per class *and* not distinguished by a + namespace -- ``AIClientBase`` naming itself after its provider, for example. + An explicit name wins over the namespace-qualified one, so the caller then + owns its uniqueness. It must be supplied here rather than assigned + afterwards: registration happens in this constructor, so a second instance + of the same class would collide before a rename could run. + namespace: The agent this component belongs to; ``""`` (the default) is the root + namespace and the whole of a single-agent application. + + Raises: + ValueError: if the namespace is not a legal namespace. This is the framework's + single gate for that: every component passes through this constructor, + including the eight that opt out of registration, and it runs before the + name is derived and before registration, so an illegal namespace cannot + reach a registry key, a queue group, a durable name or a telemetry resource. + Validated here rather than in ``Registry.add_component`` for those two + reasons -- coverage of unregistered components, and ordering. + """ if Component.shared_registry is None: # Import here to avoid circular dependency @@ -85,7 +108,8 @@ def __init__(self, should_register: bool = True) -> None: Component.init_registry(Registry(Component)) - self._name = camel_to_snake(self.__class__.__name__) + self._namespace = validate_namespace(namespace or ROOT_NAMESPACE) + self._name = name or qualified_component_name(self._namespace, camel_to_snake(self.__class__.__name__)) if should_register: self.registry.add_component(self.name, self) @@ -100,6 +124,15 @@ def name(self, value: str) -> None: self.registry.update_component_name(self._name, value) self._name = value + @property + def namespace(self) -> str: + """The agent this component belongs to; ``""`` for the root namespace. + + Owned by ``Component`` rather than by the bases that first needed it, so that the + namespace cannot be assigned after the validation gate in ``__init__`` has run. + """ + return self._namespace + @property def registry(self) -> Registry: """Get the component registry for accessing other components.""" diff --git a/src/blueprint/agents/component/namespace.py b/src/blueprint/agents/component/namespace.py new file mode 100644 index 00000000..fcebc221 --- /dev/null +++ b/src/blueprint/agents/component/namespace.py @@ -0,0 +1,187 @@ +"""Namespace naming, validation and resolution shared by namespace-owned components. + +A namespace names one agent inside a process that may host several (spec sec. 3, C1). +The empty namespace is the root: it is what every component of a single-agent +application uses, so everything here is a no-op for those applications. + +This module is the single definition of the root namespace and of what a namespace is +allowed to look like. Three operations recur wherever a component becomes +namespace-owned and are therefore kept in one place: + +- **Validation.** A namespace becomes a registry key prefix, a NATS queue group, part + of a JetStream durable name and an OpenTelemetry ``service.name``. Those four have + different alphabets, so the namespace is held to the intersection and rejected at the + point it enters the system, rather than being sanitised differently by each consumer. +- **Naming.** Two instances of the same class can now coexist in one registry, so the + class-derived component name is no longer unique. The namespace qualifies it. +- **Resolution.** A component looking for a collaborator wants *its own* namespace's + instance, and falls back to the root one when its namespace has none. This mirrors + the resolution rule the spec states for ``get_component`` (namespace, then root, + raising only on ambiguity within one level); when the registry itself grows a + namespace dimension, these helpers become the registry's own implementation. +""" + +import re +from typing import Any + +ROOT_NAMESPACE = "" +"""The namespace every component of a single-agent application lives in. + +Not a name but the absence of one, and therefore not configurable: ``qualified_component_name``, +the NATS queue group and the JetStream durable all branch on it being falsy, so a root +namespace with a value would rename every registry key and every broker-side consumer -- which +is exactly what C1 forbids. An application that wants its own name on the broker sets +``nats_queue_group``; an agent that wants its own identity gets a namespace, and is then not +the root. +""" + +ROOT_LABEL = "" +"""How the root namespace is written where a value is required, since its name is empty. + +The angle brackets are what make this a *reserved* form rather than a guess: they are excluded +from the namespace alphabet below, so no legal namespace can produce this string. A bare token +such as ``root`` could not make that promise -- a namespace called ``root`` would be +indistinguishable from the absence of one, which is the ambiguity the placeholder exists to +avoid. +""" + +_ALLOWED_NAMESPACE = re.compile(r"\A[a-z][a-z0-9_]*\Z") +"""Lowercase, digits and underscore, starting with a letter. See :func:`validate_namespace`.""" + +_DISPLAY_UNSAFE = re.compile(r"[<>.\s]+") +"""Characters a display segment cannot keep. See :func:`display_segment`.""" + + +def validate_namespace(namespace: str) -> str: + """Return ``namespace`` unchanged, or raise if it cannot serve as one. + + Rejected here rather than repaired, and rejected at construction rather than at first + use: the namespace reaches a registry key, a queue group, a durable name and a telemetry + resource, so a value that is repaired differently by each of them is four names for one + agent. The root namespace ``""`` is always valid. + + The alphabet is ``[a-z][a-z0-9_]*``, which is the intersection of what those four + consumers accept, plus two exclusions that are not obvious from any one of them: + + - ``-`` is the separator in the durable name ``f"{namespace}-{topic}-durable"`` (C1). + Allowing it in a namespace makes that name ambiguous: namespace ``orders-eu`` with + topic ``created`` and namespace ``orders`` with topic ``eu-created`` produce the same + durable, so two agents would bind one JetStream consumer and consume each other's + events. Use ``_``. + - ``<`` and ``>`` are excluded so that :data:`ROOT_LABEL` and the deployment placeholders + it is used alongside stay unforgeable. ``>`` is a NATS wildcard and illegal in a + consumer name regardless. + + Args: + namespace: The candidate namespace; ``""`` for the root. + + Returns: + The namespace, unchanged. + + Raises: + ValueError: if the namespace is padded, whitespace-only, or outside the alphabet. + The message names what the namespace would have broken, because a namespace is + declared once and read by four subsystems that would each fail differently. + """ + if namespace == ROOT_NAMESPACE: + return ROOT_NAMESPACE + + if not namespace.strip(): + raise ValueError( + f"A namespace of whitespace only ({namespace!r}) is not the root namespace. Pass '' for the root, " + "or a name matching [a-z][a-z0-9_]* for an agent." + ) + + if namespace != namespace.strip(): + raise ValueError( + f"Namespace {namespace!r} has surrounding whitespace. It is not trimmed for you, because the trimmed " + "and untrimmed forms would be one agent under two names -- one in the registry and another on the broker." + ) + + if "-" in namespace: + raise ValueError( + f"Namespace '{namespace}' contains '-', which is the separator in the JetStream durable name " + f"'{namespace}--durable'. Two namespaces could then share one durable and consume each other's " + "events. Use '_' instead." + ) + + if not _ALLOWED_NAMESPACE.match(namespace): + offenders = sorted({character for character in namespace if not _ALLOWED_NAMESPACE.match(f"a{character}")}) + raise ValueError( + f"Namespace '{namespace}' is not a legal namespace: {''.join(offenders) or namespace!r} cannot appear in it. " + "A namespace must match [a-z][a-z0-9_]*, because it becomes a registry key prefix, a NATS queue group, " + "part of a JetStream durable name and a telemetry service name, and those do not accept the same characters." + ) + + return namespace + + +def display_segment(value: str, placeholder: str) -> str: + """Return ``value`` reduced to one safe segment of a dot-separated identity string. + + Used for the values a deployment owns rather than the framework -- the group name and the + pod name in the NATS connection name (spec sec. 6). They arrive from the environment and + cannot be validated the way a namespace is: rejecting a deployment's group name would fail + a rollout over a display string. + + Two things are guaranteed instead. Dots and whitespace are replaced, so a group called + ``a.b`` cannot turn a three-segment name into four and misattribute a connection; and + angle brackets are replaced, so no environment value can forge :data:`ROOT_LABEL` or its + sibling placeholders. An empty value becomes ``placeholder``, so every position stays + filled and "absent" reads differently from "empty". + + Sanitising rather than validating is only acceptable because nothing derives from these + values: C1 forbids the queue group and the durable from reading the connection name, so + a mangled segment loses no information any consumer depends on. + """ + return _DISPLAY_UNSAFE.sub("_", value.strip()) or placeholder + + +def qualified_component_name(namespace: str, base_name: str) -> str: + """Return the registry name ``base_name`` takes inside ``namespace``. + + The root namespace keeps the bare name, so an existing application's registry keys + -- ``nats_client``, ``event_publishing_service`` -- do not change and neither do + the lookups and health-check entries that use them. + """ + return base_name if not namespace else f"{namespace}_{base_name}" + + +def namespace_of(component: Any) -> str: + """Return the namespace a component belongs to, or the root for one that has none. + + Read with ``getattr`` because the namespace currently lives on the bases that own + one (transport clients, publishing service) rather than on ``Component`` itself. + """ + return str(getattr(component, "namespace", ROOT_NAMESPACE) or ROOT_NAMESPACE) + + +def resolve_for_namespace[ComponentT]( + candidates: list[ComponentT], + namespace: str, + *, + description: str, +) -> ComponentT: + """Return the one candidate belonging to ``namespace``, else the one at the root. + + Args: + candidates: The components to choose from, typically a registry type query. + namespace: The namespace asking. ``""`` looks only at the root. + description: What is being resolved, for the error message. + + Raises: + ValueError: if neither level yields exactly one candidate. Ambiguity is an + error rather than a first-match, because picking one of two silently + attaches an agent to another agent's transport -- which is exactly the + attribution the per-namespace topology exists to provide. + """ + for level in (namespace, ROOT_NAMESPACE) if namespace else (ROOT_NAMESPACE,): + matches = [candidate for candidate in candidates if namespace_of(candidate) == level] + if len(matches) == 1: + return matches[0] + if len(matches) > 1: + raise ValueError( + f"Namespace '{level or ROOT_LABEL}' has {len(matches)} {description}s, so the one to use for " + f"namespace '{namespace or ROOT_LABEL}' is ambiguous." + ) + raise ValueError(f"No {description} is registered for namespace '{namespace or ROOT_LABEL}' or at the root.") diff --git a/src/blueprint/agents/io/api/eventing/event_handling_base.py b/src/blueprint/agents/io/api/eventing/event_handling_base.py index 2ac4f5dc..b8ee837f 100644 --- a/src/blueprint/agents/io/api/eventing/event_handling_base.py +++ b/src/blueprint/agents/io/api/eventing/event_handling_base.py @@ -9,6 +9,7 @@ from opentelemetry import metrics from ....component.component import traced +from ....component.namespace import ROOT_NAMESPACE from ....handler.handler_chain import DUPLICATE_CONTEXT_KEY from ....models import ProcessingResult, ProcessingStatus from ....models.errors import DeliveryDisposition @@ -45,13 +46,6 @@ class EventHandlingBase(RestApiBase, CloudEventProcessorMixin, ABC): their own REST endpoints via concrete ``publish`` implementations. """ - ROOT_NAMESPACE = "" - """Namespace this component's events belong to. - - Components gain a real namespace in phase 2; until then every one of them lives in the - root namespace, and this constant is the single place that assumption is written down. - """ - @traced("topic", "cloud_event") async def handle_event(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[str, Any]: """Dispatch an event and return the acknowledgement dict Dapr reads. @@ -106,9 +100,9 @@ async def _process_cloud_event( logger.debug("Processing CloudEvent: %s", cloud_event.id) processing_result = await self._dispatch_cloud_event(cloud_event, context) if context.get(DUPLICATE_CONTEXT_KEY): - _DUPLICATE_EVENTS.add(1, {"namespace": self.ROOT_NAMESPACE, "topic": topic}) + _DUPLICATE_EVENTS.add(1, {"namespace": ROOT_NAMESPACE, "topic": topic}) logger.debug("Event %s on topic '%s' was already processed", cloud_event.id, topic) elif processing_result.status is ProcessingStatus.NO_HANDLER_FOUND: - _UNHANDLED_EVENTS.add(1, {"namespace": self.ROOT_NAMESPACE, "topic": topic}) + _UNHANDLED_EVENTS.add(1, {"namespace": ROOT_NAMESPACE, "topic": topic}) logger.debug("No handler had work for event %s on topic '%s'", cloud_event.id, topic) return processing_result diff --git a/src/blueprint/agents/io/api/scheduling/scheduler.py b/src/blueprint/agents/io/api/scheduling/scheduler.py index db8b0097..d1e90a74 100644 --- a/src/blueprint/agents/io/api/scheduling/scheduler.py +++ b/src/blueprint/agents/io/api/scheduling/scheduler.py @@ -38,7 +38,6 @@ async def tick(self) -> None: from __future__ import annotations import logging -import re import time from abc import abstractmethod from datetime import UTC, datetime @@ -47,8 +46,9 @@ async def tick(self) -> None: from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.triggers.cron import CronTrigger -from ....clients.io.io_client_base import TOPIC_TRANSPORTS +from ....clients.io.io_client_base import TOPIC_TRANSPORTS, validate_subject_segment from ....component.component import traced +from ....component.namespace import ROOT_NAMESPACE from ....handler.event_handler_base import EventHandlerBase from ....models.events import GenericCloudEvent from ..rest_api_base import RestApiBase @@ -63,15 +63,6 @@ async def tick(self) -> None: SCHEDULER_MODES = (SCHEDULER_MODE_EVENT, SCHEDULER_MODE_IN_PROCESS) -ROOT_NAMESPACE = "" -"""Namespace a scheduler's tick topic is derived from. - -Components gain a real namespace in phase 2; until then every one of them lives in the -root namespace, and the tick topic falls back to ``app_name`` exactly as the queue group -does (C1). Mirrors ``EventHandlingBase.ROOT_NAMESPACE``. -""" - - TICK_CACHE_NAMESPACE = "scheduler_tick" """Cache namespace holding the per-tick claims, kept away from application data.""" @@ -390,40 +381,37 @@ def _resolve_topic(self) -> str: moving the scheduler between deployment groups does not change the subject a ``CronJob`` has to publish to (C1). - Whitespace in a *derived* topic is replaced with ``_`` rather than rejected, the way - ``NATSClient._durable_for`` already rewrites a subject into a legal durable name. - ``app_name = "Health Monitor"`` is legal and common, the topic is derived rather than - typed, so there is no author mistake to catch -- only a name to make usable. A - wildcard is still an error in either form: it would subscribe the scheduler to - traffic that is not its tick. + A derived topic is **validated, not repaired**, and both of the names it is derived + from -- the identity and the scheduler's own name -- are checked. This subject is the + contract with whatever publishes the tick: a ``CronJob`` in another repository, written + by someone who has never read this method. Rewriting ``app_name = "Health Monitor"`` + into ``Health_Monitor.scheduler.nightly`` leaves that author publishing to a subject + this scheduler does not subscribe to, and nothing anywhere says why -- the tick simply + never arrives. Failing the startup of the side that knows the name is unusable is the + only version of this that is debuggable. Raises: - ValueError: if no identity is available, if an explicit ``topic`` contains - whitespace, or if either form contains ``*`` or ``>``. All are startup + ValueError: if no identity is available, or if the identity, the scheduler name or + an explicit ``topic`` contains whitespace or a wildcard. All are startup failures rather than a silently unsubscribed scheduler. """ if self._topic_override: topic = self._topic_override - if any(char.isspace() for char in topic): - raise ValueError( - f"Scheduler '{self.name}' was given the tick topic '{topic}', which contains whitespace. " - "A NATS subject cannot, and an explicitly named topic is not rewritten." - ) - else: - # ROOT_NAMESPACE is still "" for every component; phase 2 is what gives this a value. - identity = ROOT_NAMESPACE or str(self.config.get("app_name", "") or "").strip() - if not identity: - raise ValueError( - f"Scheduler '{self.name}' runs in event mode but its tick topic cannot be derived: " - "set 'app_name', or pass topic=... to SchedulerBase.__init__." - ) - topic = re.sub(r"\s+", "_", f"{identity}.scheduler.{self.name}") - - if "*" in topic or ">" in topic: + validate_subject_segment(topic, source=f"The tick topic given to scheduler '{self.name}'", subject=topic) + return topic + + # ROOT_NAMESPACE is still "" for every component; phase 2 is what gives this a value. + identity = ROOT_NAMESPACE or str(self.config.get("app_name", "") or "").strip() + if not identity: raise ValueError( - f"Scheduler '{self.name}' resolved the tick topic '{topic}', which is not a usable subject: " - "the wildcards '*' and '>' would subscribe it to traffic that is not its tick." + f"Scheduler '{self.name}' runs in event mode but its tick topic cannot be derived: " + "set 'app_name', or pass topic=... to SchedulerBase.__init__." ) + + topic = f"{identity}.scheduler.{self.name}" + source = "'app_name'" if not ROOT_NAMESPACE else "The scheduler's namespace" + validate_subject_segment(identity, source=source, subject=topic) + validate_subject_segment(self.name, source=f"The name of scheduler '{self.name}'", subject=topic) return topic # ------------------------------------------------------------------ @@ -469,8 +457,7 @@ async def on_startup(self) -> None: if self.registry.has_cache(): logger.info( - "Scheduler '%s' started an in-process timer with crontab '%s'; each tick is claimed in the cache, " - "so one replica runs it", + "Scheduler '%s' started an in-process timer with crontab '%s'; each tick is claimed in the cache, so one replica runs it", self.name, self._crontab, ) diff --git a/src/blueprint/agents/services/eventing/event_publishing_service.py b/src/blueprint/agents/services/eventing/event_publishing_service.py index e56ac043..9646b761 100644 --- a/src/blueprint/agents/services/eventing/event_publishing_service.py +++ b/src/blueprint/agents/services/eventing/event_publishing_service.py @@ -7,6 +7,7 @@ from opentelemetry import trace from ...component.component import traced +from ...component.namespace import ROOT_NAMESPACE, resolve_for_namespace from ..service_base import ServiceBase from ...clients.io.io_client_base import IOClientBase from ...models import GenericCloudEvent @@ -21,17 +22,41 @@ class EventPublishingService(ServiceBase): Uses IOClientBase for transport-agnostic publishing (Dapr, NATS, etc.). Topic-to-event-type mapping is resolved from application configuration. - The active IO client is resolved from the registry in on_startup(). + The IO client is resolved from the registry in on_startup(). + + Namespace ownership + ~~~~~~~~~~~~~~~~~~~ + One publishing service per namespace, publishing on **its own** namespace's client + (spec sec. 6). Sharing one service across namespaces would send every agent's + outbound events down one connection, which makes outbound traffic unattributable + and defeats the reason the connections are named in the first place. + + A namespace with no client of its own falls back to the root one, so a namespaced + agent in a process that has a single shared transport keeps working. """ - def __init__(self) -> None: - super().__init__() + def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: + """Initialize the publishing service for one namespace. + + Args: + namespace: The agent whose events this service publishes; ``""`` for the + root namespace, which keeps the unqualified registry name. + + Raises: + ValueError: if the namespace is not a legal namespace. Validated by + ``Component``, which is the single gate for it. + """ + super().__init__(namespace=namespace) self._client: IOClientBase | None = None self._pub_config: EventPublishingConfig | None = None async def on_startup(self) -> None: - """Resolve IO client from registry and load event publishing configuration.""" - self._client = self.registry.get_component(IOClientBase) + """Resolve this namespace's IO client and load event publishing configuration.""" + self._client = resolve_for_namespace( + self.registry.get_io_clients(), + self.namespace, + description="IO transport client", + ) self._pub_config = self.config.get_event_publishing_config() async def on_shutdown(self) -> None: diff --git a/src/blueprint/agents/services/service_base.py b/src/blueprint/agents/services/service_base.py index c5f33ae3..f6a0ba4c 100644 --- a/src/blueprint/agents/services/service_base.py +++ b/src/blueprint/agents/services/service_base.py @@ -1,6 +1,7 @@ from abc import ABC from ..component.component import Component +from ..component.namespace import ROOT_NAMESPACE class ServiceBase(Component, ABC): @@ -11,6 +12,13 @@ class ServiceBase(Component, ABC): are inherited from Component. """ - def __init__(self) -> None: - """Initialize the business service.""" - super().__init__() + def __init__(self, name: str | None = None, namespace: str = ROOT_NAMESPACE) -> None: + """Initialize the business service. + + Args: + name: Registry name to use instead of the derived one. Forwarded to + ``Component``, which registers under it. + namespace: The agent this service belongs to; ``""`` for the root namespace. + Forwarded to ``Component``, which validates it and qualifies the name. + """ + super().__init__(name=name, namespace=namespace) diff --git a/tests/unit/agents/clients/io/test_dapr_client.py b/tests/unit/agents/clients/io/test_dapr_client.py index 0fc58ee9..0bc94ca5 100644 --- a/tests/unit/agents/clients/io/test_dapr_client.py +++ b/tests/unit/agents/clients/io/test_dapr_client.py @@ -259,3 +259,33 @@ async def test_sidecar_unreachable_leaves_ready_false( with pytest.raises(OSError): await dapr_client._start_with_retry() assert dapr_client.subscriptions_ready is False + + +# --------------------------------------------------------------------------- +# P6 -- a namespaced Dapr client, and what it does not buy (spec sec. 6) +# --------------------------------------------------------------------------- + + +class TestDaprClientNamespaceOwnership: + """Useful for health attribution and C4; it confines neither ack loss nor a slow consumer.""" + + def test_default_is_the_root_namespace(self, dapr_client: DaprClient) -> None: + assert dapr_client.namespace == "" + + def test_root_client_keeps_the_unqualified_registry_name(self, dapr_client: DaprClient) -> None: + assert dapr_client.name == "dapr_client" + + def test_namespaced_client_registers_under_a_qualified_name(self, mock_config: MagicMock) -> None: + assert DaprClient(namespace="orders").name == "orders_dapr_client" + + def test_two_namespaces_coexist_in_one_registry(self, mock_config: MagicMock) -> None: + orders = DaprClient(namespace="orders") + invoice = DaprClient(namespace="invoice") + assert orders.registry.get_component("orders_dapr_client") is orders + assert invoice.registry.get_component("invoice_dapr_client") is invoice + + async def test_no_broker_connection_is_named(self, mock_config: MagicMock) -> None: + """The sidecar owns the broker connection, so there is nothing here to name.""" + client = DaprClient(namespace="orders") + await client.connect() + assert not hasattr(client, "connection_name") diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index ece44d74..9954edf9 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -2,6 +2,7 @@ import asyncio import json +import logging from unittest.mock import AsyncMock, MagicMock, patch import pytest @@ -591,7 +592,13 @@ async def test_whitespace_in_name_raises_instead_of_reaching_nats(self, nats_cli async def test_whitespace_error_names_the_key_and_value(self, nats_client: NATSClient, mock_config: MagicMock) -> None: mock_config.get.side_effect = lambda key, default=None: {"app_name": "My Agent Service"}.get(key, default) - with pytest.raises(ValueError, match="'My Agent Service'.*'app_name'"): + with pytest.raises(ValueError, match="'app_name'.*'My Agent Service'"): + await nats_client.subscribe({"topic.a": AsyncMock()}) + + async def test_wildcard_in_the_queue_group_raises(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """It would also seed the default dead-letter subject '.dead-letter'.""" + mock_config.get.side_effect = lambda key, default=None: {"app_name": "my*service"}.get(key, default) + with pytest.raises(ValueError, match="cannot appear in a NATS subject"): await nats_client.subscribe({"topic.a": AsyncMock()}) async def test_surrounding_whitespace_is_trimmed_not_rejected(self, nats_client: NATSClient, mock_config: MagicMock) -> None: @@ -1236,3 +1243,223 @@ async def test_reconnected_resubscribes_jetstream_topics(self, connected_nats_cl # --------------------------------------------------------------------------- # asyncio import needed by the non-blocking subscribe test # --------------------------------------------------------------------------- + + +# --------------------------------------------------------------------------- +# P6 -- one connection per namespace (spec sec. 6) +# --------------------------------------------------------------------------- + + +_NAMESPACED_CONFIG = { + "app_name": "test-agent", + "nats_url": "nats://localhost:4222", + "nats_use_jetstream": False, +} + + +def _namespaced_client(mock_config: MagicMock, namespace: str) -> NATSClient: + """Return a NATSClient owned by a namespace, on a config with no durable name set.""" + mock_config.get.side_effect = lambda key, default=None: _NAMESPACED_CONFIG.get(key, default) + return NATSClient(namespace=namespace) + + +class TestNATSClientNamespaceOwnership: + """A client belongs to one namespace, and two of them coexist in one process.""" + + def test_default_is_the_root_namespace(self, nats_client: NATSClient) -> None: + assert nats_client.namespace == "" + + def test_root_client_keeps_the_unqualified_registry_name(self, nats_client: NATSClient) -> None: + assert nats_client.name == "nats_client" + + def test_namespaced_client_registers_under_a_qualified_name(self, mock_config: MagicMock) -> None: + assert _namespaced_client(mock_config, "orders").name == "orders_nats_client" + + def test_two_namespaces_coexist_in_one_registry(self, mock_config: MagicMock) -> None: + """Registry.add_component rejects a duplicate name, so this used to raise.""" + orders = _namespaced_client(mock_config, "orders") + invoice = _namespaced_client(mock_config, "invoice") + assert orders.registry.get_component("orders_nats_client") is orders + assert invoice.registry.get_component("invoice_nats_client") is invoice + + def test_surrounding_whitespace_is_rejected_rather_than_trimmed(self, mock_config: MagicMock) -> None: + """Trimming would give one agent two names: the declared one and the registered one.""" + with pytest.raises(ValueError, match="surrounding whitespace"): + _namespaced_client(mock_config, " orders ") + + +class TestNATSClientConsumerIdentityFollowsTheNamespace: + """C1 -- broker-side identity derives from the agent, so co-hosted agents never merge.""" + + async def test_queue_group_is_the_namespace(self, mock_config: MagicMock) -> None: + client = _namespaced_client(mock_config, "orders") + with patch.object(client, "_start_with_retry", new_callable=AsyncMock): + await client.subscribe({"topic.a": AsyncMock()}) + assert client.queue_group == "orders" + + async def test_namespace_wins_over_the_configured_root_queue_group(self, mock_config: MagicMock) -> None: + """'nats_queue_group' is the root namespace's key only.""" + mock_config.get.side_effect = lambda key, default=None: {"app_name": "test-agent", "nats_queue_group": "shared"}.get(key, default) + client = NATSClient(namespace="orders") + with patch.object(client, "_start_with_retry", new_callable=AsyncMock): + await client.subscribe({"topic.a": AsyncMock()}) + assert client.queue_group == "orders" + + async def test_two_namespaces_on_one_topic_get_different_queue_groups(self, mock_config: MagicMock) -> None: + """Sharing a group would make the broker deliver each event to one of the two agents.""" + orders = _namespaced_client(mock_config, "orders") + invoice = _namespaced_client(mock_config, "invoice") + with ( + patch.object(orders, "_start_with_retry", new_callable=AsyncMock), + patch.object(invoice, "_start_with_retry", new_callable=AsyncMock), + ): + await orders.subscribe({"shared.topic": AsyncMock()}) + await invoice.subscribe({"shared.topic": AsyncMock()}) + assert orders.queue_group != invoice.queue_group + + def test_whitespace_is_rejected_at_construction_not_at_subscribe(self, mock_config: MagicMock) -> None: + """A publish-only or Dapr namespace never subscribes, so a subscribe-time check misses it.""" + with pytest.raises(ValueError, match="cannot appear in it"): + _namespaced_client(mock_config, "my orders") + + def test_durable_carries_the_namespace(self, mock_config: MagicMock) -> None: + assert _namespaced_client(mock_config, "orders")._durable_for("orders.created") == "orders-orders_created-durable" + + def test_root_durable_is_unchanged(self, nats_client: NATSClient) -> None: + """Renaming a durable is a consumer migration, so the root namespace keeps its name.""" + assert nats_client._durable_for("orders.created") == "orders_created-durable" + + def test_two_namespaces_on_one_topic_get_different_durables(self, mock_config: MagicMock) -> None: + orders = _namespaced_client(mock_config, "orders") + invoice = _namespaced_client(mock_config, "invoice") + assert orders._durable_for("shared.topic") != invoice._durable_for("shared.topic") + + def test_dotted_namespace_is_rejected(self, mock_config: MagicMock) -> None: + """A dot is a subject separator, so it cannot be silently rewritten into a consumer name.""" + with pytest.raises(ValueError, match="cannot appear in it"): + _namespaced_client(mock_config, "orders.eu") + + def test_hyphenated_namespace_is_rejected_because_the_durable_would_collide(self, mock_config: MagicMock) -> None: + """'orders-eu' on 'created' and 'orders' on 'eu-created' would name one consumer.""" + with pytest.raises(ValueError, match="separator in the JetStream durable name"): + _namespaced_client(mock_config, "orders-eu") + + def test_the_namespace_reaches_the_durable_exactly_as_declared(self, mock_config: MagicMock) -> None: + """Only the topic is rewritten, so the durable can be read back to its namespace.""" + durable = _namespaced_client(mock_config, "orders_eu")._durable_for("orders.created") + assert durable == "orders_eu-orders_created-durable" + assert durable.split("-", 1)[0] == "orders_eu" + + async def test_configured_durable_under_a_namespace_warns(self, mock_config: MagicMock, caplog: pytest.LogCaptureFixture) -> None: + """A root-level durable name would make every namespace bind to one consumer.""" + mock_config.get.side_effect = lambda key, default=None: { + "app_name": "test-agent", + "nats_use_jetstream": True, + "nats_durable_name": "shared-durable", + }.get(key, default) + client = NATSClient(namespace="orders") + with caplog.at_level(logging.WARNING), patch.object(client, "_start_with_retry", new_callable=AsyncMock): + await client.subscribe({"topic.a": AsyncMock()}) + assert "consume each other" in caplog.text + + +class TestNATSClientConnectionName: + """Reason 3 -- attribution. nats.connect() used to be called with no name at all.""" + + async def test_connect_passes_the_name_to_nats(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("BLUEPRINT_GROUP", "billing") + monkeypatch.setenv("POD_NAME", "billing-7d9f") + mock_nc = MagicMock(is_closed=False, is_connected=True) + mock_nc.jetstream = MagicMock(return_value=None) + with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock) as mock_connect: + mock_connect.return_value = mock_nc + await nats_client.connect() + assert mock_connect.call_args[1]["name"] == ".billing.billing-7d9f" + + def test_name_is_namespace_group_pod(self, mock_config: MagicMock, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("BLUEPRINT_GROUP", "billing") + monkeypatch.setenv("POD_NAME", "billing-7d9f") + assert _namespaced_client(mock_config, "orders")._resolve_connection_name() == "orders.billing.billing-7d9f" + + def test_empty_namespace_is_named_rather_than_left_blank(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("BLUEPRINT_GROUP", "billing") + monkeypatch.setenv("POD_NAME", "pod-1") + assert nats_client._resolve_connection_name() == ".billing.pod-1" + + def test_unset_group_is_named_rather_than_left_blank(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("BLUEPRINT_GROUP", raising=False) + monkeypatch.setenv("POD_NAME", "pod-1") + assert nats_client._resolve_connection_name() == "..pod-1" + + def test_pod_name_wins_over_hostname(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("POD_NAME", "from-downward-api") + monkeypatch.setenv("HOSTNAME", "from-kubelet") + assert nats_client._resolve_connection_name().endswith(".from-downward-api") + + def test_hostname_is_used_when_pod_name_is_absent(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("POD_NAME", raising=False) + monkeypatch.setenv("HOSTNAME", "from-kubelet") + assert nats_client._resolve_connection_name().endswith(".from-kubelet") + + def test_falls_back_to_the_host_name(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("POD_NAME", raising=False) + monkeypatch.delenv("HOSTNAME", raising=False) + monkeypatch.setattr("blueprint.agents.clients.io.nats_client.socket.gethostname", lambda: "laptop") + assert nats_client._resolve_connection_name().endswith(".laptop") + + def test_unresolvable_host_still_yields_a_name(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("POD_NAME", raising=False) + monkeypatch.delenv("HOSTNAME", raising=False) + + def _raise() -> str: + raise OSError("no host name") + + monkeypatch.setattr("blueprint.agents.clients.io.nats_client.socket.gethostname", _raise) + assert nats_client._resolve_connection_name().endswith(".") + + def test_a_dotted_group_cannot_add_a_segment(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + """Four segments would misattribute the connection; the name is three by construction.""" + monkeypatch.setenv("BLUEPRINT_GROUP", "eu.west") + monkeypatch.setenv("POD_NAME", "pod-1") + name = nats_client._resolve_connection_name() + assert name == ".eu_west.pod-1" + assert name.count(".") == 2 + + def test_a_group_cannot_forge_a_placeholder(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + """The brackets are what make the placeholders unforgeable, so they are stripped here.""" + monkeypatch.setenv("BLUEPRINT_GROUP", "") + monkeypatch.setenv("POD_NAME", "pod-1") + assert nats_client._resolve_connection_name() == "._ungrouped_.pod-1" + + def test_an_fqdn_hostname_stays_one_segment(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("POD_NAME", raising=False) + monkeypatch.setenv("HOSTNAME", "web-7.eu.internal") + name = nats_client._resolve_connection_name() + assert name.endswith(".web-7_eu_internal") + assert name.count(".") == 2 + + def test_connection_name_is_empty_before_connect(self, nats_client: NATSClient) -> None: + assert nats_client.connection_name == "" + + async def test_connect_records_the_name_it_used(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("BLUEPRINT_GROUP", "billing") + monkeypatch.setenv("POD_NAME", "pod-1") + mock_nc = MagicMock(is_closed=False, is_connected=True) + mock_nc.jetstream = MagicMock(return_value=None) + with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock) as mock_connect: + mock_connect.return_value = mock_nc + await nats_client.connect() + assert nats_client.connection_name == ".billing.pod-1" + + async def test_deployment_identity_never_reaches_the_consumer_identity( + self, mock_config: MagicMock, monkeypatch: pytest.MonkeyPatch + ) -> None: + """C1 -- the connection name carries the pod, so nothing broker-side may derive from it.""" + monkeypatch.setenv("BLUEPRINT_GROUP", "group-b") + monkeypatch.setenv("POD_NAME", "pod-99") + client = _namespaced_client(mock_config, "orders") + with patch.object(client, "_start_with_retry", new_callable=AsyncMock): + await client.subscribe({"orders.created": AsyncMock()}) + assert client.queue_group == "orders" + assert "group-b" not in client._durable_for("orders.created") + assert "pod-99" not in client._durable_for("orders.created") diff --git a/tests/unit/agents/component/test_namespace.py b/tests/unit/agents/component/test_namespace.py new file mode 100644 index 00000000..67e461f1 --- /dev/null +++ b/tests/unit/agents/component/test_namespace.py @@ -0,0 +1,129 @@ +"""Unit tests for the namespace naming, validation and resolution helpers (P6).""" + +import pytest + +from blueprint.agents.component.namespace import ( + ROOT_LABEL, + ROOT_NAMESPACE, + display_segment, + namespace_of, + qualified_component_name, + resolve_for_namespace, + validate_namespace, +) + + +class _Client: + """Stand-in for a namespace-owned component.""" + + def __init__(self, namespace: str) -> None: + self.namespace = namespace + + +class _Unnamespaced: + """Stand-in for a component that predates namespaces.""" + + +class TestQualifiedComponentName: + def test_root_namespace_keeps_the_bare_name(self) -> None: + assert qualified_component_name(ROOT_NAMESPACE, "nats_client") == "nats_client" + + def test_namespace_prefixes_the_name(self) -> None: + assert qualified_component_name("orders", "nats_client") == "orders_nats_client" + + def test_two_namespaces_never_share_a_name(self) -> None: + assert qualified_component_name("orders", "nats_client") != qualified_component_name("invoice", "nats_client") + + +class TestNamespaceOf: + def test_reads_the_namespace_attribute(self) -> None: + assert namespace_of(_Client("orders")) == "orders" + + def test_component_without_the_attribute_is_at_the_root(self) -> None: + assert namespace_of(_Unnamespaced()) == ROOT_NAMESPACE + + def test_none_is_read_as_the_root(self) -> None: + assert namespace_of(_Client(None)) == ROOT_NAMESPACE # type: ignore[arg-type] + + +class TestResolveForNamespace: + def test_own_namespace_wins_over_the_root(self) -> None: + own, root = _Client("orders"), _Client(ROOT_NAMESPACE) + assert resolve_for_namespace([root, own], "orders", description="client") is own + + def test_falls_back_to_the_root_when_the_namespace_has_none(self) -> None: + root = _Client(ROOT_NAMESPACE) + assert resolve_for_namespace([root, _Client("invoice")], "orders", description="client") is root + + def test_root_never_picks_up_a_namespaced_candidate(self) -> None: + """A shared component must not silently attach to one agent's transport.""" + with pytest.raises(ValueError, match="No client is registered"): + resolve_for_namespace([_Client("orders")], ROOT_NAMESPACE, description="client") + + def test_two_candidates_in_one_namespace_raise(self) -> None: + with pytest.raises(ValueError, match="ambiguous"): + resolve_for_namespace([_Client("orders"), _Client("orders")], "orders", description="client") + + def test_ambiguity_error_names_the_level_and_the_asker(self) -> None: + with pytest.raises(ValueError, match="Namespace '' has 2 clients.*namespace 'orders'"): + resolve_for_namespace([_Client(ROOT_NAMESPACE), _Client(ROOT_NAMESPACE)], "orders", description="client") + + def test_nothing_registered_raises(self) -> None: + with pytest.raises(ValueError, match="No client is registered for namespace 'orders'"): + resolve_for_namespace([], "orders", description="client") + + +class TestValidateNamespace: + """One alphabet, enforced where the namespace enters the framework.""" + + def test_root_namespace_is_valid(self) -> None: + assert validate_namespace(ROOT_NAMESPACE) == ROOT_NAMESPACE + + @pytest.mark.parametrize("namespace", ["orders", "orders_eu", "a", "agent2", "order_2_eu"]) + def test_legal_namespaces_pass_through_unchanged(self, namespace: str) -> None: + assert validate_namespace(namespace) == namespace + + def test_hyphen_is_rejected_as_the_durable_separator(self) -> None: + with pytest.raises(ValueError, match="separator in the JetStream durable name"): + validate_namespace("orders-eu") + + @pytest.mark.parametrize("namespace", ["orders.eu", "orders*", "orders>", "", "Orders", "my orders", "1st"]) + def test_illegal_alphabets_are_rejected(self, namespace: str) -> None: + with pytest.raises(ValueError, match="not a legal namespace"): + validate_namespace(namespace) + + def test_the_root_label_cannot_be_produced_by_a_legal_namespace(self) -> None: + """This is what makes the placeholder a reserved form rather than a convention.""" + with pytest.raises(ValueError): + validate_namespace(ROOT_LABEL) + + def test_padded_namespace_is_rejected_rather_than_trimmed(self) -> None: + with pytest.raises(ValueError, match="surrounding whitespace"): + validate_namespace(" orders ") + + def test_whitespace_only_namespace_is_not_the_root(self) -> None: + with pytest.raises(ValueError, match="is not the root namespace"): + validate_namespace(" ") + + def test_the_error_names_the_offending_characters(self) -> None: + with pytest.raises(ValueError, match="'A'"): + validate_namespace("Agent") + + +class TestDisplaySegment: + """Values the deployment owns are sanitised, not validated -- see the docstring for why.""" + + def test_a_usable_value_survives(self) -> None: + assert display_segment("eu-west-1", "") == "eu-west-1" + + def test_dots_cannot_split_one_segment_into_several(self) -> None: + assert display_segment("web-7.eu.internal", "") == "web-7_eu_internal" + + def test_brackets_cannot_forge_a_placeholder(self) -> None: + assert display_segment(ROOT_LABEL, "") != ROOT_LABEL + + def test_whitespace_is_replaced(self) -> None: + assert display_segment("my group", "") == "my_group" + + def test_an_empty_value_becomes_the_placeholder(self) -> None: + assert display_segment(" ", "") == "" diff --git a/tests/unit/agents/io/api/scheduling/test_scheduler.py b/tests/unit/agents/io/api/scheduling/test_scheduler.py index 76b22272..e0a6e325 100644 --- a/tests/unit/agents/io/api/scheduling/test_scheduler.py +++ b/tests/unit/agents/io/api/scheduling/test_scheduler.py @@ -206,19 +206,41 @@ def test_missing_identity_raises(self, settings: dict[str, Any], scheduler: _Tes @pytest.mark.parametrize("topic", ["ops.cron.*", "ops.cron.>"]) def test_wildcard_topic_raises(self, topic: str, settings: dict[str, Any], mock_registry: MagicMock) -> None: unusable = _TestScheduler(topic=topic) - with pytest.raises(ValueError, match="not a usable subject"): + with pytest.raises(ValueError, match="cannot appear in a NATS subject"): _ = unusable.tick_topic def test_whitespace_in_an_explicit_topic_raises(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: unusable = _TestScheduler(topic="ops cron nightly") - with pytest.raises(ValueError, match="contains whitespace"): + with pytest.raises(ValueError, match="cannot appear in a NATS subject"): _ = unusable.tick_topic - def test_whitespace_in_the_identity_is_rewritten_not_rejected(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: - """A spaced app_name is legal and common, and the topic is derived, not typed.""" + def test_whitespace_in_the_identity_is_rejected_not_rewritten(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + """A CronJob is written against this subject by someone who cannot see the rewrite.""" settings["app_name"] = "Health Monitor" derived = _TestScheduler() - assert derived.tick_topic == f"Health_Monitor.scheduler.{derived.name}" + with pytest.raises(ValueError, match="cannot appear in a NATS subject"): + _ = derived.tick_topic + + def test_the_identity_error_names_the_key_and_the_subject_it_would_have_made( + self, settings: dict[str, Any], mock_registry: MagicMock + ) -> None: + settings["app_name"] = "Health Monitor" + derived = _TestScheduler() + with pytest.raises(ValueError, match="'app_name'.*'Health Monitor'.*Health Monitor.scheduler"): + _ = derived.tick_topic + + def test_wildcard_in_the_identity_is_rejected(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + settings["app_name"] = "health*monitor" + derived = _TestScheduler() + with pytest.raises(ValueError, match="cannot appear in a NATS subject"): + _ = derived.tick_topic + + def test_whitespace_in_the_scheduler_name_is_rejected(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + """with_scheduler(name=...) reaches the subject too, so it is checked as well.""" + renamed = _TestScheduler() + renamed.name = "night ly" + with pytest.raises(ValueError, match="cannot appear in a NATS subject"): + _ = renamed.tick_topic class TestWire: diff --git a/tests/unit/agents/services/eventing/conftest.py b/tests/unit/agents/services/eventing/conftest.py index b9d53ac3..060fb914 100644 --- a/tests/unit/agents/services/eventing/conftest.py +++ b/tests/unit/agents/services/eventing/conftest.py @@ -29,9 +29,10 @@ def pub_config() -> EventPublishingConfig: @pytest.fixture def mock_io_client() -> MagicMock: - """Mock IOClientBase with async publish.""" + """Mock IOClientBase with async publish, belonging to the root namespace.""" client = MagicMock() client.publish = AsyncMock() + client.namespace = "" return client diff --git a/tests/unit/agents/services/eventing/test_event_publishing_service.py b/tests/unit/agents/services/eventing/test_event_publishing_service.py index 04bb57f1..ae68bac6 100644 --- a/tests/unit/agents/services/eventing/test_event_publishing_service.py +++ b/tests/unit/agents/services/eventing/test_event_publishing_service.py @@ -1,6 +1,6 @@ """Unit tests for EventPublishingService.""" -from unittest.mock import MagicMock +from unittest.mock import AsyncMock, MagicMock import pytest @@ -14,16 +14,19 @@ class TestLifecycle: - async def test_on_startup_resolves_client_from_registry(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: + async def test_on_startup_resolves_client_from_registry( + self, mock_registry: MagicMock, mock_config: MagicMock, mock_io_client: MagicMock + ) -> None: mock_config.get_event_publishing_config.return_value = EventPublishingConfig() + mock_registry.get_io_clients.return_value = [mock_io_client] svc = EventPublishingService() await svc.on_startup() - mock_registry.get_component.assert_called() - assert svc._client is not None + assert svc._client is mock_io_client - async def test_on_startup_loads_pub_config(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: + async def test_on_startup_loads_pub_config(self, mock_registry: MagicMock, mock_config: MagicMock, mock_io_client: MagicMock) -> None: expected = EventPublishingConfig(topic_mapping={"x.event": TopicConfig(topic="t")}) mock_config.get_event_publishing_config.return_value = expected + mock_registry.get_io_clients.return_value = [mock_io_client] svc = EventPublishingService() await svc.on_startup() assert svc._pub_config is expected @@ -211,3 +214,66 @@ async def test_delegates_to_publish_event( ) await event_publishing_service.publish_status_event({"key": "val"}, "started") mock_io_client.publish.assert_awaited_once() + + +# --------------------------------------------------------------------------- +# P6 -- one publishing service per namespace, on its own client (spec sec. 6) +# --------------------------------------------------------------------------- + + +def _client_in(namespace: str) -> MagicMock: + """Return a mock IO client belonging to a namespace.""" + client = MagicMock() + client.publish = AsyncMock() + client.namespace = namespace + return client + + +class TestNamespaceOwnership: + def test_default_is_the_root_namespace(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: + assert EventPublishingService().namespace == "" + + def test_root_service_keeps_the_unqualified_registry_name(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: + assert EventPublishingService().name == "event_publishing_service" + + def test_namespaced_service_registers_under_a_qualified_name(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: + assert EventPublishingService(namespace="orders").name == "orders_event_publishing_service" + + async def test_publishes_on_its_own_namespaces_client(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: + """Outbound traffic on another namespace's connection would be unattributable.""" + own, root = _client_in("orders"), _client_in("") + mock_registry.get_io_clients.return_value = [root, own] + mock_config.get_event_publishing_config.return_value = EventPublishingConfig() + svc = EventPublishingService(namespace="orders") + await svc.on_startup() + assert svc._client is own + + async def test_falls_back_to_the_root_client(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: + """A namespaced agent in a process with one shared transport keeps working.""" + root = _client_in("") + mock_registry.get_io_clients.return_value = [root, _client_in("invoice")] + mock_config.get_event_publishing_config.return_value = EventPublishingConfig() + svc = EventPublishingService(namespace="orders") + await svc.on_startup() + assert svc._client is root + + async def test_never_borrows_another_namespaces_client(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: + mock_registry.get_io_clients.return_value = [_client_in("invoice")] + mock_config.get_event_publishing_config.return_value = EventPublishingConfig() + svc = EventPublishingService(namespace="orders") + with pytest.raises(ValueError, match="No IO transport client is registered"): + await svc.on_startup() + + async def test_two_clients_in_one_namespace_raise(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: + mock_registry.get_io_clients.return_value = [_client_in("orders"), _client_in("orders")] + mock_config.get_event_publishing_config.return_value = EventPublishingConfig() + svc = EventPublishingService(namespace="orders") + with pytest.raises(ValueError, match="ambiguous"): + await svc.on_startup() + + async def test_no_client_at_all_raises(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: + mock_registry.get_io_clients.return_value = [] + mock_config.get_event_publishing_config.return_value = EventPublishingConfig() + svc = EventPublishingService() + with pytest.raises(ValueError, match="No IO transport client is registered"): + await svc.on_startup() From b4e2529a5f65f928a5e666186b3064a0f4212b0e Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:44:48 +0200 Subject: [PATCH 006/133] fix(actuators): stop /status/env returning credentials in clear (#91) Config masking matched whole keys only, so anything with a prefix or suffix around the secret word came back in clear. Present on develop since 4e6421b and unrelated to this feature; found and fixed here. Co-Authored-By: Claude Opus 5 (1M context) --- CLAUDE.md | 2 +- ...26-08-28-multi-agent-grouping-changelog.md | 66 ++++++++++++- docs/plans/2026-08-28-multi-agent-grouping.md | 52 +++++++++- .../agents/io/api/actuators/actuator_api.py | 94 ++++++++++++++++--- .../io/api/actuators/test_actuator_api.py | 47 ++++++++++ 5 files changed, 243 insertions(+), 18 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index a8e42668..8cc76729 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -71,7 +71,7 @@ uv pip install --no-cache-dir --find-links file:///home/pajoma/pypi/ avs-bluepri surface, config reference, acceptance criteria. Where any other document disagrees with the spec, the spec wins. - **Implementation plan:** `docs/plans/2026-08-28-multi-agent-grouping.md` -- prerequisites P0-P6 - (blocking defects) and phases 0-9. + (blocking defects) and phases 0-10. **Work this feature in reviewable steps.** Make one change, then stop and report what changed and why before starting the next. Do not chain phases together, and do not chain the work items within diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 40558e23..6bc5d4ce 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -147,7 +147,7 @@ The multi-agent work breakdown lived as a 900-line section inside `CLAUDE.md`. I configuration, transport topology, event delivery, caches, startup, backwards compatibility, acceptance criteria, open questions) and `docs/plans/2026-08-28-multi-agent-grouping.md` (the phased breakdown: prerequisites P0-P6 and -phases 0-9). `CLAUDE.md` keeps pointers plus the list of paths that require reading the spec first. +phases 0-10). `CLAUDE.md` keeps pointers plus the list of paths that require reading the spec first. **Motivation.** `CLAUDE.md` is loaded into every session, so a 900-line plan costs context on every task regardless of relevance, and it cannot be reviewed the way a document under `docs/` can. The @@ -1366,6 +1366,70 @@ rewritten for you* section and the corrected placeholder spellings. C1 also gain validate-never-repair rule for boundary-crossing names, the two permitted exceptions, and the requirement that the namespace gate live in `Component.__init__`. +### `/status/env` stopped returning credentials (#91) + +Found auditing configuration handling for the config rework, and **pre-existing on `main` and +`develop`** -- introduced in `4e6421b`, unrelated to this feature. Filed as #91 and fixed here +because the grouped-process work makes the same endpoint cross-agent. + +`ActuatorApi._sanitize_config` masked a key only when the whole key equalled one of four words +(`api_key`, `secret`, `token`, `password`), so every compound key this framework actually uses was +returned in clear by `GET /status/env`: `openai_api_key`, `nats_password`, `azure_client_secret`, +any `*_token`. Lists were not walked either, so a list of provider entries was returned verbatim, +and a URL carrying inline credentials passed through because its key names nothing sensitive. + +`_sanitize_config` now delegates per pair to `_sanitize_value`, and the rules are stated in order: + +- `SECRET_KEY_MARKERS` is matched as a **substring** of the lowercased key (`key`, `secret`, + `token`, `password`, `passwd`, `pwd`, `credential`, `auth`, `private`, `salt`). Deliberately + over-broad -- `api_key_header` is masked although it holds nothing -- because a lost diagnostic + line is cheaper than a published credential, and the docstring says so. +- Dicts **and lists** are walked. +- `_strip_url_userinfo` removes `user:password@` from any string that parses as a URL carrying + userinfo, whatever its key, so `redis://admin:pw@cache:6379/0` under `redis_url` becomes + `redis://cache:6379/0` and stays diagnostic instead of becoming `***`. It returns non-URLs + unchanged -- unlike `_sanitize_redis_url`, which is handed a value already known to be a Redis + URL and can safely fall back to a placeholder. The docstring records why the two differ, so they + are not unified wrongly. +- Booleans pass through even under a matching key: a flag cannot carry a credential, and + `auth_enabled` is what someone reads this endpoint for. + +**Tests.** 17 new cases: ten compound keys as a parametrised set, secrets inside a list of dicts +and inside a list of strings, URL userinfo stripped under an innocuous key, a URL without userinfo +left alone, IPv6 brackets preserved, a boolean passing through, and a plain string containing `@` +left alone. 1354 unit tests pass. + +One unrelated formatting fix rode along: the nested conditional in `llm_status` was the one hunk +`black` wanted to rewrite in this file, and `ruff-format` accepts its version, so the file is now +clean under both formatters. + +### Phase 10 added to the plan -- migration and setup documentation, last + +Recorded on the user's prompt so it is not rediscovered later. No code: it adds a phase to +`docs/plans/2026-08-28-multi-agent-grouping.md` after Phase 9, and moves the phase range to 0-10 in +the plan's status line, `CLAUDE.md` and this changelog's header. + +**Why last rather than now.** Everything a migration guide would describe -- `AgentRegistration`, +group configuration, the entry point, the single image -- is built in phases 0, 2 and 8. Written +before them, a guide documents an API that does not exist, and a reader cannot tell which half is +aspiration. The plan already carries the migration *design* (*Migration path for an existing +agent*); what Phase 10 adds is the part a developer can read and run. + +**What it covers:** a new `docs/guides/multi-agent-setup.md` (scaffolding a group; migrating a +single-agent project; the section listing what stays byte-identical and why, which is what decides +whether anyone trusts the migration; and the one decision to make before migrating, since the agent +name becomes the queue group and part of the durable); `asbs setup` / `asbs create agent` / +`asbs validate` support; and the rewrite of `docs/guides/deployment.md`, which ships today and +contradicts this design. + +**One deliberate omission, stated in the phase:** there is no `asbs migrate` command. `main.py` is +the developer's own declaration, so a rewriter either guesses at intent or breaks on hand edits; a +checklist plus a `validate` that names what is missing is the honest shape. + +P6 is what makes the guide's central claim checkable rather than asserted: an existing project +keeps every registry key, queue group and durable name because the root namespace keeps them, and +that is now enforced by tests. + ### Deployment guide corrected (`2d80b63`) The guide recommended `replicaCount: 2`, an HPA, and `--set replicaCount=3` as ordinary scaling. It diff --git a/docs/plans/2026-08-28-multi-agent-grouping.md b/docs/plans/2026-08-28-multi-agent-grouping.md index 89aacc30..d8b12f23 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping.md +++ b/docs/plans/2026-08-28-multi-agent-grouping.md @@ -2,7 +2,7 @@ | | | |---|---| -| **Status** | P0-P6 landed on `feature/multi-agent-namespaces`; the prerequisites are done. No phase (0-9) started. | +| **Status** | P0-P6 landed on `feature/multi-agent-namespaces`; the prerequisites are done. No phase (0-10) started. | | **Spec (normative)** | `docs/specs/2026-08-28-multi-agent-grouping.md` | | **What landed, and why** | `docs/plans/2026-08-28-multi-agent-grouping-changelog.md` -- read before resuming | @@ -827,6 +827,56 @@ hidden by API design — so they must be caught mechanically rather than documen --- +## Phase 10 — Migration and setup documentation (last, deliberately) + +**Files:** `docs/guides/multi-agent-setup.md` (new), `docs/guides/deployment.md` (rewrite), +`agent_generator` CLI (`asbs setup`, `asbs create agent`, `asbs validate`) + +**Last on purpose.** Everything a migration guide would describe -- `AgentRegistration`, the +group configuration, the entry point, the single image -- is built in phases 0, 2 and 8. A guide +written before them documents an API that does not exist, which is worse than no guide: a reader +cannot tell which half is aspiration. So this phase adds no framework behaviour; it makes what the +earlier phases built usable by someone who has only ever written a single-agent service. + +**What already holds, and is what makes migration safe to document at all.** P6 fixed the +guarantee rather than asserting it: an existing project keeps every registry key, every queue +group and every durable name, because the root namespace keeps them, and that is enforced by tests +rather than by prose. The guide states this as the reason a migration is a no-op on the broker, and +it is a claim the reader can check. + +**`docs/guides/multi-agent-setup.md`:** + +1. Scaffolding a fresh multi-agent repository -- what `asbs setup` produces and why one image + serves every group. +2. Migrating an existing single-agent project -- the two file changes from *Migration path for an + existing agent* above, and nothing else. +3. What stays byte-identical and why: registry names, queue group, durable, telemetry + `service.name` (C1, C2). This is the section that decides whether anyone trusts the migration. +4. The one decision to get right **before** migrating: the agent name becomes the queue group and + part of the durable name, so renaming it afterwards is a consumer migration (sec. 7.7), and it + must satisfy the namespace alphabet (C1) -- `""` or `[a-z][a-z0-9_]*`, no `-`. +5. Group configuration, the entry point, and what regrouping does and does not change (C6). + +**CLI, and one deliberate omission.** `asbs setup` scaffolds a group; `asbs create agent` wires a +new agent into the registration; `asbs validate` reports what a single-agent project must state +before it can be grouped (`scheduler_mode` per namespace, `app_port` at root only). There is +**no `asbs migrate` command**: `main.py` is the developer's own declaration, and a tool that +rewrites it either guesses at intent or fails on anything hand-edited. A checklist plus a +`validate` that names what is missing is the honest shape, and it matches the rule that a +generator must fail loudly rather than emit something plausible. + +**`docs/guides/deployment.md` must be rewritten here or removed.** It ships today, assumes one +Deployment per agent, recommends `replicaCount: 2` plus an HPA as ordinary scaling, and says +nothing about schedulers (#73) or duplicate consumption (P1). It is listed under *Planned, not yet +written* as a Phase 8 obligation; if Phase 8 does not get to it, it lands here, because the setup +guide will contradict it directly. + +**Done when** a developer holding a single-agent service can follow the guide to a grouped +deployment without reading the spec, the plan, or this changelog -- and a reviewer can verify from +the guide alone that nothing broker-side changed. + +--- + ## File change summary | File | Phase | diff --git a/src/blueprint/agents/io/api/actuators/actuator_api.py b/src/blueprint/agents/io/api/actuators/actuator_api.py index 520b5934..135fb43d 100644 --- a/src/blueprint/agents/io/api/actuators/actuator_api.py +++ b/src/blueprint/agents/io/api/actuators/actuator_api.py @@ -6,6 +6,7 @@ from importlib import metadata from importlib.metadata import PackageNotFoundError from typing import Any +from urllib.parse import urlsplit, urlunsplit import httpx from fastapi import HTTPException, status @@ -21,6 +22,21 @@ logger = logging.getLogger(__name__) +SECRET_KEY_MARKERS = ("key", "secret", "token", "password", "passwd", "pwd", "credential", "auth", "private", "salt") +"""Substrings that make a configuration key too dangerous to return over HTTP. + +Matched as substrings, not whole keys, because the keys that actually carry secrets in this +framework are compound: ``openai_api_key``, ``nats_password``, ``azure_client_secret``. A +whole-key match sees none of them. + +Deliberately over-broad. A key such as ``api_key_header`` or ``cache_key_prefix`` is masked +although it holds nothing sensitive, which costs a line of diagnostics; the opposite error +publishes a credential to anything that can reach the actuator. +""" + +CONFIG_MASK = "***" +"""What a masked value is replaced with. Presence stays visible; the value does not.""" + class ActuatorApi(RestApiBase): """Encapsulates all actuator-related endpoints and logic.""" @@ -170,9 +186,7 @@ async def llm_status(self) -> LLMStatus: ai_config_dict = ( ai_config_model.model_dump() if hasattr(ai_config_model, "model_dump") - else ai_config_model.dict() - if hasattr(ai_config_model, "dict") - else {} + else ai_config_model.dict() if hasattr(ai_config_model, "dict") else {} ) ai_config = self._sanitize_config(ai_config_dict) @@ -238,18 +252,68 @@ async def build_status(self) -> BuildStatus: ) def _sanitize_config(self, data: dict[str, Any]) -> dict[str, Any]: - """Mask sensitive keys in configuration dictionaries.""" - - sensitive = {"api_key", "secret", "token", "password"} - sanitized: dict[str, Any] = {} - for key, value in data.items(): - if key.lower() in sensitive: - sanitized[key] = "***" - elif isinstance(value, dict): - sanitized[key] = self._sanitize_config(value) - else: - sanitized[key] = value - return sanitized + """Return ``data`` with everything that could be a credential masked. + + This endpoint publishes configuration over HTTP, so the bias is towards masking: a + false positive loses a line of diagnostics, a false negative publishes a secret. + + Three rules, in order: + + 1. A key containing any of :data:`SECRET_KEY_MARKERS` is masked, whatever its value. + 2. A string value that parses as a URL carrying userinfo has that userinfo stripped, + whatever its key -- ``redis://user:pass@host`` under a key called ``nats_url`` + names nothing sensitive but carries a password. + 3. Booleans pass through even under a matching key. A flag cannot carry a credential, + and ``auth_enabled`` is exactly the kind of value someone reads this endpoint for. + + Dictionaries and lists are walked, because a masked key is worthless if the same + secret sits one level down in a list of provider entries. + """ + return {key: self._sanitize_value(key, value) for key, value in data.items()} + + def _sanitize_value(self, key: str, value: Any) -> Any: + """Apply the rules in :meth:`_sanitize_config` to one key/value pair.""" + if isinstance(value, dict): + return self._sanitize_config(value) + if isinstance(value, (list, tuple)): + return [self._sanitize_value(key, item) for item in value] + if isinstance(value, bool): + return value + if self._is_secret_key(key): + return CONFIG_MASK + if isinstance(value, str): + return self._strip_url_userinfo(value) + return value + + @staticmethod + def _is_secret_key(key: str) -> bool: + """Return whether a configuration key may carry a credential.""" + lowered = key.lower() + return any(marker in lowered for marker in SECRET_KEY_MARKERS) + + @staticmethod + def _strip_url_userinfo(value: str) -> str: + """Return ``value`` with ``user:password@`` removed if it is a URL that carries it. + + Unlike ``_sanitize_redis_url``, which is handed a value already known to be a Redis + URL and returns a placeholder when it cannot parse it, this is handed *every* string + in the configuration. So anything that does not parse as a URL with userinfo is + returned unchanged -- most configuration values are not URLs, and replacing them with + a placeholder would empty the endpoint. + """ + if "@" not in value or "//" not in value: + return value + try: + parts = urlsplit(value) + except ValueError: + return CONFIG_MASK + if not parts.username and not parts.password: + return value + host = parts.hostname or "" + if ":" in host: + host = f"[{host}]" + netloc = f"{host}:{parts.port}" if parts.port is not None else host + return urlunsplit((parts.scheme, netloc, parts.path, parts.query, parts.fragment)) def _ensure_config(self) -> Config: if not self.config: diff --git a/tests/unit/agents/io/api/actuators/test_actuator_api.py b/tests/unit/agents/io/api/actuators/test_actuator_api.py index a7fadaf6..8be0574d 100644 --- a/tests/unit/agents/io/api/actuators/test_actuator_api.py +++ b/tests/unit/agents/io/api/actuators/test_actuator_api.py @@ -55,6 +55,53 @@ def test_deeply_nested_api_key_is_masked(self, actuator_api: ActuatorApi) -> Non def test_empty_dict_returns_empty_dict(self, actuator_api: ActuatorApi) -> None: assert actuator_api._sanitize_config({}) == {} + @pytest.mark.parametrize( + "key", + [ + "openai_api_key", + "vllm_api_key", + "nats_password", + "redis_password", + "azure_client_secret", + "client_token", + "service_credentials", + "signing_salt", + "private_key_pem", + "OPENAI_API_KEY", + ], + ) + def test_compound_keys_are_masked(self, actuator_api: ActuatorApi, key: str) -> None: + """The whole-key match returned every one of these in clear (issue #91).""" + assert actuator_api._sanitize_config({key: "s3cr3t"})[key] == "***" + + def test_secrets_inside_a_list_are_masked(self, actuator_api: ActuatorApi) -> None: + """Only dict values used to be walked, so a list of provider entries was returned whole.""" + result = actuator_api._sanitize_config({"providers": [{"name": "openai", "api_key": "sk-1234"}]}) + assert result["providers"][0] == {"name": "openai", "api_key": "***"} + + def test_a_list_of_secret_values_is_masked(self, actuator_api: ActuatorApi) -> None: + result = actuator_api._sanitize_config({"api_keys": ["sk-a", "sk-b"]}) + assert result["api_keys"] == ["***", "***"] + + def test_url_userinfo_is_stripped_although_the_key_names_nothing_sensitive(self, actuator_api: ActuatorApi) -> None: + result = actuator_api._sanitize_config({"redis_url": "redis://admin:hunter2@cache.internal:6379/0"}) + assert result["redis_url"] == "redis://cache.internal:6379/0" + assert "hunter2" not in result["redis_url"] + + def test_url_without_userinfo_is_untouched(self, actuator_api: ActuatorApi) -> None: + assert actuator_api._sanitize_config({"nats_url": "nats://localhost:4222"})["nats_url"] == "nats://localhost:4222" + + def test_ipv6_url_keeps_its_brackets(self, actuator_api: ActuatorApi) -> None: + result = actuator_api._sanitize_config({"redis_url": "redis://user:pw@[::1]:6379/0"}) + assert result["redis_url"] == "redis://[::1]:6379/0" + + def test_booleans_pass_through_even_under_a_matching_key(self, actuator_api: ActuatorApi) -> None: + """A flag cannot carry a credential, and it is what the endpoint is read for.""" + assert actuator_api._sanitize_config({"auth_enabled": True})["auth_enabled"] is True + + def test_a_plain_string_that_merely_contains_an_at_sign_is_untouched(self, actuator_api: ActuatorApi) -> None: + assert actuator_api._sanitize_config({"contact": "team@example.com"})["contact"] == "team@example.com" + # --------------------------------------------------------------------------- # liveness_probe From ae3adf65c4771adc36cf74b9c53a4d78fbafc2c1 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:44:49 +0200 Subject: [PATCH 007/133] feat(config): give each namespace a scoped view over one loaded tree Phase 0-1. One Config loads the tree; for_namespace hands out a view that reads . and falls back to the root. The application owns logging rather than the library, app_port stays a process-level key, the config loader is unreachable from agent code, and a project chooses its own environment-variable prefix. run_app lets a project serve itself from its own settings. Co-Authored-By: Claude Opus 5 (1M context) --- docs/guides/deployment.md | 53 +++ ...26-08-28-multi-agent-grouping-changelog.md | 393 ++++++++++++++++ src/blueprint/agents/__init__.py | 2 + src/blueprint/agents/app_builder.py | 5 + src/blueprint/agents/component/component.py | 66 ++- src/blueprint/agents/config/config.py | 427 +++++++++++++++++- .../agents/io/api/actuators/actuator_api.py | 60 ++- src/blueprint/agents/models/status.py | 25 +- src/blueprint/agents/utils/__init__.py | 4 +- src/blueprint/agents/utils/utils.py | 116 +++++ .../integration/test_scheduler_event_mode.py | 6 +- .../test_sessions_startup_resilience.py | 6 +- tests/unit/agents/agent/conftest.py | 9 +- tests/unit/agents/app_builder/conftest.py | 12 +- .../agents/app_builder/test_app_builder.py | 30 ++ tests/unit/agents/clients/conftest.py | 10 +- tests/unit/agents/component/conftest.py | 5 +- tests/unit/agents/component/test_component.py | 63 ++- tests/unit/agents/config/TESTS.md | 2 + tests/unit/agents/config/test_agent_scope.py | 33 +- tests/unit/agents/config/test_config_init.py | 23 + .../unit/agents/config/test_envvar_prefix.py | 206 +++++++++ .../agents/config/test_namespace_views.py | 212 +++++++++ tests/unit/agents/handler/conftest.py | 6 +- tests/unit/agents/io/TESTS.md | 2 +- .../io/api/actuators/test_actuator_api.py | 120 ++++- tests/unit/agents/io/conftest.py | 8 +- .../agents/io/telemetry/test_telemetry.py | 2 +- tests/unit/agents/services/conftest.py | 6 +- .../test_cache_sharing_via_registry.py | 3 +- tests/unit/agents/utils/TESTS.md | 8 + tests/unit/agents/utils/test_run_app.py | 103 +++++ 32 files changed, 1932 insertions(+), 94 deletions(-) create mode 100644 tests/unit/agents/config/test_envvar_prefix.py create mode 100644 tests/unit/agents/config/test_namespace_views.py create mode 100644 tests/unit/agents/utils/test_run_app.py diff --git a/docs/guides/deployment.md b/docs/guides/deployment.md index ede13d98..0e8e1d34 100644 --- a/docs/guides/deployment.md +++ b/docs/guides/deployment.md @@ -105,6 +105,59 @@ Nested settings use double underscores as separators. For example, `DYNACONF_LLM api_key = "sk-..." ``` +#### Choosing Your Own Prefix + +`DYNACONF_` is the default, not the only option. Declare `envvar_prefix` as a **top-level** key -- +above every section, because the prefix is resolved before any environment section is selected: + +```toml +envvar_prefix = "ORDERS" + +[default] +app_name = "orders" +``` + +```bash +docker run -e ORDERS_MODEL_NAME="gpt-4" my-ai-service:latest +``` + +An operator can override the declared prefix without rebuilding the image, using the framework's +own bootstrap variable: + +```bash +docker run -e BLUEPRINT_ENVVAR_PREFIX="ORDERS" -e ORDERS_MODEL_NAME="gpt-4" my-ai-service:latest +``` + +Three rules the service enforces at startup, each failing loudly rather than being ignored: + +| Declaration | Result | +|---|---| +| `envvar_prefix = "orders"` | **Rejected.** Dynaconf upper-cases the prefix before matching, so the `orders_*` you export would never be read. Declare it in the case you will export it in. | +| `envvar_prefix = "BLUEPRINT"` or `"POD"` | **Rejected.** Stripping the prefix would turn `BLUEPRINT_GROUP` into the key `group` and expose deployment identity to agent code. | +| `envvar_prefix` inside `[default]` | **Rejected.** The prefix decides how the environment section is chosen, so it cannot live inside one. | + +`DYNACONF_*` keeps working whatever prefix you declare -- Dynaconf always loads it and cannot be +told not to -- so an existing deployment can migrate one variable at a time. Where both spellings +set the same key, the declared prefix wins. + +#### Turning the Prefix Off + +`envvar_prefix = false` (or `BLUEPRINT_ENVVAR_PREFIX=false`) makes every environment variable a +setting, with no prefix at all: + +```bash +docker run -e BLUEPRINT_ENVVAR_PREFIX=false -e MODEL_NAME="gpt-4" my-ai-service:latest +``` + +**This absorbs the whole process environment into your configuration** -- `PATH`, `HOSTNAME`, the +service-discovery variables Kubernetes injects for every Service in the namespace, and any +credential that happens to be exported. Measured on a development machine: 88 settings keys from a +5-key settings file. Anything colliding with one of your key names silently replaces it. + +Prefer a short project prefix. Use `false` only for a container whose environment you fully control +and deliberately want to pass through -- and read the startup log line, which states which prefix +the process resolved. + --- ## Kubernetes with Helm diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 6bc5d4ce..94655ce8 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -1430,6 +1430,379 @@ P6 is what makes the guide's central claim checkable rather than asserted: an ex keeps every registry key, queue group and durable name because the root namespace keeps them, and that is now enforced by tests. +### Config rework, step 1 -- logging leaves `Config`, and `app_port` leaves the scope + +The two prerequisites for one `Config` per namespace (C5). Neither is a namespace feature; both are +things that only work once, and therefore break the moment a process holds N of them. + +**`Config.__init__` no longer configures logging.** The call at the end of the constructor is gone; +the body it called is now the public `Config.configure_logging()`, and `AppBuilder.__init__` makes +the call before any `with_*()` runs, so components are constructed with the format already set. + +Two reasons, and the second is the one that forced it now. It is the application's decision, not +the loader's -- a library that configures logging on construction takes the root logger from +whatever imported it and cannot be silenced by the caller. And one `Config` per namespace means N +constructions per process: each one built a fresh `LoggingManager`, whose `_configured` flag is +per-instance and therefore never helped, so each re-attached the correlation and health-check +filters, logged "Logging configured" again, and let the last namespace's `log_level` win. Verified +before the change by constructing three scoped `Config`s in one process: three configuration lines. + +Existing projects are unaffected, because they all reach `AppBuilder`. What does change: code that +builds a `Config` and never an `AppBuilder` -- a script, a test -- now gets Python's default +logging until it calls `configure_logging()` itself, which is the correct behaviour for a library +and is why the method is public rather than private. + +**`app_port` is a root key even when a `Config` is scoped.** The scoped validator required +`.app_port` alongside `.app_name`. A group is one process behind one HTTP server, so +only one port can ever be bound: requiring it per agent makes every agent declare a value that all +but one of them cannot have. `app_name` stays scoped -- it is the agent's identity and reaches +telemetry and the queue group -- while the port is validated at root with the same `default=8000` +the unscoped path uses. + +**Tests.** 1361 unit tests pass (up from 1354). `TestLoggingIsTheApplicationsDecision` asserts that +construction configures nothing, that `configure_logging()` does, that it passes the resolved +settings, and that three constructions still configure nothing. `TestLoggingOwnership` asserts +`AppBuilder` makes the call exactly once and that a later `with_*()` does not repeat it. The +`app_port` test inverted from "missing scoped port raises" to two cases: a scoped config reads the +root port, and falls back to 8000 when there is none. + +`config.py` remains on `black`'s pre-existing reformat list: the nested conditional in +`_process_dynabox` is one of the places where `black` and `ruff-format` genuinely disagree -- unlike +the `actuator_api.py` hunk, `ruff-format` rejects `black`'s version here -- so it was left as it is +rather than picking a winner inside an unrelated change. + +### Config rework, step 2 -- one loaded tree, one view per namespace (C5) + +`Config` becomes the loader and the owner of the settings tree; each agent reads through a view of +it. This is C5 ("each namespace **MUST** receive a `Config` with `agent_scope` set"), implemented +without N loads and without giving each agent a window on its neighbours. + +**`Config.for_namespace(namespace)` returns a scoped view sharing the loaded tree.** The view is a +shallow copy differing only in `_agent_scope`, so `for_namespace("orders").get("model_name")` +resolves `orders.model_name` and falls back to the root `model_name`, while `nats_url` and the rest +of the infrastructure keys stay shared. The files are parsed once per process, not once per agent: +a test asserts `view._settings is config._settings`. Views are cached per namespace, so a component +asking twice gets the same object. + +This cost almost nothing because every read already funnelled through one place: the nine typed +getters call `self.get()` 25 times and never touch the tree directly, so scoping `get` scopes all +of them. A test covers that rather than trusting it. + +`for_namespace("")` returns the object itself -- not an optimisation but the definition, since the +root namespace *is* the unscoped configuration. Calling `for_namespace` **on a view raises**: a +view is one agent's window, not a factory for other agents' windows, and allowing it would hand +every namespace an unlogged route to its neighbours' keys. + +**`Component.config` returns the component's own view.** A root-namespace component gets the +configuration object unchanged, so every existing application reads exactly what it read before; +a namespaced one gets `shared_config.for_namespace(self._namespace)`. This is what makes the view +more than an unused abstraction, and it is available now only because P6 put the namespace on +`Component` itself. + +**The raw tree becomes an audited escape hatch.** `self.settings` was a public attribute; it is now +a property over `self._settings` that logs on every access. The user asked for a hatch that logs +rather than a wall, so isolation here is **audited, not enforced** -- and the docstring says so, +because the difference matters to anyone relying on it. Enforcing it would mean making the tree +unreachable, which breaks the actuator environment endpoint and any project reading a key the typed +getters do not model. + +The level distinguishes the two cases, which is what keeps the audit useful rather than noisy: the +loader is the application's own object and owns the tree, so its access is DEBUG; a **namespaced +view** handing out the whole tree is an agent reading past its own subsection, so that is WARNING +and names the namespace. An existing single-agent application therefore logs nothing new. + +**Deployment identity is refused, not returned as `None`.** New `DEPLOYMENT_IDENTITY_KEYS` +(`blueprint_group`, `pod_name`, `hostname`) raises from `get()` with the reason: code that can read +its group or pod can be written to depend on them, and regrouping then breaks it (C6). `None` would +have read as "not configured" and sent the caller hunting for a missing setting. The check sits in +`get()`, the single reader every typed getter funnels through, and it is case-insensitive. This is +also the prerequisite for step 3: with `envvar_prefix` disabled Dynaconf absorbs the entire process +environment -- `BLUEPRINT_GROUP` included -- and this is what keeps it out of reach. + +**Tests.** 1387 unit tests pass (up from 1361). New `test_namespace_views.py`: scoped resolution and +root fallback, two agents disagreeing only where they override, the root being the object itself, +caching, the shared tree, the view-of-a-view refusal, the typed getters being scoped, the C6 +refusals including case and the `default=` argument, and the audit -- a view warns and names itself, +the loader does not, and the hatch still returns the whole tree. `TestConfigIsScopedToTheNamespace` +covers the `Component` side. + +**Two test-fixture changes the production change forced, both worth noting.** Six `mock_config` +fixtures are `MagicMock(spec=Config)`, so `for_namespace()` returned a *different* mock and any test +asserting on `mock_config.get` for a namespaced component broke; they now set +`config.for_namespace.return_value = config`, so the mock stands in for both the loader and its +views. And `tests/unit/agents/agent/conftest.py` builds `AgentRuntime` with `object.__new__`, +bypassing `Component.__init__`, so it now supplies `_namespace` the way it already supplied `_name`. +The alternative -- making `Component.config` tolerate a missing `_namespace` via `getattr` -- was +rejected deliberately: it would hide a real ordering bug in any subclass that reads configuration +before calling `super().__init__()`, which is exactly the failure that should be loud. + +### Config rework, step 2b -- the loader stops being reachable from agent code + +Found by review immediately after step 2: the scoped view and its audit could be walked past. Every +class in this framework is a `Component`, so `Component.shared_config` was in reach of every +handler, service and client -- and it hands out the **unscoped loader**, so a read through it is +neither namespaced nor logged. + +It was worse than a class-level name. `configure()` assigns through `cls`, so the value lands on the +`Component` class itself, which *is* in the instance MRO: `self.shared_config` resolved too, which +is the easiest thing to type and the least likely to look wrong. Probed rather than assumed -- all +four of `self.shared_config`, `Component.shared_config`, `type(self).shared_config` and +`type(self).config` returned the loader. + +**`shared_config` is now `_shared_config`, with no public read path at all.** The only route to +configuration is the instance property `Component.config`, which returns the component's own view +(C5) and logs any raw-tree read. Two small public additions on the metaclass replace what tests +were using the attribute for: `has_config()` reports whether configuration has been injected without +handing over the loader, and `reset_shared_state()` clears the process-wide state, which a suite +building more than one application has to do between cases. 13 assignments and 3 reads across the +suite moved onto them. + +**The metaclass `config` property is deleted, and it was the sharper trap.** It returned +`cls._shared_config` -- the *unscoped loader* -- under the name that means *scoped view* on an +instance, so `MyHandler.config` and `self.config` were two different things one character apart. +Nothing used it: a grep for class-level `.config`/`.registry` access across `src/` and `tests/` +found no hits, so it was dead code as well as a trap. + +**`shared_registry` deliberately stays public.** Hiding it protects nothing: looking up +collaborators is the registry's whole purpose, every component already reaches it through the public +instance property, and `AppBuilder` needs it before any component instance exists. A class-level +property named `registry` was tried and reverted -- it collides with the instance property of the +same name, and mypy resolves the instance one in preference to the metaclass one, so +`Component.registry.cache_service` failed to type-check. The reverted attempt is recorded in the +metaclass docstring so it is not retried. + +**Tests.** 1391 unit tests pass (up from 1387). `TestTheConfigLoaderIsNotReachable` asserts the +class-level accessor is gone, that no instance answers to `shared_config`, and that `has_config()` +and `reset_shared_state()` do their jobs. Three `Component.registry` class-level reads in +`test_component.py` moved to `shared_registry`, since deleting the metaclass property is what made +them resolve to the property object rather than the registry. + +`tests/integration/test_sessions_startup_resilience.py` keeps its pre-existing formatting: `black` +wants to rewrite one assertion there and `ruff-format` rejects the result, so the file stays on the +known-debt list rather than having a winner picked inside an unrelated change. + +### Config rework, step 3a -- the environment-variable prefix becomes the project's to choose + +Until now the only spelling an environment override could have was Dynaconf's own `DYNACONF_`. +That is a library's name in a deployment's interface: a chart for a platform hosting several +Blueprint groups has no way to say which of them a variable is meant for, and an operator reading +`DYNACONF_MODEL_NAME` cannot tell it belongs to this framework at all. + +**`envvar_prefix` is now a top-level key in the settings file, overridable in the environment by +`BLUEPRINT_ENVVAR_PREFIX`.** Precedence is environment, then file, then `DYNACONF` -- so a project +that declares nothing behaves exactly as before, which is the point: every existing chart keeps +working untouched. + +**It is resolved in the first Dynaconf pass, not the second.** `Config.__init__` already had a +bootstrap pass whose only job was to read `app_environment` before the real load. The prefix has to +be known before the tree that uses it exists, so it is resolved there, from the files read through +the default prefix -- the one spelling that is always available. + +**That pass then runs a second time whenever the resolved prefix is not the default.** Without it, +`_APP_ENVIRONMENT` would be invisible to the only read that consumes it: the main pass +would load the `[development]` section while every other key honoured the override, and nothing +would report the mismatch. The repeat is skipped entirely for the default prefix, so the common +case still parses the files twice, not three times. + +**Four declarations are rejected rather than repaired**, each because the alternative is silent: + +- **A lowercase prefix.** Dynaconf does `prefix = prefix.upper()` before matching the environment + (`loaders/env_loader.py`), so a declared `myapp` looks for `MYAPP_`. On Linux the + `myapp_` that was actually exported is then never read, and nothing says so. Windows hides + the bug -- its environment is case-insensitive -- so this is exactly the defect that ships. The + alphabet is `[A-Z][A-Z0-9_]*`; commas are excluded too, because Dynaconf reads a comma-separated + prefix as a *list* of prefixes and one override spelling is enough. +- **`BLUEPRINT` and `POD`.** Dynaconf strips the prefix to form the key, so `envvar_prefix = + "BLUEPRINT"` turns `BLUEPRINT_GROUP` into the readable key `group` -- and the C6 blocklist names + `blueprint_group`, not `group`. A prefix could therefore have quietly reopened the hole + `DEPLOYMENT_IDENTITY_KEYS` exists to close. The rejected set is *derived* from that blocklist + (`_ENVVAR_PREFIX_IDENTITY_COLLISIONS` takes the segment before the first underscore), so a new + identity variable closes its own hole without anyone remembering to. +- **`envvar_prefix = true`**, which names no prefix, and any non-string. +- **A prefix declared inside a section.** This is the mistake a developer will actually make: + putting it under `[default]` next to `app_name`. The resolving pass runs with + `environments=False`, so a section is one opaque value to it and the key inside is invisible -- + and it has to run that way, because the prefix is what decides how `app_environment` is read. + Left there it would name no prefix, so *every* override relying on it would be ignored at once. + `_reject_sectioned_envvar_prefix` walks the bootstrap tree and raises naming the path it found + (`development.envvar_prefix`). + +**`envvar_prefix = false` disables the prefix**, and this is a footgun that ships documented rather +than hidden. Dynaconf then absorbs the entire process environment: probed on this machine, 88 keys +against a 5-key settings file, `PATH`, `BLUEPRINT_GROUP`, `POD_NAME` and every `*_API_KEY` in the +shell among them. It is *safe* only because step 2 put `DEPLOYMENT_IDENTITY_KEYS` in front of +`get()` -- with the prefix off, `BLUEPRINT_GROUP` lands in the tree as `blueprint_group`, which is +the exact spelling the C6 blocklist refuses, and a test asserts that for all three identity keys. +The environment spellings that mean off are `false`, `0`, `no` and the empty string, matching +`parse_bool` rather than inventing a second boolean vocabulary. The guide recommends a short +project prefix and describes what disabling it exposes. + +**One Dynaconf behaviour is worth stating because it is not optional.** `DYNACONF_*` is loaded +whatever the prefix is, and cannot be turned off: + +```python +if global_prefix is False or global_prefix.upper() != "DYNACONF": + load_from_env(obj, "DYNACONF", ...) +``` + +So declaring a prefix **adds** a spelling rather than replacing one, and because the custom prefix +is loaded second it wins for the same key. Verified both ways. This is good for migration -- an old +chart keeps working while a new one moves -- and bad for anyone who declares a prefix believing +they have closed the `DYNACONF_` door. Both directions are tested and both are in the docstring. + +`Config.envvar_prefix` is a public read-only property, because "my variable is ignored" and "my +variable is misspelled" are otherwise indistinguishable; the startup log now names the resolved +prefix (or says the environment is read unprefixed). A namespace view shares it: the prefix is a +property of the process, and `for_namespace` copies it with the rest of the loader. + +**Tests.** 1421 unit tests pass (up from 1391), 30 of them new in +`tests/unit/agents/config/test_envvar_prefix.py`: resolution and precedence, the environment +selected through the resolved prefix, `DYNACONF_` surviving alongside a custom prefix and losing to +it, every rejection above, the four falsy spellings, and C6 still holding with the prefix disabled. +An autouse fixture strips ambient `DYNACONF_*` from the environment, since the developer's own shell +can otherwise satisfy or defeat the very lookup under test. + +`src/blueprint/agents/config/config.py` keeps its pre-existing `black` disagreement in +`_process_dynabox`, which this change does not touch: it is on the known-debt list because +`ruff-format` reverts what `black` wants there. + +### Config rework, step 3b -- the environment endpoint answers per agent, and reads the tree once + +`GET /status/env` flattened the whole settings tree into one dictionary. In a grouped process that +is every co-hosted agent's configuration in one blob, with nothing saying which agent a key belongs +to -- and worse, nothing saying what any agent actually *resolves*, because an agent reads its own +subsection overlaid on the root keys and neither half alone is the answer. + +**`Config.resolved_settings(namespace)` builds the dictionary an agent reads.** Root keys, minus +every other namespace's subsection, with this namespace's own subsection overlaid. `""` returns the +whole tree, which is what the root namespace resolves -- so a single-agent application is +unaffected. The overlay skips `None`, matching `_scoped_get`, where `None` at a scoped key means +"not set" and falls back to the root while `""` and `[]` do not. + +Two bugs in the first version of that overlay, both caught by probing it against `get()` key by key +rather than asserting it looked right: + +- **`as_dict()` upper-cases only the top level of the tree**, leaving a subsection's own keys as + written. So the overlay landed `app_name` *beside* `APP_NAME` instead of on it, and the resolved + dictionary reported the root value while `get()` answered the agent value. Fixed by upper-casing + the overlay key. +- That also silently broke the `None`-versus-empty distinction: `billing`'s `model_name = ""` + resolved to the root `"root-model"` in the flattened dictionary and to `""` through `get()`. The + same fix covers it, and a test now asserts equality with `get()` for both agents key by key. + +**`Config.namespaces` lists the namespaces that have asked for a view**, sorted. That is group +membership as configuration sees it, and it is the only reliable source: a namespace subsection and +an ordinary nested table such as `[default.cache]` are indistinguishable in the tree, so the +endpoint cannot discover agents by inspecting it. + +**Both are root-only, and raise on a view -- this is C6, not tidiness.** A view is what agent code +holds (`Component.config` returns one for a namespaced component), so `namespaces` on a view is an +agent asking who it is grouped with, and `resolved_settings("other")` on a view is an agent reading +a neighbour's configuration. Both raise `RuntimeError` naming the namespace that asked, the same +rule `for_namespace` already applies to itself. C6 is thereby enforced at the two new entry points +rather than being left to the endpoint to respect. + +**`env_status` now returns three things instead of two.** `settings` is what the root resolves, +`namespaces` carries one masked entry per agent, and `envvar_prefix` reports what step 3a resolved +(`null` when the prefix is disabled -- unambiguous for a JSON consumer in a way `""` is not). +`namespaces` is empty for every existing single-agent deployment, so the response is additive. + +**The per-namespace breakdown is masked exactly like the root tree.** It is a second copy of the +same values, so `_sanitize_config` runs over each entry; a test asserts that no marker string from +a secret in either the root or an agent section appears anywhere in the serialised response. + +**The raw tree is read once per request.** `env_status` read `config.settings` three times +(`as_dict`, `current_env` for the log, `current_env` for the response) and `build_status` twice. +`Config.settings` is the *audited* property added in step 2 -- every read logs -- so one operator +request produced three records, and would produce a WARNING per read if the actuator ever holds a +view. Both endpoints now take one reference and read fields off it, and a test asserts the property +is touched exactly once per request. `build_status` also stopped reaching for `current_env` and +`settings_files` as bare attributes, which is what made the endpoint depend on the shape of a +Dynaconf object in two places instead of one. + +**An agent-scoped actuator reports only its own scope.** `ActuatorApi` is a root component by the +plan's sharing table, so this is the branch that should never be taken -- but if it is, the +endpoint must not call the two root-only methods and turn a status request into a 500. It falls back +to the tree it holds and an empty breakdown. + +**Tests.** 1443 unit tests pass (up from 1421). 13 new in `test_namespace_views.py` +(`TestResolvedSettings`, `TestNamespacesIsRootOnly`) and 9 in `test_actuator_api.py` +(`TestEnvStatus`). The endpoint tests use a **real** `Config` rather than a `MagicMock`: what is +under test is how the endpoint uses the real scoping and audit behaviour, and a mock would assert +only which methods were called. + +`src/blueprint/agents/io/api/actuators/actuator_api.py` keeps a pre-existing `ruff-format` +disagreement in `llm_status`, untouched by this change, and `config.py` keeps its pre-existing +`black` one in `_process_dynabox`. The new fixture writes its settings text through a named local +rather than a nested `write_text(textwrap.dedent(...))` call, because the two formatters disagree +about that construct and neither has to win. + +### Phase 0, part 1 -- `run_app`, and the worker count it refuses + +First piece of phase 0. `run_app(app, config)` in `utils/utils.py`, exported from +`blueprint.agents`, is the one line a project needs to become runnable by +`python src/main.py`: host, port and log level come from the same settings tree as everything +else instead of a uvicorn invocation duplicated in a Dockerfile, a compose file and a README. + +Development (`app_environment = "development"`) differs in exactly two ways -- the server logs at +`debug`, and it runs one worker whatever the configuration says. + +**`reload` is never enabled, and that is not an omission.** Auto-reload requires uvicorn to import +the application itself, so it needs an import string; it cannot restart an object that has already +been built. The plan said this; the docstring now says it too, because "why does reload not work" +is otherwise a question that gets answered by adding a broken parameter. + +**`app_workers > 1` raises instead of being passed through**, which is a departure from the plan's +"workers from `app_workers` config (default 1)". Two independent reasons, and either alone settles +it: + +- **uvicorn cannot honour it here.** With an application *object* rather than an import string, + `workers > 1` makes uvicorn log `You must pass the application as an import string to enable + 'reload' or 'workers'` against its own logger and call `sys.exit` (`uvicorn/main.py:603-607`, + verified against uvicorn 0.52.4). So the plan's version produces a process that dies before + binding a port, with a message naming a setting the operator did not touch. +- **It is the wrong shape for this framework even where it works.** Every uvicorn worker is a + separate process that builds the application again: N workers open N transport connections, join + the queue group N times, and start N in-process scheduler timers. Scaling is what replicas are + for, and the queue group (P1) and the per-tick claim (P5) are what make replicas correct. The + error message says this and names the alternative for anyone who wants it anyway. + +**The log level is translated, not validated.** The framework spells levels as `logging` does +(`"INFO"`), uvicorn wants them lower-case and has one level `logging` does not (`"trace"`). An +unrecognised value logs a warning and falls back to `"info"` rather than raising: this level +decides only how uvicorn narrates itself, nothing outside the process can depend on it, and the +application's own logging was already configured from the same key by `Config.configure_logging`. +That is the other side of the P6 rule -- names that cross the process boundary are validated, and +this one does not cross it. + +`DEFAULT_APP_HOST = "0.0.0.0"` carries a `# nosec B104`: bind-all is the only useful default +inside a container, which cannot know the address of the interface its traffic arrives on. **Not +verified locally** -- bandit is not installed in this working copy (see `CLAUDE.local.md`), so +whether the marker satisfies the hook is unconfirmed. + +**No caller in this repository yet, deliberately.** The examples end at `app = builder.build()` and +are served by the Dockerfile's `uvicorn src.main:app`, and phase 8 is what turns `main.py` into a +declaration served by `python -m blueprint.agents.entrypoint` -- which is the caller this exists +for. It is public API from today regardless, so it is usable rather than dormant. + +**Tests.** 1462 unit tests pass (up from 1443), 19 new in `tests/unit/agents/utils/test_run_app.py`: +the arguments uvicorn is handed, the two development differences, the level translation and its +fallback, `reload=False`, and the worker refusal -- including that it happens before `uvicorn.run` +is called at all. + +### Not fixed, found while doing this: `app_environment` in `[default]` selects nothing + +The bootstrap pass runs with `environments=False`, so it sees only top-level keys -- `[default]` +arrives as one opaque value. All five examples declare `app_environment` *inside* `[default]`, where +that pass cannot read it, so it never selects an environment: it only lands in the loaded tree as a +value that `config.get("app_environment")` returns. A project that adds a `[production]` section and +sets `app_environment = "production"` under `[default]` gets `[development]` loaded and no warning. +Only a top-level `app_environment`, or `DYNACONF_APP_ENVIRONMENT`, actually switches sections. + +Pre-existing and out of this step, and the fix is not obviously safe -- honouring the sectioned key +would change which section an existing project loads. Left as a decision to take, not a defect to +patch inside a config change. + ### Deployment guide corrected (`2d80b63`) The guide recommended `replicaCount: 2`, an HPA, and `--set replicaCount=3` as ordinary scaling. It @@ -1691,6 +2064,26 @@ stay keyword-only and last, or an existing `with_cache(False)` would silently be generated `CronJob` is the remaining silent-failure case -- the missing `event_bus` and the missing mode both fail at startup now, but a mode and a transport with nothing publishing does not. Validate is where it should be caught. +- **The settings-fragment merge has two unanswered questions, both raised by step 3a.** Spec + sec. 5.3 requires each agent to keep writing plain top-level keys in its own `settings.toml` and + the build to merge each fragment under that agent's scope, reporting collisions with a root key. + Confirmed by probe that nothing does this yet: handing two fragments to + `Config(settings_files=[...])` merges them *flat*, so the last file silently wins -- two + fragments each declaring `model_name` at root end with `for_namespace("orders")` returning + billing's value. What the merge must decide, and the spec does not say: + - **A fragment declaring `envvar_prefix` must be rejected, not merged.** The prefix is + process-wide -- one group, one prefix -- and it is now a *top-level* key, which is exactly the + shape a fragment consists of. `_reject_sectioned_envvar_prefix` does not catch this: it looks + for the key nested inside a section, and a fragment's is at the top level where it looks + legitimate. Merged and scoped it would be silently inert; merged at root, whichever agent + happens to load last would decide how the whole group reads its environment. + - **Whether a fragment may override a shared infrastructure key at all.** Sec. 5.3 says a + collision between a fragment and a root key MUST be *reported*; it does not say whether it is + then refused. The two readings differ in practice: an agent overriding `model_name` is the + point of scoping, while an agent overriding `nats_url` or `app_port` breaks the group it is + hosted in -- and `app_port` is already root-only (config rework step 1), so at least one key + has to be refused rather than reported. The likely answer is a small set of group-owned keys + that a fragment may not carry, with everything else scoped. - **Two requirements this raised for later phases, now written into the spec.** `scheduler_mode` **must** resolve per namespace through C5 rather than once per process, or a group cannot host a pure-scheduler agent on `"in_process"` next to an event-driven agent on diff --git a/src/blueprint/agents/__init__.py b/src/blueprint/agents/__init__.py index 3d5407a9..93b70c5a 100644 --- a/src/blueprint/agents/__init__.py +++ b/src/blueprint/agents/__init__.py @@ -3,10 +3,12 @@ from .agent import AgentBuilder, AgentRuntime from .app_builder import AppBuilder from .config import Config +from .utils import run_app __all__ = [ "AgentBuilder", "AgentRuntime", "AppBuilder", "Config", + "run_app", ] diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index 65cd2039..5f5fdb1f 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -62,6 +62,11 @@ class AppBuilder: """ def __init__(self, config: Config) -> None: + # Logging is configured here rather than in Config.__init__: it is the application's + # decision, not the configuration loader's, and one Config per namespace would + # otherwise reconfigure the root logger once per agent. This runs before any + # with_*() call, so component construction is already logged with the right format. + config.configure_logging() self._config = config self._telemetry_manager = TelemetryManager() self._eventing_component: DaprEventing | NatsEventing | None = None diff --git a/src/blueprint/agents/component/component.py b/src/blueprint/agents/component/component.py index 89d124bf..fb6506c6 100644 --- a/src/blueprint/agents/component/component.py +++ b/src/blueprint/agents/component/component.py @@ -27,27 +27,51 @@ class _ComponentMeta(ABCMeta): - """Metaclass owning class-level config/registry state and their one-time initialisation.""" + """Metaclass owning class-level config/registry state and their one-time initialisation. + + Both attributes are private, and the asymmetry between them is deliberate. + + ``_shared_config`` has **no** public read path. The only way for a component to reach + configuration is the instance property ``Component.config``, which returns that component's + own namespace view (C5) and logs any read of the raw tree. A public class-level accessor + would defeat both: it hands out the *unscoped loader*, so an agent reads its neighbours' + keys with no scoping and no warning. Note that ``configure()`` assigns through ``cls``, so + the value lands on ``Component`` itself and a public name would also be reachable as + ``self.`` -- the easiest thing to type, and a silent bypass. + + ``shared_registry`` stays **public**, and not out of inconsistency: nothing is protected by + hiding it. Looking up collaborators is the registry's whole purpose, every component already + reaches it through the public instance property, and ``AppBuilder`` needs it before any + component instance exists. A class-level property named ``registry`` was tried and reverted -- + it collides with the instance property of the same name, which mypy resolves in preference to + the metaclass one. + """ - shared_config: Config | None = None + _shared_config: Config | None = None shared_registry: Registry | None = None - @property - def config(cls) -> Config | None: - return cls.shared_config - - @property - def registry(cls) -> Registry | None: - return cls.shared_registry - def configure(cls, config: Config) -> None: """Inject configuration once for all components. Called by AppBuilder.build(). Raises RuntimeError if called more than once. """ - if cls.shared_config is not None: + if cls._shared_config is not None: raise RuntimeError("Config is already set — can only be configured once") - cls.shared_config = config + cls._shared_config = config + + def has_config(cls) -> bool: + """Whether configuration has been injected, without handing out the loader.""" + return cls._shared_config is not None + + def reset_shared_state(cls) -> None: + """Drop the injected config and registry. For test isolation only. + + Exists so that tests do not have to assign to the private attributes: the class-level + state is process-wide and one-time, so a suite that builds more than one application has + to clear it between cases. + """ + cls._shared_config = None + cls.shared_registry = None def init_registry(cls, value: Registry) -> None: """Initialise the shared registry. Called lazily on the first Component.__init__(). @@ -140,10 +164,22 @@ def registry(self) -> Registry: @property def config(self) -> Config: - """Get the configuration linked to this component.""" - if Component.shared_config is None: + """Get the configuration linked to this component, scoped to its namespace (C5). + + A namespaced component receives a *view*: ``get`` and the typed getters resolve + ``.`` before the root key, so prompts, model choice and limits become + per-agent while infrastructure keys stay shared. The view shares the loaded tree, so + this costs one dictionary lookup, not another parse of the settings files. + + A root-namespace component gets the configuration object itself, unchanged. That is not + an optimisation but the definition: the root namespace *is* the unscoped configuration, + so every existing single-agent application reads exactly what it read before. + """ + if Component._shared_config is None: raise RuntimeError(f"Config not linked to component '{self._name}'") - return Component.shared_config + if not self._namespace: + return Component._shared_config + return Component._shared_config.for_namespace(self._namespace) @cached_property def tracer(self) -> trace.Tracer: diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index 9311b41c..be6613dd 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -2,6 +2,9 @@ import json import logging +import os +import re +from copy import copy from pathlib import Path from typing import Any @@ -19,6 +22,67 @@ class ConfigError(Exception): """Custom exception for configuration-related errors.""" +DEPLOYMENT_IDENTITY_KEYS = frozenset({"blueprint_group", "pod_name", "hostname"}) +"""Environment values describing *where* a process runs, and therefore not configuration. + +Kept unreadable through ``Config`` because C6 forbids any API reachable from agent code exposing +the deployment group, its membership or its size: an agent that can read them can be written to +depend on them, and regrouping then breaks it. Framework code that needs them reads the +environment directly (``clients/io/nats_client.py``), where no agent can follow. + +The list matters most once ``envvar_prefix`` can be disabled, because Dynaconf then absorbs the +whole process environment -- ``BLUEPRINT_GROUP`` and ``POD_NAME`` included -- and this is what +keeps them out of reach. +""" + + +DEFAULT_ENVVAR_PREFIX = "DYNACONF" +"""The prefix an environment override carries unless the project declares another one. + +Kept as Dynaconf's own default so no existing deployment changes: every ``DYNACONF_`` in a +Helm chart or ``docker run`` keeps resolving. It is also the one spelling that is *always* +available -- Dynaconf loads ``DYNACONF_*`` in addition to any custom prefix and cannot be told +not to (``loaders/env_loader.py``), so declaring a prefix **adds** a spelling rather than +replacing this one. A custom prefix is loaded second and therefore wins for the same key. +""" + +ENVVAR_PREFIX_OVERRIDE = "BLUEPRINT_ENVVAR_PREFIX" +"""Environment variable that overrides the declared ``envvar_prefix``. + +The prefix cannot be overridden through Dynaconf, because it decides what Dynaconf reads: an +operator who wants to change it has to be able to say so before the tree exists. Hence a +framework-owned ``BLUEPRINT_`` variable read straight from the process environment, the same +bootstrap channel the deployment group uses. +""" + +_ENVVAR_PREFIX_ALPHABET = re.compile(r"^[A-Z][A-Z0-9_]*$") +"""Uppercase only, and validated rather than repaired. + +Dynaconf upper-cases the prefix before matching the environment, so a declared ``myapp`` looks +for ``MYAPP_``: on Linux the ``myapp_`` the author actually exported is ignored, with +nothing to debug. The prefix crosses the process boundary -- a chart, a compose file and a +``docker run`` all encode it -- so it is checked, never rewritten. + +Commas are excluded too: Dynaconf reads a comma-separated prefix as a *list* of prefixes, which +is a second way to spell the same override and not something this framework needs. +""" + +_ENVVAR_PREFIX_DISABLED = frozenset({"", "false", "0", "no"}) +"""Spellings that mean "no prefix at all", matching :func:`blueprint.agents.utils.parse_bool`. + +An environment variable carries text, so ``false`` has to mean what TOML's ``false`` means. +""" + +_ENVVAR_PREFIX_IDENTITY_COLLISIONS = frozenset(key.split("_", 1)[0].upper() for key in DEPLOYMENT_IDENTITY_KEYS if "_" in key) +"""Prefixes that would smuggle a deployment-identity variable past :data:`DEPLOYMENT_IDENTITY_KEYS`. + +Dynaconf strips the prefix to form the key, so ``envvar_prefix = "BLUEPRINT"`` turns +``BLUEPRINT_GROUP`` into the readable key ``group`` -- and the C6 blocklist names +``blueprint_group``, not ``group``. Derived from the blocklist rather than written out, so a new +identity variable closes its own hole. +""" + + class Config: """A class to manage the application's configuration using dynaconf.""" @@ -37,24 +101,57 @@ def __init__( TOML files. Raw access via ``self.settings`` remains unscoped. + + Which environment variables count as overrides is decided here too, before the tree is + built: see :meth:`_resolve_envvar_prefix`. The prefix is a property of the process, not + of a namespace, so a view built by :meth:`for_namespace` shares it. """ self._validation_errors: list[str] = [] self._root_path = Path(root_path) if root_path else Path.cwd() self._agent_scope = agent_scope - - # First pass: load config to get app_environment + self._is_view = False + self._views: dict[str, Config] = {} + + # First pass: load config to get envvar_prefix and app_environment. + # + # The prefix has to be known before the tree that uses it can be built, and it is declared + # in the same files -- so this pass reads them through Dynaconf's default prefix, the one + # spelling that is always available (see DEFAULT_ENVVAR_PREFIX). temp_settings = Dynaconf( settings_files=settings_files, environments=False, load_dotenv=False, merge_enabled=True, root_path=root_path ) + self._envvar_prefix = self._resolve_envvar_prefix(temp_settings) + if self._envvar_prefix != DEFAULT_ENVVAR_PREFIX: + # Repeat the pass through the resolved prefix. Without this, `_APP_ENVIRONMENT` + # is invisible to the only read that consumes it: the second pass would load the + # default environment's section while every other key honoured the override, and + # nothing would report the mismatch. + temp_settings = Dynaconf( + settings_files=settings_files, + environments=False, + load_dotenv=False, + merge_enabled=True, + root_path=root_path, + envvar_prefix=self._envvar_prefix, + ) app_env = temp_settings.get("app_environment", "development") - logger.info("Loading configuration properties for environment: %s", app_env) + logger.info( + "Loading configuration properties for environment: %s (environment overrides read from %s)", + app_env, + f"{self._envvar_prefix}_*" if self._envvar_prefix else "the whole process environment, unprefixed", + ) - # Validators differ when scoped: app_name/app_port must live under the scope. + # Validators differ when scoped: app_name is per agent, app_port is not. + # + # A group is one process behind one HTTP server, so only one port can be bound no + # matter how many agents share it. Requiring `.app_port` would make every + # agent declare a value that all but one of them cannot have, so the port stays a + # root key and is validated as one. if agent_scope: validators = [ Validator(f"{agent_scope}.app_name", must_exist=True), - Validator(f"{agent_scope}.app_port", must_exist=True, is_type_of=int), + Validator("app_port", must_exist=True, is_type_of=int, default=8000), Validator("app_environment", must_exist=True, default="development"), ] else: @@ -65,48 +162,316 @@ def __init__( ] # Second pass: load with the correct environment - self.settings = Dynaconf( + self._settings = Dynaconf( settings_files=settings_files, environments=True, current_env=app_env, load_dotenv=False, merge_enabled=True, root_path=root_path, + envvar_prefix=self._envvar_prefix, validators=validators, ) # Validate first. Dynaconf's lazy _setup() triggers validators on the # first attribute access, so this needs to run before any other access - # to self.settings to ensure ValidationError is converted to ConfigError + # to self._settings to ensure ValidationError is converted to ConfigError # by validate()'s exception handler. self.validate() # Replace DOT placeholders - dot_placeholder = self.settings.get("dot_placeholder", "") + dot_placeholder = self._settings.get("dot_placeholder", "") if dot_placeholder: # Process the entire settings object - processed = self._process_dynabox(self.settings, dot_placeholder, ".") + processed = self._process_dynabox(self._settings, dot_placeholder, ".") # Update settings with processed values for key, value in processed.items(): - self.settings[key] = value + self._settings[key] = value + + @staticmethod + def _resolve_envvar_prefix(bootstrap_settings: Any) -> str | bool: + """Decide which prefix environment overrides must carry, before the real tree is loaded. + + Precedence, highest first: the :data:`ENVVAR_PREFIX_OVERRIDE` environment variable, the + ``envvar_prefix`` key in the settings files, then :data:`DEFAULT_ENVVAR_PREFIX`. An + unset prefix therefore behaves exactly as before this existed. + + Args: + bootstrap_settings: The first-pass Dynaconf object, read through the default prefix. + + Returns: + The prefix to hand Dynaconf, or ``False`` to read the environment unprefixed. + + Raises: + ConfigError: if the declared value is not a usable prefix. Every rejection is a + mistake that would otherwise be silent -- an ignored override, or an identity + variable turned into a readable key. + """ + raw: Any = os.environ.get(ENVVAR_PREFIX_OVERRIDE) + source = f"environment variable {ENVVAR_PREFIX_OVERRIDE}" + if raw is None: + raw = bootstrap_settings.get("envvar_prefix") + source = "key 'envvar_prefix' in the settings files" + if raw is None: + Config._reject_sectioned_envvar_prefix(bootstrap_settings) + return DEFAULT_ENVVAR_PREFIX + + if isinstance(raw, bool): + if raw: + raise ConfigError( + f"envvar_prefix ({source}) is true, which names no prefix. Use a string such as " + f"'{DEFAULT_ENVVAR_PREFIX}', or false to read the environment with no prefix." + ) + return False + if not isinstance(raw, str): + raise ConfigError(f"envvar_prefix ({source}) must be a string or false, got {raw!r}.") + + candidate = raw.strip() + if candidate.lower() in _ENVVAR_PREFIX_DISABLED: + return False + if not _ENVVAR_PREFIX_ALPHABET.match(candidate): + raise ConfigError( + f"envvar_prefix ({source}) is {candidate!r}, which cannot be used as a prefix: it must match " + "[A-Z][A-Z0-9_]*. Dynaconf upper-cases the prefix before matching the environment, so a " + "lowercase prefix silently looks for the upper-cased spelling and the variable that was " + "actually exported is never read. Declare the prefix in the case it will be exported in, or " + "use false to read the environment with no prefix." + ) + if candidate in _ENVVAR_PREFIX_IDENTITY_COLLISIONS: + raise ConfigError( + f"envvar_prefix ({source}) is {candidate!r}, which collides with deployment identity: Dynaconf " + f"strips the prefix to form the key, so {candidate}_ would become the readable key '' " + "and bypass the C6 blocklist that keeps the deployment group and the pod out of reach of agent " + "code. Choose another prefix." + ) + return candidate + + @staticmethod + def _reject_sectioned_envvar_prefix(bootstrap_settings: Any) -> None: + """Fail if ``envvar_prefix`` was declared inside a section, where nothing can read it. + + The prefix must be a **top-level** key. The pass that resolves it runs with + ``environments=False``, so a section such as ``[default]`` is still one opaque value to it + and the key inside is invisible -- and it has to run that way, because the prefix is what + decides how ``app_environment`` is read in the first place. A prefix cannot live in the + section that its own resolution selects. + + The natural mistake is therefore to put it next to ``app_name`` under ``[default]``, where + it would do nothing at all. That is the failure this raises for: an ignored prefix means + every environment override is silently ignored with it. + + Raises: + ConfigError: naming each section the key was found in. + """ - # Initialize logging after config is fully loaded - self._initialize_logging() + def find(node: Any, path: str) -> list[str]: + if not hasattr(node, "items"): + return [] + found = [] + for key, value in node.items(): + where = f"{path}.{key}".lstrip(".").lower() + if str(key).lower() == "envvar_prefix": + found.append(where) + else: + found.extend(find(value, where)) + return found + + sectioned = find(bootstrap_settings.as_dict(), "") + if sectioned: + raise ConfigError( + f"'envvar_prefix' is declared as {', '.join(sorted(sectioned))}, inside a section, where nothing " + "reads it: the prefix is resolved before any environment section is selected, so it must be a " + f"top-level key in the settings file (or set as {ENVVAR_PREFIX_OVERRIDE} in the environment). " + "Left where it is, it names no prefix and every environment override that relies on it is ignored." + ) + + @property + def envvar_prefix(self) -> str | bool: + """The prefix an environment override must carry, or ``False`` when none is required. + + Read by the actuator environment endpoint and worth logging at startup: "my variable is + ignored" is otherwise indistinguishable from "my variable is misspelled". + """ + return self._envvar_prefix + + @property + def settings(self) -> Any: + """The raw, unscoped settings tree -- the deliberate escape hatch. + + Everything a component should need is on ``get`` and the typed getters, which resolve + ``.`` before the root key. This property is what stays reachable when that + is not enough, and **every use of it is logged**, so reaching around a namespace view is + visible rather than merely discouraged. + + Isolation between agents is therefore *audited, not enforced*. Enforcing it would mean + making the tree unreachable, which breaks the actuator environment endpoint and any project + reading a key the typed getters do not model. The trade is deliberate: a hatch that leaves + a trace beats a wall with a hole in it. + + The level distinguishes the two cases. The loader is the application's own object and owns + the tree, so its access is DEBUG. A **namespaced view** handing out the whole tree is an + agent reading past its own subsection, which is the case worth seeing, so that is WARNING. + """ + if self._is_view: + logger.warning( + "Namespace '%s' read the raw settings tree, which is not scoped to it: it can see every other " + "agent's configuration. Prefer get() or a typed getter, which resolve '%s.' before the root key.", + self._agent_scope, + self._agent_scope, + ) + else: + logger.debug("Raw settings tree read from the root configuration") + return self._settings + + def for_namespace(self, namespace: str) -> "Config": + """Return a view of this configuration scoped to one agent (C5). + + The view shares this object's loaded tree -- the files are parsed once per process, not + once per agent -- and differs only in which scope its lookups try first. So + ``for_namespace("orders").get("model_name")`` resolves ``orders.model_name`` and falls back + to the root ``model_name``, while infrastructure keys stay shared at the root. + + Views are cached, so a component asking twice gets the same object. + + Args: + namespace: The agent to scope to. ``""`` returns this object unchanged, because the + root namespace *is* the unscoped configuration. + + Raises: + RuntimeError: if called on a view. A view is one agent's window on the configuration, + not a factory for other agents' windows -- allowing it would hand every namespace + an unlogged route to its neighbours' keys, which is exactly what ``settings`` + exists to make visible. + """ + if self._is_view: + raise RuntimeError( + f"Namespace '{self._agent_scope}' asked its own configuration view for a view of namespace " + f"'{namespace}'. Views are created from the application's configuration, not from another " + "agent's view." + ) + if not namespace: + return self + + cached = self._views.get(namespace) + if cached is not None: + return cached + + view = copy(self) + view._agent_scope = namespace + view._is_view = True + view._views = {} + self._views[namespace] = view + return view + + @property + def agent_scope(self) -> str | None: + """The namespace whose keys this object resolves first; ``None`` at the root.""" + return self._agent_scope + + @property + def is_view(self) -> bool: + """Whether this is a per-namespace view rather than the application's own configuration.""" + return self._is_view + + @property + def namespaces(self) -> tuple[str, ...]: + """The namespaces that have asked this configuration for their own view, sorted. + + This is the group membership as *configuration* sees it -- a namespace appears once a + component in it has read :attr:`Component.config`. It exists for the operator-facing + environment endpoint, which otherwise has no way to say which agent a key belongs to. + + Raises: + RuntimeError: if called on a view. C6 forbids agent code observing its grouping, and + a view is what agent code holds: an agent that can list its neighbours can be + written to depend on them, and regrouping then breaks it. The same rule that + makes :meth:`for_namespace` refuse to be called on a view. + """ + if self._is_view: + raise RuntimeError( + f"Namespace '{self._agent_scope}' asked which other namespaces share its process. That is " + "deployment grouping, not configuration, and C6 keeps it out of reach of agent code: an agent " + "written against its neighbours breaks when the group is changed." + ) + return tuple(sorted(self._views)) + + def resolved_settings(self, namespace: str = "") -> dict[str, Any]: + """Return the configuration one namespace resolves, flattened as it would read it. + + The tree holds each agent's overrides in its own subsection, so no single dictionary in it + says what a given agent actually sees. This builds that dictionary the way :meth:`get` + would answer key by key: the root keys, minus every *other* namespace's subsection, with + this namespace's own subsection overlaid on top. + + A key whose scoped value is ``None`` is left at its root value, matching + :meth:`_scoped_get` -- ``None`` there means "not set", not "set to nothing". + + Args: + namespace: The agent to resolve for. ``""`` returns the whole tree, which is what the + root namespace resolves. + + Returns: + A plain dictionary, keys as the settings tree spells them. + + Raises: + RuntimeError: if called on a view, for the reason given on :attr:`namespaces` -- this + answers for an arbitrary namespace, so on a view it would be a route to a + neighbour's configuration. + """ + if self._is_view: + raise RuntimeError( + f"Namespace '{self._agent_scope}' asked its own view to resolve configuration for namespace " + f"'{namespace}'. Views resolve their own keys through get(); they are not a window on another " + "agent's configuration." + ) + + tree: dict[str, Any] = dict(self._settings.as_dict()) + if not namespace: + return tree + + logger.debug("Resolving the flattened configuration of namespace '%s'", namespace) + others = {name.lower() for name in self._views} - {namespace.lower()} + own: Any = None + resolved: dict[str, Any] = {} + for key, value in tree.items(): + lowered = str(key).lower() + if lowered == namespace.lower(): + own = value + elif lowered not in others: + resolved[key] = value + + if hasattr(own, "items"): + # as_dict() upper-cases the top level of the tree but leaves a subsection's own keys + # as written, so the overlay has to be upper-cased to land *on* the root key rather + # than beside it. Without this, a resolved dictionary reports the root value under + # APP_NAME and the agent value under app_name, and disagrees with what get() answers. + for key, value in own.items(): + if value is not None: + resolved[str(key).upper()] = value + return resolved def get_package_root(self) -> Path: """Return the root path where configuration files are located.""" return self._root_path - def _initialize_logging(self) -> None: - """Initialize logging based on configuration. + def configure_logging(self) -> None: + """Configure the root logger from ``log_level``, ``log_format`` and ``suppress_noisy_loggers``. - Called automatically at the end of Config initialization. - Sets up logging with the configured log level and format from settings. + **Called by the application, not by this constructor.** Configuring logging is the + application's decision: a library that does it on import steals the root logger from + whatever imported it, and cannot be silenced by the caller. ``AppBuilder.__init__`` + makes the call, so an existing ``main.py`` that builds an app is unaffected. + + It also has to leave the constructor for the namespace work: one ``Config`` per + namespace means N constructions in one process, and each one re-ran this. It is + idempotent in the sense that matters -- ``LoggingManager`` only touches the root + logger when it has no handlers -- but it re-attached filters and logged + "Logging configured" once per namespace, and the last namespace's level won. """ - log_level = self.settings.get("log_level", "INFO") - log_format = self.settings.get("log_format", "text") - suppress_noisy = self.settings.get("suppress_noisy_loggers", True) + log_level = self._settings.get("log_level", "INFO") + log_format = self._settings.get("log_format", "text") + suppress_noisy = self._settings.get("suppress_noisy_loggers", True) manager = LoggingManager() manager.configure(log_level=log_level, log_format=log_format, suppress_noisy_loggers=suppress_noisy) @@ -192,20 +557,34 @@ def _scoped_get(self, key: str, default: Any = None) -> Any: When ``agent_scope`` is set, tries ``.`` first; if missing or ``None``, falls back to ```` at root. When ``agent_scope`` is None, - behaves exactly like ``self.settings.get(key, default)``. + behaves exactly like a plain unscoped lookup in the tree. ``None`` from a scoped lookup is treated as "not set" so the root fallback fires. Empty containers (``[]``, ``{}``, ``""``) at the scoped key are returned as-is — only ``None`` triggers fallback. """ if self._agent_scope: - scoped = self.settings.get(f"{self._agent_scope}.{key}") + scoped = self._settings.get(f"{self._agent_scope}.{key}") if scoped is not None: return scoped - return self.settings.get(key, default) + return self._settings.get(key, default) def get(self, key: str, default: Any = None) -> Any: - """Get a configuration value, scope-aware when ``agent_scope`` is set.""" + """Get a configuration value, scope-aware when ``agent_scope`` is set. + + Raises: + ValueError: for a key in :data:`DEPLOYMENT_IDENTITY_KEYS`. Raised rather than answered + with ``None``, because ``None`` reads as "not configured" and would send the caller + hunting for a missing setting instead of telling them the value is deliberately out + of reach (C6). Every typed getter funnels through here, so one check covers them all. + """ + if key.lower() in DEPLOYMENT_IDENTITY_KEYS: + raise ValueError( + f"'{key}' is deployment identity, not configuration, and is deliberately unreadable through " + "Config (C6): code that can read the group or the pod can be written to depend on them, and " + "moving the agent to another group then breaks it. Framework code reads these from the " + "environment directly." + ) env_var = self._scoped_get(key, default) # Convert DynaBox to dict @@ -430,7 +809,7 @@ def validate(self) -> bool: """Validate the configuration.""" self._validation_errors.clear() try: - self.settings.validators.validate() + self._settings.validators.validate() if not 1 <= self.get("app_port") <= 65535: raise ConfigError(f"Invalid app port: {self.get('app_port')}") diff --git a/src/blueprint/agents/io/api/actuators/actuator_api.py b/src/blueprint/agents/io/api/actuators/actuator_api.py index 135fb43d..c5f4ffff 100644 --- a/src/blueprint/agents/io/api/actuators/actuator_api.py +++ b/src/blueprint/agents/io/api/actuators/actuator_api.py @@ -162,21 +162,59 @@ async def liveness_probe(self) -> LivenessResponse: "/status/env", response_model=EnvironmentStatus, tags=["Status"], summary="Returns a snapshot of the current configuration." ) async def env_status(self) -> EnvironmentStatus: - """Expose the current configuration state (with secrets masked).""" + """Expose the current configuration state (with secrets masked). + + In a grouped process the settings tree holds every co-hosted agent's configuration, and + flattened into one dictionary it says nothing about which agent a key belongs to. So the + response separates them: ``settings`` is what the root namespace resolves, and + ``namespaces`` carries one entry per agent -- each one flattened the way that agent reads + it, root keys included, so a value inherited from the root is visible where it is used + rather than only where it is declared. + + ``envvar_prefix`` is reported because an override that is ignored and an override that is + misspelled look identical from outside the process. + """ config = self._ensure_config() - try: - raw_config = config.settings.as_dict() - except AttributeError: # pragma: no cover - defensive - raw_config = {} - logger.info("Returning environment status for env %s", config.settings.current_env) + # One read of the raw tree per request, not one per field. Config.settings is audited + # (it logs every raw-tree access), so re-reading it for current_env and again for the + # log line turned a single operator request into three records. + settings = config.settings + environment = getattr(settings, "current_env", "unknown") + + namespaces: dict[str, dict[str, Any]] = {} + if config.is_view: + # An agent-scoped actuator reports its own scope and nothing else: resolving for + # another namespace is refused on a view (C6), and listing neighbours is the thing + # C6 exists to prevent. + raw_config = self._as_dict(settings) + else: + raw_config = config.resolved_settings() + namespaces = {name: self._sanitize_config(config.resolved_settings(name)) for name in config.namespaces} + + logger.info( + "Returning environment status for env %s (%d namespace(s), overrides read from %s)", + environment, + len(namespaces), + f"{config.envvar_prefix}_*" if config.envvar_prefix else "the whole process environment, unprefixed", + ) return EnvironmentStatus( - environment=config.settings.current_env, + environment=environment, + envvar_prefix=config.envvar_prefix if isinstance(config.envvar_prefix, str) else None, settings=self._sanitize_config(raw_config), + namespaces=namespaces, ) + @staticmethod + def _as_dict(settings: Any) -> dict[str, Any]: + """Return the settings tree as a plain dictionary, or ``{}`` if it cannot be read.""" + try: + return dict(settings.as_dict()) + except AttributeError: # pragma: no cover - defensive + return {} + @RestApiBase.get("/status/llm", response_model=LLMStatus, tags=["Status"], summary="Returns AI provider configuration and diagnostics.") async def llm_status(self) -> LLMStatus: """Expose AI configuration and provider diagnostics.""" @@ -240,13 +278,17 @@ async def build_status(self) -> BuildStatus: logger.info("Returning build status for service %s", config.get("app_name")) + # One read of the audited raw tree, as in env_status: current_env and settings_files + # are two fields of the same object, not two reasons to reach past the scoped getters. + settings = config.settings + return BuildStatus( app_name=config.get("app_name"), app_version=config.get("app_version", "unknown"), - environment=config.settings.current_env, + environment=getattr(settings, "current_env", "unknown"), python_version=platform.python_version(), platform=platform.platform(), - settings_files=list(config.settings.settings_files or []), + settings_files=list(getattr(settings, "settings_files", None) or []), build_commit=os.getenv("BUILD_COMMIT", "unknown"), build_timestamp=os.getenv("BUILD_TIMESTAMP", "unknown"), ) diff --git a/src/blueprint/agents/models/status.py b/src/blueprint/agents/models/status.py index c18035f1..2272a3d7 100644 --- a/src/blueprint/agents/models/status.py +++ b/src/blueprint/agents/models/status.py @@ -34,19 +34,42 @@ class EnvironmentStatus(BaseModel): description="Current environment name.", examples=["development", "production"], ) + envvar_prefix: str | None = Field( + default=None, + description=( + "Prefix an environment variable must carry to override a setting. Null means the " + "prefix is disabled and the whole process environment is read unprefixed." + ), + examples=["DYNACONF", "ORDERS"], + ) settings: dict[str, Any] = Field( ..., - description="Sanitized configuration settings.", + description="Sanitized configuration the root namespace resolves.", + ) + namespaces: dict[str, dict[str, Any]] = Field( + default_factory=dict, + description=( + "Sanitized configuration each co-hosted agent resolves, flattened as that agent " + "reads it -- inherited root keys included. Empty for a single-agent service." + ), ) model_config = ConfigDict( json_schema_extra={ "example": { "environment": "development", + "envvar_prefix": "DYNACONF", "settings": { "app_name": "agent-service", "api_key": "***", }, + "namespaces": { + "orders": { + "app_name": "orders", + "model_name": "gpt-4", + "api_key": "***", + } + }, } } ) diff --git a/src/blueprint/agents/utils/__init__.py b/src/blueprint/agents/utils/__init__.py index 6430a8d6..c6ee3c57 100644 --- a/src/blueprint/agents/utils/__init__.py +++ b/src/blueprint/agents/utils/__init__.py @@ -1,3 +1,3 @@ -from .utils import camel_to_snake, parse_bool +from .utils import camel_to_snake, parse_bool, run_app, uvicorn_log_level -__all__ = ["camel_to_snake", "parse_bool"] +__all__ = ["camel_to_snake", "parse_bool", "run_app", "uvicorn_log_level"] diff --git a/src/blueprint/agents/utils/utils.py b/src/blueprint/agents/utils/utils.py index add303f6..e18ed10b 100644 --- a/src/blueprint/agents/utils/utils.py +++ b/src/blueprint/agents/utils/utils.py @@ -1,4 +1,28 @@ import re +from logging import getLogger +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from fastapi import FastAPI + + from ..config import Config + +_log = getLogger(__name__) + +DEFAULT_APP_HOST = "0.0.0.0" # nosec B104 -- a container has to accept traffic from outside itself +"""Address the server binds when ``app_host`` is unset. + +Bind-all is the only useful default inside a container: the process cannot know the address of +the interface its traffic arrives on, and the network boundary is the pod or the daemon, not the +listener. Override ``app_host`` to narrow it. +""" + +DEFAULT_APP_PORT = 8000 +"""Port the server binds when ``app_port`` is unset. One port per process, root-scoped: a group +is one application behind one HTTP server, so a per-agent port could not be bound.""" + +UVICORN_LOG_LEVELS = frozenset({"critical", "error", "warning", "info", "debug", "trace"}) +"""The level names uvicorn accepts, which are not quite the ones :mod:`logging` accepts.""" def camel_to_snake(name: str) -> str: @@ -43,3 +67,95 @@ def parse_bool(value: object, key: str) -> bool: if normalized in ("false", "0", "no"): return False raise ValueError(f"Config key '{key}' must be a boolean, got {value!r}.") + + +def uvicorn_log_level(configured: object) -> str: + """Translate the framework's ``log_level`` into one uvicorn accepts. + + The framework spells levels the way :mod:`logging` does (``"INFO"``); uvicorn wants them + lower-case and knows one level ``logging`` does not (``"trace"``). An unrecognised value + falls back to ``"info"`` with a warning rather than raising: this level only decides how + uvicorn narrates itself, nothing outside the process depends on it, and the application's + own logging has already been configured from the same key by ``Config.configure_logging``. + + Args: + configured: The raw ``log_level`` value. + + Returns: + A level name from :data:`UVICORN_LOG_LEVELS`. + """ + level = str(configured).strip().lower() + if level in UVICORN_LOG_LEVELS: + return level + _log.warning( + "log_level %r is not a level uvicorn understands (%s); the server will log at 'info'", + configured, + ", ".join(sorted(UVICORN_LOG_LEVELS)), + ) + return "info" + + +def run_app(app: "FastAPI", config: "Config") -> None: + """Serve ``app`` with uvicorn, configured from ``config``. + + This is the one line a project's ``main.py`` needs to become runnable, and it exists so the + host, port and log level a container is started with come from the same settings tree as + everything else rather than from a duplicated uvicorn invocation. + + Development (``app_environment = "development"``) differs in two ways: the server logs at + ``debug``, and it runs a single worker whatever the configuration says. Note what is *not* + here -- **``reload`` is never enabled**. Auto-reload requires uvicorn to import the + application itself, so it needs an import string (``"src.main:app"``); it cannot restart an + object that has already been built. A developer who wants reload runs the uvicorn CLI. + + Config keys read: ``app_host`` (default ``"0.0.0.0"``), ``app_port`` (default ``8000``), + ``app_environment`` (default ``"development"``), ``log_level`` (default ``"info"``) and + ``app_workers`` (default ``1``). + + Args: + app: The application returned by ``AppBuilder.build()``. + config: The configuration the application was built from. + + Raises: + ValueError: if ``app_workers`` is greater than 1. See below -- this is deliberate. + """ + import uvicorn + + environment = str(config.get("app_environment", "development")) + development = environment == "development" + + host = str(config.get("app_host", DEFAULT_APP_HOST)) + port = int(config.get("app_port", DEFAULT_APP_PORT)) + workers = 1 if development else int(config.get("app_workers", 1)) + + # Refused rather than passed through, for two independent reasons. + # + # uvicorn cannot honour it here at all: with an application *object* rather than an import + # string, `workers > 1` makes uvicorn log "You must pass the application as an import string" + # against its own logger and call sys.exit (uvicorn/main.py:603-607). That is a process that + # dies before binding a port, with a message naming the wrong setting. + # + # And it is the wrong shape for this framework even where it works: every worker is a separate + # process that builds the application again, so N workers open N transport connections, join + # the queue group N times and start N in-process scheduler timers. Scaling belongs to replicas, + # which the queue group and the tick claim are built for. + if workers > 1: + raise ValueError( + f"app_workers is {workers}, and this framework serves one application per process. uvicorn cannot " + "start multiple workers from an application object -- it needs an import string -- and each worker " + "would build the application again, opening its own transport connection and starting its own " + "scheduler timer. Scale with replicas instead, or run 'uvicorn src.main:app --workers N' yourself " + "and accept that every worker is a separate member of the queue group." + ) + + log_level = "debug" if development else uvicorn_log_level(config.get("log_level", "info")) + + _log.info( + "Serving '%s' on %s:%d (environment %s, uvicorn log level %s, reload disabled)", + config.get("app_name"), + host, + port, + environment, + log_level, + ) + uvicorn.run(app, host=host, port=port, log_level=log_level, workers=workers, reload=False) diff --git a/tests/integration/test_scheduler_event_mode.py b/tests/integration/test_scheduler_event_mode.py index c0e9ce14..dda0c6b3 100644 --- a/tests/integration/test_scheduler_event_mode.py +++ b/tests/integration/test_scheduler_event_mode.py @@ -38,11 +38,9 @@ async def tick(self) -> None: @pytest.fixture(autouse=True) def _reset_component_state(): - Component.shared_config = None - Component.shared_registry = None + Component.reset_shared_state() yield - Component.shared_config = None - Component.shared_registry = None + Component.reset_shared_state() def _config(tmp_path, mode: str) -> Config: diff --git a/tests/integration/test_sessions_startup_resilience.py b/tests/integration/test_sessions_startup_resilience.py index 121eb540..736495af 100644 --- a/tests/integration/test_sessions_startup_resilience.py +++ b/tests/integration/test_sessions_startup_resilience.py @@ -54,11 +54,9 @@ async def handle_event(self, event: GenericCloudEvent, context: dict): # pragma @pytest.fixture(autouse=True) def _reset_component_state(): - Component.shared_config = None - Component.shared_registry = None + Component.reset_shared_state() yield - Component.shared_config = None - Component.shared_registry = None + Component.reset_shared_state() # Not marked @pytest.mark.integration — this test is fully offline (it deliberately diff --git a/tests/unit/agents/agent/conftest.py b/tests/unit/agents/agent/conftest.py index 41d12d67..88fa4964 100644 --- a/tests/unit/agents/agent/conftest.py +++ b/tests/unit/agents/agent/conftest.py @@ -19,13 +19,15 @@ def reset_component_state() -> Generator[None]: return_value=MagicMock(), ): yield - Component.shared_config = None - Component.shared_registry = None + Component.reset_shared_state() @pytest.fixture def mock_config() -> MagicMock: config = MagicMock(spec=Config) + # A namespaced component reads through Config.for_namespace(); the mock stands in for + # both the loader and its views, so a test controls one object rather than two. + config.for_namespace.return_value = config Component.configure(config) return config @@ -46,6 +48,9 @@ def runtime(mock_config: MagicMock, mock_registry: MagicMock) -> AgentRuntime: """ rt = object.__new__(AgentRuntime) rt._name = "test-agent" + # Component.__init__ is skipped here, so the namespace it would set has to be supplied: + # self.config resolves through it to pick the right per-namespace view. + rt._namespace = "" # pydantic_ai Agent.name calls self._override_name.get() (no default — raises LookupError if unset). # Setting it to None makes the property return self._name as the fallback. rt._override_name = contextvars.ContextVar("_override_name") diff --git a/tests/unit/agents/app_builder/conftest.py b/tests/unit/agents/app_builder/conftest.py index 57ff032e..2f8cdca7 100644 --- a/tests/unit/agents/app_builder/conftest.py +++ b/tests/unit/agents/app_builder/conftest.py @@ -37,13 +37,15 @@ def reset_component_state() -> Generator[None]: return_value=MagicMock(), ): yield - Component.shared_config = None - Component.shared_registry = None + Component.reset_shared_state() @pytest.fixture def mock_config() -> MagicMock: config = MagicMock(spec=Config) + # A namespaced component reads through Config.for_namespace(); the mock stands in for + # both the loader and its views, so a test controls one object rather than two. + config.for_namespace.return_value = config Component.configure(config) return config @@ -57,13 +59,13 @@ def mock_registry() -> MagicMock: @pytest.fixture def builder(mock_config: MagicMock) -> AppBuilder: - """AppBuilder with shared_config pre-configured — for fluent-setter tests.""" + """AppBuilder with the shared config pre-configured — for fluent-setter tests.""" return AppBuilder(mock_config) @pytest.fixture def build_config() -> MagicMock: - """Config for build() tests — NOT pre-configured in Component.shared_config. + """Config for build() tests — NOT pre-configured in Component._shared_config. build() calls Component.configure(self._config) internally; injecting via mock_config first would make that call raise 'already configured'. @@ -75,7 +77,7 @@ def build_config() -> MagicMock: @pytest.fixture def builder_for_build(build_config: MagicMock, mock_registry: MagicMock) -> AppBuilder: - """AppBuilder ready for build() — shared_config is still None.""" + """AppBuilder ready for build() — no config has been injected yet.""" return AppBuilder(build_config) diff --git a/tests/unit/agents/app_builder/test_app_builder.py b/tests/unit/agents/app_builder/test_app_builder.py index ccca33dc..a98c1430 100644 --- a/tests/unit/agents/app_builder/test_app_builder.py +++ b/tests/unit/agents/app_builder/test_app_builder.py @@ -9,6 +9,36 @@ from blueprint.agents.services.service_base import ServiceBase from tests.unit.agents.app_builder.conftest import StubHandler, wire_empty_registry +# --------------------------------------------------------------------------- +# logging ownership +# --------------------------------------------------------------------------- + + +class TestLoggingOwnership: + """The application configures logging; Config only supplies the values.""" + + def test_construction_configures_logging(self, mock_config: MagicMock) -> None: + AppBuilder(mock_config) + mock_config.configure_logging.assert_called_once() + + def test_it_happens_before_any_component_is_registered(self, mock_config: MagicMock, mock_registry: MagicMock) -> None: + """A with_*() call constructs components that log, so the format must already be set.""" + builder = AppBuilder(mock_config) + assert mock_config.configure_logging.call_count == 1 + builder.with_service(StubService) + assert mock_config.configure_logging.call_count == 1 + + +class StubService(ServiceBase): + """Minimal service for the ordering test above.""" + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + # --------------------------------------------------------------------------- # with_handler # --------------------------------------------------------------------------- diff --git a/tests/unit/agents/clients/conftest.py b/tests/unit/agents/clients/conftest.py index 8d11476e..0c05a36e 100644 --- a/tests/unit/agents/clients/conftest.py +++ b/tests/unit/agents/clients/conftest.py @@ -14,7 +14,7 @@ def reset_component_state() -> Generator[None]: """Reset shared Component class state after every test. Mirrors the pattern in tests/unit/agents/component/conftest.py: - _ComponentMeta stores shared_config and shared_registry as class-level + _ComponentMeta stores the config and registry as class-level attributes, so they must be cleared to prevent cross-test leakage. """ with patch( @@ -22,8 +22,7 @@ def reset_component_state() -> Generator[None]: return_value=MagicMock(), ): yield - Component.shared_config = None - Component.shared_registry = None + Component.reset_shared_state() @pytest.fixture @@ -31,8 +30,11 @@ def mock_config() -> MagicMock: """Inject a MagicMock Config as the shared component config. All client classes read configuration via self.config, which resolves - to Component.shared_config. This fixture sets that up once per test. + to Component._shared_config. This fixture sets that up once per test. """ config = MagicMock(spec=Config) + # A namespaced component reads through Config.for_namespace(); the mock stands in for + # both the loader and its views, so a test controls one object rather than two. + config.for_namespace.return_value = config Component.configure(config) return config diff --git a/tests/unit/agents/component/conftest.py b/tests/unit/agents/component/conftest.py index 4cfe1f3e..b6b61721 100644 --- a/tests/unit/agents/component/conftest.py +++ b/tests/unit/agents/component/conftest.py @@ -28,7 +28,7 @@ def concrete_component() -> ConcreteComponent: def reset_component_state() -> Generator[None]: """Reset shared class-level state and patch correlation context for every test. - _ComponentMeta stores shared_config and shared_registry as class-level attributes + _ComponentMeta stores the config and registry as class-level attributes on Component. Without this reset, state leaks between tests. """ with patch( @@ -36,5 +36,4 @@ def reset_component_state() -> Generator[None]: return_value=MagicMock(), ): yield - Component.shared_config = None - Component.shared_registry = None + Component.reset_shared_state() diff --git a/tests/unit/agents/component/test_component.py b/tests/unit/agents/component/test_component.py index 5c1c141d..cefdfdb5 100644 --- a/tests/unit/agents/component/test_component.py +++ b/tests/unit/agents/component/test_component.py @@ -114,7 +114,7 @@ class TestComponentMeta: def test_configure_sets_shared_config(self) -> None: mock_config = MagicMock(spec=Config) Component.configure(mock_config) - assert Component.shared_config is mock_config + assert Component._shared_config is mock_config def test_configure_raises_on_second_call(self) -> None: Component.configure(MagicMock(spec=Config)) @@ -341,3 +341,64 @@ async def test_async_still_sets_error_status_when_not_recording(self) -> None: span.set_status.assert_called_once() assert span.set_status.call_args[0][0].status_code == StatusCode.ERROR + + +class TestConfigIsScopedToTheNamespace: + """C5 -- a namespaced component reads its own subsection, the root reads the whole thing.""" + + def test_root_component_gets_the_configuration_itself(self, reset_component_state: None) -> None: + config = MagicMock(spec=Config) + Component.configure(config) + component = ConcreteComponent() + assert component.config is config + config.for_namespace.assert_not_called() + + def test_namespaced_component_gets_its_view(self, reset_component_state: None) -> None: + config = MagicMock(spec=Config) + view = MagicMock(spec=Config) + config.for_namespace.return_value = view + Component.configure(config) + component = ConcreteComponent(namespace="orders") + assert component.config is view + config.for_namespace.assert_called_once_with("orders") + + def test_two_namespaces_get_different_views(self, reset_component_state: None) -> None: + config = MagicMock(spec=Config) + config.for_namespace.side_effect = lambda ns: MagicMock(spec=Config, name=f"view-{ns}") + Component.configure(config) + assert ConcreteComponent(namespace="orders").config is not ConcreteComponent(namespace="billing").config + + def test_missing_config_still_raises(self, reset_component_state: None) -> None: + component = ConcreteComponent() + with pytest.raises(RuntimeError, match="Config not linked"): + _ = component.config + + +class TestTheConfigLoaderIsNotReachable: + """The scoped view is the only route to configuration, so the class-level state stays private.""" + + def test_no_public_class_level_config_accessor(self, reset_component_state: None) -> None: + """Component.config as a *class* attribute used to return the unscoped loader.""" + config = MagicMock(spec=Config) + Component.configure(config) + assert not isinstance(Component.config, Config) + assert isinstance(Component.config, property) + + def test_the_public_name_is_gone_from_instances_too(self, reset_component_state: None) -> None: + """configure() assigns through cls, so a public name would also answer to self..""" + config = MagicMock(spec=Config) + Component.configure(config) + component = ConcreteComponent(namespace="orders") + assert not hasattr(component, "shared_config") + + def test_presence_is_reportable_without_handing_over_the_loader(self, reset_component_state: None) -> None: + assert Component.has_config() is False + Component.configure(MagicMock(spec=Config)) + assert Component.has_config() is True + + def test_reset_clears_both(self, reset_component_state: None) -> None: + Component.configure(MagicMock(spec=Config)) + Component.init_registry(MagicMock()) + Component.reset_shared_state() + assert Component.has_config() is False + assert Component.shared_registry is None diff --git a/tests/unit/agents/config/TESTS.md b/tests/unit/agents/config/TESTS.md index 62132660..ec208544 100644 --- a/tests/unit/agents/config/TESTS.md +++ b/tests/unit/agents/config/TESTS.md @@ -11,6 +11,8 @@ Test coverage for `src/blueprint/agents/config/config.py` and |---|---|---| | `test_config_api_key_resolution.py` | `Config` | Global vs. runtime-specific API key loading (pre-existing, refactored) | | `test_config_init.py` | `Config` | `__init__`, `get`, `get_package_root`, `_process_dynabox` | +| `test_namespace_views.py` | `Config` | `for_namespace` views (C5), the audited `settings` hatch, `resolved_settings` agreeing with `get()` key by key, `namespaces` and its C6 refusal on a view | +| `test_envvar_prefix.py` | `Config` | `envvar_prefix` resolution and precedence, the environment selected through it, `DYNACONF_` coexisting with a custom prefix, the four rejections, prefix disabled and C6 still holding | | `test_config_validation.py` | `Config` | `validate`, `has_validation_errors`, `get_validation_errors` | | `test_config_get_ai_config.py` | `Config` | `get_ai_config` — global/runtime fallback chain, `UsageLimits` | | `test_config_get_runtime_config.py` | `Config` | `get_runtime_config` — merging, key normalisation | diff --git a/tests/unit/agents/config/test_agent_scope.py b/tests/unit/agents/config/test_agent_scope.py index f3971b54..b1759101 100644 --- a/tests/unit/agents/config/test_agent_scope.py +++ b/tests/unit/agents/config/test_agent_scope.py @@ -123,21 +123,38 @@ def test_missing_scoped_app_name_raises(self, write_settings: WriteSettings) -> agent_scope="foo", ) - def test_missing_scoped_app_port_raises(self, write_settings: WriteSettings) -> None: + def test_scoped_config_needs_no_scoped_app_port(self, write_settings: WriteSettings) -> None: + """A group is one process behind one HTTP server, so the port cannot be per agent.""" settings_file = write_settings(""" [development] app_environment = "development" + app_port = 8080 [development.foo] app_name = "foo-app" - # app_port intentionally missing """) - with pytest.raises(ConfigError): - Config( - settings_files=[str(settings_file)], - root_path=str(settings_file.parent), - agent_scope="foo", - ) + config = Config( + settings_files=[str(settings_file)], + root_path=str(settings_file.parent), + agent_scope="foo", + ) + assert config.get("app_name") == "foo-app" + assert config.get("app_port") == 8080 + + def test_scoped_config_falls_back_to_the_default_port(self, write_settings: WriteSettings) -> None: + settings_file = write_settings(""" + [development] + app_environment = "development" + + [development.foo] + app_name = "foo-app" + """) + config = Config( + settings_files=[str(settings_file)], + root_path=str(settings_file.parent), + agent_scope="foo", + ) + assert config.get("app_port") == 8000 def test_root_keys_not_required_when_scoped(self, write_settings: WriteSettings) -> None: # No root app_name / app_port; only scoped versions exist. diff --git a/tests/unit/agents/config/test_config_init.py b/tests/unit/agents/config/test_config_init.py index d9ed9533..c4dc498f 100644 --- a/tests/unit/agents/config/test_config_init.py +++ b/tests/unit/agents/config/test_config_init.py @@ -1,6 +1,7 @@ """Unit tests for Config initialisation and low-level accessors.""" from pathlib import Path +from unittest.mock import MagicMock from blueprint.agents.config import Config @@ -57,6 +58,28 @@ def test_settings_without_dot_placeholder_leaves_keys_intact(self, write_setting assert config.get("my_key") == "value" +class TestLoggingIsTheApplicationsDecision: + """Config loads configuration; it does not touch the root logger (see configure_logging).""" + + def test_construction_does_not_configure_logging(self, base_settings_file: Path, mock_logging_configure: MagicMock) -> None: + Config(settings_files=[str(base_settings_file)], root_path=str(base_settings_file.parent)) + mock_logging_configure.return_value.configure.assert_not_called() + + def test_configure_logging_configures_on_request(self, base_config: Config, mock_logging_configure: MagicMock) -> None: + base_config.configure_logging() + mock_logging_configure.return_value.configure.assert_called_once() + + def test_configure_logging_passes_the_resolved_settings(self, base_config: Config, mock_logging_configure: MagicMock) -> None: + base_config.configure_logging() + assert mock_logging_configure.return_value.configure.call_args.kwargs["log_level"] == base_config.settings.get("log_level", "INFO") + + def test_two_configs_configure_nothing_between_them(self, base_settings_file: Path, mock_logging_configure: MagicMock) -> None: + """One Config per namespace is the point of this move: N constructions, zero reconfigurations.""" + for _ in range(3): + Config(settings_files=[str(base_settings_file)], root_path=str(base_settings_file.parent)) + mock_logging_configure.return_value.configure.assert_not_called() + + class TestProcessDynabox: """Unit tests for the _process_dynabox helper (tested directly).""" diff --git a/tests/unit/agents/config/test_envvar_prefix.py b/tests/unit/agents/config/test_envvar_prefix.py new file mode 100644 index 00000000..23b5e6d3 --- /dev/null +++ b/tests/unit/agents/config/test_envvar_prefix.py @@ -0,0 +1,206 @@ +"""Unit tests for the settable ``envvar_prefix`` and the mistakes it refuses to make silently.""" + +import os +from collections.abc import Iterator +from pathlib import Path + +import pytest + +from blueprint.agents.config import Config +from blueprint.agents.config.config import ( + DEFAULT_ENVVAR_PREFIX, + DEPLOYMENT_IDENTITY_KEYS, + ENVVAR_PREFIX_OVERRIDE, + ConfigError, +) + +from tests.unit.agents.config.conftest import WriteSettings + +PREFIXES_UNDER_TEST = ("DYNACONF_", "MYAPP_", "OTHER_", "BLUEPRINT_ENVVAR") + + +@pytest.fixture(autouse=True) +def clean_environment() -> Iterator[None]: + """Remove any ambient variable that could satisfy or defeat a prefix under test. + + The shell running the tests may export DYNACONF_* values of its own, and every assertion + here is about which spelling Dynaconf reads, so the environment has to start empty of them. + """ + saved = {key: value for key, value in os.environ.items() if key.startswith(PREFIXES_UNDER_TEST)} + for key in saved: + del os.environ[key] + yield + os.environ.update(saved) + + +@pytest.fixture +def settings_file(write_settings: WriteSettings) -> Path: + """A minimal project with no declared prefix.""" + return write_settings(""" + [development] + app_name = "root-app" + app_port = 8000 + model_name = "from-file" + """) + + +@pytest.fixture +def prefixed_settings_file(write_settings: WriteSettings) -> Path: + """The same project, declaring MYAPP as its prefix -- at the top level, where it is read.""" + return write_settings(""" + envvar_prefix = "MYAPP" + + [development] + app_name = "root-app" + app_port = 8000 + model_name = "from-file" + """) + + +def load(path: Path) -> Config: + return Config(settings_files=[str(path)], root_path=str(path.parent)) + + +class TestResolution: + def test_the_default_is_dynaconf(self, settings_file: Path) -> None: + """An existing project declares nothing and must keep the prefix it has always used.""" + assert load(settings_file).envvar_prefix == DEFAULT_ENVVAR_PREFIX + + def test_the_default_prefix_overrides_a_file_value(self, settings_file: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("DYNACONF_MODEL_NAME", "from-dynaconf") + assert load(settings_file).get("model_name") == "from-dynaconf" + + def test_a_top_level_key_declares_the_prefix(self, prefixed_settings_file: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("MYAPP_MODEL_NAME", "from-myapp") + config = load(prefixed_settings_file) + assert (config.envvar_prefix, config.get("model_name")) == ("MYAPP", "from-myapp") + + def test_the_environment_override_beats_the_file(self, prefixed_settings_file: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """An operator has to be able to change the prefix without editing the image.""" + monkeypatch.setenv(ENVVAR_PREFIX_OVERRIDE, "OTHER") + monkeypatch.setenv("OTHER_MODEL_NAME", "from-other") + monkeypatch.setenv("MYAPP_MODEL_NAME", "from-myapp") + config = load(prefixed_settings_file) + assert (config.envvar_prefix, config.get("model_name")) == ("OTHER", "from-other") + + def test_dynaconf_still_resolves_alongside_a_custom_prefix(self, prefixed_settings_file: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Dynaconf always loads DYNACONF_* and cannot be told not to, so declaring a prefix adds one.""" + monkeypatch.setenv("DYNACONF_MODEL_NAME", "from-dynaconf") + assert load(prefixed_settings_file).get("model_name") == "from-dynaconf" + + def test_a_custom_prefix_wins_over_dynaconf_for_the_same_key( + self, prefixed_settings_file: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """The declared prefix is loaded second, so it is the one that decides.""" + monkeypatch.setenv("DYNACONF_MODEL_NAME", "from-dynaconf") + monkeypatch.setenv("MYAPP_MODEL_NAME", "from-myapp") + assert load(prefixed_settings_file).get("model_name") == "from-myapp" + + def test_the_environment_is_selected_through_the_resolved_prefix( + self, prefixed_settings_file: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """app_environment decides which section loads, so it must honour the declared prefix too.""" + monkeypatch.setenv("MYAPP_APP_ENVIRONMENT", "production") + assert load(prefixed_settings_file).get("app_environment") == "production" + + def test_a_namespace_view_reports_the_same_prefix(self, prefixed_settings_file: Path) -> None: + """One process, one prefix: a view shares the loaded tree and cannot have its own.""" + config = load(prefixed_settings_file) + assert config.for_namespace("orders").envvar_prefix == config.envvar_prefix + + +class TestDisabled: + @pytest.mark.parametrize("spelling", ["false", "FALSE", "no", "0", ""]) + def test_a_falsy_spelling_disables_the_prefix(self, settings_file: Path, monkeypatch: pytest.MonkeyPatch, spelling: str) -> None: + monkeypatch.setenv(ENVVAR_PREFIX_OVERRIDE, spelling) + assert load(settings_file).envvar_prefix is False + + def test_toml_false_disables_the_prefix(self, write_settings: WriteSettings) -> None: + path = write_settings(""" + envvar_prefix = false + + [development] + app_name = "root-app" + app_port = 8000 + """) + assert load(path).envvar_prefix is False + + def test_an_unprefixed_variable_resolves(self, settings_file: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv(ENVVAR_PREFIX_OVERRIDE, "false") + monkeypatch.setenv("MODEL_NAME", "bare") + assert load(settings_file).get("model_name") == "bare" + + @pytest.mark.parametrize("key", sorted(DEPLOYMENT_IDENTITY_KEYS)) + def test_deployment_identity_stays_unreadable(self, settings_file: Path, monkeypatch: pytest.MonkeyPatch, key: str) -> None: + """The whole process environment is now in the tree -- C6 is what keeps identity out of reach.""" + monkeypatch.setenv(ENVVAR_PREFIX_OVERRIDE, "false") + monkeypatch.setenv(key.upper(), "leaked") + config = load(settings_file) + with pytest.raises(ValueError, match="deployment identity"): + config.get(key) + + +class TestRejections: + def test_a_lowercase_prefix_is_rejected_not_upper_cased(self, settings_file: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Dynaconf would upper-case it and read a spelling that was never exported.""" + monkeypatch.setenv(ENVVAR_PREFIX_OVERRIDE, "myapp") + with pytest.raises(ConfigError, match="upper-cases the prefix"): + load(settings_file) + + @pytest.mark.parametrize("candidate", ["MY-APP", "A,B", "1APP", "MY APP", "_APP"]) + def test_an_unusable_alphabet_is_rejected(self, settings_file: Path, monkeypatch: pytest.MonkeyPatch, candidate: str) -> None: + monkeypatch.setenv(ENVVAR_PREFIX_OVERRIDE, candidate) + with pytest.raises(ConfigError, match=r"\[A-Z\]\[A-Z0-9_\]\*"): + load(settings_file) + + @pytest.mark.parametrize("candidate", ["BLUEPRINT", "POD"]) + def test_a_prefix_that_would_expose_deployment_identity_is_rejected( + self, settings_file: Path, monkeypatch: pytest.MonkeyPatch, candidate: str + ) -> None: + """Stripping BLUEPRINT_ from BLUEPRINT_GROUP yields 'group', which the C6 blocklist does not name.""" + monkeypatch.setenv(ENVVAR_PREFIX_OVERRIDE, candidate) + with pytest.raises(ConfigError, match="collides with deployment identity"): + load(settings_file) + + def test_true_names_no_prefix_and_is_rejected(self, write_settings: WriteSettings) -> None: + path = write_settings(""" + envvar_prefix = true + + [development] + app_name = "root-app" + app_port = 8000 + """) + with pytest.raises(ConfigError, match="names no prefix"): + load(path) + + def test_a_non_string_is_rejected(self, write_settings: WriteSettings) -> None: + path = write_settings(""" + envvar_prefix = 42 + + [development] + app_name = "root-app" + app_port = 8000 + """) + with pytest.raises(ConfigError, match="must be a string or false"): + load(path) + + def test_a_prefix_declared_inside_a_section_is_rejected(self, write_settings: WriteSettings) -> None: + """The natural mistake: next to app_name under [default], where nothing can read it.""" + path = write_settings(""" + [development] + app_name = "root-app" + app_port = 8000 + envvar_prefix = "MYAPP" + """) + with pytest.raises(ConfigError, match="inside a section"): + load(path) + + def test_the_rejection_names_the_section(self, write_settings: WriteSettings) -> None: + path = write_settings(""" + [development] + app_name = "root-app" + app_port = 8000 + envvar_prefix = "MYAPP" + """) + with pytest.raises(ConfigError, match="development.envvar_prefix"): + load(path) diff --git a/tests/unit/agents/config/test_namespace_views.py b/tests/unit/agents/config/test_namespace_views.py new file mode 100644 index 00000000..d67a4168 --- /dev/null +++ b/tests/unit/agents/config/test_namespace_views.py @@ -0,0 +1,212 @@ +"""Unit tests for per-namespace configuration views (C5) and the audited escape hatch.""" + +import logging +from pathlib import Path + +import pytest + +from blueprint.agents.config import Config +from blueprint.agents.config.config import DEPLOYMENT_IDENTITY_KEYS + +from tests.unit.agents.config.conftest import WriteSettings + + +@pytest.fixture +def two_agent_config(write_settings: WriteSettings) -> Config: + """Configuration with a shared root and two agents that override parts of it.""" + settings_file = write_settings(""" + [development] + app_environment = "development" + app_name = "root-app" + app_port = 8000 + model_name = "root-model" + nats_url = "nats://localhost:4222" + + [development.orders] + app_name = "orders" + model_name = "orders-model" + + [development.billing] + app_name = "billing" + """) + return Config(settings_files=[str(settings_file)], root_path=str(settings_file.parent)) + + +class TestForNamespace: + def test_view_resolves_its_own_key_first(self, two_agent_config: Config) -> None: + assert two_agent_config.for_namespace("orders").get("model_name") == "orders-model" + + def test_view_falls_back_to_the_root_key(self, two_agent_config: Config) -> None: + """Infrastructure stays shared; only what an agent overrides is per-agent.""" + assert two_agent_config.for_namespace("orders").get("nats_url") == "nats://localhost:4222" + + def test_an_agent_without_an_override_reads_the_root_value(self, two_agent_config: Config) -> None: + assert two_agent_config.for_namespace("billing").get("model_name") == "root-model" + + def test_two_views_disagree_where_the_agents_do(self, two_agent_config: Config) -> None: + orders = two_agent_config.for_namespace("orders") + billing = two_agent_config.for_namespace("billing") + assert orders.get("model_name") != billing.get("model_name") + assert orders.get("app_name") == "orders" + assert billing.get("app_name") == "billing" + + def test_the_root_namespace_is_the_configuration_itself(self, two_agent_config: Config) -> None: + """Not an optimisation: the root namespace *is* the unscoped configuration.""" + assert two_agent_config.for_namespace("") is two_agent_config + + def test_views_are_cached(self, two_agent_config: Config) -> None: + assert two_agent_config.for_namespace("orders") is two_agent_config.for_namespace("orders") + + def test_the_tree_is_loaded_once_and_shared(self, two_agent_config: Config) -> None: + """A view must not re-parse the settings files -- one process, one load.""" + view = two_agent_config.for_namespace("orders") + assert view._settings is two_agent_config._settings + + def test_a_view_reports_its_scope(self, two_agent_config: Config) -> None: + view = two_agent_config.for_namespace("orders") + assert (view.agent_scope, view.is_view) == ("orders", True) + + def test_the_loader_is_not_a_view(self, two_agent_config: Config) -> None: + assert (two_agent_config.agent_scope, two_agent_config.is_view) == (None, False) + + def test_a_view_cannot_hand_out_another_namespaces_view(self, two_agent_config: Config) -> None: + """Otherwise every agent has an unlogged route to its neighbours' keys.""" + orders = two_agent_config.for_namespace("orders") + with pytest.raises(RuntimeError, match="not from another"): + orders.for_namespace("billing") + + def test_the_typed_getters_are_scoped_too(self, write_settings: WriteSettings) -> None: + """Every typed getter funnels through get(), so scoping applies without per-getter work.""" + settings_file = write_settings(""" + [development] + app_environment = "development" + app_name = "root-app" + app_port = 8000 + idempotency_enabled = false + + [development.orders] + app_name = "orders" + idempotency_enabled = true + idempotency_ttl = 600 + """) + config = Config(settings_files=[str(settings_file)], root_path=str(settings_file.parent)) + assert config.get_event_publishing_config() is not None + assert config.for_namespace("orders").get("idempotency_ttl") == 600 + + +class TestDeploymentIdentityIsNotConfiguration: + """C6 -- agent code that can read its group can be written to depend on it.""" + + @pytest.mark.parametrize("key", sorted(DEPLOYMENT_IDENTITY_KEYS)) + def test_deployment_keys_are_refused(self, two_agent_config: Config, key: str) -> None: + with pytest.raises(ValueError, match="deployment identity"): + two_agent_config.get(key) + + def test_the_refusal_holds_for_a_view(self, two_agent_config: Config) -> None: + with pytest.raises(ValueError, match="deployment identity"): + two_agent_config.for_namespace("orders").get("BLUEPRINT_GROUP") + + def test_the_check_is_case_insensitive(self, two_agent_config: Config) -> None: + with pytest.raises(ValueError, match="deployment identity"): + two_agent_config.get("Pod_Name") + + def test_it_raises_rather_than_answering_none(self, two_agent_config: Config) -> None: + """None would read as 'not configured' and send the caller hunting for a missing key.""" + with pytest.raises(ValueError): + two_agent_config.get("hostname", "a-default") + + def test_an_ordinary_key_is_unaffected(self, two_agent_config: Config) -> None: + assert two_agent_config.get("app_name") == "root-app" + + +class TestRawSettingsIsAudited: + """Isolation is audited, not enforced -- so the audit has to actually happen.""" + + def test_a_view_reading_the_tree_warns_and_names_the_namespace( + self, two_agent_config: Config, caplog: pytest.LogCaptureFixture + ) -> None: + view = two_agent_config.for_namespace("orders") + with caplog.at_level(logging.WARNING): + _ = view.settings + assert "orders" in caplog.text + assert "not scoped to it" in caplog.text + + def test_the_loader_reading_the_tree_does_not_warn(self, two_agent_config: Config, caplog: pytest.LogCaptureFixture) -> None: + """The application owns its own configuration; only reaching past a view is notable.""" + with caplog.at_level(logging.WARNING): + _ = two_agent_config.settings + assert caplog.text == "" + + def test_the_hatch_still_returns_the_whole_tree(self, two_agent_config: Config) -> None: + """It is an escape hatch, not a second scoped reader -- it has to work.""" + assert two_agent_config.for_namespace("orders").settings.get("billing.app_name") == "billing" + + +class TestPackageRootSurvivesTheView: + def test_view_keeps_the_root_path(self, two_agent_config: Config) -> None: + assert isinstance(two_agent_config.for_namespace("orders").get_package_root(), Path) + assert two_agent_config.for_namespace("orders").get_package_root() == two_agent_config.get_package_root() + + +class TestResolvedSettings: + """The flattened view of what one namespace reads, used by the environment endpoint.""" + + @pytest.mark.parametrize("key", ["app_name", "model_name", "nats_url"]) + def test_it_agrees_with_get_key_by_key(self, two_agent_config: Config, key: str) -> None: + """The whole point: a dictionary that says what the agent resolves, not what it declares.""" + view = two_agent_config.for_namespace("orders") + resolved = two_agent_config.resolved_settings("orders") + assert resolved[key.upper()] == view.get(key) + + def test_an_inherited_root_key_is_present(self, two_agent_config: Config) -> None: + """Shared infrastructure is what the agent reads, so it belongs in the agent's view.""" + assert two_agent_config.resolved_settings("orders")["NATS_URL"] == "nats://localhost:4222" + + def test_the_agent_override_replaces_the_root_key(self, two_agent_config: Config) -> None: + resolved = two_agent_config.resolved_settings("orders") + assert resolved["MODEL_NAME"] == "orders-model" + assert [k for k in resolved if k.lower() == "model_name"] == ["MODEL_NAME"] + + def test_another_namespace_section_is_removed(self, two_agent_config: Config) -> None: + """An operator asking what orders resolves must not be handed billing's configuration.""" + two_agent_config.for_namespace("billing") + resolved = two_agent_config.resolved_settings("orders") + assert "BILLING" not in resolved + assert "ORDERS" not in resolved + + def test_an_empty_string_override_is_kept(self, two_agent_config: Config) -> None: + """Only None means "not set" in _scoped_get, so an empty value must survive the overlay.""" + settings = two_agent_config.settings + settings["billing"] = {**dict(settings["billing"]), "model_name": ""} + view = two_agent_config.for_namespace("billing") + assert two_agent_config.resolved_settings("billing")["MODEL_NAME"] == view.get("model_name") == "" + + def test_the_root_resolves_the_whole_tree(self, two_agent_config: Config) -> None: + """Unchanged behaviour for a single-agent application: the root namespace sees everything.""" + resolved = two_agent_config.resolved_settings() + assert resolved["MODEL_NAME"] == "root-model" + assert "ORDERS" in resolved + + def test_a_namespace_nobody_declared_resolves_the_root(self, two_agent_config: Config) -> None: + assert two_agent_config.resolved_settings("unknown")["MODEL_NAME"] == "root-model" + + +class TestNamespacesIsRootOnly: + def test_it_lists_the_namespaces_that_asked_for_a_view(self, two_agent_config: Config) -> None: + two_agent_config.for_namespace("orders") + two_agent_config.for_namespace("billing") + assert two_agent_config.namespaces == ("billing", "orders") + + def test_it_is_empty_before_any_view_exists(self, two_agent_config: Config) -> None: + assert two_agent_config.namespaces == () + + def test_a_view_cannot_list_its_neighbours(self, two_agent_config: Config) -> None: + """C6: an agent that can see its grouping can be written to depend on it.""" + view = two_agent_config.for_namespace("orders") + with pytest.raises(RuntimeError, match="C6"): + _ = view.namespaces + + def test_a_view_cannot_resolve_another_namespace(self, two_agent_config: Config) -> None: + view = two_agent_config.for_namespace("orders") + with pytest.raises(RuntimeError, match="not a window on another"): + view.resolved_settings("billing") diff --git a/tests/unit/agents/handler/conftest.py b/tests/unit/agents/handler/conftest.py index 5b0cde36..89f40a97 100644 --- a/tests/unit/agents/handler/conftest.py +++ b/tests/unit/agents/handler/conftest.py @@ -40,13 +40,15 @@ def reset_component_state() -> Generator[None]: return_value=MagicMock(), ): yield - Component.shared_config = None - Component.shared_registry = None + Component.reset_shared_state() @pytest.fixture def mock_config() -> MagicMock: config = MagicMock(spec=Config) + # A namespaced component reads through Config.for_namespace(); the mock stands in for + # both the loader and its views, so a test controls one object rather than two. + config.for_namespace.return_value = config Component.configure(config) return config diff --git a/tests/unit/agents/io/TESTS.md b/tests/unit/agents/io/TESTS.md index 1cb61486..79f69bcf 100644 --- a/tests/unit/agents/io/TESTS.md +++ b/tests/unit/agents/io/TESTS.md @@ -9,7 +9,7 @@ Test coverage for `src/blueprint/agents/io/`. | File | Class under test | What is covered | |---|---|---| | `api/test_rest_api_base.py` | `RestApiBase` | HTTP verb decorators attach `_route`, `_wire_routes` registers routes, `_build_problem_details` RFC 7807 fields, `_resolve_status_title` | -| `api/actuators/test_actuator_api.py` | `ActuatorApi` | `_sanitize_config` (flat + nested), `liveness_probe` always UP, `on_startup`/`on_shutdown` lifecycle | +| `api/actuators/test_actuator_api.py` | `ActuatorApi` | `_sanitize_config` (flat + nested), `liveness_probe` always UP, `on_startup`/`on_shutdown` lifecycle, `env_status` per-namespace breakdown and masking, reported `envvar_prefix`, one audited tree read per request | | `api/actuators/health/test_client_health.py` | `ClientHealthChecker` | `connect()` called before `health_check()`, healthy/unhealthy/mixed aggregation, empty client list | | `api/actuators/health/test_health_cache.py` | `HealthCheckCache` | Initial state, provider updates, all-healthy→UP, one-unhealthy→DOWN, exception→unhealthy component, `get_cache_age_seconds`, `get_cache_info`, start/stop idempotency | | `api/actuators/health/test_sessions_health.py` | `SessionsServiceHealthChecker` | REST API reachable→UP, `RequestError`→DOWN with details, fresh heartbeat→UP, stale heartbeat→DOWN, no heartbeat→UP (unknown), `update_heartbeat` | diff --git a/tests/unit/agents/io/api/actuators/test_actuator_api.py b/tests/unit/agents/io/api/actuators/test_actuator_api.py index 8be0574d..f4d37bcd 100644 --- a/tests/unit/agents/io/api/actuators/test_actuator_api.py +++ b/tests/unit/agents/io/api/actuators/test_actuator_api.py @@ -1,9 +1,14 @@ """Unit tests for ActuatorApi.""" -from unittest.mock import AsyncMock, MagicMock, patch +import textwrap +from pathlib import Path +from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch import pytest +from blueprint.agents.component.component import Component +from blueprint.agents.component.registry import Registry +from blueprint.agents.config import Config from blueprint.agents.io.api.actuators.actuator_api import ActuatorApi @@ -220,3 +225,116 @@ async def test_validation_error_payload_is_preserved(self, actuator_with_cache: # below would have overwritten it with "Readiness probe failed". assert exc_info.value.detail["status"] == "DOWN" assert exc_info.value.detail["errors"] == ["missing redis_url"] + + +# --------------------------------------------------------------------------- +# env_status +# --------------------------------------------------------------------------- + + +@pytest.fixture +def grouped_config(tmp_path: Path, mock_registry: MagicMock) -> Config: + """A real Config with two agents, injected as the shared component config. + + A MagicMock cannot stand in here: the endpoint is being tested for how it uses the scoping + and audit behaviour of the real Config, not for which methods it happens to call. + """ + settings = tmp_path / "settings.toml" + content = textwrap.dedent(""" + [development] + app_name = "root-app" + app_port = 8000 + health_check_interval_seconds = 30 + model_name = "root-model" + nats_url = "nats://localhost:4222" + openai_api_key = "sk-must-not-appear" + + [development.orders] + app_name = "orders" + model_name = "orders-model" + orders_api_token = "tok-must-not-appear" + + [development.billing] + app_name = "billing" + """) + settings.write_text(content) + config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + Component.configure(config) + return config + + +class TestEnvStatus: + async def test_a_single_agent_service_reports_no_namespaces(self, grouped_config: Config) -> None: + """Nothing has asked for a view, so the response is shaped as it always was.""" + result = await ActuatorApi().env_status() + assert result.namespaces == {} + assert result.settings["MODEL_NAME"] == "root-model" + + async def test_each_namespace_that_asked_for_config_is_reported(self, grouped_config: Config) -> None: + grouped_config.for_namespace("orders") + grouped_config.for_namespace("billing") + + result = await ActuatorApi().env_status() + + assert sorted(result.namespaces) == ["billing", "orders"] + + async def test_a_namespace_entry_is_what_that_agent_resolves(self, grouped_config: Config) -> None: + """Including keys it inherits: an operator debugging a value needs where it is read, not declared.""" + view = grouped_config.for_namespace("orders") + + result = await ActuatorApi().env_status() + + orders = result.namespaces["orders"] + assert orders["MODEL_NAME"] == view.get("model_name") == "orders-model" + assert orders["NATS_URL"] == "nats://localhost:4222" + + async def test_one_namespace_does_not_see_another(self, grouped_config: Config) -> None: + grouped_config.for_namespace("orders") + grouped_config.for_namespace("billing") + + result = await ActuatorApi().env_status() + + assert "BILLING" not in result.namespaces["orders"] + assert result.namespaces["billing"]["APP_NAME"] == "billing" + + async def test_secrets_are_masked_in_every_namespace(self, grouped_config: Config) -> None: + """The per-namespace breakdown is a second copy of the tree, so it needs the same masking.""" + grouped_config.for_namespace("orders") + + result = await ActuatorApi().env_status() + + assert result.settings["OPENAI_API_KEY"] == "***" + assert result.namespaces["orders"]["OPENAI_API_KEY"] == "***" + assert result.namespaces["orders"]["ORDERS_API_TOKEN"] == "***" + assert "must-not-appear" not in str(result.model_dump()) + + async def test_the_resolved_envvar_prefix_is_reported(self, grouped_config: Config) -> None: + assert (await ActuatorApi().env_status()).envvar_prefix == "DYNACONF" + + async def test_a_disabled_prefix_is_reported_as_null(self, tmp_path: Path, mock_registry: MagicMock) -> None: + """Null is unambiguous for a JSON consumer; an empty string reads as a prefix of nothing.""" + settings = tmp_path / "settings.toml" + settings.write_text('envvar_prefix = false\n\n[development]\napp_name = "root-app"\napp_port = 8000\n') + Component.configure(Config(settings_files=[str(settings)], root_path=str(tmp_path))) + + assert (await ActuatorApi().env_status()).envvar_prefix is None + + async def test_the_raw_tree_is_read_once_per_request(self, grouped_config: Config) -> None: + """Config.settings is audited, so re-reading it turns one operator request into three records.""" + grouped_config.for_namespace("orders") + with patch.object(type(grouped_config), "settings", new_callable=PropertyMock) as raw: + raw.return_value = grouped_config._settings + await ActuatorApi().env_status() + + assert raw.call_count == 1 + + async def test_an_agent_scoped_actuator_reports_only_its_own_scope(self, grouped_config: Config) -> None: + """C6 refuses both halves of the breakdown on a view, so the endpoint must not attempt it.""" + Component.reset_shared_state() + Component.configure(grouped_config.for_namespace("orders")) + Component.shared_registry = MagicMock(spec=Registry) + + result = await ActuatorApi().env_status() + + assert result.namespaces == {} + assert result.settings["APP_NAME"] == "root-app" diff --git a/tests/unit/agents/io/conftest.py b/tests/unit/agents/io/conftest.py index ce245e18..694126cc 100644 --- a/tests/unit/agents/io/conftest.py +++ b/tests/unit/agents/io/conftest.py @@ -15,7 +15,7 @@ def reset_component_state() -> Generator[None]: """Reset shared Component class state after every test. Mirrors the pattern from clients/conftest.py — _ComponentMeta stores - shared_config and shared_registry as class-level attributes and must be + the config and registry as class-level attributes and must be cleared between tests to prevent cross-test leakage. """ with patch( @@ -23,14 +23,16 @@ def reset_component_state() -> Generator[None]: return_value=MagicMock(), ): yield - Component.shared_config = None - Component.shared_registry = None + Component.reset_shared_state() @pytest.fixture def mock_config() -> MagicMock: """Inject a MagicMock Config as the shared component config.""" config = MagicMock(spec=Config) + # A namespaced component reads through Config.for_namespace(); the mock stands in for + # both the loader and its views, so a test controls one object rather than two. + config.for_namespace.return_value = config Component.configure(config) return config diff --git a/tests/unit/agents/io/telemetry/test_telemetry.py b/tests/unit/agents/io/telemetry/test_telemetry.py index 0e4b318b..6c63d366 100644 --- a/tests/unit/agents/io/telemetry/test_telemetry.py +++ b/tests/unit/agents/io/telemetry/test_telemetry.py @@ -41,7 +41,7 @@ class TestConfigureTracing: def test_raises_when_config_is_none(self, telemetry_manager: TelemetryManager) -> None: from blueprint.agents.component.component import Component - Component.shared_config = None + Component.reset_shared_state() with pytest.raises((ValueError, RuntimeError)): telemetry_manager.configure_tracing() diff --git a/tests/unit/agents/services/conftest.py b/tests/unit/agents/services/conftest.py index 677fa9e4..f8838d56 100644 --- a/tests/unit/agents/services/conftest.py +++ b/tests/unit/agents/services/conftest.py @@ -17,13 +17,15 @@ def reset_component_state() -> Generator[None]: return_value=MagicMock(), ): yield - Component.shared_config = None - Component.shared_registry = None + Component.reset_shared_state() @pytest.fixture def mock_config() -> MagicMock: config = MagicMock(spec=Config) + # A namespaced component reads through Config.for_namespace(); the mock stands in for + # both the loader and its views, so a test controls one object rather than two. + config.for_namespace.return_value = config Component.configure(config) return config diff --git a/tests/unit/agents/services/infrastructure/test_cache_sharing_via_registry.py b/tests/unit/agents/services/infrastructure/test_cache_sharing_via_registry.py index 238a4792..2bd57a4b 100644 --- a/tests/unit/agents/services/infrastructure/test_cache_sharing_via_registry.py +++ b/tests/unit/agents/services/infrastructure/test_cache_sharing_via_registry.py @@ -77,8 +77,7 @@ def read(self, key: str) -> dict | None: def reset_component_state() -> Generator[None]: """Reset Component class-level state between tests so each test starts fresh.""" yield - Component.shared_config = None - Component.shared_registry = None + Component.reset_shared_state() @pytest.fixture diff --git a/tests/unit/agents/utils/TESTS.md b/tests/unit/agents/utils/TESTS.md index 5d7dfcb1..229f5365 100644 --- a/tests/unit/agents/utils/TESTS.md +++ b/tests/unit/agents/utils/TESTS.md @@ -9,6 +9,7 @@ Test coverage for `src/blueprint/agents/utils/utils.py`. | File | Function under test | What is covered | |---|---|---| | `test_camel_to_snake.py` | `camel_to_snake` | Standard CamelCase, acronyms (leading/mid/trailing), numbers, edge cases | +| `test_run_app.py` | `run_app`, `uvicorn_log_level` | Arguments handed to uvicorn (host, port, coerced string port, defaults); development logs at `debug` and forces one worker; production translates `log_level` and defaults to `info`; `app_workers > 1` raises before `uvicorn.run` is called; `reload` is never enabled; unknown level falls back to `info` with a warning | | `test_parse_bool.py` | `parse_bool` | Real bools pass through; the truthy and falsy strings an environment override delivers (`true`/`1`/`yes`, `false`/`0`/`no`, case and whitespace tolerant); everything else raises rather than reading as false, including empty and whitespace-only; the error names the key | --- @@ -18,3 +19,10 @@ Test coverage for `src/blueprint/agents/utils/utils.py`. ### No conftest needed `camel_to_snake` and `parse_bool` are pure functions with no dependencies or side effects. All inputs are inline string literals — no fixtures, no shared state. + +### `run_app` is tested through a patched `uvicorn.run` +`run_app` imports uvicorn inside the function, so `patch("uvicorn.run")` is enough and no server +is ever started. What is asserted is the argument set uvicorn is handed, which is the whole of +what `run_app` decides. Two local helpers in the test module stand in for a conftest: `make_config` +builds a `Config` stand-in answering `get` from a dict, and `serve` runs the function and returns +the keyword arguments uvicorn received. diff --git a/tests/unit/agents/utils/test_run_app.py b/tests/unit/agents/utils/test_run_app.py new file mode 100644 index 00000000..42b393e0 --- /dev/null +++ b/tests/unit/agents/utils/test_run_app.py @@ -0,0 +1,103 @@ +"""Unit tests for ``run_app`` and the uvicorn log-level translation.""" + +import logging +from typing import Any +from unittest.mock import MagicMock, patch + +import pytest + +from blueprint.agents.config import Config +from blueprint.agents.utils import run_app, uvicorn_log_level + +Settings = dict[str, Any] + + +def make_config(**settings: Any) -> MagicMock: + """Return a Config stand-in answering ``get`` from ``settings``, defaults otherwise.""" + config = MagicMock(spec=Config) + config.get.side_effect = lambda key, default=None: settings.get(key, default) + return config + + +def serve(**settings: Any) -> dict[str, Any]: + """Run ``run_app`` against a mocked uvicorn and return the keyword arguments it received.""" + app = MagicMock() + with patch("uvicorn.run") as run: + run_app(app, make_config(**settings)) + assert run.call_args.args == (app,) + return dict(run.call_args.kwargs) + + +class TestServerArguments: + def test_host_and_port_come_from_config(self) -> None: + kwargs = serve(app_host="127.0.0.1", app_port=9001) + assert (kwargs["host"], kwargs["port"]) == ("127.0.0.1", 9001) + + def test_the_defaults_bind_all_interfaces_on_8000(self) -> None: + """A container cannot know which interface its traffic arrives on.""" + kwargs = serve() + assert (kwargs["host"], kwargs["port"]) == ("0.0.0.0", 8000) + + def test_a_string_port_is_coerced(self) -> None: + """An environment override arrives as text, and uvicorn wants an int.""" + assert serve(app_port="9002")["port"] == 9002 + + def test_reload_is_never_enabled(self) -> None: + """Auto-reload needs an import string; uvicorn cannot restart an object already built.""" + assert serve(app_environment="development")["reload"] is False + + +class TestDevelopment: + def test_development_logs_at_debug(self) -> None: + assert serve(app_environment="development", log_level="WARNING")["log_level"] == "debug" + + def test_development_ignores_configured_workers(self) -> None: + """The refusal below is a production concern; in development it is simply one worker.""" + assert serve(app_environment="development", app_workers=4)["workers"] == 1 + + def test_the_default_environment_is_development(self) -> None: + assert serve()["log_level"] == "debug" + + +class TestProduction: + def test_the_configured_level_is_translated(self) -> None: + assert serve(app_environment="production", log_level="WARNING")["log_level"] == "warning" + + def test_the_level_defaults_to_info(self) -> None: + assert serve(app_environment="production")["log_level"] == "info" + + def test_one_worker_is_allowed(self) -> None: + assert serve(app_environment="production", app_workers=1)["workers"] == 1 + + @pytest.mark.parametrize("workers", [2, "4"]) + def test_more_than_one_worker_is_refused(self, workers: object) -> None: + """uvicorn would sys.exit here, naming 'reload' -- and N workers means N transports.""" + with pytest.raises(ValueError, match="one application per process"): + serve(app_environment="production", app_workers=workers) + + def test_the_refusal_happens_before_the_server_starts(self) -> None: + with patch("uvicorn.run") as run: + with pytest.raises(ValueError): + run_app(MagicMock(), make_config(app_environment="production", app_workers=8)) + run.assert_not_called() + + +class TestUvicornLogLevel: + @pytest.mark.parametrize( + ("configured", "expected"), + [ + ("INFO", "info"), + ("debug", "debug"), + (" WARNING ", "warning"), + ("critical", "critical"), + ("trace", "trace"), + ], + ) + def test_a_known_level_is_lower_cased(self, configured: str, expected: str) -> None: + assert uvicorn_log_level(configured) == expected + + def test_an_unknown_level_falls_back_to_info_and_warns(self, caplog: pytest.LogCaptureFixture) -> None: + """Nothing outside the process depends on this level, so it warns rather than raising.""" + with caplog.at_level(logging.WARNING): + assert uvicorn_log_level("WARN") == "info" + assert "uvicorn understands" in caplog.text From c818a122b40191bb9fc88de426644f410bf0775e Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:44:51 +0200 Subject: [PATCH 008/133] feat(component): resolve components and caches per agent Phases 2-4. The namespace is ambient -- captured from the scope at the call site, never named by developer code and never forwarded to a constructor -- so one declaration can be applied alone or once per namespace. The registry resolves per namespace with the root as fallback, each namespace gets its own thread pool, and a cache gains a name with its own store and its own partition per agent. Co-Authored-By: Claude Opus 5 (1M context) --- docs/guides/deployment.md | 56 ++ ...26-08-28-multi-agent-grouping-changelog.md | 843 ++++++++++++++++++ .../agent_generator/base_files/Dockerfile | 6 + src/blueprint/agents/__init__.py | 4 +- src/blueprint/agents/app_builder.py | 559 +++++++++++- src/blueprint/agents/component/component.py | 59 +- src/blueprint/agents/component/namespace.py | 59 ++ src/blueprint/agents/component/registry.py | 540 +++++++++-- .../eventing/event_publishing_service.py | 16 +- .../infrastructure/agent_scoped_cache.py | 157 ++++ .../infrastructure/cache_backend_factory.py | 125 ++- .../services/infrastructure/cache_service.py | 21 +- .../infrastructure/redis_cache_service.py | 6 +- src/blueprint/agents/services/service_base.py | 10 +- tests/unit/agents/app_builder/TESTS.md | 1 + .../app_builder/test_agent_registration.py | 217 +++++ .../agents/app_builder/test_named_caches.py | 155 ++++ .../app_builder/test_namespace_builder.py | 307 +++++++ tests/unit/agents/component/TESTS.md | 5 +- tests/unit/agents/component/test_component.py | 132 +++ tests/unit/agents/component/test_namespace.py | 47 + tests/unit/agents/component/test_registry.py | 274 +++++- tests/unit/agents/services/TESTS.md | 3 +- .../eventing/test_event_publishing_service.py | 83 +- .../infrastructure/test_agent_scoped_cache.py | 169 ++++ .../test_cache_backend_factory.py | 139 ++- .../test_cache_sharing_via_registry.py | 15 +- .../infrastructure/test_disk_cache_service.py | 32 + 28 files changed, 3827 insertions(+), 213 deletions(-) create mode 100644 src/blueprint/agents/services/infrastructure/agent_scoped_cache.py create mode 100644 tests/unit/agents/app_builder/test_agent_registration.py create mode 100644 tests/unit/agents/app_builder/test_named_caches.py create mode 100644 tests/unit/agents/app_builder/test_namespace_builder.py create mode 100644 tests/unit/agents/services/infrastructure/test_agent_scoped_cache.py diff --git a/docs/guides/deployment.md b/docs/guides/deployment.md index 0e8e1d34..e74bcb48 100644 --- a/docs/guides/deployment.md +++ b/docs/guides/deployment.md @@ -344,6 +344,62 @@ helm uninstall my-ai-service --namespace ai-services --- +### Writable Cache Directory + +The disk cache backend (`cache.backend = "disk"`, the default) writes to `cache.cache_dir`, which +defaults to the **relative** path `.cache/blueprint` -- resolved against the working directory, +so `/app/.cache/blueprint` in the generated image. It is created at startup, and a container can +only create it where the process user may write. + +Two things have to be true, and neither is automatic: + +1. **The directory belongs to the user the process runs as.** `WORKDIR /app` creates `/app` owned + by root, and the image runs as `appuser`, so `mkdir /app/.cache` fails with EACCES. The + generated Dockerfile therefore creates and hands it over at build time: + + ```dockerfile + RUN mkdir -p /app/.cache && chown -R appuser:appuser /app/.cache + ``` + + A project scaffolded before this was added needs the same two lines. + +2. **A read-only root filesystem needs a volume mounted there.** With + `readOnlyRootFilesystem: true` the ownership above is irrelevant -- nothing may be written + anywhere except a mounted volume, and the mount is declared in the pod spec rather than + discovered at runtime: + + ```yaml + spec: + containers: + - name: agent + securityContext: + readOnlyRootFilesystem: true + runAsNonRoot: true + volumeMounts: + - name: cache + mountPath: /app/.cache + volumes: + - name: cache + emptyDir: + sizeLimit: 1Gi + ``` + + Keep `sizeLimit` at or above `cache.size_limit` (default 1 GB): an `emptyDir` is backed by + node disk, and a pod that exceeds its limit is evicted. + +If the directory cannot be created the service fails at startup with a message naming the path +and these options, rather than an errno from inside a constructor. + +**Grouped agents need no additional paths.** Agents hosted in one process share one cache backend +and are isolated by key prefix, not by directory, so a group of five agents mounts the same single +volume a single agent does and keeps one `size_limit` budget over it. + +**Or avoid the filesystem entirely.** `cache.backend = "redis"` needs no writable path, which +makes it the simpler choice for a hardened pod, and the only choice if the cache has to survive a +restart or be shared across replicas -- an `emptyDir` is per pod and is deleted with it. + +--- + ## Health Probes Blueprint Agents provides three built-in health endpoints: diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 94655ce8..e705ab2c 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -1790,6 +1790,496 @@ the arguments uvicorn is handed, the two development differences, the level tran fallback, `reload=False`, and the worker refusal -- including that it happens before `uvicorn.run` is called at all. +### Phase 0, part 2 -- the namespace becomes ambient, so a developer never writes one + +The constraint this serves, stated by the user while phase 0 was in progress and now the test the +design is held to: **a developer using the blueprint should not have to care about namespaces at +all**, and a project should read the same whether it runs as a single agent or inside a group -- +with `main.py` the only file that may differ. + +Threading a namespace through constructors fails that immediately: every handler, service and +client would carry a parameter that exists only because of how it is deployed. So the namespace is +**ambient during construction** instead. + +`component/namespace.py` gains three things -- placed there rather than in `component.py` as the +plan said, because that module already declares itself the single definition of what a namespace +is, and the scope validates through `validate_namespace` two functions above it: + +- `_CURRENT_NAMESPACE`, a `ContextVar[str]` defaulting to `ROOT_NAMESPACE`. +- `current_namespace()`, read by `Component.__init__`. +- `namespace_scope(namespace)`, a context manager: validate, set, and reset in `finally`. A + leaked namespace would attach the next agent -- or the framework's own root components -- to the + wrong one, and the registry key, the queue group and the durable name would all be wrong + together, so the reset is not left to a caller to remember. Nested scopes restore the enclosing + namespace rather than the root, and the namespace is validated **on entry**, so an illegal name + is reported against the registration that declared it instead of against whichever component + happened to be built first. + +**`Component.__init__` now resolves `namespace or current_namespace()`**, and the direction of that +`or` is the whole change: + +```python +self._namespace = validate_namespace(namespace or current_namespace()) +``` + +The obvious reading -- an explicit argument wins over the ambient scope -- is wrong here, and +quietly so. `ServiceBase`, `ClientBase`, `IOClientBase` and `EventPublishingService` all declare +`namespace: str = ROOT_NAMESPACE` and forward it **unconditionally**, so a developer writing + +```python +class OrderService(ServiceBase): + def __init__(self) -> None: + super().__init__() +``` + +passes an explicit `""` down to `Component`. Treating that as a decision would pin every +developer-written component to the root and leave the ambient scope applying to nothing that +matters -- the exact components the constraint is about. A *non-empty* argument still wins, which +is what the framework's own namespace-owning components (the transport clients, the publishing +service) rely on. The alternative -- a `None` sentinel threaded through four base classes -- was +rejected: it changes four public signatures to express what one `or` expresses, and it would have +to be repeated by every base class added later. + +**Nothing changes for a single-agent application.** Outside a scope `current_namespace()` is +`ROOT_NAMESPACE`, so `namespace or current_namespace()` is `""` exactly as before, and +`qualified_component_name` keeps the bare registry name. The 1462 tests that passed before this +change still pass unmodified. + +**One limit worth stating.** A `ContextVar` is not inherited by another thread or task, so a +component constructed off the builder's thread does not see the scope. That is the correct shape +rather than a gap: construction happens synchronously inside the builder, and anything built +lazily at request time is a root component by construction, which is what the fallback gives it. + +**Tests.** 1476 unit tests pass (up from 1462), 14 new. `TestAmbientNamespace` in +`test_namespace.py` covers the default, setting, exit, exit **on exception**, nesting, +the root scope as a no-op and validation on entry. `TestNamespaceComesFromTheAmbientScope` in +`test_component.py` covers the part that matters: a `ServiceBase` subclass whose `__init__` takes +no namespace and calls bare `super().__init__()` comes out namespaced, the same class registers +under two different qualified names in two scopes, and an explicit non-empty namespace still wins. + +### Phase 0, part 3 -- one declaration, applied alone or once per agent + +Completes phase 0. `AgentRegistration` collects component *classes* and builds none of them; +`AppBuilder.with_registration(registration, namespace="")` is what builds them, inside +`namespace_scope`. Together with part 2 that satisfies the constraint end to end: a project +declares its components once, and the same object serves both deployment shapes. + +```python +registration = AgentRegistration().with_service(OrderService).with_handler(OrderHandler) + +app = AppBuilder(config).with_registration(registration).with_cache().build() # alone +# a group applies the same object once per agent, under that agent's namespace +``` + +Verified rather than asserted: applying one registration under `orders` and again under +`billing` produces `orders_order_service` and `billing_order_service`, each resolving its own +`app_name` and `model_name` through its own scoped `Config` view -- with the word "namespace" +appearing nowhere in `OrderService` or in the declaration. + +**`with_registration` is new public API that the spec does not list.** Spec sec. 4.2 has only +`with_namespace(..., registration=...)`, which is phase 3. Added now because without a caller +`AgentRegistration` would be a collector nothing could consume for three phases, which is worse +than an extra method: it is a published API that does not work yet. It is also the exact call +phase 8's entry point needs per agent, so phase 3 narrows the gap rather than replacing this. + +**An already-built component is refused, and this is the part that would otherwise bite.** Four +of the five examples pass instances today -- `with_rest_api(MonitorApi())`, +`with_agent(agent)` -- which an `AppBuilder` chain accepts. In a registration that object is +constructed at import time, *before any namespace exists*, so it belongs to the root whichever +agent declared it; two grouped agents each declaring one would collide on its registry name, and +until they collided the misattribution would be silent. `_add` raises `TypeError` on any +`Component` instance, and the message names the class, the method and the fix. + +**Factories are accepted for the case a class cannot express.** `examples/document_summarizer` +builds its agent as `AgentBuilder(config, runtime_name=...).with_model_from_config()...build()` +-- a fluent chain, not a class plus keyword arguments. A zero-argument callable is therefore a +legal target, called *inside* the scope, so the model and prompt resolve in the agent's own +namespace instead of at import time. `apply` distinguishes the two: + +```python +target = entry.target if isinstance(entry.target, type) else entry.target() +appliers[entry.kind](target, name=entry.name, **entry.kwargs) +``` + +A class is handed to the builder, which instantiates it -- still inside the scope. A factory has +to be called here, because the builder would otherwise take the callable itself for a built +component. + +**`apply` is public, departing from the plan's `_apply`.** It is called from another class, and +this repo's convention is that a leading underscore means internal to the defining class. + +**There is no `with_cache`,** per spec sec. 4.1: a cache is process-wide and belongs to the +`AppBuilder` hosting the group. An agent that declared its own would duplicate a neighbour's or +quietly take it over. `AttributeError` plus the class docstring is the whole of that story -- a +method existing only to raise seemed worse than one not existing. + +`RegisteredComponent` is a frozen dataclass (`kind`, `target`, `name`, `kwargs`) and +`AgentRegistration.components` exposes the tuple in declaration order. Order is preserved +because it is meaningful -- handler priority and scheduler wiring read it -- and the tuple is +what phase 8 will validate against `agents.toml` and what spec sec. 9.2's startup log needs. + +**Tests.** 1498 unit tests pass (up from 1476), 22 new in +`tests/unit/agents/app_builder/test_agent_registration.py`: nothing is constructed at +declaration time (asserted through `Component.shared_registry` still being `None`), order and +kwargs survive the round trip, the instance and non-callable refusals, root application keeping +the bare registry name, one declaration becoming two independently configured agents, the scope +being left behind afterwards, and a factory both deferred and called inside the namespace. + +**Not done, and the obvious next proof:** no example uses this yet. Migrating one project's +`main.py` to a registration would demonstrate the "only `main.py` differs" claim in the tree +rather than in a test -- and would have to convert its `with_rest_api(MonitorApi())` to the +class form, which is precisely the change the refusal above forces. + +### Phase 1, part 1 -- the registry resolves per namespace, without a namespace dimension + +Every lookup on `Registry` now takes an optional `namespace`, so two agents can own the same +component class in one process and each find its own. Verified: `orders` and `billing` both +declaring `OrderService` produce `orders_order_service` and `billing_order_service`, each +resolvable as the bare `order_service` from its own namespace, with a root-registered +`shared_audit` inherited by both. + +**The storage was not changed, and the plan's `dict[str, dict[str, Any]]` is not what this +needs.** The plan predates P6, which made every registry name namespace-qualified +(`qualified_component_name`). With qualified names, a namespace → name → component nesting +duplicates the namespace in the outer key and the inner name at once, and either the inner key is +the qualified name -- in which case the outer level carries no information -- or it is the bare +name, in which case `get_component("orders_order_service")` stops resolving and every existing +lookup, health-check entry and log line that uses `Component.name` breaks. So the namespace +dimension the plan asked for is already present in the key space, and what was missing was only +the ability to *ask* through it. + +Two kinds of question, and they resolve differently on purpose: + +- **"Find me the one X"** -- `get_component`, `get_service`, `get_scheduler`, `get_client`, + `get_agent` -- resolves **namespace first, then root**, because infrastructure stays shared + while an agent overrides what it owns. For a name that is `_lookup`, a new private helper that + tries `_` before ``; for a class it is `resolve_for_namespace`, which + P6 already wrote for this and whose docstring said it would become the registry's + implementation when the registry grew a namespace. It now is. +- **"Give me all the Xs"** -- `get_components_by_type`, `get_services`, `get_schedulers`, + `get_rest_apis`, `get_clients`, `get_event_handler` -- filters to **that namespace exactly**, + since iterating one agent's components must not sweep in a neighbour's. + +**`namespace=None` is the default and means every namespace, not the root** -- a departure from +the plan's `namespace: str = ""`. With `""` as the default, `build()` calling +`get_event_handler()` would have quietly seen only root handlers: correct on a single-agent +application, and silently short-staffed on a grouped one, which is the worst possible shape for +a default. `None` keeps today's behaviour exactly, so every existing caller is unaffected. + +Filtering is on the component's own `namespace` attribute, not on its registry name. An explicit +`name=` overrides the qualified name (documented on `Component.__init__`, used by +`AIClientBase`), so a name-based filter would lose exactly those components. + +**Ambiguity raises rather than picking a first match.** A class lookup with a namespace goes +through `resolve_for_namespace`, which refuses two candidates at the same level; without a +namespace the pre-existing "Multiple components of type X found" applies. Silently handing an +agent a neighbour's collaborator is the attribution the whole topology exists to provide. + +**`get_known_namespaces()` was NOT added, because C6 forbids it.** The plan asks for it so +`NatsEventing` and `build()` can iterate namespaces. But C6 says no API reachable from agent code +may expose the group's membership or size, and `Component.registry` is a public property on every +component -- so a `get_known_namespaces()` here is precisely the API C6 rules out, reachable by +`self.registry.get_known_namespaces()` from any handler. The builder already knows the group +composition, because it was told: it passes each namespace to the wiring that needs one, which is +also the layering the plan argues for elsewhere ("`AppBuilder` must remain a pure function of its +call sequence"). A test asserts the method does not exist, so it cannot be added back without the +reason being read. + +**Tests.** 1514 unit tests pass (up from 1498), 16 new in `test_registry.py` +(`TestNamespacedNameLookup`, `TestNamespacedTypeLookup`, `TestC6`): the fallback in both +directions, an already-qualified name still resolving, a bare name *not* resolving without a +namespace, the error naming where it looked, `None` returning every namespace, filtering by +attribute rather than name, ambiguity refused both across and within a namespace, and the absence +of `get_known_namespaces`. + +Still to do in phase 1: named caches (spec sec. 8) and the per-namespace executor. Note that the +executor has its own plan-versus-spec conflict to settle -- the plan provisions the root executor +eagerly in `build()`, while spec sec. 4.3 requires it to be created **lazily on first access**, so +that an application which never performs blocking work spawns no threads. + +### Phase 1, part 2 -- caches are looked up by name, and never substituted for one another + +`_cache_service: CacheService | None` became `_caches: dict[str, CacheService]`, with +`add_cache(name, cache)`, `get_cache(name="default")`, `has_cache(name="default")` and +`get_all_caches()`. `DEFAULT_CACHE_NAME = "default"` names the one every existing application +has, and `registry.cache_service` -- getter and setter -- is retained as an alias for it, which +spec sec. 8 requires. Every existing caller (`with_cache`, `HandlerChain`, the scheduler tick +claim, the cache management endpoints, the health check) reads the alias and is untouched. + +**`get_cache` has no fallback to the default cache, deliberately.** Spec sec. 8: two +independently written agents both asking for `"sessions"` must not silently share one store the +moment they are grouped. A missing name is therefore an error naming what *is* registered, not +an invitation to hand over some other cache. This is the opposite of how components resolve -- +where namespace-then-root is right, because infrastructure is shared on purpose -- and the two +sit next to each other in the same class, so the module docstring and both docstrings say which +is which and why. + +**One behaviour change: registering a second cache under one name now replaces it and warns, +where the setter used to raise.** The plan asks for an upsert so a cache can be added after +startup, and an alias for `add_cache` cannot be stricter than the method it aliases. Replacing +silently would be worse than either, because the usual way to arrive twice at `"default"` is two +calls to `with_cache()` -- so it logs at WARNING with both backend types named. Two tests +asserted the old raise and were rewritten to assert the new behaviour; +`test_cache_sharing_via_registry.py` now protects the invariant that actually matters -- both +services still resolve one object, and `get_all_caches()` still has exactly one entry. + +`clear()` clears and drops every cache rather than the single one. + +`get_or_create_cache` from the plan was **not** written. It is specified as "atomic get-or-create +protected by an `asyncio.Lock`", but every registry method here is synchronous and every cache is +registered during `build()`, before a loop exists -- a lock that cannot be awaited protects +nothing, and nothing in the framework creates a cache lazily for it to protect. When something +does, it can be added with a mechanism that matches how it is actually called. + +### Phase 1, part 3 -- one thread pool per agent, and only if something needs one + +`Registry.get_or_create_executor(namespace, max_workers)` returns a namespace's +`ThreadPoolExecutor`, creating it on first use; `Component.executor` is the property a component +reaches it through: + +```python + @cached_property + def executor(self) -> ThreadPoolExecutor: + return self.registry.get_or_create_executor(self._namespace, self.config.get("executor_workers")) +``` + +One pool per namespace, so an agent doing blocking work -- DiskCache, SQLite, a synchronous SDK +-- cannot exhaust the pool another agent is waiting on. Threads are named +`blueprint-_N`, so a stack dump says which agent a blocked thread belongs to. + +**Created on first access, not provisioned in `build()`, which is a departure from the plan and +required by spec sec. 4.3.** The plan says "the root executor is provisioned in +`AppBuilder.build()` (not in `with_namespace`) so standalone apps always have one". That would +add `cpu_count() + 4` idle threads to every application that has no blocking work at all -- +including every single-agent application that exists today -- and works directly against the +thread budget in #36. Verified: with nothing asking, the process has one thread and +`_executors` is empty. + +**The plan's root fallback is subsumed rather than implemented.** `get_executor` was to fall back +to the root when a namespace had no pool; with creation on demand a namespace can never be +missing one, so that branch could never be taken. For the same reason there is no `add_executor`: +nothing needs to hand a pool in. + +**Sizing is per namespace, and the first asker wins.** `executor_workers` is read through +`Component.config`, which is the namespace's scoped view (C5), so one agent can be sized +differently from its neighbour. A live pool cannot be resized, so a later component of the same +namespace passing a different value is ignored rather than raising -- failing an application over +a number nobody chose deliberately would be worse than using the first one. + +**The pools are shut down with the application.** `Registry.shutdown_executors()` waits for +running work and clears the map, and it is called at the very end of the lifespan shutdown -- +after every `on_shutdown`, because a component may well run its last blocking call there -- and +from `Registry.clear()`, so a test suite building many applications does not accumulate pools. +This is not optional tidiness: a `ThreadPoolExecutor`'s workers are non-daemon threads, so +leaving them running keeps the interpreter alive past the point the container was asked to stop. + +No public read accessor for the executors was added; nothing in `src/` needs one, and the two +tests that check the map is empty read the private attribute rather than growing the API for +their own convenience. + +**Tests.** 1538 unit tests pass (up from 1514), 24 new. `TestNamedCaches` (11) covers lookup by +name, the absence of a fallback, the error listing what is registered, the alias in both +directions, `get_all_caches` returning a copy, and `clear` clearing every cache. +`TestExecutors` (9) covers nothing existing until asked, creation then reuse, isolation between +namespaces, sizing on the creating call and being ignored afterwards, thread naming, and +shutdown from both entry points. `TestExecutorBelongsToTheNamespace` (5) covers the component +side: its own namespace's pool, two agents not sharing, two components of one agent sharing, and +sizing from the scoped configuration. + +**Phase 1 is complete.** `Component.executor` belongs to spec sec. 4.3 rather than to phase 1 +strictly, and was written here because the registry half is unreachable without it -- an +executor store with no way to reach it is the unused surface this repo keeps out. + +### Phase 2 -- a component's registry answers for its own agent + +Phase 2 is titled "component namespace awareness", and three of its four bullets were already +satisfied by earlier work: the `ContextVar` and `Component.__init__` reading it landed in phase 0 +part 2, `Component.executor` in phase 1 part 3, and `shared_registry` was never going to stop +being a class-level singleton. Its fourth -- passing `namespace=` to `add_component` -- is +obsolete: phase 1 kept the flat store precisely because P6 had already made the registry name +namespace-qualified, so the namespace is in the key. + +What was actually missing is the half phase 1 enabled and nothing used. Every lookup on `Registry` +took a `namespace`, and **no caller passed one**, so a grouped process would have resolved +collaborators at random or refused to choose. Two examples from the framework's own code, both +written long before namespaces: + +```python +self._client = self.registry.get_component(NATSClient) # io/api/eventing/nats.py:33 +handlers = sorted(self.registry.get_event_handler()) # handler/handler_chain.py:130 +``` + +With one transport client per namespace (P6) the first raises "Multiple components of type +NATSClient found" the moment a second agent joins the process, and the second dispatches one +agent's event to another agent's handlers. Neither call site may grow a namespace argument, +because the constraint is that no code names a namespace unless it is about namespaces. + +**`Registry.for_namespace(namespace)` returns a view, and `Component.registry` hands each +component its own.** The mechanism is the one `Config.for_namespace` established in the config +rework, deliberately: a shallow `copy` sharing `_components`, `_caches` and `_executors` by +reference -- one registry per process, a view is a lens on it -- differing only in what an +*omitted* `namespace` argument means. + +```python + def _effective_namespace(self, namespace: str | None) -> str | None: + return self._default_namespace if namespace is None else namespace +``` + +- On the application's registry, an omitted namespace still means **every namespace**, so + `build()` and the lifespan keep iterating everything. Nothing about a single-agent application + changes; `for_namespace("")` returns the registry itself, as `Config.for_namespace("")` does. +- On a view it means **that agent**, so `self.registry.get_service(OrderService)` resolves this + agent's service, and `self.registry.get_service(EventProcessingService)` still finds the shared + root one through the namespace-then-root fallback. +- An explicit argument wins on either. + +**Calling `for_namespace` on a view raises**, as on `Config`: a view is one agent's lens, and +letting it mint another agent's would hand every component a route to its neighbours, which is +what C6 forbids. + +Verified with a service written the way a project writes one -- no namespace anywhere in it: + +``` + orders self.registry.get_service(OrderService) -> orders_order_service Audit -> audit + billing self.registry.get_service(OrderService) -> billing_order_service Audit -> audit +``` + +One declaration, two agents, each wiring itself correctly, plus a root-registered `Audit` shared +by both. + +**A hand-rolled resolution was deleted.** `EventPublishingService.on_startup` called +`resolve_for_namespace(self.registry.get_io_clients(), self.namespace, ...)` by hand, because P6 +needed namespace resolution before the registry could do it. It is now +`self.registry.get_io_client(IOClientBase)` -- the view resolves it -- which is what P6's own +changelog predicted would happen to that helper. + +**A bug the test rewrite caught, worth recording because the shape recurs.** `get_component` +gathered its candidates with `self.get_components_by_type(name_or_class, None)`, passing `None` +to mean "every namespace". On a *view* `None` means *this* namespace, so the resolver was handed +only the asking agent's components and its root fallback could never fire: a namespaced service +in a process with one shared root transport failed to find it. Fixed with `_all_of_type`, a +namespace-blind helper used by the two callers that must not have their argument reinterpreted +-- the class-resolution path and the message that lists candidates when it cannot choose. The +six `EventPublishingService` ownership tests were rewritten from a `MagicMock` registry onto a +**real** one for exactly this reason: the mock version asserted that a stub returned what it was +told to, and would not have caught this. + +While there, the class-lookup failure message stopped printing a class repr: +"No IOClientBase is registered for namespace 'orders' or at the root" rather than +"No is registered ...". + +**Tests.** 1554 unit tests pass (up from 1538). `TestNamespaceViews` (12) covers the root +identity, caching, the shared store, the C6 refusal, omitted-means-this-agent, the root fallback +for both name and class lookups, plural lookups returning one agent, an explicit override, and +the application registry still seeing everything. `TestRegistryIsScopedToTheComponent` (4) covers +the component side. The six rewritten ownership tests now exercise the real resolution. + +### Still open after phase 2: cache names are not namespace-scoped yet + +Spec sec. 8 requires cache *names* to be namespace-scoped by default, with an explicit opt-in for +genuinely shared caches, so that two agents both asking for `"sessions"` do not silently share a +store. Phase 1 gave the registry the name dimension that policy needs, and phase 2 gave every +component a namespace-aware view -- but `get_cache` on a view still resolves the bare name, so +the policy is not enforced. + +It is left open rather than guessed at because the obvious implementation collides with something +that already exists: `CacheService.get/set/delete` take their own `namespace=` argument, which is +a *partition inside* a cache and is what a project already uses (`CACHE_NAMESPACE` in two +examples). So there are two plausible designs and they are not equivalent -- qualify the cache +*name* on the way in (`orders_sessions`, one backend per agent per name), or prefix the +*partition* the agent's calls land in (one backend, agent-scoped keys). The first isolates +storage and multiplies backends; the second keeps one backend and has to compose with the +developer's own partition argument without either silently winning. That is a decision, not an +implementation detail. + +### Cache names become namespace-scoped (spec sec. 8), and the pod filesystem decides how + +Sec. 8's requirement -- two independently written agents both asking for `"sessions"` must not +silently share a store once grouped -- had two plausible implementations, and the deployment +constraint settled it rather than taste. + +**The constraint.** A pod may write only where its process user is allowed to, and under +`readOnlyRootFilesystem: true` only where a volume is mounted -- a mount declared in the pod spec, +not discovered at runtime. `DiskCacheService` is a directory; `RedisCacheService` is a connection. +So the design that registers **one cache backend per agent per name** multiplies the writable +paths a group needs, gives each agent its own `size_limit` over one node-backed `emptyDir` (five +agents at the 1 GB default is 5 GB against one volume, and an `emptyDir` over its limit evicts the +pod), and turns "add an agent to this group" into a change to the pod spec. The design that +**prefixes the partition** needs no new path at all. + +**So the partition carries the agent.** New `services/infrastructure/agent_scoped_cache.py`: +`AgentScopedCache` wraps one shared backend and prefixes every call's `namespace` argument with +the agent, so `orders` writing `"prices"` lands in `orders.prices` and `billing` writing the same +name lands in `billing.prices`. One directory, one connection, one budget, whatever the group +size. + +`Registry.get_cache` (and the `cache_service` alias) returns that lens **when asked through a +namespace view**, and the raw backend at the root -- which is unchanged behaviour for every +single-agent application, and is also sec. 8's "explicit opt-in for genuinely shared caches": +framework code holding `Component.shared_registry` gets the shared store. The lens is cached per +name per view. Nothing at a call site changes: a service writing +`self.registry.cache_service.set(key, value, namespace="prices")` is isolated without naming a +namespace, because phase 2 already gave it a namespace-aware registry. + +The separator is `.`, not `:`: `:` already separates the partition from the hashed key +(`cache_key_mixin._make_key`) and `list_namespaces` splits on the first one, so `orders:prices` +would read back as the partition `orders`. A namespace cannot contain `.`, so stripping +`.` back off is unambiguous whatever the agent called its own partition. + +Three methods needed more than a prefix: + +- **`clear(None)` means this agent's partitions, never the whole cache.** The backend's own + `clear(None)` would take the neighbours' data with it -- the exact accident this class exists to + prevent -- so the lens enumerates the partitions it owns and clears those. +- **`list_namespaces()`** returns this agent's partitions with the prefix stripped, so an agent + sees the names it used. +- **`close()` raises.** The backend belongs to the process; closing it from one agent's lens would + take every other agent's cache down with it, silently. + +`get_stats()` forwards the backend's numbers and adds the agent's name: size, hits and eviction +are properties of the one shared store, and there is nothing per-agent to report. + +`ServiceBase.__init__` gained a keyword-only `should_register: bool = True`. `CacheService` is a +`ServiceBase`, so the lens is a component by inheritance, and one per agent per cache would +otherwise add a registry entry each. `RestApiBase` has taken the same parameter since before +namespaces, so this is the existing pattern rather than a new one. + +### The same constraint exposed a pre-existing defect: the disk cache cannot create its directory + +Read from the generated Dockerfile rather than observed in a cluster, and independent of grouping: + +- `cache.cache_dir` defaults to the **relative** `.cache/blueprint`, resolved against the working + directory, so `/app/.cache/blueprint` in the image. +- `DiskCacheService.__init__` creates it at **runtime** (`mkdir(parents=True, exist_ok=True)`). +- The image does `WORKDIR /app` **before** `USER appuser`, so `/app` is root-owned, and only + `src/` and `settings.toml` are `--chown`ed. Creating `/app/.cache` as `appuser` therefore fails + with EACCES. + +So a container built from the generated Dockerfile, running as the user it declares, with the +default cache backend, cannot start. It has not been noticed because tests and local runs have a +writable working directory. Three changes: + +- **The image creates the directory and hands it over**: + `RUN mkdir -p /app/.cache && chown -R appuser:appuser /app/.cache`. A project scaffolded before + this needs the same two lines. +- **The failure explains itself.** The `mkdir` is wrapped, and an `OSError` becomes a + `RuntimeError` naming the path and the four ways out -- create and chown it in the image, mount + a volume if the root filesystem is read-only, point `cache.cache_dir` somewhere writable, or use + the redis backend, which needs no filesystem. The original error is kept as `__cause__`. +- **`docs/guides/deployment.md` gained "Writable Cache Directory"**: the ownership requirement, + the `readOnlyRootFilesystem` + `emptyDir` manifest with `sizeLimit` matched to + `cache.size_limit`, the note that a grouped process needs no additional paths, and redis as the + filesystem-free alternative. + +**Tests.** 1577 unit tests pass (up from 1554). 21 new in `test_agent_scoped_cache.py`, against a +**real** `DiskCacheService` rather than a mock, since what is under test is which keys end up +where: isolation of values, absence rather than a neighbour's value, one backend, the partition +carrying the agent, per-agent `list_namespaces`, the scoped default partition, per-agent `delete` +and `claim` (two schedulers must not steal each other's tick slots), both `clear` shapes, the +`close` refusal, the root-namespace refusal, not registering itself, and the six paths through the +registry. Two more in `test_disk_cache_service.py` cover the unwritable directory: the message +names the path and the options, and the original `PermissionError` survives as the cause. + ### Not fixed, found while doing this: `app_environment` in `[default]` selects nothing The bootstrap pass runs with `environments=False`, so it sees only top-level keys -- `[default]` @@ -1824,6 +2314,321 @@ mechanism whenever real implementation lands, with lint, typing, tests and docs **Motivation.** The feature is delivered across many sessions and unreviewed batches are expensive to unpick. +### Phase 3, part 1 -- a namespace can be named at the call site, and a group can be written by hand + +Phase 0 part 3 made the namespace ambient, and phase 1 and 2 made the registry answer per +namespace. What was still missing is the *entry point*: nothing outside `AgentRegistration.apply` +could put a component in a namespace, and there was no way to assemble a group at all. This step +adds the three builder-side pieces of phase 3; `with_cache(name=...)` follows as part 2. + +**The five `with_*` methods take a keyword-only `namespace`, and it never reaches the component.** +Their bodies were five copies of "build it if it is a class, adopt it if it is not, rename it if +asked", so they now share one helper and differ only in the type check `with_handler` performs: + +```python + def with_handler( + self, handler: type[HandlerT] | HandlerT, *, name: str | None = None, namespace: str = ROOT_NAMESPACE, **kwargs: Any + ) -> "AppBuilder": + if isinstance(handler, type) and not issubclass(handler, EventHandlerBase): + raise TypeError(f"Expected EventHandlerBase subclass, got {handler.__name__}") + self._register(handler, namespace, kwargs, name=name, method="with_handler") + return self +``` + +`AppBuilder._register` is where the namespace is turned into a scope rather than an argument: + +```python + if isinstance(target, type): + with _construction_scope(namespace): + instance = target(**kwargs) +``` + +This is the point of the whole ambient mechanism, and it is why the parameter cannot simply be +forwarded. The builder passes `**kwargs` straight to the constructor, and a project's component +takes the arguments its author wrote -- `StrictService(retries=3)`, no namespace anywhere -- so +`with_service(StrictService, namespace="orders", retries=3)` must construct +`StrictService(retries=3)` *inside* namespace `orders` and let `Component.__init__` read the +namespace from the context variable. Forwarding it would be a `TypeError` on every component a +developer has ever written. + +**`_construction_scope` exists because `namespace_scope("")` is not a no-op** -- it *sets* the +current namespace to the root: + +```python +@contextmanager +def _construction_scope(namespace: str) -> Iterator[None]: + if not namespace: + yield + return + with namespace_scope(namespace): + yield +``` + +Without that branch this step would have broken the mechanism it is extending. +`AgentRegistration.apply` opens one `namespace_scope("orders")` and then calls +`builder.with_service(target, name=...)` with no namespace argument -- so an unconditional +`namespace_scope(namespace)` would reset every component of every agent back to the root, with no +error, and every registration applied per agent would have produced a root component. There is a +test for exactly this (`test_the_default_does_not_reset_an_ambient_namespace`), because the failure +is invisible: the app builds, and the registry keys are simply wrong. + +**An explicit `name=` is now qualified with the namespace the component ended up in:** + +```python + if name is not None: + instance.name = qualified_component_name(namespace_of(instance), name) +``` + +A defect, not a refinement. `Component.__init__` qualifies a *derived* name but uses an explicit +one verbatim, so `AgentRegistration().with_service(OrderService, name="db")` applied to two agents +registered both as `db` and the second failed with "Component with name db already exists" -- the +one-declaration-per-group case, which is the primary API. Qualifying costs the caller nothing: +`Registry._lookup` tries `_` before ``, so `get_component("db")` from +inside the agent still finds it. `namespace_of(instance)` rather than the `namespace` argument, +because the instance may have come from the ambient scope instead. + +**An already-built instance offered to a namespace is refused rather than silently rerouted.** +A component's namespace and its registry key are fixed by the scope it was constructed in, so +`with_service(instance, namespace="orders")` cannot do what it says: + +```python + built_in = namespace_of(target) + if namespace and built_in != namespace: + raise ValueError( + f"{type(target).__name__} was passed to {method}() as an instance for namespace '{namespace}', " + f"but it was already built in namespace '{built_in or ROOT_LABEL}', and a component cannot change " + ... + ) +``` + +Ignoring the argument would register the component at the root while the caller believed it +belonged to an agent -- the same trap `AgentRegistration._add` already refuses instances for, and +the message points the same way: pass the class. An instance built inside the matching scope is +accepted, since nothing is being changed. + +**`NamespaceBuilder` is one agent's view of the builder**, and it holds no build state: five +`with_*` that delegate with `namespace=` filled in, `with_registration`, and `end()` returning the +parent. Registering a component therefore still has exactly one implementation, and this class only +decides which namespace it goes to. It has no `with_cache` -- a cache is process-wide (spec sec. 8), +and an agent registering its own would duplicate or quietly take over a neighbour's. + +**`AppBuilder.with_namespace(name, *, registration=None)`** is the entry point: + +```python + namespace = validate_namespace(name) + if not namespace: + raise ValueError("with_namespace('') names no agent: ...") + if namespace not in self._namespaces: + self._namespaces.append(namespace) + logger.info("Hosting agent namespace '%s'", namespace) + if registration is None: + return NamespaceBuilder(self, namespace) + return self.with_registration(registration, namespace) +``` + +`with_namespace("")` is refused: the root is the absence of an agent, and returning a block that +registers into it would be a silent no-op dressed as a declaration. The namespace is recorded +*before* anything is built, so a registration that fails half way through still leaves the agent +declared -- the startup log (spec sec. 9.2) and the readiness policy have to be able to say an +agent was meant to be here. + +**Two spec departures, both argued rather than assumed.** + +- **The `AppBuilder | NamespaceBuilder` union is kept, but no caller sees it.** Spec sec. 4.2 + types `with_namespace` as returning the union, which would make every call site narrow a type + it already knows statically. Two `@overload`s resolve it instead: `registration=` is an `AppBuilder`, `registration` omitted is a `NamespaceBuilder`. The runtime + behaviour is exactly what the spec asks for; the union survives only as the implementation + signature. +- **The `config: Config | None` parameter is not accepted.** Spec sec. 4.2 and the plan both list + it, and the plan says `with_namespace` should build a `Config` with `agent_scope=name` from the + root config's settings files. Config rework step 2 made that obsolete: `Config.for_namespace` + returns a view sharing the one loaded tree, and `Component.config` already hands each component + the view for its own namespace, which tries `.` before `` (C5). A `Config` + passed here would have no reader -- components do not consult the builder -- so it would be + either ignored outright or re-parse the same files once per agent and then be ignored. Accepting + a parameter that does nothing is worse than not having it: it reads as per-agent configuration + support that is not there. **Needs a spec amendment**; listed under *Open points*. + +**`AppBuilder.namespaces`** exposes the declared agents in declaration order, root excluded, so +phase 6 can iterate them. It lives on the builder because it may not live on the registry: +`Registry` is reachable from every component (C6), so a `get_known_namespaces()` there would let +an agent enumerate its neighbours, and grouping is supposed to be invisible from inside. The +builder is the object that was *told* which agents to host and is not reachable from a component. +A tagged `with_service(X, namespace="orders")` deliberately does *not* record a namespace: the +list is what the builder was told to host, not every namespace a component was tagged with. + +`NamespaceBuilder` is exported from `blueprint.agents`, since it is a return type callers can hold. + +Tests: `tests/unit/agents/app_builder/test_namespace_builder.py`, 36 cases -- the namespace +qualifying the registry key and reaching the component; the constructor *not* receiving it; the +ambient namespace surviving the default and being overridden by an explicit one; an explicit name +qualified, unchanged at the root, and one declaration with an explicit name serving two agents; an +instance refused for another namespace and accepted for its own; both `with_namespace` forms; the +root and an illegal namespace refused; `namespaces` order, dedup and its indifference to tagged +calls; and the block delegating, chaining, closing and carrying constructor arguments. + +### Phase 3, part 2 -- a cache has a name, and a name buys it its own store + +Phase 1 part 2 gave the registry `add_cache(name, cache)` / `get_cache(name)` and no fallback +between names. The builder never used any of it: `with_cache()` still went through the +`cache_service` setter, so a process could hold exactly one cache. This step is the builder side, +and three defects had to be fixed for it to work at all. + +**The signature change, and why the parameter order is the whole point:** + +```python + def with_cache(self, enabled: bool = True, enable_locking: bool = True, *, name: str = DEFAULT_CACHE_NAME) -> "AppBuilder": + if not enabled: + logger.info("Caching disabled; cache '%s' is not registered", name) + return self + + cache_config = _cache_config_for(self._config.get_cache_config(), name) +``` + +`name` is keyword-only and follows the two existing positional parameters, as spec sec. 4.2 +requires. Had it come first, `with_cache(False)` -- which *disables* caching in projects that +exist today -- would have become a cache named `False` with caching silently switched on, no +`TypeError` and no warning. `with_cache()`, `with_cache(False)` and `with_cache(True, False)` all +still mean exactly what they meant, and there are tests for the three of them. + +**Turning a name into isolated storage lives in `CacheBackendFactory`, not in the builder.** +It was written in `app_builder.py` first and moved on review, and the review was right: the +builder would have been the one place that knew disk caches isolate by directory and Redis caches +by key prefix. Anyone adding a third backend edits the factory and has no reason to open the +builder, so their backend would have inherited one store shared across every name -- the exact +failure the scoping exists to prevent, arrived at by writing new code in the obvious place. So +`create` takes the cache name and each `_create_*` scopes what its own backend needs: + +```python + @staticmethod + def create(config: CacheConfig, enable_locking: bool = True, name: str = DEFAULT_CACHE_NAME) -> CacheService: + CacheBackendFactory._validate_name(name) + if config.backend == "redis": + return CacheBackendFactory._create_redis(config, enable_locking, name) + return CacheBackendFactory._create_disk(config, enable_locking, name) +``` + +`create` is the single door through which a cache is built, so the name cannot arrive +unvalidated and a backend cannot be reached without having answered how it separates one name +from another. The builder is left with one line and no cache knowledge: + +```python + cache_service = CacheBackendFactory.create(self._config.get_cache_config(), enable_locking=enable_locking, name=name) +``` + +`config` reaches the factory **unscoped**. That matters for the fallback: `_create_redis` scopes +a key prefix, and when Redis is unreachable it hands `_create_disk` the original config plus the +name, so the fallback isolates by directory rather than carrying a prefix that means nothing to +it. Pre-scoping both fields before the branch -- what the first version did -- only worked because +it scoped fields no chosen backend would read. + +The two derivations, each on the backend that needs it. The default name returns the configured +value untouched, so an existing application's cache directory and Redis keyspace do not move: + +```python + def _scoped_cache_dir(config: CacheConfig, name: str) -> str: + if name == DEFAULT_CACHE_NAME: + return config.cache_dir + return str(PurePosixPath(config.cache_dir.replace("\\", "/")) / name) + + def _scoped_key_prefix(config: CacheConfig, name: str) -> str: + if name == DEFAULT_CACHE_NAME: + return config.key_prefix + return f"{config.key_prefix}:{name}" if config.key_prefix else name +``` + +- **Disk: `/`, a subdirectory and not a sibling.** The plan says + `{base_dir}/{name}` without saying which directory `base_dir` is, and only one reading is always + writable: a deployment may mount its volume *at* `cache.cache_dir`, and under + `readOnlyRootFilesystem` a sibling of the mount cannot be created -- see "Writable Cache + Directory" in `docs/guides/deployment.md`. The cost is that a named cache's directory sits + inside the default cache's own store. diskcache ignores directories it did not create, and the + alternative fails in production only. +- **Redis: the name is appended to `cache.key_prefix`.** *Not in the plan, and without it naming a + cache would have isolated nothing on Redis.* The disk backend separates caches by directory and + Redis has no analogue -- `RedisCacheService` scopes every key by `key_prefix` alone -- so two + caches registered as `sessions` and `prompts` against one Redis with one configured prefix would + have written the same keys. That is precisely the silent cross-cache sharing spec sec. 8 exists + to prevent, and here the name is the only thing meant to tell them apart. + +**The cache name is validated, because it is now a filesystem path segment:** + +```python +_ALLOWED_CACHE_NAME = re.compile(r"\A[a-z0-9][a-z0-9_.-]*\Z") +``` + +`with_cache(name="../evil")` would otherwise write outside the cache directory entirely. Lower +case only, and that is not tidiness: a directory whose name differs only by case is one directory +on a developer's macOS or Windows machine and two on the Linux node, so `Sessions` and `sessions` +would be one cache locally and two in production. Validation runs before anything is constructed, +so a refused name never creates a directory. + +**Three defects fixed to get here.** + +1. **Two caches collided on one registry name.** A `CacheService` is a `ServiceBase` and therefore + a `Component`, so it registers itself under a derived name -- and a second `DiskCacheService` + raised `Component with name disk_cache_service already exists`. Registering a named cache + without a component entry was not an option: the lifespan closes caches by iterating + `registry.get_services()`, so an unregistered one would leak its file handle or Redis + connection for the life of the process. `DiskCacheService.__init__` and + `RedisCacheService.__init__` therefore take `component_name`, forwarded to + `super().__init__(name=...)`, and `CacheBackendFactory.create` passes it through: + + ```python + @staticmethod + def _component_name(name: str) -> str | None: + return None if name == DEFAULT_CACHE_NAME else f"cache_{name}" + ``` + + `None` for the default, so `disk_cache_service` stays the key existing lookups and health + entries already use. `cache_` rather than `_` because `fallback_to_local` + swaps `RedisCacheService` for `DiskCacheService` at construction -- a registry key that depends + on whether Redis answered the startup ping is worse than one that does not name the backend. + Both fallback paths therefore produce the same registry name as the Redis service would have. + +2. **`with_cache()` as an application's first builder call crashed.** `Component.shared_registry` + is `None` until the first `Component.__init__` creates it, and a cache service is what creates + it here. Reading the registry before building the service is an `AttributeError` on `None`; the + old code happened to read it afterwards. The order is now explicit and commented, because + nothing about the line says it matters: + + ```python + cache_service = CacheBackendFactory.create(cache_config, enable_locking=enable_locking, component_name=component_name) + registry: Registry = Component.shared_registry # type: ignore[assignment] + registry.add_cache(name, cache_service) + ``` + +3. **`registry.add_cache` replaced the `cache_service` setter.** The setter still exists as the + spec sec. 8 alias and still reads and writes the `"default"` cache, so `registry.cache_service` + keeps working; the builder simply no longer goes through it. + +`CacheBackendFactory.create`'s third parameter is `name`, not `component_name`: the registry name +is derived from the cache name, so there is one name to pass rather than two that must agree. + +**Not done here, and deliberately.** Readiness and the management endpoints still see only the +default cache -- `if registry.has_cache(): health_providers["cache"] = ...` and the `CacheManagementApi` +mount are both keyed on the default name. Plan phase 6 owns both ("`CacheManagementApi`: one router, +endpoints accept optional `?name=`" and "`ActuatorApi` cache health: iterates all entries"), so a +project that registers only a named cache gets no cache health check until then. Nothing regresses: +those call sites are guarded by `has_cache()` and simply do not fire. + +Also noted rather than fixed: `add_cache`'s documented replace-and-warn path is unreachable from +the builder, because two `with_cache()` calls with one name now collide on the *component* name +first. That was already true before this change, and the resulting error names the colliding key. + +Tests, split the way the code is. `tests/unit/agents/app_builder/test_named_caches.py`, 33 cases, +covers what is visible through `with_cache`: the default cache keeping its name, directory, +registry key and `cache_service` alias; `with_cache()` working as an application's first builder +call; the three positional forms; a named cache getting its own directory (asserted on disk), its +own registry name, coexisting with the default, and appearing in `get_services()` so the lifespan +closes it; an unregistered name raising instead of yielding the default; and eleven rejected names. +`tests/unit/agents/services/infrastructure/test_cache_backend_factory.py` gains 34 cases for the +isolation itself: the derived registry name and its independence from the backend; the disk +subdirectory including a Windows separator in the configured path; the Redis prefix, asserted both +on the derivation and on the kwargs the service is constructed with; both fallback paths isolating +as disk rather than as Redis; and the name being validated before any directory is created. + --- ## Compatibility @@ -1897,6 +2702,19 @@ Everything else remains non-breaking. Specifically: Whether Dapr merges the two or delivers twice needs checking against a real sidecar; it belongs on the broker-test list. - New config keys all default to current behaviour. +- **`AppBuilder.with_cache` gained a keyword-only `name`, and the three positional forms are + unchanged.** `with_cache()`, `with_cache(False)` and `with_cache(True, False)` mean what they + always meant, which is why `name` had to come last and be keyword-only (spec sec. 4.2). The + default cache keeps its registry key `disk_cache_service`, its configured `cache.cache_dir` and + its Redis key prefix, so no existing cache data moves. +- **`DiskCacheService.__init__` and `RedisCacheService.__init__` gained a trailing optional + `component_name`, and `CacheBackendFactory.create` a trailing optional `name`.** Additive and + defaulted; existing positional calls are unaffected. `create` derives the component name from + the cache name, so callers pass one name rather than two that have to agree. +- **`AppBuilder.with_*` gained a keyword-only `namespace`, and an explicit `name=` is now qualified + with the namespace the component was built in.** At the root -- every single-agent application -- + `qualified_component_name("", name)` is `name`, so nothing changes. In a namespace the key becomes + `_`, which is what makes one registration applicable to two agents at all. - **`EventHandlingBase._process_cloud_event` takes a third argument, `topic`.** A protected method, so this affects only a third-party transport implementation that called it -- of which the repo contains two, both updated. @@ -2022,6 +2840,14 @@ stay keyword-only and last, or an existing `with_cache(False)` would silently be ## Open points +- **Two spec amendments are outstanding for `with_namespace` (phase 3 part 1).** Spec sec. 4.2 + types the return as `AppBuilder | NamespaceBuilder` and lists a `config: Config | None` + parameter. The union is honoured at runtime but resolved by `@overload` so no caller narrows it; + the `config` parameter is **not** accepted, because config rework step 2 left it with no reader + -- `Component.config` derives each component's view from the one loaded tree. The spec should + say so rather than describing a parameter the implementation refuses. Reasoning in the phase 3 + part 1 entry above. + - **P0-P5 have landed. P6 is next**, and two requirements for it were settled during P5 (see the namespace bullet below). What remains open from P5 is deferred work rather than unfinished work: both modes now fire a cron once across three replicas, which was P5's acceptance criterion. @@ -2144,6 +2970,23 @@ stay keyword-only and last, or an existing `with_cache(False)` would silently be - **Nothing observes dead-lettering.** It is logged, but there is no counter, so "how many messages did we give up on today" cannot be answered from metrics. It belongs with the telemetry work in phase 9, next to `blueprint.events.unhandled`. +- ~~**Cache names are not namespace-scoped**~~ -- **done**, by prefixing the partition + (`AgentScopedCache`). The deployment constraint decided it: a backend per agent per name would + multiply the writable paths a group needs and split one `emptyDir`'s budget N ways. Two things + it leaves open. The lens is per *registry view*, so framework code that reaches + `Component.shared_registry` directly still gets the shared store -- correct today, and worth + re-checking whenever a framework component starts caching on an agent's behalf. And nothing + migrates keys written before the prefix existed: an application upgrading with a persistent + redis cache sees its old entries as absent, which is a cold cache rather than an error, but + should be said in the migration guide (phase 10). +- **The examples are not migrated to `AgentRegistration`, by decision (2026-09-08).** Asked + whether to convert one project's `main.py` as proof, the user chose not to touch the examples + part-way through the changes, and to revisit them when the integration tests are written -- + where two real example projects grouped into one process would be a better test of C1 and C5 + than a fixture written for the purpose. So the "only `main.py` differs" claim currently lives + in `test_agent_registration.py` rather than in the tree, and the examples keep passing + instances (`with_rest_api(MonitorApi())`), which `AgentRegistration` refuses -- converting them + is part of that later work, not a prerequisite for it. - **Local NATS and Dapr integration environment.** Everything above is covered by unit tests with mocked transports. Once the feature is implemented, stand both brokers up locally (compose file plus a CI job) and cover the behaviour that only a real broker exhibits: queue-group distribution diff --git a/src/blueprint/agent_generator/base_files/Dockerfile b/src/blueprint/agent_generator/base_files/Dockerfile index df5fe8c1..61f09b21 100644 --- a/src/blueprint/agent_generator/base_files/Dockerfile +++ b/src/blueprint/agent_generator/base_files/Dockerfile @@ -60,6 +60,12 @@ COPY --from=builder /usr/local/bin /usr/local/bin COPY --chown=appuser:appuser src ./src COPY --chown=appuser:appuser settings.toml ./ +# The disk cache backend writes here, and it cannot create this itself: WORKDIR made /app +# root-owned, so mkdir() as appuser fails with EACCES. Created and handed over at build time, +# which is also the mount point to use under a read-only root filesystem -- see the +# "Writable cache directory" section of docs/guides/deployment.md. +RUN mkdir -p /app/.cache && chown -R appuser:appuser /app/.cache + # Note: secrets.toml is NOT copied into the image. # Mount it at runtime via Docker secrets or volume mount. # Example (Docker Swarm): diff --git a/src/blueprint/agents/__init__.py b/src/blueprint/agents/__init__.py index 93b70c5a..8d6db750 100644 --- a/src/blueprint/agents/__init__.py +++ b/src/blueprint/agents/__init__.py @@ -1,14 +1,16 @@ """Base framework components for the agent blueprint.""" from .agent import AgentBuilder, AgentRuntime -from .app_builder import AppBuilder +from .app_builder import AgentRegistration, AppBuilder, NamespaceBuilder from .config import Config from .utils import run_app __all__ = [ "AgentBuilder", + "AgentRegistration", "AgentRuntime", "AppBuilder", "Config", + "NamespaceBuilder", "run_app", ] diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index 5f5fdb1f..75162ee2 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -1,9 +1,10 @@ """Generic FastAPI application setup and configuration.""" import logging -from collections.abc import AsyncIterator -from contextlib import asynccontextmanager -from typing import TYPE_CHECKING, Any, TypeVar +from collections.abc import AsyncIterator, Callable, Iterator, Mapping +from contextlib import asynccontextmanager, contextmanager +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, TypeVar, overload from fastapi import FastAPI @@ -11,7 +12,8 @@ from .io.api.actuators.health import HealthCheckerBase from .component.component import Component -from .component.registry import Registry +from .component.namespace import ROOT_LABEL, ROOT_NAMESPACE, namespace_of, namespace_scope, qualified_component_name, validate_namespace +from .component.registry import DEFAULT_CACHE_NAME, Registry from .agent.agent_runtime import AgentRuntime from .handler.event_handler_base import EventHandlerBase from .io.api.rest_api_base import RestApiBase @@ -43,6 +45,274 @@ logger = logging.getLogger(__name__) +@contextmanager +def _construction_scope(namespace: str) -> Iterator[None]: + """Construct inside ``namespace``, or leave the ambient namespace exactly as it is. + + The difference matters because ``namespace_scope("")`` is not a no-op: it *sets* the current + namespace to the root. :meth:`AgentRegistration.apply` opens one scope per agent and then + calls the builder's ``with_*`` methods, which default ``namespace`` to the root -- so + entering a scope unconditionally would reset every component of every agent back to the + root, silently, and the ambient mechanism would apply to nothing. + + Args: + namespace: The agent to construct for, or ``""`` to keep whatever is already in force. + + Yields: + Nothing; the scope is ambient. + """ + if not namespace: + yield + return + with namespace_scope(namespace): + yield + + +@dataclass(frozen=True) +class RegisteredComponent: + """One component an :class:`AgentRegistration` will build when it is applied. + + Attributes: + kind: Which ``with_*`` on the builder this entry is applied through. + target: A component class, or a zero-argument callable returning a component. + name: Registry name override, or ``None`` to let the component derive its own. + kwargs: Constructor arguments, forwarded when ``target`` is a class. + """ + + kind: str + target: Any + name: str | None + kwargs: Mapping[str, Any] + + +class AgentRegistration: + """What an agent is made of, declared without building any of it. + + This is the shape a project's ``main.py`` takes so that the same agent can run alone or + inside a group. It collects component *classes*; whoever applies it decides the namespace + they are built in, which is why nothing here -- and nothing in the components themselves -- + mentions a namespace:: + + registration = AgentRegistration().with_service(OrderService).with_handler(OrderHandler) + + app = AppBuilder(config).with_registration(registration).build() # alone + # a group applies the same object under the agent's own namespace instead + + **Nothing is instantiated until :meth:`apply` runs**, and that is the point rather than an + optimisation: a component built here would be built before any namespace exists, and would + belong to the root whichever agent it was declared for. So an already-constructed component + is refused -- see :meth:`with_rest_api` for what to write instead. + + **There is no ``with_cache``.** A cache is process-wide and is registered on the + ``AppBuilder`` that hosts the group; an agent that declared its own would either duplicate + another agent's or quietly take it over. Ask for a cache by name from the registry instead. + """ + + def __init__(self) -> None: + self._components: list[RegisteredComponent] = [] + + @property + def components(self) -> tuple[RegisteredComponent, ...]: + """What has been declared, in declaration order. + + Order is preserved because it is meaningful: handler priority and scheduler wiring both + read it, so a registration applied twice must produce the same application twice. + """ + return tuple(self._components) + + def with_handler(self, handler: type[HandlerT], *, name: str | None = None, **kwargs: Any) -> "AgentRegistration": + """Declare an event handler class.""" + return self._add("handler", handler, name, kwargs) + + def with_service(self, service: type[ServiceT], *, name: str | None = None, **kwargs: Any) -> "AgentRegistration": + """Declare a business service class.""" + return self._add("service", service, name, kwargs) + + def with_agent(self, agent: type[AgentT] | Callable[[], AgentT], *, name: str | None = None, **kwargs: Any) -> "AgentRegistration": + """Declare an agent runtime, as a class or as a factory. + + The factory form exists for the fluent builder: an ``AgentRuntime`` assembled by + ``AgentBuilder(...).with_model_from_config()...build()`` cannot be expressed as a class + plus keyword arguments. Wrapping that chain in a ``lambda`` defers it into + :meth:`apply`, so the model and prompt are resolved inside the agent's own namespace + rather than at import time:: + + AgentRegistration().with_agent(lambda: AgentBuilder(config, runtime_name="orders").build()) + """ + return self._add("agent", agent, name, kwargs) + + def with_scheduler( + self, scheduler: type[SchedulerT] | Callable[[], SchedulerT], *, name: str | None = None, **kwargs: Any + ) -> "AgentRegistration": + """Declare a scheduler class, or a factory returning one.""" + return self._add("scheduler", scheduler, name, kwargs) + + def with_rest_api(self, api: type[RestApiT] | Callable[[], RestApiT], *, name: str | None = None, **kwargs: Any) -> "AgentRegistration": + """Declare a REST API class, or a factory returning one. + + Pass the class, not an instance: ``with_rest_api(OrderApi)`` rather than + ``with_rest_api(OrderApi())``. The instance form is what an ``AppBuilder`` chain + accepts, and it is refused here because the object would already exist -- built at + import time, before any namespace, and therefore belonging to the root no matter which + agent declared it. Two grouped agents each declaring one would collide on its registry + name. Constructor arguments go here as keyword arguments; anything a plain call cannot + express goes in a ``lambda``. + """ + return self._add("rest_api", api, name, kwargs) + + def _add(self, kind: str, target: Any, name: str | None, kwargs: Mapping[str, Any]) -> "AgentRegistration": + """Store one declaration, rejecting anything already built.""" + if isinstance(target, Component): + raise TypeError( + f"{type(target).__name__} was passed to AgentRegistration.with_{kind}() as an instance, but a " + "registration declares components rather than holding them: this object was built before any " + "namespace existed, so it belongs to the root namespace whichever agent declared it, and two " + f"grouped agents declaring one would collide on its registry name. Pass the class -- " + f"with_{kind}({type(target).__name__}, ...) with its constructor arguments as keyword arguments -- " + "or a callable returning it." + ) + if not callable(target): + raise TypeError(f"AgentRegistration.with_{kind}() needs a component class or a callable returning one, got {target!r}.") + self._components.append(RegisteredComponent(kind=kind, target=target, name=name, kwargs=dict(kwargs))) + return self + + def apply(self, builder: "AppBuilder", namespace: str = ROOT_NAMESPACE) -> None: + """Build everything declared here on ``builder``, inside ``namespace``. + + Public rather than private because the caller is another class: ``AppBuilder`` for a + single agent today, the group entry point per agent later. + + Every component is constructed inside :func:`namespace_scope`, which is the whole + mechanism -- ``Component.__init__`` reads the ambient namespace, so no component and no + constructor signature mentions one. A factory is called here for the same reason. + + Args: + builder: The builder to register on. + namespace: The agent these components belong to. ``""`` is the root, which is what + a single-agent application uses. + + Raises: + ValueError: if ``namespace`` is not a legal namespace. + """ + appliers: dict[str, Callable[..., Any]] = { + "handler": builder.with_handler, + "service": builder.with_service, + "agent": builder.with_agent, + "scheduler": builder.with_scheduler, + "rest_api": builder.with_rest_api, + } + + with namespace_scope(namespace): + for entry in self._components: + # A class goes to the builder, which instantiates it -- still inside this scope. + # A factory has to be called here, because the builder would take the callable + # itself for an already-built component. + target = entry.target if isinstance(entry.target, type) else entry.target() + appliers[entry.kind](target, name=entry.name, **entry.kwargs) + + logger.debug( + "Applied %d component(s) to namespace '%s': %s", + len(self._components), + namespace or ROOT_LABEL, + ", ".join(f"{entry.kind}:{getattr(entry.target, '__name__', entry.target)}" for entry in self._components), + ) + + +class NamespaceBuilder: + """One agent's view of an :class:`AppBuilder`: every ``with_*`` call lands in its namespace. + + Returned by :meth:`AppBuilder.with_namespace` when no registration is passed, for the + indent-and-close style:: + + app = ( + AppBuilder(config) + .with_namespace("orders") + .with_service(OrderService) + .with_handler(OrderHandler) + .end() + .with_namespace("billing") + .with_service(BillingService) + .end() + .with_cache() + .build() + ) + + This form is for a group assembled by hand -- a test, or agents that are not packaged as + registrations. The primary form is + ``with_namespace("orders", registration=orders.registration)``, which needs no ``end()`` + because it returns the ``AppBuilder`` itself. + + Every method delegates to the parent builder with ``namespace=`` filled in, so registering a + component has one implementation and this class only decides which namespace it goes to. + + **There is no** ``with_cache``. A cache is process-wide and belongs to the ``AppBuilder`` + that hosts the group: an agent registering its own would either duplicate a neighbour's or + quietly take it over, which is the collision spec sec. 8 exists to prevent. Ask the registry + for a cache by name instead. + """ + + def __init__(self, builder: "AppBuilder", namespace: str) -> None: + """Bind a namespace to a builder. + + Args: + builder: The builder every call is forwarded to. + namespace: The agent this view registers into. + + Raises: + ValueError: if ``namespace`` is not a legal namespace. + """ + self._builder = builder + self._namespace = validate_namespace(namespace) + + @property + def namespace(self) -> str: + """The agent this view registers into.""" + return self._namespace + + def with_handler(self, handler: type[HandlerT] | HandlerT, *, name: str | None = None, **kwargs: Any) -> "NamespaceBuilder": + """Register an event handler in this namespace.""" + self._builder.with_handler(handler, name=name, namespace=self._namespace, **kwargs) + return self + + def with_service(self, service: type[ServiceT] | ServiceT, *, name: str | None = None, **kwargs: Any) -> "NamespaceBuilder": + """Register a business service in this namespace.""" + self._builder.with_service(service, name=name, namespace=self._namespace, **kwargs) + return self + + def with_agent(self, agent: type[AgentT] | AgentT, *, name: str | None = None, **kwargs: Any) -> "NamespaceBuilder": + """Register an agent runtime in this namespace.""" + self._builder.with_agent(agent, name=name, namespace=self._namespace, **kwargs) + return self + + def with_scheduler(self, scheduler: type[SchedulerT] | SchedulerT, *, name: str | None = None, **kwargs: Any) -> "NamespaceBuilder": + """Register a scheduler in this namespace.""" + self._builder.with_scheduler(scheduler, name=name, namespace=self._namespace, **kwargs) + return self + + def with_rest_api(self, api: type[RestApiT] | RestApiT, *, name: str | None = None, **kwargs: Any) -> "NamespaceBuilder": + """Register a REST API in this namespace.""" + self._builder.with_rest_api(api, name=name, namespace=self._namespace, **kwargs) + return self + + def with_registration(self, registration: AgentRegistration) -> "NamespaceBuilder": + """Apply a whole :class:`AgentRegistration` in this namespace. + + The same thing ``with_namespace(name, registration=...)`` does, reachable from inside an + indented block so a hand-assembled agent and a packaged one can be mixed. + """ + self._builder.with_registration(registration, self._namespace) + return self + + def end(self) -> "AppBuilder": + """Close the namespace block and return the parent builder. + + Nothing is "left" in any real sense: this object holds no build state and the components + are already registered. ``end()`` exists so the chain can continue with another + namespace or with ``build()``. + """ + return self._builder + + class AppBuilder: """Builds the FastAPI application with a fluent interface. @@ -76,70 +346,255 @@ def __init__(self, config: Config) -> None: # special case in _build_rest_endpoints. self._lifecycle_components: list[Component] = [] self._actuator_api: ActuatorApi | None = None + # Which agents this process hosts. See the 'namespaces' property for why the + # builder is the thing that keeps the list rather than the registry. + self._namespaces: list[str] = [] # ------------------------------------------------------------------ # Fluent registration API # ------------------------------------------------------------------ - def with_handler(self, handler: type[HandlerT] | HandlerT, *, name: str | None = None, **kwargs: Any) -> "AppBuilder": - """Register an event handler class or instance.""" - if isinstance(handler, type): - if not issubclass(handler, EventHandlerBase): - raise TypeError(f"Expected EventHandlerBase subclass, got {handler.__name__}") - instance = handler(**kwargs) - else: - instance = handler - if name is not None: - instance.name = name + def with_registration(self, registration: AgentRegistration, namespace: str = ROOT_NAMESPACE) -> "AppBuilder": + """Register everything an :class:`AgentRegistration` declares. + + This is what lets one declaration serve both deployment shapes. A project keeps its + components in an ``AgentRegistration``, and a single-agent ``main.py`` builds it here:: + + app = AppBuilder(config).with_registration(registration).with_cache().build() + + while a group applies the same object once per agent, under that agent's namespace. + Everything above that last line is the same file in both cases. + + Equivalent to the individual ``with_*`` calls, in declaration order, so it composes with + them and with ``with_cache``. + + Args: + registration: The declaration to build. + namespace: The agent these components belong to. Defaults to the root, which is the + whole of a single-agent application. + """ + registration.apply(self, namespace) return self - def with_service(self, service: type[ServiceT] | ServiceT, *, name: str | None = None, **kwargs: Any) -> "AppBuilder": - """Register a business service class or instance.""" - instance = service(**kwargs) if isinstance(service, type) else service - if name is not None: - instance.name = name + @overload + def with_namespace(self, name: str, *, registration: AgentRegistration) -> "AppBuilder": ... + + @overload + def with_namespace(self, name: str, *, registration: None = None) -> "NamespaceBuilder": ... + + def with_namespace(self, name: str, *, registration: AgentRegistration | None = None) -> "AppBuilder | NamespaceBuilder": + """Declare an agent hosted by this process, and register its components into it. + + Two forms, and which one you get depends on whether you hand over a registration:: + + # primary: the agent is packaged, so the chain never leaves the AppBuilder + AppBuilder(config).with_namespace("orders", registration=orders.registration) + + # hand-assembled: an indented block, closed with end() + AppBuilder(config).with_namespace("billing").with_service(BillingService).end() + + The overloads above are what make that union tolerable at a call site: passing a + registration is statically an ``AppBuilder`` and omitting it is statically a + ``NamespaceBuilder``, so no caller has to narrow a union or assert its way out of one. + + **There is no** ``config`` **parameter**, and spec sec. 4.2 lists one. It would have + nothing to do: configuration is already resolved per namespace from the one loaded tree + -- ``Component.config`` hands each component ``Config.for_namespace(its own namespace)``, + which tries ``.`` before ```` (C5). A second ``Config`` here would + either be ignored, or re-parse the same files once per agent and then be ignored anyway, + because a component reads the shared one rather than anything the builder holds. Nothing + would read it, so it is not accepted; see the changelog entry for this phase. + + Args: + name: The agent's namespace. Must be a legal namespace and must not be the root. + registration: The agent's declaration, applied immediately in ``name``. Omit it to + get a :class:`NamespaceBuilder` and register components one at a time. + + Returns: + This builder when ``registration`` was given, otherwise a :class:`NamespaceBuilder` + for ``name``. + + Raises: + ValueError: if ``name`` is the root namespace or is not a legal namespace. + """ + namespace = validate_namespace(name) + if not namespace: + raise ValueError( + "with_namespace('') names no agent: '' is the root namespace, which is where the plain with_*() calls " + "already register. Pass the agent's name, or drop the with_namespace() call for a single-agent " + "application." + ) + + # Recorded before anything is built, so that a registration failing half way through + # still leaves the namespace declared: the startup log and the readiness policy have to + # be able to say that an agent was meant to be here. + if namespace not in self._namespaces: + self._namespaces.append(namespace) + logger.info("Hosting agent namespace '%s'", namespace) + + if registration is None: + return NamespaceBuilder(self, namespace) + return self.with_registration(registration, namespace) + + @property + def namespaces(self) -> tuple[str, ...]: + """The agent namespaces declared on this builder, in declaration order. + + The builder keeps this list because nothing else may. ``Registry`` deliberately has no + ``get_known_namespaces()``: it is reachable from every component (C6), so an agent could + use it to enumerate the neighbours it shares a process with -- and grouping is supposed + to be invisible from inside. The builder is the object that was *told* which agents to + host, and it is not reachable from a component, so the list lives here. + + The root namespace is not in it: a single-agent application declares no namespace at all, + so an empty tuple means "root only" rather than "nothing registered". + """ + return tuple(self._namespaces) + + def with_handler( + self, handler: type[HandlerT] | HandlerT, *, name: str | None = None, namespace: str = ROOT_NAMESPACE, **kwargs: Any + ) -> "AppBuilder": + """Register an event handler class or instance. + + Args: + handler: The handler class to build, or an already-built instance. + name: Registry name override, qualified with the namespace like a derived one. + namespace: The agent this handler belongs to. ``""`` keeps whatever namespace is + already in force, which is what lets a registration applied per agent land in + the right one. + **kwargs: Constructor arguments, forwarded when a class is passed. + """ + if isinstance(handler, type) and not issubclass(handler, EventHandlerBase): + raise TypeError(f"Expected EventHandlerBase subclass, got {handler.__name__}") + self._register(handler, namespace, kwargs, name=name, method="with_handler") return self - def with_agent(self, agent: type[AgentT] | AgentT, *, name: str | None = None, **kwargs: Any) -> "AppBuilder": - """Register an agent runtime class or instance.""" - instance = agent(**kwargs) if isinstance(agent, type) else agent - if name is not None: - instance.name = name + def with_service( + self, service: type[ServiceT] | ServiceT, *, name: str | None = None, namespace: str = ROOT_NAMESPACE, **kwargs: Any + ) -> "AppBuilder": + """Register a business service class or instance. See :meth:`with_handler` for the arguments.""" + self._register(service, namespace, kwargs, name=name, method="with_service") return self - def with_scheduler(self, scheduler: type[SchedulerT] | SchedulerT, *, name: str | None = None, **kwargs: Any) -> "AppBuilder": - """Register a scheduler class or instance.""" - instance = scheduler(**kwargs) if isinstance(scheduler, type) else scheduler - if name is not None: - instance.name = name + def with_agent( + self, agent: type[AgentT] | AgentT, *, name: str | None = None, namespace: str = ROOT_NAMESPACE, **kwargs: Any + ) -> "AppBuilder": + """Register an agent runtime class or instance. See :meth:`with_handler` for the arguments.""" + self._register(agent, namespace, kwargs, name=name, method="with_agent") return self - def with_rest_api(self, api: type[RestApiT] | RestApiT, *, name: str | None = None, **kwargs: Any) -> "AppBuilder": - """Register a custom REST API class or instance.""" - instance = api(**kwargs) if isinstance(api, type) else api - if name is not None: - instance.name = name + def with_scheduler( + self, scheduler: type[SchedulerT] | SchedulerT, *, name: str | None = None, namespace: str = ROOT_NAMESPACE, **kwargs: Any + ) -> "AppBuilder": + """Register a scheduler class or instance. See :meth:`with_handler` for the arguments.""" + self._register(scheduler, namespace, kwargs, name=name, method="with_scheduler") return self - def with_cache(self, enabled: bool = True, enable_locking: bool = True) -> "AppBuilder": - """Enable persistent caching using DiskCache. + def with_rest_api( + self, api: type[RestApiT] | RestApiT, *, name: str | None = None, namespace: str = ROOT_NAMESPACE, **kwargs: Any + ) -> "AppBuilder": + """Register a custom REST API class or instance. See :meth:`with_handler` for the arguments.""" + self._register(api, namespace, kwargs, name=name, method="with_rest_api") + return self + + @staticmethod + def _register(target: Any, namespace: str, kwargs: Mapping[str, Any], *, name: str | None, method: str) -> Any: + """Build ``target`` inside ``namespace`` -- or adopt it if it is already built -- and name it. + + Registration itself does not happen here: ``Component.__init__`` adds the instance to + the registry, so the only two things left are *which namespace it is constructed in* and + *what it is called*. + + **The namespace is never handed to** ``target``. A project's component takes the + constructor arguments its author wrote and nothing else, so the namespace travels + through the ambient scope and is read by ``Component.__init__``. That is why + ``with_service(OrderService, namespace="orders")`` does not become + ``OrderService(namespace="orders")`` and does not require ``OrderService`` to know what + a namespace is -- which is the whole point of the ambient mechanism. + + An already-built instance cannot be moved into a namespace: its namespace, and its + registry key with it, were fixed by the scope it was constructed in. A mismatch is + refused rather than ignored, because ignoring it registers the component at the root + while the caller believes it belongs to an agent. Args: - enabled: Whether to enable caching (default: True) - enable_locking: Enable file-based locking for multi-deployment safety (default: True). + target: A component class to build, or a built component to adopt. + namespace: The agent to build inside; ``""`` keeps the ambient namespace. + kwargs: Constructor arguments, used only when ``target`` is a class. + name: Registry name override, or ``None`` to keep the derived name. + method: The builder method being called, for the error message. + + Returns: + The component instance, already in the registry. + + Raises: + ValueError: if a built instance is offered to a namespace other than its own. """ - if enabled: - cache_config = self._config.get_cache_config() - cache_service = CacheBackendFactory.create(cache_config, enable_locking=enable_locking) - Component.shared_registry.cache_service = cache_service # type: ignore[union-attr] - logger.info( - "Registered %s with cache_dir=%s (locking=%s)", - type(cache_service).__name__, - cache_config.cache_dir, - enable_locking, - ) + if isinstance(target, type): + with _construction_scope(namespace): + instance = target(**kwargs) else: - logger.info("Caching disabled") + built_in = namespace_of(target) + if namespace and built_in != namespace: + raise ValueError( + f"{type(target).__name__} was passed to {method}() as an instance for namespace '{namespace}', " + f"but it was already built in namespace '{built_in or ROOT_LABEL}', and a component cannot change " + "namespace afterwards: both its namespace and its registry key are fixed at construction. Pass " + f"the class instead -- {method}({type(target).__name__}, namespace='{namespace}', ...) -- so that " + "it is built inside that namespace." + ) + instance = target + + if name is not None: + # Qualified for the same reason Component.__init__ qualifies a derived name: one + # registration applied to two agents would otherwise register both under the one + # literal name, and the second would fail on the collision. It stays findable by + # the bare name the caller wrote, because Registry._lookup tries + # '_' before ''. + instance.name = qualified_component_name(namespace_of(instance), name) + return instance + + def with_cache(self, enabled: bool = True, enable_locking: bool = True, *, name: str = DEFAULT_CACHE_NAME) -> "AppBuilder": + """Register a cache, by default the one every existing application already has. + + Call it more than once to register several:: + + AppBuilder(config).with_cache().with_cache(name="sessions").build() + + Each name gets its own storage, isolated per backend by ``CacheBackendFactory``, and + any component reads one back with ``self.registry.get_cache("sessions")``. There is + deliberately no fallback from an unknown name to the default (spec sec. 8). + + ``name`` is **keyword-only and comes last**, which is a constraint rather than a style + choice. ``with_cache(False)`` disables caching today; had ``name`` been the first + parameter that call would have become a cache named ``False`` with caching silently + switched *on*, with no ``TypeError`` to notice. So ``with_cache()``, + ``with_cache(False)`` and ``with_cache(True, False)`` all still mean what they meant. + + Args: + enabled: Whether to create the cache at all. ``False`` registers nothing. + enable_locking: File-based locking for multi-process safety, for the disk backend. + name: Which cache this is. The default keeps the registry key, the cache directory + and the Redis keyspace an existing application already uses. + + Raises: + ValueError: if ``name`` cannot serve as a cache name. + """ + if not enabled: + logger.info("Caching disabled; cache '%s' is not registered", name) + return self + + # The name goes to the factory rather than being resolved here: which store a name + # maps to is backend knowledge, and the factory is where a backend is chosen and where + # a new one would be added. + cache_service = CacheBackendFactory.create(self._config.get_cache_config(), enable_locking=enable_locking, name=name) + # Read after the service is built, never before: a cache service is itself a Component, + # and Component.__init__ is what creates the shared registry on first use. Capturing it + # first is an AttributeError on None for an application whose first builder call is + # with_cache(). + registry: Registry = Component.shared_registry # type: ignore[assignment] + registry.add_cache(name, cache_service) + logger.info("Registered cache '%s' as %s (locking=%s)", name, type(cache_service).__name__, enable_locking) return self def with_health_checker(self, name: str, checker: "HealthCheckerBase") -> "AppBuilder": @@ -502,6 +957,12 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: if self._actuator_api is not None: await self._actuator_api.on_shutdown() + + # Last, and after every on_shutdown: a component may well run its final blocking + # work there. The pools hold non-daemon threads, so leaving them running keeps the + # interpreter alive past the point the container was asked to stop. + registry.shutdown_executors() + logger.info("Application shutdown completed") return lifespan diff --git a/src/blueprint/agents/component/component.py b/src/blueprint/agents/component/component.py index fb6506c6..a0d456b0 100644 --- a/src/blueprint/agents/component/component.py +++ b/src/blueprint/agents/component/component.py @@ -12,6 +12,7 @@ import functools import inspect from abc import ABC, ABCMeta, abstractmethod +from concurrent.futures import ThreadPoolExecutor from functools import cached_property from typing import Any, TYPE_CHECKING from collections.abc import Callable @@ -20,7 +21,7 @@ from ..config import Config from ..utils import camel_to_snake -from .namespace import ROOT_NAMESPACE, qualified_component_name, validate_namespace +from .namespace import ROOT_NAMESPACE, current_namespace, qualified_component_name, validate_namespace if TYPE_CHECKING: from .registry import Registry @@ -113,8 +114,12 @@ def __init__(self, should_register: bool = True, name: str | None = None, namesp owns its uniqueness. It must be supplied here rather than assigned afterwards: registration happens in this constructor, so a second instance of the same class would collide before a rename could run. - namespace: The agent this component belongs to; ``""`` (the default) is the root - namespace and the whole of a single-agent application. + namespace: The agent this component belongs to. Left unset -- which is what every + developer-written component does -- it is taken from the ambient + ``namespace_scope`` in force during construction, so a handler or service + carries no namespace in its own code and reads the same whether it runs alone + or beside five other agents. ``""`` is the root namespace and the whole of a + single-agent application. Raises: ValueError: if the namespace is not a legal namespace. This is the framework's @@ -132,7 +137,13 @@ def __init__(self, should_register: bool = True, name: str | None = None, namesp Component.init_registry(Registry(Component)) - self._namespace = validate_namespace(namespace or ROOT_NAMESPACE) + # A *non-empty* argument wins; anything else defers to the ambient scope. It cannot be + # the other way round: ServiceBase, ClientBase, IOClientBase and EventPublishingService + # all default this parameter to ROOT_NAMESPACE and forward it unconditionally, so a + # developer writing `super().__init__()` in their own service passes an explicit "" -- + # and treating that as a decision would pin every developer-written component to the + # root and make the ambient scope apply to nothing that matters. + self._namespace = validate_namespace(namespace or current_namespace()) self._name = name or qualified_component_name(self._namespace, camel_to_snake(self.__class__.__name__)) if should_register: self.registry.add_component(self.name, self) @@ -159,8 +170,24 @@ def namespace(self) -> str: @property def registry(self) -> Registry: - """Get the component registry for accessing other components.""" - return Component.shared_registry # type: ignore[return-value] + """The component registry, as a view that answers for this component's namespace. + + A namespaced component receives a *view*: an omitted ``namespace`` on any lookup means + this agent, resolving its own component first and a root one second. So + ``self.registry.get_service(OrderService)`` finds this agent's service while + ``self.registry.get_service(EventProcessingService)`` finds the shared root one, and + neither call site names a namespace -- which is the point. Two agents can then be built + from one declaration and each wire itself correctly. + + A root-namespace component gets the registry itself, unchanged. As with + :attr:`config`, that is the definition rather than an optimisation: the root namespace + *is* the unscoped registry, so every existing single-agent application resolves exactly + what it resolved before. + """ + registry: Registry = Component.shared_registry # type: ignore[assignment] + if not self._namespace: + return registry + return registry.for_namespace(self._namespace) @property def config(self) -> Config: @@ -181,6 +208,26 @@ def config(self) -> Config: return Component._shared_config return Component._shared_config.for_namespace(self._namespace) + @cached_property + def executor(self) -> ThreadPoolExecutor: + """This component's namespace thread pool, for running blocking work off the event loop. + + Use it through ``asyncio.get_running_loop().run_in_executor(self.executor, ...)``. The + pool belongs to the namespace, not to the component, so every component of one agent + shares one and no agent can exhaust another's. + + Created on first access. A component that never touches this property costs nothing, so + an application with no blocking work runs with no extra threads at all -- which is why + this is a property rather than something ``build()`` provisions. + + Its size comes from ``executor_workers`` in this component's own configuration, which is + namespace-scoped (C5), so one agent can be sized differently from its neighbour. The + first component of a namespace to ask is the one that sizes it: a live pool cannot be + resized, and the alternative -- rejecting a later disagreeing value -- would fail an + application over a number nobody chose deliberately. + """ + return self.registry.get_or_create_executor(self._namespace, self.config.get("executor_workers")) + @cached_property def tracer(self) -> trace.Tracer: """OTel tracer named after the concrete class.""" diff --git a/src/blueprint/agents/component/namespace.py b/src/blueprint/agents/component/namespace.py index fcebc221..83778255 100644 --- a/src/blueprint/agents/component/namespace.py +++ b/src/blueprint/agents/component/namespace.py @@ -22,6 +22,9 @@ """ import re +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar from typing import Any ROOT_NAMESPACE = "" @@ -116,6 +119,62 @@ def validate_namespace(namespace: str) -> str: return namespace +_CURRENT_NAMESPACE: ContextVar[str] = ContextVar("blueprint_current_namespace", default=ROOT_NAMESPACE) +"""The namespace components are being constructed for, or the root when nothing set one. + +This is how a component learns its namespace **without the developer knowing namespaces exist**. +An agent is a directory of handlers, services and clients written the same way whether it runs +alone or beside five others; the only thing that differs is who builds it. So the namespace is +ambient during construction rather than an argument threaded through every constructor: a +developer writing ``class OrderService(ServiceBase)`` with ``super().__init__()`` gets a +namespaced service without a namespace appearing anywhere in their code. + +A ``ContextVar`` rather than a module global because it resets deterministically and is scoped +to the context that set it. Note the limit: a component constructed in another thread or task +does not inherit it. Construction happens synchronously inside the builder, so that is the +correct shape -- and a component built lazily at request time is a root component by +construction, which is what falling back to the root gives it. +""" + + +def current_namespace() -> str: + """Return the namespace being constructed for, or :data:`ROOT_NAMESPACE`. + + Read by ``Component.__init__``. Outside a :func:`namespace_scope` this is always the root, + so a single-agent application behaves exactly as it did before this existed. + """ + return _CURRENT_NAMESPACE.get() + + +@contextmanager +def namespace_scope(namespace: str) -> Iterator[str]: + """Construct every component inside this block for ``namespace``. + + Entered once per agent by whatever applies that agent's registration, and always exited: + leaking a namespace would silently attach the next agent -- or the framework's own root + components -- to the wrong one, and a registry key, a queue group and a durable name would + all be wrong together. + + The namespace is validated on entry rather than at the first component, so an illegal name + is reported against the registration that declared it instead of against whichever component + happened to be constructed first. + + Args: + namespace: The agent to construct for. ``""`` is the root and makes the block a no-op. + + Yields: + The namespace in force inside the block. + + Raises: + ValueError: if the namespace is not a legal namespace. + """ + token = _CURRENT_NAMESPACE.set(validate_namespace(namespace)) + try: + yield namespace + finally: + _CURRENT_NAMESPACE.reset(token) + + def display_segment(value: str, placeholder: str) -> str: """Return ``value`` reduced to one safe segment of a dot-separated identity string. diff --git a/src/blueprint/agents/component/registry.py b/src/blueprint/agents/component/registry.py index 206376e0..0fe83ed1 100644 --- a/src/blueprint/agents/component/registry.py +++ b/src/blueprint/agents/component/registry.py @@ -3,9 +3,31 @@ This registry consolidates handler, runtime, and agent management into a single component without containing business logic. Business logic remains in ProcessingService. + +**Namespaces.** One process can host several agents, and every lookup here takes an optional +``namespace``. What it means differs between the two kinds of question, deliberately: + +- *Find me the one X* (``get_component``, ``get_service``, ``get_scheduler``, ...) resolves + **the namespace first, then the root**, because infrastructure stays shared while an agent + overrides what it owns. This mirrors :func:`resolve_for_namespace`, which is the + implementation. +- *Give me all the Xs* (``get_components_by_type``, ``get_services``, ...) filters to **that + namespace exactly**, because iterating one agent's components must not sweep in a + neighbour's. + +``namespace=None``, the default, means *every namespace* and is today's behaviour unchanged. It +is not the root: ``build()`` iterating handlers has to see all of them, and a root-only default +would have silently short-changed a grouped process while looking correct on a single-agent one. + +**What is deliberately absent: any way to ask which namespaces exist.** C6 forbids agent code +observing its grouping, and ``Component.registry`` is reachable from every component, so a +``get_known_namespaces()`` here would be exactly the API C6 rules out. The builder knows the +group composition because it was told; it passes each namespace to the wiring that needs one. """ import logging +from concurrent.futures import ThreadPoolExecutor +from copy import copy from typing import Any, TypeVar from ..agent.agent_runtime import AgentRuntime @@ -19,6 +41,7 @@ from ..services.infrastructure.cache_service import CacheService from ..services.service_base import ServiceBase from ..utils import camel_to_snake +from .namespace import ROOT_LABEL, ROOT_NAMESPACE, namespace_of, qualified_component_name, resolve_for_namespace ServiceT = TypeVar("ServiceT", bound="ServiceBase") @@ -27,6 +50,13 @@ logger = logging.getLogger(__name__) +DEFAULT_CACHE_NAME = "default" +"""The cache an application gets when it asks for one without saying which. + +``AppBuilder.with_cache()`` registers under this name and ``registry.cache_service`` reads it, so +every application that predates named caches has exactly one cache called ``default``. +""" + class Registry: """ @@ -52,12 +82,16 @@ def __init__(self, component_class: Any) -> None: Registry._component_class = component_class self._correlation_context = CorrelationContextProvider.get_correlation_context() - self._cache_service: CacheService | None = None + self._caches: dict[str, CacheService] = {} self._components: dict[str, Any] = {} + self._executors: dict[str, ThreadPoolExecutor] = {} + self._default_namespace: str | None = None + self._views: dict[str, Registry] = {} + self._scoped_caches: dict[str, CacheService] = {} logger.info("ComponentRegistry initialized") - def _resolve_single(self, name_or_class: str | type[T], base_type: type[T]) -> T: + def _resolve_single(self, name_or_class: str | type[T], base_type: type[T], namespace: str | None = None) -> T: """Resolve a single component by name string or concrete class. Resolution order when a class is passed: @@ -65,52 +99,277 @@ def _resolve_single(self, name_or_class: str | type[T], base_type: type[T]) -> T 2. If not found, collect all instances of that class. - Exactly one → return it. - Zero or many → raise ValueError. + + Args: + name_or_class: Name string or concrete class. + base_type: The type the result must be an instance of. + namespace: Resolve for this agent -- its own component first, then the root one. """ if not isinstance(name_or_class, str): snake_name = camel_to_snake(name_or_class.__name__) - if snake_name in self._components: + if self._lookup(snake_name, namespace) is not None: name_or_class = snake_name # fall through to string lookup below # else: pass the class to get_component for type-scan - component = self.get_component(name_or_class) + component = self.get_component(name_or_class, namespace) if not isinstance(component, base_type): raise ValueError(f"Component '{name_or_class}' is not a {base_type.__name__}") return component + def for_namespace(self, namespace: str) -> "Registry": + """Return a view of this registry that answers as ``namespace`` unless told otherwise. + + This is what lets a component find *its own* agent's collaborators while writing the + lookup it would write in a single-agent application. ``Component.registry`` hands each + component its namespace's view, so ``self.registry.get_service(OrderService)`` resolves + this agent's service and falls back to a root one -- with no namespace named at the call + site, which is the whole requirement. + + The view shares this registry's components, caches and executors by reference: there is + one registry per process and a view is a lens on it, not a copy. It differs only in what + an omitted ``namespace`` argument means -- this agent, rather than every agent. + + Views are cached, so a component asking twice gets the same object. + + Args: + namespace: The agent to answer as. ``""`` returns this registry unchanged, because + the root namespace *is* the unscoped registry -- so a single-agent application + and every framework caller that holds ``Component.shared_registry`` behave + exactly as before. + + Raises: + RuntimeError: if called on a view. A view is one agent's lens; letting it mint + another agent's would hand every component a route to its neighbours, which is + what C6 forbids. + """ + if self._default_namespace is not None: + raise RuntimeError( + f"The registry view for namespace '{self._default_namespace}' was asked for a view of namespace " + f"'{namespace}'. Views are created from the application's registry, not from another agent's view." + ) + if not namespace: + return self + + cached = self._views.get(namespace) + if cached is not None: + return cached + + view = copy(self) + view._default_namespace = namespace + view._views = {} + # Its own, because the entries are per agent: the shallow copy would otherwise have + # every view handing out the first agent's lens. + view._scoped_caches = {} + self._views[namespace] = view + return view + + @property + def default_namespace(self) -> str | None: + """The namespace this object answers as; ``None`` on the application's own registry.""" + return self._default_namespace + + def _all_of_type(self, component_type: Any) -> list[Any]: + """Every component of a type, from every namespace, whatever this object answers as. + + The namespace-blind counterpart of :meth:`get_components_by_type`, for the two callers + that must not have their argument reinterpreted: the class-resolution path, which needs + all the candidates in order to choose between the namespace and the root, and the + message that lists them when it cannot. + """ + return [component for component in self._components.values() if isinstance(component, component_type)] + + def _effective_namespace(self, namespace: str | None) -> str | None: + """Resolve an omitted ``namespace`` argument. + + On the application's own registry an omitted namespace means *every* namespace, which is + what ``build()`` and the lifespan need when they iterate. On a view it means *that view's* + namespace, which is what a component needs when it looks up a collaborator. An explicit + argument always wins, on either. + """ + return self._default_namespace if namespace is None else namespace + + def _lookup(self, name: str, namespace: str | None) -> Any | None: + """Return the component registered under ``name`` for ``namespace``, or ``None``. + + The namespace-qualified name is tried before the bare one, which is the whole of the + namespace-then-root fallback: ``Component.__init__`` registers a namespaced component as + ``_`` and a root one as ````, so asking for ``event_publishing_service`` + in namespace ``orders`` finds ``orders_event_publishing_service`` if that agent has its own + and the shared root one otherwise. + + A caller that already holds the qualified name is unaffected: qualifying it a second time + simply misses, and the bare lookup then finds it. + """ + namespace = self._effective_namespace(namespace) + if namespace: + qualified = qualified_component_name(namespace, name) + if qualified in self._components: + return self._components[qualified] + return self._components.get(name) + @property def correlation_context(self) -> CorrelationContext: """Return the correlation context used for logging.""" return self._correlation_context + def get_or_create_executor(self, namespace: str = ROOT_NAMESPACE, max_workers: int | None = None) -> ThreadPoolExecutor: + """Return this namespace's thread pool, creating it on first use. + + One pool **per namespace**, so that an agent doing blocking work -- DiskCache, SQLite, a + synchronous SDK -- cannot exhaust the pool another agent is waiting on. + + **Created on first access, never in advance** (spec sec. 4.3). Provisioning one per + namespace during ``build()`` would add ``cpu_count() + 4`` idle threads to every + application that has no blocking work at all, including every single-agent application + that exists today, and work against the thread budget in #36. That is also why there is + no separate ``add_executor``: with creation on demand, a namespace can never be missing + one, so the root-fallback the plan describes has nothing left to fall back for -- it + would be a branch that cannot be taken. + + Args: + namespace: The agent asking. The root namespace is a namespace like any other here. + max_workers: Size to create it with, on the call that creates it; ``None`` leaves + the interpreter default (``min(32, cpu_count() + 4)``). Ignored once the pool + exists, because a live pool cannot be resized -- the first caller sizes it, and + that caller is the component reading ``executor_workers`` from its own config. + + Returns: + The pool for that namespace. + """ + + executor = self._executors.get(namespace) + if executor is None: + executor = ThreadPoolExecutor( + max_workers=max_workers, + thread_name_prefix=f"blueprint-{namespace or 'root'}", + ) + self._executors[namespace] = executor + logger.info( + "Created thread pool for namespace '%s' with max_workers=%s", + namespace or ROOT_LABEL, + max_workers if max_workers is not None else "default", + ) + return executor + + def shutdown_executors(self) -> None: + """Shut down every thread pool this registry created, waiting for running work. + + Called from the application's shutdown and from :meth:`clear`. Without it the pools + outlive the application: a ``ThreadPoolExecutor``'s workers are non-daemon threads, so + the interpreter waits for them at exit and a container that should stop in a second + hangs until the last blocking call returns on its own. + """ + + for namespace, executor in self._executors.items(): + logger.info("Shutting down thread pool for namespace '%s'", namespace or ROOT_LABEL) + executor.shutdown(wait=True) + self._executors.clear() + + def add_cache(self, name: str, cache: CacheService) -> None: + """Register a cache under ``name``, replacing any cache already registered under it. + + Replacing is allowed rather than refused, because a cache is not tied to the build the + way a component is: one can legitimately be swapped or added after startup. It is logged + at WARNING, because the common way to arrive here twice with the same name is by + mistake -- two calls to ``with_cache()`` -- and the second would otherwise take over the + first silently. + + Args: + name: What to register it as. See :data:`DEFAULT_CACHE_NAME`. + cache: The cache to register. + """ + + if name in self._caches: + logger.warning( + "Cache '%s' is already registered as %s and is being replaced by %s", + name, + type(self._caches[name]).__name__, + type(cache).__name__, + ) + else: + logger.info("Registering cache '%s': %s", name, type(cache).__name__) + self._caches[name] = cache + + def get_cache(self, name: str = DEFAULT_CACHE_NAME) -> CacheService: + """Get the cache registered under ``name``. + + There is deliberately **no fallback to the default cache**. Caches are the one thing + agents must not share by accident (spec sec. 8): two independently written agents both + asking for ``"sessions"`` would silently share one store the moment they were grouped, + and only in production. A name that is not registered is therefore an error, not an + invitation to hand over some other cache. + + Args: + name: Which cache. Defaults to :data:`DEFAULT_CACHE_NAME`. + + Returns: + The cache registered under that name. + + Raises: + ValueError: If no cache is registered under ``name``. + """ + + cache = self._caches.get(name) + if cache is None: + registered = ", ".join(sorted(self._caches)) or "none" + raise ValueError(f"No cache registered as '{name}' (registered: {registered})") + if self._default_namespace: + return self._scoped_cache(name, cache) + return cache + + def _scoped_cache(self, name: str, cache: CacheService) -> CacheService: + """Return this view's agent-scoped lens on ``cache`` (spec sec. 8). + + Built here rather than at registration because the same backend serves every agent: one + cache, N views of it, each prefixing its own partitions. Cached per name so an agent + asking twice gets one object, which keeps the lens as cheap as the raw cache. + """ + # Imported here: agent_scoped_cache imports CacheService, which is a ServiceBase, which + # is a Component -- and component.py imports this module. + from ..services.infrastructure.agent_scoped_cache import AgentScopedCache + + agent = self._default_namespace + assert agent is not None # nosec B101 -- guarded by the caller; a view always has one + scoped = self._scoped_caches.get(name) + if scoped is None: + scoped = AgentScopedCache(cache, agent) + self._scoped_caches[name] = scoped + return scoped + + def get_all_caches(self) -> dict[str, CacheService]: + """Return every registered cache by name, as a copy. + + A copy so that a caller iterating the caches -- the health checks and the cache + management endpoints do -- cannot mutate the registry by accident. + """ + + return dict(self._caches) + @property def cache_service(self) -> CacheService: - """Get the registered cache service. + """The default cache. Retained as an alias for ``get_cache()`` (spec sec. 8). Returns: - The cache service instance + The cache registered as :data:`DEFAULT_CACHE_NAME` Raises: ValueError: If no cache service is registered """ - if self._cache_service is None: + if not self._caches: raise ValueError("No cache service registered") - return self._cache_service + return self.get_cache() @cache_service.setter def cache_service(self, cache_service: CacheService) -> None: - """Register a cache service. + """Register the default cache. Retained as an alias for ``add_cache()`` (spec sec. 8). Args: cache_service: The cache service instance to register """ - if self._cache_service is not None: - raise ValueError("Cache service already registered") - - logger.info("Registering cache service: %s", type(cache_service).__name__) - self._cache_service = cache_service + self.add_cache(DEFAULT_CACHE_NAME, cache_service) def add_component(self, name: str, component: Any) -> None: """Add a component to the registry. @@ -143,89 +402,125 @@ def update_component_name(self, old_name: str, new_name: str) -> None: logger.info("Updating component name from %s to %s", old_name, new_name) self._components[new_name] = self._components.pop(old_name) - def get_component(self, name_or_class: str | Any) -> Any: + def get_component(self, name_or_class: str | Any, namespace: str | None = None) -> Any: """Get a component from the registry. Args: name_or_class: Name of the component or class, that inherits from Component + namespace: Resolve for this agent: its own component first, then the root one. + ``None`` searches every namespace, which is what a single-agent application and + every pre-namespace caller does. Returns: An instance of a Component class + + Raises: + ValueError: if nothing matches, or if a class matches more than one component at the + same level. Ambiguity is an error rather than a first match: silently handing an + agent a neighbour's collaborator is the attribution the namespace exists to give. """ + namespace = self._effective_namespace(namespace) if not isinstance(name_or_class, str): - candidates = [name for name, component in self._components.items() if isinstance(component, name_or_class)] + # Every candidate, unfiltered -- resolve_for_namespace is what picks between the + # levels, so it has to see them all. Not get_components_by_type(..., None): on a + # view "None" means *this* view's namespace, so that call would hand the resolver + # only this agent's components and its root fallback could never fire. + candidates = self._all_of_type(name_or_class) + if namespace is not None: + # The class name, not its repr: these messages name what an agent was looking + # for ("No IOClientBase is registered for namespace 'orders' or at the root"), + # and "" in the middle of that sentence reads worse. + described = getattr(name_or_class, "__name__", str(name_or_class)) + return resolve_for_namespace(candidates, namespace, description=described) if len(candidates) == 0: raise ValueError(f"No components of type {name_or_class} found") - if len(candidates) == 1: - name_or_class = candidates[0] if len(candidates) > 1: - raise ValueError(f"Multiple components of type {name_or_class} found: {candidates}") - elif name_or_class not in self._components: - raise ValueError(f"Component with name {name_or_class} does not exist") - - return self._components[name_or_class] + names = [name for name, component in self._components.items() if isinstance(component, name_or_class)] + raise ValueError(f"Multiple components of type {name_or_class} found: {names}") + return candidates[0] + + component = self._lookup(name_or_class, namespace) + if component is None: + in_namespace = "" if namespace is None else f" in namespace '{namespace or ROOT_LABEL}' or at the root" + raise ValueError(f"Component with name {name_or_class} does not exist{in_namespace}") + return component - def get_components_by_type(self, component_type: Any) -> list[Any]: # + def get_components_by_type(self, component_type: Any, namespace: str | None = None) -> list[Any]: """Get all components from the registry of a specific type. Args: component_type: The type of the components to retrieve + namespace: Return only this agent's components. Filtered on the component's own + ``namespace`` rather than on its registry name, so a component registered under + an explicit name is still attributed correctly. ``None`` returns every + namespace, which is what iteration over the whole application wants. Returns: A list of components """ - return [component for component in self._components.values() if isinstance(component, component_type)] + namespace = self._effective_namespace(namespace) + return [ + component + for component in self._components.values() + if isinstance(component, component_type) and (namespace is None or namespace_of(component) == namespace) + ] - def get_component_names_by_type(self, component_type: Any) -> list[str]: # + def get_component_names_by_type(self, component_type: Any, namespace: str | None = None) -> list[str]: """Get all component names from the registry of a specific type. Args: component_type: The type of the components to retrieve + namespace: Return only this agent's components; ``None`` returns every namespace. Returns: A list of component names """ - return [name for name, component in self._components.items() if isinstance(component, component_type)] + namespace = self._effective_namespace(namespace) + return [ + name + for name, component in self._components.items() + if isinstance(component, component_type) and (namespace is None or namespace_of(component) == namespace) + ] - def has_component(self, name_or_class: str | Any) -> bool: + def has_component(self, name_or_class: str | Any, namespace: str | None = None) -> bool: """Check if a component is registered. Args: name_or_class: Name of the component or class, that inherits from Component + namespace: Look in this agent, then the root, for a name; for a class, look only in + this agent. ``None`` looks everywhere. Returns: True if component is registered, False otherwise """ if isinstance(name_or_class, str): - return name_or_class in self._components - else: - return any(isinstance(component, name_or_class) for component in self._components.values()) + return self._lookup(name_or_class, namespace) is not None + return bool(self.get_components_by_type(name_or_class, namespace)) - def has_component_of_type(self, component_type: Any, name: str | None = None) -> bool: + def has_component_of_type(self, component_type: Any, name: str | None = None, namespace: str | None = None) -> bool: """Check if a component is registered. Args: component_type: Type of the component name: Name of the component (optional) + namespace: Restrict the question to this agent; ``None`` asks about every namespace. Returns: True if component is registered, False otherwise """ if name is not None: - if name in self._components: - if not isinstance(self._components[name], component_type): - raise ValueError(f"Component with name {name} is not of type {component_type}") - else: - return True - else: + component = self._lookup(name, namespace) + if component is None: raise ValueError(f"No component with name {name} registered") - else: - return any(isinstance(component, component_type) for component in self._components.values()) + if not isinstance(component, component_type): + raise ValueError(f"Component with name {name} is not of type {component_type}") + return True + return bool(self.get_components_by_type(component_type, namespace)) def clear_components(self) -> None: """Clear all registered components (useful for testing).""" @@ -242,20 +537,26 @@ def clear(self) -> None: logger.info("Clearing all components from registry") self.clear_components() - if self._cache_service is not None: - self._cache_service.clear() - self._cache_service = None + self.shutdown_executors() + for name, cache in self._caches.items(): + logger.info("Clearing cache '%s'", name) + cache.clear() + self._caches.clear() + + def has_cache(self, name: str = DEFAULT_CACHE_NAME) -> bool: + """Check whether a cache is registered under ``name``. - def has_cache(self) -> bool: - """Check if a cache service is registered. + Args: + name: Which cache. Defaults to :data:`DEFAULT_CACHE_NAME`, so an existing caller + asking whether "the" cache exists keeps its meaning. Returns: - True if cache service is registered, False otherwise + True if a cache is registered under that name, False otherwise """ - return self._cache_service is not None + return name in self._caches - def has_event_handler(self, name: str | None = None) -> bool: + def has_event_handler(self, name: str | None = None, namespace: str | None = None) -> bool: """Check if a handler is registered. Args: @@ -265,14 +566,18 @@ def has_event_handler(self, name: str | None = None) -> bool: True if handler is registered, False otherwise """ - return self.has_component_of_type(EventHandlerBase, name) + return self.has_component_of_type(EventHandlerBase, name, namespace) - def get_event_handler(self) -> list[EventHandlerBase]: - """Get all registered handlers.""" + def get_event_handler(self, namespace: str | None = None) -> list[EventHandlerBase]: + """Get all registered handlers. + + Args: + namespace: Restrict to this agent; ``None`` (the default) is every namespace. + """ - return self.get_components_by_type(EventHandlerBase) + return self.get_components_by_type(EventHandlerBase, namespace) - def has_agents(self, name: str | None = None) -> bool: + def has_agents(self, name: str | None = None, namespace: str | None = None) -> bool: """Check if an agent is registered. Args: @@ -282,13 +587,14 @@ def has_agents(self, name: str | None = None) -> bool: True if at least one agent is registered, False otherwise """ - return self.has_component_of_type(AgentRuntime, name) + return self.has_component_of_type(AgentRuntime, name, namespace) - def get_agent(self, name: str) -> AgentRuntime: + def get_agent(self, name: str, namespace: str | None = None) -> AgentRuntime: """Get a registered agent by name. Args: name: Name of the agent + namespace: Resolve for this agent -- its own first, then the root one. Returns: The AgentRuntime instance @@ -297,17 +603,21 @@ def get_agent(self, name: str) -> AgentRuntime: ValueError: If no agent with that name is registered or the component is not an AgentRuntime """ - component = self.get_component(name) + component = self.get_component(name, namespace) if not isinstance(component, AgentRuntime): raise ValueError(f"Component '{name}' is not an AgentRuntime") return component - def get_agents(self) -> list[str]: - """Get list of all registered agent names.""" + def get_agents(self, namespace: str | None = None) -> list[str]: + """Get list of all registered agent names. - return self.get_component_names_by_type(AgentRuntime) + Args: + namespace: Restrict to this agent; ``None`` (the default) is every namespace. + """ + + return self.get_component_names_by_type(AgentRuntime, namespace) - def has_rest_apis(self, name: str | None = None) -> bool: + def has_rest_apis(self, name: str | None = None, namespace: str | None = None) -> bool: """Check if a REST API is registered. Args: @@ -317,18 +627,23 @@ def has_rest_apis(self, name: str | None = None) -> bool: True if REST API is registered, False otherwise """ - return self.has_component_of_type(RestApiBase, name) + return self.has_component_of_type(RestApiBase, name, namespace) - def get_rest_api_names(self) -> list[str]: - """Get list of all registered REST API names.""" + def get_rest_api_names(self, namespace: str | None = None) -> list[str]: + """Get list of all registered REST API names. + + Args: + namespace: Restrict to this agent; ``None`` (the default) is every namespace. + """ - return self.get_component_names_by_type(RestApiBase) + return self.get_component_names_by_type(RestApiBase, namespace) - def get_rest_api(self, name_or_class: str | type[RestApiBase]) -> RestApiBase: + def get_rest_api(self, name_or_class: str | type[RestApiBase], namespace: str | None = None) -> RestApiBase: """Get a registered REST API by name or class. Args: name_or_class: Name string or concrete REST API class + namespace: Resolve for this agent -- its own first, then the root one. Returns: The RestApiBase instance @@ -337,14 +652,18 @@ def get_rest_api(self, name_or_class: str | type[RestApiBase]) -> RestApiBase: ValueError: If not found, wrong type, or multiple matches exist """ - return self._resolve_single(name_or_class, RestApiBase) # type: ignore[type-abstract] + return self._resolve_single(name_or_class, RestApiBase, namespace) # type: ignore[type-abstract] - def get_rest_apis(self) -> list[RestApiBase]: - """Get all registered REST APIs.""" + def get_rest_apis(self, namespace: str | None = None) -> list[RestApiBase]: + """Get all registered REST APIs. - return self.get_components_by_type(RestApiBase) + Args: + namespace: Restrict to this agent; ``None`` (the default) is every namespace. + """ + + return self.get_components_by_type(RestApiBase, namespace) - def has_services(self, name: str | None = None) -> bool: + def has_services(self, name: str | None = None, namespace: str | None = None) -> bool: """Check if a business service is registered. Args: @@ -354,13 +673,14 @@ def has_services(self, name: str | None = None) -> bool: True if business service is registered, False otherwise """ - return self.has_component_of_type(ServiceBase, name) + return self.has_component_of_type(ServiceBase, name, namespace) - def get_service(self, name_or_class: str | type[ServiceT]) -> ServiceT: + def get_service(self, name_or_class: str | type[ServiceT], namespace: str | None = None) -> ServiceT: """Get a registered service by name or class. Args: name_or_class: Name string or concrete service class + namespace: Resolve for this agent -- its own first, then the root one. Returns: The ServiceBase instance @@ -369,14 +689,18 @@ def get_service(self, name_or_class: str | type[ServiceT]) -> ServiceT: ValueError: If not found, wrong type, or multiple matches exist """ - return self._resolve_single(name_or_class, ServiceBase) # type: ignore + return self._resolve_single(name_or_class, ServiceBase, namespace) # type: ignore - def get_services(self) -> list[ServiceBase]: - """Get all registered business services.""" + def get_services(self, namespace: str | None = None) -> list[ServiceBase]: + """Get all registered business services. + + Args: + namespace: Restrict to this agent; ``None`` (the default) is every namespace. + """ - return self.get_components_by_type(ServiceBase) + return self.get_components_by_type(ServiceBase, namespace) - def has_schedulers(self, name: str | None = None) -> bool: + def has_schedulers(self, name: str | None = None, namespace: str | None = None) -> bool: """Check if a scheduler is registered. Args: @@ -386,13 +710,14 @@ def has_schedulers(self, name: str | None = None) -> bool: True if scheduler is registered, False otherwise """ - return self.has_component_of_type(SchedulerBase, name) + return self.has_component_of_type(SchedulerBase, name, namespace) - def get_scheduler(self, name_or_class: str | type[SchedulerBase]) -> SchedulerBase: + def get_scheduler(self, name_or_class: str | type[SchedulerBase], namespace: str | None = None) -> SchedulerBase: """Get a registered scheduler by name or class. Args: name_or_class: Name string or concrete scheduler class + namespace: Resolve for this agent -- its own first, then the root one. Returns: The SchedulerBase instance @@ -401,18 +726,23 @@ def get_scheduler(self, name_or_class: str | type[SchedulerBase]) -> SchedulerBa ValueError: If not found, wrong type, or multiple matches exist """ - return self._resolve_single(name_or_class, SchedulerBase) # type: ignore[type-abstract] + return self._resolve_single(name_or_class, SchedulerBase, namespace) # type: ignore[type-abstract] - def get_schedulers(self) -> list[SchedulerBase]: - """Get all registered schedulers.""" + def get_schedulers(self, namespace: str | None = None) -> list[SchedulerBase]: + """Get all registered schedulers. - return self.get_components_by_type(SchedulerBase) + Args: + namespace: Restrict to this agent; ``None`` (the default) is every namespace. + """ + + return self.get_components_by_type(SchedulerBase, namespace) - def get_client(self, name_or_class: str | type[ClientBase]) -> ClientBase: + def get_client(self, name_or_class: str | type[ClientBase], namespace: str | None = None) -> ClientBase: """Get a registered client by name or class. Args: name_or_class: Name string or concrete client class + namespace: Resolve for this agent -- its own first, then the root one. Returns: The ClientBase instance @@ -421,13 +751,14 @@ def get_client(self, name_or_class: str | type[ClientBase]) -> ClientBase: ValueError: If not found, wrong type, or multiple matches exist """ - return self._resolve_single(name_or_class, ClientBase) # type: ignore[type-abstract] + return self._resolve_single(name_or_class, ClientBase, namespace) # type: ignore[type-abstract] - def get_io_client(self, name_or_class: str | type[IOClientBase]) -> IOClientBase: + def get_io_client(self, name_or_class: str | type[IOClientBase], namespace: str | None = None) -> IOClientBase: """Get a registered IO client by name or class. Args: name_or_class: Name string or concrete IO client class + namespace: Resolve for this agent -- its own first, then the root one. Returns: The IOClientBase instance @@ -436,13 +767,14 @@ def get_io_client(self, name_or_class: str | type[IOClientBase]) -> IOClientBase ValueError: If not found, wrong type, or multiple matches exist """ - return self._resolve_single(name_or_class, IOClientBase) # type: ignore[type-abstract] + return self._resolve_single(name_or_class, IOClientBase, namespace) # type: ignore[type-abstract] - def get_ai_client(self, name_or_class: str | type[AIClientBase]) -> AIClientBase: + def get_ai_client(self, name_or_class: str | type[AIClientBase], namespace: str | None = None) -> AIClientBase: """Get a registered AI client by name or class. Args: name_or_class: Name string or concrete AI client class + namespace: Resolve for this agent -- its own first, then the root one. Returns: The AIClientBase instance @@ -451,19 +783,31 @@ def get_ai_client(self, name_or_class: str | type[AIClientBase]) -> AIClientBase ValueError: If not found, wrong type, or multiple matches exist """ - return self._resolve_single(name_or_class, AIClientBase) # type: ignore[type-abstract] + return self._resolve_single(name_or_class, AIClientBase, namespace) # type: ignore[type-abstract] + + def get_clients(self, namespace: str | None = None) -> list[ClientBase]: + """Get all registered clients (IO and AI). + + Args: + namespace: Restrict to this agent; ``None`` (the default) is every namespace. + """ + + return self.get_components_by_type(ClientBase, namespace) - def get_clients(self) -> list[ClientBase]: - """Get all registered clients (IO and AI).""" + def get_io_clients(self, namespace: str | None = None) -> list[IOClientBase]: + """Get all registered IO transport clients (Dapr, NATS, etc.). - return self.get_components_by_type(ClientBase) + Args: + namespace: Restrict to this agent; ``None`` (the default) is every namespace. + """ - def get_io_clients(self) -> list[IOClientBase]: - """Get all registered IO transport clients (Dapr, NATS, etc.).""" + return self.get_components_by_type(IOClientBase, namespace) - return self.get_components_by_type(IOClientBase) + def get_ai_clients(self, namespace: str | None = None) -> list[AIClientBase]: + """Get all registered AI provider clients (vLLM, OpenAI, etc.). - def get_ai_clients(self) -> list[AIClientBase]: - """Get all registered AI provider clients (vLLM, OpenAI, etc.).""" + Args: + namespace: Restrict to this agent; ``None`` (the default) is every namespace. + """ - return self.get_components_by_type(AIClientBase) + return self.get_components_by_type(AIClientBase, namespace) diff --git a/src/blueprint/agents/services/eventing/event_publishing_service.py b/src/blueprint/agents/services/eventing/event_publishing_service.py index 9646b761..54fe6f7c 100644 --- a/src/blueprint/agents/services/eventing/event_publishing_service.py +++ b/src/blueprint/agents/services/eventing/event_publishing_service.py @@ -7,7 +7,7 @@ from opentelemetry import trace from ...component.component import traced -from ...component.namespace import ROOT_NAMESPACE, resolve_for_namespace +from ...component.namespace import ROOT_NAMESPACE from ..service_base import ServiceBase from ...clients.io.io_client_base import IOClientBase from ...models import GenericCloudEvent @@ -51,12 +51,14 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: self._pub_config: EventPublishingConfig | None = None async def on_startup(self) -> None: - """Resolve this namespace's IO client and load event publishing configuration.""" - self._client = resolve_for_namespace( - self.registry.get_io_clients(), - self.namespace, - description="IO transport client", - ) + """Resolve this namespace's IO client and load event publishing configuration. + + The resolution is the registry view's now: ``self.registry`` answers for this + service's namespace, so ``get_io_client`` returns this agent's transport and falls back + to a root one. It used to call ``resolve_for_namespace`` here by hand, because P6 needed + namespace resolution before the registry could do it. + """ + self._client = self.registry.get_io_client(IOClientBase) self._pub_config = self.config.get_event_publishing_config() async def on_shutdown(self) -> None: diff --git a/src/blueprint/agents/services/infrastructure/agent_scoped_cache.py b/src/blueprint/agents/services/infrastructure/agent_scoped_cache.py new file mode 100644 index 00000000..995daec7 --- /dev/null +++ b/src/blueprint/agents/services/infrastructure/agent_scoped_cache.py @@ -0,0 +1,157 @@ +"""A per-agent lens on one shared cache backend (spec sec. 8).""" + +import logging +from collections.abc import Iterator +from typing import Any + +from .cache_service import CacheService + +logger = logging.getLogger(__name__) + +AGENT_SEPARATOR = "." +"""Separates the agent from the partition it asked for, inside one cache. + +A ``.`` rather than a ``:`` because ``:`` is already the separator between the partition and the +hashed key (``cache_key_mixin._make_key``), and ``list_namespaces`` splits on the first one -- so +a ``:`` here would make ``orders:prices`` read back as the partition ``orders``. A namespace +cannot contain ``.`` (its alphabet is ``[a-z][a-z0-9_]*``), so stripping ``.`` back off is +unambiguous whatever the agent called its own partition. +""" + + +class AgentScopedCache(CacheService): + """One agent's view of a shared cache, isolating its keys from its neighbours'. + + Spec sec. 8: two independently written agents both storing under ``"sessions"`` must not + share a store the moment they are grouped. This is what enforces that, and it does so + *without a second backend*: every call has its partition prefixed with the agent's + namespace, so ``orders`` writing ``sessions`` lands in ``orders.sessions`` and ``billing`` + writing the same name lands in ``billing.sessions``. + + **Why prefix the partition rather than register a cache per agent.** A cache backend is a + filesystem directory (``DiskCacheService``) or a connection (``RedisCacheService``). One + backend per agent per name would multiply both, and on Kubernetes the directory is the + binding constraint: a pod with a read-only root filesystem can write only where a volume is + mounted, and that mount is declared in the pod spec, not discovered at runtime. Prefixing + keys means grouping agents changes no path, needs no additional mount, and keeps one + ``size_limit`` budget over one volume rather than N budgets over one. + + The agent never sees this. ``Component.registry`` hands a namespaced component its + namespace's registry view, and that view's ``get_cache`` returns this object, so a service + writing ``self.registry.cache_service.set(key, value, namespace="prices")`` is isolated + without naming a namespace. A **root** component gets the raw backend, which is also the + opt-in for a deliberately shared cache. + """ + + def __init__(self, cache: CacheService, agent: str) -> None: + """Wrap ``cache`` for ``agent``. + + Args: + cache: The shared backend. Not owned: this object never closes it. + agent: The namespace to prefix partitions with. Must not be empty -- the root + namespace uses the backend directly, so wrapping it would add a ``.`` prefix + that changes where an existing single-agent application's keys live. + + Raises: + ValueError: if ``agent`` is empty. + """ + if not agent: + raise ValueError( + "AgentScopedCache needs an agent namespace: the root namespace reads the cache backend directly, and " + "wrapping it would move every key of an existing application." + ) + super().__init__(name=f"{agent}_scoped_cache", should_register=False) + self._cache = cache + self._agent = agent + + @property + def agent(self) -> str: + """The namespace whose keys this view reads and writes.""" + return self._agent + + @property + def backend(self) -> CacheService: + """The shared cache underneath, for the framework code that owns it.""" + return self._cache + + def _scoped(self, namespace: str) -> str: + """Return the partition ``namespace`` becomes for this agent.""" + return f"{self._agent}{AGENT_SEPARATOR}{namespace}" + + def _owns(self, namespace: str) -> bool: + """Whether a partition in the shared cache belongs to this agent.""" + return namespace.startswith(f"{self._agent}{AGENT_SEPARATOR}") + + async def on_startup(self) -> None: + """Nothing to start: the backend is started by whoever registered it.""" + + async def on_shutdown(self) -> None: + """Nothing to stop: the backend outlives any one agent's view of it.""" + + def get(self, key: str | list[str] | dict[str, Any], namespace: str = "default") -> Any | None: + return self._cache.get(key, self._scoped(namespace)) + + def set( + self, + key: str | list[str] | dict[str, Any], + value: Any, + namespace: str = "default", + ttl: int | None = None, + ) -> None: + self._cache.set(key, value, self._scoped(namespace), ttl) + + def delete(self, key: str | list[str] | dict[str, Any], namespace: str = "default") -> bool: + return self._cache.delete(key, self._scoped(namespace)) + + def exists(self, key: str | list[str] | dict[str, Any], namespace: str = "default") -> bool: + return self._cache.exists(key, self._scoped(namespace)) + + def claim(self, key: str | list[str] | dict[str, Any], value: Any, namespace: str = "default", ttl: int | None = None) -> bool: + return self._cache.claim(key, value, self._scoped(namespace), ttl) + + def clear(self, namespace: str | None = None) -> None: + """Clear one of this agent's partitions, or all of them. + + ``None`` means *this agent's* partitions, never the whole cache -- the backend's own + ``clear(None)`` would take its neighbours' data with it, which is the accident this + class exists to prevent. + """ + if namespace is not None: + self._cache.clear(self._scoped(namespace)) + return + for owned in (name for name in self._cache.list_namespaces() if self._owns(name)): + self._cache.clear(owned) + + def list_namespaces(self) -> list[str]: + """This agent's partitions, named as it named them.""" + prefix = f"{self._agent}{AGENT_SEPARATOR}" + return [name.removeprefix(prefix) for name in self._cache.list_namespaces() if self._owns(name)] + + def list_values(self, namespace: str = "default", limit: int = 100, offset: int = 0) -> Iterator[Any]: + return self._cache.list_values(self._scoped(namespace), limit, offset) + + def get_stats(self) -> dict[str, Any]: + """The backend's statistics, which are process-wide rather than per agent. + + Size, hit counts and eviction are properties of the one store every agent shares, so + there is nothing per-agent to report and nothing gained by pretending otherwise. The + agent is named in the result so a reader knows whose view produced it. + """ + return {**self._cache.get_stats(), "agent": self._agent} + + def hash(self, value: str | list[str] | dict[str, Any]) -> str: + return self._cache.hash(value) + + def close(self) -> None: + """Refuse: the backend belongs to the process, not to one agent. + + Closing it here would take every other agent's cache down with it, and the caller would + have no way to know it had happened. + + Raises: + RuntimeError: always. + """ + raise RuntimeError( + f"Namespace '{self._agent}' tried to close the cache, which is shared with every other agent in this " + "process. The application closes it, through the registry that owns it." + ) diff --git a/src/blueprint/agents/services/infrastructure/cache_backend_factory.py b/src/blueprint/agents/services/infrastructure/cache_backend_factory.py index c68defff..7c6bc86f 100644 --- a/src/blueprint/agents/services/infrastructure/cache_backend_factory.py +++ b/src/blueprint/agents/services/infrastructure/cache_backend_factory.py @@ -1,31 +1,132 @@ """Factory for selecting the appropriate cache backend from configuration.""" import logging +import re +from pathlib import PurePosixPath +from blueprint.agents.component.registry import DEFAULT_CACHE_NAME from blueprint.agents.models.config import CacheConfig from blueprint.agents.services.infrastructure.redis_url_utils import _sanitize_redis_url from blueprint.agents.services.infrastructure.cache_service import CacheService logger = logging.getLogger(__name__) +_ALLOWED_CACHE_NAME = re.compile(r"\A[a-z0-9][a-z0-9_.-]*\Z") +"""What a cache name may look like. See :meth:`CacheBackendFactory._validate_name`.""" + class CacheBackendFactory: - """Instantiates the correct CacheService implementation based on CacheConfig.backend.""" + """Instantiates the correct CacheService implementation based on CacheConfig.backend. + + **A cache name is turned into isolated storage here**, in the same place the backend is + chosen, and that is deliberate rather than incidental. A process may hold several caches + registered under different names (spec sec. 8), and two of them sharing one store are one + cache under two names -- with the name, the only thing meant to tell them apart, quietly + doing nothing. How a backend isolates is knowledge only the backend has: the disk cache + separates by directory, Redis by key prefix, and a future backend by something else again. + So each ``_create_*`` scopes what its own backend needs, and adding a backend means + answering that question in the method that creates it -- not discovering later that a + caller somewhere else was supposed to have answered it. + """ @staticmethod - def create(config: CacheConfig, enable_locking: bool = True) -> CacheService: + def create(config: CacheConfig, enable_locking: bool = True, name: str = DEFAULT_CACHE_NAME) -> CacheService: + """Create the cache called ``name``, on the backend ``config`` selects. + + Args: + config: The application's cache configuration, as loaded. It is *not* pre-scoped: + scoping is per backend and happens below. + enable_locking: File-based locking, for the disk backend. + name: Which cache this is. :data:`DEFAULT_CACHE_NAME` reproduces exactly what a + single-cache application has always got -- same directory, same Redis + keyspace, same registry name. + + Returns: + The cache service, already registered in the component registry under the name + :meth:`_component_name` derives. + + Raises: + ValueError: if ``name`` cannot serve as a cache name. + """ + CacheBackendFactory._validate_name(name) if config.backend == "redis": - return CacheBackendFactory._create_redis(config, enable_locking) - return CacheBackendFactory._create_disk(config, enable_locking) + return CacheBackendFactory._create_redis(config, enable_locking, name) + return CacheBackendFactory._create_disk(config, enable_locking, name) + + @staticmethod + def _validate_name(name: str) -> None: + """Reject a cache name that cannot serve as one. + + The name becomes a filesystem path segment and a segment of a Redis key prefix, so + ``"../evil"`` would write outside the configured cache directory. Lower case only, and + not for tidiness: a directory whose name differs only by case is one directory on a + developer's machine and two on a Linux node, so ``Sessions`` and ``sessions`` would be + one cache locally and two in production. + + Raises: + ValueError: if ``name`` is outside the allowed alphabet. + """ + if not _ALLOWED_CACHE_NAME.match(name): + raise ValueError( + f"Cache name {name!r} is not a legal cache name: it must match [a-z0-9][a-z0-9_.-]*. A cache name " + "becomes a directory under the configured cache_dir and a segment of the Redis key prefix, so it " + "cannot contain a path separator, and it is lower-case only because two names differing by case are " + "one directory on a case-insensitive filesystem and two on Linux." + ) + + @staticmethod + def _component_name(name: str) -> str | None: + """Return the registry name the cache service registers under, or ``None`` to derive it. + + A cache service is a ``Component``, so two of them would collide on the one name derived + from their class. The default cache keeps that derived name -- ``disk_cache_service`` -- + because existing lookups and health entries already use it. + + ``cache_`` rather than ``_`` because ``fallback_to_local`` can swap + ``RedisCacheService`` for ``DiskCacheService`` at construction: a registry key that + depends on whether Redis answered the startup ping is worse than one that does not name + the backend at all. + """ + return None if name == DEFAULT_CACHE_NAME else f"cache_{name}" + + @staticmethod + def _scoped_cache_dir(config: CacheConfig, name: str) -> str: + """Return the directory the disk cache called ``name`` stores in. + + ``/`` -- a *subdirectory* of the configured directory and not a sibling + of it, which is the only form that is always writable. A deployment may mount its volume + at ``cache.cache_dir`` itself, and under ``readOnlyRootFilesystem`` nothing outside the + mount can be created; see "Writable Cache Directory" in ``docs/guides/deployment.md``. + The cost is that a named cache's directory sits inside the default cache's own store. + diskcache ignores directories it did not create, and the alternative is a path that + fails in production only. + """ + if name == DEFAULT_CACHE_NAME: + return config.cache_dir + return str(PurePosixPath(config.cache_dir.replace("\\", "/")) / name) + + @staticmethod + def _scoped_key_prefix(config: CacheConfig, name: str) -> str: + """Return the Redis key prefix the cache called ``name`` writes under. + + On Redis the prefix is the whole of the separation: ``RedisCacheService`` scopes every + key by ``key_prefix`` and nothing else, so two caches named ``sessions`` and ``prompts`` + against one Redis with one configured prefix would write the same keys. The disk + backend's directory has no analogue here, so without this the name would isolate + nothing at all. + """ + if name == DEFAULT_CACHE_NAME: + return config.key_prefix + return f"{config.key_prefix}:{name}" if config.key_prefix else name @staticmethod - def _create_redis(config: CacheConfig, enable_locking: bool) -> CacheService: + def _create_redis(config: CacheConfig, enable_locking: bool, name: str = DEFAULT_CACHE_NAME) -> CacheService: try: from blueprint.agents.services.infrastructure.redis_cache_service import RedisCacheService except ImportError as e: if config.fallback_to_local: logger.warning("Redis extra not installed, falling back to DiskCacheService: %s", e) - return CacheBackendFactory._create_disk(config, enable_locking) + return CacheBackendFactory._create_disk(config, enable_locking, name) raise resolved_url = config.redis_url or "redis://localhost:6379/0" @@ -35,9 +136,10 @@ def _create_redis(config: CacheConfig, enable_locking: bool) -> CacheService: password=config.redis_password, db=config.redis_db, tls=config.redis_tls, - key_prefix=config.key_prefix, + key_prefix=CacheBackendFactory._scoped_key_prefix(config, name), default_ttl=config.default_ttl, fallback_to_local=config.fallback_to_local, + component_name=CacheBackendFactory._component_name(name), ) # Probe the connection synchronously so a "RedisCacheService" instance @@ -55,19 +157,22 @@ def _create_redis(config: CacheConfig, enable_locking: bool) -> CacheService: _sanitize_redis_url(resolved_url), e, ) - return CacheBackendFactory._create_disk(config, enable_locking) + # The unscoped config plus the name, never the redis-scoped one: the fallback is + # a different backend and needs its own isolation -- a directory, not a prefix. + return CacheBackendFactory._create_disk(config, enable_locking, name) raise return service @staticmethod - def _create_disk(config: CacheConfig, enable_locking: bool = True) -> CacheService: + def _create_disk(config: CacheConfig, enable_locking: bool = True, name: str = DEFAULT_CACHE_NAME) -> CacheService: from blueprint.agents.services.infrastructure.cache_service import DiskCacheService return DiskCacheService( - cache_dir=config.cache_dir, + cache_dir=CacheBackendFactory._scoped_cache_dir(config, name), size_limit=config.size_limit, eviction_policy=config.eviction_policy, enable_locking=enable_locking, default_ttl=config.default_ttl, + component_name=CacheBackendFactory._component_name(name), ) diff --git a/src/blueprint/agents/services/infrastructure/cache_service.py b/src/blueprint/agents/services/infrastructure/cache_service.py index 4bd41f92..5aed27b5 100644 --- a/src/blueprint/agents/services/infrastructure/cache_service.py +++ b/src/blueprint/agents/services/infrastructure/cache_service.py @@ -183,6 +183,7 @@ def __init__( eviction_policy: str = "least-recently-used", enable_locking: bool = True, default_ttl: int | None = None, + component_name: str | None = None, ): """Initialize DiskCacheService. @@ -195,10 +196,26 @@ def __init__( called without an explicit ``ttl``. ``None`` means no expiration. Mirrors ``RedisCacheService`` so the choice of backend does not silently change TTL behaviour. + component_name: Registry name to use instead of the derived ``disk_cache_service``. + Needed because a process may hold several named caches (spec sec. 8) and two + instances of this class would otherwise collide on the one derived name. The + default keeps an existing single-cache application's registry key unchanged. """ - super().__init__() + super().__init__(name=component_name) self.cache_dir = Path(cache_dir) - self.cache_dir.mkdir(parents=True, exist_ok=True) + try: + self.cache_dir.mkdir(parents=True, exist_ok=True) + except OSError as error: + # The common production failure, and the least self-explanatory: a container image + # whose working directory is root-owned, or a pod with `readOnlyRootFilesystem: true` + # and nothing mounted here. Both surface as an errno from deep inside a constructor, + # so the cause and the fix are named here instead. + raise RuntimeError( + f"Cache directory '{self.cache_dir}' could not be created ({error.strerror}). A container cannot " + "create it at runtime unless the path is writable by the user the process runs as: create it in the " + "image and chown it, mount a volume there if the root filesystem is read-only, point " + "'cache.cache_dir' somewhere writable, or use the redis cache backend, which needs no filesystem." + ) from error self._size_limit = size_limit self._eviction_policy = eviction_policy diff --git a/src/blueprint/agents/services/infrastructure/redis_cache_service.py b/src/blueprint/agents/services/infrastructure/redis_cache_service.py index e20944ff..bcaffbe0 100644 --- a/src/blueprint/agents/services/infrastructure/redis_cache_service.py +++ b/src/blueprint/agents/services/infrastructure/redis_cache_service.py @@ -36,8 +36,12 @@ def __init__( key_prefix: str = "", default_ttl: int | None = None, fallback_to_local: bool = False, + component_name: str | None = None, ) -> None: - super().__init__() + # component_name: registry name to use instead of the derived 'redis_cache_service'. + # A process may hold several named caches (spec sec. 8), and two instances of this + # class would otherwise collide on the one derived name. None keeps the existing key. + super().__init__(name=component_name) self._redis_url = redis_url # Cached credential-free variant for logs, /readiness payloads, and stats. self._safe_redis_url = _sanitize_redis_url(redis_url) diff --git a/src/blueprint/agents/services/service_base.py b/src/blueprint/agents/services/service_base.py index f6a0ba4c..b261bd90 100644 --- a/src/blueprint/agents/services/service_base.py +++ b/src/blueprint/agents/services/service_base.py @@ -12,7 +12,7 @@ class ServiceBase(Component, ABC): are inherited from Component. """ - def __init__(self, name: str | None = None, namespace: str = ROOT_NAMESPACE) -> None: + def __init__(self, name: str | None = None, namespace: str = ROOT_NAMESPACE, *, should_register: bool = True) -> None: """Initialize the business service. Args: @@ -20,5 +20,11 @@ def __init__(self, name: str | None = None, namespace: str = ROOT_NAMESPACE) -> ``Component``, which registers under it. namespace: The agent this service belongs to; ``""`` for the root namespace. Forwarded to ``Component``, which validates it and qualifies the name. + should_register: Whether to add this instance to the registry. Keyword-only and + default ``True``, so no existing subclass changes. ``False`` is for a + service-shaped object that is not a collaborator anyone looks up -- + ``AgentScopedCache``, which is one agent's lens on a registered cache and + would otherwise register a second entry per agent. ``RestApiBase`` has taken + the same parameter since before namespaces. """ - super().__init__(name=name, namespace=namespace) + super().__init__(should_register=should_register, name=name, namespace=namespace) diff --git a/tests/unit/agents/app_builder/TESTS.md b/tests/unit/agents/app_builder/TESTS.md index d8c04d89..63bf2d90 100644 --- a/tests/unit/agents/app_builder/TESTS.md +++ b/tests/unit/agents/app_builder/TESTS.md @@ -8,6 +8,7 @@ Test coverage for `src/blueprint/agents/app_builder.py`. | File | Class under test | What is covered | |---|---|---| +| `test_agent_registration.py` | `AgentRegistration`, `AppBuilder.with_registration` | Nothing is constructed at declaration time; declaration order, names and constructor kwargs survive the round trip; no `with_cache`; an already-built component and a non-callable are refused; root application keeps the bare registry name and a namespace qualifies it; one declaration applied twice yields two independently configured agents (each with its own scoped `Config` view); the ambient namespace is left behind afterwards; factories are deferred and called inside the namespace | | `test_app_builder.py` | `AppBuilder` | `with_handler` (TypeError for non-subclass, class instantiated, instance accepted without re-instantiation, name propagated, returns self); `with_service`/`with_agent`/`with_scheduler`/`with_rest_api` (instance accepted, returns self); `with_cache` (enabled creates DiskCacheService, disabled skips config read); `with_health_checker` (stored pending before build, added immediately after build, multiple checkers accumulated, returns self); `build()` (event_bus=dapr/nats/unknown/no-handlers routing, EventPublishingService conditional on IO clients, pending health checkers wired, returns FastAPI instance); scheduler wiring (an event-mode scheduler is wired before the transport decision, so its tick handler is what causes a NATS client and eventing endpoint to be created; an in-process scheduler alone creates neither); the publish/consume split (`event_publishing_enabled` off means no client; on means a client with no eventing component and no `EventProcessingService`; the string form an environment variable delivers; rejections for no transport, `"sessions"` and a non-boolean; and a consuming application still publishing without the key) | --- diff --git a/tests/unit/agents/app_builder/test_agent_registration.py b/tests/unit/agents/app_builder/test_agent_registration.py new file mode 100644 index 00000000..5b4f2afc --- /dev/null +++ b/tests/unit/agents/app_builder/test_agent_registration.py @@ -0,0 +1,217 @@ +"""Unit tests for ``AgentRegistration`` and ``AppBuilder.with_registration``. + +What these are really testing is the constraint the design exists for: one declaration, no +namespace anywhere in it or in the components it names, applied either alone or once per agent. +""" + +from pathlib import Path +from typing import Any + +import pytest + +from blueprint.agents.app_builder import AgentRegistration, AppBuilder +from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import ROOT_NAMESPACE, current_namespace +from blueprint.agents.config import Config +from blueprint.agents.io.api.rest_api_base import RestApiBase +from blueprint.agents.services.service_base import ServiceBase + +from .conftest import StubHandler + + +class OrderService(ServiceBase): + """A service written the way a project writes one: no namespace, no arguments.""" + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class ConfiguredService(ServiceBase): + """A service that takes constructor arguments, to check they survive the round trip.""" + + def __init__(self, retries: int = 0) -> None: + super().__init__() + self.retries = retries + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class OrderApi(RestApiBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +@pytest.fixture +def two_agent_config(tmp_path: Path) -> Config: + """A settings tree with a root and two agents, injected as the shared component config.""" + settings = tmp_path / "settings.toml" + content = """ + [development] + app_name = "root-app" + app_port = 8000 + model_name = "root-model" + + [development.orders] + app_name = "orders" + model_name = "orders-model" + + [development.billing] + app_name = "billing" + """ + settings.write_text(content.replace("\n ", "\n")) + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + +def service_names() -> list[str]: + registry = Component.shared_registry + assert registry is not None + return sorted(registry.get_component_names_by_type(ServiceBase)) + + +class TestDeclaration: + def test_nothing_is_built_when_a_component_is_declared(self) -> None: + """The point of a registration: a component built now would predate every namespace.""" + AgentRegistration().with_service(OrderService) + assert Component.shared_registry is None + + def test_declarations_are_kept_in_order(self) -> None: + """Handler priority and scheduler wiring read this order.""" + registration = AgentRegistration().with_handler(StubHandler).with_service(OrderService) + assert [(entry.kind, entry.target) for entry in registration.components] == [ + ("handler", StubHandler), + ("service", OrderService), + ] + + def test_the_fluent_calls_return_the_same_registration(self) -> None: + registration = AgentRegistration() + assert registration.with_service(OrderService) is registration + + def test_constructor_arguments_and_names_are_stored(self) -> None: + registration = AgentRegistration().with_service(ConfiguredService, name="orders_svc", retries=3) + entry = registration.components[0] + assert (entry.name, entry.kwargs) == ("orders_svc", {"retries": 3}) + + def test_there_is_no_with_cache(self) -> None: + """A cache is process-wide and belongs to the AppBuilder that hosts the group.""" + assert not hasattr(AgentRegistration(), "with_cache") + + +class TestRejections: + def test_an_already_built_component_is_refused(self, two_agent_config: Config) -> None: + """It was built before any namespace existed, so it belongs to the root whoever declared it.""" + Component.configure(two_agent_config) + service = OrderService() + with pytest.raises(TypeError, match="as an instance"): + AgentRegistration().with_service(service) + + def test_the_refusal_names_the_class_and_the_method(self, two_agent_config: Config) -> None: + Component.configure(two_agent_config) + with pytest.raises(TypeError, match=r"with_rest_api\(OrderApi, \.\.\.\)"): + AgentRegistration().with_rest_api(OrderApi()) + + @pytest.mark.parametrize("target", ["OrderService", 42, None]) + def test_something_that_cannot_be_called_is_refused(self, target: Any) -> None: + with pytest.raises(TypeError, match="component class or a callable"): + AgentRegistration().with_handler(target) + + +class TestApplyToOneAgent: + def test_a_single_agent_application_registers_at_the_root(self, two_agent_config: Config) -> None: + """Unchanged naming: this is what an existing project gets, whichever way it declares.""" + AppBuilder(two_agent_config).with_registration(AgentRegistration().with_service(OrderService)) + assert service_names() == ["order_service"] + + def test_applying_under_a_namespace_qualifies_the_name(self, two_agent_config: Config) -> None: + AppBuilder(two_agent_config).with_registration(AgentRegistration().with_service(OrderService), "orders") + assert service_names() == ["orders_order_service"] + + def test_with_registration_returns_the_builder(self, two_agent_config: Config) -> None: + builder = AppBuilder(two_agent_config) + assert builder.with_registration(AgentRegistration()) is builder + + def test_constructor_arguments_reach_the_component(self, two_agent_config: Config) -> None: + AppBuilder(two_agent_config).with_registration(AgentRegistration().with_service(ConfiguredService, retries=3)) + registry = Component.shared_registry + assert registry is not None + assert registry.get_component("configured_service").retries == 3 + + def test_an_explicit_name_is_forwarded(self, two_agent_config: Config) -> None: + AppBuilder(two_agent_config).with_registration(AgentRegistration().with_service(OrderService, name="svc")) + assert service_names() == ["svc"] + + def test_an_illegal_namespace_is_refused(self, two_agent_config: Config) -> None: + with pytest.raises(ValueError, match="legal namespace"): + AppBuilder(two_agent_config).with_registration(AgentRegistration().with_service(OrderService), "Orders") + + +class TestOneDeclarationTwoAgents: + """The constraint, end to end: the same object applied twice, under two namespaces.""" + + def test_one_declaration_becomes_two_independently_named_agents(self, two_agent_config: Config) -> None: + registration = AgentRegistration().with_service(OrderService) + builder = AppBuilder(two_agent_config) + + builder.with_registration(registration, "orders") + builder.with_registration(registration, "billing") + + assert service_names() == ["billing_order_service", "orders_order_service"] + + def test_each_agent_reads_its_own_configuration(self, two_agent_config: Config) -> None: + """C5 through the ambient namespace: neither the service nor the declaration mentions one.""" + registration = AgentRegistration().with_service(OrderService) + builder = AppBuilder(two_agent_config) + builder.with_registration(registration, "orders") + builder.with_registration(registration, "billing") + Component.configure(two_agent_config) + + registry = Component.shared_registry + assert registry is not None + orders = registry.get_component("orders_order_service") + billing = registry.get_component("billing_order_service") + + assert (orders.config.get("model_name"), billing.config.get("model_name")) == ("orders-model", "root-model") + assert (orders.config.get("app_name"), billing.config.get("app_name")) == ("orders", "billing") + + def test_the_namespace_is_left_behind_afterwards(self, two_agent_config: Config) -> None: + """Otherwise the builder's own root components would join the last agent applied.""" + AppBuilder(two_agent_config).with_registration(AgentRegistration().with_service(OrderService), "orders") + assert current_namespace() == ROOT_NAMESPACE + + +class TestFactories: + def test_a_factory_is_called_inside_the_namespace(self, two_agent_config: Config) -> None: + """The form the fluent AgentBuilder needs: a chain that cannot be a class plus kwargs.""" + registration = AgentRegistration().with_service(lambda: ConfiguredService(retries=7)) + + AppBuilder(two_agent_config).with_registration(registration, "orders") + + registry = Component.shared_registry + assert registry is not None + built = registry.get_component("orders_configured_service") + assert (built.namespace, built.retries) == ("orders", 7) + + def test_a_factory_sees_the_ambient_namespace_while_it_runs(self, two_agent_config: Config) -> None: + seen: list[str] = [] + + def build_service() -> OrderService: + seen.append(current_namespace()) + return OrderService() + + AppBuilder(two_agent_config).with_registration(AgentRegistration().with_service(build_service), "orders") + + assert seen == ["orders"] + + def test_a_factory_is_not_called_at_declaration_time(self) -> None: + calls: list[int] = [] + AgentRegistration().with_service(lambda: calls.append(1) or OrderService()) + assert calls == [] diff --git a/tests/unit/agents/app_builder/test_named_caches.py b/tests/unit/agents/app_builder/test_named_caches.py new file mode 100644 index 00000000..83460b42 --- /dev/null +++ b/tests/unit/agents/app_builder/test_named_caches.py @@ -0,0 +1,155 @@ +"""Unit tests for ``AppBuilder.with_cache(name=...)``. + +Two things are being pinned down. The first is compatibility: ``with_cache()``, +``with_cache(False)`` and ``with_cache(True, False)`` are written positionally in projects that +exist today, and adding ``name`` must not change what any of them means. The second is that a +named cache is a first-class registry entry -- its own store, its own registry name, closed by +the lifespan like any other service. + +How a *backend* isolates one name from another belongs to ``CacheBackendFactory`` and is tested +in ``tests/unit/agents/services/infrastructure/test_cache_backend_factory.py``. +""" + +from pathlib import Path +from unittest.mock import MagicMock + +import pytest + +from blueprint.agents.app_builder import AppBuilder +from blueprint.agents.component.component import Component +from blueprint.agents.component.registry import DEFAULT_CACHE_NAME, Registry +from blueprint.agents.config import Config +from blueprint.agents.models.config import CacheConfig +from blueprint.agents.services.infrastructure.cache_service import CacheService, DiskCacheService + + +@pytest.fixture +def cache_dir(tmp_path: Path) -> Path: + return tmp_path / "blueprint" + + +@pytest.fixture +def builder(cache_dir: Path) -> AppBuilder: + """An ``AppBuilder`` whose cache configuration points at a real temporary directory. + + The config is a mock and the cache is not: ``with_cache`` builds a real + ``DiskCacheService``, so the directory it chooses is observable on disk, which is the whole + point of the per-name scoping. + """ + config = MagicMock(spec=Config) + config.get_cache_config.return_value = CacheConfig(cache_dir=str(cache_dir), backend="disk") + return AppBuilder(config) + + +def registry() -> Registry: + assert Component.shared_registry is not None + return Component.shared_registry + + +class TestTheDefaultCacheIsUnchanged: + def test_it_registers_under_the_default_name(self, builder: AppBuilder) -> None: + builder.with_cache() + assert isinstance(registry().get_cache(DEFAULT_CACHE_NAME), CacheService) + + def test_it_keeps_the_configured_directory(self, builder: AppBuilder, cache_dir: Path) -> None: + builder.with_cache() + cache = registry().get_cache() + assert isinstance(cache, DiskCacheService) + assert cache.cache_dir == cache_dir + + def test_it_keeps_the_derived_registry_name(self, builder: AppBuilder) -> None: + """Renaming this would move a key that existing lookups and health entries use.""" + builder.with_cache() + assert registry().get_component("disk_cache_service") is registry().get_cache() + + def test_the_cache_service_alias_still_reads_it(self, builder: AppBuilder) -> None: + builder.with_cache() + assert registry().cache_service is registry().get_cache() + + def test_it_works_as_the_first_builder_call(self, builder: AppBuilder) -> None: + """A cache service is itself a Component, so it is what creates the shared registry.""" + Component.shared_registry = None + builder.with_cache() + assert registry().has_cache() + + +class TestPositionalCompatibility: + def test_disabled_registers_nothing(self, builder: AppBuilder) -> None: + builder.with_cache(False) + assert Component.shared_registry is None or not Component.shared_registry.has_cache() + + def test_disabled_does_not_read_the_cache_config(self, builder: AppBuilder) -> None: + builder.with_cache(False) + builder._config.get_cache_config.assert_not_called() # type: ignore[attr-defined] + + def test_locking_is_still_the_second_positional(self, builder: AppBuilder) -> None: + builder.with_cache(True, False) + cache = registry().get_cache() + assert isinstance(cache, DiskCacheService) + assert cache._enable_locking is False + + def test_returns_self_for_chaining(self, builder: AppBuilder) -> None: + assert builder.with_cache() is builder + + +class TestNamedCaches: + def test_a_named_cache_is_reachable_by_its_name(self, builder: AppBuilder) -> None: + builder.with_cache(name="sessions") + assert isinstance(registry().get_cache("sessions"), CacheService) + + def test_a_named_cache_gets_its_own_directory(self, builder: AppBuilder, cache_dir: Path) -> None: + builder.with_cache(name="sessions") + cache = registry().get_cache("sessions") + assert isinstance(cache, DiskCacheService) + assert cache.cache_dir == cache_dir / "sessions" + + def test_the_directory_is_inside_the_configured_one(self, builder: AppBuilder, cache_dir: Path) -> None: + """A sibling of the configured directory is not writable when that directory is the mount.""" + builder.with_cache(name="sessions") + assert (cache_dir / "sessions").is_dir() + + def test_a_named_cache_gets_its_own_registry_name(self, builder: AppBuilder) -> None: + builder.with_cache(name="sessions") + assert registry().get_component("cache_sessions") is registry().get_cache("sessions") + + def test_the_default_and_a_named_cache_coexist(self, builder: AppBuilder) -> None: + """Both are Components: without distinct registry names the second would fail to register.""" + builder.with_cache().with_cache(name="sessions") + assert registry().get_cache() is not registry().get_cache("sessions") + assert sorted(registry().get_all_caches()) == ["default", "sessions"] + + def test_two_named_caches_do_not_share_a_directory(self, builder: AppBuilder) -> None: + builder.with_cache(name="sessions").with_cache(name="prompts") + sessions, prompts = registry().get_cache("sessions"), registry().get_cache("prompts") + assert isinstance(sessions, DiskCacheService) + assert isinstance(prompts, DiskCacheService) + assert sessions.cache_dir != prompts.cache_dir + + def test_an_unregistered_name_is_an_error_not_the_default(self, builder: AppBuilder) -> None: + builder.with_cache() + with pytest.raises(ValueError, match="No cache registered as 'sessions'"): + registry().get_cache("sessions") + + def test_a_named_cache_is_closed_by_the_lifespan(self, builder: AppBuilder) -> None: + """It is closed because it is a registered service; the lifespan drives get_services().""" + builder.with_cache(name="sessions") + assert registry().get_cache("sessions") in registry().get_services() + + +class TestCacheNameValidation: + @pytest.mark.parametrize( + "name", + ["Sessions", "../evil", "a/b", "a\\b", "", " ", "a:b", ".hidden", "_leading", "-leading", "sess ions"], + ) + def test_a_name_that_cannot_be_a_directory_is_refused(self, builder: AppBuilder, name: str) -> None: + with pytest.raises(ValueError, match="not a legal cache name"): + builder.with_cache(name=name) + + @pytest.mark.parametrize("name", ["sessions", "llm-responses", "v2.cache", "a_b"]) + def test_a_usable_name_is_accepted(self, builder: AppBuilder, name: str) -> None: + assert builder.with_cache(name=name) is builder + + def test_nothing_is_registered_when_the_name_is_refused(self, builder: AppBuilder) -> None: + with pytest.raises(ValueError): + builder.with_cache(name="../evil") + assert Component.shared_registry is None or not Component.shared_registry.get_all_caches() diff --git a/tests/unit/agents/app_builder/test_namespace_builder.py b/tests/unit/agents/app_builder/test_namespace_builder.py new file mode 100644 index 00000000..a342e065 --- /dev/null +++ b/tests/unit/agents/app_builder/test_namespace_builder.py @@ -0,0 +1,307 @@ +"""Unit tests for the namespace-aware ``AppBuilder`` and for ``NamespaceBuilder``. + +The behaviour under test is the one thing the whole design rests on: a component ends up in the +right agent without the component, its constructor, or the code that declares it ever mentioning +a namespace. So most of these assert on the registry key a component got, which is the only +externally visible consequence of the namespace it was built in. +""" + +from pathlib import Path +from typing import Any + +import pytest + +from blueprint.agents.app_builder import AgentRegistration, AppBuilder, NamespaceBuilder +from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import ROOT_NAMESPACE, current_namespace, namespace_scope +from blueprint.agents.config import Config +from blueprint.agents.io.api.rest_api_base import RestApiBase +from blueprint.agents.services.service_base import ServiceBase + +from .conftest import StubHandler + + +class OrderService(ServiceBase): + """A service written the way a project writes one: no namespace, no arguments.""" + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class StrictService(ServiceBase): + """A service whose constructor accepts exactly one argument and no namespace. + + The point of the signature: if the builder ever forwarded ``namespace`` to the component, + constructing this would raise ``TypeError`` instead of registering. + """ + + def __init__(self, retries: int = 0) -> None: + super().__init__() + self.retries = retries + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class OrderApi(RestApiBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +@pytest.fixture +def two_agent_config(tmp_path: Path) -> Config: + """A settings tree with a root and two agents, injected as the shared component config.""" + settings = tmp_path / "settings.toml" + content = """ + [development] + app_name = "root-app" + app_port = 8000 + + [development.orders] + app_name = "orders" + + [development.billing] + app_name = "billing" + """ + settings.write_text(content.replace("\n ", "\n")) + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + +def component_names() -> list[str]: + registry = Component.shared_registry + assert registry is not None + return sorted(registry.get_component_names_by_type(Component)) + + +class TestNamespaceOnTheBuilderMethods: + def test_a_namespace_qualifies_the_registry_name(self, two_agent_config: Config) -> None: + AppBuilder(two_agent_config).with_service(OrderService, namespace="orders") + assert component_names() == ["orders_order_service"] + + def test_the_namespace_reaches_the_component_itself(self, two_agent_config: Config) -> None: + AppBuilder(two_agent_config).with_service(OrderService, namespace="orders") + registry = Component.shared_registry + assert registry is not None + assert registry.get_component("orders_order_service").namespace == "orders" + + def test_the_namespace_is_not_forwarded_to_the_constructor(self, two_agent_config: Config) -> None: + """StrictService takes no namespace argument, which is what every project's code looks like.""" + AppBuilder(two_agent_config).with_service(StrictService, namespace="orders", retries=3) + registry = Component.shared_registry + assert registry is not None + built = registry.get_component("orders_strict_service") + assert (built.namespace, built.retries) == ("orders", 3) + + def test_no_namespace_keeps_todays_names(self, two_agent_config: Config) -> None: + AppBuilder(two_agent_config).with_service(OrderService) + assert component_names() == ["order_service"] + + def test_the_default_does_not_reset_an_ambient_namespace(self, two_agent_config: Config) -> None: + """The trap: ``namespace_scope("")`` *sets* the root, so the default must not open a scope. + + This is the path ``AgentRegistration.apply`` takes -- it opens one scope per agent and + then calls these methods without a namespace argument. + """ + builder = AppBuilder(two_agent_config) + with namespace_scope("orders"): + builder.with_service(OrderService) + assert component_names() == ["orders_order_service"] + + def test_an_explicit_namespace_wins_over_the_ambient_one(self, two_agent_config: Config) -> None: + builder = AppBuilder(two_agent_config) + with namespace_scope("orders"): + builder.with_service(OrderService, namespace="billing") + assert component_names() == ["billing_order_service"] + + def test_the_ambient_namespace_is_restored_afterwards(self, two_agent_config: Config) -> None: + AppBuilder(two_agent_config).with_service(OrderService, namespace="orders") + assert current_namespace() == ROOT_NAMESPACE + + @pytest.mark.parametrize( + ("method", "target", "expected"), + [ + ("with_handler", StubHandler, "orders_stub_handler"), + ("with_service", OrderService, "orders_order_service"), + ("with_rest_api", OrderApi, "orders_order_api"), + ], + ) + def test_every_method_takes_a_namespace(self, two_agent_config: Config, method: str, target: Any, expected: str) -> None: + builder = AppBuilder(two_agent_config) + getattr(builder, method)(target, namespace="orders") + assert component_names() == [expected] + + def test_an_illegal_namespace_is_refused(self, two_agent_config: Config) -> None: + with pytest.raises(ValueError, match="legal namespace"): + AppBuilder(two_agent_config).with_service(OrderService, namespace="Orders") + + def test_the_handler_type_check_still_fires(self, two_agent_config: Config) -> None: + with pytest.raises(TypeError, match="EventHandlerBase subclass"): + AppBuilder(two_agent_config).with_handler(OrderService, namespace="orders") # type: ignore[type-var] + + +class TestExplicitNames: + def test_an_explicit_name_is_qualified_with_the_namespace(self, two_agent_config: Config) -> None: + AppBuilder(two_agent_config).with_service(OrderService, name="db", namespace="orders") + assert component_names() == ["orders_db"] + + def test_an_explicit_name_at_the_root_is_unchanged(self, two_agent_config: Config) -> None: + AppBuilder(two_agent_config).with_service(OrderService, name="db") + assert component_names() == ["db"] + + def test_one_declaration_with_an_explicit_name_serves_two_agents(self, two_agent_config: Config) -> None: + """Unqualified, the second agent would collide on the one literal name and fail to build.""" + registration = AgentRegistration().with_service(OrderService, name="db") + builder = AppBuilder(two_agent_config) + + builder.with_namespace("orders", registration=registration) + builder.with_namespace("billing", registration=registration) + + assert component_names() == ["billing_db", "orders_db"] + + def test_the_bare_name_still_finds_it(self, two_agent_config: Config) -> None: + """Registry._lookup tries '_' first, so qualifying costs the caller nothing.""" + AppBuilder(two_agent_config).with_service(OrderService, name="db", namespace="orders") + registry = Component.shared_registry + assert registry is not None + assert registry.get_component("db", namespace="orders").namespace == "orders" + + +class TestAlreadyBuiltInstances: + def test_an_instance_is_refused_for_another_namespace(self, two_agent_config: Config) -> None: + Component.configure(two_agent_config) + instance = OrderService() + + with pytest.raises(ValueError, match="cannot change namespace"): + AppBuilder(two_agent_config).with_service(instance, namespace="orders") + + def test_the_refusal_names_both_namespaces_and_the_method(self, two_agent_config: Config) -> None: + Component.configure(two_agent_config) + instance = OrderService() + + with pytest.raises(ValueError, match=r"with_service\(\).*'orders'.*''"): + AppBuilder(two_agent_config).with_service(instance, namespace="orders") + + def test_an_instance_from_the_same_namespace_is_accepted(self, two_agent_config: Config) -> None: + Component.configure(two_agent_config) + with namespace_scope("orders"): + instance = OrderService() + + AppBuilder(two_agent_config).with_service(instance, namespace="orders") + assert component_names() == ["orders_order_service"] + + def test_an_instance_at_the_root_is_unaffected(self, two_agent_config: Config) -> None: + Component.configure(two_agent_config) + instance = OrderService() + + AppBuilder(two_agent_config).with_service(instance) + assert component_names() == ["order_service"] + + +class TestWithNamespace: + def test_a_registration_keeps_the_chain_on_the_builder(self, two_agent_config: Config) -> None: + builder = AppBuilder(two_agent_config) + returned = builder.with_namespace("orders", registration=AgentRegistration().with_service(OrderService)) + assert returned is builder + assert component_names() == ["orders_order_service"] + + def test_no_registration_opens_a_namespace_block(self, two_agent_config: Config) -> None: + builder = AppBuilder(two_agent_config) + opened = builder.with_namespace("orders") + assert isinstance(opened, NamespaceBuilder) + assert opened.namespace == "orders" + + def test_the_root_namespace_is_refused(self, two_agent_config: Config) -> None: + with pytest.raises(ValueError, match="names no agent"): + AppBuilder(two_agent_config).with_namespace("") + + def test_an_illegal_namespace_is_refused(self, two_agent_config: Config) -> None: + with pytest.raises(ValueError, match="legal namespace"): + AppBuilder(two_agent_config).with_namespace("Orders") + + def test_the_ambient_namespace_is_left_behind(self, two_agent_config: Config) -> None: + AppBuilder(two_agent_config).with_namespace("orders", registration=AgentRegistration().with_service(OrderService)) + assert current_namespace() == ROOT_NAMESPACE + + +class TestDeclaredNamespaces: + def test_a_single_agent_application_declares_none(self, two_agent_config: Config) -> None: + builder = AppBuilder(two_agent_config).with_service(OrderService) + assert builder.namespaces == () + + def test_declaration_order_is_kept(self, two_agent_config: Config) -> None: + builder = AppBuilder(two_agent_config) + builder.with_namespace("orders").end().with_namespace("billing").end() + assert builder.namespaces == ("orders", "billing") + + def test_a_namespace_is_recorded_once(self, two_agent_config: Config) -> None: + builder = AppBuilder(two_agent_config) + builder.with_namespace("orders", registration=AgentRegistration()) + builder.with_namespace("orders", registration=AgentRegistration().with_service(OrderService)) + assert builder.namespaces == ("orders",) + + def test_a_tagged_with_call_is_not_a_declaration(self, two_agent_config: Config) -> None: + """``namespaces`` is what the builder was *told* to host; a tagged call is not that. + + Recording it there would make ``with_service(X, namespace="orders")`` enough to make + 'orders' an agent of the group, and phases that iterate the list -- the startup log, + the readiness policy -- would then report an agent nobody declared. + """ + builder = AppBuilder(two_agent_config).with_service(OrderService, namespace="orders") + assert builder.namespaces == () + + +class TestNamespaceBlock: + def test_every_call_lands_in_the_namespace(self, two_agent_config: Config) -> None: + ( + AppBuilder(two_agent_config) + .with_namespace("orders") + .with_service(OrderService) + .with_handler(StubHandler) + .with_rest_api(OrderApi) + .end() + ) + assert component_names() == ["orders_order_api", "orders_order_service", "orders_stub_handler"] + + def test_the_calls_chain_on_the_block(self, two_agent_config: Config) -> None: + block = AppBuilder(two_agent_config).with_namespace("orders") + assert block.with_service(OrderService) is block + + def test_end_returns_the_parent_builder(self, two_agent_config: Config) -> None: + builder = AppBuilder(two_agent_config) + assert builder.with_namespace("orders").end() is builder + + def test_two_blocks_build_two_independent_agents(self, two_agent_config: Config) -> None: + ( + AppBuilder(two_agent_config) + .with_namespace("orders") + .with_service(OrderService) + .end() + .with_namespace("billing") + .with_service(OrderService) + .end() + ) + assert component_names() == ["billing_order_service", "orders_order_service"] + + def test_a_registration_can_be_applied_inside_a_block(self, two_agent_config: Config) -> None: + block = AppBuilder(two_agent_config).with_namespace("orders") + block.with_registration(AgentRegistration().with_service(OrderService)) + assert component_names() == ["orders_order_service"] + + def test_constructor_arguments_survive_the_delegation(self, two_agent_config: Config) -> None: + AppBuilder(two_agent_config).with_namespace("orders").with_service(StrictService, retries=5).end() + registry = Component.shared_registry + assert registry is not None + assert registry.get_component("orders_strict_service").retries == 5 + + def test_there_is_no_with_cache(self) -> None: + """A cache belongs to the process, not to an agent (spec sec. 8).""" + assert not hasattr(NamespaceBuilder, "with_cache") diff --git a/tests/unit/agents/component/TESTS.md b/tests/unit/agents/component/TESTS.md index 527cb01a..048a51f4 100644 --- a/tests/unit/agents/component/TESTS.md +++ b/tests/unit/agents/component/TESTS.md @@ -9,10 +9,11 @@ Test coverage for `src/blueprint/agents/component/component.py` and | File | Class under test | What is covered | |---|---|---| -| `test_component.py` | `Component`, `_ComponentMeta` | `configure`, `init_registry`, `__init__`, properties, `name` setter | +| `test_component.py` | `Component`, `_ComponentMeta` | `configure`, `init_registry`, `__init__`, properties, `name` setter, namespace taken from the ambient scope (bare `super().__init__()` in a `ServiceBase` subclass, two scopes yielding two qualified names, explicit non-empty namespace still winning), `executor` resolving to the namespace's pool (not shared across agents, shared within one, sized from the scoped `executor_workers`), `registry` returning the namespace's view (the registry itself at the root, this agent's components for an unqualified lookup, two agents resolving their own of one class) | | `test_component.py` | `_is_cloud_event`, `_stamp_span` | Helper function correctness | | `test_component.py` | `traced` decorator | Async/sync span creation, error status, CloudEvent/plain-value stamping | -| `test_registry.py` | `Registry` | Construction, add/get/has/rename/clear, type-based lookups, `cache_service` | +| `test_namespace.py` | `namespace.py` helpers | `validate_namespace`, `qualified_component_name`, `namespace_of`, `display_segment`, `resolve_for_namespace`, and `namespace_scope`/`current_namespace` (default root, set/exit, exit on exception, nesting, validation on entry) | +| `test_registry.py` | `Registry` | Construction, add/get/has/rename/clear, type-based lookups, `cache_service`; namespaced lookup (bare name resolving to the asking namespace, root fallback, already-qualified names, the error naming where it looked), type queries (`None` = every namespace, a namespace = that agent exactly, filtering by attribute not name, ambiguity refused across and within a namespace), and that `get_known_namespaces` does not exist (C6); named caches (lookup by name, no fallback to the default, the error listing what is registered, the `cache_service` alias both ways, `get_all_caches` copying, `clear` clearing every cache, replace-and-warn on a second registration); per-namespace executors (none until asked, create then reuse, isolation, sizing on the creating call only, thread naming, shutdown from `clear` and `shutdown_executors`); namespace views (`for_namespace` identity at the root, caching, the shared store, the C6 refusal on a view, omitted-means-this-agent, root fallback for name and class lookups, plural lookups scoped to one agent, explicit override, and the application registry still seeing everything) | --- diff --git a/tests/unit/agents/component/test_component.py b/tests/unit/agents/component/test_component.py index cefdfdb5..da5d78b2 100644 --- a/tests/unit/agents/component/test_component.py +++ b/tests/unit/agents/component/test_component.py @@ -16,7 +16,10 @@ _stamp_span, traced, ) +from blueprint.agents.component.namespace import ROOT_NAMESPACE, namespace_scope +from blueprint.agents.component.registry import Registry from blueprint.agents.config import Config +from blueprint.agents.services.service_base import ServiceBase from .conftest import ConcreteComponent @@ -402,3 +405,132 @@ def test_reset_clears_both(self, reset_component_state: None) -> None: Component.reset_shared_state() assert Component.has_config() is False assert Component.shared_registry is None + + +class TestNamespaceComesFromTheAmbientScope: + """A developer-written component must be namespaced without naming a namespace. + + These use the same shapes a project writes: a service that takes no namespace parameter at + all, and one that calls ``super().__init__()`` with nothing. + """ + + def test_a_component_built_outside_a_scope_is_root(self) -> None: + assert ConcreteComponent().namespace == ROOT_NAMESPACE + + def test_a_component_built_inside_a_scope_takes_that_namespace(self) -> None: + with namespace_scope("orders"): + assert ConcreteComponent().namespace == "orders" + + def test_a_developer_service_needs_no_namespace_parameter(self) -> None: + """ServiceBase defaults namespace to "" and forwards it, so "" must defer to the scope.""" + + class OrderService(ServiceBase): + def __init__(self) -> None: + super().__init__() + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + with namespace_scope("orders"): + service = OrderService() + + assert service.namespace == "orders" + + def test_the_registry_name_is_qualified_by_the_ambient_namespace(self) -> None: + """The point of the namespace: two agents can register the same class in one process.""" + with namespace_scope("orders"): + first = ConcreteComponent() + with namespace_scope("billing"): + second = ConcreteComponent() + + assert (first.name, second.name) == ("orders_concrete_component", "billing_concrete_component") + + def test_an_explicit_namespace_still_wins(self) -> None: + """Framework components that own their namespace pass it; nothing ambient may override that.""" + with namespace_scope("orders"): + assert ConcreteComponent(namespace="billing").namespace == "billing" + + def test_the_namespace_is_validated_whichever_way_it_arrives(self) -> None: + with pytest.raises(ValueError, match="legal namespace"): + ConcreteComponent(namespace="Orders") + + +class TestExecutorBelongsToTheNamespace: + @pytest.fixture(autouse=True) + def injected_config(self) -> MagicMock: + """A Config stand-in, since `executor` is the first property to read configuration.""" + config = MagicMock(spec=Config) + config.get.side_effect = lambda key, default=None: default + config.for_namespace.return_value = config + Component.configure(config) + return config + + def test_a_component_gets_its_namespace_pool(self) -> None: + with namespace_scope("orders"): + component = ConcreteComponent() + assert component.executor is component.registry.get_or_create_executor("orders") + + def test_two_agents_do_not_share_a_pool(self) -> None: + with namespace_scope("orders"): + orders = ConcreteComponent() + with namespace_scope("billing"): + billing = ConcreteComponent() + assert orders.executor is not billing.executor + + def test_two_components_of_one_agent_share_its_pool(self) -> None: + """The pool belongs to the agent, not to the component.""" + with namespace_scope("orders"): + first, second = ConcreteComponent(), ConcreteComponent(name="second") + assert first.executor is second.executor + + def test_the_pool_is_sized_from_the_scoped_configuration(self, injected_config: MagicMock) -> None: + """executor_workers is namespace-scoped (C5), so one agent can be sized differently.""" + injected_config.get.side_effect = lambda key, default=None: 3 if key == "executor_workers" else default + with namespace_scope("orders"): + component = ConcreteComponent() + assert component.executor._max_workers == 3 + + def test_asking_twice_returns_the_same_pool(self) -> None: + component = ConcreteComponent() + assert component.executor is component.executor + + +class TestRegistryIsScopedToTheComponent: + """The other half of "a developer never writes a namespace": collaborator lookups.""" + + @pytest.fixture(autouse=True) + def real_registry(self) -> Registry: + registry = Registry(Component) + Component.shared_registry = registry + Component.configure(MagicMock(spec=Config)) + return registry + + def test_a_root_component_gets_the_registry_itself(self, real_registry: Registry) -> None: + assert ConcreteComponent().registry is real_registry + + def test_a_namespaced_component_gets_its_own_view(self, real_registry: Registry) -> None: + with namespace_scope("orders"): + component = ConcreteComponent() + assert component.registry is real_registry.for_namespace("orders") + + def test_a_lookup_with_no_namespace_finds_this_agents_component(self, real_registry: Registry) -> None: + with namespace_scope("orders"): + asker = ConcreteComponent(name="orders_asker") + with namespace_scope("billing"): + ConcreteComponent(name="billing_asker") + + found = asker.registry.get_components_by_type(ConcreteComponent) + + assert [component.namespace for component in found] == ["orders"] + + def test_two_agents_resolve_their_own_of_the_same_class(self, real_registry: Registry) -> None: + with namespace_scope("orders"): + orders = ConcreteComponent() + with namespace_scope("billing"): + billing = ConcreteComponent() + + assert orders.registry.get_component(ConcreteComponent) is orders + assert billing.registry.get_component(ConcreteComponent) is billing diff --git a/tests/unit/agents/component/test_namespace.py b/tests/unit/agents/component/test_namespace.py index 67e461f1..93f3d156 100644 --- a/tests/unit/agents/component/test_namespace.py +++ b/tests/unit/agents/component/test_namespace.py @@ -5,8 +5,10 @@ from blueprint.agents.component.namespace import ( ROOT_LABEL, ROOT_NAMESPACE, + current_namespace, display_segment, namespace_of, + namespace_scope, qualified_component_name, resolve_for_namespace, validate_namespace, @@ -127,3 +129,48 @@ def test_whitespace_is_replaced(self) -> None: def test_an_empty_value_becomes_the_placeholder(self) -> None: assert display_segment(" ", "") == "" + + +class TestAmbientNamespace: + """The scope that lets a developer-written component be namespaced without saying so.""" + + def test_the_root_is_in_force_by_default(self) -> None: + """A single-agent application never enters a scope, so nothing may change for it.""" + assert current_namespace() == ROOT_NAMESPACE + + def test_a_scope_sets_the_namespace(self) -> None: + with namespace_scope("orders"): + assert current_namespace() == "orders" + + def test_the_scope_is_left_on_the_way_out(self) -> None: + with namespace_scope("orders"): + pass + assert current_namespace() == ROOT_NAMESPACE + + def test_the_scope_is_left_even_when_the_block_raises(self) -> None: + """A leaked namespace would attach the next agent, or a root component, to the wrong one.""" + with pytest.raises(RuntimeError): + with namespace_scope("orders"): + raise RuntimeError("component construction failed") + assert current_namespace() == ROOT_NAMESPACE + + def test_scopes_restore_the_previous_namespace_not_the_root(self) -> None: + with namespace_scope("orders"): + with namespace_scope("billing"): + assert current_namespace() == "billing" + assert current_namespace() == "orders" + + def test_the_root_scope_is_a_no_op(self) -> None: + with namespace_scope(ROOT_NAMESPACE): + assert current_namespace() == ROOT_NAMESPACE + + def test_an_illegal_namespace_is_rejected_on_entry(self) -> None: + """Reported against the registration that declared it, not the first component built.""" + with pytest.raises(ValueError, match="legal namespace"): + with namespace_scope("Orders"): + pass + assert current_namespace() == ROOT_NAMESPACE + + def test_the_scope_yields_its_namespace(self) -> None: + with namespace_scope("orders") as namespace: + assert namespace == "orders" diff --git a/tests/unit/agents/component/test_registry.py b/tests/unit/agents/component/test_registry.py index 5acd77f0..01a34958 100644 --- a/tests/unit/agents/component/test_registry.py +++ b/tests/unit/agents/component/test_registry.py @@ -1,5 +1,7 @@ """Unit tests for the component Registry.""" +import logging + import pytest from unittest.mock import MagicMock @@ -165,10 +167,19 @@ def test_setter_assigns(self, registry: Registry) -> None: registry.cache_service = mock_cache assert registry.cache_service is mock_cache - def test_setter_raises_on_second_set(self, registry: Registry) -> None: - registry.cache_service = MagicMock() - with pytest.raises(ValueError): - registry.cache_service = MagicMock() + def test_setter_replaces_and_warns_on_a_second_set(self, registry: Registry, caplog: pytest.LogCaptureFixture) -> None: + """Named caches made this an upsert: a cache can legitimately be swapped after startup. + + It warns because the usual way to get here is two calls to ``with_cache()``, and the + second would otherwise take over the first with nothing said. + """ + first, second = MagicMock(), MagicMock() + registry.cache_service = first + with caplog.at_level(logging.WARNING): + registry.cache_service = second + + assert registry.cache_service is second + assert "is being replaced by" in caplog.text def test_has_cache_false_when_unset(self, registry: Registry) -> None: assert registry.has_cache() is False @@ -199,3 +210,258 @@ def test_clear_without_cache_does_not_raise(self, registry: Registry) -> None: registry.add_component("a", StubA()) registry.clear() assert not registry.has_component("a") + + +class _Namespaced(StubBase): + """A stub carrying the ``namespace`` attribute every real component has.""" + + def __init__(self, namespace: str = "") -> None: + self.namespace = namespace + + +@pytest.fixture +def grouped_registry() -> Registry: + """Two agents owning the same component type, plus one shared at the root. + + Registered under the qualified names ``Component.__init__`` derives, because that is what + the namespace-then-root fallback resolves through. + """ + registry = Registry(StubBase) + registry.add_component("orders_order_service", _Namespaced("orders")) + registry.add_component("billing_order_service", _Namespaced("billing")) + registry.add_component("shared_audit", _Namespaced("")) + return registry + + +class TestNamespacedNameLookup: + def test_a_bare_name_resolves_to_the_asking_namespace(self, grouped_registry: Registry) -> None: + assert grouped_registry.get_component("order_service", "orders").namespace == "orders" + + def test_two_agents_get_their_own(self, grouped_registry: Registry) -> None: + orders = grouped_registry.get_component("order_service", "orders") + billing = grouped_registry.get_component("order_service", "billing") + assert (orders.namespace, billing.namespace) == ("orders", "billing") + + def test_a_namespace_falls_back_to_the_root(self, grouped_registry: Registry) -> None: + """Infrastructure stays shared: only what an agent owns is per-agent.""" + assert grouped_registry.get_component("shared_audit", "orders").namespace == "" + + def test_an_already_qualified_name_still_resolves(self, grouped_registry: Registry) -> None: + """Qualifying it twice simply misses, and the bare lookup then finds it.""" + assert grouped_registry.get_component("orders_order_service", "orders").namespace == "orders" + + def test_a_bare_name_without_a_namespace_does_not_resolve(self, grouped_registry: Registry) -> None: + with pytest.raises(ValueError, match="does not exist"): + grouped_registry.get_component("order_service") + + def test_the_error_names_where_it_looked(self, grouped_registry: Registry) -> None: + with pytest.raises(ValueError, match="namespace 'orders' or at the root"): + grouped_registry.get_component("missing", "orders") + + def test_has_component_follows_the_same_fallback(self, grouped_registry: Registry) -> None: + assert grouped_registry.has_component("order_service", "orders") is True + assert grouped_registry.has_component("order_service", "") is False + assert grouped_registry.has_component("shared_audit", "orders") is True + + +class TestNamespacedTypeLookup: + def test_no_namespace_returns_every_namespace(self, grouped_registry: Registry) -> None: + """The default has to stay "everything" -- build() iterating handlers needs all of them.""" + assert len(grouped_registry.get_components_by_type(_Namespaced)) == 3 + + def test_a_namespace_returns_only_that_agent(self, grouped_registry: Registry) -> None: + found = grouped_registry.get_components_by_type(_Namespaced, "orders") + assert [component.namespace for component in found] == ["orders"] + + def test_the_root_is_a_namespace_like_any_other(self, grouped_registry: Registry) -> None: + found = grouped_registry.get_component_names_by_type(_Namespaced, "") + assert found == ["shared_audit"] + + def test_filtering_is_by_attribute_not_by_name(self, grouped_registry: Registry) -> None: + """A component registered under an explicit name is still attributed correctly.""" + grouped_registry.add_component("legacy_name", _Namespaced("orders")) + found = grouped_registry.get_component_names_by_type(_Namespaced, "orders") + assert sorted(found) == ["legacy_name", "orders_order_service"] + + def test_a_class_lookup_prefers_the_asking_namespace(self, grouped_registry: Registry) -> None: + assert grouped_registry.get_component(_Namespaced, "billing").namespace == "billing" + + def test_a_class_lookup_without_a_namespace_refuses_to_guess(self, grouped_registry: Registry) -> None: + """Handing an agent a neighbour's collaborator is the failure the namespace prevents.""" + with pytest.raises(ValueError, match="Multiple components"): + grouped_registry.get_component(_Namespaced) + + def test_a_class_lookup_is_ambiguous_within_one_namespace_too(self, grouped_registry: Registry) -> None: + grouped_registry.add_component("orders_second", _Namespaced("orders")) + with pytest.raises(ValueError, match="ambiguous"): + grouped_registry.get_component(_Namespaced, "orders") + + def test_has_component_of_type_can_be_asked_per_namespace(self, grouped_registry: Registry) -> None: + assert grouped_registry.has_component_of_type(_Namespaced, None, "orders") is True + assert grouped_registry.has_component_of_type(_Namespaced, None, "shipping") is False + + +class TestC6: + def test_the_registry_cannot_be_asked_which_namespaces_exist(self, grouped_registry: Registry) -> None: + """C6: Component.registry is reachable from agent code, so this must not be answerable.""" + assert not hasattr(grouped_registry, "get_known_namespaces") + + +class TestNamedCaches: + """Caches are looked up by name, and never substituted for one another (spec sec. 8).""" + + def test_a_cache_is_retrieved_under_the_name_it_was_added_with(self, registry: Registry) -> None: + sessions = MagicMock() + registry.add_cache("sessions", sessions) + assert registry.get_cache("sessions") is sessions + + def test_an_unregistered_name_does_not_fall_back_to_the_default(self, registry: Registry) -> None: + """Two agents asking for "sessions" must not silently be handed one store.""" + registry.add_cache("default", MagicMock()) + with pytest.raises(ValueError, match="No cache registered as 'sessions'"): + registry.get_cache("sessions") + + def test_the_error_lists_what_is_registered(self, registry: Registry) -> None: + registry.add_cache("sessions", MagicMock()) + with pytest.raises(ValueError, match=r"registered: sessions"): + registry.get_cache("prompts") + + def test_the_error_says_none_when_nothing_is_registered(self, registry: Registry) -> None: + with pytest.raises(ValueError, match=r"registered: none"): + registry.get_cache("sessions") + + def test_caches_do_not_collide(self, registry: Registry) -> None: + first, second = MagicMock(), MagicMock() + registry.add_cache("sessions", first) + registry.add_cache("prompts", second) + assert (registry.get_cache("sessions"), registry.get_cache("prompts")) == (first, second) + + def test_has_cache_asks_about_one_name(self, registry: Registry) -> None: + registry.add_cache("sessions", MagicMock()) + assert (registry.has_cache("sessions"), registry.has_cache("prompts"), registry.has_cache()) == (True, False, False) + + def test_the_default_name_is_what_the_alias_reads(self, registry: Registry) -> None: + cache = MagicMock() + registry.add_cache("default", cache) + assert (registry.cache_service is cache, registry.has_cache()) == (True, True) + + def test_the_alias_writes_the_default_name(self, registry: Registry) -> None: + cache = MagicMock() + registry.cache_service = cache + assert registry.get_cache("default") is cache + + def test_get_all_caches_returns_a_copy(self, registry: Registry) -> None: + """The health checks and the management endpoints iterate this; they must not mutate it.""" + registry.add_cache("sessions", MagicMock()) + caches = registry.get_all_caches() + caches["injected"] = MagicMock() + assert registry.has_cache("injected") is False + + def test_clear_empties_and_clears_every_cache(self, registry: Registry) -> None: + first, second = MagicMock(), MagicMock() + registry.add_cache("default", first) + registry.add_cache("sessions", second) + + registry.clear() + + first.clear.assert_called_once() + second.clear.assert_called_once() + assert registry.get_all_caches() == {} + + +class TestExecutors: + """One thread pool per namespace, created only when something actually needs one.""" + + def test_no_pool_exists_until_one_is_asked_for(self, registry: Registry) -> None: + """An application with no blocking work must run with no extra threads (spec sec. 4.3).""" + assert registry._executors == {} + + def test_the_first_call_creates_and_the_second_reuses(self, registry: Registry) -> None: + first = registry.get_or_create_executor("orders") + assert registry.get_or_create_executor("orders") is first + + def test_each_namespace_gets_its_own(self, registry: Registry) -> None: + """One agent exhausting its pool must not stall another's blocking work.""" + assert registry.get_or_create_executor("orders") is not registry.get_or_create_executor("billing") + + def test_the_root_is_a_namespace_like_any_other(self, registry: Registry) -> None: + assert registry.get_or_create_executor() is registry.get_or_create_executor("") + + def test_the_creating_call_sizes_the_pool(self, registry: Registry) -> None: + assert registry.get_or_create_executor("orders", 3)._max_workers == 3 + + def test_a_later_size_is_ignored_because_a_live_pool_cannot_be_resized(self, registry: Registry) -> None: + registry.get_or_create_executor("orders", 3) + assert registry.get_or_create_executor("orders", 9)._max_workers == 3 + + def test_threads_are_named_after_their_namespace(self, registry: Registry) -> None: + """So a stack dump or a profiler says which agent a blocked thread belongs to.""" + assert registry.get_or_create_executor("orders")._thread_name_prefix == "blueprint-orders" + + def test_shutdown_closes_and_forgets_every_pool(self, registry: Registry) -> None: + executor = registry.get_or_create_executor("orders") + registry.shutdown_executors() + assert registry._executors == {} + assert executor._shutdown is True + + def test_clear_shuts_the_pools_down_too(self, registry: Registry) -> None: + """Otherwise a test suite building many applications accumulates thread pools.""" + executor = registry.get_or_create_executor("orders") + registry.clear() + assert registry._executors == {} + assert executor._shutdown is True + + +class TestNamespaceViews: + """A view answers as one agent, so a call site never has to name a namespace.""" + + def test_the_root_namespace_is_the_registry_itself(self, grouped_registry: Registry) -> None: + """Not an optimisation: the root namespace *is* the unscoped registry.""" + assert grouped_registry.for_namespace("") is grouped_registry + + def test_views_are_cached(self, grouped_registry: Registry) -> None: + assert grouped_registry.for_namespace("orders") is grouped_registry.for_namespace("orders") + + def test_a_view_shares_the_one_component_store(self, grouped_registry: Registry) -> None: + """One registry per process; a view is a lens on it, not a copy of it.""" + view = grouped_registry.for_namespace("orders") + assert view._components is grouped_registry._components + assert view._caches is grouped_registry._caches + + def test_a_view_reports_the_namespace_it_answers_as(self, grouped_registry: Registry) -> None: + assert grouped_registry.for_namespace("orders").default_namespace == "orders" + assert grouped_registry.default_namespace is None + + def test_a_view_cannot_mint_another_agents_view(self, grouped_registry: Registry) -> None: + """C6: it would hand every component a route to its neighbours.""" + view = grouped_registry.for_namespace("orders") + with pytest.raises(RuntimeError, match="not from another agent"): + view.for_namespace("billing") + + def test_an_omitted_namespace_means_this_agent(self, grouped_registry: Registry) -> None: + view = grouped_registry.for_namespace("orders") + assert view.get_component("order_service").namespace == "orders" + + def test_an_omitted_namespace_still_falls_back_to_the_root(self, grouped_registry: Registry) -> None: + assert grouped_registry.for_namespace("orders").get_component("shared_audit").namespace == "" + + def test_a_class_lookup_on_a_view_finds_this_agents_instance(self, grouped_registry: Registry) -> None: + assert grouped_registry.for_namespace("billing").get_component(_Namespaced).namespace == "billing" + + def test_a_class_lookup_on_a_view_falls_back_to_the_root(self, grouped_registry: Registry) -> None: + """The candidates must be gathered unfiltered, or the fallback could never fire.""" + registry = Registry(StubBase) + registry.add_component("shared_audit", _Namespaced("")) + assert registry.for_namespace("orders").get_component(_Namespaced).namespace == "" + + def test_a_plural_lookup_on_a_view_returns_only_this_agent(self, grouped_registry: Registry) -> None: + found = grouped_registry.for_namespace("orders").get_components_by_type(_Namespaced) + assert [component.namespace for component in found] == ["orders"] + + def test_an_explicit_namespace_overrides_the_view(self, grouped_registry: Registry) -> None: + view = grouped_registry.for_namespace("orders") + assert view.get_component("order_service", "billing").namespace == "billing" + + def test_the_application_registry_still_sees_everything(self, grouped_registry: Registry) -> None: + """build() and the lifespan hold the unscoped registry and must keep iterating all of it.""" + assert len(grouped_registry.get_components_by_type(_Namespaced)) == 3 diff --git a/tests/unit/agents/services/TESTS.md b/tests/unit/agents/services/TESTS.md index dd98ba0d..a83e145e 100644 --- a/tests/unit/agents/services/TESTS.md +++ b/tests/unit/agents/services/TESTS.md @@ -10,8 +10,9 @@ Test coverage for `src/blueprint/agents/services/`. |---|---|---| | `eventing/test_event_processing_service.py` | `EventProcessingService` | `_extract_handler_results` (None/HandlerResult/list/dict variants), `_build_result` (message text, request_id, result list), `_unwrap_dapr_event` (passthrough / CloudEvent inner / dict inner / missing type / unexpected type), lifecycle no-ops, `process_rest_request` delegates to `process_event` with correct event shape | | `eventing/test_event_publishing_service.py` | `EventPublishingService` | `on_startup` wires client and config, `_get_pub_config` raises before startup, `get_topic_for_event_type` / `get_available_event_types`, `publish_event` (topic mapping, explicit topic override, missing mapping raises, sets default source, result shape), `publish_handler_event` (no mapping → skip, loop prevention → skip, normal → publishes), `publish_status_event` type format and delegation | -| `infrastructure/test_disk_cache_service.py` | `DiskCacheService` | `set`/`get` (string/dict/list keys, namespace isolation), `delete` (return values), `exists` (before/after set/delete), `clear` (namespace-scoped and full), TTL expiration via mocked `time.time`, `hash` consistency for string/list/dict inputs, `list_namespaces`, `list_values` (content, TTL-entry exclusion, limit), `get_stats` field presence, lifecycle, context-manager protocol; `claim` set-if-absent (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, keys and namespaces independent, dict keys hashed consistently, TTL recorded so readers see expiry, a logically expired claim taken over, no TTL never expires, and an unreachable cache failing open) | +| `infrastructure/test_disk_cache_service.py` | `DiskCacheService` | `set`/`get` (string/dict/list keys, namespace isolation), `delete` (return values), `exists` (before/after set/delete), `clear` (namespace-scoped and full), TTL expiration via mocked `time.time`, `hash` consistency for string/list/dict inputs, `list_namespaces`, `list_values` (content, TTL-entry exclusion, limit), `get_stats` field presence, lifecycle, context-manager protocol, an unwritable cache directory failing with a message that names the path and the options (and keeping the OSError as the cause); `claim` set-if-absent (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, keys and namespaces independent, dict keys hashed consistently, TTL recorded so readers see expiry, a logically expired claim taken over, no TTL never expires, and an unreachable cache failing open) | | `infrastructure/test_redis_cache_service.py` | `RedisCacheService` | Backed by `fakeredis`. `claim` via `SET NX EX` (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, the TTL is applied to the key, namespaces are independent, and an unreachable cache fails open). *The rest of this file's coverage predates this table and is not itemised here.* | +| `infrastructure/test_agent_scoped_cache.py` | `AgentScopedCache` | Per-agent isolation over one shared backend (same key and partition name kept apart, a neighbour's key reading as absent, the partition carrying the agent, `list_namespaces` stripped back, the default partition scoped, per-agent `delete` and `claim`); `clear` for one partition and for all of this agent's, never the neighbours'; the `close` refusal, the root-namespace refusal, not registering itself, stats naming the agent; and the six paths through a registry view (scoped for a namespace, raw at the root, one lens per view, different lenses per agent, named caches scoped, unknown name still raising) | | `infrastructure/test_cache_backend_factory.py`, `infrastructure/test_cache_sharing_via_registry.py`, `infrastructure/test_redis_url_utils.py` | `CacheBackendFactory`, registry cache sharing, Redis URL helpers | Present but not itemised in this table. | | `sessions/test_api_client.py` | `SessionsApiClient` | `on_startup` (valid config, missing config/base_url/api_key → ValueError), `on_shutdown` (closes client, no-op when uninitialised), `get_job_detail`/`start_job`/`complete_job`/`cancel_job` (URL shape, required headers, payload contents, uninitialised guard) | | `sessions/test_key_provider.py` | `SessionKeyProvider` | `on_startup` (initialises cache, reads source/env_var from config, missing config → ValueError), `on_shutdown` (clears cache, no-op when uninitialised), `get_session_key` (env hit/miss, config source, vault → NotImplementedError, remote source via respx — happy path/caching/404/missing session_id/missing URL, unknown source, cache-hit bypass, result cached after fetch), `invalidate_cache` (default and per-session key removal, no-op when empty/uninitialised) | diff --git a/tests/unit/agents/services/eventing/test_event_publishing_service.py b/tests/unit/agents/services/eventing/test_event_publishing_service.py index ae68bac6..10082a1b 100644 --- a/tests/unit/agents/services/eventing/test_event_publishing_service.py +++ b/tests/unit/agents/services/eventing/test_event_publishing_service.py @@ -1,9 +1,13 @@ """Unit tests for EventPublishingService.""" +from collections.abc import Callable from unittest.mock import AsyncMock, MagicMock import pytest +from blueprint.agents.clients.io.io_client_base import IOClientBase +from blueprint.agents.component.component import Component +from blueprint.agents.component.registry import Registry from blueprint.agents.models.config import EventPublishingConfig, TopicConfig from blueprint.agents.models.events import GenericCloudEvent from blueprint.agents.services.eventing.event_publishing_service import EventPublishingService @@ -15,13 +19,13 @@ class TestLifecycle: async def test_on_startup_resolves_client_from_registry( - self, mock_registry: MagicMock, mock_config: MagicMock, mock_io_client: MagicMock + self, real_registry: Registry, mock_config: MagicMock, register_client: Callable[[str], MagicMock] ) -> None: mock_config.get_event_publishing_config.return_value = EventPublishingConfig() - mock_registry.get_io_clients.return_value = [mock_io_client] + client = register_client("") svc = EventPublishingService() await svc.on_startup() - assert svc._client is mock_io_client + assert svc._client is client async def test_on_startup_loads_pub_config(self, mock_registry: MagicMock, mock_config: MagicMock, mock_io_client: MagicMock) -> None: expected = EventPublishingConfig(topic_mapping={"x.event": TopicConfig(topic="t")}) @@ -221,12 +225,31 @@ async def test_delegates_to_publish_event( # --------------------------------------------------------------------------- -def _client_in(namespace: str) -> MagicMock: - """Return a mock IO client belonging to a namespace.""" - client = MagicMock() - client.publish = AsyncMock() - client.namespace = namespace - return client +@pytest.fixture +def real_registry() -> Registry: + """A real Registry, because what is under test is the resolution it performs. + + `EventPublishingService` no longer resolves its client by hand: `self.registry` is its + namespace's view, and the view is what prefers this agent's transport over a root one. A + MagicMock registry would only assert that a stub returned what it was told to. + """ + registry = Registry(Component) + Component.shared_registry = registry + return registry + + +@pytest.fixture +def register_client(real_registry: Registry) -> Callable[[str], MagicMock]: + """Register an IO client belonging to a namespace, named as Component would name it.""" + + def _register(namespace: str, name: str = "nats_client") -> MagicMock: + client = MagicMock(spec=IOClientBase) + client.namespace = namespace + client.publish = AsyncMock() + real_registry.add_component(f"{namespace}_{name}" if namespace else name, client) + return client + + return _register class TestNamespaceOwnership: @@ -239,41 +262,55 @@ def test_root_service_keeps_the_unqualified_registry_name(self, mock_registry: M def test_namespaced_service_registers_under_a_qualified_name(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: assert EventPublishingService(namespace="orders").name == "orders_event_publishing_service" - async def test_publishes_on_its_own_namespaces_client(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: + async def test_publishes_on_its_own_namespaces_client( + self, real_registry: Registry, mock_config: MagicMock, register_client: Callable[..., MagicMock] + ) -> None: """Outbound traffic on another namespace's connection would be unattributable.""" - own, root = _client_in("orders"), _client_in("") - mock_registry.get_io_clients.return_value = [root, own] + register_client("") + own = register_client("orders") mock_config.get_event_publishing_config.return_value = EventPublishingConfig() + svc = EventPublishingService(namespace="orders") await svc.on_startup() + assert svc._client is own - async def test_falls_back_to_the_root_client(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: + async def test_falls_back_to_the_root_client( + self, real_registry: Registry, mock_config: MagicMock, register_client: Callable[..., MagicMock] + ) -> None: """A namespaced agent in a process with one shared transport keeps working.""" - root = _client_in("") - mock_registry.get_io_clients.return_value = [root, _client_in("invoice")] + root = register_client("") + register_client("invoice") mock_config.get_event_publishing_config.return_value = EventPublishingConfig() + svc = EventPublishingService(namespace="orders") await svc.on_startup() + assert svc._client is root - async def test_never_borrows_another_namespaces_client(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: - mock_registry.get_io_clients.return_value = [_client_in("invoice")] + async def test_never_borrows_another_namespaces_client( + self, real_registry: Registry, mock_config: MagicMock, register_client: Callable[..., MagicMock] + ) -> None: + register_client("invoice") mock_config.get_event_publishing_config.return_value = EventPublishingConfig() + svc = EventPublishingService(namespace="orders") - with pytest.raises(ValueError, match="No IO transport client is registered"): + with pytest.raises(ValueError, match="No IOClientBase is registered"): await svc.on_startup() - async def test_two_clients_in_one_namespace_raise(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: - mock_registry.get_io_clients.return_value = [_client_in("orders"), _client_in("orders")] + async def test_two_clients_in_one_namespace_raise( + self, real_registry: Registry, mock_config: MagicMock, register_client: Callable[..., MagicMock] + ) -> None: + register_client("orders", "nats_client") + register_client("orders", "dapr_client") mock_config.get_event_publishing_config.return_value = EventPublishingConfig() + svc = EventPublishingService(namespace="orders") with pytest.raises(ValueError, match="ambiguous"): await svc.on_startup() - async def test_no_client_at_all_raises(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: - mock_registry.get_io_clients.return_value = [] + async def test_no_client_at_all_raises(self, real_registry: Registry, mock_config: MagicMock) -> None: mock_config.get_event_publishing_config.return_value = EventPublishingConfig() svc = EventPublishingService() - with pytest.raises(ValueError, match="No IO transport client is registered"): + with pytest.raises(ValueError, match="No components of type"): await svc.on_startup() diff --git a/tests/unit/agents/services/infrastructure/test_agent_scoped_cache.py b/tests/unit/agents/services/infrastructure/test_agent_scoped_cache.py new file mode 100644 index 00000000..b8accc7b --- /dev/null +++ b/tests/unit/agents/services/infrastructure/test_agent_scoped_cache.py @@ -0,0 +1,169 @@ +"""Unit tests for AgentScopedCache -- one cache, isolated per agent (spec sec. 8).""" + +from collections.abc import Iterator +from pathlib import Path + +import pytest + +from blueprint.agents.component.component import Component +from blueprint.agents.component.registry import Registry +from blueprint.agents.services.infrastructure.agent_scoped_cache import AgentScopedCache +from blueprint.agents.services.infrastructure.cache_service import DiskCacheService + + +@pytest.fixture +def backend(tmp_path: Path) -> Iterator[DiskCacheService]: + """A real disk cache, because what is under test is which keys end up where.""" + cache = DiskCacheService(cache_dir=str(tmp_path / "cache"), enable_locking=False) + yield cache + cache.close() + + +@pytest.fixture +def orders(backend: DiskCacheService) -> AgentScopedCache: + return AgentScopedCache(backend, "orders") + + +@pytest.fixture +def billing(backend: DiskCacheService) -> AgentScopedCache: + return AgentScopedCache(backend, "billing") + + +class TestIsolation: + def test_two_agents_do_not_see_each_others_values(self, orders: AgentScopedCache, billing: AgentScopedCache) -> None: + """The whole point: the same key in the same partition name, kept apart.""" + orders.set("laptop", {"price": 1}, namespace="prices") + billing.set("laptop", {"price": 2}, namespace="prices") + + assert orders.get("laptop", namespace="prices") == {"price": 1} + assert billing.get("laptop", namespace="prices") == {"price": 2} + + def test_a_neighbours_key_reads_as_absent(self, orders: AgentScopedCache, billing: AgentScopedCache) -> None: + billing.set("laptop", {"price": 2}, namespace="prices") + assert orders.get("laptop", namespace="prices") is None + assert orders.exists("laptop", namespace="prices") is False + + def test_one_backend_serves_every_agent(self, orders: AgentScopedCache, billing: AgentScopedCache, backend: DiskCacheService) -> None: + """No second directory and no second connection -- that is why the keys carry the agent.""" + assert orders.backend is billing.backend is backend + + def test_the_partition_carries_the_agent(self, orders: AgentScopedCache, billing: AgentScopedCache, backend: DiskCacheService) -> None: + orders.set("laptop", 1, namespace="prices") + billing.set("laptop", 2, namespace="prices") + assert backend.list_namespaces() == ["billing.prices", "orders.prices"] + + def test_an_agent_lists_its_partitions_by_the_names_it_used(self, orders: AgentScopedCache, billing: AgentScopedCache) -> None: + orders.set("laptop", 1, namespace="prices") + orders.set("session", 1, namespace="sessions") + billing.set("laptop", 2, namespace="prices") + + assert orders.list_namespaces() == ["prices", "sessions"] + + def test_the_default_partition_is_scoped_too(self, orders: AgentScopedCache, billing: AgentScopedCache) -> None: + orders.set("k", 1) + billing.set("k", 2) + assert (orders.get("k"), billing.get("k")) == (1, 2) + + def test_delete_only_reaches_this_agent(self, orders: AgentScopedCache, billing: AgentScopedCache) -> None: + orders.set("laptop", 1, namespace="prices") + billing.set("laptop", 2, namespace="prices") + + orders.delete("laptop", namespace="prices") + + assert orders.get("laptop", namespace="prices") is None + assert billing.get("laptop", namespace="prices") == 2 + + def test_claim_is_per_agent(self, orders: AgentScopedCache, billing: AgentScopedCache) -> None: + """Two agents' schedulers must not steal each other's tick slots.""" + assert orders.claim("tick", "held", namespace="ticks", ttl=60) is True + assert billing.claim("tick", "held", namespace="ticks", ttl=60) is True + assert orders.claim("tick", "held", namespace="ticks", ttl=60) is False + + +class TestClear: + def test_clearing_one_partition_leaves_the_neighbour(self, orders: AgentScopedCache, billing: AgentScopedCache) -> None: + orders.set("laptop", 1, namespace="prices") + billing.set("laptop", 2, namespace="prices") + + orders.clear("prices") + + assert orders.get("laptop", namespace="prices") is None + assert billing.get("laptop", namespace="prices") == 2 + + def test_clearing_everything_means_everything_of_this_agent(self, orders: AgentScopedCache, billing: AgentScopedCache) -> None: + """The backend's own clear(None) would take the neighbours with it.""" + orders.set("a", 1, namespace="prices") + orders.set("b", 1, namespace="sessions") + billing.set("c", 2, namespace="prices") + + orders.clear() + + assert orders.list_namespaces() == [] + assert billing.get("c", namespace="prices") == 2 + + +class TestOwnership: + def test_closing_the_shared_backend_is_refused(self, orders: AgentScopedCache, backend: DiskCacheService) -> None: + with pytest.raises(RuntimeError, match="shared with every other agent"): + orders.close() + + def test_the_root_namespace_cannot_be_wrapped(self, backend: DiskCacheService) -> None: + """The root reads the backend directly; wrapping it would move an existing app's keys.""" + with pytest.raises(ValueError, match="needs an agent namespace"): + AgentScopedCache(backend, "") + + def test_it_does_not_register_itself(self, backend: DiskCacheService) -> None: + """One lens per agent per cache would otherwise add a registry entry each.""" + Component.reset_shared_state() + registry = Registry(Component) + Component.shared_registry = registry + + AgentScopedCache(backend, "orders") + + assert registry.get_component_names_by_type(AgentScopedCache) == [] + + def test_stats_come_from_the_backend_and_name_the_agent(self, orders: AgentScopedCache) -> None: + """Size and eviction belong to the one shared store; there is nothing per-agent to report.""" + assert orders.get_stats()["agent"] == "orders" + + def test_hash_is_the_backends(self, orders: AgentScopedCache, backend: DiskCacheService) -> None: + assert orders.hash("laptop") == backend.hash("laptop") + + +class TestThroughTheRegistry: + """How a component actually gets one: it asks for a cache and is handed its own view.""" + + @pytest.fixture + def registry(self, backend: DiskCacheService) -> Registry: + Component.reset_shared_state() + registry = Registry(Component) + Component.shared_registry = registry + registry.add_cache("default", backend) + return registry + + def test_a_namespaced_view_gets_a_scoped_cache(self, registry: Registry) -> None: + cache = registry.for_namespace("orders").cache_service + assert isinstance(cache, AgentScopedCache) + assert cache.agent == "orders" + + def test_the_root_gets_the_backend_itself(self, registry: Registry, backend: DiskCacheService) -> None: + """Unchanged for every single-agent application, and the opt-in for a shared cache.""" + assert registry.cache_service is backend + + def test_asking_twice_gives_one_lens(self, registry: Registry) -> None: + view = registry.for_namespace("orders") + assert view.cache_service is view.cache_service + + def test_two_agents_get_different_lenses(self, registry: Registry) -> None: + orders = registry.for_namespace("orders").cache_service + billing = registry.for_namespace("billing").cache_service + assert orders is not billing + + def test_a_named_cache_is_scoped_too(self, registry: Registry, backend: DiskCacheService) -> None: + registry.add_cache("sessions", backend) + cache = registry.for_namespace("orders").get_cache("sessions") + assert isinstance(cache, AgentScopedCache) + + def test_an_unregistered_name_still_raises_on_a_view(self, registry: Registry) -> None: + with pytest.raises(ValueError, match="No cache registered as 'prompts'"): + registry.for_namespace("orders").get_cache("prompts") diff --git a/tests/unit/agents/services/infrastructure/test_cache_backend_factory.py b/tests/unit/agents/services/infrastructure/test_cache_backend_factory.py index 049bce2f..16a6929e 100644 --- a/tests/unit/agents/services/infrastructure/test_cache_backend_factory.py +++ b/tests/unit/agents/services/infrastructure/test_cache_backend_factory.py @@ -1,17 +1,21 @@ """Unit tests for CacheBackendFactory. -Focus is on the ``enable_locking`` propagation through the Redis→Disk fallback -paths, which was previously dropped silently. +Two concerns. The first is ``enable_locking`` propagation through the Redis-to-Disk fallback +paths, which was previously dropped silently. The second is that a cache *name* buys isolated +storage: the factory is where a backend is chosen, so it is where each backend answers how it +separates one named cache from another -- a directory for disk, a key prefix for Redis. """ from __future__ import annotations import builtins import sys +from pathlib import Path from unittest.mock import MagicMock, patch import pytest +from blueprint.agents.component.registry import DEFAULT_CACHE_NAME from blueprint.agents.models.config import CacheConfig from blueprint.agents.services.infrastructure.cache_backend_factory import CacheBackendFactory from blueprint.agents.services.infrastructure.cache_service import DiskCacheService @@ -119,3 +123,134 @@ def test_redis_fallback_log_does_not_leak_credentials(tmp_path, caplog: pytest.L assert "supersecret" not in caplog.text assert "redis://host:6379/0" in caplog.text + + +class TestComponentName: + def test_the_default_cache_keeps_its_derived_name(self) -> None: + """None means "derive it", which is the name existing lookups and health entries use.""" + assert CacheBackendFactory._component_name(DEFAULT_CACHE_NAME) is None + + def test_a_named_cache_gets_its_own(self) -> None: + assert CacheBackendFactory._component_name("sessions") == "cache_sessions" + + def test_the_name_does_not_depend_on_the_backend(self, redis_fallback_config: CacheConfig) -> None: + """fallback_to_local swaps the class, so a class-derived key would move on a Redis outage.""" + failing = MagicMock() + failing._client.ping.side_effect = ConnectionError("simulated outage") + + with patch( + "blueprint.agents.services.infrastructure.redis_cache_service.RedisCacheService", + return_value=failing, + ): + service = CacheBackendFactory.create(redis_fallback_config, name="sessions") + + assert isinstance(service, DiskCacheService) + assert service.name == "cache_sessions" + + +class TestDiskIsolation: + def test_the_default_cache_uses_the_configured_directory(self, disk_config: CacheConfig) -> None: + assert CacheBackendFactory._scoped_cache_dir(disk_config, DEFAULT_CACHE_NAME) == disk_config.cache_dir + + def test_a_name_becomes_a_subdirectory(self) -> None: + config = CacheConfig(cache_dir=".cache/blueprint") + assert CacheBackendFactory._scoped_cache_dir(config, "sessions") == ".cache/blueprint/sessions" + + def test_a_windows_separator_does_not_survive_into_the_path(self) -> None: + config = CacheConfig(cache_dir=".cache\\blueprint") + assert CacheBackendFactory._scoped_cache_dir(config, "sessions") == ".cache/blueprint/sessions" + + def test_the_created_cache_stores_in_it(self, disk_config: CacheConfig, tmp_path: Path) -> None: + service = CacheBackendFactory.create(disk_config, name="sessions") + assert isinstance(service, DiskCacheService) + assert service.cache_dir == tmp_path / "cache" / "sessions" + + def test_two_names_do_not_share_a_directory(self, disk_config: CacheConfig) -> None: + first = CacheBackendFactory._scoped_cache_dir(disk_config, "sessions") + assert first != CacheBackendFactory._scoped_cache_dir(disk_config, "prompts") + + +class TestRedisIsolation: + def test_the_default_cache_uses_the_configured_prefix(self) -> None: + config = CacheConfig(backend="redis", key_prefix="myapp") + assert CacheBackendFactory._scoped_key_prefix(config, DEFAULT_CACHE_NAME) == "myapp" + + def test_a_name_is_appended_to_the_prefix(self) -> None: + config = CacheConfig(backend="redis", key_prefix="myapp") + assert CacheBackendFactory._scoped_key_prefix(config, "sessions") == "myapp:sessions" + + def test_a_name_becomes_the_prefix_when_none_is_configured(self) -> None: + assert CacheBackendFactory._scoped_key_prefix(CacheConfig(backend="redis"), "sessions") == "sessions" + + def test_two_names_do_not_share_a_keyspace(self) -> None: + """Without this the name would isolate nothing on Redis: the prefix is all there is.""" + config = CacheConfig(backend="redis", key_prefix="myapp") + first = CacheBackendFactory._scoped_key_prefix(config, "sessions") + assert first != CacheBackendFactory._scoped_key_prefix(config, "prompts") + + def test_the_created_service_is_given_the_scoped_prefix(self, tmp_path: Path) -> None: + config = CacheConfig(backend="redis", redis_url="redis://localhost:6379/0", key_prefix="myapp") + reachable = MagicMock() + + with patch( + "blueprint.agents.services.infrastructure.redis_cache_service.RedisCacheService", + return_value=reachable, + ) as constructor: + CacheBackendFactory.create(config, name="sessions") + + assert constructor.call_args.kwargs["key_prefix"] == "myapp:sessions" + assert constructor.call_args.kwargs["component_name"] == "cache_sessions" + + +class TestTheFallbackIsolatesAsDiskNotAsRedis: + def test_the_fallback_uses_the_directory_for_the_name(self, redis_fallback_config: CacheConfig, tmp_path: Path) -> None: + """The fallback is a different backend, so it needs its own isolation -- a directory.""" + failing = MagicMock() + failing._client.ping.side_effect = ConnectionError("simulated outage") + + with patch( + "blueprint.agents.services.infrastructure.redis_cache_service.RedisCacheService", + return_value=failing, + ): + service = CacheBackendFactory.create(redis_fallback_config, name="sessions") + + assert isinstance(service, DiskCacheService) + assert service.cache_dir == tmp_path / "cache" / "sessions" + + def test_the_import_error_fallback_does_the_same( + self, redis_fallback_config: CacheConfig, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + real_import = builtins.__import__ + + def _fail_redis_import(name, *args, **kwargs): + if name == "blueprint.agents.services.infrastructure.redis_cache_service": + raise ImportError("simulated missing extra") + return real_import(name, *args, **kwargs) + + monkeypatch.delitem(sys.modules, "blueprint.agents.services.infrastructure.redis_cache_service", raising=False) + monkeypatch.setattr(builtins, "__import__", _fail_redis_import) + + service = CacheBackendFactory.create(redis_fallback_config, name="sessions") + + assert isinstance(service, DiskCacheService) + assert service.cache_dir == tmp_path / "cache" / "sessions" + + +class TestCacheNameValidation: + @pytest.mark.parametrize( + "name", + ["Sessions", "../evil", "a/b", "a\\b", "", " ", "a:b", ".hidden", "_leading", "-leading", "sess ions"], + ) + def test_a_name_that_cannot_be_a_directory_is_refused(self, disk_config: CacheConfig, name: str) -> None: + with pytest.raises(ValueError, match="not a legal cache name"): + CacheBackendFactory.create(disk_config, name=name) + + @pytest.mark.parametrize("name", ["sessions", "default", "llm-responses", "v2.cache", "a", "0", "a_b"]) + def test_a_usable_name_is_accepted(self, disk_config: CacheConfig, name: str) -> None: + assert isinstance(CacheBackendFactory.create(disk_config, name=name), DiskCacheService) + + def test_the_name_is_checked_before_anything_is_built(self, disk_config: CacheConfig, tmp_path: Path) -> None: + """Otherwise a rejected name would already have created a directory outside the cache.""" + with pytest.raises(ValueError): + CacheBackendFactory.create(disk_config, name="../evil") + assert not (tmp_path / "evil").exists() diff --git a/tests/unit/agents/services/infrastructure/test_cache_sharing_via_registry.py b/tests/unit/agents/services/infrastructure/test_cache_sharing_via_registry.py index 2bd57a4b..c8f9dedc 100644 --- a/tests/unit/agents/services/infrastructure/test_cache_sharing_via_registry.py +++ b/tests/unit/agents/services/infrastructure/test_cache_sharing_via_registry.py @@ -149,15 +149,20 @@ def test_bidirectional_write_read_round_trip(self, two_services_sharing_cache: t assert writer.read("price:laptop") == {"amount": 49.99} assert reader.read("recommendation:laptop") == {"verdict": "BUY"} - def test_registry_setter_rejects_double_registration(self, shared_cache: DiskCacheService, tmp_path: Path) -> None: - """AC-protection: assigning a 2nd cache to the registry raises, ensuring - a single source of truth across all services.""" + def test_the_default_cache_stays_a_single_source_of_truth(self, shared_cache: DiskCacheService, tmp_path: Path) -> None: + """AC-protection: there is one cache called "default", so every service reads the same one. + + Assigning a second one replaces it rather than raising -- named caches made the setter an + upsert -- so what protects the invariant is that both services still resolve one object, + and that the replacement is announced. + """ Component.shared_registry = Registry(Component) Component.shared_registry.cache_service = shared_cache second_cache = DiskCacheService(cache_dir=str(tmp_path / "second"), enable_locking=False) try: - with pytest.raises(ValueError): - Component.shared_registry.cache_service = second_cache + Component.shared_registry.cache_service = second_cache + assert Component.shared_registry.cache_service is second_cache + assert list(Component.shared_registry.get_all_caches()) == ["default"] finally: second_cache.close() diff --git a/tests/unit/agents/services/infrastructure/test_disk_cache_service.py b/tests/unit/agents/services/infrastructure/test_disk_cache_service.py index 22d146a0..117f70a8 100644 --- a/tests/unit/agents/services/infrastructure/test_disk_cache_service.py +++ b/tests/unit/agents/services/infrastructure/test_disk_cache_service.py @@ -1,5 +1,6 @@ """Unit tests for DiskCacheService.""" +from pathlib import Path from unittest.mock import patch import pytest @@ -304,3 +305,34 @@ def test_an_unreachable_cache_fails_open(self, cache_service: DiskCacheService) with patch.object(cache_service, "_cache") as broken: broken.add.side_effect = OSError("disk gone") assert cache_service.claim("slot", 1) is True + + +class TestUnwritableCacheDirectory: + """The production failure this cannot create its own directory for.""" + + def test_the_error_names_the_path_and_the_options(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """A container image with a root-owned workdir, or a read-only root filesystem, both land here.""" + + def refuse(*_args: object, **_kwargs: object) -> None: + raise PermissionError(13, "Permission denied") + + monkeypatch.setattr(Path, "mkdir", refuse) + + with pytest.raises(RuntimeError, match="could not be created") as error: + DiskCacheService(cache_dir=str(tmp_path / "denied"), enable_locking=False) + + message = str(error.value) + assert "denied" in message + assert "mount a volume" in message + assert "redis" in message + + def test_the_original_error_is_kept_as_the_cause(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + def refuse(*_args: object, **_kwargs: object) -> None: + raise PermissionError(13, "Permission denied") + + monkeypatch.setattr(Path, "mkdir", refuse) + + with pytest.raises(RuntimeError) as error: + DiskCacheService(cache_dir=str(tmp_path / "denied"), enable_locking=False) + + assert isinstance(error.value.__cause__, PermissionError) From 8ff9ae94dd2dff7b6288749a5f2fdb17bdfa7a72 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:44:53 +0200 Subject: [PATCH 009/133] feat(eventing): host a group in one process, each event to one agent Phases 5-7. Dispatch is indexed on declared event types, wildcard by default, and each event goes to one agent's handlers; subscriptions are per agent, so two agents may want the same topic; one transport client is wired per agent and none for an agent that needs none; each agent's routes mount under its own prefix; every named cache is managed and probed, not only the default. On Dapr the one endpoint routes and fans out in the process. A handler may say which agent runtime should serve an event. Co-Authored-By: Claude Opus 5 (1M context) --- ...26-08-28-multi-agent-grouping-changelog.md | 1010 ++++++++++++++++- src/blueprint/agents/app_builder.py | 279 +++-- .../agents/handler/event_handler_base.py | 72 ++ src/blueprint/agents/handler/handler_chain.py | 326 +++++- .../agents/handler/sessions_job_handler.py | 21 +- .../eventing/cloud_event_processor_mixin.py | 11 +- src/blueprint/agents/io/api/eventing/dapr.py | 217 +++- .../io/api/eventing/event_handling_base.py | 28 +- src/blueprint/agents/io/api/eventing/nats.py | 71 +- .../agents/io/api/eventing/sessions_bus.py | 14 +- src/blueprint/agents/io/api/rest_api_base.py | 36 +- .../agents/io/api/utilities/cache.py | 66 +- src/blueprint/agents/models/errors.py | 39 + .../eventing/event_processing_service.py | 101 +- .../agents/services/sessions/api_client.py | 12 +- .../agents/services/sessions/key_provider.py | 12 +- tests/unit/agents/app_builder/conftest.py | 3 + .../agents/app_builder/test_app_builder.py | 19 +- .../app_builder/test_build_namespaces.py | 250 ++++ .../agents/app_builder/test_named_caches.py | 46 +- .../app_builder/test_route_namespacing.py | 208 ++++ .../agents/clients/io/test_nats_client.py | 79 ++ .../agents/handler/test_dispatch_index.py | 297 +++++ .../agents/handler/test_runtime_binding.py | 296 +++++ .../unit/agents/io/api/eventing/test_dapr.py | 23 +- .../io/api/eventing/test_dapr_fanout.py | 290 +++++ .../api/eventing/test_eventing_namespaces.py | 187 +++ .../agents/io/api/utilities/test_cache.py | 143 ++- .../test_event_processing_namespaces.py | 262 +++++ .../eventing/test_event_processing_service.py | 44 +- 30 files changed, 4224 insertions(+), 238 deletions(-) create mode 100644 tests/unit/agents/app_builder/test_build_namespaces.py create mode 100644 tests/unit/agents/app_builder/test_route_namespacing.py create mode 100644 tests/unit/agents/handler/test_dispatch_index.py create mode 100644 tests/unit/agents/handler/test_runtime_binding.py create mode 100644 tests/unit/agents/io/api/eventing/test_dapr_fanout.py create mode 100644 tests/unit/agents/io/api/eventing/test_eventing_namespaces.py create mode 100644 tests/unit/agents/services/eventing/test_event_processing_namespaces.py diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index e705ab2c..1beaf717 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -2629,6 +2629,918 @@ subdirectory including a Windows separator in the configured path; the Redis pre on the derivation and on the kwargs the service is constructed with; both fallback paths isolating as disk rather than as Redis; and the name being validated before any directory is created. +### Phase 4, part 1 -- dispatch happens per agent, and the root stops reaching into one + +Phase 1 and 2 made the registry answer per namespace and gave every component its own view of +it. The dispatch path never used any of that: one `HandlerChain` served the process, and it asked +the *application's* registry for handlers -- which in a grouped process means every agent's. This +step makes an event reach one agent's handlers and no other's. The dispatch index (spec sec. 7.7, +the second half of plan phase 4) is a separate step and is not in this one. + +**A `HandlerChain` now belongs to a namespace, and that is the only line about it in the class:** + +```python + def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: + super().__init__(should_register=False, namespace=namespace) +``` + +Everything else follows from `Component.registry` and `Component.config` handing a component its +own namespace's view: the handlers it dispatches to, the `idempotency_enabled` / `idempotency_ttl` +it reads, and the cache partition the dedup markers are claimed in (the agent-scoped lens from +spec sec. 8) are all that agent's already, with no further plumbing. Two agents in one process can +therefore run different dedup windows, and the tests assert exactly that against one settings +tree. + +**The namespace is named explicitly in `_dispatch`, and that is the load-bearing part:** + +```python + handlers = sorted(self.registry.get_event_handler(namespace=self.namespace)) +``` + +It looks redundant -- the registry view already defaults to its own namespace -- and it is not. +`Registry.for_namespace("")` returns the registry *itself*, whose `_default_namespace` is `None`, +and on the registry an omitted namespace means **every namespace**. So a root chain in a grouped +process would have dispatched one delivery through every agent's handlers. Naming the namespace +makes the root chain mean strictly the root, which in a single-agent application is every handler +there is -- unchanged. `test_the_root_chain_does_not_reach_into_an_agent` is the test for it. + +There is deliberately **no fallback to root handlers** either, unlike the singleton lookups that +resolve namespace-then-root. A handler registered at the root of a grouped process would +otherwise run for every agent in it, and nothing in a handler's code could tell its author that +was happening. + +**`EventProcessingService` keeps one chain per agent and stays a single root service.** What it +does -- correlation context, request ids, Dapr unwrapping, normalising handler output -- is the +same for every agent; what differs is the dispatch. So: + +```python + self._handler_chains: dict[str, HandlerChain] = {ROOT_NAMESPACE: HandlerChain()} +``` + +The root chain always exists, so an application that never mentions a namespace behaves exactly +as it did. `_chain_for(namespace)` creates the others: + +```python + chain = self._handler_chains.get(namespace) + if chain is None: + chain = HandlerChain(namespace=namespace) + self._handler_chains[namespace] = chain +``` + +**The chains are built at startup, not on first delivery**, and the namespaces come from the +handlers rather than from a list of agents: + +```python + for namespace in sorted({namespace_of(handler) for handler in self.registry.get_event_handler()}): + self._chain_for(namespace) + + for namespace, chain in self._handler_chains.items(): + await chain.on_startup() +``` + +A chain's startup resolves its idempotency policy, and the existing guarantee is that a +misconfigured dedup window fails the pod rather than the first event. That guarantee is *per +agent*: built lazily, a group whose second agent has a bad `idempotency_ttl` would start cleanly +and fail on a delivery hours later, while the first agent's clean startup said nothing about it. + +Reading the namespaces off the registered handlers is not a way around C6. The registry +deliberately cannot enumerate agents, and this service is not the builder -- but what it needs is +not "which agents exist", it is "which namespaces have handlers to dispatch to", and the handlers +are the authority on that. `_chain_for` stays lazy for anything that arrives later, because a +handler registered after startup should produce a dispatch that finds nobody -- an outcome the +acknowledgement contract already has a disposition for -- rather than a failed delivery. + +**`process_event` and `process_rest_request` take a keyword-only `namespace`.** Keyword-only +because both already have positional tails that existing callers use; `""` is the root, which is +what every caller that does not know about agents gets. + +**The publishing-service lookup became namespace-aware, and that was a latent crash:** + +```python + # This agent's publishing service, falling back to a root one. Not the + # 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) +``` + +P6 already gives each namespace its own `EventPublishingService`. The old call passed no +namespace, which on the application's registry means "search every namespace and raise if more +than one matches" -- so the first handler in a grouped process to return a `HandlerResult` with an +`event_type` would have raised `Multiple components of type EventPublishingService found`. With +`namespace=""` the lookup is restricted to the root, which is where the only publishing service in +a single-agent application lives. + +**The two call sites pass their own namespace**, which is what makes the parameter reach anything: + +- `CloudEventProcessorMixin._dispatch_cloud_event` passes `namespace=self.namespace` -- the + namespace of the transport endpoint that received the delivery. Its docstring's contract grew + from "a class that supplies a `registry` attribute" to `registry` and `namespace`. +- `RestApiBase._process_resource` passes `namespace=self.namespace`, so a REST call into one agent + is not offered to another agent's handlers. + +Both are the root today, so both are today's behaviour today; they become per-agent the moment +phase 5 and 6 give each namespace its own endpoints. + +**Not in this step.** The plan's third phase-4 bullet -- "wire previously unused `runtime_name`: +after the chain picks a winner, resolve the agent via `get_runtime_name()`" -- depends on +`EventHandlerBase.get_runtime_name`, which phase 7 adds. The spec's own compatibility table +(sec. 10) records `runtime_name` as only logged today, so it stays logged; the namespace is now +logged alongside it. + +Tests: `tests/unit/agents/services/eventing/test_event_processing_namespaces.py`, 18 cases against +real `Config`, `Registry`, `HandlerChain` and handler subclasses rather than mocks -- an event +reaching one agent's handler and not the other's; a namespace with no handler returning +`NO_HANDLER_FOUND` rather than raising; the root chain not reaching into an agent; a root handler +not running for an agent; a single-agent application dispatching as before over both `process_event` +and `process_rest_request`; one chain per namespace with handlers, each carrying its own namespace +and resolving its own agent's dedup policy from one settings tree; a chain created on first use for +an unknown namespace and reused across deliveries; an illegal namespace refused; and four cases for +`HandlerChain` itself, including that it is still not a registered component. The three +mock-based lifecycle tests in `test_event_processing_service.py` were updated to the chain map and +one added for the per-namespace startup. + +### Phase 4, part 2 -- a handler can say what it wants, and stops being asked about the rest + +`_dispatch` asked every registered handler's `can_handle` in turn until one said yes, so a +process hosting fifty handlers awaited fifty coroutines to find the one that wanted the event. +Grouping multiplies exactly that, because a group's handlers all live in one process. Spec +sec. 7.7 asks for an in-process dispatch index; this is it. + +**The declaration: `EventHandlerBase.get_handled_event_types()`**, defaulting to `[]`. It joins +the two declaration methods already on the class (`get_published_event_types`, +`get_subscribed_topics`) and is a *selection hint, not a selector* -- `can_handle_event` still +decides, and a declared handler is still asked and may still say no. + +**The default means "offer me everything", and getting that backwards is the whole risk.** No +handler in this framework or in any scaffolded project declares an event type today, so an index +that read an empty declaration as an empty set would silence every handler that exists -- and +because an unhandled event acknowledges (spec sec. 7.2), the deliveries would be consumed and +discarded rather than piling up anywhere visible. Spec sec. 7.7 calls this "the most destructive +failure mode available in this design". + +**`DispatchIndex`** is a frozen dataclass with two fields and one question: + +```python + by_type: dict[str, tuple[EventHandlerBase, ...]] + wildcard: tuple[EventHandlerBase, ...] + + def candidates(self, event_type: str) -> tuple[EventHandlerBase, ...]: + return self.by_type.get(event_type, self.wildcard) +``` + +`by_type[t]` already holds the *merged* candidate list -- the handlers that declared `t` plus +every wildcard handler -- so dispatch is one dictionary lookup and no per-event merging or +sorting. An event type nobody declared falls back to `wildcard`, because a type no handler named +is not a type no handler wants. + +**The candidate lists are built by filtering the priority-sorted order, not by concatenating +buckets:** + +```python + wildcard = tuple(handler for handler, declared in declarations if not declared) + by_type = { + event_type: tuple(handler for handler, declared in declarations if not declared or event_type in declared) + for event_type in {event_type for _, declared in declarations for event_type in declared} + } +``` + +Concatenating `typed + wildcard` and sorting would have put declared handlers ahead of undeclared +ones *of equal priority*, and priority ties are currently resolved by registration order -- +something a project may be relying on without having said so. Filtering the already-sorted list +means the sequence a handler is tried in is exactly the sequence it would have been tried in +without an index. There is a test comparing the two orders. + +**A declaration that looks like a pattern is refused, at startup:** + +```python + if _WILDCARD_IN_DECLARATION.search(event_type): + raise ValueError( + f"Handler '{handler.name}' declares the event type '{event_type}', which looks like a pattern. " + "Declarations are matched by equality, so this handler would never be asked about any event. ..." + ) +``` + +This is not defensive tidiness, it closes a hole the new API opens. Declarations are matched by +equality, so `get_handled_event_types() -> ["order.*"]` is a type no event ever has: the handler +would go in the typed bucket for the literal string and never be asked about anything -- the same +silent silencing, reintroduced by the very method meant to avoid it. Blank declarations are +refused for the same reason. Both fail while the pod is starting, naming the handler. + +**The index is built once at startup, and checked on every dispatch.** `on_startup` builds it (so +a malformed declaration fails the pod) and logs how many handlers are offered every event against +how many event types are declared -- the observable evidence that nothing was silenced. But +`_candidates` re-reads the handlers: + +```python + handlers = self._handlers() + if self._index is None or handlers != self._indexed: + self._indexed = handlers + self._index = DispatchIndex.build(handlers) + return self._index.candidates(event_type) +``` + +Before the index, the chain queried the registry per event, so a handler registered after startup +was picked up automatically. A purely startup-built index would drop it silently, which is the +class of failure this design is most careful about. The check costs exactly what the old code +already paid -- one registry query and now a tuple comparison instead of a sort -- while the index +still removes the `can_handle` await per handler, which is the expensive part. `HandlerChain` +being unregistered means nothing calls its `on_startup` when it is used outside `AppBuilder`, and +the same branch covers that. + +**`SessionsJobHandler` opts in without its subclasses writing anything.** Its `can_handle_event` +was `event.type == f"sessions.job.created.{self.JOB_TYPE}"`; that string now has one definition: + +```python + @property + def job_created_event_type(self) -> str: + return f"sessions.job.created.{self.JOB_TYPE}" + + def get_handled_event_types(self) -> list[str]: + return [self.job_created_event_type] +``` + +`can_handle_event` reads the same property. Written out twice the two could drift, and a +declaration that no longer matches the check is a handler the index never offers an event to -- +which is why the property exists rather than a second f-string. A subclass opts in by setting the +`JOB_TYPE` class variable it already had to set. + +`_dispatch` was also split: `_handlers()` now owns the namespace-scoped registry query (with the +explanation of why the namespace is named explicitly, from part 1), and `_dispatch` itself asks +`_candidates(event.type)`. The `handlers.count` span attribute keeps its meaning -- how many +handlers this dispatch will walk -- and the debug line now reports candidates against the total. + +Tests: `tests/unit/agents/handler/test_dispatch_index.py`, 24 cases -- an undeclared handler being +a candidate for every event type, including alongside a declared one, and an undeclared-only +application indexing to nothing at all; declarations narrowing who is asked, every declared type +keyed, and an unknown type falling back to the wildcard handlers or to nobody; candidate order +identical to the unindexed order and priority still deciding; dispatch asking only the candidates, +the chain-of-responsibility fallthrough surviving, and an event no candidate wants returning +`None`; a pattern and a blank declaration refused with the handler named, and the refusal landing +on `on_startup`; the index built at startup, not rebuilt when nothing changed, rebuilt for a +handler registered afterwards, and built on demand for a chain nobody started; and two agents in +one process indexing only their own handlers. One mock-based test in +`test_event_processing_service.py` grew a small stub handler, because a bare `MagicMock` is no +longer sortable now that startup indexes. + +### Phase 5, part 1 -- a transport endpoint subscribes for one agent, and only for one agent + +P6 gave each namespace its own `NATSClient`, with the queue group and the durable derived from +the namespace. What still ran once for the whole process was the thing that decides *what to +subscribe to*: `NatsEventing` and `DaprEventing` each collected topics from +`registry.get_event_handler()` with no namespace, which on the application's registry means every +agent's handlers, and deduplicated the result globally. + +Both of those are wrong in a group, and the second is wrong in the way spec sec. 7.6 singles out. + +**The endpoints are namespace-owned.** `NatsEventing(namespace=...)` and +`DaprEventing(namespace=...)`, so phase 6 can build one per agent: + +```python + def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: + super().__init__(should_register=False, namespace=namespace) +``` + +That needed `RestApiBase.__init__` to accept a namespace, since `EventHandlingBase` is a +`RestApiBase`: + +```python + def __init__(self, should_register: bool = True, *, namespace: str = ROOT_NAMESPACE) -> None: + super().__init__(should_register, namespace=namespace) +``` + +Keyword-only, defaulting to the root, and every existing subclass already calls +`super().__init__()` or `super().__init__(should_register=False)` by keyword -- so nothing +changes for a developer's API, which still gets its namespace from the ambient scope. The +framework's own per-agent endpoints are constructed outside any scope, which is why they name it. + +**Each endpoint resolves its own agent's client:** + +```python + self._client = self.registry.get_component(NATSClient, namespace=self.namespace) +``` + +Unscoped, this raised `Multiple components of type NATSClient found` the moment a second agent +joined the process -- P6 created the clients but nothing had been taught to pick between them. +With `namespace=""` the lookup is restricted to the root, which is where a single-agent +application's only client is. + +**`NatsEventing._declared_topics` is new and is where the per-agent scope lands:** + +```python + topics: dict[str, None] = {} + for handler in self.registry.get_event_handler(namespace=self.namespace): + for topic in handler.get_subscribed_topics(): + if topic: + topics[topic] = None + for topic in self.config.get_nats_subscription_config(): + if topic: + topics[topic] = None + return list(topics) +``` + +Two sources, handler declarations first and the configured list second, both already scoped to +this agent -- `self.registry` and `self.config` are this namespace's views, so +`orders.nats_subscriptions` resolves before the shared list (C5) with nothing here saying so. +`DaprEventing._declared_topics` took the same namespace argument, which scopes both halves of the +Dapr path at once: the sidecar's subscription document and the readiness hand-off to `DaprClient`. + +**Deduplication is now per agent because it cannot be anything else.** The `dict` above lives +inside one endpoint, and one endpoint serves one namespace, so a cross-agent "first declaration +wins" is not something that has to be avoided -- it is unreachable. That is the point of spec +sec. 7.6: two agents subscribing to one topic both want the event, and a global dedup would +silently disable one of them, invisibly to an author who runs that agent alone. + +**The unhandled and duplicate counters were attributing every event to the root.** Both are +documented as per-namespace and both were hardcoded: + +```python +- _DUPLICATE_EVENTS.add(1, {"namespace": ROOT_NAMESPACE, "topic": topic}) ++ _DUPLICATE_EVENTS.add(1, {"namespace": self.namespace, "topic": topic}) +``` + +In a group that would have reported one agent's over-broad subscription as everybody's, which is +precisely the signal spec sec. 7.7 wants those counters to carry. The value is the namespace +verbatim rather than `ROOT_LABEL`, so a single-agent application keeps emitting `""` and its +existing dashboards do not suddenly see a new label value. + +**Two plan bullets are already satisfied, and one of them must not be implemented as written.** + +- **"`NATSClient` consumer identity (C1)"** -- the durable `f"{namespace}-{topic}-durable"` and + `queue=namespace` landed with P6. Part 2 of this phase adds the invariant test the plan asks + for. +- **"Give each namespace's JetStream consumer a `filter_subjects` set"** -- already true, in a + better form, and building it as written would make things worse. The client creates **one + durable per `(namespace, topic)` pair** with `filter_subject=topic` + (`nats_client.py:_consumer_config`), so the filter set of a namespace *is* the union of its + declared topics and its `nats_subscriptions`, one consumer per element. The plan's own + objection to a multi-subject filter is the reason to keep it that way: "a filter that follows + handler churn turns adding one handler into a consumer reconfiguration -- and possibly a + redelivery storm on deploy". With one consumer per topic, declaring a new topic *adds* a + consumer and never rewrites one, so there is no reconfiguration to be had. Collapsing several + topics into one consumer with a `filter_subjects` set would reintroduce exactly that. + + The fan-out the bullet worries about is not removable at this layer either: spec sec. 7.6 + *requires* one consumer per `(namespace, topic)`, so a broad subject selected by three agents + is copied three times by definition. Sec. 7.7 asks for that to be *observable*, not absent, and + the plan puts the reporting in `asbs validate`. + +**Also not implemented as written: "iterate `registry.get_known_namespaces()`".** That method +deliberately does not exist -- the registry is reachable from every component, so it would let an +agent enumerate its neighbours (C6). It is not needed: with one endpoint per agent, each one +knows only its own namespace, which is all the collection needs. + +**Still to come in phase 6.** The Dapr path mounts `POST /events/{topic}` and +`GET /dapr/subscribe` on the endpoint's router, and two agents' routers would collide on both +paths. Phase 6 owns the route namespacing and the `_eventing_component` list that creates these +per agent; nothing in this step creates more than one, so nothing collides yet. + +Tests: `tests/unit/agents/io/api/eventing/test_eventing_namespaces.py`, 18 cases -- an endpoint +subscribing its own handlers' topics and not another agent's; two agents on one topic both +getting it, for both transports; a topic declared twice inside one agent subscribed once; the +agent's own `nats_subscriptions` winning and falling back to the shared list; handler topics +ordered before configured ones; each endpoint resolving its own namespace's client and a root +endpoint resolving the root one; only this agent's topics reaching the client; the Dapr +subscription document holding one agent's topics and a root document unchanged; and namespace +ownership, including that an illegal namespace is refused and that endpoints stay unregistered. + +### Phase 5, part 2 -- C1 gets the regression test the plan asks for + +No production change. The plan marks the consumer identity "**C1 -- invariant, cover with a +test**", and the invariant was the one thing about P6's naming that nothing checked: the durable +and the queue group are derived from the namespace, and the tests proved they *are* -- but nothing +proved a deployment value cannot get in. + +That is the failure worth a permanent guard rather than a review. A durable that picks up the +group name becomes a *different* durable the moment the agent is moved between groups, and a +fresh JetStream consumer resumes according to its delivery policy: the agent either replays the +stream from the beginning or silently skips whatever arrived while it was being renamed. Nothing +in the process reports either. And the temptation is real, because the connection name +(`f"{namespace}.{group}.{pod}"`) is right there in the same class and carries both values. + +`TestConsumerIdentityIgnoresTheDeployment` in `tests/unit/agents/clients/io/test_nats_client.py`, +four cases. Each derives the queue group and the durable, changes the deployment, and derives them +again from the same client -- so what is asserted is the derivation rather than a value cached at +subscribe time: + +- the group name changing leaves both identifiers untouched; +- the pod name changing leaves both untouched (a pod name in a durable would mean a new consumer + on every restart); +- the connection name *does* change across the same edit, which is the positive half: the + deployment is visible where attribution needs it and nowhere else; +- the JetStream `ConsumerConfig` carries `durable_name`, `filter_subject` and `deliver_group` + derived from the namespace and the topic, and neither the group nor the pod appears anywhere in + it. + +**The tests were verified to fail.** Injecting `BLUEPRINT_GROUP` into `_durable_for`'s prefix +fails three of the four; injecting `POD_NAME` fails all four. An invariant test that passes +against a broken implementation is worse than no test, so this was checked rather than assumed. + +The last case doubles as the record of why part 1 does not build a `filter_subjects` set: one +durable per `(namespace, topic)` filtering one subject means declaring a topic *adds* a consumer +and never rewrites one, so there is no filter to churn and no reconfiguration to migrate. + +### Phase 6, part 1 -- build() wires a transport per agent, and none for an agent that needs one not + +Phase 5 made a transport endpoint able to subscribe for one agent. Nothing created more than one: +`build()` still made a single client and a single endpoint for the whole process, so every agent +in a group would have shared the root's connection and the root's subscription set -- which is +neither what spec sec. 6 asks for nor what phase 5's endpoints were built to do. + +**`_eventing_component` became `_eventing_components: list[...]`**, and the decision moved into +one method per agent: + +```python + event_bus_type = str(self._config.get("event_bus", "") or "").strip().lower() + for namespace in self.hosted_namespaces: + self._wire_transport(registry, namespace, event_bus_type) +``` + +`event_bus` is read once, from the root: one transport type per process is a stated boundary of +this plan (mixing NATS and Dapr is out of scope). What is decided per agent is *whether* that +agent gets a client, and whether it gets an endpoint. + +**`AppBuilder.hosted_namespaces`** is the list `build()` iterates -- the root first, then each +declared agent. It is deliberately not `namespaces`, which is only what `with_namespace` was +told: that property answers "which agents was this builder asked to host", this one answers +"which namespaces does `build()` have to walk", and they differ by exactly the root. The root +cannot be conditional, because it is where a single-agent application's components live and where +the framework's own root components go. + +**`_wire_transport` is where the per-agent gates live:** + +```python + consumes = bool(registry.get_event_handler(namespace=namespace)) + publishes = self._publishing_requested(namespace) + ... + if not (consumes or publishes): + logger.debug("Namespace '%s' neither consumes nor publishes events; it is given no transport client", agent) + return + + if event_bus_type == "dapr": + DaprClient(namespace=namespace) # auto-registers + if consumes: + self._eventing_components.append(DaprEventing(namespace=namespace)) + elif event_bus_type == "nats": + NATSClient(namespace=namespace) # auto-registers + if consumes: + self._eventing_components.append(NatsEventing(namespace=namespace)) +``` + +The early return is a spec requirement, not an optimisation: **an agent that neither consumes nor +publishes must not be given a client** (sec. 6). A pure-scheduler agent in `in_process` mode that +has not opted into publishing is that case, and a connection for it would be a socket, a +readiness dependency and a `/connz` entry for traffic that does not exist -- on a broker its own +deployment may have no access to. The same gate is what makes the root pass a no-op in a grouped +application, where every handler belongs to a namespace and the root holds nothing. + +**Publishing became a per-agent opt-in.** `_publishing_requested` now takes a namespace and reads +through that agent's configuration view: + +```python + raw = self._config.for_namespace(namespace).get("event_publishing_enabled", False) +``` + +So one agent in a group can emit events while its neighbours do not (C5). `for_namespace("")` +returns the loader itself, so a single-agent application reads exactly the key it always read. +The error for "publishing enabled, no transport" now names the agent that asked, because in a +group "somebody set this" is not a usable message. + +**One `EventPublishingService` per agent that has a client**, which is what spec sec. 6 requires +for outbound attribution -- an agent's events go out on its own connection: + +```python + for namespace in self.hosted_namespaces: + if registry.get_io_clients(namespace=namespace): + EventPublishingService(namespace=namespace) +``` + +Keyed on the client rather than on `publishes`, so a consuming agent keeps the publishing service +it has always had without opting in. `EventProcessingService` stays single and at the root, since +phase 4 gave it a chain per agent instead. + +**The lifespan and the router mount iterate the list**, shutdown in reverse, and both log the +namespace of the endpoint they are driving -- in a group "eventing component startup failed" with +no agent named is not attributable, which is C7. + +**Three sessions components gained a namespace** (`SessionsApiClient`, `SessionKeyProvider`, +`SessionsBus`), because the sessions branch of `_wire_transport` creates them per agent like the +other two. `SessionsBus` is the one that matters beyond naming: it dispatches through +`CloudEventProcessorMixin`, which passes `self.namespace` since phase 4, so a job notification is +now offered to that agent's handlers and no other's. + +Tests: `tests/unit/agents/app_builder/test_build_namespaces.py`, 16 cases against real +components -- one client per consuming agent, one at the root for a single-agent application, none +for the root when it holds nothing, none for an agent that neither consumes nor publishes, and a +client-without-endpoint for a publish-only agent; publishing opted into per agent; one endpoint +per consuming agent, one at the root for a single-agent application, none without handlers, and +each endpoint subscribing only its own topics; one publishing service per agent with a client and +none for an agent without one; `hosted_namespaces` ordering; and the publish-opt-in error naming +the agent. + +Four existing `build()` tests were updated: the mock config gained +`for_namespace.return_value = config` (the pattern `mock_config` already used), seven +`assert_called_once_with()` assertions became `assert_called_once_with(namespace="")` -- the same +call, now explicit -- `_eventing_component is None` became `_eventing_components == []`, and one +`get_event_handler` stub lambda took the namespace argument it is now passed. None of these is a +behaviour change; each is an assertion on a call shape. + +### Phase 6, part 2 -- an agent's HTTP surface lives under its own prefix, and grouped Dapr is refused + +A group applies the same registration once per agent, so two agents declare the *same* paths. +FastAPI serves the first match, so without a prefix one agent's requests are answered by another +agent's code -- and its Dapr deliveries by another agent's handlers. Nothing about that is visible +from a response. + +**`RestApiBase.route_prefix`** is the single definition of where a component's routes go: + +```python + @property + def route_prefix(self) -> str: + return f"/api/{self.namespace}" if self.namespace else "" +``` + +It is a property on the component rather than a rule inside `AppBuilder` because **two places +have to agree on it**: the builder, which mounts the router, and `DaprEventing.subscribe`, which +tells the sidecar where to post. If those disagreed the sidecar would post to a path FastAPI does +not serve and every delivery would 404, with the application otherwise healthy. + +**`AppBuilder._mount` applies it, and rewrites the tags:** + +```python + prefix = component.route_prefix or root_prefix + if component.namespace: + for route in component.router.routes: + if isinstance(route, APIRoute) and route.tags: + route.tags = [f"{component.namespace}.{tag}" for tag in route.tags] + app.include_router(component.router, prefix=prefix) +``` + +`root_prefix` is what a *root* component keeps, and it is not the same for every kind: a REST API +has always been mounted under `/api`, a transport endpoint at the top level because its paths are +a contract with a sidecar. A namespaced component ignores it and takes `route_prefix`, so both +kinds end up under one prefix per agent -- `/api/orders/orders` for the REST API and +`/api/orders/events/{topic}` for deliveries, which matches the `/api/order/orders/{id}` shape +spec sec. 11 uses. + +The tags are **rewritten, not appended to**. `include_router(tags=...)` appends, which would put +each operation in two Swagger groups -- once under the agent and once under the bare resource +name -- so the rewrite happens on the routes. `isinstance(route, APIRoute)` rather than a +`getattr`: a Starlette `BaseRoute` has no tags, and only the decorator-produced routes do. +Mutating them is safe because a router belongs to exactly one component and `build()` runs once +per process (`Component.configure` refuses a second call). + +**Grouped Dapr is refused at build time, and this is the part worth arguing.** *(Superseded by +part 4 below, which routes and fans out in the process instead. The reasoning is kept because it +is why the endpoint had to become singular.)* Prefixing fixed +delivery, but discovery cannot be prefixed: the sidecar fetches `GET /dapr/subscribe` from one +path, fixed by Dapr's protocol. With each agent's document behind its own prefix the sidecar finds +*no* document, subscribes to nothing, and the pod reports itself healthy while consuming nothing +-- the exact silent failure this feature exists to prevent. So: + +```python + if event_bus_type != "dapr" or len(self._eventing_components) <= 1: + return + ... + raise ValueError( + f"{len(self._eventing_components)} agents ({agents}) consume events and 'event_bus' is 'dapr', ..." + ) +``` + +The check is on the resolved `event_bus_type` rather than on the endpoint types, because one +transport serves the whole process and the type is what is already known here -- `isinstance` +against a module-level name would also break under the test patching that mocks these classes. + +NATS is unaffected: it has no discovery endpoint, because the client subscribes directly, per +agent. **A single-agent Dapr application is unaffected** -- one endpoint, no prefix, byte-identical +document. + +Fixing grouped Dapr properly means one process-wide discovery endpoint returning the union of +every agent's subscriptions, each entry naming that agent's own delivery route. That is a change +to the sidecar-facing contract rather than an internal detail, so it is **not** done here and is +listed under *Open points*. Refusing loudly is the interim, because the alternative is a pod that +looks healthy and consumes nothing. + +Tests: `tests/unit/agents/app_builder/test_route_namespacing.py`, 18 cases, asserting through +`app.openapi()["paths"]` rather than `app.routes` -- FastAPI stores an included router as one +opaque entry rather than flattening its routes, so `app.routes` does not contain the paths under +test while the OpenAPI document is exactly what is served. Covered: the prefix for a root and a +namespaced component; a single-agent application's paths not moving; an agent's route carrying its +namespace; two agents declaring one route not colliding; tags prefixed, the bare tag replaced +rather than added to, two agents' tags not merging, and a root component's tags untouched; grouped +Dapr refused with both agents named, one agent on Dapr fine, two on NATS fine; the root delivery +path unchanged; an agent's delivery path moved; two agents on NATS getting their own; and the +subscription document naming the mounted path for an agent and the unchanged path for the root. + +### Phase 6, part 3 -- every cache is manageable and every cache is probed + +Phase 3 part 2 let a process hold several named caches. Two things still only knew about the +default one, and both were listed as phase 6's work. + +**`CacheManagementApi` takes an optional `?name=` on every endpoint:** + +```python + async def get_cache_stats(self, name: str = DEFAULT_CACHE_NAME) -> CacheStatsResponse: + stats = self._cache(name).get_stats() +``` + +One router for the process rather than one per cache, and that is a correctness point rather +than tidiness: caches can be registered *after* startup (`registry.add_cache` exists for that), +routes cannot, so anything keyed on the set of caches at build time would serve a stale list. +Resolving the name per request has no such window. A request that names nothing reaches the +default cache, so every existing call is unchanged. + +**`_cache(name)` answers the two failures differently, and the distinction is the point:** + +```python + if not self.registry.get_all_caches(): + raise HTTPException(status_code=503, detail="Cache service not available") + try: + return self.registry.get_cache(name) + except ValueError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc +``` + +**503** when no cache is registered at all: the application was built without one, it is not the +caller's doing, and it may resolve without a redeploy -- which is what 503 says, and it is what +this endpoint has always answered. **404** when caches exist but none has that name: that is a +bad request for a resource that is not there, and answering 503 would invite a retry that can +never succeed. The registered names go in the 404 body, because a caller who mistypes a name has +no other way to discover the right one -- there is no endpoint that lists them. + +The eviction response gained a `"cache"` field naming which cache was cleared. With one cache the +answer was implicit; with several, a response that does not say what it cleared is not usable. + +**Readiness probes every cache, not just the default:** + +```python + for cache_name, cache in registry.get_all_caches().items(): + entry = "cache" if cache_name == DEFAULT_CACHE_NAME else f"cache:{cache_name}" + health_providers[entry] = CacheHealthChecker(cache) +``` + +This was a real gap rather than a missing feature. `CacheHealthChecker` pings Redis and flips +readiness when it cannot be reached; keyed on the default name, a project whose `sessions` cache +was a Redis instance had that instance unprobed -- so a Redis outage there took the pod out of +nothing, and the agent silently served cache misses. Worse, a project that registered *only* a +named cache had no cache health check at all, because the old gate was `registry.has_cache()`, +which asks about the default. + +The default keeps the entry name `cache` it has always had, so an existing `/readiness` payload +does not change; a named cache appears as `cache:`. + +Tests: `tests/unit/agents/io/api/utilities/test_cache.py` rewritten onto the new registry calls +and grown to 20 cases -- the three endpoints reading and clearing a named cache, the default used +when no name is given, the response naming the cache it cleared, 503 with no cache registered, +404 for an unknown name on all three endpoints, and the 404 body listing the registered names. +Four cases added to `test_named_caches.py` for the readiness wiring: the default keeping the +`cache` entry name, a named cache getting its own, a *named-only* application still reaching +readiness, and each entry probing its own cache object. + +Also corrected here: part 2's entry said 17 test cases where the file has 18. + +### Phase 6, part 4 -- grouped Dapr works: one endpoint, routed and fanned out in the process + +Part 2 refused a group of consuming agents on Dapr, because discovery cannot be prefixed per +agent. The user's answer was the right one and better than the refusal: **do the routing in the +process.** Keep the one endpoint the sidecar's protocol demands, pick the agents from the event, +and fan out -- since several agents may legitimately want the same event. Part 2's guard is +removed. + +**There is one Dapr endpoint, at the root, and that is now structural:** + +```python + def __init__(self) -> None: + super().__init__(should_register=False) +``` + +`DaprEventing` takes **no namespace at all**, unlike every other transport component. That is not +a simplification -- it is what keeps `_topics_by_agent` correct. That method reads *every* handler +in the process, which it can only do because `self.registry` is the application's registry rather +than one agent's view of it; a namespaced instance would silently see one agent's handlers and +route only that agent's topics. Making the constructor refuse a namespace means the mistake cannot +be made, and `route_prefix` is then always `""`, so the two fixed paths never move. + +**The routing table is read from the handlers:** + +```python + by_agent: dict[str, dict[str, None]] = {} + for handler in self.registry.get_event_handler(): + for topic in handler.get_subscribed_topics(): + if topic: + by_agent.setdefault(namespace_of(handler), {})[topic] = None +``` + +An agent that declared no topic does not appear, because it has nothing to subscribe and nothing +to be delivered. + +**The document is the union; the delivery is the fan-out.** Those are two different readings of +the same table, and the asymmetry is the whole design: + +- `_declared_topics` flattens it, deduplicated, because the sidecar delivers a topic to the + application **once** however many agents want it -- so it is told once. +- `_agents_for(topic)` inverts it, returning every agent that declared the topic. Fanning that + single delivery out is the application's job, not the sidecar's. + +```python + declared = tuple(namespace for namespace, topics in by_agent.items() if topic in topics) + if declared: + return declared + with_handlers = tuple(dict.fromkeys(namespace_of(handler) for handler in self.registry.get_event_handler())) + return with_handlers or (ROOT_NAMESPACE,) +``` + +The fallback is the same rule `DispatchIndex.candidates` applies one level down: **an absent +declaration cannot narrow anything to nothing.** A topic nobody declared goes to every agent that +has handlers, and each agent's `can_handle_event` decides. That is what a topic arriving from +outside the application needs -- `dapr_declarative_subscriptions` makes the document empty, so no +handler need declare anything and the framework never sees the topic list, yet the sidecar still +delivers. Routing such a delivery nowhere would silence the application, and an unhandled event +acknowledges (spec sec. 7.2), so the events would be consumed and discarded. For a single-agent +application both branches are the root, so nothing changes there. + +**`publish` dispatches once per agent and does not let a failure stop the others:** + +```python + for namespace in agents: + try: + await self._process_cloud_event(cloud_event, {"dapr_topic": topic}, topic, namespace=namespace) + dispositions.append(DeliveryDisposition.ACK) + except Exception as exc: + disposition = disposition_for(exc) + dispositions.append(disposition) + ... +``` + +Letting the exception out of the loop would let one agent silently cancel a neighbour's work. Each +failure is logged with its own agent named, so a fan-out failure stays attributable (C7). + +**The single acknowledgement is `combined_disposition`, new in `models/errors.py`** beside the +disposition table it extends, since it is a spec sec. 7.2 concern rather than a Dapr detail: + +```python + outcomes = set(dispositions) + if DeliveryDisposition.NAK in outcomes: + return DeliveryDisposition.NAK + if DeliveryDisposition.ACK in outcomes or not outcomes: + return DeliveryDisposition.ACK + return DeliveryDisposition.TERM +``` + +Each step is a decision, argued in its docstring. **Any NAK wins**, because one agent asked for +the delivery again and the only way to give it one is to ask for the whole message again. +**Otherwise ACK beats TERM**, because a TERM from one agent means *that* agent found the message +undeliverable -- a finished outcome -- and if another agent handled it, the message was handled; +answering TERM would report a successful delivery as dropped. **All TERM is TERM.** Empty is ACK: +nothing was dispatched, so nothing failed. + +**The cost, stated because it has no NATS equivalent:** there is one delivery, so one +acknowledgement, so **a retry asked for by one agent redelivers to every agent in the group**. +A grouped Dapr deployment therefore wants `idempotency_enabled`, or handlers that tolerate a +repeat. Under NATS each agent has its own consumer and its own ack, and no such coupling exists. +This is in the class docstring as well as here, because it is the thing an operator has to know. + +**Plumbing:** `_process_cloud_event` and `_dispatch_cloud_event` took an optional `namespace`, +defaulting to the endpoint's own -- every caller but this one. The unhandled and duplicate +counters now carry the agent the dispatch was *for* rather than the endpoint's namespace, which +for the fan-out is the difference between attributing an event to the agent that declined it and +attributing every event in the process to the root. + +**`AppBuilder._wire_dapr_endpoint`** replaces `_refuse_grouped_dapr`: the Dapr branch of +`_wire_transport` now creates only the per-agent client, and one root endpoint is created after +the loop if anything in the process consumes. NATS endpoints stay per agent, because there the +broker routes -- one consumer per `(namespace, topic)` -- and nothing needs to be done in +process. + +Tests: `tests/unit/agents/io/api/eventing/test_dapr_fanout.py`, 24 cases against real handlers, +config and chains -- the routing table keyed per agent and an agent that declared nothing absent +from it; the document as the deduplicated union with every route at the fixed path; `_agents_for` +resolving one declaring agent, two declaring agents, an undeclared topic to every agent with +handlers, and a single-agent application to the root; the fan-out reaching both declaring agents, +skipping a non-declaring one, dispatching once for a single-agent application, and continuing past +one agent's failure; all six acknowledgement combinations; each agent's client receiving its own +topics and being kept per agent; and the constructor refusing a namespace. + +Updated: `test_route_namespacing.py` lost `TestGroupedDaprIsRefused` and gained the Dapr endpoint +staying at the root; `test_eventing_namespaces.py` is now NATS-only, since Dapr's per-agent +subscription moved to the fan-out file; `test_dapr.py` moved from `_client` to `_clients` and its +mock handlers gained a real `namespace` attribute, which `namespace_of` needs; and one +`assert_called_once_with(namespace="")` became `assert_called_once_with()`. + +### Phase 7 -- a handler says which agent runtime should serve an event + +`EventHandlerBase`'s own usage docstring has shown `get_runtime_name` since before any of this +work; the method did not exist. A project that overrode it got a method nothing ever called. +Alongside it, `process_event` has taken a `runtime_name` argument that the spec's compatibility +table records as "only logged". This closes both. + +**The hook, on `EventHandlerBase`:** + +```python + def get_runtime_name(self, event: GenericCloudEvent, context: dict[str, Any]) -> str | None: + return None +``` + +Per *event* rather than per handler, because the choice can depend on the payload -- one handler +routing to a fast model or a thorough one on the same event type is the case it exists for. + +**The resolution happens in the chain, between selection and handling, and that is a departure +from the plan.** The plan puts it in `EventProcessingService` "after the chain selects a +handler". By then the handler has already run: the chain selects *and* runs in one pass, so a +runtime resolved afterwards is a value nothing can act on. Inside the loop there is exactly one +moment where the winner is known and the answer is still useful: + +```python + if await handler.can_handle(event, context): + logger.info("Handler '%s' handling event '%s'", handler.name, event.type) + self._bind_runtime(handler, event, context) + result = await handler.handle(event, context) +``` + +So the runtime is *bound into the context the handler is about to be given*, under +`RUNTIME_CONTEXT_KEY` (`"runtime"`) and `RUNTIME_NAME_CONTEXT_KEY` (`"runtime_name"`). A handler +that wants a particular runtime reads it from the context rather than looking it up -- and in a +grouped process it gets its own agent's runtime with no namespace anywhere in handler code, which +is the constraint the whole feature is under. The fallthrough is unaffected: a candidate whose +`handle` returns `None` passes on, and the next candidate gets its own binding. + +**Three sources, most explicit first:** + +```python + declared = handler.get_runtime_name(event, context) or context.get(RUNTIME_NAME_CONTEXT_KEY) + if declared: + context[RUNTIME_NAME_CONTEXT_KEY] = declared + context[RUNTIME_CONTEXT_KEY] = self._runtime_named(str(declared), handler) + return + + names = self.registry.get_agents(namespace=self.namespace) + if len(names) == 1: + context[RUNTIME_NAME_CONTEXT_KEY] = names[0] + context[RUNTIME_CONTEXT_KEY] = self.registry.get_agent(names[0], self.namespace) + return +``` + +The handler's own answer, then the caller's `runtime_name`, then the single runtime in this +handler's namespace. `process_event` now seeds its argument into the context: + +```python + if runtime_name: + context[RUNTIME_NAME_CONTEXT_KEY] = runtime_name +``` + +Only when asked for, so a caller that passes nothing leaves the key *absent* rather than `None` -- +the difference between "no preference" and "explicitly no runtime". That is what makes a parameter +which has only ever been logged mean something, while keeping the handler's own answer above it. + +The namespace is named explicitly in both registry calls, for the reason it is named in +`_handlers`: an omitted namespace on the root registry means every namespace, so the single-runtime +count would include a neighbour's agent and "exactly one" would be wrong in a group. There is a +test for two agents each owning a `planner`, where each chain binds its own. + +**The plan's ambiguity error is not implemented, and this is the substantive departure.** The plan +says "`None` + multiple agents + no name declared -> raise a descriptive error". That would break +applications that work today: two agents plus handlers that resolve their own runtime by name is a +shape this framework already supports -- it is what the scaffolder generates, `self.registry +.get_agent('')` in a service's `on_startup` -- and those applications rely on the +framework resolving nothing. Raising would fail every delivery in them. So nothing is bound, and +the ambiguity is reported once per handler at WARNING, naming the candidates and the override. +Once, because the condition is a property of the code rather than of the event: the same handler +in the same namespace is ambiguous for every event it will ever see, and a per-delivery warning +would bury the one line that matters. This needs a spec amendment; it is under *Open points*. + +**What *does* raise is a declaration the framework cannot honour:** + +```python + raise ValueError( + f"Handler '{handler.name}' asked for agent runtime '{name}', which is not registered in namespace " + f"'{self.namespace or ROOT_LABEL}' or at the root (registered here: {registered}). Either register it, " + "or return a name that exists from get_runtime_name()." + ) +``` + +The same reading as `event_publishing_enabled` without a transport: an explicit statement the +framework cannot satisfy is a failure, not something to fall back from silently. + +**Found while writing the tests, and worth recording:** constructing a component *directly* with +an explicit `name=` does not qualify it with the namespace -- only `AppBuilder._register` does +that (phase 3 part 1). So two `AgentRuntime(name="planner")` instances in two namespace scopes +still collide on the one registry key. Everything the builder creates is safe; a test or a project +that constructs a component by hand inside a `namespace_scope` is not. The test helper qualifies +the name itself and says why. Not fixed here -- the fix would be `Component.__init__` qualifying an +explicit name, which changes naming for every component in the framework and deserves its own step. + +Tests: `tests/unit/agents/handler/test_runtime_binding.py`, 18 cases against real +`AgentRuntime`, `Config` and chains -- a declared runtime bound and bound *before* the handler +runs; the choice varying with the payload; the handler winning over the caller and the caller +winning over the fallback; `process_event` seeding its argument and leaving the key absent when +it has none; one runtime bound with no declaration, none bound when there is no runtime at all, +and each agent binding its own in a group; the ambiguous case binding nothing, reporting once +rather than per delivery; an unknown declared name raising with the handler, the namespace and the +registered names in the message; and the default hook returning `None`. + +**Verified not vacuous:** with the `_bind_runtime` call removed, 14 of the 18 fail -- the four +that survive are the ones asserting that *nothing* is bound. + --- ## Compatibility @@ -2702,6 +3614,86 @@ Everything else remains non-breaking. Specifically: Whether Dapr merges the two or delivers twice needs checking against a real sidecar; it belongs on the broker-test list. - New config keys all default to current behaviour. +- **`EventHandlerBase.get_runtime_name(event, context)` is new and defaults to `None`.** It was + already in the class's usage docstring, so a project may have written one; it is now actually + called. Returning `None` keeps today's behaviour. +- **The processing context gains `runtime` and `runtime_name` keys when a runtime can be chosen.** + A single-agent application with one `AgentRuntime` now finds them populated where it did not + before -- additive, and nothing in the framework reads them. With several runtimes and no + declaration neither key is set, and a WARNING names the candidates once per handler. +- **`process_event`'s `runtime_name` argument is no longer only logged.** It seeds the context as + the caller's choice, below the handler's own `get_runtime_name` and above the single-runtime + fallback. A caller that passes nothing is unaffected. +- **`DaprEventing()` takes no namespace, and `DaprEventing._client` is now `_clients`, a dict + keyed by namespace.** There is one endpoint per process, at the root. A single-agent + application's document, delivery path and acknowledgement are all unchanged. +- **A group of consuming agents on Dapr now works** (it was refused in phase 6 part 2). One + delivery is fanned out to every agent that declared the topic, and the one acknowledgement is + their combination -- so **a retry asked for by one agent redelivers to all of them.** Set + `idempotency_enabled` for grouped Dapr, or keep handlers repeat-tolerant. NATS is unaffected. +- **`_process_cloud_event` and `_dispatch_cloud_event` gained a trailing optional `namespace`.** + Both are protected; the default is the endpoint's own namespace, which is what every caller + except the Dapr fan-out passes. +- **The `/cache/*` endpoints take an optional `?name=`, defaulting to `default`.** Every existing + call is unchanged. New answer: an unknown name is `404` rather than `503`, and `POST + /cache/evict` now includes a `"cache"` field in its response body. +- **`/readiness` gains one entry per named cache, as `cache:`.** The default cache keeps + the entry name `cache`, so an existing payload is unchanged. A project that registered only a + named cache previously had no cache health check at all. +- **A namespaced component's routes move to `/api//...`, and its tags gain an + `.` prefix.** Nothing moves for an application that declares no namespace: a root REST + API stays under `/api`, and a root transport endpoint stays at `/events/{topic}` and + `/dapr/subscribe`. +- **`RestApiBase.route_prefix` is new**, and public, because `DaprEventing.subscribe` has to + render the same prefix the builder mounts. +- **A group of two or more consuming agents on `event_bus = "dapr"` now fails at `build()`.** + The sidecar fetches the subscription document from one fixed path, so per-agent documents + would leave it subscribed to nothing. Single-agent Dapr is unchanged; NATS hosts groups + normally. Listed under *Open points*. +- **`AppBuilder._eventing_component` is now `_eventing_components`, a list.** Underscore-private, + but anything introspecting it breaks. It holds exactly one element for every application that + declares no namespace. +- **`event_publishing_enabled` is now read per agent**, through that agent's configuration view. + A root-level key still applies to a single-agent application unchanged; in a group an agent can + set its own, and `.event_publishing_enabled` wins over the shared value. +- **`SessionsApiClient`, `SessionKeyProvider` and `SessionsBus` gained a leading optional + `namespace`.** All three are framework-constructed from `build()`, so the leading position + affects nobody. +- **Phase 5 is not a consumer migration, and expects neither a replay nor a gap.** The plan + requires this to be stated, because renaming a durable or changing a filter set is broker-side + state and a recreated consumer resumes by its delivery policy. Neither happens here: the + namespace-qualified durable landed with P6 and is dormant until a namespace exists (the root + keeps `-durable`), and phase 5 changes no filter set -- one durable per + `(namespace, topic)` filtering one subject was already the shape, so declaring a topic adds a + consumer instead of reconfiguring one. The first deployment that *is* a migration is the first + one that declares a namespace, and it creates new consumers rather than renaming existing ones. +- **`RestApiBase.__init__` gained a keyword-only `namespace`**, forwarded to `Component`. + Defaults to the root, and every subclass in the repo already passes `should_register` by + keyword, so no existing call changes. +- **`NatsEventing.__init__` and `DaprEventing.__init__` gained a leading optional `namespace`.** + Both are framework-constructed and unregistered, so the leading position affects nobody. +- **The `blueprint.events.unhandled` and `blueprint.events.duplicate` counters now carry the + endpoint's real namespace** instead of a hardcoded root. A single-agent application still + reports `namespace=""`, so no existing dashboard sees a new label value. +- **`EventHandlerBase.get_handled_event_types()` is new and defaults to `[]`**, which means + "offer me every event" -- the behaviour every handler has today. Overriding it narrows only + which events that handler is *asked* about; `can_handle_event` still decides. Declarations are + matched by equality: a pattern such as `order.*` is refused at startup rather than silently + matching nothing. +- **`SessionsJobHandler` now declares its event type**, derived from the `JOB_TYPE` its + subclasses already set. Selection is unchanged -- the declaration and `can_handle_event` read + one property -- so a subclass sees no difference beyond not being asked about other job types. +- **`HandlerChain.__init__` gained a leading optional `namespace`, and `process_event` / + `process_rest_request` a trailing keyword-only one.** All default to the root. `HandlerChain` + is constructed by the framework only -- it is `should_register=False` and nothing looks it up -- + so the leading position is safe; the two service methods took keyword-only because their + positional tails are used by callers. +- **`HandlerChain._dispatch` now asks for its own namespace's handlers instead of every + namespace's.** For a single-agent application these are the same set: every handler is at the + root. In a grouped process it is the difference between dispatching to one agent and to all of + them. +- **`CloudEventProcessorMixin` requires a `namespace` attribute as well as `registry`.** Both come + from `Component`, which every class it is mixed into already subclasses. - **`AppBuilder.with_cache` gained a keyword-only `name`, and the three positional forms are unchanged.** `with_cache()`, `with_cache(False)` and `with_cache(True, False)` mean what they always meant, which is why `name` had to come last and be keyword-only (spec sec. 4.2). The @@ -2840,13 +3832,17 @@ stay keyword-only and last, or an existing `with_cache(False)` would silently be ## Open points -- **Two spec amendments are outstanding for `with_namespace` (phase 3 part 1).** Spec sec. 4.2 - types the return as `AppBuilder | NamespaceBuilder` and lists a `config: Config | None` - parameter. The union is honoured at runtime but resolved by `@overload` so no caller narrows it; - the `config` parameter is **not** accepted, because config rework step 2 left it with no reader - -- `Component.config` derives each component's view from the one loaded tree. The spec should - say so rather than describing a parameter the implementation refuses. Reasoning in the phase 3 - part 1 entry above. +- **Phase 7's ambiguity error needs a spec amendment.** The plan asks `process_event` to raise + when a handler declares no runtime and several are registered. It is implemented as a + once-per-handler WARNING with nothing bound, because raising would fail every delivery in an + application that has two agents and handlers resolving their own runtime by name -- the shape + the scaffolder generates. The spec's compatibility table already calls phase 7 "purely + additive", which the raise would contradict; the plan bullet is what should change. +- **An explicit `name=` is qualified with the namespace only on the builder path.** Constructing + a component directly inside a `namespace_scope` with `name="planner"` registers it as + `planner`, so two agents doing that collide on one registry key. `AppBuilder._register` + qualifies; `Component.__init__` does not. Fixing it there would change naming for every + component and wants its own step. - **P0-P5 have landed. P6 is next**, and two requirements for it were settled during P5 (see the namespace bullet below). What remains open from P5 is deferred work rather than unfinished work: diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index 75162ee2..0af06f2d 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any, TypeVar, overload from fastapi import FastAPI +from fastapi.routing import APIRoute if TYPE_CHECKING: from .io.api.actuators.health import HealthCheckerBase @@ -339,7 +340,10 @@ def __init__(self, config: Config) -> None: config.configure_logging() self._config = config self._telemetry_manager = TelemetryManager() - self._eventing_component: DaprEventing | NatsEventing | None = None + # One transport endpoint per agent that consumes. A list rather than a single slot + # because a group's agents each subscribe on their own behalf (spec sec. 7.6); it holds + # exactly one element for every application that declares no namespace. + self._eventing_components: list[DaprEventing | NatsEventing] = [] # Components that need lifespan (on_startup / on_shutdown) but do not expose # a FastAPI router. SessionsBus lives here because it is SSE-driven, not # HTTP-driven; keeping it out of _eventing_component avoids the routerless @@ -451,6 +455,22 @@ def namespaces(self) -> tuple[str, ...]: """ return tuple(self._namespaces) + @property + def hosted_namespaces(self) -> tuple[str, ...]: + """Every namespace this process serves: the root first, then each declared agent. + + The root is always present, and always first. It is where a single-agent application's + components live, and where the framework's own root components go, so it cannot be + conditional. In a grouped application the root usually holds nothing, and then the root + pass over this list simply creates nothing -- the per-agent gates decide that, not this + list. + + Distinct from :attr:`namespaces`, which is only what ``with_namespace`` was told. That + one answers "which agents was this builder asked to host"; this one answers "which + namespaces does ``build()`` have to iterate", and those differ by exactly the root. + """ + return (ROOT_NAMESPACE, *self._namespaces) + def with_handler( self, handler: type[HandlerT] | HandlerT, *, name: str | None = None, namespace: str = ROOT_NAMESPACE, **kwargs: Any ) -> "AppBuilder": @@ -646,74 +666,42 @@ def build(self) -> FastAPI: scheduler.crontab, ) - # 3. Create the IO transport client, and the eventing endpoint only if something - # consumes. Publishing and consuming are decided separately: an application that - # only emits events -- a scheduler that reports what it did, a REST API that hands - # work on -- needs a client but must not be subscribed to anything it never asked - # for. Consuming still implies publishing, because a handler returning a - # HandlerResult with an event_type has always published through the same client. - consumes = bool(registry.get_event_handler()) - publishes = self._publishing_requested() + # 3. Create the IO transport, once per agent this process hosts. One transport type + # per process -- 'event_bus' is read from the root config, and mixing NATS with Dapr + # is out of scope for this plan -- but which agents get a client, and which of them + # get an endpoint, is decided per agent below. event_bus_type = str(self._config.get("event_bus", "") or "").strip().lower() - - if publishes and event_bus_type not in TOPIC_TRANSPORTS: - # Strict where the handler branch below only warns: 'event_publishing_enabled' is - # a new key, and setting it is an explicit statement that this application emits - # events. Honouring that with no transport would mean the first publish fails at - # runtime, inside whatever business operation produced the event. - raise ValueError( - f"'event_publishing_enabled' is true but 'event_bus' is {event_bus_type or 'not set'!r}, so there is " - f"no client to publish through. Set 'event_bus' to one of {', '.join(TOPIC_TRANSPORTS)}, or remove " - "'event_publishing_enabled'." - ) - - if consumes or publishes: - if event_bus_type == "dapr": - DaprClient() # auto-registers - if consumes: - self._eventing_component = DaprEventing() - elif event_bus_type == "nats": - NATSClient() # auto-registers - if consumes: - self._eventing_component = NatsEventing() - elif event_bus_type == "sessions": - SessionsApiClient() # ServiceBase → auto-registers - SessionKeyProvider() # ServiceBase → auto-registers - # SessionsBus has no router (SSE-driven). Track it via the - # lifecycle list so the lifespan hook still drives on_startup / - # on_shutdown without polluting the router-mount path. - self._lifecycle_components.append(SessionsBus()) - else: - logger.warning( - "Event handlers are registered but no valid event_bus configured " - "('dapr', 'nats', or 'sessions'). Event handling will be disabled." - ) - - if publishes and not consumes: - logger.info( - "Event publishing is enabled without any handler: a '%s' client is created, and nothing is subscribed", - event_bus_type, - ) + for namespace in self.hosted_namespaces: + self._wire_transport(registry, namespace, event_bus_type) + self._wire_dapr_endpoint(registry, event_bus_type) # 4. Create internal services (auto-register) # EventProcessingService is only useful when there's a handler to route # requests to -- whether via an eventing endpoint (see step 3) or a REST - # API calling RestApiBase._process_resource() directly. - if consumes: + # API calling RestApiBase._process_resource() directly. One per process, at the + # root: it keeps a handler chain per agent (phase 4) rather than being one per agent. + if registry.get_event_handler(): EventProcessingService() - # Keyed on the client rather than on 'publishes', so a consuming application keeps - # the publishing service it has always had without opting in. - if registry.get_io_clients(): - EventPublishingService() + # One publishing service per agent that has a client, so an agent's outbound events + # go out on its own connection (spec sec. 6) and are attributable to it. Keyed on the + # client rather than on 'publishes', so a consuming agent keeps the publishing service + # it has always had without opting in. + for namespace in self.hosted_namespaces: + if registry.get_io_clients(namespace=namespace): + EventPublishingService(namespace=namespace) # 5. Create ActuatorApi and wire health checkers from all registered clients self._actuator_api = ActuatorApi() health_providers: dict[str, HealthCheckerBase] = {client.name: ClientHealthChecker([client]) for client in registry.get_clients()} - # Pull the registered cache (if any) into the readiness probe so a Redis - # outage takes the pod out of service rotation instead of letting it - # silently serve cache misses. - if registry.has_cache(): - health_providers["cache"] = CacheHealthChecker(registry.cache_service) + # Pull every registered cache into the readiness probe so a Redis outage takes the pod + # out of service rotation instead of letting it silently serve cache misses. Every + # cache, not just the default one: a named cache is a real backend with a real + # connection, and one that only the default cache was probed would be an unreachable + # Redis nobody was told about. The default keeps the entry name 'cache' it has always + # had, so an existing /readiness payload is unchanged. + for cache_name, cache in registry.get_all_caches().items(): + entry = "cache" if cache_name == DEFAULT_CACHE_NAME else f"cache:{cache_name}" + health_providers[entry] = CacheHealthChecker(cache) if hasattr(self, "_custom_health_checkers"): health_providers.update(self._custom_health_checkers) if health_providers: @@ -733,6 +721,78 @@ def build(self) -> FastAPI: self._build_rest_endpoints(app, registry) return app + def _wire_transport(self, registry: Registry, namespace: str, event_bus_type: str) -> None: + """Give ``namespace`` a transport client, and an endpoint if it consumes. + + Publishing and consuming are decided separately, per agent. An agent that only emits + events -- a scheduler reporting what it did, a REST API handing work on -- needs a + client but must not be subscribed to anything it never asked for. Consuming still + implies publishing, because a handler returning a ``HandlerResult`` with an + ``event_type`` has always published through the same client. + + **An agent that neither consumes nor publishes gets no client** (spec sec. 6). A + pure-scheduler agent in ``in_process`` mode that has not opted into publishing is that + case, and a connection for it would be a socket, a readiness dependency and a + ``/connz`` entry for traffic that does not exist -- on a broker its own deployment may + have no access to. This is also what makes the root pass a no-op in a grouped + application, where every handler belongs to a namespace and the root has nothing. + + Args: + registry: The application's registry, queried per namespace. + namespace: The agent to wire. + event_bus_type: The resolved ``event_bus`` value, shared by the whole process. + + Raises: + ValueError: if this agent opted into publishing and there is no topic transport + to publish through. + """ + consumes = bool(registry.get_event_handler(namespace=namespace)) + publishes = self._publishing_requested(namespace) + agent = namespace or ROOT_LABEL + + if publishes and event_bus_type not in TOPIC_TRANSPORTS: + # Strict where the handler branch below only warns: 'event_publishing_enabled' is + # an explicit statement that this agent emits events. Honouring that with no + # transport would mean the first publish fails at runtime, inside whatever + # business operation produced the event. + raise ValueError( + f"'event_publishing_enabled' is true for namespace '{agent}' but 'event_bus' is " + f"{event_bus_type or 'not set'!r}, so there is no client to publish through. Set 'event_bus' to one " + f"of {', '.join(TOPIC_TRANSPORTS)}, or remove 'event_publishing_enabled'." + ) + + if not (consumes or publishes): + logger.debug("Namespace '%s' neither consumes nor publishes events; it is given no transport client", agent) + return + + if event_bus_type == "dapr": + # The client is per agent; the endpoint is not. See _wire_dapr_endpoint. + DaprClient(namespace=namespace) # auto-registers + elif event_bus_type == "nats": + NATSClient(namespace=namespace) # auto-registers + if consumes: + self._eventing_components.append(NatsEventing(namespace=namespace)) + elif event_bus_type == "sessions": + SessionsApiClient(namespace=namespace) # ServiceBase -> auto-registers + SessionKeyProvider(namespace=namespace) # ServiceBase -> auto-registers + # SessionsBus has no router (SSE-driven). Track it via the lifecycle list so the + # lifespan hook still drives on_startup / on_shutdown without polluting the + # router-mount path. + self._lifecycle_components.append(SessionsBus(namespace=namespace)) + else: + logger.warning( + "Namespace '%s' has event handlers registered but no valid event_bus is configured " + "('dapr', 'nats', or 'sessions'). Event handling will be disabled for it.", + agent, + ) + + if publishes and not consumes: + logger.info( + "Event publishing is enabled for namespace '%s' without any handler: a '%s' client is created, and nothing is subscribed", + agent, + event_bus_type, + ) + @staticmethod def _lifecycle_rest_apis(registry: Registry) -> list[RestApiBase]: """Return the REST APIs the lifespan owns, which is every one that is not a scheduler. @@ -744,8 +804,8 @@ def _lifecycle_rest_apis(registry: Registry) -> list[RestApiBase]: """ return [rest_api for rest_api in registry.get_rest_apis() if not isinstance(rest_api, SchedulerBase)] - def _publishing_requested(self) -> bool: - """Report whether this application has opted into publishing events. + def _publishing_requested(self, namespace: str = ROOT_NAMESPACE) -> bool: + """Report whether ``namespace`` has opted into publishing events. ``event_publishing_enabled`` (bool, default ``False``). Off by default because publishing needs broker access, and a project that only wants a scheduler or a REST @@ -758,10 +818,17 @@ def _publishing_requested(self) -> bool: ``BLUEPRINT_EVENT_PUBLISHING_ENABLED=`` means the key is not set. Anything else that is not a boolean does raise. + Read through the agent's own configuration view, so one agent in a group can emit + events while its neighbours do not (C5). ``for_namespace("")`` returns the loader + itself, so a single-agent application reads exactly the key it always read. + + Args: + namespace: The agent asking. ``""`` is the root. + Raises: ValueError: if the key holds a non-empty value that is not a boolean. """ - raw = self._config.get("event_publishing_enabled", False) + raw = self._config.for_namespace(namespace).get("event_publishing_enabled", False) if raw is None or (isinstance(raw, str) and not raw.strip()): return False return parse_bool(raw, "event_publishing_enabled") @@ -776,10 +843,10 @@ def _build_rest_endpoints(self, app: FastAPI, registry: Registry) -> None: # in Swagger UI. Routes carry their per-operation tags (set via the RestApiBase decorators) # and group correctly; untagged routes fall under FastAPI's "default", which is the nudge # for services to tag their routes rather than hide behind a catch-all. - app.include_router(rest_api.router, prefix="/api") + self._mount(app, rest_api, root_prefix="/api") - if self._eventing_component is not None: - app.include_router(self._eventing_component.router) + for eventing_component in self._eventing_components: + self._mount(app, eventing_component, root_prefix="") if registry.has_cache(): app.include_router(CacheManagementApi().router, prefix="/api", tags=["cache"]) @@ -787,6 +854,62 @@ def _build_rest_endpoints(self, app: FastAPI, registry: Registry) -> None: if self._actuator_api is not None: app.include_router(self._actuator_api.router, tags=["actuators"]) + def _wire_dapr_endpoint(self, registry: Registry, event_bus_type: str) -> None: + """Create the process's single Dapr endpoint, at the root, if anything consumes. + + One endpoint however many agents this process hosts, and that is forced rather than + chosen. Both Dapr paths are fixed by its protocol: the sidecar fetches + ``GET /dapr/subscribe`` from one place and posts deliveries where that document says. + An endpoint per agent behind its own prefix would leave the sidecar with no document to + fetch, subscribed to nothing, on a pod reporting itself healthy. + + So the endpoint is built at the root -- unprefixed, exactly where a single-agent + application has always served it -- and it does the routing itself: the union of every + agent's topics in the document, and one dispatch per agent that declared the delivered + topic. NATS needs none of this, because the broker routes: one consumer per + ``(namespace, topic)``, so its endpoints stay per agent. + + Args: + registry: The application's registry, asked whether anything consumes at all. + event_bus_type: The resolved ``event_bus``; anything but ``"dapr"`` returns. + """ + if event_bus_type != "dapr" or not registry.get_event_handler(): + return + self._eventing_components.append(DaprEventing()) + logger.info( + "One Dapr endpoint serves this process, fanning each delivery out to the agents that declared its topic", + ) + + @staticmethod + def _mount(app: FastAPI, component: RestApiBase, *, root_prefix: str) -> None: + """Include one component's router, under its agent's prefix if it has one. + + ``root_prefix`` is what a *root* component keeps, and it is not the same for every + kind: a REST API has always been mounted under ``/api``, while a transport endpoint has + always been mounted at the top level because its paths are a contract with a sidecar. + A namespaced component ignores it and takes ``route_prefix`` instead, so both kinds end + up under one prefix per agent. + + The tags are rewritten rather than added to, so an agent's operations form their own + group in Swagger UI instead of appearing twice -- once under the agent and once under + the bare resource name. ``include_router(tags=...)`` appends, which is why this is done + on the routes. Mutating them is safe because a router belongs to exactly one component + and ``build()`` runs once per process (``Component.configure`` refuses a second call). + + Args: + app: The application to mount on. + component: The component whose router is being mounted. + root_prefix: The prefix to use when the component belongs to the root namespace. + """ + prefix = component.route_prefix or root_prefix + if component.namespace: + for route in component.router.routes: + # A Starlette BaseRoute has no tags; an APIRoute does, and those are the + # ones the decorators produce. Anything else is left alone. + if isinstance(route, APIRoute) and route.tags: + route.tags = [f"{component.namespace}.{tag}" for tag in route.tags] + app.include_router(component.router, prefix=prefix) + # ------------------------------------------------------------------ # Lifespan # ------------------------------------------------------------------ @@ -870,13 +993,18 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: logger.error("Scheduler %s startup failed: %s", scheduler.name, e, exc_info=True) raise - # Eventing component (Dapr / NATS endpoint) - if self._eventing_component is not None: + # Eventing components (one Dapr / NATS endpoint per agent that consumes) + for eventing_component in self._eventing_components: try: - await self._eventing_component.on_startup() - logger.info("Eventing component startup completed") + await eventing_component.on_startup() + logger.info("Eventing component for namespace '%s' startup completed", eventing_component.namespace or ROOT_LABEL) except Exception as e: - logger.error("Eventing component startup failed: %s", e, exc_info=True) + logger.error( + "Eventing component for namespace '%s' startup failed: %s", + eventing_component.namespace or ROOT_LABEL, + e, + exc_info=True, + ) raise # Routerless lifecycle components (e.g. SessionsBus). @@ -912,11 +1040,16 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: exc_info=True, ) - if self._eventing_component is not None: + for eventing_component in reversed(self._eventing_components): try: - await self._eventing_component.on_shutdown() + await eventing_component.on_shutdown() except Exception as e: - logger.error("Eventing component shutdown failed: %s", e, exc_info=True) + logger.error( + "Eventing component for namespace '%s' shutdown failed: %s", + eventing_component.namespace or ROOT_LABEL, + e, + exc_info=True, + ) for scheduler in registry.get_schedulers(): try: diff --git a/src/blueprint/agents/handler/event_handler_base.py b/src/blueprint/agents/handler/event_handler_base.py index 26b0cc2d..7f0c2a3b 100644 --- a/src/blueprint/agents/handler/event_handler_base.py +++ b/src/blueprint/agents/handler/event_handler_base.py @@ -10,6 +10,9 @@ Handlers can also declare published event types by overriding: - `get_published_event_types()` - Return (success_event_type, error_event_type) - `get_subscribed_topics()` - Return list of NATS topics to auto-subscribe on startup +- `get_handled_event_types()` - Return the event types this handler accepts, so the + dispatch index can skip it for everything else +- `get_runtime_name()` - Return which agent runtime should serve this event The framework provides automatic OpenTelemetry tracing for all handlers. """ @@ -161,6 +164,75 @@ def get_published_event_types(self) -> tuple[str, str] | None: return None + def get_runtime_name(self, event: GenericCloudEvent, context: dict[str, Any]) -> str | None: + """Declare which agent runtime should serve this event, or ``None`` to let the framework decide. + + Called between :meth:`can_handle_event` saying yes and :meth:`handle_event` running, so + what it returns is resolved and put in ``context`` under ``"runtime"`` (the + ``AgentRuntime``) and ``"runtime_name"`` (its registry name) **before** the handler runs. + A handler that wants a particular runtime for a particular event therefore reads it from + the context it is handed rather than looking it up -- and in a grouped process it gets + its *own* agent's runtime without naming a namespace anywhere. + + Per event rather than per handler, because the choice can depend on the payload: one + handler routing to a fast model or a thorough one on the same event type is the case + this exists for. + + **Returning ``None`` is the normal case.** With exactly one agent runtime in this + handler's namespace, that one is provided -- which is what a single-agent application + has in practice. With several and no declaration, nothing is provided and the ambiguity + is reported once: there is no basis for the framework to choose between them. + + Args: + event: The event about to be handled. + context: The processing context, already carrying ``request_id`` and whatever + ``runtime_name`` the caller of ``process_event`` asked for. + + Returns: + The registry name of the runtime to use, or ``None`` to let the framework decide. + + Example:: + + def get_runtime_name(self, event, context): + return "thorough" if event.data.get("priority") == "high" else "fast" + """ + + return None + + def get_handled_event_types(self) -> list[str]: + """Declare the event types this handler accepts, or nothing to be offered every event. + + This is a **selection hint, not a selector**. :meth:`can_handle_event` remains the + decision: a declared handler is still asked, and may still say no. What the declaration + buys is that handlers which cannot possibly want an event are not asked at all, so a + process hosting many handlers does not run every one of them against every delivery. + + **The default is an empty list, and that means "offer me everything".** It is not + "offer me nothing", and the difference is the most destructive mistake available here: + no handler in this framework or in any scaffolded project declares anything today, so a + dispatch index that read an empty declaration as an empty set would silence every + handler that exists -- and because an unhandled event is acknowledged rather than + retried (spec sec. 7.2), the events would be consumed and discarded rather than piling + up somewhere visible. + + **Exact event types only -- no wildcards.** A declaration is matched by equality, so + ``"orders.*"`` would be a type no event ever has and the handler would never run. + Declarations are checked when the index is built and a wildcard is rejected there, at + startup, rather than being silently ignored. A handler that selects a *family* of event + types should declare nothing and keep deciding in ``can_handle_event``. + + Returns: + The event types this handler accepts, exactly as they appear in ``event.type``. + Empty (the default) means every event is offered to it. + + Example:: + + def get_handled_event_types(self) -> list[str]: + return ["order.created", "order.cancelled"] + """ + + return [] + def get_subscribed_topics(self) -> list[str]: """Declare the NATS topics this handler subscribes to. diff --git a/src/blueprint/agents/handler/handler_chain.py b/src/blueprint/agents/handler/handler_chain.py index 89e8cd71..f010d949 100644 --- a/src/blueprint/agents/handler/handler_chain.py +++ b/src/blueprint/agents/handler/handler_chain.py @@ -1,6 +1,7 @@ """Handler chain for executing event handlers in priority order.""" import logging +import re import time from dataclasses import dataclass from typing import Any @@ -8,6 +9,8 @@ from opentelemetry import trace from ..component.component import Component, traced +from ..component.namespace import ROOT_LABEL, ROOT_NAMESPACE +from .event_handler_base import EventHandlerBase from ..models.events import CloudEvent, HandlerResult from ..utils import parse_bool @@ -26,6 +29,129 @@ IDEMPOTENCY_CACHE_NAMESPACE = "idempotency" """Cache namespace holding the seen-event markers, kept away from application data.""" +RUNTIME_CONTEXT_KEY = "runtime" +"""Context key carrying the ``AgentRuntime`` chosen for this event, when one was. + +Set by ``HandlerChain._bind_runtime`` before the winning handler runs, so a handler reads its +runtime from the context it is handed rather than looking one up -- which in a grouped process +is what keeps a namespace out of handler code. Absent when no runtime could be chosen, which +is every application that has no agent and every one with several and no declaration. +""" + +RUNTIME_NAME_CONTEXT_KEY = "runtime_name" +"""Context key carrying the registry name of that runtime. + +Read as well as written: ``EventProcessingService.process_event`` puts its ``runtime_name`` +argument here, and ``_bind_runtime`` treats it as the caller's choice -- below the handler's +own answer and above the single-runtime fallback. The name is kept beside the instance because +it is what appears in logs, and a caller that only wants to record which runtime served an +event should not have to reach into the object. +""" + +_WILDCARD_IN_DECLARATION = re.compile(r"[*>?\[\]\s]") +"""Characters that mean a declared event type was meant as a pattern. See :class:`DispatchIndex`.""" + + +@dataclass(frozen=True) +class DispatchIndex: + """Which handlers are worth asking about an event type (spec sec. 7.7). + + ``_dispatch`` used to ask every registered handler's ``can_handle`` in turn, so a process + hosting fifty handlers awaited fifty coroutines to find the one that wanted the event -- + and grouping multiplies exactly that, since a group's handlers all live in one process. + A handler that has declared the event types it accepts can be skipped without being asked. + + Two things this is *not*, both of them requirements rather than choices: + + - **It does not decide.** ``can_handle_event`` is imperative code and remains the selector; + the index only decides who gets asked. A declared handler is still asked and may still + say no, and the chain-of-responsibility fallthrough is untouched -- a candidate whose + ``handle`` returns ``None`` still passes the event to the next candidate. + - **It never narrows an undeclared handler.** A handler that declares nothing goes in + :attr:`wildcard` and is a candidate for every event, which is today's behaviour for every + handler that exists. Nothing in this framework or in any scaffolded project declares an + event type, so an index that treated declarations as authoritative would describe an empty + set and silence the entire application -- and an unhandled event acknowledges (spec + sec. 7.2), so the deliveries would be consumed and discarded rather than accumulating + where somebody would notice. + + Attributes: + by_type: For each declared event type, the candidates for it -- the handlers that + declared it *and* every wildcard handler, already merged and in priority order. + Merged at build time so that dispatch is a dictionary lookup. + wildcard: The handlers that declared nothing, in priority order. Also the candidate + list for any event type nobody declared. + """ + + by_type: dict[str, tuple[EventHandlerBase, ...]] + wildcard: tuple[EventHandlerBase, ...] + + def candidates(self, event_type: str) -> tuple[EventHandlerBase, ...]: + """Return the handlers to ask about ``event_type``, in priority order. + + An event type nobody declared falls back to the wildcard handlers rather than to + nothing: a type no handler named is not a type no handler wants, because a handler + that declared nothing wants all of them. + """ + return self.by_type.get(event_type, self.wildcard) + + @classmethod + def build(cls, handlers: tuple[EventHandlerBase, ...]) -> "DispatchIndex": + """Index ``handlers``, which must already be in the order dispatch should try them. + + Every candidate list is produced by *filtering* that order rather than by concatenating + buckets, so the sequence a handler is tried in is exactly the sequence it would have + been tried in without an index. Concatenating would reorder handlers of equal priority + -- putting the declared ones first -- and priority ties are currently resolved by + registration order, which a project may well be relying on without having said so. + + Args: + handlers: The namespace's handlers, priority-sorted. + + Returns: + The index. + + Raises: + ValueError: if a declared event type looks like a pattern. See + :meth:`_validate_declaration`. + """ + declarations = [(handler, tuple(handler.get_handled_event_types())) for handler in handlers] + for handler, declared in declarations: + for event_type in declared: + cls._validate_declaration(handler, event_type) + + wildcard = tuple(handler for handler, declared in declarations if not declared) + by_type = { + event_type: tuple(handler for handler, declared in declarations if not declared or event_type in declared) + for event_type in {event_type for _, declared in declarations for event_type in declared} + } + return cls(by_type=by_type, wildcard=wildcard) + + @staticmethod + def _validate_declaration(handler: EventHandlerBase, event_type: str) -> None: + """Reject a declaration that was written as a pattern, or that is empty. + + A declaration is matched by equality, so ``"orders.*"`` is a type no event ever has and + the handler would never be asked about anything. Ignoring it silently is the one failure + this whole design is built to avoid, so it fails here -- at startup, naming the handler + -- instead of at the first delivery that goes missing. + + Raises: + ValueError: if the declaration is blank or contains a wildcard character. + """ + if not event_type.strip(): + raise ValueError( + f"Handler '{handler.name}' declares an empty event type in get_handled_event_types(). Return an empty " + "list to be offered every event; a blank string matches nothing." + ) + if _WILDCARD_IN_DECLARATION.search(event_type): + raise ValueError( + f"Handler '{handler.name}' declares the event type '{event_type}', which looks like a pattern. " + "Declarations are matched by equality, so this handler would never be asked about any event. Declare " + "the exact event types, or return an empty list from get_handled_event_types() and keep selecting in " + "can_handle_event()." + ) + @dataclass(frozen=True) class IdempotencyPolicy: @@ -71,18 +197,62 @@ class HandlerChain(Component): ``idempotency_enabled`` (bool, default ``False``): opt into dedup. ``idempotency_ttl`` (int, no default): seconds a seen-event marker is kept. Required when dedup is enabled, and deliberately without a default -- see ``_resolve_idempotency_policy``. + + One chain per agent + ~~~~~~~~~~~~~~~~~~~ + A chain belongs to a namespace, and everything it reaches is that agent's: the handlers it + dispatches to, the configuration the dedup policy is read from, and the cache partition the + markers are claimed in. None of that is threaded through this class -- it all follows from + ``Component.registry`` and ``Component.config`` handing a component its own namespace's view + -- so the namespace appears here exactly once, in the constructor. + + That is also why a chain cannot be shared. Two agents in one process have their own handler + sets and may have different ``idempotency_ttl`` values, and a shared chain would resolve one + policy and dispatch to both agents' handlers. """ - def __init__(self) -> None: - """Initialize the handler chain.""" - super().__init__(should_register=False) + def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: + """Initialize the handler chain for one agent. + + Args: + namespace: The agent whose handlers this chain dispatches to, and whose + configuration and cache it reads. ``""`` is the root, which is the whole of a + single-agent application. + + Raises: + ValueError: if ``namespace`` is not a legal namespace. + """ + super().__init__(should_register=False, namespace=namespace) self._policy: IdempotencyPolicy | None = None + self._index: DispatchIndex | None = None + # Handlers already warned about an unchoosable runtime. See _warn_ambiguous_runtime. + self._warned_ambiguous: set[str] = set() + # The handler list the index was built from, so a change in the registered handlers is + # noticed. See _candidates. + self._indexed: tuple[EventHandlerBase, ...] = () async def on_startup(self) -> None: - """Resolve the idempotency policy so a bad setting fails startup, not a delivery.""" + """Resolve the idempotency policy and build the dispatch index. + + Both happen here so that a bad setting or a malformed event-type declaration fails + startup rather than a delivery. + """ self._policy = self._resolve_idempotency_policy() if self._policy.enabled: - logger.info("Event deduplication is enabled with a %d second window", self._policy.ttl) + logger.info( + "Event deduplication is enabled for namespace '%s' with a %d second window", + self.namespace or ROOT_LABEL, + self._policy.ttl, + ) + + index = self._refresh_index() + logger.info( + "Namespace '%s' dispatches %d handler(s): %d offered every event, %d declared event type(s)", + self.namespace or ROOT_LABEL, + len(self._indexed), + len(index.wildcard), + len(index.by_type), + ) async def on_shutdown(self) -> None: """No shutdown actions required.""" @@ -125,18 +295,64 @@ async def process(self, event: CloudEvent[Any], context: dict[str, Any]) -> Any # Dispatch # ------------------------------------------------------------------ + def _handlers(self) -> tuple[EventHandlerBase, ...]: + """Return this agent's handlers, in the order dispatch should try them. + + The namespace is passed explicitly rather than left to the registry view's default, + and the difference only shows up in a grouped process. On the root registry an omitted + namespace means *every* namespace, so a root chain would dispatch one agent's event + through every other agent's handlers. Naming the namespace makes the root chain mean + strictly the root, which in a single-agent application is every handler there is. + + There is no fallback to root handlers either. A handler registered at the root of a + grouped process would otherwise run for every agent in it, and nothing in a handler's + code could tell its author that is happening. + """ + return tuple(sorted(self.registry.get_event_handler(namespace=self.namespace))) + + def _refresh_index(self) -> DispatchIndex: + """Rebuild the dispatch index from the currently registered handlers.""" + self._indexed = self._handlers() + self._index = DispatchIndex.build(self._indexed) + return self._index + + def _candidates(self, event_type: str) -> tuple[EventHandlerBase, ...]: + """Return the handlers to ask about ``event_type``, rebuilding the index if it is stale. + + The index is built once, at startup. It is nevertheless *checked* on every dispatch, + because a handler registered after startup would otherwise never be asked about + anything: before the index, the chain queried the registry per event and picked such a + handler up automatically. Losing that silently is the failure this design is most + careful about, and the check costs what the old code already paid -- one registry query + and a tuple comparison -- while the index still saves the ``can_handle`` await per + handler, which is the expensive part. + """ + handlers = self._handlers() + if self._index is None or handlers != self._indexed: + self._indexed = handlers + self._index = DispatchIndex.build(handlers) + return self._index.candidates(event_type) + async def _dispatch(self, event: CloudEvent[Any], context: dict[str, Any]) -> Any | HandlerResult | list[HandlerResult] | None: - """Run the registered handlers in priority order until one returns a result.""" - handlers = sorted(self.registry.get_event_handler()) + """Ask this agent's candidate handlers in priority order until one returns a result.""" + handlers = self._candidates(event.type) span = trace.get_current_span() span.set_attribute("handlers.count", len(handlers)) - - logger.debug("Processing event through %d handlers", len(handlers)) + span.set_attribute("agent", self.namespace or ROOT_LABEL) + + logger.debug( + "Processing event '%s' through %d candidate handler(s) of %d in namespace '%s'", + event.type, + len(handlers), + len(self._indexed), + self.namespace or ROOT_LABEL, + ) for handler in handlers: try: if await handler.can_handle(event, context): logger.info("Handler '%s' handling event '%s'", handler.name, event.type) + self._bind_runtime(handler, event, context) result = await handler.handle(event, context) if result is not None: span.set_attribute("handler.processed_by", handler.name) @@ -148,9 +364,99 @@ async def _dispatch(self, event: CloudEvent[Any], context: dict[str, Any]) -> An span.record_exception(e) raise - logger.warning("No handler processed event '%s'", event.type) + logger.warning("No handler in namespace '%s' processed event '%s'", self.namespace or ROOT_LABEL, event.type) return None + # ------------------------------------------------------------------ + # Handler -> agent binding (phase 7) + # ------------------------------------------------------------------ + + def _bind_runtime(self, handler: EventHandlerBase, event: CloudEvent[Any], context: dict[str, Any]) -> None: + """Put the agent runtime this handler should use into ``context``, if one can be chosen. + + Called between ``can_handle`` saying yes and ``handle`` running, which is the only point + where the answer is still useful: the winning handler is known, and it has not run yet. + Resolving after the fact -- which is where the plan put this -- would produce a runtime + nothing could act on. + + Three sources, in order of how explicit they are: + + 1. ``handler.get_runtime_name(event, context)``, the handler's own choice for this event. + 2. ``context["runtime_name"]``, which is what a caller passed to ``process_event``. That + parameter existed and was only logged; honouring it here is what makes it mean + something, while keeping the handler's own answer above it. + 3. The single agent runtime in this handler's namespace, if there is exactly one. This is + what a single-agent application has in practice, and it is why the common case needs + no declaration at all. + + With several runtimes and nothing declared, **nothing is bound**. The plan asks for an + error here, and that would break applications that work today: two agents plus handlers + that resolve their own runtime by name is a shape this framework already supports, and + the framework resolving nothing is exactly what those applications rely on. So the + ambiguity is reported once, at WARNING, naming the candidates and the override -- an + unexpected condition that was handled, which is what that level is for. A handler that + genuinely needs a runtime and finds none is a handler that has to say which one it wants. + + Args: + handler: The handler about to run. + event: The event it is about to be given. + context: The processing context, mutated in place. + + Raises: + ValueError: if a name *was* declared and no such runtime exists. A declaration the + framework cannot honour is a failure, not something to fall back from -- the + same reading as ``event_publishing_enabled`` without a transport. + """ + declared = handler.get_runtime_name(event, context) or context.get(RUNTIME_NAME_CONTEXT_KEY) + if declared: + context[RUNTIME_NAME_CONTEXT_KEY] = declared + context[RUNTIME_CONTEXT_KEY] = self._runtime_named(str(declared), handler) + return + + names = self.registry.get_agents(namespace=self.namespace) + if len(names) == 1: + context[RUNTIME_NAME_CONTEXT_KEY] = names[0] + context[RUNTIME_CONTEXT_KEY] = self.registry.get_agent(names[0], self.namespace) + return + + if len(names) > 1: + self._warn_ambiguous_runtime(handler, names) + + def _runtime_named(self, name: str, handler: EventHandlerBase) -> Any: + """Return the runtime called ``name`` in this agent, or raise saying what is registered. + + The namespace is named explicitly, so the lookup is this agent's runtime first and a + shared root one second -- and never a neighbour's, which an unscoped lookup would reach. + """ + try: + return self.registry.get_agent(name, self.namespace) + except ValueError as exc: + registered = ", ".join(self.registry.get_agents(namespace=self.namespace)) or "none" + raise ValueError( + f"Handler '{handler.name}' asked for agent runtime '{name}', which is not registered in namespace " + f"'{self.namespace or ROOT_LABEL}' or at the root (registered here: {registered}). Either register it, " + "or return a name that exists from get_runtime_name()." + ) from exc + + def _warn_ambiguous_runtime(self, handler: EventHandlerBase, names: list[str]) -> None: + """Report once that a runtime could not be chosen, rather than on every delivery. + + Once per handler, because the condition is a property of the code rather than of the + event: the same handler with the same namespace will be ambiguous for every event it + ever handles, and a per-delivery warning would bury the one line that matters. + """ + if handler.name in self._warned_ambiguous: + return + self._warned_ambiguous.add(handler.name) + logger.warning( + "Handler '%s' in namespace '%s' did not say which agent runtime to use and %d are registered (%s), so " + "none was bound into the context. Override get_runtime_name() to choose one.", + handler.name, + self.namespace or ROOT_LABEL, + len(names), + ", ".join(names), + ) + # ------------------------------------------------------------------ # Idempotency (P4) # ------------------------------------------------------------------ diff --git a/src/blueprint/agents/handler/sessions_job_handler.py b/src/blueprint/agents/handler/sessions_job_handler.py index 93215cf1..db6ee9a3 100644 --- a/src/blueprint/agents/handler/sessions_job_handler.py +++ b/src/blueprint/agents/handler/sessions_job_handler.py @@ -100,9 +100,28 @@ async def on_startup(self) -> None: async def on_shutdown(self) -> None: return None + @property + def job_created_event_type(self) -> str: + """The event type a job of this handler's :attr:`JOB_TYPE` arrives as. + + One definition, read by both selectors: :meth:`can_handle_event` decides with it and + :meth:`get_handled_event_types` declares it. Written out twice they could drift, and a + declaration that no longer matches the check is a handler the index never offers an + event to. + """ + return f"sessions.job.created.{self.JOB_TYPE}" + + def get_handled_event_types(self) -> list[str]: + """Declare the one event type this subclass's jobs arrive as. + + Derived from :attr:`JOB_TYPE`, so a subclass opts into the dispatch index by setting + the class variable it already had to set -- it declares nothing of its own. + """ + return [self.job_created_event_type] + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: """Handle only this subclass's job type; unknown types are ignored.""" - return event.type == f"sessions.job.created.{self.JOB_TYPE}" + return event.type == self.job_created_event_type @abstractmethod async def process(self, payload: BaseModel, context: dict[str, Any]) -> BaseModel: diff --git a/src/blueprint/agents/io/api/eventing/cloud_event_processor_mixin.py b/src/blueprint/agents/io/api/eventing/cloud_event_processor_mixin.py index 5706a4a5..5a2e2c26 100644 --- a/src/blueprint/agents/io/api/eventing/cloud_event_processor_mixin.py +++ b/src/blueprint/agents/io/api/eventing/cloud_event_processor_mixin.py @@ -21,7 +21,7 @@ class CloudEventProcessorMixin: Provides unwrapping of nested CloudEvents, correlation-context management, OTel span attribute stamping, and dispatch to the EventProcessingService. - Must be combined with a class that supplies a ``registry`` attribute + Must be combined with a class that supplies ``registry`` and ``namespace`` attributes (i.e. any ``Component`` subclass). """ @@ -31,8 +31,9 @@ async def _dispatch_cloud_event( self, cloud_event: CloudEvent[Any], context: dict[str, Any], + namespace: str | None = None, ) -> ProcessingResult: - """Dispatch a CloudEvent through the processing service. + """Dispatch a CloudEvent through the processing service, for one agent. Sets up correlation context and OTel span attributes, optionally unwraps Dapr-style envelopes, then delegates to EventProcessingService. @@ -73,7 +74,11 @@ async def _dispatch_cloud_event( span.set_attribute("event.unwrapped", True) processing_service = self.registry.get_service(EventProcessingService) # type: ignore[attr-defined] - processing_result = await processing_service.process_event(cloud_event, context) + # Which agent to dispatch to: the caller's choice where it fans one delivery out to + # several, otherwise this endpoint's own namespace. One processing service serves the + # process; the namespace is what tells it which chain to use. + target = self.namespace if namespace is None else namespace # type: ignore[attr-defined] + processing_result = await processing_service.process_event(cloud_event, context, namespace=target) if not isinstance(processing_result, ProcessingResult): logger.error( diff --git a/src/blueprint/agents/io/api/eventing/dapr.py b/src/blueprint/agents/io/api/eventing/dapr.py index b7896d72..b46de40d 100644 --- a/src/blueprint/agents/io/api/eventing/dapr.py +++ b/src/blueprint/agents/io/api/eventing/dapr.py @@ -10,7 +10,8 @@ from fastapi.routing import APIRoute from ....clients.io.dapr_client import DaprClient -from ....models.errors import DeliveryDisposition, HandlerError, disposition_for +from ....component.namespace import ROOT_LABEL, ROOT_NAMESPACE, namespace_of +from ....models.errors import DeliveryDisposition, HandlerError, combined_disposition, disposition_for from ....models.events import CloudEvent from ..rest_api_base import RestApiBase from .dapr_response import dapr_status @@ -64,34 +65,89 @@ class DaprEventing(EventHandlingBase): ``health_check()``. The client never invokes those callbacks, because delivery arrives over HTTP rather than through a client-side subscription. + One endpoint for the process, fanned out to the agents + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + Unlike the NATS endpoint, there is exactly **one** of these however many agents the process + hosts, and it lives at the root. The two paths above are fixed by Dapr's protocol: the + sidecar fetches the document from one place and posts deliveries where the document says. + An endpoint per agent, each behind its own prefix, would leave the sidecar with no document + to fetch at all. + + So the routing that NATS gets from the broker -- one consumer per ``(namespace, topic)`` -- + is done here instead, in the process: + + - :meth:`subscribe` returns the **union** of every agent's declared topics, deduplicated, + because the sidecar needs telling once per topic. + - :meth:`publish` looks the delivered topic up in :meth:`_agents_for` and dispatches once + **per agent that declared it**, each through that agent's own handler chain. Two agents + declaring one topic therefore both receive it, which is the same rule spec sec. 7.6 states + for the broker-side case. + - The one acknowledgement the sidecar reads is the combination of what each dispatch earned + (:func:`combined_disposition`). + + **The cost, which has no equivalent under NATS: a redelivery is shared.** There is one + delivery, so there is one acknowledgement; if any agent asks for a retry, every agent in the + group sees the message again. A grouped Dapr deployment therefore wants + ``idempotency_enabled`` set, or handlers that tolerate a repeat. Under NATS each agent has + its own consumer and its own acknowledgement, and no such coupling exists. + Config keys ~~~~~~~~~~~ ``dapr_pubsub_name`` (str, default ``"pubsub"``): the Dapr pub/sub component to bind to. ``dapr_declarative_subscriptions`` (bool, default ``False``): set ``True`` when subscriptions are declared outside the application (CRD or YAML) so the discovery - endpoint returns an empty document and the sidecar cannot subscribe twice. + endpoint returns an empty document and the sidecar cannot subscribe twice. Note that the + framework then has no topic-to-agent map, so a delivery is offered to every agent -- see + :meth:`_agents_for`. """ route_class = DaprDeliveryRoute def __init__(self) -> None: + """Initialize the process's Dapr endpoint. + + **Takes no namespace, unlike every other transport component.** There is one of these + per process and it belongs to the root, because Dapr's two paths are fixed by its + protocol and cannot be prefixed per agent. Making that structural rather than + documented is what keeps :meth:`_topics_by_agent` correct: it reads *every* handler in + the process, which it can only do because ``self.registry`` is the application's + registry rather than one agent's view of it. A namespaced instance would see one + agent's handlers and silently route only that agent's topics. + """ super().__init__(should_register=False) - self._client: DaprClient | None = None + # The client per agent, not one client: this endpoint is shared by the process, and + # the clients are not. Populated in on_startup; empty when no agent declared a topic. + self._clients: dict[str, DaprClient] = {} async def on_startup(self) -> None: - self._client = self.registry.get_component(DaprClient) - - # Delivery is driven by the subscription document in subscribe(); this handing-over - # exists so the client starts its sidecar-reachability retry and can report - # subscriptions_ready. Removing it would silently disable readiness gating. - topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = { - topic: self._make_event_callback(topic) for topic in self._declared_topics() - } - - if topic_callbacks: - await self._client.subscribe(topic_callbacks) - else: + """Hand each agent's topics to that agent's client, for readiness reporting. + + Delivery is driven by the subscription document in :meth:`subscribe`; this handing-over + exists so each client starts its sidecar-reachability retry and can report + ``subscriptions_ready``. Removing it would silently disable readiness gating. + + Per agent rather than once for the process, even though this endpoint is shared: the + client is per agent (spec sec. 6), and readiness reported against the wrong agent is + what makes ``readiness_policy = "critical"`` unusable. + """ + topics_by_agent = self._topics_by_agent() + if not topics_by_agent: logger.debug("DaprEventing: no handler declared a topic; nothing to report as ready") + return + + for namespace, topics in topics_by_agent.items(): + client = self.registry.get_component(DaprClient, namespace=namespace) + self._clients[namespace] = client + topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = { + topic: self._make_event_callback(topic) for topic in topics + } + logger.info( + "Namespace '%s' declares %d topic(s) to the sidecar: %s", + namespace or ROOT_LABEL, + len(topic_callbacks), + ", ".join(topic_callbacks), + ) + await client.subscribe(topic_callbacks) async def on_shutdown(self) -> None: pass @@ -130,43 +186,128 @@ async def subscribe(self) -> list[dict[str, Any]]: return [] pubsub_name = self.config.get("dapr_pubsub_name", "pubsub") - return [{"pubsubname": pubsub_name, "topic": topic, "route": f"/events/{topic}"} for topic in self._declared_topics()] - - def _declared_topics(self) -> list[str]: - """Return every topic declared by a registered handler, in declaration order.""" - topics: dict[str, None] = {} + # route_prefix, not a bare '/events/...': this document is what makes the sidecar post + # anywhere at all, so it has to name the path the router is actually mounted at. This + # endpoint is always the root one, so the prefix is empty and the document is + # byte-identical to what it always was -- the property is read rather than hardcoded so + # the two cannot drift if that ever changes. + return [ + {"pubsubname": pubsub_name, "topic": topic, "route": f"{self.route_prefix}/events/{topic}"} for topic in self._declared_topics() + ] + + def _topics_by_agent(self) -> dict[str, list[str]]: + """Return each agent's declared topics, keyed by namespace, in declaration order. + + Read from the handlers themselves rather than from any list of agents: an agent that + declared no topic has nothing to subscribe and nothing to be delivered, so it does not + appear here at all. Every handler in the process is walked, which is what makes this the + one place that sees the whole routing picture -- and it is only safe because this + endpoint is the process's single Dapr endpoint rather than one of several. + """ + by_agent: dict[str, dict[str, None]] = {} + # No namespace argument, which here means every namespace: this endpoint is the root + # one -- enforced by __init__ taking no namespace at all -- so its registry is the + # application's rather than one agent's view, and an omitted namespace is the whole + # process. That is the one place in the framework where this reading is what is wanted. for handler in self.registry.get_event_handler(): for topic in handler.get_subscribed_topics(): if topic: - topics[topic] = None + by_agent.setdefault(namespace_of(handler), {})[topic] = None + return {namespace: list(topics) for namespace, topics in by_agent.items()} + + def _declared_topics(self) -> list[str]: + """Return every topic any agent in this process declares, deduplicated. + + This is the union, not one agent's list, because it renders the sidecar's subscription + document and the sidecar needs telling **once** per topic -- it delivers a topic to the + application once however many agents want it. Fanning that one delivery out is + :meth:`publish`'s job, not the sidecar's. + """ + topics: dict[str, None] = {} + for declared in self._topics_by_agent().values(): + for topic in declared: + topics[topic] = None return list(topics) + def _agents_for(self, topic: str) -> tuple[str, ...]: + """Return the agents a delivery on ``topic`` is offered to. + + The agents that declared the topic, in a stable order. When **nobody** declared it, + every agent that has handlers at all -- which is the same rule + ``DispatchIndex.candidates`` applies one level down: a declaration narrows who is asked, + and its absence cannot narrow anything to nothing. + + That fallback is what a topic arriving from outside the application needs. + ``dapr_declarative_subscriptions`` makes the subscription document empty, so the + framework never sees the topic list at all and no handler need declare anything; the + sidecar still delivers. Sending such a delivery nowhere would silence the application, + and an unhandled event acknowledges (spec sec. 7.2), so the events would be consumed and + discarded. For a single-agent application both branches are the root, so this changes + nothing there. + """ + by_agent = self._topics_by_agent() + declared = tuple(namespace for namespace, topics in by_agent.items() if topic in topics) + if declared: + return declared + with_handlers = tuple(dict.fromkeys(namespace_of(handler) for handler in self.registry.get_event_handler())) + return with_handlers or (ROOT_NAMESPACE,) + @RestApiBase.post("/events/{topic}", tags=["dapr"]) async def publish(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[str, Any]: - """Receive an event from the sidecar and answer with its acknowledgement. + """Receive an event from the sidecar, offer it to every agent that wants it, and answer. The returned dict is the acknowledgement, so this method is Dapr's equivalent of ``NATSClient._settle`` and follows the same table (spec sec. 7.2): a handler chain - that returned answers ``SUCCESS`` whatever its status, and a raised exception is - classified by ``disposition_for`` and rendered into Dapr's words. One ``except`` - rather than one per error type, so the two transports cannot drift apart. + that returned acknowledges whatever its status, and a raised exception is classified by + ``disposition_for`` and rendered into Dapr's words. One ``except`` rather than one per + error type, so the two transports cannot drift apart. + + **One delivery, one answer, several agents.** Each agent named by :meth:`_agents_for` + gets its own dispatch through its own chain, and a failure in one does not stop the + others -- an agent that raised must not silently cancel a neighbour's work, which is + what letting the exception out of the loop would do. The answers are then combined by + :func:`combined_disposition`, whose docstring carries the ordering and its cost: a retry + asked for by one agent redelivers to all of them. + + The reason string reports the first failure. There is one field for it and no way to + return several, so it names the first agent that failed rather than concatenating; the + per-agent errors are logged individually above it, each with its agent. """ + agents = self._agents_for(topic) + dispositions: list[DeliveryDisposition] = [] + reason: str | None = None - try: - await self._process_cloud_event(cloud_event, {"dapr_topic": topic}, topic) - except Exception as exc: - disposition = disposition_for(exc) - reason = exc.reason if isinstance(exc, HandlerError) else str(exc) - logger.error( - "Handler failed for event %s on topic '%s', answering %s: %s", + for namespace in agents: + try: + await self._process_cloud_event(cloud_event, {"dapr_topic": topic}, topic, namespace=namespace) + dispositions.append(DeliveryDisposition.ACK) + except Exception as exc: + disposition = disposition_for(exc) + dispositions.append(disposition) + if reason is None: + reason = exc.reason if isinstance(exc, HandlerError) else str(exc) + logger.error( + "Handler in namespace '%s' failed for event %s on topic '%s', answering %s: %s", + namespace or ROOT_LABEL, + cloud_event.id, + topic, + dapr_status(disposition), + exc, + exc_info=True, + ) + + combined = combined_disposition(dispositions) + if len(agents) > 1: + logger.debug( + "Event %s on topic '%s' was offered to %d agents (%s); answering %s", cloud_event.id, topic, - dapr_status(disposition), - exc, - exc_info=True, + len(agents), + ", ".join(namespace or ROOT_LABEL for namespace in agents), + dapr_status(combined), ) - return {"status": dapr_status(disposition), "reason": reason} - # An unmatched event acknowledges like any other completed dispatch; the accounting # that keeps it visible lives in _process_cloud_event, shared with the NATS edge. - return {"status": dapr_status(DeliveryDisposition.ACK)} + if reason is None: + return {"status": dapr_status(combined)} + return {"status": dapr_status(combined), "reason": reason} diff --git a/src/blueprint/agents/io/api/eventing/event_handling_base.py b/src/blueprint/agents/io/api/eventing/event_handling_base.py index b8ee837f..c0049f90 100644 --- a/src/blueprint/agents/io/api/eventing/event_handling_base.py +++ b/src/blueprint/agents/io/api/eventing/event_handling_base.py @@ -9,7 +9,7 @@ from opentelemetry import metrics from ....component.component import traced -from ....component.namespace import ROOT_NAMESPACE +from ....component.namespace import ROOT_LABEL from ....handler.handler_chain import DUPLICATE_CONTEXT_KEY from ....models import ProcessingResult, ProcessingStatus from ....models.errors import DeliveryDisposition @@ -68,8 +68,14 @@ async def _process_cloud_event( cloud_event: CloudEvent[Any], context: dict[str, Any], topic: str, + namespace: str | None = None, ) -> ProcessingResult: - """Dispatch a CloudEvent through the handler chain, letting failures propagate. + """Dispatch a CloudEvent through one agent's handler chain, letting failures propagate. + + ``namespace`` names the agent to dispatch to, defaulting to this endpoint's own -- which + is every case but one. The exception is the Dapr path in a grouped process: the sidecar + delivers to one fixed path, so a single root endpoint receives the delivery and fans it + out, naming a different agent on each call. Deliberately does not log those failures. Every caller of this method is a transport edge that must both decide the delivery disposition and report the failure (spec @@ -97,12 +103,18 @@ async def _process_cloud_event( own key there (``nats_topic``, ``dapr_topic``), and those keys reach user handlers, so they cannot be unified without breaking them. """ - logger.debug("Processing CloudEvent: %s", cloud_event.id) - processing_result = await self._dispatch_cloud_event(cloud_event, context) + agent = self.namespace if namespace is None else namespace + logger.debug("Processing CloudEvent %s for namespace '%s'", cloud_event.id, agent or ROOT_LABEL) + processing_result = await self._dispatch_cloud_event(cloud_event, context, namespace=agent) + # The agent this dispatch was for, not a hardcoded root. Both counters are documented as + # per-namespace and were attributing every event in the process to the root, so a group + # would have reported one agent's broad subscription as everybody's. The value is the + # namespace verbatim, so a single-agent application keeps reporting '' and its existing + # dashboards do not see a new label value. if context.get(DUPLICATE_CONTEXT_KEY): - _DUPLICATE_EVENTS.add(1, {"namespace": ROOT_NAMESPACE, "topic": topic}) - logger.debug("Event %s on topic '%s' was already processed", cloud_event.id, topic) + _DUPLICATE_EVENTS.add(1, {"namespace": agent, "topic": topic}) + logger.debug("Event %s on topic '%s' was already processed by '%s'", cloud_event.id, topic, agent or ROOT_LABEL) elif processing_result.status is ProcessingStatus.NO_HANDLER_FOUND: - _UNHANDLED_EVENTS.add(1, {"namespace": ROOT_NAMESPACE, "topic": topic}) - logger.debug("No handler had work for event %s on topic '%s'", cloud_event.id, topic) + _UNHANDLED_EVENTS.add(1, {"namespace": agent, "topic": topic}) + logger.debug("No handler in '%s' had work for event %s on topic '%s'", agent or ROOT_LABEL, cloud_event.id, topic) return processing_result diff --git a/src/blueprint/agents/io/api/eventing/nats.py b/src/blueprint/agents/io/api/eventing/nats.py index fabf708a..5db230ed 100644 --- a/src/blueprint/agents/io/api/eventing/nats.py +++ b/src/blueprint/agents/io/api/eventing/nats.py @@ -5,6 +5,7 @@ from typing import Any from ....clients.io.nats_client import NATSClient +from ....component.namespace import ROOT_LABEL, ROOT_NAMESPACE from ....models.events import CloudEvent from ..rest_api_base import RestApiBase from .event_handling_base import EventHandlingBase @@ -23,28 +24,74 @@ class NatsEventing(EventHandlingBase): failure reaches the transport -- ``ProcessingStatus`` has no failure value -- and the transport edge is what turns it into a nak or a term (spec sec. 7.2). Catching one here would acknowledge the event as successfully processed. + + One endpoint per agent + ~~~~~~~~~~~~~~~~~~~~~~ + This component belongs to a namespace and subscribes on behalf of that agent alone: it + reads that agent's handlers, that agent's ``nats_subscriptions``, and that agent's + ``NATSClient``. A process hosting three agents therefore holds three of these, and each + ``(namespace, topic)`` pair ends up with its own subscription and its own consumer, which + is what spec sec. 7.6 requires. + + **Topic deduplication is per agent, and only per agent.** Two agents subscribing to the + same topic both want the event, so there is no cross-agent "first declaration wins" -- + which would silently disable one agent's subscription, and could not be observed by its + author running it alone. Deduplication happens inside one of these components, so it + cannot reach across namespaces by construction. """ - def __init__(self) -> None: - super().__init__(should_register=False) + def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: + """Initialize the NATS endpoint for one agent. + + Args: + namespace: The agent this endpoint subscribes for. ``""`` is the root, which is + the whole of a single-agent application. + """ + super().__init__(should_register=False, namespace=namespace) self._client: NATSClient | None = None async def on_startup(self) -> None: - self._client = self.registry.get_component(NATSClient) + """Subscribe this agent's topics through this agent's client.""" + self._client = self.registry.get_component(NATSClient, namespace=self.namespace) - topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = {} - for handler in self.registry.get_event_handler(): - for topic in handler.get_subscribed_topics(): - if topic and topic not in topic_callbacks: - topic_callbacks[topic] = self._make_event_callback(topic) - for topic in self.config.get_nats_subscription_config(): - if topic and topic not in topic_callbacks: - topic_callbacks[topic] = self._make_event_callback(topic) + topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = { + topic: self._make_event_callback(topic) for topic in self._declared_topics() + } if topic_callbacks: + logger.info( + "Namespace '%s' subscribes to %d topic(s): %s", + self.namespace or ROOT_LABEL, + len(topic_callbacks), + ", ".join(topic_callbacks), + ) await self._client.subscribe(topic_callbacks) else: - logger.info("NatsEventing: no auto-subscriptions configured") + logger.info("NatsEventing: no auto-subscriptions configured for namespace '%s'", self.namespace or ROOT_LABEL) + + def _declared_topics(self) -> list[str]: + """Return the topics this agent subscribes to, in declaration order. + + Two sources, in this order: the ``get_subscribed_topics()`` of this agent's handlers, + then the ``nats_subscriptions`` config list. Both are scoped to this agent without + anything here saying so -- ``self.registry`` and ``self.config`` are already this + namespace's views, so the config key resolves ``.nats_subscriptions`` before + falling back to the shared list (C5), and the handler query is filtered below. + + The namespace is named explicitly in the handler query for the reason it is named in + ``HandlerChain._handlers``: on the root registry an omitted namespace means *every* + namespace, so the root endpoint would otherwise subscribe to every agent's topics and + deliver them all through the root chain. + """ + topics: dict[str, None] = {} + for handler in self.registry.get_event_handler(namespace=self.namespace): + for topic in handler.get_subscribed_topics(): + if topic: + topics[topic] = None + for topic in self.config.get_nats_subscription_config(): + if topic: + topics[topic] = None + return list(topics) async def on_shutdown(self) -> None: pass diff --git a/src/blueprint/agents/io/api/eventing/sessions_bus.py b/src/blueprint/agents/io/api/eventing/sessions_bus.py index d9b86e7d..2b85c0ed 100644 --- a/src/blueprint/agents/io/api/eventing/sessions_bus.py +++ b/src/blueprint/agents/io/api/eventing/sessions_bus.py @@ -16,6 +16,7 @@ from opentelemetry import trace from ....component.component import Component +from ....component.namespace import ROOT_NAMESPACE from ....models.errors import InvalidEventError, RetryableHandlerError from ....models.events import GenericCloudEvent from ....models.sessions import JobNotification @@ -37,9 +38,16 @@ class SessionsBus(Component, CloudEventProcessorMixin): with the standard Component registry. """ - def __init__(self) -> None: - """Initialize the sessions event bus.""" - super().__init__() + def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: + """Initialize the sessions event bus for one agent. + + Args: + namespace: The agent whose jobs this bus dispatches; ``""`` is the root, which is + the whole of a single-agent application. The namespace reaches + ``_dispatch_cloud_event`` from here, so a job notification is offered to that + agent's handlers and no other's. + """ + super().__init__(namespace=namespace) # SSE connection self._sse_task: asyncio.Task[None] | None = None diff --git a/src/blueprint/agents/io/api/rest_api_base.py b/src/blueprint/agents/io/api/rest_api_base.py index 1bb09e04..94c6e650 100644 --- a/src/blueprint/agents/io/api/rest_api_base.py +++ b/src/blueprint/agents/io/api/rest_api_base.py @@ -35,6 +35,7 @@ async def create_item(self, payload: ItemRequest) -> Item: from opentelemetry import trace from ...component.component import traced +from ...component.namespace import ROOT_NAMESPACE from ...models import ProcessResourceResponse, ProcessingStatus from ..io_base import IOBase @@ -60,11 +61,38 @@ class RestApiBase(IOBase, ABC): which routes it is allowed to answer for. """ - def __init__(self, should_register: bool = True) -> None: - super().__init__(should_register) + def __init__(self, should_register: bool = True, *, namespace: str = ROOT_NAMESPACE) -> None: + """Initialize the REST API and wire its declared routes. + + Args: + should_register: Whether to add this instance to the shared registry. + namespace: The agent this API belongs to. Keyword-only and defaulting to the root, + so no existing subclass changes. A developer's API never passes it -- it is + read from the ambient scope by ``Component`` -- but the framework's own + per-agent endpoints are built outside any scope and name it. + """ + super().__init__(should_register, namespace=namespace) self._router = APIRouter(route_class=type(self).route_class) self._wire_routes() + @property + def route_prefix(self) -> str: + """The path prefix this component's routes are mounted under. + + ``""`` for the root, so every path an existing application serves is unchanged, and + ``/api/`` for a component that belongs to one. An agent's whole HTTP surface + therefore lives under one prefix, and two agents in a group cannot collide on a path -- + which they otherwise would, since a group applies the same registration twice and both + copies declare the same routes. + + It is a property on this class rather than a rule inside ``AppBuilder`` because two + places have to agree on it: the builder, which mounts the router, and + ``DaprEventing.subscribe``, which tells the sidecar where to post deliveries. If those + two disagreed the sidecar would post to a path FastAPI does not serve, and every + delivery would 404 -- with the application otherwise healthy. + """ + return f"/api/{self.namespace}" if self.namespace else "" + @property def router(self) -> APIRouter: """Access the instance router. This property is read-only.""" @@ -168,7 +196,9 @@ async def _process_resource(self, request: Request, payload: Any) -> ProcessReso from ...services.eventing.event_processing_service import EventProcessingService # noqa: PLC0415 event_processing_service = self.registry.get_service(EventProcessingService) - processing_result = await event_processing_service.process_rest_request(payload, context) + # This API's own namespace: a REST call into one agent must not be offered to + # another agent's handlers. + processing_result = await event_processing_service.process_rest_request(payload, context, namespace=self.namespace) success = processing_result.status == ProcessingStatus.PROCESSED success_message = processing_result.message or "Processing completed successfully" diff --git a/src/blueprint/agents/io/api/utilities/cache.py b/src/blueprint/agents/io/api/utilities/cache.py index b6befac7..b7a0a30d 100644 --- a/src/blueprint/agents/io/api/utilities/cache.py +++ b/src/blueprint/agents/io/api/utilities/cache.py @@ -4,14 +4,25 @@ from fastapi import HTTPException +from ....component.registry import DEFAULT_CACHE_NAME from ....models.api import CacheEvictRequest, CacheNamespacesResponse, CacheStatsResponse +from ....services.infrastructure.cache_service import CacheService from ..rest_api_base import RestApiBase logger = logging.getLogger(__name__) class CacheManagementApi(RestApiBase): - """API for managing cache operations.""" + """API for managing cache operations. + + One router for the process, and every endpoint takes an optional ``?name=`` naming which + cache to act on. It defaults to :data:`DEFAULT_CACHE_NAME`, so a request that names nothing + reaches the cache a single-cache application has always had. + + A router per cache was the alternative and is wrong: caches can be registered after startup + (``registry.add_cache``), and routes cannot, so anything keyed on the set of caches at build + time would serve a stale list. Resolving the name per request has no such window. + """ def __init__(self) -> None: super().__init__(should_register=False) @@ -22,35 +33,52 @@ async def on_startup(self) -> None: async def on_shutdown(self) -> None: """No shutdown actions required; cache service is managed externally.""" - @RestApiBase.get("/cache/stats", response_model=CacheStatsResponse, tags=["cache"], summary="Get cache statistics.") - async def get_cache_stats(self) -> CacheStatsResponse: - """Get cache statistics.""" - if not self.registry.has_cache(): + def _cache(self, name: str) -> CacheService: + """Return the cache called ``name``, or answer the request with an HTTP error. + + Two distinct failures, answered differently. **503** when no cache is registered at all: + the application was built without one, the condition is not the caller's doing, and it + may resolve without a redeploy -- which is what 503 says. **404** when caches exist but + none has this name: that is a bad request for a resource that is not there, and + answering 503 would invite a retry that can never succeed. + + The registered names go in the 404 body. A caller who mistypes a cache name otherwise + has no way to discover the right one, and there is no endpoint that lists them. + + Raises: + HTTPException: 503 with no cache registered, 404 for an unknown name. + """ + if not self.registry.get_all_caches(): raise HTTPException(status_code=503, detail="Cache service not available") - stats = self.registry.cache_service.get_stats() + try: + return self.registry.get_cache(name) + except ValueError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + + @RestApiBase.get("/cache/stats", response_model=CacheStatsResponse, tags=["cache"], summary="Get cache statistics.") + async def get_cache_stats(self, name: str = DEFAULT_CACHE_NAME) -> CacheStatsResponse: + """Get statistics for one cache.""" + stats = self._cache(name).get_stats() return CacheStatsResponse(**stats) @RestApiBase.get("/cache/namespaces", response_model=CacheNamespacesResponse, tags=["cache"], summary="List all cache namespaces.") - async def list_cache_namespaces(self) -> CacheNamespacesResponse: - """List all namespaces currently stored in cache.""" - if not self.registry.has_cache(): - raise HTTPException(status_code=503, detail="Cache service not available") - namespaces = self.registry.cache_service.list_namespaces() - logger.debug("Listing cache namespaces: %s", namespaces) + async def list_cache_namespaces(self, name: str = DEFAULT_CACHE_NAME) -> CacheNamespacesResponse: + """List all namespaces currently stored in one cache.""" + namespaces = self._cache(name).list_namespaces() + logger.debug("Listing namespaces in cache '%s': %s", name, namespaces) return CacheNamespacesResponse(namespaces=namespaces, count=len(namespaces)) @RestApiBase.post("/cache/evict", tags=["cache"], summary="Evict cache contents for an optional namespace.") - async def evict_cache_entry(self, request: CacheEvictRequest) -> dict[str, str]: - """Evict (clear) cache contents for an optional namespace.""" - if not self.registry.has_cache(): - raise HTTPException(status_code=503, detail="Cache service not available") - self.registry.cache_service.clear(namespace=request.namespace) + async def evict_cache_entry(self, request: CacheEvictRequest, name: str = DEFAULT_CACHE_NAME) -> dict[str, str]: + """Evict (clear) contents of one cache, for an optional namespace within it.""" + self._cache(name).clear(namespace=request.namespace) if request.namespace: - logger.info("Cleared cache namespace '%s'", request.namespace) + logger.info("Cleared namespace '%s' in cache '%s'", request.namespace, name) else: - logger.info("Cleared entire cache") + logger.info("Cleared the whole of cache '%s'", name) return { "status": "ok", + "cache": name, "namespace": request.namespace or "all", "message": f"Cache cleared for namespace '{request.namespace}'" if request.namespace else "Entire cache cleared", } diff --git a/src/blueprint/agents/models/errors.py b/src/blueprint/agents/models/errors.py index 1bee354b..d51def5c 100644 --- a/src/blueprint/agents/models/errors.py +++ b/src/blueprint/agents/models/errors.py @@ -1,5 +1,6 @@ """Handler exceptions, and the delivery disposition each one implies.""" +from collections.abc import Iterable from enum import Enum @@ -71,3 +72,41 @@ def disposition_for(exc: BaseException) -> DeliveryDisposition: if isinstance(exc, error_type): return disposition return DeliveryDisposition.NAK + + +def combined_disposition(dispositions: Iterable[DeliveryDisposition]) -> DeliveryDisposition: + """Return the one disposition that answers for several dispatches of one delivery. + + Needed where a single delivery is fanned out to several agents and the transport reads + exactly one answer -- which is the Dapr path in a grouped process: the sidecar delivers a + topic once and reads one status from the response. + + The order is ``NAK`` > ``ACK`` > ``TERM``, and each step is a decision: + + - **Any ``NAK`` wins.** One agent asked for the delivery again, and the only way to give it + one is to ask for a redelivery of the whole message. The cost is that the agents which + already succeeded see it again, so a grouped Dapr deployment wants + ``idempotency_enabled`` -- there is no per-agent acknowledgement to be had on this path, + because there is no per-agent delivery. + - **Otherwise any ``ACK`` wins over ``TERM``.** A ``TERM`` from one agent means *that* agent + found the message undeliverable, which is a finished outcome rather than a failure of the + delivery; if another agent handled it, the message was handled. Answering ``TERM`` there + would report a successful delivery as dropped. + - **All ``TERM`` is ``TERM``.** Every agent judged it undeliverable, and no redelivery + changes that. + + An empty argument is ``ACK``: nothing was dispatched, so nothing failed, and the delivery is + complete. That is the same answer the single-agent path gives for an event no handler wanted. + + Args: + dispositions: What each dispatch of this delivery earned. + + Returns: + The disposition to report to the transport. + """ + outcomes = set(dispositions) + if DeliveryDisposition.NAK in outcomes: + return DeliveryDisposition.NAK + if DeliveryDisposition.ACK in outcomes or not outcomes: + return DeliveryDisposition.ACK + return DeliveryDisposition.TERM diff --git a/src/blueprint/agents/services/eventing/event_processing_service.py b/src/blueprint/agents/services/eventing/event_processing_service.py index 53ddfdc5..1a3f56e2 100644 --- a/src/blueprint/agents/services/eventing/event_processing_service.py +++ b/src/blueprint/agents/services/eventing/event_processing_service.py @@ -7,7 +7,8 @@ from opentelemetry import trace from ...component.component import traced -from ...handler.handler_chain import HandlerChain +from ...component.namespace import ROOT_LABEL, ROOT_NAMESPACE, namespace_of +from ...handler.handler_chain import RUNTIME_NAME_CONTEXT_KEY, HandlerChain from ...models import ProcessingResult, ProcessingStatus from ...models.events import GenericCloudEvent, HandlerResult, CloudEvent from ..service_base import ServiceBase @@ -22,26 +23,72 @@ class EventProcessingService(ServiceBase): This service provides a consistent interface for all API endpoints (REST, Events, Dapr) to process requests using the registered handlers and agent runtimes. + + One service, one chain per agent + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + There is a single instance of this service in a process, at the root, because what it does + -- correlation context, request ids, unwrapping, normalising handler output -- is the same + for every agent. What is *not* the same is the dispatch: which handlers an event is offered + to, which dedup policy applies, and which cache partition the markers go in. All three are + properties of a :class:`HandlerChain`, so the service keeps one chain per namespace and + every caller says which agent it is dispatching for. + + A caller that says nothing gets the root chain, which in a single-agent application is + every handler in the process. """ def __init__(self) -> None: super().__init__() - self._handler_chain: HandlerChain = HandlerChain() + # The root chain always exists, so an application that never mentions a namespace -- + # 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 async def on_startup(self) -> None: - """Start the handler chain. - - The chain is not a registered component, so nothing else calls its lifecycle - hooks. Its startup resolves the idempotency policy, and that has to happen while - the application is starting: a misconfigured dedup window must fail the pod, not - the first event that arrives on it. + """Start one handler chain per namespace that has handlers registered in it. + + The chains are not registered components, so nothing else calls their lifecycle hooks. + A chain's startup resolves its idempotency policy, and that has to happen while the + application is starting: a misconfigured dedup window must fail the pod, not the first + event that arrives on it. + + That guarantee is per agent, which is why the chains are built here rather than on first + delivery. Otherwise a group whose second agent has a bad ``idempotency_ttl`` would start + cleanly and fail on an event hours later, and the first agent's clean startup would have + said nothing about it. + + The namespaces come from the registered handlers, not from any list of agents. The + registry deliberately cannot enumerate agents (C6) and this service is not the builder; + what it needs is not "which agents exist" but "which namespaces have handlers to + dispatch to", and the handlers themselves are the authority on that. """ - await self._handler_chain.on_startup() + for namespace in sorted({namespace_of(handler) for handler in self.registry.get_event_handler()}): + self._chain_for(namespace) + + for namespace, chain in self._handler_chains.items(): + await chain.on_startup() + logger.debug("Handler chain for namespace '%s' started", namespace or ROOT_LABEL) async def on_shutdown(self) -> None: - """Stop the handler chain, for the same reason startup starts it.""" - await self._handler_chain.on_shutdown() + """Stop every handler chain, for the same reason startup starts them.""" + for chain in self._handler_chains.values(): + await chain.on_shutdown() + + def _chain_for(self, namespace: str) -> HandlerChain: + """Return the chain for ``namespace``, creating it if there is not one yet. + + Creation is lazy for a namespace that had no handler at startup. A chain is cheap, and + raising here would turn a handler registered after startup into a failed delivery + instead of a dispatch that finds nobody -- which is the outcome the acknowledgement + contract already has a disposition for. A chain created this way resolves its own dedup + policy on first use, which ``HandlerChain.process`` already does for exactly this case. + """ + chain = self._handler_chains.get(namespace) + if chain is None: + chain = HandlerChain(namespace=namespace) + self._handler_chains[namespace] = chain + logger.debug("Created a handler chain for namespace '%s'", namespace or ROOT_LABEL) + return chain @traced("event") async def process_event( @@ -50,14 +97,19 @@ async def process_event( context: dict[str, Any] | None = None, runtime_name: str | None = None, new_subject: str | None = None, + *, + namespace: str = ROOT_NAMESPACE, ) -> ProcessingResult: - """Process a CloudEvent through the handler chain. + """Process a CloudEvent through one agent's handler chain. Args: event: The CloudEvent to process context: Additional context for processing runtime_name: Specific runtime to use, or None for default new_subject: New subject for the CloudEvent + namespace: The agent this delivery belongs to. Keyword-only, because the four + parameters before it are passed positionally by existing callers. ``""`` is the + root, which is what every caller that does not know about agents gets. Returns: ProcessingResult describing the processing outcome @@ -69,6 +121,15 @@ async def process_event( context["request_id"] = request_id trace.get_current_span().set_attribute("request_id", request_id) + # The caller's choice of runtime, put where the chain will look for it. This + # parameter has existed since before there were agents to resolve and was only ever + # logged; the chain now treats it as a default, below the winning handler's own + # get_runtime_name() and above the single-runtime fallback. Only set when asked for, + # so a caller that passes nothing leaves the key absent rather than None -- which is + # the difference between "no preference" and "explicitly no runtime". + if runtime_name: + context[RUNTIME_NAME_CONTEXT_KEY] = runtime_name + correlation_token = self._correlation_context.set(getattr(event, "id", None) or request_id) logger.info( @@ -80,19 +141,25 @@ async def process_event( "event_source": event.source, "event_id": getattr(event, "id", None), "runtime_name": runtime_name, + "agent": namespace or ROOT_LABEL, }, ) event = self._unwrap_dapr_event(event) try: - handler_result: Any | HandlerResult | list[HandlerResult] | None = await self._handler_chain.process(event, context) + handler_result: Any | HandlerResult | list[HandlerResult] | None = await self._chain_for(namespace).process(event, context) handler_results: list[HandlerResult] = self._extract_handler_results(handler_result) for result in handler_results: if result.event_type: - await self.registry.get_component(EventPublishingService).publish_handler_event( + # This agent's publishing service, falling back to a root one. Not the + # 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) + await publisher.publish_handler_event( event_type=result.event_type, data=result.data, metadata=result.metadata or {}, @@ -120,6 +187,8 @@ async def process_rest_request( payload: dict[str, Any], context: dict[str, Any] | None = None, runtime_name: str | None = None, + *, + namespace: str = ROOT_NAMESPACE, ) -> ProcessingResult: """Process a REST request by converting it to a CloudEvent and processing. @@ -127,6 +196,8 @@ async def process_rest_request( payload: The REST request payload context: Additional context for processing runtime_name: Specific runtime to use, or None for default + namespace: The agent whose REST API received the request, so the synthesised event + is dispatched to that agent's handlers and no other's. Returns: ProcessingResult describing the processing outcome @@ -142,7 +213,7 @@ async def process_rest_request( data=payload, subject="rest.request", ) - return await self.process_event(event, context, runtime_name) + return await self.process_event(event, context, runtime_name, namespace=namespace) # ------------------------------------------------------------------ # Private helpers diff --git a/src/blueprint/agents/services/sessions/api_client.py b/src/blueprint/agents/services/sessions/api_client.py index d9c98632..b97a57a0 100644 --- a/src/blueprint/agents/services/sessions/api_client.py +++ b/src/blueprint/agents/services/sessions/api_client.py @@ -11,6 +11,7 @@ import httpx +from ...component.namespace import ROOT_NAMESPACE from ..service_base import ServiceBase logger = logging.getLogger(__name__) @@ -29,8 +30,15 @@ class SessionsApiClient(ServiceBase): api_key = "@format {env[SESSIONS_API_KEY]}" """ - def __init__(self) -> None: - super().__init__() + def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: + """Initialize the sessions API client for one agent. + + Args: + namespace: The agent this client belongs to; ``""`` is the root, which is the + whole of a single-agent application. Named by ``AppBuilder.build()``, which + creates one per agent using the sessions transport; a project never passes it. + """ + super().__init__(namespace=namespace) self._base_url: str | None = None self._api_key: str | None = None self._client: httpx.AsyncClient | None = None diff --git a/src/blueprint/agents/services/sessions/key_provider.py b/src/blueprint/agents/services/sessions/key_provider.py index 4721db6d..f565c9ee 100644 --- a/src/blueprint/agents/services/sessions/key_provider.py +++ b/src/blueprint/agents/services/sessions/key_provider.py @@ -13,6 +13,7 @@ from cachetools import TTLCache +from ...component.namespace import ROOT_NAMESPACE from ..service_base import ServiceBase logger = logging.getLogger(__name__) @@ -46,8 +47,15 @@ class SessionKeyProvider(ServiceBase): agent_id = "..." # required when session_key_source = "job" """ - def __init__(self) -> None: - super().__init__() + def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: + """Initialize the key provider for one agent. + + Args: + namespace: The agent this provider belongs to; ``""`` is the root, which is the + whole of a single-agent application. Named by ``AppBuilder.build()``, which + creates one per agent using the sessions transport; a project never passes it. + """ + super().__init__(namespace=namespace) self._cache: TTLCache[str, str] | None = None self._source: str = "env" self._env_var: str = "SESSION_KEY" diff --git a/tests/unit/agents/app_builder/conftest.py b/tests/unit/agents/app_builder/conftest.py index 2f8cdca7..8cbfc189 100644 --- a/tests/unit/agents/app_builder/conftest.py +++ b/tests/unit/agents/app_builder/conftest.py @@ -72,6 +72,9 @@ def build_config() -> MagicMock: """ config = MagicMock(spec=Config) config.get.return_value = "" # safe default for all config.get() calls + # build() reads per-agent keys through Config.for_namespace(); the mock stands in for + # both the loader and its views, as mock_config does, so a test controls one object. + config.for_namespace.return_value = config return config diff --git a/tests/unit/agents/app_builder/test_app_builder.py b/tests/unit/agents/app_builder/test_app_builder.py index a98c1430..e8aba902 100644 --- a/tests/unit/agents/app_builder/test_app_builder.py +++ b/tests/unit/agents/app_builder/test_app_builder.py @@ -345,9 +345,9 @@ def test_instantiates_three_sessions_components( builder_for_build.build() - all_build_mocks.sessions_api_client.assert_called_once_with() - all_build_mocks.session_key_provider.assert_called_once_with() - all_build_mocks.sessions_bus.assert_called_once_with() + all_build_mocks.sessions_api_client.assert_called_once_with(namespace="") + all_build_mocks.session_key_provider.assert_called_once_with(namespace="") + all_build_mocks.sessions_bus.assert_called_once_with(namespace="") all_build_mocks.dapr_client.assert_not_called() all_build_mocks.nats_client.assert_not_called() @@ -365,7 +365,7 @@ def test_sessions_bus_tracked_as_lifecycle_component( builder_for_build.build() - assert builder_for_build._eventing_component is None + assert builder_for_build._eventing_components == [] assert all_build_mocks.sessions_bus.return_value in builder_for_build._lifecycle_components def test_sessions_bus_router_never_mounted( @@ -416,7 +416,7 @@ def test_dapr_branch_still_wires_client_and_eventing( builder_for_build.build() - all_build_mocks.dapr_client.assert_called_once_with() + all_build_mocks.dapr_client.assert_called_once_with(namespace="") all_build_mocks.dapr_eventing.assert_called_once_with() all_build_mocks.sessions_bus.assert_not_called() @@ -447,8 +447,8 @@ def test_nats_branch_still_wires_client_and_eventing( builder_for_build.build() - all_build_mocks.nats_client.assert_called_once_with() - all_build_mocks.nats_eventing.assert_called_once_with() + all_build_mocks.nats_client.assert_called_once_with(namespace="") + all_build_mocks.nats_eventing.assert_called_once_with(namespace="") all_build_mocks.sessions_bus.assert_not_called() @@ -526,7 +526,8 @@ def test_event_mode_scheduler_is_wired_before_the_transport_decision( scheduler = MagicMock() mock_registry.get_schedulers.return_value = [scheduler] # The tick handler wire() registers is what makes get_event_handler() non-empty. - mock_registry.get_event_handler.side_effect = lambda: [MagicMock()] if scheduler.wire.called else [] + # build() now asks per namespace, so the stub takes the argument it is given. + mock_registry.get_event_handler.side_effect = lambda namespace=None: [MagicMock()] if scheduler.wire.called else [] self._config(build_config, event_bus="nats") builder_for_build.build() @@ -604,7 +605,7 @@ def test_opt_in_creates_a_client_but_subscribes_to_nothing( all_build_mocks.nats_eventing.assert_not_called() all_build_mocks.eps.assert_not_called() all_build_mocks.epubs.assert_called_once() - assert builder_for_build._eventing_component is None + assert builder_for_build._eventing_components == [] def test_opt_in_accepts_the_string_an_environment_variable_delivers( self, diff --git a/tests/unit/agents/app_builder/test_build_namespaces.py b/tests/unit/agents/app_builder/test_build_namespaces.py new file mode 100644 index 00000000..38ce6c83 --- /dev/null +++ b/tests/unit/agents/app_builder/test_build_namespaces.py @@ -0,0 +1,250 @@ +"""``build()`` wiring a transport per agent, against real components. + +Three decisions are being pinned down. Which agents get a client -- one per agent that consumes +or publishes, and none for an agent that does neither (spec sec. 6). Which get an endpoint -- +one per agent that consumes, so each subscribes on its own behalf (spec sec. 7.6). And that a +single-agent application still gets exactly one of each, at the root. +""" + +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock, patch + +import pytest + +from blueprint.agents.app_builder import AgentRegistration, AppBuilder +from blueprint.agents.clients.io.nats_client import NATSClient +from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import ROOT_NAMESPACE +from blueprint.agents.config import Config +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.io.api.eventing.nats import NatsEventing +from blueprint.agents.models.events import GenericCloudEvent +from blueprint.agents.services.eventing.event_publishing_service import EventPublishingService +from blueprint.agents.services.service_base import ServiceBase + + +class OrderHandler(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return ["orders.created"] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict) -> Any: + return None + + +class BillingHandler(OrderHandler): + def get_subscribed_topics(self) -> list[str]: + return ["invoices.raised"] + + +class QuietService(ServiceBase): + """A service, so an agent can exist without consuming or publishing anything.""" + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +def settings(tmp_path: Path, body: str) -> Config: + path = tmp_path / "settings.toml" + path.write_text(body.replace("\n ", "\n")) + return Config(settings_files=[str(path)], root_path=str(tmp_path)) + + +@pytest.fixture +def nats_config(tmp_path: Path) -> Config: + """A root and two agents on NATS, with publishing opted into by one agent only.""" + return settings( + tmp_path, + """ + [development] + app_name = "root-app" + app_port = 8000 + event_bus = "nats" + + [development.orders] + app_name = "orders" + + [development.billing] + app_name = "billing" + + [development.reporting] + app_name = "reporting" + event_publishing_enabled = true + """, + ) + + +def registry_names(component_type: Any) -> list[str]: + registry = Component.shared_registry + assert registry is not None + return sorted(registry.get_component_names_by_type(component_type)) + + +def build(builder: AppBuilder) -> None: + """Run build() with the FastAPI app construction stubbed out.""" + with patch("blueprint.agents.app_builder.FastAPI"): + builder.build() + + +class TestOneClientPerConsumingAgent: + def test_each_agent_gets_its_own_client(self, nats_config: Config) -> None: + builder = AppBuilder(nats_config) + builder.with_namespace("orders", registration=AgentRegistration().with_handler(OrderHandler)) + builder.with_namespace("billing", registration=AgentRegistration().with_handler(BillingHandler)) + + build(builder) + + assert registry_names(NATSClient) == ["billing_nats_client", "orders_nats_client"] + + def test_a_single_agent_application_gets_one_client_at_the_root(self, nats_config: Config) -> None: + builder = AppBuilder(nats_config).with_handler(OrderHandler) + + build(builder) + + assert registry_names(NATSClient) == ["nats_client"] + + def test_the_root_gets_no_client_when_it_has_nothing(self, nats_config: Config) -> None: + """A grouped application usually has nothing at the root, and then the root pass is a no-op.""" + builder = AppBuilder(nats_config) + builder.with_namespace("orders", registration=AgentRegistration().with_handler(OrderHandler)) + + build(builder) + + assert registry_names(NATSClient) == ["orders_nats_client"] + + def test_an_agent_that_neither_consumes_nor_publishes_gets_no_client(self, nats_config: Config) -> None: + """Spec sec. 6: a connection for it is a readiness dependency on traffic that does not exist.""" + builder = AppBuilder(nats_config) + builder.with_namespace("orders", registration=AgentRegistration().with_handler(OrderHandler)) + builder.with_namespace("billing", registration=AgentRegistration().with_service(QuietService)) + + build(builder) + + assert registry_names(NATSClient) == ["orders_nats_client"] + + def test_a_publish_only_agent_gets_a_client_and_no_endpoint(self, nats_config: Config) -> None: + builder = AppBuilder(nats_config) + builder.with_namespace("reporting", registration=AgentRegistration().with_service(QuietService)) + + build(builder) + + assert registry_names(NATSClient) == ["reporting_nats_client"] + assert builder._eventing_components == [] + + def test_publishing_is_opted_into_per_agent(self, nats_config: Config) -> None: + """C5: 'reporting.event_publishing_enabled' is on, and its neighbour's is not.""" + builder = AppBuilder(nats_config) + + assert builder._publishing_requested("reporting") is True + assert builder._publishing_requested("billing") is False + assert builder._publishing_requested(ROOT_NAMESPACE) is False + + +class TestOneEndpointPerConsumingAgent: + def test_each_consuming_agent_gets_an_endpoint(self, nats_config: Config) -> None: + builder = AppBuilder(nats_config) + builder.with_namespace("orders", registration=AgentRegistration().with_handler(OrderHandler)) + builder.with_namespace("billing", registration=AgentRegistration().with_handler(BillingHandler)) + + build(builder) + + assert sorted(component.namespace for component in builder._eventing_components) == ["billing", "orders"] + + def test_a_single_agent_application_gets_one_at_the_root(self, nats_config: Config) -> None: + builder = AppBuilder(nats_config).with_handler(OrderHandler) + + build(builder) + + assert [component.namespace for component in builder._eventing_components] == [ROOT_NAMESPACE] + assert isinstance(builder._eventing_components[0], NatsEventing) + + def test_an_application_with_no_handler_gets_none(self, nats_config: Config) -> None: + build(AppBuilder(nats_config).with_service(QuietService)) + + assert Component.shared_registry is not None + assert registry_names(NATSClient) == [] + + async def test_each_endpoint_subscribes_only_its_own_topics(self, nats_config: Config) -> None: + builder = AppBuilder(nats_config) + builder.with_namespace("orders", registration=AgentRegistration().with_handler(OrderHandler)) + builder.with_namespace("billing", registration=AgentRegistration().with_handler(BillingHandler)) + build(builder) + + with patch.object(NATSClient, "subscribe", new_callable=AsyncMock) as subscribe: + for component in builder._eventing_components: + await component.on_startup() + + subscribed = [sorted(call[0][0]) for call in subscribe.call_args_list] + assert subscribed == [["orders.created"], ["invoices.raised"]] + + +class TestOnePublishingServicePerAgentWithAClient: + def test_each_agent_with_a_client_gets_one(self, nats_config: Config) -> None: + builder = AppBuilder(nats_config) + builder.with_namespace("orders", registration=AgentRegistration().with_handler(OrderHandler)) + builder.with_namespace("billing", registration=AgentRegistration().with_handler(BillingHandler)) + + build(builder) + + assert registry_names(EventPublishingService) == [ + "billing_event_publishing_service", + "orders_event_publishing_service", + ] + + def test_a_single_agent_application_gets_one_at_the_root(self, nats_config: Config) -> None: + build(AppBuilder(nats_config).with_handler(OrderHandler)) + + assert registry_names(EventPublishingService) == ["event_publishing_service"] + + def test_an_agent_without_a_client_gets_none(self, nats_config: Config) -> None: + builder = AppBuilder(nats_config) + builder.with_namespace("orders", registration=AgentRegistration().with_handler(OrderHandler)) + builder.with_namespace("billing", registration=AgentRegistration().with_service(QuietService)) + + build(builder) + + assert registry_names(EventPublishingService) == ["orders_event_publishing_service"] + + +class TestHostedNamespaces: + def test_a_single_agent_application_hosts_the_root_only(self, nats_config: Config) -> None: + assert AppBuilder(nats_config).hosted_namespaces == (ROOT_NAMESPACE,) + + def test_the_root_comes_first_and_the_agents_in_order(self, nats_config: Config) -> None: + builder = AppBuilder(nats_config) + builder.with_namespace("orders").end().with_namespace("billing").end() + + assert builder.hosted_namespaces == (ROOT_NAMESPACE, "orders", "billing") + + +class TestPublishOptInWithoutATransport: + def test_it_names_the_agent_that_asked(self, tmp_path: Path) -> None: + config = settings( + tmp_path, + """ + [development] + app_name = "root-app" + app_port = 8000 + + [development.reporting] + app_name = "reporting" + event_publishing_enabled = true + """.replace("\n ", "\n "), + ) + builder = AppBuilder(config) + builder.with_namespace("reporting", registration=AgentRegistration().with_service(QuietService)) + + with pytest.raises(ValueError, match="'reporting'"): + build(builder) diff --git a/tests/unit/agents/app_builder/test_named_caches.py b/tests/unit/agents/app_builder/test_named_caches.py index 83460b42..6eae3517 100644 --- a/tests/unit/agents/app_builder/test_named_caches.py +++ b/tests/unit/agents/app_builder/test_named_caches.py @@ -11,7 +11,7 @@ """ from pathlib import Path -from unittest.mock import MagicMock +from unittest.mock import MagicMock, patch import pytest @@ -38,6 +38,10 @@ def builder(cache_dir: Path) -> AppBuilder: """ config = MagicMock(spec=Config) config.get_cache_config.return_value = CacheConfig(cache_dir=str(cache_dir), backend="disk") + config.get.return_value = "" + # build() reads per-agent keys through Config.for_namespace(); the mock stands in for + # both the loader and its views, so a test controls one object. + config.for_namespace.return_value = config return AppBuilder(config) @@ -153,3 +157,43 @@ def test_nothing_is_registered_when_the_name_is_refused(self, builder: AppBuilde with pytest.raises(ValueError): builder.with_cache(name="../evil") assert Component.shared_registry is None or not Component.shared_registry.get_all_caches() + + +class TestEveryCacheReachesReadiness: + """A named cache is a real backend; one that nothing probes is an outage nobody is told about.""" + + def test_the_default_cache_keeps_the_entry_name_it_has_always_had(self, builder: AppBuilder) -> None: + builder.with_cache() + + with patch("blueprint.agents.app_builder.FastAPI"): + builder.build() + + assert "cache" in builder._actuator_api._pending_providers # type: ignore[union-attr] + + def test_a_named_cache_gets_its_own_entry(self, builder: AppBuilder) -> None: + builder.with_cache().with_cache(name="sessions") + + with patch("blueprint.agents.app_builder.FastAPI"): + builder.build() + + providers = builder._actuator_api._pending_providers # type: ignore[union-attr] + assert {"cache", "cache:sessions"} <= set(providers) + + def test_a_named_cache_alone_still_reaches_readiness(self, builder: AppBuilder) -> None: + """Previously the probe was keyed on the default name, so this cache went unprobed.""" + builder.with_cache(name="sessions") + + with patch("blueprint.agents.app_builder.FastAPI"): + builder.build() + + assert "cache:sessions" in builder._actuator_api._pending_providers # type: ignore[union-attr] + + def test_each_entry_probes_its_own_cache(self, builder: AppBuilder) -> None: + builder.with_cache().with_cache(name="sessions") + + with patch("blueprint.agents.app_builder.FastAPI"): + builder.build() + + providers = builder._actuator_api._pending_providers # type: ignore[union-attr] + assert providers["cache"]._cache is registry().get_cache() + assert providers["cache:sessions"]._cache is registry().get_cache("sessions") diff --git a/tests/unit/agents/app_builder/test_route_namespacing.py b/tests/unit/agents/app_builder/test_route_namespacing.py new file mode 100644 index 00000000..9cdd0e2b --- /dev/null +++ b/tests/unit/agents/app_builder/test_route_namespacing.py @@ -0,0 +1,208 @@ +"""Where an agent's HTTP routes are mounted, and how they are tagged. + +The problem: a group applies the same registration once per agent, so two agents declare the +same paths. Without a per-agent prefix FastAPI serves the first match and one agent's requests +are silently answered by another agent's code. The constraint alongside it is that a single-agent +application's paths must not move at all. + +Assertions go through ``app.openapi()`` rather than ``app.routes``, because FastAPI stores an +included router as one opaque entry rather than flattening its routes into the app -- so +``app.routes`` does not contain the paths being tested, while the OpenAPI document is exactly +what the application serves. +""" + +from pathlib import Path +from typing import Any + +import pytest +from fastapi import FastAPI + +from blueprint.agents.app_builder import AgentRegistration, AppBuilder +from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import namespace_scope +from blueprint.agents.config import Config +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.io.api.eventing.dapr import DaprEventing +from blueprint.agents.io.api.rest_api_base import RestApiBase +from blueprint.agents.models.events import GenericCloudEvent + + +class OrderApi(RestApiBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + @RestApiBase.get("/orders", tags=["orders"]) + async def list_orders(self) -> list[str]: + return [] + + +class OrderHandler(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return ["orders.created"] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict) -> Any: + return None + + +@pytest.fixture +def dapr_config(tmp_path: Path) -> Config: + settings = tmp_path / "settings.toml" + settings.write_text( + '[development]\napp_name = "root-app"\napp_port = 8000\nevent_bus = "dapr"\n\n' + '[development.orders]\napp_name = "orders"\n\n' + '[development.billing]\napp_name = "billing"\n' + ) + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + +@pytest.fixture +def nats_config(tmp_path: Path) -> Config: + """The same tree on NATS, for the cases that host more than one consuming agent. + + Dapr cannot host a group of consumers yet -- the sidecar fetches the subscription document + from one fixed path -- and ``build()`` refuses it rather than starting a pod that subscribes + to nothing. See ``TestGroupedDaprIsRefused``. + """ + settings = tmp_path / "settings.toml" + settings.write_text( + '[development]\napp_name = "root-app"\napp_port = 8000\nevent_bus = "nats"\n\n' + '[development.orders]\napp_name = "orders"\n\n' + '[development.billing]\napp_name = "billing"\n' + ) + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + +def paths(app: FastAPI) -> list[str]: + return sorted(app.openapi()["paths"]) + + +def tags_for(app: FastAPI, path: str) -> list[str]: + operations = app.openapi()["paths"][path] + return sorted({tag for operation in operations.values() for tag in operation.get("tags", [])}) + + +class TestRoutePrefix: + def test_a_root_component_has_no_prefix(self, dapr_config: Config) -> None: + Component.configure(dapr_config) + assert OrderApi().route_prefix == "" + + def test_an_agents_component_is_prefixed_with_its_name(self, dapr_config: Config) -> None: + Component.configure(dapr_config) + with namespace_scope("orders"): + api = OrderApi() + assert api.route_prefix == "/api/orders" + + def test_the_dapr_endpoint_is_always_the_root_one(self, dapr_config: Config) -> None: + """It takes no namespace at all: Dapr's paths are fixed, so there is one endpoint.""" + Component.configure(dapr_config) + assert DaprEventing().route_prefix == "" + + +class TestRestRoutesMoveUnderTheAgent: + def test_a_single_agent_applications_paths_do_not_move(self, dapr_config: Config) -> None: + app = AppBuilder(dapr_config).with_rest_api(OrderApi).build() + + assert "/api/orders" in paths(app) + + def test_an_agents_route_carries_its_namespace(self, dapr_config: Config) -> None: + builder = AppBuilder(dapr_config) + builder.with_namespace("orders", registration=AgentRegistration().with_rest_api(OrderApi)) + + app = builder.build() + + assert "/api/orders/orders" in paths(app) + + def test_two_agents_declaring_one_route_do_not_collide(self, dapr_config: Config) -> None: + """The failure without a prefix: FastAPI serves the first match for both agents.""" + registration = AgentRegistration().with_rest_api(OrderApi) + builder = AppBuilder(dapr_config) + builder.with_namespace("orders", registration=registration) + builder.with_namespace("billing", registration=registration) + + app = builder.build() + + assert {"/api/orders/orders", "/api/billing/orders"} <= set(paths(app)) + + +class TestTags: + def test_an_agents_tags_are_prefixed(self, dapr_config: Config) -> None: + builder = AppBuilder(dapr_config) + builder.with_namespace("orders", registration=AgentRegistration().with_rest_api(OrderApi)) + + app = builder.build() + + assert tags_for(app, "/api/orders/orders") == ["orders.orders"] + + def test_the_bare_tag_is_replaced_rather_than_added_to(self, dapr_config: Config) -> None: + """Appending would put the operation in two Swagger groups instead of one.""" + builder = AppBuilder(dapr_config) + builder.with_namespace("orders", registration=AgentRegistration().with_rest_api(OrderApi)) + + app = builder.build() + + assert "orders" not in tags_for(app, "/api/orders/orders") + + def test_two_agents_tags_do_not_merge(self, dapr_config: Config) -> None: + registration = AgentRegistration().with_rest_api(OrderApi) + builder = AppBuilder(dapr_config) + builder.with_namespace("orders", registration=registration) + builder.with_namespace("billing", registration=registration) + + app = builder.build() + + assert tags_for(app, "/api/orders/orders") == ["orders.orders"] + assert tags_for(app, "/api/billing/orders") == ["billing.orders"] + + def test_a_root_components_tags_are_untouched(self, dapr_config: Config) -> None: + app = AppBuilder(dapr_config).with_rest_api(OrderApi).build() + + assert tags_for(app, "/api/orders") == ["orders"] + + +class TestEventingRoutes: + def test_a_root_delivery_path_is_unchanged(self, dapr_config: Config) -> None: + """A sidecar posting to /events/{topic} keeps working for every existing deployment.""" + app = AppBuilder(dapr_config).with_handler(OrderHandler).build() + + assert "/events/{topic}" in paths(app) + + def test_the_dapr_delivery_path_never_moves(self, dapr_config: Config) -> None: + """Dapr's two paths are fixed by its protocol, so its endpoint stays at the root.""" + builder = AppBuilder(dapr_config) + builder.with_namespace("orders", registration=AgentRegistration().with_handler(OrderHandler)) + + app = builder.build() + + assert {"/events/{topic}", "/dapr/subscribe"} <= set(paths(app)) + assert "/api/orders/events/{topic}" not in paths(app) + + def test_two_agents_get_their_own_nats_delivery_paths(self, nats_config: Config) -> None: + """Unprefixed, FastAPI would serve one agent's endpoint for both agents' deliveries.""" + registration = AgentRegistration().with_handler(OrderHandler) + builder = AppBuilder(nats_config) + builder.with_namespace("orders", registration=registration) + builder.with_namespace("billing", registration=registration) + + app = builder.build() + + assert {"/api/orders/events/{topic}", "/api/billing/events/{topic}"} <= set(paths(app)) + + async def test_a_root_document_is_unchanged(self, dapr_config: Config) -> None: + Component.configure(dapr_config) + OrderHandler() + + document = await DaprEventing().subscribe() + + assert document == [{"pubsubname": "pubsub", "topic": "orders.created", "route": "/events/orders.created"}] diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index 9954edf9..6d1535f3 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -1363,6 +1363,85 @@ async def test_configured_durable_under_a_namespace_warns(self, mock_config: Mag assert "consume each other" in caplog.text +class TestConsumerIdentityIgnoresTheDeployment: + """C1 -- regrouping must be invisible to the broker, so no deployment value may reach it. + + The two broker-side identifiers are the queue group and the durable name, and both derive + from the namespace alone. A deployment identifier reaching either would make regrouping + observable: a durable that picked up the group name becomes a *different* durable when the + agent moves group, and a fresh consumer resumes according to its delivery policy -- so the + agent either replays the stream from the start or silently skips whatever arrived while it + was being renamed. This is the invariant the plan asks to be covered by a test, and it is + why the connection name -- which does carry the group and the pod -- is kept away from both. + + Each case derives the two identifiers, changes the deployment, and derives them again from + the same client, so what is asserted is the derivation rather than a cached value. + """ + + @staticmethod + def _identities(client: NATSClient) -> tuple[str, str]: + return client._resolve_queue_group(), client._durable_for("orders.created") + + def test_the_group_name_reaches_neither(self, mock_config: MagicMock, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("BLUEPRINT_GROUP", "group-a") + monkeypatch.setenv("POD_NAME", "pod-1") + client = _namespaced_client(mock_config, "orders") + before = self._identities(client) + + monkeypatch.setenv("BLUEPRINT_GROUP", "group-b") + + assert self._identities(client) == before == ("orders", "orders-orders_created-durable") + + def test_the_pod_name_reaches_neither(self, mock_config: MagicMock, monkeypatch: pytest.MonkeyPatch) -> None: + """A pod name in a durable would mean a new consumer on every restart.""" + monkeypatch.setenv("BLUEPRINT_GROUP", "group-a") + monkeypatch.setenv("POD_NAME", "pod-1") + client = _namespaced_client(mock_config, "orders") + before = self._identities(client) + + monkeypatch.setenv("POD_NAME", "pod-2") + + assert self._identities(client) == before + + def test_the_connection_name_changes_while_they_do_not(self, mock_config: MagicMock, monkeypatch: pytest.MonkeyPatch) -> None: + """The positive half: the deployment is visible, but only where attribution needs it.""" + monkeypatch.setenv("BLUEPRINT_GROUP", "group-a") + monkeypatch.setenv("POD_NAME", "pod-1") + client = _namespaced_client(mock_config, "orders") + identities, connection = self._identities(client), client._resolve_connection_name() + + monkeypatch.setenv("BLUEPRINT_GROUP", "group-b") + monkeypatch.setenv("POD_NAME", "pod-2") + + assert client._resolve_connection_name() != connection + assert self._identities(client) == identities + + async def test_the_consumer_carries_the_namespace_and_not_the_deployment( + self, mock_config: MagicMock, monkeypatch: pytest.MonkeyPatch + ) -> None: + """One durable per (namespace, topic), filtering that one subject. + + This is also what makes the plan's per-namespace ``filter_subjects`` set unnecessary: a + filter set that followed the handler list would be rewritten whenever a handler was + added, and a durable's filter is broker-side state that cannot be rewritten without + replaying or gapping. Here the filter is one subject and never changes. + """ + monkeypatch.setenv("BLUEPRINT_GROUP", "group-a") + monkeypatch.setenv("POD_NAME", "pod-1") + client = _namespaced_client(mock_config, "orders") + with patch.object(client, "_start_with_retry", new_callable=AsyncMock): + await client.subscribe({"orders.created": AsyncMock()}) + + config = client._consumer_config("orders.created", client._durable_for("orders.created")) + + assert (config.durable_name, config.filter_subject, config.deliver_group) == ( + "orders-orders_created-durable", + "orders.created", + "orders", + ) + assert "group-a" not in str(config) and "pod-1" not in str(config) + + class TestNATSClientConnectionName: """Reason 3 -- attribution. nats.connect() used to be called with no name at all.""" diff --git a/tests/unit/agents/handler/test_dispatch_index.py b/tests/unit/agents/handler/test_dispatch_index.py new file mode 100644 index 00000000..ede6a2ce --- /dev/null +++ b/tests/unit/agents/handler/test_dispatch_index.py @@ -0,0 +1,297 @@ +"""Unit tests for the dispatch index (spec sec. 7.7). + +The index is an optimisation with one hard requirement attached: it must not change which +handler processes an event. So most of these compare the indexed behaviour against the +behaviour of a handler set that declares nothing -- which is every handler that exists in this +framework or in any project scaffolded from it. +""" + +from pathlib import Path +from typing import Any + +import pytest + +from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import namespace_scope +from blueprint.agents.config import Config +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.handler.handler_chain import DispatchIndex, HandlerChain +from blueprint.agents.models.events import GenericCloudEvent + +CALLS: list[str] = [] +"""Which handlers were asked, in order. Reset by the ``calls`` fixture.""" + + +class RecordingHandler(EventHandlerBase): + """Records that it was asked, and handles whatever it is asked about.""" + + DECLARES: list[str] = [] + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_handled_event_types(self) -> list[str]: + return list(self.DECLARES) + + async def can_handle_event(self, event: GenericCloudEvent, context: dict) -> bool: + CALLS.append(self.name) + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict) -> Any: + return {"handled_by": self.name} + + +class UndeclaredHandler(RecordingHandler): + """The shape of every handler that exists today: it selects in can_handle_event only.""" + + +class OrderHandler(RecordingHandler): + DECLARES = ["order.created"] + + +class InvoiceHandler(RecordingHandler): + DECLARES = ["invoice.raised", "invoice.paid"] + + +class PassingHandler(RecordingHandler): + """Declares an event type, is asked, says yes, and then returns None from handle.""" + + DECLARES = ["order.created"] + + async def handle_event(self, event: GenericCloudEvent, context: dict) -> Any: + return None + + +class PatternHandler(RecordingHandler): + DECLARES = ["order.*"] + + +class BlankHandler(RecordingHandler): + DECLARES = [" "] + + +@pytest.fixture(autouse=True) +def calls() -> list[str]: + CALLS.clear() + return CALLS + + +@pytest.fixture +def config(tmp_path: Path) -> Config: + settings = tmp_path / "settings.toml" + settings.write_text('[development]\napp_name = "indexed"\napp_port = 8000\n') + loaded = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + Component.configure(loaded) + return loaded + + +def event(event_type: str) -> GenericCloudEvent: + return GenericCloudEvent.model_construct(id="evt-1", type=event_type, source="/tests") + + +class TestUndeclaredHandlersAreAlwaysCandidates: + def test_a_handler_that_declares_nothing_is_a_candidate_for_everything(self, config: Config) -> None: + """The requirement the whole design turns on: an empty declaration is not an empty set.""" + handler = UndeclaredHandler() + index = DispatchIndex.build((handler,)) + + assert index.candidates("anything.at.all") == (handler,) + + def test_it_is_a_candidate_alongside_a_declared_handler(self, config: Config) -> None: + undeclared, orders = UndeclaredHandler(), OrderHandler() + index = DispatchIndex.build((undeclared, orders)) + + assert index.candidates("order.created") == (undeclared, orders) + + def test_an_undeclared_only_application_indexes_to_nothing(self, config: Config) -> None: + """Today's every application: no event type is keyed, and everyone is asked.""" + index = DispatchIndex.build((UndeclaredHandler(),)) + + assert index.by_type == {} + assert len(index.wildcard) == 1 + + +class TestDeclarationsNarrowWhoIsAsked: + def test_a_declared_handler_is_not_a_candidate_for_another_type(self, config: Config) -> None: + orders, invoices = OrderHandler(), InvoiceHandler() + index = DispatchIndex.build((orders, invoices)) + + assert index.candidates("order.created") == (orders,) + + def test_every_declared_type_is_keyed(self, config: Config) -> None: + index = DispatchIndex.build((InvoiceHandler(),)) + + assert sorted(index.by_type) == ["invoice.paid", "invoice.raised"] + + def test_an_undeclared_type_falls_back_to_the_wildcard_handlers(self, config: Config) -> None: + undeclared, orders = UndeclaredHandler(), OrderHandler() + index = DispatchIndex.build((undeclared, orders)) + + assert index.candidates("something.else") == (undeclared,) + + def test_an_undeclared_type_with_no_wildcard_handler_has_no_candidates(self, config: Config) -> None: + index = DispatchIndex.build((OrderHandler(),)) + + assert index.candidates("something.else") == () + + +class TestOrderIsPreserved: + def test_candidates_keep_the_order_they_were_given(self, config: Config) -> None: + """Built by filtering the priority-sorted list, not by concatenating buckets. + + Concatenating would put declared handlers ahead of undeclared ones of equal priority, + and equal priority is currently resolved by registration order. + """ + first = UndeclaredHandler() + first.name = "first" # two instances of one class would collide on the derived name + second = OrderHandler() + third = UndeclaredHandler() + index = DispatchIndex.build((first, second, third)) + + assert index.candidates("order.created") == (first, second, third) + + def test_priority_still_decides(self, config: Config) -> None: + low, high = OrderHandler(priority=10), UndeclaredHandler(priority=1) + chain = HandlerChain() + + assert chain._handlers() == (high, low) + + +class TestDispatchThroughTheIndex: + async def test_only_the_candidates_are_asked(self, config: Config) -> None: + OrderHandler() + InvoiceHandler() + chain = HandlerChain() + + await chain.process(event("order.created"), {}) + + assert CALLS == ["order_handler"] + + async def test_the_undeclared_handler_is_asked_too(self, config: Config) -> None: + UndeclaredHandler() + OrderHandler() + chain = HandlerChain() + + await chain.process(event("order.created"), {}) + + assert CALLS == ["undeclared_handler"] # first candidate returns a result, chain stops + + async def test_a_handler_declaring_nothing_still_receives_an_unknown_type(self, config: Config) -> None: + UndeclaredHandler() + OrderHandler() + chain = HandlerChain() + + result = await chain.process(event("nobody.declared.this"), {}) + + assert (CALLS, result) == (["undeclared_handler"], {"handled_by": "undeclared_handler"}) + + async def test_the_fallthrough_is_preserved(self, config: Config) -> None: + """A candidate whose handle returns None still passes the event to the next.""" + PassingHandler(priority=1) + OrderHandler(priority=2) + chain = HandlerChain() + + result = await chain.process(event("order.created"), {}) + + assert CALLS == ["passing_handler", "order_handler"] + assert result == {"handled_by": "order_handler"} + + async def test_an_event_no_candidate_wants_returns_none(self, config: Config) -> None: + OrderHandler() + chain = HandlerChain() + + assert await chain.process(event("invoice.paid"), {}) is None + assert CALLS == [] + + +class TestMalformedDeclarations: + def test_a_pattern_is_refused(self, config: Config) -> None: + """Matched by equality, so 'order.*' would be a handler that never runs.""" + with pytest.raises(ValueError, match="looks like a pattern"): + DispatchIndex.build((PatternHandler(),)) + + def test_the_refusal_names_the_handler_and_the_declaration(self, config: Config) -> None: + with pytest.raises(ValueError, match=r"'pattern_handler'.*'order\.\*'"): + DispatchIndex.build((PatternHandler(),)) + + def test_a_blank_declaration_is_refused(self, config: Config) -> None: + with pytest.raises(ValueError, match="empty event type"): + DispatchIndex.build((BlankHandler(),)) + + async def test_it_fails_at_startup_not_at_a_delivery(self, config: Config) -> None: + PatternHandler() + chain = HandlerChain() + + with pytest.raises(ValueError, match="looks like a pattern"): + await chain.on_startup() + + +class TestIndexLifecycle: + async def test_the_index_is_built_at_startup(self, config: Config) -> None: + OrderHandler() + chain = HandlerChain() + + await chain.on_startup() + + assert chain._index is not None + + async def test_a_handler_registered_after_startup_is_still_asked(self, config: Config) -> None: + """Before the index the chain queried the registry per event and picked this up. + + Losing that silently is the failure this design is most careful about, so the index is + rebuilt when the registered handlers change. + """ + OrderHandler() + chain = HandlerChain() + await chain.on_startup() + + UndeclaredHandler() + await chain.process(event("late.arrival"), {}) + + assert CALLS == ["undeclared_handler"] + + async def test_the_index_is_not_rebuilt_when_nothing_changed(self, config: Config) -> None: + OrderHandler() + chain = HandlerChain() + await chain.on_startup() + built = chain._index + + await chain.process(event("order.created"), {}) + + assert chain._index is built + + async def test_a_chain_used_without_startup_still_indexes(self, config: Config) -> None: + """The chain is not a registered component, so a caller outside AppBuilder never starts it.""" + OrderHandler() + chain = HandlerChain() + + await chain.process(event("order.created"), {}) + + assert CALLS == ["order_handler"] + + +class TestPerAgentIndexes: + async def test_each_agent_indexes_only_its_own_handlers(self, config: Config) -> None: + with namespace_scope("orders"): + OrderHandler() + with namespace_scope("billing"): + InvoiceHandler() + + orders_chain = HandlerChain(namespace="orders") + await orders_chain.on_startup() + + assert sorted(orders_chain._index.by_type) == ["order.created"] # type: ignore[union-attr] + + async def test_one_agents_declaration_does_not_reach_another(self, config: Config) -> None: + with namespace_scope("orders"): + OrderHandler() + with namespace_scope("billing"): + UndeclaredHandler() + + billing_chain = HandlerChain(namespace="billing") + await billing_chain.process(event("order.created"), {}) + + assert CALLS == ["billing_undeclared_handler"] diff --git a/tests/unit/agents/handler/test_runtime_binding.py b/tests/unit/agents/handler/test_runtime_binding.py new file mode 100644 index 00000000..2b8581cb --- /dev/null +++ b/tests/unit/agents/handler/test_runtime_binding.py @@ -0,0 +1,296 @@ +"""Binding a handler to an agent runtime (plan phase 7). + +The runtime is resolved between ``can_handle`` saying yes and ``handle`` running, and put in the +context the handler is about to be given. That timing is the whole point: it is the only moment +at which the winner is known *and* the answer can still be used. + +Three sources, most explicit first -- the handler's own ``get_runtime_name``, the ``runtime_name`` +a caller passed to ``process_event``, then the single runtime in the handler's namespace. What is +deliberately *not* here is a failure when several runtimes exist and nothing was declared; see +``TestAmbiguity``. +""" + +from pathlib import Path +from typing import Any + +import pytest + +from blueprint.agents.agent.agent_runtime import AgentRuntime +from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import namespace_scope, qualified_component_name +from blueprint.agents.config import Config +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.handler.handler_chain import RUNTIME_CONTEXT_KEY, RUNTIME_NAME_CONTEXT_KEY, HandlerChain +from blueprint.agents.models.events import GenericCloudEvent +from blueprint.agents.services.eventing.event_processing_service import EventProcessingService + +SEEN: list[dict[str, Any]] = [] +"""The context each handler was given, so the binding can be inspected after the fact.""" + + +class RecordingHandler(EventHandlerBase): + """Records the context it was handed, which is where the runtime is bound.""" + + RUNTIME: str | None = None + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_runtime_name(self, event: GenericCloudEvent, context: dict[str, Any]) -> str | None: + return self.RUNTIME + + async def can_handle_event(self, event: GenericCloudEvent, context: dict) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict) -> Any: + SEEN.append(dict(context)) + return {"ok": True} + + +class UndeclaredHandler(RecordingHandler): + """The shape of every handler that exists today: it declares no runtime.""" + + +class FastHandler(RecordingHandler): + RUNTIME = "fast" + + +class MissingRuntimeHandler(RecordingHandler): + RUNTIME = "nope" + + +class PayloadRoutingHandler(RecordingHandler): + """The case get_runtime_name exists for: the choice depends on the event.""" + + async def handle_event(self, event: GenericCloudEvent, context: dict) -> Any: + SEEN.append(dict(context)) + return {"ok": True} + + def get_runtime_name(self, event: GenericCloudEvent, context: dict[str, Any]) -> str | None: + return "thorough" if (event.data or {}).get("priority") == "high" else "fast" + + +@pytest.fixture(autouse=True) +def seen() -> list[dict[str, Any]]: + SEEN.clear() + return SEEN + + +@pytest.fixture +def config(tmp_path: Path) -> Config: + settings = tmp_path / "settings.toml" + settings.write_text( + '[development]\napp_name = "root-app"\napp_port = 8000\nai_model_provider = "vllm"\n' + 'ai_model_name = "test"\nai_model_api_key = "k"\nai_model_base_url = "http://localhost"\n\n' + '[development.orders]\napp_name = "orders"\n\n' + '[development.billing]\napp_name = "billing"\n' + ) + loaded = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + Component.configure(loaded) + return loaded + + +def runtime(name: str, namespace: str = "") -> AgentRuntime: + """Register an agent runtime under ``name``, in ``namespace``. + + The name is qualified the way ``AppBuilder._register`` qualifies one, because an explicit + ``name=`` reaches ``Component`` verbatim: two agents called ``planner`` in two namespaces + would otherwise collide on the one registry key. Constructing the component directly, as + this helper does, bypasses the builder that normally does the qualifying. + """ + with namespace_scope(namespace): + agent = AgentRuntime(model="test", name=qualified_component_name(namespace, name)) + return agent + + +def event(priority: str | None = None) -> GenericCloudEvent: + data = {"priority": priority} if priority else {} + return GenericCloudEvent.model_construct(id="evt-1", type="test.event", source="/tests", data=data) + + +class TestTheHandlersOwnChoice: + async def test_a_declared_runtime_is_bound(self, config: Config) -> None: + fast = runtime("fast") + runtime("thorough") + FastHandler() + + await HandlerChain().process(event(), {}) + + assert SEEN[0][RUNTIME_NAME_CONTEXT_KEY] == "fast" + assert SEEN[0][RUNTIME_CONTEXT_KEY] is fast + + async def test_it_is_bound_before_the_handler_runs(self, config: Config) -> None: + """The handler reads it from the context it is given, not from a later return value.""" + runtime("fast") + FastHandler() + + await HandlerChain().process(event(), {}) + + assert RUNTIME_CONTEXT_KEY in SEEN[0] + + async def test_the_choice_can_depend_on_the_event(self, config: Config) -> None: + fast, thorough = runtime("fast"), runtime("thorough") + PayloadRoutingHandler() + chain = HandlerChain() + + await chain.process(event(priority="high"), {}) + await chain.process(event(priority="low"), {}) + + assert [seen[RUNTIME_CONTEXT_KEY] for seen in SEEN] == [thorough, fast] + + async def test_it_wins_over_the_callers_choice(self, config: Config) -> None: + fast = runtime("fast") + runtime("thorough") + FastHandler() + + await HandlerChain().process(event(), {RUNTIME_NAME_CONTEXT_KEY: "thorough"}) + + assert SEEN[0][RUNTIME_CONTEXT_KEY] is fast + + +class TestTheCallersChoice: + async def test_a_caller_supplied_name_is_honoured(self, config: Config) -> None: + """The parameter existed and was only logged; this is what makes it mean something.""" + thorough = runtime("thorough") + runtime("fast") + UndeclaredHandler() + + await HandlerChain().process(event(), {RUNTIME_NAME_CONTEXT_KEY: "thorough"}) + + assert SEEN[0][RUNTIME_CONTEXT_KEY] is thorough + + async def test_process_event_puts_its_argument_where_the_chain_looks(self, config: Config) -> None: + thorough = runtime("thorough") + runtime("fast") + UndeclaredHandler() + service = EventProcessingService() + + await service.process_event(event(), runtime_name="thorough") + + assert SEEN[0][RUNTIME_CONTEXT_KEY] is thorough + + async def test_passing_nothing_leaves_the_key_absent(self, config: Config) -> None: + """Absent means "no preference"; None would mean "explicitly no runtime".""" + UndeclaredHandler() + service = EventProcessingService() + + await service.process_event(event()) + + assert RUNTIME_NAME_CONTEXT_KEY not in SEEN[0] + + +class TestTheSingleRuntimeFallback: + async def test_one_runtime_is_bound_without_any_declaration(self, config: Config) -> None: + """What a single-agent application has in practice, so it needs no declaration.""" + only = runtime("planner") + UndeclaredHandler() + + await HandlerChain().process(event(), {}) + + assert SEEN[0][RUNTIME_CONTEXT_KEY] is only + assert SEEN[0][RUNTIME_NAME_CONTEXT_KEY] == "planner" + + async def test_no_runtime_at_all_binds_nothing(self, config: Config) -> None: + """Most applications have no agent; nothing about that is an error.""" + UndeclaredHandler() + + await HandlerChain().process(event(), {}) + + assert RUNTIME_CONTEXT_KEY not in SEEN[0] + + async def test_each_agent_gets_its_own_runtime(self, config: Config) -> None: + """The namespace is named explicitly, so a neighbour's runtime is never reachable.""" + orders_runtime = runtime("planner", namespace="orders") + runtime("planner", namespace="billing") + with namespace_scope("orders"): + UndeclaredHandler() + + await HandlerChain(namespace="orders").process(event(), {}) + + assert SEEN[0][RUNTIME_CONTEXT_KEY] is orders_runtime + + async def test_a_neighbours_runtime_does_not_count_towards_the_one(self, config: Config) -> None: + """Two runtimes in the process but one per agent, so each agent's choice is unambiguous.""" + runtime("planner", namespace="orders") + billing_runtime = runtime("planner", namespace="billing") + with namespace_scope("billing"): + UndeclaredHandler() + + await HandlerChain(namespace="billing").process(event(), {}) + + assert SEEN[0][RUNTIME_CONTEXT_KEY] is billing_runtime + + +class TestAmbiguity: + async def test_several_runtimes_and_no_declaration_binds_nothing(self, config: Config) -> None: + """The plan asks for an error here; that would break applications that work today. + + Two agents plus handlers that resolve their own runtime by name is a supported shape, + and those applications rely on the framework resolving nothing. + """ + runtime("fast") + runtime("thorough") + UndeclaredHandler() + + result = await HandlerChain().process(event(), {}) + + assert result == {"ok": True} + assert RUNTIME_CONTEXT_KEY not in SEEN[0] + + async def test_the_ambiguity_is_reported(self, config: Config, caplog: pytest.LogCaptureFixture) -> None: + runtime("fast") + runtime("thorough") + UndeclaredHandler() + + with caplog.at_level("WARNING", logger="blueprint.agents.handler.handler_chain"): + await HandlerChain().process(event(), {}) + + assert "did not say which agent runtime" in caplog.text + assert "fast" in caplog.text and "thorough" in caplog.text + + async def test_it_is_reported_once_and_not_per_delivery(self, config: Config, caplog: pytest.LogCaptureFixture) -> None: + """The condition is a property of the code, so a per-event warning would bury it.""" + runtime("fast") + runtime("thorough") + UndeclaredHandler() + chain = HandlerChain() + + with caplog.at_level("WARNING", logger="blueprint.agents.handler.handler_chain"): + await chain.process(event(), {}) + await chain.process(event(), {}) + + assert caplog.text.count("did not say which agent runtime") == 1 + + +class TestADeclarationThatCannotBeHonoured: + async def test_an_unknown_runtime_raises(self, config: Config) -> None: + """A declaration the framework cannot honour is a failure, not something to fall back from.""" + runtime("fast") + MissingRuntimeHandler() + + with pytest.raises(ValueError, match="asked for agent runtime 'nope'"): + await HandlerChain().process(event(), {}) + + async def test_the_error_names_what_is_registered(self, config: Config) -> None: + runtime("fast") + MissingRuntimeHandler() + + with pytest.raises(ValueError, match="registered here: fast"): + await HandlerChain().process(event(), {}) + + async def test_the_error_names_the_handler_and_the_namespace(self, config: Config) -> None: + with namespace_scope("orders"): + MissingRuntimeHandler() + + with pytest.raises(ValueError, match=r"'orders_missing_runtime_handler'.*'orders'"): + await HandlerChain(namespace="orders").process(event(), {}) + + +class TestTheDefaultHook: + def test_it_returns_none(self, config: Config) -> None: + """Every handler that exists today inherits this, and nothing about it resolves.""" + handler = UndeclaredHandler() + assert handler.get_runtime_name(event(), {}) is None diff --git a/tests/unit/agents/io/api/eventing/test_dapr.py b/tests/unit/agents/io/api/eventing/test_dapr.py index a26bab6c..78e496a2 100644 --- a/tests/unit/agents/io/api/eventing/test_dapr.py +++ b/tests/unit/agents/io/api/eventing/test_dapr.py @@ -153,6 +153,7 @@ async def test_subscription_document_is_empty_without_declarations(self, dapr_ev async def test_subscription_document_lists_declared_topics(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: handler = MagicMock() handler.get_subscribed_topics.return_value = ["orders.created", "orders.cancelled"] + handler.namespace = "" mock_registry.get_event_handler.return_value = [handler] assert await dapr_eventing.subscribe() == [ @@ -174,6 +175,7 @@ async def test_subscription_document_deduplicates_across_handlers(self, dapr_eve async def test_subscription_document_uses_configured_pubsub_name(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: handler = MagicMock() handler.get_subscribed_topics.return_value = ["orders.created"] + handler.namespace = "" mock_registry.get_event_handler.return_value = [handler] dapr_eventing.config.get.side_effect = lambda key, default=None: "orders-bus" if key == "dapr_pubsub_name" else default @@ -186,6 +188,7 @@ async def test_subscription_document_is_empty_when_declared_externally( ) -> None: handler = MagicMock() handler.get_subscribed_topics.return_value = ["orders.created"] + handler.namespace = "" mock_registry.get_event_handler.return_value = [handler] dapr_eventing.config.get.side_effect = lambda key, default=None: True if key == "dapr_declarative_subscriptions" else default @@ -197,6 +200,7 @@ async def test_sidecar_can_fetch_the_document_without_query_parameters( """Regression: a required query parameter here answered 422 to every sidecar call.""" handler = MagicMock() handler.get_subscribed_topics.return_value = ["orders.created"] + handler.namespace = "" mock_registry.get_event_handler.return_value = [handler] app = FastAPI() @@ -280,7 +284,7 @@ async def test_no_transport_client_is_needed( ) -> None: """on_startup never ran, so there is no DaprClient -- and the endpoint does not want one.""" _wire_processing_result(mock_registry, processed_result) - assert dapr_eventing._client is None + assert dapr_eventing._clients == {} async with AsyncClient(transport=ASGITransport(app=self._app(dapr_eventing)), base_url="http://local") as client: response = await client.post("/events/orders.created", json=dict(cloud_event)) @@ -347,15 +351,26 @@ async def test_an_ordinary_endpoint_still_answers_422(self, nats_eventing: NatsE class TestDaprEventingOnStartup: - async def test_fetches_dapr_client_from_registry(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: + async def test_fetches_the_client_of_each_declaring_agent(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: + """Per agent, not once: readiness reported against the wrong agent is unusable.""" + handler = MagicMock() + handler.get_subscribed_topics.return_value = ["orders.created"] + handler.namespace = "" mock_client = MagicMock() mock_client.subscribe = AsyncMock() mock_registry.get_component.return_value = mock_client + mock_registry.get_event_handler.return_value = [handler] + + await dapr_eventing.on_startup() + + assert dapr_eventing._clients[""] is mock_client + + async def test_no_declared_topic_fetches_no_client(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: mock_registry.get_event_handler.return_value = [] await dapr_eventing.on_startup() - assert dapr_eventing._client is mock_client + assert dapr_eventing._clients == {} async def test_no_handlers_skips_client_subscribe(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: mock_client = MagicMock() @@ -370,6 +385,7 @@ async def test_no_handlers_skips_client_subscribe(self, dapr_eventing: DaprEvent async def test_handler_topics_passed_to_client_subscribe(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: handler = MagicMock() handler.get_subscribed_topics.return_value = ["orders.created"] + handler.namespace = "" mock_client = MagicMock() mock_client.subscribe = AsyncMock() mock_registry.get_component.return_value = mock_client @@ -386,6 +402,7 @@ async def test_on_startup_returns_without_raising(self, dapr_eventing: DaprEvent """on_startup must return immediately; subscribe() starts a background task.""" handler = MagicMock() handler.get_subscribed_topics.return_value = ["t"] + handler.namespace = "" mock_client = MagicMock() mock_client.subscribe = AsyncMock() mock_registry.get_component.return_value = mock_client diff --git a/tests/unit/agents/io/api/eventing/test_dapr_fanout.py b/tests/unit/agents/io/api/eventing/test_dapr_fanout.py new file mode 100644 index 00000000..cebcd455 --- /dev/null +++ b/tests/unit/agents/io/api/eventing/test_dapr_fanout.py @@ -0,0 +1,290 @@ +"""One Dapr endpoint routing deliveries to the agents that want them. + +Dapr fixes both of its paths: the sidecar fetches the subscription document from +``GET /dapr/subscribe`` and posts deliveries where that document says. So a grouped process +cannot give each agent its own endpoint -- there is one, at the root, and it does in the process +what the broker does for NATS: tell the sidecar about each topic once, then fan each delivery out +to every agent that declared that topic. + +The cases below are the routing table, the fan-out, and the single acknowledgement a fan-out has +to collapse to. +""" + +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock + +import pytest + +from blueprint.agents.clients.io.dapr_client import DaprClient +from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import ROOT_NAMESPACE, namespace_scope +from blueprint.agents.config import Config +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.io.api.eventing.dapr import DaprEventing +from blueprint.agents.models.errors import CriticalHandlerError, RetryableHandlerError +from blueprint.agents.models.events import GenericCloudEvent +from blueprint.agents.services.eventing.event_processing_service import EventProcessingService + +CALLS: list[str] = [] +"""Which agents' handlers ran, in order. Reset by the ``calls`` fixture.""" + + +class RecordingHandler(EventHandlerBase): + """A handler that records the agent it ran for, and optionally fails.""" + + TOPICS: list[str] = [] + FAILURE: Exception | None = None + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return list(self.TOPICS) + + async def can_handle_event(self, event: GenericCloudEvent, context: dict) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict) -> Any: + CALLS.append(self.namespace) + if self.FAILURE is not None: + raise self.FAILURE + return {"handled_by": self.namespace} + + +class OrderHandler(RecordingHandler): + TOPICS = ["orders.created"] + + +class BillingHandler(RecordingHandler): + TOPICS = ["orders.created", "invoices.raised"] + + +class ShippingHandler(RecordingHandler): + TOPICS = ["shipments.booked"] + + +class RetryingHandler(RecordingHandler): + TOPICS = ["orders.created"] + FAILURE = RetryableHandlerError(status="busy", reason="try again") + + +class DroppingHandler(RecordingHandler): + TOPICS = ["orders.created"] + FAILURE = CriticalHandlerError(status="broken", reason="give up") + + +@pytest.fixture(autouse=True) +def calls() -> list[str]: + CALLS.clear() + return CALLS + + +@pytest.fixture +def config(tmp_path: Path) -> Config: + settings = tmp_path / "settings.toml" + settings.write_text( + '[development]\napp_name = "root-app"\napp_port = 8000\nevent_bus = "dapr"\n\n' + '[development.orders]\napp_name = "orders"\n\n' + '[development.billing]\napp_name = "billing"\n\n' + '[development.shipping]\napp_name = "shipping"\n' + ) + loaded = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + Component.configure(loaded) + return loaded + + +def event(event_type: str = "test.event") -> GenericCloudEvent: + return GenericCloudEvent.model_construct(id="evt-1", type=event_type, source="/tests") + + +def build_agents(**handlers: type[RecordingHandler]) -> DaprEventing: + """Register one handler per named agent, then return the process's Dapr endpoint.""" + for namespace, handler_type in handlers.items(): + with namespace_scope(namespace): + handler_type() + EventProcessingService() + return DaprEventing() + + +class TestTheRoutingTable: + def test_each_agents_topics_are_keyed_by_its_namespace(self, config: Config) -> None: + endpoint = build_agents(orders=OrderHandler, billing=BillingHandler) + + assert endpoint._topics_by_agent() == { + "orders": ["orders.created"], + "billing": ["orders.created", "invoices.raised"], + } + + def test_the_document_is_the_union_deduplicated(self, config: Config) -> None: + """The sidecar delivers a topic to the application once, so it is told once.""" + endpoint = build_agents(orders=OrderHandler, billing=BillingHandler) + + assert sorted(endpoint._declared_topics()) == ["invoices.raised", "orders.created"] + + async def test_the_subscription_document_carries_the_union(self, config: Config) -> None: + endpoint = build_agents(orders=OrderHandler, billing=BillingHandler) + + document = await endpoint.subscribe() + + assert sorted(entry["topic"] for entry in document) == ["invoices.raised", "orders.created"] + + async def test_every_route_stays_at_the_fixed_path(self, config: Config) -> None: + """The sidecar posts where the document says, and the endpoint is not prefixed.""" + endpoint = build_agents(orders=OrderHandler, billing=BillingHandler) + + document = await endpoint.subscribe() + + assert all(entry["route"] == f"/events/{entry['topic']}" for entry in document) + + def test_an_agent_that_declared_nothing_is_absent(self, config: Config) -> None: + endpoint = build_agents(orders=OrderHandler) + with namespace_scope("billing"): + RecordingHandler() # declares no topic + + assert "billing" not in endpoint._topics_by_agent() + + +class TestAgentsForATopic: + def test_one_declaring_agent(self, config: Config) -> None: + endpoint = build_agents(orders=OrderHandler, shipping=ShippingHandler) + + assert endpoint._agents_for("shipments.booked") == ("shipping",) + + def test_two_agents_declaring_one_topic_both_appear(self, config: Config) -> None: + """Spec sec. 7.6 for the in-process case: both want the event, so both get it.""" + endpoint = build_agents(orders=OrderHandler, billing=BillingHandler) + + assert sorted(endpoint._agents_for("orders.created")) == ["billing", "orders"] + + def test_an_undeclared_topic_reaches_every_agent_with_handlers(self, config: Config) -> None: + """The same rule as the dispatch index: an absent declaration narrows nothing. + + This is the path a topic declared outside the application takes -- + ``dapr_declarative_subscriptions`` leaves the framework with no topic list at all. + """ + endpoint = build_agents(orders=OrderHandler, shipping=ShippingHandler) + + assert sorted(endpoint._agents_for("nobody.declared.this")) == ["orders", "shipping"] + + def test_a_single_agent_application_resolves_to_the_root(self, config: Config) -> None: + endpoint = build_agents() + RecordingHandler() + + assert endpoint._agents_for("anything") == (ROOT_NAMESPACE,) + + def test_no_handlers_at_all_resolves_to_the_root(self, config: Config) -> None: + endpoint = build_agents() + + assert endpoint._agents_for("anything") == (ROOT_NAMESPACE,) + + +class TestFanOut: + async def test_both_declaring_agents_handle_the_delivery(self, config: Config) -> None: + endpoint = build_agents(orders=OrderHandler, billing=BillingHandler) + + await endpoint.publish("orders.created", event()) + + assert sorted(CALLS) == ["billing", "orders"] + + async def test_a_non_declaring_agent_is_not_offered_it(self, config: Config) -> None: + endpoint = build_agents(orders=OrderHandler, shipping=ShippingHandler) + + await endpoint.publish("orders.created", event()) + + assert CALLS == ["orders"] + + async def test_a_single_agent_application_dispatches_once(self, config: Config) -> None: + endpoint = build_agents() + RecordingHandler() + + await endpoint.publish("anything", event()) + + assert CALLS == [ROOT_NAMESPACE] + + async def test_one_agent_failing_does_not_stop_the_other(self, config: Config) -> None: + """Letting the exception out of the loop would cancel a neighbour's work silently.""" + endpoint = build_agents(orders=RetryingHandler, billing=BillingHandler) + + await endpoint.publish("orders.created", event()) + + assert sorted(CALLS) == ["billing", "orders"] + + +class TestTheSingleAcknowledgement: + async def test_all_succeeding_acknowledges(self, config: Config) -> None: + endpoint = build_agents(orders=OrderHandler, billing=BillingHandler) + + assert await endpoint.publish("orders.created", event()) == {"status": "SUCCESS"} + + async def test_one_retry_wins_over_a_success(self, config: Config) -> None: + """There is one delivery, so one answer: the only way to retry that agent is to retry all.""" + endpoint = build_agents(orders=RetryingHandler, billing=BillingHandler) + + answer = await endpoint.publish("orders.created", event()) + + assert answer["status"] == "RETRY" + assert answer["reason"] == "try again" + + async def test_a_drop_alongside_a_success_acknowledges(self, config: Config) -> None: + """One agent finding it undeliverable is a finished outcome, not a failed delivery.""" + endpoint = build_agents(orders=DroppingHandler, billing=BillingHandler) + + answer = await endpoint.publish("orders.created", event()) + + assert answer["status"] == "SUCCESS" + + async def test_a_retry_wins_over_a_drop(self, config: Config) -> None: + endpoint = build_agents(orders=RetryingHandler, billing=DroppingHandler) + + assert (await endpoint.publish("orders.created", event()))["status"] == "RETRY" + + async def test_every_agent_dropping_drops(self, config: Config) -> None: + endpoint = build_agents(orders=DroppingHandler, billing=DroppingHandler) + + assert (await endpoint.publish("orders.created", event()))["status"] == "DROP" + + async def test_an_event_nobody_handles_still_acknowledges(self, config: Config) -> None: + endpoint = build_agents() + + assert await endpoint.publish("orders.created", event()) == {"status": "SUCCESS"} + + +class TestReadinessIsPerAgent: + async def test_each_agents_client_is_given_its_own_topics(self, config: Config) -> None: + """The endpoint is shared; the clients are not, and readiness is reported per client.""" + endpoint = build_agents(orders=OrderHandler, billing=BillingHandler) + orders_client = DaprClient(namespace="orders") + billing_client = DaprClient(namespace="billing") + orders_client.subscribe = AsyncMock() # type: ignore[method-assign] + billing_client.subscribe = AsyncMock() # type: ignore[method-assign] + + await endpoint.on_startup() + + assert sorted(orders_client.subscribe.call_args[0][0]) == ["orders.created"] + assert sorted(billing_client.subscribe.call_args[0][0]) == ["invoices.raised", "orders.created"] + + async def test_the_clients_are_kept_per_agent(self, config: Config) -> None: + endpoint = build_agents(orders=OrderHandler, billing=BillingHandler) + for namespace in ("orders", "billing"): + client = DaprClient(namespace=namespace) + client.subscribe = AsyncMock() # type: ignore[method-assign] + + await endpoint.on_startup() + + assert sorted(endpoint._clients) == ["billing", "orders"] + + async def test_no_declared_topic_fetches_no_client(self, config: Config) -> None: + endpoint = build_agents() + + await endpoint.on_startup() + + assert endpoint._clients == {} + + def test_the_endpoint_takes_no_namespace(self, config: Config) -> None: + """There is one per process, at the root, and that is structural rather than a default.""" + with pytest.raises(TypeError): + DaprEventing(namespace="orders") # type: ignore[call-arg] diff --git a/tests/unit/agents/io/api/eventing/test_eventing_namespaces.py b/tests/unit/agents/io/api/eventing/test_eventing_namespaces.py new file mode 100644 index 00000000..7f9a44dc --- /dev/null +++ b/tests/unit/agents/io/api/eventing/test_eventing_namespaces.py @@ -0,0 +1,187 @@ +"""Per-agent topic subscription on the NATS transport (spec sec. 7.6). + +The requirement being pinned down is that each ``(namespace, topic)`` pair is subscribed on its +own behalf: an agent subscribes to its own handlers' topics and its own configured list, and two +agents wanting the same topic both get it. The failure this guards against is a cross-agent +deduplication that silently drops one agent's subscription -- invisible to its author, who runs +that agent alone. +""" + +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock, patch + +import pytest + +from blueprint.agents.clients.io.nats_client import NATSClient +from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import ROOT_NAMESPACE, namespace_scope +from blueprint.agents.config import Config +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.io.api.eventing.nats import NatsEventing +from blueprint.agents.models.events import GenericCloudEvent + + +class TopicHandler(EventHandlerBase): + """A handler that declares topics the way a project's handler does.""" + + TOPICS: list[str] = [] + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return list(self.TOPICS) + + async def can_handle_event(self, event: GenericCloudEvent, context: dict) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict) -> Any: + return None + + +class OrderHandler(TopicHandler): + TOPICS = ["orders.created"] + + +class BillingHandler(TopicHandler): + TOPICS = ["invoices.raised"] + + +class SharedTopicHandler(TopicHandler): + TOPICS = ["orders.created"] + + +@pytest.fixture +def two_agent_config(tmp_path: Path) -> Config: + """A root and two agents, with a per-agent ``nats_subscriptions`` list for one of them.""" + settings = tmp_path / "settings.toml" + content = """ + [development] + app_name = "root-app" + app_port = 8000 + event_bus = "nats" + nats_subscriptions = ["shared.>"] + + [development.orders] + app_name = "orders" + nats_subscriptions = ["orders.legacy"] + + [development.billing] + app_name = "billing" + """ + settings.write_text(content.replace("\n ", "\n")) + config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + Component.configure(config) + return config + + +class TestNatsSubscribesForOneAgent: + async def test_it_subscribes_its_own_handlers_topics(self, two_agent_config: Config) -> None: + with namespace_scope("orders"): + OrderHandler() + NATSClient(namespace="orders") + endpoint = NatsEventing(namespace="orders") + + assert "orders.created" in endpoint._declared_topics() + + async def test_it_does_not_subscribe_another_agents_topics(self, two_agent_config: Config) -> None: + with namespace_scope("orders"): + OrderHandler() + with namespace_scope("billing"): + BillingHandler() + + assert NatsEventing(namespace="orders")._declared_topics() == ["orders.created", "orders.legacy"] + + async def test_two_agents_wanting_one_topic_both_get_it(self, two_agent_config: Config) -> None: + """Spec sec. 7.6: both want the event, so neither subscription may be deduplicated away.""" + with namespace_scope("orders"): + OrderHandler() + with namespace_scope("billing"): + SharedTopicHandler() + + orders = NatsEventing(namespace="orders")._declared_topics() + billing = NatsEventing(namespace="billing")._declared_topics() + + assert "orders.created" in orders + assert "orders.created" in billing + + async def test_a_topic_declared_twice_in_one_agent_is_subscribed_once(self, two_agent_config: Config) -> None: + with namespace_scope("orders"): + OrderHandler() + SharedTopicHandler() + + assert NatsEventing(namespace="orders")._declared_topics().count("orders.created") == 1 + + async def test_the_agents_own_subscription_list_is_read(self, two_agent_config: Config) -> None: + """C5: 'orders.nats_subscriptions' wins over the root list, with no code saying so.""" + assert NatsEventing(namespace="orders")._declared_topics() == ["orders.legacy"] + + async def test_an_agent_without_its_own_list_falls_back_to_the_shared_one(self, two_agent_config: Config) -> None: + assert NatsEventing(namespace="billing")._declared_topics() == ["shared.>"] + + async def test_handler_topics_come_before_configured_ones(self, two_agent_config: Config) -> None: + with namespace_scope("orders"): + OrderHandler() + + assert NatsEventing(namespace="orders")._declared_topics() == ["orders.created", "orders.legacy"] + + +class TestNatsResolvesItsOwnClient: + async def test_it_takes_its_own_namespaces_client(self, two_agent_config: Config) -> None: + with namespace_scope("orders"): + orders_client = NATSClient(namespace="orders") + with namespace_scope("billing"): + NATSClient(namespace="billing") + endpoint = NatsEventing(namespace="orders") + + with patch.object(NATSClient, "subscribe", new_callable=AsyncMock): + await endpoint.on_startup() + + assert endpoint._client is orders_client + + async def test_a_root_endpoint_takes_the_root_client(self, two_agent_config: Config) -> None: + """Unchanged for every single-agent application: one client, at the root.""" + root_client = NATSClient() + endpoint = NatsEventing() + + with patch.object(NATSClient, "subscribe", new_callable=AsyncMock): + await endpoint.on_startup() + + assert endpoint._client is root_client + + async def test_only_this_agents_topics_reach_the_client(self, two_agent_config: Config) -> None: + with namespace_scope("orders"): + OrderHandler() + NATSClient(namespace="orders") + with namespace_scope("billing"): + BillingHandler() + endpoint = NatsEventing(namespace="orders") + + with patch.object(NATSClient, "subscribe", new_callable=AsyncMock) as subscribe: + await endpoint.on_startup() + + assert sorted(subscribe.call_args[0][0]) == ["orders.created", "orders.legacy"] + + +class TestNamespaceOwnership: + def test_an_endpoint_defaults_to_the_root(self, two_agent_config: Config) -> None: + assert NatsEventing().namespace == ROOT_NAMESPACE + + def test_an_endpoint_takes_the_namespace_it_is_given(self, two_agent_config: Config) -> None: + assert NatsEventing(namespace="orders").namespace == "orders" + + def test_an_illegal_namespace_is_refused(self, two_agent_config: Config) -> None: + with pytest.raises(ValueError, match="legal namespace"): + NatsEventing(namespace="Orders") + + def test_endpoints_are_not_registered(self, two_agent_config: Config) -> None: + """Two agents' endpoints would collide on the derived name, and nothing looks them up.""" + NatsEventing(namespace="orders") + NatsEventing(namespace="billing") + registry = Component.shared_registry + assert registry is not None + assert registry.get_component_names_by_type(NatsEventing) == [] diff --git a/tests/unit/agents/io/api/utilities/test_cache.py b/tests/unit/agents/io/api/utilities/test_cache.py index 61a564fb..d5a18b6b 100644 --- a/tests/unit/agents/io/api/utilities/test_cache.py +++ b/tests/unit/agents/io/api/utilities/test_cache.py @@ -1,4 +1,11 @@ -"""Unit tests for CacheManagementApi.""" +"""Unit tests for CacheManagementApi. + +Every endpoint takes an optional ``?name=`` naming which cache to act on, defaulting to the +one a single-cache application has always had. The two failure answers are deliberately +different -- 503 when no cache is registered at all, 404 for a name that is not among the ones +that are -- and both are asserted, because answering 503 for a mistyped name would invite a +retry that can never succeed. +""" from unittest.mock import MagicMock @@ -8,32 +15,51 @@ from blueprint.agents.io.api.utilities.cache import CacheManagementApi from blueprint.agents.models.api import CacheEvictRequest +STATS = { + "size": 10, + "cache_dir": "/tmp/cache", + "ttl_tracked_keys": 5, + "size_limit": 1_000_000_000, + "eviction_policy": "least-recently-used", +} + @pytest.fixture def cache_api(mock_config: MagicMock, mock_registry: MagicMock) -> CacheManagementApi: - """Return a CacheManagementApi with a mocked registry.""" + """Return a CacheManagementApi with a mocked registry holding no cache.""" + mock_registry.get_all_caches.return_value = {} return CacheManagementApi() +def register(mock_registry: MagicMock, **caches: MagicMock) -> None: + """Make the mocked registry answer for exactly the given cache names.""" + mock_registry.get_all_caches.return_value = dict(caches) + mock_registry.get_cache.side_effect = lambda name="default": ( + caches[name] if name in caches else _raise(ValueError(f"No cache registered as '{name}' (registered: {', '.join(sorted(caches))})")) + ) + + +def _raise(error: Exception) -> None: + raise error + + +def cache_double() -> MagicMock: + cache = MagicMock() + cache.get_stats.return_value = STATS + cache.list_namespaces.return_value = ["ns1", "ns2"] + cache.clear = MagicMock() + return cache + + @pytest.fixture def cache_api_with_cache(cache_api: CacheManagementApi, mock_registry: MagicMock) -> CacheManagementApi: - """CacheManagementApi with registry.has_cache() returning True.""" - mock_registry.has_cache.return_value = True - mock_registry.cache_service.get_stats.return_value = { - "size": 10, - "cache_dir": "/tmp/cache", - "ttl_tracked_keys": 5, - "size_limit": 1_000_000_000, - "eviction_policy": "least-recently-used", - } - mock_registry.cache_service.list_namespaces.return_value = ["ns1", "ns2"] - mock_registry.cache_service.clear = MagicMock() + """CacheManagementApi with one cache registered under the default name.""" + register(mock_registry, default=cache_double()) return cache_api class TestGetCacheStats: - async def test_raises_503_when_no_cache(self, cache_api: CacheManagementApi, mock_registry: MagicMock) -> None: - mock_registry.has_cache.return_value = False + async def test_raises_503_when_no_cache(self, cache_api: CacheManagementApi) -> None: with pytest.raises(HTTPException) as exc_info: await cache_api.get_cache_stats() assert exc_info.value.status_code == 503 @@ -45,12 +71,11 @@ async def test_returns_stats_when_cache_available(self, cache_api_with_cache: Ca async def test_calls_cache_service_get_stats(self, cache_api_with_cache: CacheManagementApi, mock_registry: MagicMock) -> None: await cache_api_with_cache.get_cache_stats() - mock_registry.cache_service.get_stats.assert_called_once() + mock_registry.get_all_caches.return_value["default"].get_stats.assert_called_once() class TestListCacheNamespaces: - async def test_raises_503_when_no_cache(self, cache_api: CacheManagementApi, mock_registry: MagicMock) -> None: - mock_registry.has_cache.return_value = False + async def test_raises_503_when_no_cache(self, cache_api: CacheManagementApi) -> None: with pytest.raises(HTTPException) as exc_info: await cache_api.list_cache_namespaces() assert exc_info.value.status_code == 503 @@ -62,19 +87,18 @@ async def test_returns_namespaces(self, cache_api_with_cache: CacheManagementApi class TestEvictCacheEntry: - async def test_raises_503_when_no_cache(self, cache_api: CacheManagementApi, mock_registry: MagicMock) -> None: - mock_registry.has_cache.return_value = False + async def test_raises_503_when_no_cache(self, cache_api: CacheManagementApi) -> None: with pytest.raises(HTTPException) as exc_info: await cache_api.evict_cache_entry(CacheEvictRequest()) assert exc_info.value.status_code == 503 async def test_clears_specific_namespace(self, cache_api_with_cache: CacheManagementApi, mock_registry: MagicMock) -> None: await cache_api_with_cache.evict_cache_entry(CacheEvictRequest(namespace="ns1")) - mock_registry.cache_service.clear.assert_called_once_with(namespace="ns1") + mock_registry.get_all_caches.return_value["default"].clear.assert_called_once_with(namespace="ns1") async def test_clears_all_when_no_namespace(self, cache_api_with_cache: CacheManagementApi, mock_registry: MagicMock) -> None: await cache_api_with_cache.evict_cache_entry(CacheEvictRequest()) - mock_registry.cache_service.clear.assert_called_once_with(namespace=None) + mock_registry.get_all_caches.return_value["default"].clear.assert_called_once_with(namespace=None) async def test_returns_ok_status(self, cache_api_with_cache: CacheManagementApi) -> None: result = await cache_api_with_cache.evict_cache_entry(CacheEvictRequest(namespace="ns1")) @@ -87,3 +111,78 @@ async def test_response_includes_namespace(self, cache_api_with_cache: CacheMana async def test_response_reports_all_when_no_namespace(self, cache_api_with_cache: CacheManagementApi) -> None: result = await cache_api_with_cache.evict_cache_entry(CacheEvictRequest()) assert result["namespace"] == "all" + + +class TestNamedCaches: + async def test_stats_read_the_named_cache(self, cache_api: CacheManagementApi, mock_registry: MagicMock) -> None: + default, sessions = cache_double(), cache_double() + sessions.get_stats.return_value = {**STATS, "size": 99} + register(mock_registry, default=default, sessions=sessions) + + result = await cache_api.get_cache_stats(name="sessions") + + assert result.size == 99 + default.get_stats.assert_not_called() + + async def test_the_default_is_used_when_no_name_is_given(self, cache_api: CacheManagementApi, mock_registry: MagicMock) -> None: + default, sessions = cache_double(), cache_double() + register(mock_registry, default=default, sessions=sessions) + + await cache_api.get_cache_stats() + + default.get_stats.assert_called_once() + sessions.get_stats.assert_not_called() + + async def test_evict_clears_only_the_named_cache(self, cache_api: CacheManagementApi, mock_registry: MagicMock) -> None: + default, sessions = cache_double(), cache_double() + register(mock_registry, default=default, sessions=sessions) + + await cache_api.evict_cache_entry(CacheEvictRequest(), name="sessions") + + sessions.clear.assert_called_once_with(namespace=None) + default.clear.assert_not_called() + + async def test_the_response_names_the_cache_it_cleared(self, cache_api: CacheManagementApi, mock_registry: MagicMock) -> None: + register(mock_registry, default=cache_double(), sessions=cache_double()) + + result = await cache_api.evict_cache_entry(CacheEvictRequest(), name="sessions") + + assert result["cache"] == "sessions" + + async def test_namespaces_read_the_named_cache(self, cache_api: CacheManagementApi, mock_registry: MagicMock) -> None: + sessions = cache_double() + sessions.list_namespaces.return_value = ["jobs"] + register(mock_registry, default=cache_double(), sessions=sessions) + + result = await cache_api.list_cache_namespaces(name="sessions") + + assert result.namespaces == ["jobs"] + + +class TestUnknownName: + @pytest.mark.parametrize("call", ["get_cache_stats", "list_cache_namespaces"]) + async def test_an_unknown_name_answers_404(self, cache_api: CacheManagementApi, mock_registry: MagicMock, call: str) -> None: + """404 rather than 503: a mistyped name is a bad request, and a retry cannot fix it.""" + register(mock_registry, default=cache_double()) + + with pytest.raises(HTTPException) as exc_info: + await getattr(cache_api, call)(name="nope") + + assert exc_info.value.status_code == 404 + + async def test_evict_answers_404_too(self, cache_api: CacheManagementApi, mock_registry: MagicMock) -> None: + register(mock_registry, default=cache_double()) + + with pytest.raises(HTTPException) as exc_info: + await cache_api.evict_cache_entry(CacheEvictRequest(), name="nope") + + assert exc_info.value.status_code == 404 + + async def test_the_404_lists_the_registered_names(self, cache_api: CacheManagementApi, mock_registry: MagicMock) -> None: + """There is no endpoint that lists them, so a mistyped name has to be recoverable here.""" + register(mock_registry, default=cache_double(), sessions=cache_double()) + + with pytest.raises(HTTPException) as exc_info: + await cache_api.get_cache_stats(name="nope") + + assert "default" in str(exc_info.value.detail) and "sessions" in str(exc_info.value.detail) diff --git a/tests/unit/agents/services/eventing/test_event_processing_namespaces.py b/tests/unit/agents/services/eventing/test_event_processing_namespaces.py new file mode 100644 index 00000000..1c567c21 --- /dev/null +++ b/tests/unit/agents/services/eventing/test_event_processing_namespaces.py @@ -0,0 +1,262 @@ +"""Per-agent dispatch, against real components rather than mocks. + +What is being tested is that an event delivered for one agent reaches that agent's handlers and +no others, that each agent's chain reads that agent's own configuration, and that an application +which never mentions a namespace is dispatched exactly as it was before any of this existed. + +Real ``Config``, real ``Registry``, real ``HandlerChain`` and real handler subclasses on purpose: +the routing is a composition of ``Component.registry``, ``Component.config`` and the registry's +namespace filtering, and a mocked registry would assert the call rather than the outcome. +""" + +from pathlib import Path +from typing import Any + +import pytest + +from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import ROOT_NAMESPACE, namespace_scope +from blueprint.agents.component.registry import DEFAULT_CACHE_NAME +from blueprint.agents.config import Config +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.handler.handler_chain import HandlerChain +from blueprint.agents.models.config import CacheConfig +from blueprint.agents.models.events import GenericCloudEvent +from blueprint.agents.models.result import ProcessingStatus +from blueprint.agents.services.eventing.event_processing_service import EventProcessingService +from blueprint.agents.services.infrastructure.cache_backend_factory import CacheBackendFactory + +CALLS: list[str] = [] +"""Which handlers ran, in order. Reset by the ``calls`` fixture.""" + + +class RecordingHandler(EventHandlerBase): + """A handler written the way a project writes one -- it knows nothing about namespaces.""" + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + async def can_handle_event(self, event: GenericCloudEvent, context: dict) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict) -> Any: + CALLS.append(self.name) + return {"handled_by": self.name} + + +class OrderHandler(RecordingHandler): + pass + + +class BillingHandler(RecordingHandler): + pass + + +@pytest.fixture(autouse=True) +def calls() -> list[str]: + CALLS.clear() + return CALLS + + +@pytest.fixture +def two_agent_config(tmp_path: Path) -> Config: + """A root and two agents, one of which enables deduplication and the other does not. + + A cache is registered as well, because ``orders`` opts into deduplication and a chain + refuses to resolve that policy with nowhere to keep the markers. It also puts the + agent-scoped cache lens in the dispatch path, which is where it will actually be used. + """ + settings = tmp_path / "settings.toml" + content = """ + [development] + app_name = "root-app" + app_port = 8000 + idempotency_enabled = false + + [development.orders] + app_name = "orders" + idempotency_enabled = true + idempotency_ttl = 60 + + [development.billing] + app_name = "billing" + """ + settings.write_text(content.replace("\n ", "\n")) + config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + Component.configure(config) + + cache = CacheBackendFactory.create(CacheConfig(cache_dir=str(tmp_path / "cache"))) + registry = Component.shared_registry + assert registry is not None + registry.add_cache(DEFAULT_CACHE_NAME, cache) + return config + + +@pytest.fixture +def event() -> GenericCloudEvent: + return GenericCloudEvent.model_construct(id="evt-1", type="test.event", source="/tests") + + +def build_two_agents() -> None: + """Register one handler per agent, the way a registration applied per namespace does.""" + with namespace_scope("orders"): + OrderHandler() + with namespace_scope("billing"): + BillingHandler() + + +class TestDispatchGoesToOneAgent: + async def test_only_that_agents_handler_runs(self, two_agent_config: Config, event: GenericCloudEvent) -> None: + build_two_agents() + service = EventProcessingService() + + await service.process_event(event, namespace="orders") + + assert CALLS == ["orders_order_handler"] + + async def test_the_other_agent_is_reachable_too(self, two_agent_config: Config, event: GenericCloudEvent) -> None: + build_two_agents() + service = EventProcessingService() + + await service.process_event(event, namespace="billing") + + assert CALLS == ["billing_billing_handler"] + + async def test_a_namespace_with_no_handler_finds_nobody(self, two_agent_config: Config, event: GenericCloudEvent) -> None: + """Not an error: 'no handler' is an outcome the acknowledgement contract already has.""" + build_two_agents() + service = EventProcessingService() + + result = await service.process_event(event, namespace="shipping") + + assert (result.status, CALLS) == (ProcessingStatus.NO_HANDLER_FOUND, []) + + async def test_the_root_chain_does_not_reach_into_an_agent(self, two_agent_config: Config, event: GenericCloudEvent) -> None: + """The hazard behind naming the namespace explicitly in ``_dispatch``. + + On the root registry an omitted namespace means *every* namespace, so a root dispatch + would otherwise run both agents' handlers for one delivery. + """ + build_two_agents() + service = EventProcessingService() + + result = await service.process_event(event) + + assert (result.status, CALLS) == (ProcessingStatus.NO_HANDLER_FOUND, []) + + async def test_a_root_handler_does_not_run_for_an_agent(self, two_agent_config: Config, event: GenericCloudEvent) -> None: + """No fallback to root handlers: one would otherwise run for every agent in the group.""" + RecordingHandler() + build_two_agents() + service = EventProcessingService() + + await service.process_event(event, namespace="orders") + + assert CALLS == ["orders_order_handler"] + + +class TestSingleAgentApplicationsAreUnchanged: + async def test_a_root_handler_receives_a_root_dispatch(self, two_agent_config: Config, event: GenericCloudEvent) -> None: + RecordingHandler() + service = EventProcessingService() + + result = await service.process_event(event) + + assert (result.status, CALLS) == (ProcessingStatus.PROCESSED, ["recording_handler"]) + + async def test_every_root_handler_is_offered_the_event(self, two_agent_config: Config, event: GenericCloudEvent) -> None: + """Two handlers at the root are both candidates, which is today's chain behaviour.""" + OrderHandler() + BillingHandler() + service = EventProcessingService() + + await service.process_event(event) + + assert len(CALLS) == 1 # the first to return a result stops the chain + assert CALLS[0] in {"order_handler", "billing_handler"} + + async def test_a_rest_request_reaches_the_root_handler(self, two_agent_config: Config) -> None: + RecordingHandler() + service = EventProcessingService() + + result = await service.process_rest_request({"x": 1}) + + assert (result.status, CALLS) == (ProcessingStatus.PROCESSED, ["recording_handler"]) + + +class TestChainsPerAgent: + async def test_one_chain_is_built_per_namespace_with_handlers(self, two_agent_config: Config) -> None: + build_two_agents() + service = EventProcessingService() + + await service.on_startup() + + assert sorted(service._handler_chains) == [ROOT_NAMESPACE, "billing", "orders"] + + async def test_each_chain_carries_its_own_namespace(self, two_agent_config: Config) -> None: + build_two_agents() + service = EventProcessingService() + + await service.on_startup() + + assert service._handler_chains["orders"].namespace == "orders" + + async def test_each_chain_reads_its_own_agents_configuration(self, two_agent_config: Config) -> None: + """C5 through the chain: dedup is on for orders and off for billing, from one settings tree.""" + build_two_agents() + service = EventProcessingService() + + await service.on_startup() + + orders = service._handler_chains["orders"]._policy + billing = service._handler_chains["billing"]._policy + assert orders is not None and billing is not None + assert (orders.enabled, orders.ttl, billing.enabled) == (True, 60, False) + + async def test_a_chain_is_created_on_first_use_for_an_unknown_namespace( + self, two_agent_config: Config, event: GenericCloudEvent + ) -> None: + build_two_agents() + service = EventProcessingService() + await service.on_startup() + + await service.process_event(event, namespace="shipping") + + assert service._handler_chains["shipping"].namespace == "shipping" + + async def test_the_same_chain_is_reused_across_deliveries(self, two_agent_config: Config, event: GenericCloudEvent) -> None: + build_two_agents() + service = EventProcessingService() + + await service.process_event(event, namespace="orders") + first = service._handler_chains["orders"] + await service.process_event(event, namespace="orders") + + assert service._handler_chains["orders"] is first + + async def test_an_illegal_namespace_is_refused(self, two_agent_config: Config, event: GenericCloudEvent) -> None: + service = EventProcessingService() + + with pytest.raises(ValueError, match="legal namespace"): + await service.process_event(event, namespace="Orders") + + +class TestHandlerChainNamespace: + def test_a_chain_defaults_to_the_root(self, two_agent_config: Config) -> None: + assert HandlerChain().namespace == ROOT_NAMESPACE + + def test_a_chain_takes_the_namespace_it_is_given(self, two_agent_config: Config) -> None: + assert HandlerChain(namespace="orders").namespace == "orders" + + def test_a_chain_is_not_registered(self, two_agent_config: Config) -> None: + """It is one agent's dispatcher, not a collaborator anything looks up.""" + HandlerChain(namespace="orders") + registry = Component.shared_registry + assert registry is not None + assert registry.get_component_names_by_type(HandlerChain) == [] + + def test_a_chain_reads_its_own_agents_configuration(self, two_agent_config: Config) -> None: + assert HandlerChain(namespace="orders").config.get("app_name") == "orders" 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 6d944225..cbeabc09 100644 --- a/tests/unit/agents/services/eventing/test_event_processing_service.py +++ b/tests/unit/agents/services/eventing/test_event_processing_service.py @@ -4,6 +4,7 @@ import pytest +from blueprint.agents.component.namespace import ROOT_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 @@ -119,24 +120,53 @@ def test_dapr_event_with_non_dict_non_event_inner_raises(self, event_processing_ # --------------------------------------------------------------------------- +class StubbedHandler: + """Just enough handler for the chain map: a namespace, an ordering, and no declarations. + + A bare ``MagicMock`` will not do any more: a chain builds its dispatch index at startup, + which sorts the handlers and reads their declarations. + """ + + def __init__(self, namespace: str) -> None: + self.namespace = namespace + self.name = f"{namespace}_handler" + + def __lt__(self, other: "StubbedHandler") -> bool: + return False + + def get_handled_event_types(self) -> list[str]: + return [] + + class TestLifecycle: - async def test_on_startup_starts_the_handler_chain(self, event_processing_service: EventProcessingService) -> None: + async def test_on_startup_starts_the_root_chain(self, event_processing_service: EventProcessingService) -> None: chain = MagicMock() chain.on_startup = AsyncMock() - event_processing_service._handler_chain = chain + event_processing_service._handler_chains = {ROOT_NAMESPACE: chain} await event_processing_service.on_startup() chain.on_startup.assert_awaited_once() - async def test_on_shutdown_stops_the_handler_chain(self, event_processing_service: EventProcessingService) -> None: - chain = MagicMock() - chain.on_shutdown = AsyncMock() - event_processing_service._handler_chain = chain + async def test_on_startup_builds_a_chain_for_every_namespace_with_handlers( + self, event_processing_service: EventProcessingService, mock_registry: MagicMock + ) -> None: + """Built at startup, not on first delivery: a bad dedup window must fail the pod.""" + mock_registry.get_event_handler.return_value = [StubbedHandler("orders"), StubbedHandler("billing")] + + await event_processing_service.on_startup() + + assert sorted(event_processing_service._handler_chains) == [ROOT_NAMESPACE, "billing", "orders"] + + async def test_on_shutdown_stops_every_chain(self, event_processing_service: EventProcessingService) -> None: + root, orders = MagicMock(), MagicMock() + root.on_shutdown, orders.on_shutdown = AsyncMock(), AsyncMock() + event_processing_service._handler_chains = {ROOT_NAMESPACE: root, "orders": orders} await event_processing_service.on_shutdown() - chain.on_shutdown.assert_awaited_once() + root.on_shutdown.assert_awaited_once() + orders.on_shutdown.assert_awaited_once() # --------------------------------------------------------------------------- From d098183351253d4cb55de8e578a541493410f98e Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:44:54 +0200 Subject: [PATCH 010/133] feat(group): resolve the hosted group and serve it from the entry point Phase 8. The name given in code is the agent's identity and app_name is only the fallback; any name that cannot identify one agent fails at startup. GroupConfig resolves which agents a process hosts from a file and the environment, AppBuilder applies the resolved group one namespace per agent, and python -m blueprint.agents.entrypoint is the container's command: it resolves, builds and serves. pyyaml is now declared rather than reached through a transitive dependency. Co-Authored-By: Claude Opus 5 (1M context) --- ...26-08-28-multi-agent-grouping-changelog.md | 430 +++++++++++++++++- pyproject.toml | 2 + src/blueprint/agents/app_builder.py | 156 ++++++- src/blueprint/agents/component/component.py | 24 +- src/blueprint/agents/component/namespace.py | 14 + src/blueprint/agents/component/registry.py | 38 +- src/blueprint/agents/config/config.py | 34 +- src/blueprint/agents/entrypoint.py | 97 ++++ src/blueprint/agents/group_config.py | 403 ++++++++++++++++ .../agents/io/api/scheduling/scheduler.py | 24 +- .../app_builder/test_namespace_builder.py | 14 +- .../agents/app_builder/test_with_group.py | 270 +++++++++++ .../agents/component/test_name_uniqueness.py | 188 ++++++++ .../unit/agents/config/test_agent_identity.py | 84 ++++ tests/unit/agents/config/test_agent_scope.py | 24 +- .../io/api/scheduling/test_scheduler.py | 27 +- tests/unit/agents/test_entrypoint.py | 207 +++++++++ tests/unit/agents/test_group_config.py | 269 +++++++++++ 18 files changed, 2256 insertions(+), 49 deletions(-) create mode 100644 src/blueprint/agents/entrypoint.py create mode 100644 src/blueprint/agents/group_config.py create mode 100644 tests/unit/agents/app_builder/test_with_group.py create mode 100644 tests/unit/agents/component/test_name_uniqueness.py create mode 100644 tests/unit/agents/config/test_agent_identity.py create mode 100644 tests/unit/agents/test_entrypoint.py create mode 100644 tests/unit/agents/test_group_config.py diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 1beaf717..ca7ef424 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -3541,17 +3541,398 @@ registered names in the message; and the default hook returning `None`. **Verified not vacuous:** with the `_bind_runtime` call removed, 14 of the 18 fail -- the four that survive are the ones asserting that *nothing* is bound. +### An ambiguous name fails at startup, wherever it comes from + +Raised by the user against phase 7's open point, and the reason given is the right frame for it: +a registry name is what appears in every log line, span and health entry, so **two components +that share one -- or one whose name does not say which agent it belongs to -- cannot be told +apart when someone is reading the logs.** That has to fail while the process is starting, not be +disambiguated silently or, worse, resolved by dropping one of them. + +Four paths could produce an ambiguous name. All four are closed. + +**1. An explicit `name=` reached `Component` verbatim.** The derived name was qualified with the +namespace; an explicit one was not: + +```python +- self._name = name or qualified_component_name(self._namespace, camel_to_snake(self.__class__.__name__)) ++ self._name = qualified_component_name(self._namespace, name or camel_to_snake(self.__class__.__name__)) +``` + +So `AgentRuntime(name="planner")` built inside `namespace_scope("orders")` registered as +`planner`. The log line said `planner` and nothing about which agent's, and a second agent's +`planner` collided on the key. `AppBuilder._register` had been compensating by qualifying after +construction; it now assigns the bare name and lets the setter do it, so the rule lives in one +place instead of two. + +**2. `Component.name`'s setter took the new name verbatim** -- the same hole, reachable by any +component doing `self.name = "..."`. It qualifies now. + +**3. `Registry.update_component_name` silently dropped whatever held the target name.** It was: + +```python + self._components[new_name] = self._components.pop(old_name) +``` + +Renaming one component onto another's name **removed the other from the registry**, and the only +symptom was a collaborator that could no longer be found -- no error, no log. It now refuses, +naming what is there; renaming to the name a component already has is a no-op rather than a +failure, which is what makes the qualifying setter safe to call twice. + +**4. `AppBuilder.with_namespace` deduplicated a repeated agent name.** Declaring `orders` twice +quietly merged two agents' components into one namespace: + +```python + if namespace in self._namespaces: + raise ValueError( + f"Namespace '{namespace}' is already hosted by this process, so it cannot be declared again. Two " + "agents cannot share a name: the name is what identifies an agent in every log line, span, queue " + "group, durable and cache partition, ..." + ) +``` + +The agent name is the strongest case of the user's point: it reaches the queue group, the +JetStream durable and the cache partition as well as the logs, so two agents under one name are +indistinguishable to the broker too. The message names the legitimate case it might be mistaken +for -- one agent assembled from several parts -- and says to compose those into a single +`AgentRegistration` instead. + +**`qualified_component_name` is deliberately *not* idempotent**, and finding out why was the one +surprise here. Skipping the prefix when a name already appears to carry it looks like a safeguard +against `orders_orders_db`; it is worse than the problem. A base name can legitimately begin with +the namespace -- `BillingHandler` in namespace `billing` derives `billing_handler` -- and such a +component would then register *unqualified*, which is exactly the ambiguity being removed. It was +implemented that way first and a test caught it. "Already prefixed" is not decidable from the +string, so it is not guessed; the docstring says so, and there is a test for the +`BillingHandler`-in-`billing` case. The cost is that a caller who qualifies a name itself gets it +qualified twice -- redundant, still unambiguous, and no framework code does it. + +**The duplicate-name error now says what to do.** `add_component`'s message was `Component with +name X already exists`, which in a group does not say whose or why: + +```python + f"Component name '{name}' is already taken by a {existing}, so {type(component).__name__} in namespace " + f"'{agent}' cannot register under it. Registry names have to be unique across the whole process: they " + "are what identifies a component in logs, spans and health entries, and two components sharing one " + "name cannot be told apart afterwards. A name is qualified with its namespace automatically, so this " + "is either two components of one class in one agent, or two explicit names that collide -- pass a " + "distinct 'name=' to one of them." +``` + +Tests: `tests/unit/agents/component/test_name_uniqueness.py`, 16 cases -- a directly constructed +component qualified, two agents each holding a `planner`, the root keeping the bare name, a +rename qualified and a root rename unchanged; the `BillingHandler`-in-`billing` case and the +qualifier being a plain prefix; two components of one class in one agent colliding, two explicit +names colliding, the message naming the agent and the fix, and a root component not colliding +with an agent's; renaming onto a taken name refused with the other component still registered +afterwards, renaming to the same name and to a component's own qualified name both no-ops, and +renaming from an unregistered name still raising. `test_namespace_builder.py`'s dedupe test became +two refusal tests. + +### One name per agent: the name given in code, with `app_name` as the fallback + +Raised by the user, whose premise was worth checking first: the namespace is **not** derived from +`app_name`. It never was -- an agent's name comes from `with_namespace("orders")` in code, and +config supplies nothing. But the instinct behind the question was right, because config was +supplying a *second* name for the same agent, and two of the places that read it were wrong. + +The rule now, stated once: **the name given in code is the agent's identity; `app_name` is used +only when no name was given, and is otherwise a display string for the process.** + +**1. An agent no longer has to restate its name in config.** `Config(agent_scope=...)` carried +`Validator(f"{agent_scope}.app_name", must_exist=True)`, so every agent in a group had to declare +an `app_name` of its own -- a second name, free to disagree with the first. The same agent could +be `orders` in the registry, the queue group, the durable and the cache partition, and +`Order Processing` in a dashboard. The validator is gone. `app_name` stays a root key for the +OpenAPI title, `/info` and `/status/build`, and an agent may still set one *for display* without +it touching identity. + +**2. Telemetry identity was the display name, which breaks C2.** `otel_service_name` defaulted to +`app_name`, so an agent's `service.name` was whatever `app_name` said: + +```python + def _resolve_service_name(self) -> str: + if self._agent_scope: + scoped = self._settings.get(f"{self._agent_scope}.otel_service_name") + return str(scoped) if scoped else self._agent_scope + return str(self.get("otel_service_name", self.get("app_name", "agent-service"))) +``` + +A scoped view answers with its own `otel_service_name` if the agent set one, and otherwise with +the **namespace**. Note what it deliberately does *not* do: fall back to the root's +`otel_service_name`. That is the one place a scoped read must not, because inheriting it would +give every agent in a group the same `service.name` -- and then regrouping moves work between +agents that no dashboard can tell apart, which is the whole of what C2 forbids. The root view +keeps the old chain exactly, so a single-agent application's dashboards do not move. + +**3. A namespaced scheduler derived its tick subject from `app_name`.** This was a live defect +left behind by a placeholder: + +```python +- # ROOT_NAMESPACE is still "" for every component; phase 2 is what gives this a value. +- identity = ROOT_NAMESPACE or str(self.config.get("app_name", "") or "").strip() ++ identity = self.namespace or str(self.config.get("app_name", "") or "").strip() +``` + +`ROOT_NAMESPACE` is the module constant `""`, so the expression was *always* `app_name`. The +comment says phase 2 would give it a value -- phase 2 landed, `self.namespace` has one, and +nothing came back to this line. The consequence: two agents in a group each with a `nightly` +scheduler derived the same tick subject and would have consumed each other's ticks, and moving an +agent between groups could change the subject its external `CronJob` publishes to, which is +exactly what C1 forbids. The `source` string on the next line had the same inversion, so the +error message named the wrong key. Both fixed, with two regression tests that fail against the old +expression. + +Everything else that reads `app_name` was already right and is untouched: the NATS queue group +(`if self.namespace: return self.namespace`, then `nats_queue_group`, then `app_name`), and the +display readers. + +**Which of these are breaking, precisely.** The `otel_service_name` change is, and it is listed as +*Breaking change 2* under *Compatibility*: `Config(agent_scope=...)` is not new -- it landed in +April and is on `develop` -- so a repo already using it sees its `service.name` change. The +dropped validator is a loosening: configuration that was valid stays valid. The scheduler subject +is **not** breaking for anything deployed, because a scheduler can only have a namespace if it was +built inside a `namespace_scope`, which is branch-new; the *Compatibility* bullet says so rather +than claiming a break that cannot happen. + +Tests: `tests/unit/agents/config/test_agent_identity.py`, 8 cases -- an agent's service name being +its own name, an agent overriding it for itself, the root's override *not* leaking into an agent, +a single-agent application still reading `app_name`, an explicit root override still winning at +the root, the default when there is neither, and `app_name` staying readable and settable for +display without touching identity. Two cases added to `test_scheduler.py` for the namespaced tick +subject, and `test_agent_scope.py`'s "missing scoped app_name raises" became "an agent does not +have to restate its name". + +**Not touched, deliberately:** `black --check` still fails on `config/config.py`, and did at HEAD too -- it is one of the files `CLAUDE.local.md` documents as +disputed between `black` and `ruff format`. `black` reformatted a pre-existing ternary there when +run over the changed files; that reformat was reverted, because accepting it would have started +the ping-pong the two formatters play over that file. + +### Phase 8 -- the group becomes a running process + +Everything before this made a group *possible*; nothing made one *start*. This is the phase that +turns a deployment decision into a process: which agents run here arrives at container start, +and the code that reads it is the only code allowed to. + +Three commits, split along the one line the plan is emphatic about -- **resolution versus +wiring**. Environment reads, file reads and `sys.exit` stay out of `AppBuilder`, so it remains a +pure function of its call sequence and a test can state an exact composition without controlling +the environment or the filesystem. + +#### `GroupConfig` and its resolution (`d00ca03`) + +Two files, and their different lifetimes are the reason there are two rather than one: + +- **`agents.toml`** says which agents this *image* contains and where their declarations live. + It changes only when an agent is added or removed -- a rebuild anyway -- so it is baked in. +- **`deployment-groups.yaml`** says which of them *this process* runs. Never baked in, since one + image serves every group, so it arrives as a mount or is replaced entirely by environment + variables. + +`GroupConfig.resolve` is the only member that reads either, plus the environment: + +```python + declared = cls._read_group_file(env, root) + name, agent_names, critical_names, cache_names = cls._apply_env_overrides(env, declared) + ... + agent_map = cls._read_agent_map(env, root) + agents = cls._resolve_agents(agent_names, critical_names, agent_map, name) +``` + +**Environment overrides the file key by key** (spec sec. 5.1), so a Deployment changes the agent +list without restating the group's name or its caches, and each resolved value is logged with the +source it came from -- "which agents did this pod actually start" being the first question asked +of a group that misbehaves. + +One rule the spec does not state and the tests forced out: **when `BLUEPRINT_AGENTS` supplies the +group and `BLUEPRINT_GROUP` names none, the file is not read at all.** That is the `docker run` +and CI shape from sec. 5.1, and reading the file anyway made an unrelated multi-group file in the +image *ambiguous* -- for nothing, because with no group named no slice of it applies and the only +value it would have contributed is already overridden. + +**Every way of getting a group wrong is a startup failure**, because the alternative is a pod +that passes its probes with a queue nobody is consuming: an agent the image does not contain, an +agent named twice, a name that cannot be a namespace, an unknown group, a malformed or +`groups`-less file, a missing or malformed agent map. Each message names what it found and what it +expected. `critical` defaults to `True` for the reason sec. 9.1 gives -- a group short one +consumer is worse than no pod -- and a *non*-critical agent missing from the map is skipped with +an ERROR instead, since that flag is the deployment saying it would rather run the rest. + +Two details worth their lines. `AgentSpec.name` is put through `validate_namespace`, because it +*becomes* a namespace: rejecting it here names the group file, while letting it through would +surface as a validation error from inside some component's constructor. And PyYAML is imported +inside the parse rather than at module scope -- it is not a declared dependency of this package, +it arrives with `uvicorn[standard]`, so a module-level import would break importing *anything* +from the package in an installation that trimmed it. See *Open points*. + +#### `with_group` and `from_group` (`71dfbb1`) + +```python + for spec in group.agents: + registration = self._load_registration(spec) + if registration is None: + continue + self.with_namespace(spec.name, registration=registration) + + for cache_name in group.cache_names: + self.with_cache(name=cache_name) +``` + +The caches are the group's rather than any agent's, because a cache is process-wide (spec +sec. 8) -- so phase 3 part 2's `with_cache(name=...)` is what the group's `cache_names` feed. + +Importing an agent's module is the one thing here that reaches outside, and it is deliberately on +this side of the resolution/wiring line: it is driven entirely by the `module` strings the group +carries, so a test points them at test modules and controls neither environment nor filesystem to +do it. Imports happen **per group**, so cold start is proportional to the agents this process +hosts rather than to the agents the image contains. + +`_load_registration` catches **every** exception from the import, not `ImportError` alone: +importing a module runs it, and an agent whose declaration raises at import is exactly as +unloadable as one whose module is absent. It also refuses an attribute that is not an +`AgentRegistration`, and a `module` string that is not `package.module:attribute` -- both of which +would otherwise fail later and further away. + +A critical agent that cannot be loaded raises `GroupConfigError`; a non-critical one is skipped +with an ERROR and the rest of the group still starts. The flag is read *before* the agent is +wired rather than after an exception, because there is no partial build to unwind: one process, +one `build()`. + +#### The entry point (`029f287`) + +`python -m blueprint.agents.entrypoint`, and it exists to hold the three things `AppBuilder` must +not: reading the environment, reading files, and exiting. + +```python +def build(*, environ: dict[str, str] | None = None) -> tuple[FastAPI, Config]: + config = Config(settings_files=DEFAULT_SETTINGS_FILES) + group = GroupConfig.resolve(config, environ=environ) + app = AppBuilder(config).with_group(group).build() + return app, config +``` + +Split from `main` so the whole startup path is testable without a server and without +`sys.exit`: everything that can fail happens in `build`, and `main` only decides what to do about +it. `main` returns a status rather than exiting, so a test asserts on the status; the +`__main__` guard is what turns it into an exit. + +**Why it catches rather than lets the exception out.** A group that cannot be resolved must stop +the process *before the port is bound* (spec sec. 9.1), so Kubernetes crash-loops with a readable +message instead of reporting a healthy replica that is silently short a consumer. An uncaught +exception also exits non-zero, but buries the one line an operator needs under a traceback of +framework internals. The reason is `print`ed to stderr *as well as* logged, because logging is +configured by `AppBuilder` -- which has not run yet when resolution fails. + +A project keeps its own `main.py` if it wants: a standalone deployment is untouched, and +`uvicorn src.main:app` works exactly as before. + +#### Not in this phase, and why + +- **The settings-fragment merge.** The plan lists it here; the changelog's *Open points* has + carried it since config rework step 3a with **two unanswered questions** -- whether a fragment + declaring `envvar_prefix` is rejected, and whether a fragment may override a shared + infrastructure key at all. Both are decisions rather than implementations, and guessing either + produces a merge that silently drops or silently overrides configuration. Still open. +- **`on_startup` raising** -- the third row of sec. 9.1's failure table. It says "mark namespace + down, pause consumers (C4), continue", which is phase 9's per-namespace degradation machinery, + not something to improvise here. +- **`deployment-groups.yaml` and `agents.toml` are not generated.** Phase 8 *reads* them; the + scaffolder writing them belongs with the manifest generation that is already parked. + +Tests: `tests/unit/agents/test_group_config.py` (33 cases), `test_with_group.py` (24) and +`test_entrypoint.py` (12) -- 69 in total. The group file and the environment as sources and in +combination, precedence and its logging, criticality from both sources, every validation failure, +the value object's freezing; one namespace per agent with order preserved, the group's caches, +every declaration-loading failure for critical and non-critical agents, and that `with_group` +ignores the environment even when it is set; and the entry point building from either source, +serving what it built, and returning non-zero with the reason on stderr without binding a port. + +### `build()` did not change, and one `main.py` does serve both shapes + +Both raised by the user against phase 8, and the first was a fair misreading of a name I chose +badly. + +**`AppBuilder.build()` still returns a `FastAPI`.** Nothing about it changed in phase 8, and no +existing `main.py` needs editing. The function that returns a tuple was `entrypoint.build()` -- a +*different* function, in a module nothing imported before this phase. But a second `build` in the +same package returning a different shape is exactly the trap it looks like, so it is now +`entrypoint.build_group_app()`, with the reason in its docstring and a test asserting that +`entrypoint.build` does not exist. The lesson is worth keeping: `build` is spoken for in this +package. + +**One `main.py` for both shapes is not merely possible, it is what spec sec. 11 requires** -- and +it already works. The single declaration the spec asks for is the whole file: + +```python +registration = ( + AgentRegistration() + .with_service(OrderService) + .with_handler(OrderValidationHandler) + .with_rest_api(OrderApi) +) +``` + +No `AppBuilder`, no `Config`, no `run_app`, no `if __name__`, no namespace, no group. The same +object then serves three deployments, which `TestOneDeclarationServesBothDeploymentShapes` now +pins down rather than asserting: + +| Deployment | How | What runs | +|---|---|---| +| Standalone, as today | `AppBuilder(config).with_registration(registration).build()`, `uvicorn src.main:app` | root namespace | +| Alone, as a group of one | `BLUEPRINT_AGENTS=order python -m blueprint.agents.entrypoint` | namespace `order` | +| Beside other agents | `BLUEPRINT_AGENTS=order,billing ...` | namespaces `order`, `billing` | + +The dual-branch `main.py` the plan once described -- the component list duplicated under +`if __name__ == "__main__"` and `else:` -- is what the spec forbids, and nothing in the +implementation needs it: `agents.toml` points at `main:registration` like any other module, and a +group of one is an ordinary group. + +**The one consequence to know about, and it is deliberate.** A group of one is *not* identical to +standalone, because it uses the agent's real name: components become `order_order_service` rather +than `order_service`, routes move from `/api/...` to `/api/order/...`, and the queue group becomes +`order` rather than `app_name`. Spec sec. 11 chooses this on purpose -- "a dev mode that ran at +`namespace=""` would give every developer local URLs and integration tests that differ from +production" -- so local and CI match the deployment instead of diverging from it. Migrating an +existing agent from standalone to a group of one therefore moves its routes and its consumer +identity, which is a migration with consequences rather than a rename; phase 10 is where that gets +written up for a project to follow. + --- ## Compatibility -**One breaking change has landed: `scheduler_mode` is required.** A project that registers a +**Two breaking changes have landed.** The second one only affects a project that already uses +`Config(agent_scope=...)`; the scheduler change discussed further down is deliberately *not* on +this list, and why is stated with it. + +**Breaking change 1: `scheduler_mode` is required.** A project that registers a scheduler and does not set it fails at `build()` with an error naming both values and what each one costs. Nothing changes behaviour silently: the alternative -- defaulting the key -- would either keep firing a timer per replica (#73) or stop ticking a service that has no broker, and neither is safe to inherit. The reasoning, including the counter-argument, is under *P5* above; it is a deliberate departure from spec sec. 7.5 and needs a spec amendment. +**Breaking change 2: a scoped `Config`'s telemetry `service.name` is now the agent's name.** +This affects a project that constructs `Config(agent_scope="foo")` -- which is not new, it has +been available since April and is on `develop`, so this is a change to shipped behaviour rather +than to something only this branch can reach. + +| | Was | Is | +|---|---|---| +| `otel_service_name` for a scoped view | `.otel_service_name`, else root `otel_service_name`, else `.app_name`, else root `app_name` | `.otel_service_name`, else the scope name | + +So a repo with `foo.app_name = "Foo Service"` and no `foo.otel_service_name` sees its +`service.name` change from `Foo Service` to `foo`, and one relying on a *root* +`otel_service_name` while using a scope sees it change to the scope name as well. The root path is +untouched, so a project that passes no `agent_scope` -- every single-agent application -- is +unaffected. + +**Migration** is one line if the old name matters: set `.otel_service_name` to whatever the +dashboards already key on. Keeping the old chain was the alternative and is what C2 forbids: it +lets every agent in a group report one `service.name`, and then regrouping moves work between +agents no dashboard can tell apart. The point of the change is that the agent's name is the one +identity it has. + **Migrating an existing service with a scheduler** is one line, and which line depends on the deployment: @@ -3614,6 +3995,47 @@ Everything else remains non-breaking. Specifically: Whether Dapr merges the two or delivers twice needs checking against a real sidecar; it belongs on the broker-test list. - New config keys all default to current behaviour. +- **Phase 8 is entirely additive.** A standalone `main.py` deployment is untouched: nothing + reads `deployment-groups.yaml` or `agents.toml` unless `python -m blueprint.agents.entrypoint` + or `GroupConfig.resolve` is called, and `uvicorn src.main:app` behaves exactly as before. +- **New environment variables, all optional**: `BLUEPRINT_GROUP_CONFIG`, `BLUEPRINT_GROUP`, + `BLUEPRINT_AGENTS`, `BLUEPRINT_CRITICAL_AGENTS`, `BLUEPRINT_AGENT_MAP`. They are read only by + the group resolution, never by `Config`, so they cannot collide with a project's settings. +- **`pyyaml>=6.0` is a new declared dependency.** Asked for and approved; it is what reads the + group file. Already present in every environment through `uvicorn[standard]`, so declaring it + changes no installed set -- it stops the group file depending on a *transitive* dependency, + which is the thing that breaks on an unrelated upgrade. +- **`.app_name` is no longer required.** A scoped `Config` used to refuse to load without + it. Setting one is still allowed and still read, but only for display. +- **An agent's `otel_service_name` now defaults to its own name rather than to `app_name`, and no + longer inherits a root-level `otel_service_name`.** A single-agent application is unchanged: + explicit `otel_service_name`, then `app_name`, then the default. A grouped agent's + `service.name` becomes its agent name unless it sets its own -- which is the point (C2), and + which does change what a dashboard sees for a project that had been relying on the root value + while using namespaces. +- **A namespaced scheduler's derived tick subject changes from `.scheduler.` to + `.scheduler.` -- and this is deliberately *not* counted as a breaking change.** + A scheduler's namespace is only non-empty when it was constructed inside a `namespace_scope`, + which exists only on this branch: `SchedulerBase.__init__` never took a namespace, and + `Component`'s namespace parameter arrived with P6. So no deployed scheduler can have one, and + no `CronJob` in the field publishes to a namespaced subject. A root scheduler -- every one that + exists -- derives exactly what it derived before. + + It *is* a change for anyone who adopted this branch mid-flight and gave a scheduler a + namespace: their tick subject moves, and the publisher has to move with it. The startup log + names the subject in both modes, which is where to read the new value. Note also that + `Config(agent_scope=...)` alone does **not** give a scheduler a namespace -- a scoped config and + a component's namespace are different things before this branch -- so a project using + `agent_scope` today is unaffected by this one. +- **An explicit `name=` is now namespace-qualified, wherever it is set.** At the root -- every + single-agent application -- `qualified_component_name("", name)` is `name`, so nothing changes. + Inside a namespace, a component constructed directly with `name="planner"` registers as + `orders_planner` where it used to register as `planner`. The builder path already behaved this + way. +- **`Registry.update_component_name` refuses a name that is taken** instead of overwriting the + entry. Anything relying on the overwrite was losing a component silently. +- **`AppBuilder.with_namespace` refuses an agent name it already hosts** instead of merging into + it. To assemble one agent from several parts, compose them into one `AgentRegistration`. - **`EventHandlerBase.get_runtime_name(event, context)` is new and defaults to `None`.** It was already in the class's usage docstring, so a project may have written one; it is now actually called. Returning `None` keeps today's behaviour. @@ -3838,12 +4260,6 @@ stay keyword-only and last, or an existing `with_cache(False)` would silently be application that has two agents and handlers resolving their own runtime by name -- the shape the scaffolder generates. The spec's compatibility table already calls phase 7 "purely additive", which the raise would contradict; the plan bullet is what should change. -- **An explicit `name=` is qualified with the namespace only on the builder path.** Constructing - a component directly inside a `namespace_scope` with `name="planner"` registers it as - `planner`, so two agents doing that collide on one registry key. `AppBuilder._register` - qualifies; `Component.__init__` does not. Fixing it there would change naming for every - component and wants its own step. - - **P0-P5 have landed. P6 is next**, and two requirements for it were settled during P5 (see the namespace bullet below). What remains open from P5 is deferred work rather than unfinished work: both modes now fire a cron once across three replicas, which was P5's acceptance criterion. diff --git a/pyproject.toml b/pyproject.toml index 2a487dc3..905b6cda 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,6 +41,7 @@ dependencies = [ "diskcache-rs>=0.4.4", "nats-py>=2.13.1", "croniter>=6.0.0", + "pyyaml>=6.0", "pytest", "pytest-asyncio" ] @@ -171,6 +172,7 @@ module = [ "croniter", "dapr.*", "nats.*", + "yaml", ] ignore_missing_imports = true diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index 0af06f2d..8c41a490 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -1,5 +1,6 @@ """Generic FastAPI application setup and configuration.""" +import importlib import logging from collections.abc import AsyncIterator, Callable, Iterator, Mapping from contextlib import asynccontextmanager, contextmanager @@ -13,7 +14,7 @@ from .io.api.actuators.health import HealthCheckerBase from .component.component import Component -from .component.namespace import ROOT_LABEL, ROOT_NAMESPACE, namespace_of, namespace_scope, qualified_component_name, validate_namespace +from .component.namespace import ROOT_LABEL, ROOT_NAMESPACE, namespace_of, namespace_scope, validate_namespace from .component.registry import DEFAULT_CACHE_NAME, Registry from .agent.agent_runtime import AgentRuntime from .handler.event_handler_base import EventHandlerBase @@ -35,6 +36,7 @@ from .services.sessions import SessionKeyProvider, SessionsApiClient from .services.infrastructure.cache_backend_factory import CacheBackendFactory from .config import Config, TelemetryManager +from .group_config import AgentSpec, GroupConfig, GroupConfigError from .utils import parse_bool HandlerT = TypeVar("HandlerT", bound=EventHandlerBase) @@ -429,12 +431,21 @@ def with_namespace(self, name: str, *, registration: AgentRegistration | None = "application." ) + if namespace in self._namespaces: + raise ValueError( + f"Namespace '{namespace}' is already hosted by this process, so it cannot be declared again. Two " + "agents cannot share a name: the name is what identifies an agent in every log line, span, queue " + "group, durable and cache partition, so a second agent under it would be indistinguishable from the " + "first and their components would merge into one registry namespace. Give one of them a different " + "name, or -- if this is one agent assembled from several parts -- compose the parts into a single " + "AgentRegistration and apply that once." + ) + # Recorded before anything is built, so that a registration failing half way through # still leaves the namespace declared: the startup log and the readiness policy have to # be able to say that an agent was meant to be here. - if namespace not in self._namespaces: - self._namespaces.append(namespace) - logger.info("Hosting agent namespace '%s'", namespace) + self._namespaces.append(namespace) + logger.info("Hosting agent namespace '%s'", namespace) if registration is None: return NamespaceBuilder(self, namespace) @@ -455,6 +466,132 @@ def namespaces(self) -> tuple[str, ...]: """ return tuple(self._namespaces) + @classmethod + def from_group(cls, config: Config, *, environ: dict[str, str] | None = None) -> "AppBuilder": + """Resolve this process's group and apply it, in one call. + + The convenience form of the entry point's first two lines. Kept separate from + :meth:`with_group` because this one performs I/O -- it is ``GroupConfig.resolve`` that + reads the environment and the group file -- while ``with_group`` does not, and a test + that wants an exact composition needs the half that does not. + + Args: + config: The application's configuration. + environ: The environment to resolve from, for tests. + + Returns: + A builder with every agent in the group applied. + + Raises: + GroupConfigError: if the group cannot be resolved. See ``GroupConfig.resolve``. + """ + return cls(config).with_group(GroupConfig.resolve(config, environ=environ)) + + def with_group(self, group: GroupConfig) -> "AppBuilder": + """Apply every agent in ``group``, and register the caches the group declares. + + **Performs no I/O of its own**, which is what keeps this class a pure function of its + call sequence: no environment reads, no file reads, no ``sys.exit``, and no knowledge of + an agent repo's layout. Those belong to ``GroupConfig.resolve`` and to the entry point, + so a test can state an exact composition by constructing a ``GroupConfig`` literally. + + Importing an agent's module is the one thing here that reaches outside, and it is + deliberately on this side of the line: it is driven entirely by the ``module`` strings + the group carries, so a test points them at test modules and controls neither the + environment nor the filesystem to do it. Imports happen **per group**, so cold start is + proportional to the number of agents this process actually hosts rather than to the + number the image contains. + + A critical agent that cannot be loaded raises, which the entry point turns into a + non-zero exit before the port is bound. A non-critical one is skipped with an ERROR: + that flag is the deployment saying it would rather run the rest (spec sec. 9.1). The + flag is read *before* the agent is wired rather than after an exception, because there + is no partial build to unwind -- one process, one ``build()``. + + Args: + group: The resolved group. + + Returns: + This builder. + + Raises: + GroupConfigError: if a critical agent's module or registration cannot be loaded. + """ + logger.info( + "Applying group '%s': %d agent(s), %d declared cache(s)", + group.name, + len(group.agents), + len(group.cache_names), + ) + + for spec in group.agents: + registration = self._load_registration(spec) + if registration is None: + continue + self.with_namespace(spec.name, registration=registration) + + for cache_name in group.cache_names: + self.with_cache(name=cache_name) + + return self + + @staticmethod + def _load_registration(spec: AgentSpec) -> AgentRegistration | None: + """Import an agent's declaration, or report why it could not be loaded. + + Returns: + The registration, or ``None`` when a non-critical agent could not be loaded and is + to be skipped. + + Raises: + GroupConfigError: if a critical agent cannot be loaded. The message names the agent + and the module path it came from, because the two are declared in different + files -- the agent name in the group file or an environment variable, the module + in the image's agent map -- and which of them is wrong is the first thing to + establish. + """ + module_path, _, attribute = spec.module.partition(":") + if not module_path or not attribute: + return AppBuilder._skip_or_raise( + spec, + f"'{spec.module}' is not a valid declaration path. Write it as 'package.module:attribute', naming the " + "AgentRegistration the module assigns.", + ) + + try: + module = importlib.import_module(module_path) + except Exception as exc: + # Every exception, not only ImportError: importing a module runs it, so anything its + # top level does can fail here, and an agent whose declaration raises on import is + # exactly as unloadable as one whose module is absent. + return AppBuilder._skip_or_raise(spec, f"importing '{module_path}' raised {type(exc).__name__}: {exc}", exc) + + registration = getattr(module, attribute, None) + if registration is None: + return AppBuilder._skip_or_raise( + spec, f"module '{module_path}' has no attribute '{attribute}', so its declaration cannot be read." + ) + if not isinstance(registration, AgentRegistration): + return AppBuilder._skip_or_raise( + spec, + f"'{spec.module}' is a {type(registration).__name__}, not an AgentRegistration. An agent's " + "declaration is the object its components are declared on.", + ) + logger.debug("Loaded the declaration for agent '%s' from '%s'", spec.name, spec.module) + return registration + + @staticmethod + def _skip_or_raise(spec: AgentSpec, reason: str, cause: BaseException | None = None) -> None: + """Raise for a critical agent, or log and skip a non-critical one. + + Raises: + GroupConfigError: when ``spec`` is critical. + """ + if spec.critical: + raise GroupConfigError(f"Agent '{spec.name}' could not be loaded and is critical: {reason}") from cause + logger.error("Agent '%s' could not be loaded and is not critical, so it is skipped: %s", spec.name, reason) + return None + @property def hosted_namespaces(self) -> tuple[str, ...]: """Every namespace this process serves: the root first, then each declared agent. @@ -566,12 +703,11 @@ def _register(target: Any, namespace: str, kwargs: Mapping[str, Any], *, name: s instance = target if name is not None: - # Qualified for the same reason Component.__init__ qualifies a derived name: one - # registration applied to two agents would otherwise register both under the one - # literal name, and the second would fail on the collision. It stays findable by - # the bare name the caller wrote, because Registry._lookup tries - # '_' before ''. - instance.name = qualified_component_name(namespace_of(instance), name) + # Assigned bare: the setter qualifies it with the component's own namespace, which is + # the single place that rule lives now. One registration applied to two agents + # therefore registers 'orders_db' and 'billing_db' rather than colliding on 'db', + # and either stays findable by the bare name because Registry._lookup qualifies too. + instance.name = name return instance def with_cache(self, enabled: bool = True, enable_locking: bool = True, *, name: str = DEFAULT_CACHE_NAME) -> "AppBuilder": diff --git a/src/blueprint/agents/component/component.py b/src/blueprint/agents/component/component.py index a0d456b0..877ea795 100644 --- a/src/blueprint/agents/component/component.py +++ b/src/blueprint/agents/component/component.py @@ -144,7 +144,12 @@ def __init__(self, should_register: bool = True, name: str | None = None, namesp # and treating that as a decision would pin every developer-written component to the # root and make the ambient scope apply to nothing that matters. self._namespace = validate_namespace(namespace or current_namespace()) - self._name = name or qualified_component_name(self._namespace, camel_to_snake(self.__class__.__name__)) + # An explicit name is qualified exactly like a derived one. It used to be taken + # verbatim, which made a component's registry key -- the name that appears in every log + # line, health entry and span -- say nothing about which agent it belonged to. Two + # agents in a group each with a 'planner' were then one indistinguishable 'planner' in + # the logs, and the second one to register collided on the key. + self._name = qualified_component_name(self._namespace, name or camel_to_snake(self.__class__.__name__)) if should_register: self.registry.add_component(self.name, self) @@ -155,9 +160,20 @@ def name(self) -> str: @name.setter def name(self, value: str) -> None: - """Set the component name. Also updates the name in the component registry.""" - self.registry.update_component_name(self._name, value) - self._name = value + """Rename the component, in the registry as well as on the instance. + + The new name is qualified with this component's namespace, for the same reason the + constructor qualifies one: a name that does not carry its agent is a name that cannot be + told apart from a neighbour's in a log. ``qualified_component_name`` is idempotent, so a + caller that has already qualified the name is not punished for it. + + Raises: + ValueError: if the component is not registered under its current name, or if the new + name is already taken -- see ``Registry.update_component_name``. + """ + qualified = qualified_component_name(self._namespace, value) + self.registry.update_component_name(self._name, qualified) + self._name = qualified @property def namespace(self) -> str: diff --git a/src/blueprint/agents/component/namespace.py b/src/blueprint/agents/component/namespace.py index 83778255..32d523fd 100644 --- a/src/blueprint/agents/component/namespace.py +++ b/src/blueprint/agents/component/namespace.py @@ -202,6 +202,20 @@ def qualified_component_name(namespace: str, base_name: str) -> str: The root namespace keeps the bare name, so an existing application's registry keys -- ``nats_client``, ``event_publishing_service`` -- do not change and neither do the lookups and health-check entries that use them. + + Every name a component can be given passes through here: the one derived from its class, an + explicit constructor argument, and an assignment to ``Component.name``. So a name always + carries the agent it belongs to, which is what lets two agents' components be told apart in + a log. + + **Deliberately not idempotent.** Skipping the prefix when a name already starts with it + looks like a safeguard against ``orders_orders_db`` and is worse than the problem: a base + name can legitimately begin with the namespace -- ``BillingHandler`` in namespace + ``billing`` derives ``billing_handler`` -- and such a component would silently register + unqualified, which is exactly the ambiguity the qualification exists to remove. "Already + prefixed" is not decidable from the string, so it is not guessed. The cost is that a caller + who qualifies a name itself gets it qualified twice; the result is redundant but still + unambiguous, and no framework code does it. """ return base_name if not namespace else f"{namespace}_{base_name}" diff --git a/src/blueprint/agents/component/registry.py b/src/blueprint/agents/component/registry.py index 0fe83ed1..dcda4ad9 100644 --- a/src/blueprint/agents/component/registry.py +++ b/src/blueprint/agents/component/registry.py @@ -383,22 +383,52 @@ def add_component(self, name: str, component: Any) -> None: raise ValueError(f"component must be an instance of {self._component_class}") if name in self._components: - raise ValueError(f"Component with name {name} already exists") + existing = type(self._components[name]).__name__ + agent = namespace_of(component) or ROOT_LABEL + raise ValueError( + f"Component name '{name}' is already taken by a {existing}, so {type(component).__name__} in namespace " + f"'{agent}' cannot register under it. Registry names have to be unique across the whole process: they " + "are what identifies a component in logs, spans and health entries, and two components sharing one " + "name cannot be told apart afterwards. A name is qualified with its namespace automatically, so this " + "is either two components of one class in one agent, or two explicit names that collide -- pass a " + "distinct 'name=' to one of them." + ) logger.info("Adding component: %s to registry", name) self._components[name] = component def update_component_name(self, old_name: str, new_name: str) -> None: - """Update the name of a component in the registry. + """Rename a registered component, refusing to take a name that is in use. + + The refusal is the point. This used to be ``self._components[new_name] = pop(old_name)``, + which **silently dropped** whatever was registered under ``new_name`` -- so renaming one + component onto another's name removed the other from the registry entirely, and the only + symptom was a collaborator that could no longer be found. Two components asking for one + name has to surface where it happens. Args: - old_name: The old name of the component - new_name: The new name of the component + old_name: The name the component is currently registered under. + new_name: The name to move it to, already namespace-qualified by the caller. + + Raises: + ValueError: if nothing is registered under ``old_name``, or if ``new_name`` is + already taken by a different component. """ if old_name not in self._components: raise ValueError(f"Component with name {old_name} does not exist") + if new_name == old_name: + return + + if new_name in self._components: + existing = type(self._components[new_name]).__name__ + raise ValueError( + f"Cannot rename '{old_name}' to '{new_name}': that name is already taken by a {existing}. Registry " + "names identify a component in logs, spans and health entries, so the rename would have left two " + "components indistinguishable -- and the one already there unreachable. Choose another name." + ) + logger.info("Updating component name from %s to %s", old_name, new_name) self._components[new_name] = self._components.pop(old_name) diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index be6613dd..08ae01e4 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -142,7 +142,15 @@ def __init__( f"{self._envvar_prefix}_*" if self._envvar_prefix else "the whole process environment, unprefixed", ) - # Validators differ when scoped: app_name is per agent, app_port is not. + # A scoped view validates neither app_name nor a per-agent port. + # + # `app_name` is **not** required per agent, and must not be: an agent's identity is the + # namespace it was given in code, and that is what reaches the registry, the queue + # group, the durable, the cache partition and its telemetry service name. Requiring + # `.app_name` made every agent carry a *second* name, free to disagree with the + # first -- so the same agent could be `orders` on the broker and `Order Processing` in + # a dashboard, which is precisely the confusion having one name is supposed to avoid. + # `app_name` stays a root key for display: the OpenAPI title, `/info`, `/status/build`. # # A group is one process behind one HTTP server, so only one port can be bound no # matter how many agents share it. Requiring `.app_port` would make every @@ -150,7 +158,6 @@ def __init__( # root key and is validated as one. if agent_scope: validators = [ - Validator(f"{agent_scope}.app_name", must_exist=True), Validator("app_port", must_exist=True, is_type_of=int, default=8000), Validator("app_environment", must_exist=True, default="development"), ] @@ -750,10 +757,31 @@ def get_observability_config(self) -> ObservabilityConfig: return ObservabilityConfig( otel_enabled=self.get("otel_enabled", False), otel_endpoint=self.get("otel_endpoint"), - otel_service_name=self.get("otel_service_name", self.get("app_name", "agent-service")), + otel_service_name=self._resolve_service_name(), log_level=self.get("log_level", "INFO"), ) + def _resolve_service_name(self) -> str: + """Return the ``service.name`` this view reports to telemetry (C2). + + **An agent's telemetry identity is its agent name.** For a scoped view that is the + namespace, unless the agent overrode ``otel_service_name`` for itself -- and the root's + ``otel_service_name`` deliberately does *not* apply, which is the one place a scoped read + must not fall back. Inheriting it would give every agent in a group the same + ``service.name``, so a regrouping would move work between agents that dashboards cannot + tell apart, and C2 exists to prevent exactly that. + + The root view keeps the old chain untouched -- explicit ``otel_service_name``, then + ``app_name``, then a default -- so a single-agent application's dashboards do not move. + + Returns: + The service name for this view. + """ + if self._agent_scope: + scoped = self._settings.get(f"{self._agent_scope}.otel_service_name") + return str(scoped) if scoped else self._agent_scope + return str(self.get("otel_service_name", self.get("app_name", "agent-service"))) + def get_event_publishing_config(self) -> EventPublishingConfig: """Get complete event publishing configuration. diff --git a/src/blueprint/agents/entrypoint.py b/src/blueprint/agents/entrypoint.py new file mode 100644 index 00000000..59b43308 --- /dev/null +++ b/src/blueprint/agents/entrypoint.py @@ -0,0 +1,97 @@ +"""The container's command: resolve this process's group, build it, and serve it. + +``python -m blueprint.agents.entrypoint``. One image for the whole platform, with the group +injected at container start rather than baked in at build time -- so which agents a pod runs is +a deployment decision and changing it is a Deployment edit, not a rebuild. + +This module exists to hold the three things ``AppBuilder`` must not: reading the environment, +reading files, and exiting the process. Everything it does is four lines; the rest of the file is +about what happens when one of them fails. + +**Why exit rather than raise.** A group that cannot be resolved must stop the process *before the +port is bound* (spec sec. 9.1), so that Kubernetes crash-loops the pod with a readable message +instead of reporting a healthy replica that is silently short one consumer. An uncaught exception +would also exit non-zero, but buries the one line an operator needs under a traceback of +framework internals, so the resolution failures are caught and printed as themselves. + +A project keeps its own ``main.py`` if it wants: a standalone deployment is untouched by any of +this, and ``uvicorn src.main:app`` still works exactly as before. +""" + +import logging +import sys + +from fastapi import FastAPI + +from .app_builder import AppBuilder +from .config import Config +from .group_config import GroupConfig, GroupConfigError +from .utils import run_app + +logger = logging.getLogger(__name__) + +DEFAULT_SETTINGS_FILES = ["settings.toml", ".secrets.toml"] +"""Settings the entry point loads, in Dynaconf's usual order. + +Named here rather than left to a default because this module *is* the deployment's entry point: +what it loads is part of the contract with the image, and a project that needs something else +writes its own ``main.py`` rather than discovering that this one guessed. +""" + + +def build_group_app(*, environ: dict[str, str] | None = None) -> tuple[FastAPI, Config]: + """Resolve the group, build the application, and return it with its configuration. + + Separate from :func:`main` so that the whole startup path is testable without a server and + without ``sys.exit``: everything that can fail happens here, and ``main`` only decides what + to do about it. + + **Not called ``build``**, deliberately. ``AppBuilder.build()`` returns a ``FastAPI`` and is + what every existing ``main.py`` calls; a second ``build`` in this package that returns a + *tuple* invites exactly the misreading that the application builder's contract had changed. + It has not: this is a different function, in a module nothing imported before this phase. + + Args: + environ: The environment to resolve the group from, for tests. + + Returns: + The application and the configuration it was built from. + + Raises: + GroupConfigError: if the group cannot be resolved or a critical agent cannot be loaded. + """ + config = Config(settings_files=DEFAULT_SETTINGS_FILES) + group = GroupConfig.resolve(config, environ=environ) + app = AppBuilder(config).with_group(group).build() + return app, config + + +def main(*, environ: dict[str, str] | None = None) -> int: + """Serve this process's group, or fail with a message and a non-zero status. + + Returns an exit status rather than calling ``sys.exit`` itself, so that a test can assert on + the status without catching ``SystemExit`` -- the module-level ``__main__`` guard is what + turns it into an exit. + + Args: + environ: The environment to resolve the group from, for tests. + + Returns: + ``0`` if the server ran and stopped normally, ``1`` if the group could not be started. + """ + try: + app, config = build_group_app(environ=environ) + except GroupConfigError as exc: + # Printed as well as logged: logging is configured by AppBuilder, which may not have run + # yet, and a container whose group is wrong must say so on stderr whatever state the + # logging configuration is in. + print(f"Cannot start: {exc}", file=sys.stderr) # noqa: T201 -- see above + logger.error("Cannot start: %s", exc) + return 1 + + run_app(app, config) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/blueprint/agents/group_config.py b/src/blueprint/agents/group_config.py new file mode 100644 index 00000000..48cb7ec8 --- /dev/null +++ b/src/blueprint/agents/group_config.py @@ -0,0 +1,403 @@ +"""Which agents this process hosts, resolved from the deployment rather than from the image. + +An agent's *code* says nothing about which other agents it runs beside: that is a deployment +decision, and the whole point of the namespace model is that changing it is invisible to the +agents (spec sec. 3). So the composition arrives at container start, from two sources that +compose, and this module is the only place that reads either of them. + +Two files, with different lifetimes, and the difference is the reason there are two: + +- **The agent map** (``agents.toml``) says what agents *exist* in this image and where their + declarations live. It changes only when an agent is added or removed, which is a rebuild + anyway, so it is baked in. +- **The group file** (``deployment-groups.yaml``) says which of them *this* process runs. It is + never baked in -- one image serves every group -- so it arrives as a mount, or is replaced + entirely by environment variables. + +Read **before** any ``Config`` view exists, and deliberately not through Dynaconf: group +composition decides which agents get a configuration view at all, so it cannot itself come from +one. That is why these are plain environment reads plus one parse each, and why the variables +carry an explicit ``BLUEPRINT_`` prefix rather than Dynaconf's override mechanism (spec sec. 5.1). + +Environment variables +~~~~~~~~~~~~~~~~~~~~~ +============================== ============================ ==================================== +Variable Default Meaning +============================== ============================ ==================================== +``BLUEPRINT_GROUP_CONFIG`` ``./deployment-groups.yaml`` Path to the group file. An absent + file is not an error when the + environment supplies the group. +``BLUEPRINT_GROUP`` -- Which group to load. May be omitted + when the file declares exactly one. +``BLUEPRINT_AGENTS`` -- Comma-separated agent names, which + supply the group with no file at all. +``BLUEPRINT_CRITICAL_AGENTS`` -- Comma-separated subset to mark + critical. See :attr:`AgentSpec.critical`. +``BLUEPRINT_AGENT_MAP`` ``./agents.toml`` Path to the agent map. +============================== ============================ ==================================== + +**Environment variables override the file key by key** (spec sec. 5.1), so one Deployment can +change the agent list without editing or duplicating the file. Every resolved value is logged +with the source it came from, because "which agents did this pod actually start" is the first +question asked of a group that misbehaves. +""" + +import logging +import os +import tomllib +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import yaml + +from .component.namespace import validate_namespace +from .config import Config + +logger = logging.getLogger(__name__) + +GROUP_CONFIG_ENV = "BLUEPRINT_GROUP_CONFIG" +GROUP_ENV = "BLUEPRINT_GROUP" +AGENTS_ENV = "BLUEPRINT_AGENTS" +CRITICAL_AGENTS_ENV = "BLUEPRINT_CRITICAL_AGENTS" +AGENT_MAP_ENV = "BLUEPRINT_AGENT_MAP" + +DEFAULT_GROUP_CONFIG = "deployment-groups.yaml" +DEFAULT_AGENT_MAP = "agents.toml" + + +class GroupConfigError(Exception): + """A group could not be resolved, and the process must not start. + + Its own type rather than ``ValueError`` because the entry point treats it differently from + every other failure: it is turned into a readable message and a non-zero exit *before the + port is bound*, so Kubernetes crash-loops with something an operator can act on rather than + reporting a healthy pod that is silently short-staffed (spec sec. 9.1). + """ + + +@dataclass(frozen=True) +class AgentSpec: + """One agent this process is asked to host. + + Attributes: + name: The agent's name, which becomes its namespace -- and with it its registry key + prefix, queue group, durable name, cache partition and telemetry service name. Held + to the namespace alphabet, so a group file cannot name an agent the rest of the + system could not identify. + module: Where the agent's ``AgentRegistration`` lives, as ``"module.path:attribute"``. + Comes from the agent map, never from the group file: what an agent *is* belongs to + the image, and only which agents run belongs to the deployment. + critical: Whether this agent failing to load must stop the process. Defaults to + ``True``, because a partially loaded group whose missing agent's queue has no + consumer is a worse failure than no pod at all (spec sec. 9.1) -- the pod would pass + its probes while a queue silently backed up. ``False`` is the deliberate choice to + run the rest without it. + """ + + name: str + module: str + critical: bool = True + + +@dataclass(frozen=True) +class GroupConfig: + """A resolved group: which agents run in this process, and under what name. + + A value object. :meth:`resolve` performs every read this module does; once constructed, + nothing here touches the environment or the filesystem, so a test builds one literally + rather than arranging files and variables around the code under test. + + Attributes: + name: The group's name. Reaches the NATS connection name for attribution and the + telemetry ``deployment.group`` resource attribute, and **nothing else** -- no + broker-side identifier may derive from it, or moving an agent between groups would + be visible to the broker (C1). + agents: The agents to host, in the order the group declared them. + cache_names: Caches to register for the process, beyond the default one. A cache is + process-wide (spec sec. 8), so it is the group's to declare rather than any single + agent's. + """ + + name: str + agents: tuple[AgentSpec, ...] + cache_names: tuple[str, ...] = field(default=()) + + @property + def agent_names(self) -> tuple[str, ...]: + """The agent names, in declaration order.""" + return tuple(agent.name for agent in self.agents) + + @classmethod + def resolve(cls, config: Config, *, environ: dict[str, str] | None = None) -> "GroupConfig": + """Read the group from the environment and the group file, and validate it. + + The only member that touches the environment or the filesystem. Order of operations: + + 1. Read the group file, if there is one, and take the requested group's slice. + 2. Apply environment overrides key by key -- so a Deployment can change the agent list + without editing a mounted file. + 3. Resolve every agent name against the in-image agent map, which is what turns a typo + into a crash-loop with a readable message instead of a pod missing one consumer. + + Args: + config: The application's configuration, used for the project root that relative + paths resolve against -- the same root its settings files resolved against, so + a project whose files live outside the working directory behaves consistently. + environ: The environment to read, for tests. Defaults to the process environment. + + Returns: + The resolved group. + + Raises: + GroupConfigError: if no group can be determined, if the file is unreadable or + malformed, if a named group is absent, or if an agent is not in the agent map + and is critical. + """ + env = os.environ if environ is None else environ + root = config.get_package_root() + + declared = cls._read_group_file(env, root) + name, agent_names, critical_names, cache_names = cls._apply_env_overrides(env, declared) + + if not agent_names: + raise GroupConfigError( + f"No agents were resolved for this process. Either mount a group file and name the group with " + f"'{GROUP_ENV}', or set '{AGENTS_ENV}' to a comma-separated list of agent names. Looked for a group " + f"file at {cls._group_file_path(env, root)}." + ) + + agent_map = cls._read_agent_map(env, root) + agents = cls._resolve_agents(agent_names, critical_names, agent_map, name) + + group = cls(name=name, agents=tuple(agents), cache_names=tuple(cache_names)) + logger.info( + "Resolved group '%s' with %d agent(s): %s%s", + group.name, + len(group.agents), + ", ".join(f"{agent.name}{'' if agent.critical else ' (non-critical)'}" for agent in group.agents), + f"; caches: {', '.join(group.cache_names)}" if group.cache_names else "", + ) + return group + + # ------------------------------------------------------------------ + # Reading + # ------------------------------------------------------------------ + + @staticmethod + def _group_file_path(env: dict[str, str] | Any, root: Path) -> Path: + """Return where the group file is looked for, whether or not it exists.""" + configured = str(env.get(GROUP_CONFIG_ENV, "") or "").strip() + path = Path(configured) if configured else root / DEFAULT_GROUP_CONFIG + return path if path.is_absolute() else root / path + + @classmethod + def _read_group_file(cls, env: dict[str, str] | Any, root: Path) -> dict[str, Any]: + """Return the requested group's slice of the group file, or an empty mapping. + + An absent file is not an error: the environment alone can supply a group, which is the + ``docker run`` and CI shape. A file that exists and cannot be parsed *is* an error -- + somebody mounted it meaning it to be used. + + Raises: + GroupConfigError: if the file cannot be read or parsed, if it does not declare + ``groups``, if the named group is absent, or if it declares several groups and + the environment names none. + """ + requested_group = str(env.get(GROUP_ENV, "") or "").strip() + if not requested_group and str(env.get(AGENTS_ENV, "") or "").strip(): + # The environment supplies the whole group, so the file is not consulted at all -- + # this is the `docker run` and CI shape from spec sec. 5.1. Reading it anyway would + # make an unrelated multi-group file mounted in the image ambiguous, and there is + # nothing to be ambiguous *about*: with no group named, no slice of that file + # applies, and the agent list that would have come from it is already overridden. + logger.debug("'%s' supplies the group and '%s' names none, so no group file is read", AGENTS_ENV, GROUP_ENV) + return {} + + path = cls._group_file_path(env, root) + if not path.is_file(): + logger.debug("No group file at %s; the group must come from the environment", path) + return {} + + document = cls._parse_group_file(path) + groups = document.get("groups") + if not isinstance(groups, list) or not groups: + raise GroupConfigError(f"Group file {path} declares no 'groups' list, so no group can be resolved from it.") + + by_name = {str(entry.get("name", "")): entry for entry in groups if isinstance(entry, dict)} + requested = requested_group + + if not requested: + if len(by_name) != 1: + raise GroupConfigError( + f"Group file {path} declares {len(by_name)} groups ({', '.join(sorted(by_name))}) and " + f"'{GROUP_ENV}' is not set, so which one to run is ambiguous. Set '{GROUP_ENV}'." + ) + only = next(iter(by_name.values())) + logger.info("Group file %s declares one group ('%s'), so it is the one loaded", path, only.get("name")) + return only + + if requested not in by_name: + raise GroupConfigError( + f"Group '{requested}' is not declared in {path} (it has: {', '.join(sorted(by_name)) or 'nothing'}). " + f"Either the group file mounted here is the wrong one, or '{GROUP_ENV}' is misspelt." + ) + logger.info("Loaded group '%s' from %s", requested, path) + return by_name[requested] + + @staticmethod + def _parse_group_file(path: Path) -> dict[str, Any]: + """Parse the group file as YAML. + + Raises: + GroupConfigError: if the file is unreadable or is not a YAML mapping. + """ + try: + document = yaml.safe_load(path.read_text(encoding="utf-8")) + except (OSError, yaml.YAMLError) as exc: + raise GroupConfigError(f"Group file {path} could not be read: {exc}") from exc + + if document is None: + return {} + if not isinstance(document, dict): + raise GroupConfigError(f"Group file {path} must contain a mapping with a 'groups' key, got {type(document).__name__}.") + return document + + @classmethod + def _read_agent_map(cls, env: dict[str, str] | Any, root: Path) -> dict[str, str]: + """Return ``{agent name: "module:attribute"}`` from the in-image agent map. + + An explicit map rather than scanning for modules by convention. Discovery by convention + makes the set of agents in an image depend on what happens to be importable, so a + renamed directory silently removes an agent and a stray one silently adds it; the map + makes both a diff in a file that has to be edited on purpose. + + Raises: + GroupConfigError: if the map is missing, unparseable, or malformed. + """ + configured = str(env.get(AGENT_MAP_ENV, "") or "").strip() + path = Path(configured) if configured else root / DEFAULT_AGENT_MAP + if not path.is_absolute(): + path = root / path + + if not path.is_file(): + raise GroupConfigError( + f"No agent map at {path}, so no agent name can be resolved to code. This file is part of the image " + "and lists every agent it contains, as [agents.] with module = 'pkg.mod:registration'. Set " + f"'{AGENT_MAP_ENV}' if it lives elsewhere." + ) + + try: + document = tomllib.loads(path.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError) as exc: + raise GroupConfigError(f"Agent map {path} could not be read: {exc}") from exc + + agents = document.get("agents") + if not isinstance(agents, dict) or not agents: + raise GroupConfigError(f"Agent map {path} declares no [agents.] entries, so this image contains no agents.") + + resolved: dict[str, str] = {} + for agent_name, entry in agents.items(): + module = entry.get("module") if isinstance(entry, dict) else None + if not module or not isinstance(module, str): + raise GroupConfigError( + f"Agent '{agent_name}' in {path} has no 'module', so its declaration cannot be found. Write it as " + 'module = "pkg.mod:registration".' + ) + resolved[str(agent_name)] = module + logger.debug("Agent map %s contains %d agent(s): %s", path, len(resolved), ", ".join(sorted(resolved))) + return resolved + + # ------------------------------------------------------------------ + # Overriding and validating + # ------------------------------------------------------------------ + + @staticmethod + def _apply_env_overrides(env: dict[str, str] | Any, declared: dict[str, Any]) -> tuple[str, list[str], set[str], list[str]]: + """Overlay environment variables on the file's slice, key by key, logging each source. + + Key by key rather than all-or-nothing (spec sec. 5.1): a Deployment that wants a + different agent list should not have to restate the group's name and caches to get it. + The log line per value is what answers "where did this pod's agent list come from", + which is the first question asked of a group that started with the wrong contents. + """ + + def _split(raw: str) -> list[str]: + return [part.strip() for part in raw.split(",") if part.strip()] + + name = str(declared.get("name", "") or "").strip() + agents = [str(agent).strip() for agent in declared.get("agents", []) or [] if str(agent).strip()] + critical = {str(agent).strip() for agent in declared.get("critical_agents", []) or [] if str(agent).strip()} + caches = [str(cache).strip() for cache in declared.get("cache_names", []) or [] if str(cache).strip()] + sources = {"name": "file", "agents": "file", "critical_agents": "file", "cache_names": "file"} + + if override := str(env.get(GROUP_ENV, "") or "").strip(): + if not name: + name, sources["name"] = override, f"${GROUP_ENV}" + if override := str(env.get(AGENTS_ENV, "") or "").strip(): + agents, sources["agents"] = _split(override), f"${AGENTS_ENV}" + if override := str(env.get(CRITICAL_AGENTS_ENV, "") or "").strip(): + critical, sources["critical_agents"] = set(_split(override)), f"${CRITICAL_AGENTS_ENV}" + + if not name: + # A group has to be called something: the name reaches the connection name and the + # telemetry resource, where an empty segment reads as a bug rather than as "no group". + name, sources["name"] = "ungrouped", "default" + + for key, source in sources.items(): + if source != "file" or declared: + logger.info("Group value '%s' resolved from %s", key, source) + return name, agents, critical, caches + + @staticmethod + def _resolve_agents(agent_names: list[str], critical_names: set[str], agent_map: dict[str, str], group_name: str) -> list[AgentSpec]: + """Turn names into specs, refusing a name the image does not contain. + + A name absent from the map is refused **here**, before anything is built, which is the + seam the plan asks for: a typo in a mounted group file becomes a crash-loop naming the + group and the agent, rather than a pod that passes its probes with one queue unconsumed. + + A name marked non-critical is *skipped* instead, with an ERROR, because that flag is the + deployment saying it would rather run the rest. + + The name is also held to the namespace alphabet, since it becomes a namespace: rejecting + it here names the group file, while letting it through would surface as a validation + error from inside some component's constructor. + + Raises: + GroupConfigError: if a critical agent is not in the map, if a name is not a legal + namespace, or if the group names the same agent twice. + """ + specs: list[AgentSpec] = [] + seen: set[str] = set() + for name in agent_names: + if name in seen: + raise GroupConfigError( + f"Group '{group_name}' names agent '{name}' more than once. Two agents cannot share a name -- it " + "is what identifies one in every log line, queue group, durable and cache partition -- and one " + "agent named twice is a group whose size does not match its contents." + ) + seen.add(name) + + try: + validate_namespace(name) + except ValueError as exc: + raise GroupConfigError(f"Group '{group_name}' names an agent that cannot be a namespace: {exc}") from exc + + critical = name in critical_names if critical_names else True + module = agent_map.get(name) + if module is None: + if critical: + raise GroupConfigError( + f"Group '{group_name}' names agent '{name}', which this image does not contain (it has: " + f"{', '.join(sorted(agent_map))}). Either the agent map is out of date, or the group file " + f"names an agent that was removed." + ) + logger.error( + "Agent '%s' of group '%s' is not in this image's agent map and is not critical, so it is skipped", + name, + group_name, + ) + continue + specs.append(AgentSpec(name=name, module=module, critical=critical)) + return specs diff --git a/src/blueprint/agents/io/api/scheduling/scheduler.py b/src/blueprint/agents/io/api/scheduling/scheduler.py index d1e90a74..f8d45d03 100644 --- a/src/blueprint/agents/io/api/scheduling/scheduler.py +++ b/src/blueprint/agents/io/api/scheduling/scheduler.py @@ -48,7 +48,6 @@ async def tick(self) -> None: from ....clients.io.io_client_base import TOPIC_TRANSPORTS, validate_subject_segment from ....component.component import traced -from ....component.namespace import ROOT_NAMESPACE from ....handler.event_handler_base import EventHandlerBase from ....models.events import GenericCloudEvent from ..rest_api_base import RestApiBase @@ -376,10 +375,12 @@ def _require_event_transport(self) -> None: def _resolve_topic(self) -> str: """Derive the tick topic from the agent's own identity, or take the override. - ``f"{namespace}.scheduler.{name}"``, falling back to ``app_name`` while the - namespace is the root one -- the same identity the queue group derives from, so - moving the scheduler between deployment groups does not change the subject a - ``CronJob`` has to publish to (C1). + ``f"{namespace}.scheduler.{name}"``, falling back to ``app_name`` only for a scheduler + at the root -- the same identity the queue group derives from, so moving the scheduler + between deployment groups does not change the subject a ``CronJob`` has to publish to + (C1). An agent's name is the agent's own; ``app_name`` is a display string belonging to + the whole process, so deriving a namespaced scheduler's subject from it would give two + agents' schedulers of the same name one subject. A derived topic is **validated, not repaired**, and both of the names it is derived from -- the identity and the scheduler's own name -- are checked. This subject is the @@ -400,8 +401,15 @@ def _resolve_topic(self) -> str: validate_subject_segment(topic, source=f"The tick topic given to scheduler '{self.name}'", subject=topic) return topic - # ROOT_NAMESPACE is still "" for every component; phase 2 is what gives this a value. - identity = ROOT_NAMESPACE or str(self.config.get("app_name", "") or "").strip() + # The scheduler's own namespace, and only then app_name. This read was + # `ROOT_NAMESPACE or app_name` -- the module constant, which is always "" -- left behind + # as a placeholder for phase 2. Phase 2 landed, so `self.namespace` has a value, and the + # placeholder had become a defect: a namespaced scheduler derived its tick subject from + # `app_name`, which is a display string shared by the whole process. Two agents in a + # group each with a `nightly` scheduler would have derived the same subject and consumed + # each other's ticks, and moving an agent between groups could change the subject its + # CronJob has to publish to (C1). + identity = self.namespace or str(self.config.get("app_name", "") or "").strip() if not identity: raise ValueError( f"Scheduler '{self.name}' runs in event mode but its tick topic cannot be derived: " @@ -409,7 +417,7 @@ def _resolve_topic(self) -> str: ) topic = f"{identity}.scheduler.{self.name}" - source = "'app_name'" if not ROOT_NAMESPACE else "The scheduler's namespace" + source = "The scheduler's namespace" if self.namespace else "'app_name'" validate_subject_segment(identity, source=source, subject=topic) validate_subject_segment(self.name, source=f"The name of scheduler '{self.name}'", subject=topic) return topic diff --git a/tests/unit/agents/app_builder/test_namespace_builder.py b/tests/unit/agents/app_builder/test_namespace_builder.py index a342e065..1e639f75 100644 --- a/tests/unit/agents/app_builder/test_namespace_builder.py +++ b/tests/unit/agents/app_builder/test_namespace_builder.py @@ -242,11 +242,19 @@ def test_declaration_order_is_kept(self, two_agent_config: Config) -> None: builder.with_namespace("orders").end().with_namespace("billing").end() assert builder.namespaces == ("orders", "billing") - def test_a_namespace_is_recorded_once(self, two_agent_config: Config) -> None: + def test_declaring_one_namespace_twice_is_refused(self, two_agent_config: Config) -> None: + """Two agents cannot share a name: the name is what tells them apart everywhere.""" builder = AppBuilder(two_agent_config) builder.with_namespace("orders", registration=AgentRegistration()) - builder.with_namespace("orders", registration=AgentRegistration().with_service(OrderService)) - assert builder.namespaces == ("orders",) + + with pytest.raises(ValueError, match="already hosted by this process"): + builder.with_namespace("orders", registration=AgentRegistration().with_service(OrderService)) + + def test_the_refusal_points_at_composing_one_registration(self, two_agent_config: Config) -> None: + builder = AppBuilder(two_agent_config).with_namespace("orders").end() + + with pytest.raises(ValueError, match=r"single\s+AgentRegistration"): + builder.with_namespace("orders") def test_a_tagged_with_call_is_not_a_declaration(self, two_agent_config: Config) -> None: """``namespaces`` is what the builder was *told* to host; a tagged call is not that. diff --git a/tests/unit/agents/app_builder/test_with_group.py b/tests/unit/agents/app_builder/test_with_group.py new file mode 100644 index 00000000..8c38ba14 --- /dev/null +++ b/tests/unit/agents/app_builder/test_with_group.py @@ -0,0 +1,270 @@ +"""Applying a resolved group: one namespace per agent, and the group's caches. + +``with_group`` is the wiring half of phase 8, and its contract is that it performs no I/O -- no +environment, no files, no ``sys.exit``, no knowledge of an agent repo's layout. That is why the +``GroupConfig`` here is always constructed literally: these tests state exact compositions +without arranging anything around the code under test. + +Importing an agent's module is the one thing it reaches outside for, and it is driven entirely by +the ``module`` strings the group carries -- so the declarations below live in this file and are +named by their real dotted paths. +""" + +from pathlib import Path +from typing import Any + +import pytest + +from blueprint.agents.app_builder import AgentRegistration, AppBuilder +from blueprint.agents.component.component import Component +from blueprint.agents.component.registry import DEFAULT_CACHE_NAME +from blueprint.agents.config import Config +from blueprint.agents.group_config import AgentSpec, GroupConfig, GroupConfigError +from blueprint.agents.models.config import CacheConfig +from blueprint.agents.services.service_base import ServiceBase + +_THIS = "tests.unit.agents.app_builder.test_with_group" + + +class OrderService(ServiceBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class BillingService(ServiceBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +# The module-level declarations a group's `module` strings point at, exactly as an agent's own +# module would expose them. +order_registration = AgentRegistration().with_service(OrderService) +billing_registration = AgentRegistration().with_service(BillingService) +not_a_registration = "this is not an AgentRegistration" + + +@pytest.fixture +def config(tmp_path: Path) -> Config: + settings = tmp_path / "settings.toml" + settings.write_text( + '[development]\napp_environment = "development"\napp_name = "the-process"\napp_port = 8000\n\n' + "[development.order]\napp_port = 8000\n\n" + "[development.billing]\napp_port = 8000\n" + ) + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + +def spec(name: str, attribute: str, *, critical: bool = True) -> AgentSpec: + return AgentSpec(name=name, module=f"{_THIS}:{attribute}", critical=critical) + + +def component_names() -> list[str]: + registry = Component.shared_registry + assert registry is not None + return sorted(registry.get_component_names_by_type(Component)) + + +class TestOneNamespacePerAgent: + def test_each_agent_is_applied_under_its_own_name(self, config: Config) -> None: + group = GroupConfig(name="finance", agents=(spec("order", "order_registration"), spec("billing", "billing_registration"))) + + AppBuilder(config).with_group(group) + + assert component_names() == ["billing_billing_service", "order_order_service"] + + def test_the_builder_records_the_agents_it_hosts(self, config: Config) -> None: + group = GroupConfig(name="finance", agents=(spec("order", "order_registration"), spec("billing", "billing_registration"))) + + builder = AppBuilder(config).with_group(group) + + assert builder.namespaces == ("order", "billing") + + def test_declaration_order_is_kept(self, config: Config) -> None: + group = GroupConfig(name="finance", agents=(spec("billing", "billing_registration"), spec("order", "order_registration"))) + + builder = AppBuilder(config).with_group(group) + + assert builder.namespaces == ("billing", "order") + + def test_it_returns_the_builder(self, config: Config) -> None: + builder = AppBuilder(config) + + assert builder.with_group(GroupConfig(name="empty", agents=())) is builder + + def test_a_group_of_one_is_an_ordinary_group(self, config: Config) -> None: + """Group size 1 is how an agent gets a process to itself; nothing about it is special.""" + group = GroupConfig(name="just-order", agents=(spec("order", "order_registration"),)) + + AppBuilder(config).with_group(group) + + assert component_names() == ["order_order_service"] + + def test_the_same_declaration_can_serve_two_agents(self, config: Config) -> None: + """One declaration, applied per agent -- the property the whole design rests on.""" + group = GroupConfig(name="two", agents=(spec("order", "order_registration"), spec("billing", "order_registration"))) + + AppBuilder(config).with_group(group) + + assert component_names() == ["billing_order_service", "order_order_service"] + + +class TestTheGroupsCaches: + def test_declared_caches_are_registered(self, config: Config, tmp_path: Path) -> None: + """A cache is process-wide, so the group declares it rather than any single agent.""" + config.get_cache_config = lambda: CacheConfig(cache_dir=str(tmp_path / "cache"), backend="disk") # type: ignore[method-assign] + group = GroupConfig(name="finance", agents=(spec("order", "order_registration"),), cache_names=("sessions", "prompts")) + + AppBuilder(config).with_group(group) + + registry = Component.shared_registry + assert registry is not None + assert sorted(registry.get_all_caches()) == ["prompts", "sessions"] + + def test_a_group_with_no_caches_registers_none(self, config: Config) -> None: + AppBuilder(config).with_group(GroupConfig(name="finance", agents=(spec("order", "order_registration"),))) + + registry = Component.shared_registry + assert registry is not None + assert registry.get_all_caches() == {} + + def test_the_default_cache_is_still_the_applications_to_add(self, config: Config, tmp_path: Path) -> None: + """with_cache() on the chain and the group's list compose.""" + config.get_cache_config = lambda: CacheConfig(cache_dir=str(tmp_path / "cache"), backend="disk") # type: ignore[method-assign] + group = GroupConfig(name="finance", agents=(), cache_names=("sessions",)) + + AppBuilder(config).with_cache().with_group(group) + + registry = Component.shared_registry + assert registry is not None + assert sorted(registry.get_all_caches()) == [DEFAULT_CACHE_NAME, "sessions"] + + +class TestLoadingADeclaration: + def test_a_missing_module_fails_a_critical_agent(self, config: Config) -> None: + group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module="no.such.module:registration"),)) + + with pytest.raises(GroupConfigError, match="could not be loaded and is critical"): + AppBuilder(config).with_group(group) + + def test_the_failure_names_the_agent_and_the_module(self, config: Config) -> None: + group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module="no.such.module:registration"),)) + + with pytest.raises(GroupConfigError, match=r"'order'.*no\.such\.module"): + AppBuilder(config).with_group(group) + + def test_a_missing_attribute_fails_a_critical_agent(self, config: Config) -> None: + group = GroupConfig(name="finance", agents=(spec("order", "nope"),)) + + with pytest.raises(GroupConfigError, match="has no attribute 'nope'"): + AppBuilder(config).with_group(group) + + def test_an_attribute_that_is_not_a_registration_is_refused(self, config: Config) -> None: + group = GroupConfig(name="finance", agents=(spec("order", "not_a_registration"),)) + + with pytest.raises(GroupConfigError, match="is a str, not an AgentRegistration"): + AppBuilder(config).with_group(group) + + @pytest.mark.parametrize("module", ["no_colon_at_all", ":registration", "module.path:"]) + def test_a_malformed_declaration_path_is_refused(self, config: Config, module: str) -> None: + group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module=module),)) + + with pytest.raises(GroupConfigError, match="is not a valid declaration path"): + AppBuilder(config).with_group(group) + + def test_a_non_critical_agent_is_skipped(self, config: Config, caplog: pytest.LogCaptureFixture) -> None: + """The flag is the deployment saying it would rather run the rest.""" + group = GroupConfig( + name="finance", + agents=( + AgentSpec(name="order", module="no.such.module:registration", critical=False), + spec("billing", "billing_registration"), + ), + ) + + with caplog.at_level("ERROR", logger="blueprint.agents.app_builder"): + builder = AppBuilder(config).with_group(group) + + assert builder.namespaces == ("billing",) + assert component_names() == ["billing_billing_service"] + assert "is not critical, so it is skipped" in caplog.text + + def test_a_skipped_agent_does_not_stop_the_ones_after_it(self, config: Config) -> None: + group = GroupConfig( + name="finance", + agents=( + AgentSpec(name="order", module="no.such.module:registration", critical=False), + spec("billing", "billing_registration"), + ), + ) + + AppBuilder(config).with_group(group) + + assert component_names() == ["billing_billing_service"] + + def test_a_critical_agent_stops_the_build_before_later_ones(self, config: Config) -> None: + """There is no partial build to unwind, so it fails rather than half-wiring the group.""" + group = GroupConfig( + name="finance", + agents=(AgentSpec(name="order", module="no.such.module:registration"), spec("billing", "billing_registration")), + ) + + with pytest.raises(GroupConfigError): + AppBuilder(config).with_group(group) + + assert "billing_billing_service" not in component_names() + + +class TestNoIoOfItsOwn: + def test_it_reads_no_environment(self, config: Config, monkeypatch: pytest.MonkeyPatch) -> None: + """The contract that keeps AppBuilder a pure function of its call sequence.""" + monkeypatch.setenv("BLUEPRINT_AGENTS", "something-else") + monkeypatch.setenv("BLUEPRINT_GROUP", "another-group") + group = GroupConfig(name="finance", agents=(spec("order", "order_registration"),)) + + builder = AppBuilder(config).with_group(group) + + assert builder.namespaces == ("order",) + + def test_a_group_can_be_constructed_literally(self, config: Config) -> None: + group = GroupConfig(name="finance", agents=(spec("order", "order_registration"),)) + + AppBuilder(config).with_group(group) + + assert component_names() == ["order_order_service"] + + +class TestFromGroup: + def test_it_resolves_and_applies_in_one_call(self, tmp_path: Path) -> None: + (tmp_path / "agents.toml").write_text(f'[agents.order]\nmodule = "{_THIS}:order_registration"\n') + settings = tmp_path / "settings.toml" + settings.write_text('[development]\napp_environment = "development"\napp_port = 8000\n') + config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + builder = AppBuilder.from_group(config, environ={"BLUEPRINT_AGENTS": "order", "BLUEPRINT_GROUP": "finance"}) + + assert builder.namespaces == ("order",) + assert component_names() == ["order_order_service"] + + def test_a_resolution_failure_propagates(self, tmp_path: Path) -> None: + settings = tmp_path / "settings.toml" + settings.write_text('[development]\napp_environment = "development"\napp_port = 8000\n') + config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + with pytest.raises(GroupConfigError, match="No agent map at"): + AppBuilder.from_group(config, environ={"BLUEPRINT_AGENTS": "order"}) + + def test_it_returns_a_builder_ready_to_chain(self, tmp_path: Path) -> None: + (tmp_path / "agents.toml").write_text(f'[agents.order]\nmodule = "{_THIS}:order_registration"\n') + settings = tmp_path / "settings.toml" + settings.write_text('[development]\napp_environment = "development"\napp_port = 8000\n') + config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + builder: Any = AppBuilder.from_group(config, environ={"BLUEPRINT_AGENTS": "order"}) + + assert isinstance(builder, AppBuilder) diff --git a/tests/unit/agents/component/test_name_uniqueness.py b/tests/unit/agents/component/test_name_uniqueness.py new file mode 100644 index 00000000..44b93c1c --- /dev/null +++ b/tests/unit/agents/component/test_name_uniqueness.py @@ -0,0 +1,188 @@ +"""A registry name always says which agent it belongs to, and two components never share one. + +The requirement is about reading logs, not about the registry. A component's registry name is +what appears in every log line, span and health entry, so two components that share one -- or one +whose name does not carry its agent -- cannot be told apart afterwards. Every way a name can be +set is covered here, because each of them used to be able to produce an ambiguous one. +""" + +from pathlib import Path + +import pytest + +from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import namespace_scope, qualified_component_name +from blueprint.agents.config import Config +from blueprint.agents.services.service_base import ServiceBase + + +class Planner(ServiceBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class Reporter(ServiceBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class BillingHandler(ServiceBase): + """A class whose snake_case name begins with a namespace's name. See the qualifier tests.""" + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +@pytest.fixture +def config(tmp_path: Path) -> Config: + settings = tmp_path / "settings.toml" + settings.write_text( + '[development]\napp_name = "root-app"\napp_port = 8000\n\n' + '[development.orders]\napp_name = "orders"\n\n' + '[development.billing]\napp_name = "billing"\n' + ) + loaded = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + Component.configure(loaded) + return loaded + + +def registry_names() -> list[str]: + registry = Component.shared_registry + assert registry is not None + return sorted(registry.get_component_names_by_type(Component)) + + +class TestAnExplicitNameCarriesItsAgent: + def test_a_directly_constructed_component_is_qualified(self, config: Config) -> None: + """It used to be taken verbatim, so the log said 'planner' and not which agent's.""" + with namespace_scope("orders"): + Planner(name="planner") + + assert registry_names() == ["orders_planner"] + + def test_two_agents_can_each_have_one(self, config: Config) -> None: + with namespace_scope("orders"): + orders = Planner(name="planner") + with namespace_scope("billing"): + billing = Planner(name="planner") + + assert registry_names() == ["billing_planner", "orders_planner"] + assert (orders.name, billing.name) == ("orders_planner", "billing_planner") + + def test_the_root_keeps_the_bare_name(self, config: Config) -> None: + Planner(name="planner") + + assert registry_names() == ["planner"] + + def test_a_rename_is_qualified_too(self, config: Config) -> None: + with namespace_scope("orders"): + planner = Planner() + + planner.name = "db" + + assert (planner.name, registry_names()) == ("orders_db", ["orders_db"]) + + def test_a_rename_at_the_root_is_unchanged(self, config: Config) -> None: + planner = Planner() + + planner.name = "db" + + assert planner.name == "db" + + +class TestTheQualifierDoesNotGuess: + def test_a_base_name_starting_with_the_namespace_is_still_qualified(self, config: Config) -> None: + """Skipping the prefix when it looks present would silently unqualify this component. + + ``BillingHandler`` in namespace ``billing`` derives ``billing_handler``, which *looks* + qualified and is not. "Already prefixed" is not decidable from the string. + """ + with namespace_scope("billing"): + BillingHandler() + + assert registry_names() == ["billing_billing_handler"] + + def test_qualifying_is_a_plain_prefix(self, config: Config) -> None: + assert qualified_component_name("orders", "db") == "orders_db" + assert qualified_component_name("", "db") == "db" + + +class TestADuplicateNameFailsAtStartup: + def test_two_components_of_one_class_in_one_agent_collide(self, config: Config) -> None: + with namespace_scope("orders"): + Planner() + with pytest.raises(ValueError, match="is already taken by a Planner"): + Planner() + + def test_two_explicit_names_that_collide_are_refused(self, config: Config) -> None: + with namespace_scope("orders"): + Planner(name="shared") + with pytest.raises(ValueError, match="already taken"): + Reporter(name="shared") + + def test_the_refusal_names_the_agent_and_the_fix(self, config: Config) -> None: + with namespace_scope("orders"): + Planner(name="shared") + with pytest.raises(ValueError, match=r"namespace 'orders'.*distinct 'name='"): + Reporter(name="shared") + + def test_a_root_component_and_an_agents_do_not_collide(self, config: Config) -> None: + Planner(name="planner") + with namespace_scope("orders"): + Planner(name="planner") + + assert registry_names() == ["orders_planner", "planner"] + + +class TestARenameNeverLosesAComponent: + def test_renaming_onto_a_taken_name_is_refused(self, config: Config) -> None: + """This used to overwrite the dict entry, removing the other component silently.""" + planner = Planner(name="planner") + Reporter(name="reporter") + + with pytest.raises(ValueError, match="already taken by a Reporter"): + planner.name = "reporter" + + def test_the_other_component_is_still_registered_afterwards(self, config: Config) -> None: + planner = Planner(name="planner") + reporter = Reporter(name="reporter") + + with pytest.raises(ValueError): + planner.name = "reporter" + + registry = Component.shared_registry + assert registry is not None + assert registry.get_component("reporter") is reporter + assert registry.get_component("planner") is planner + + def test_renaming_to_the_same_name_is_a_no_op(self, config: Config) -> None: + planner = Planner(name="planner") + + planner.name = "planner" + + assert registry_names() == ["planner"] + + def test_renaming_to_its_own_qualified_name_is_a_no_op(self, config: Config) -> None: + """The setter qualifies, so assigning the bare name a component already has must settle.""" + with namespace_scope("orders"): + planner = Planner(name="planner") + + planner.name = "planner" + + assert (planner.name, registry_names()) == ("orders_planner", ["orders_planner"]) + + def test_renaming_an_unregistered_name_still_raises(self, config: Config) -> None: + planner = Planner(name="planner") + planner._name = "never-registered" + + with pytest.raises(ValueError, match="does not exist"): + planner.name = "something" diff --git a/tests/unit/agents/config/test_agent_identity.py b/tests/unit/agents/config/test_agent_identity.py new file mode 100644 index 00000000..668de06d --- /dev/null +++ b/tests/unit/agents/config/test_agent_identity.py @@ -0,0 +1,84 @@ +"""One name per agent: the one it was given in code, with ``app_name`` as the fallback. + +An agent's identity reaches its registry keys, its NATS queue group, its JetStream durable, its +cache partition and its telemetry ``service.name``. If config could supply a second name, the +same agent could be ``orders`` on the broker and something else in a dashboard -- so the name +given in code wins wherever identity is meant, and ``app_name`` is used only when no name was +given. Everywhere else ``app_name`` is a display string for the process. +""" + +from pathlib import Path + +import pytest + +from blueprint.agents.config import Config + +TWO_AGENTS = ( + '[development]\napp_environment = "development"\napp_name = "the-process"\napp_port = 8000\n\n' + "[development.orders]\napp_port = 8000\n\n" + '[development.billing]\notel_service_name = "billing-override"\n' +) + + +@pytest.fixture +def settings(tmp_path: Path) -> Path: + path = tmp_path / "settings.toml" + path.write_text(TWO_AGENTS) + return path + + +def written(tmp_path: Path, body: str) -> Path: + path = tmp_path / "settings.toml" + path.write_text(body) + return path + + +def load(settings: Path, agent: str | None = None) -> Config: + return Config(settings_files=[str(settings)], root_path=str(settings.parent), agent_scope=agent) + + +class TestTelemetryIdentity: + def test_an_agents_service_name_is_its_own_name(self, settings: Path) -> None: + """C2: dashboards key on the agent, so regrouping cannot move work between them.""" + assert load(settings, "orders").get_observability_config().otel_service_name == "orders" + + def test_an_agent_can_override_it_for_itself(self, settings: Path) -> None: + assert load(settings, "billing").get_observability_config().otel_service_name == "billing-override" + + def test_the_roots_override_does_not_leak_into_an_agent(self, tmp_path: Path) -> None: + """The one place a scoped read must not fall back: it would give every agent one name.""" + path = written(tmp_path, '[development]\napp_environment = "development"\notel_service_name = "one-name-for-all"\n') + + assert load(path, "orders").get_observability_config().otel_service_name == "orders" + + def test_a_single_agent_application_still_reads_app_name(self, settings: Path) -> None: + """No name given, so app_name is used -- unchanged, and its dashboards do not move.""" + assert load(settings).get_observability_config().otel_service_name == "the-process" + + def test_an_explicit_root_override_still_wins_at_the_root(self, tmp_path: Path) -> None: + path = written(tmp_path, '[development]\napp_environment = "development"\napp_name = "a"\notel_service_name = "b"\n') + + assert load(path).get_observability_config().otel_service_name == "b" + + def test_with_neither_it_falls_back_to_a_default(self, tmp_path: Path) -> None: + path = written(tmp_path, '[development]\napp_environment = "development"\n') + + assert load(path).get_observability_config().otel_service_name == "agent_blueprint" + + +class TestAppNameStaysADisplayString: + def test_an_agent_reads_the_processes_app_name(self, settings: Path) -> None: + """It is not the agent's name, so it is not scoped away from it either.""" + assert load(settings, "orders").get("app_name") == "the-process" + + def test_an_agent_may_still_set_one_for_display(self, tmp_path: Path) -> None: + path = written( + tmp_path, + '[development]\napp_environment = "development"\napp_name = "the-process"\n\n' + '[development.orders]\napp_name = "Order Processing"\n', + ) + config = load(path, "orders") + + assert config.get("app_name") == "Order Processing" + # Identity is unaffected by it. + assert config.get_observability_config().otel_service_name == "orders" diff --git a/tests/unit/agents/config/test_agent_scope.py b/tests/unit/agents/config/test_agent_scope.py index b1759101..18d239ec 100644 --- a/tests/unit/agents/config/test_agent_scope.py +++ b/tests/unit/agents/config/test_agent_scope.py @@ -17,7 +17,6 @@ import pytest from blueprint.agents.config import Config -from blueprint.agents.config.config import ConfigError from tests.unit.agents.config.conftest import WriteSettings FIXTURES_DIR = Path(__file__).parent / "fixtures" @@ -107,21 +106,28 @@ def test_resolves_scoped_model_settings(self, scoped_config_foo: Config) -> None class TestValidators: - def test_missing_scoped_app_name_raises(self, write_settings: WriteSettings) -> None: + def test_an_agent_does_not_have_to_restate_its_name(self, write_settings: WriteSettings) -> None: + """An agent's identity is the name it was given in code, not a second one in config. + + Requiring `.app_name` gave every agent two names free to disagree -- `orders` on + the broker and in the registry, something else in a dashboard. + """ settings_file = write_settings(""" [development] app_environment = "development" + app_name = "the-process" [development.foo] app_port = 8101 - # app_name intentionally missing """) - with pytest.raises(ConfigError): - Config( - settings_files=[str(settings_file)], - root_path=str(settings_file.parent), - agent_scope="foo", - ) + + config = Config( + settings_files=[str(settings_file)], + root_path=str(settings_file.parent), + agent_scope="foo", + ) + + assert config.get("app_name") == "the-process" def test_scoped_config_needs_no_scoped_app_port(self, write_settings: WriteSettings) -> None: """A group is one process behind one HTTP server, so the port cannot be per agent.""" diff --git a/tests/unit/agents/io/api/scheduling/test_scheduler.py b/tests/unit/agents/io/api/scheduling/test_scheduler.py index e0a6e325..9c6b9d33 100644 --- a/tests/unit/agents/io/api/scheduling/test_scheduler.py +++ b/tests/unit/agents/io/api/scheduling/test_scheduler.py @@ -18,6 +18,7 @@ SchedulerTickHandler, validate_crontab, ) +from blueprint.agents.component.namespace import namespace_scope from blueprint.agents.services.infrastructure.cache_service import DiskCacheService _SCHEDULER_MODULE = "blueprint.agents.io.api.scheduling.scheduler" @@ -186,9 +187,33 @@ async def tick(self) -> None: class TestTickTopic: - def test_topic_derives_from_app_name_and_scheduler_name(self, scheduler: _TestScheduler) -> None: + def test_topic_derives_from_app_name_when_no_name_was_given(self, scheduler: _TestScheduler) -> None: + """No namespace, so app_name is the identity -- which is every single-agent application.""" assert scheduler.tick_topic == f"cleanup_service.scheduler.{scheduler.name}" + def test_a_namespaced_scheduler_derives_from_its_own_name(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + """The name given in code wins over app_name, which belongs to the whole process. + + This read used to be the module constant ROOT_NAMESPACE -- always "" -- left as a + placeholder for phase 2, so a namespaced scheduler derived its subject from app_name. + """ + settings["scheduler_mode"] = SCHEDULER_MODE_EVENT + with namespace_scope("orders"): + namespaced = _TestScheduler() + + assert namespaced.tick_topic == f"orders.scheduler.{namespaced.name}" + + def test_two_agents_schedulers_of_one_name_get_two_subjects(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + """Derived from app_name they shared a subject and consumed each other's ticks.""" + settings["scheduler_mode"] = SCHEDULER_MODE_EVENT + with namespace_scope("orders"): + orders = _TestScheduler() + with namespace_scope("billing"): + billing = _TestScheduler() + + assert orders.tick_topic != billing.tick_topic + assert orders.tick_topic.startswith("orders.") and billing.tick_topic.startswith("billing.") + def test_topic_follows_a_renamed_scheduler(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: renamed = _TestScheduler() renamed.name = "nightly" diff --git a/tests/unit/agents/test_entrypoint.py b/tests/unit/agents/test_entrypoint.py new file mode 100644 index 00000000..381e462f --- /dev/null +++ b/tests/unit/agents/test_entrypoint.py @@ -0,0 +1,207 @@ +"""The container's command: what it starts, and how it fails. + +The failure path is the reason this module exists as its own unit. A group that cannot be +resolved has to stop the process *before the port is bound*, with a message an operator can act +on -- otherwise Kubernetes reports a healthy replica that is silently short a consumer, which is +the failure this whole feature is built to prevent. +""" + +from collections.abc import Generator +from pathlib import Path +from unittest.mock import patch + +import pytest + +from blueprint.agents import entrypoint +from blueprint.agents.app_builder import AgentRegistration, AppBuilder +from blueprint.agents.config import Config +from blueprint.agents.component.component import Component +from blueprint.agents.services.service_base import ServiceBase + +_THIS = "tests.unit.agents.test_entrypoint" + + +class OrderService(ServiceBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +order_registration = AgentRegistration().with_service(OrderService) + + +@pytest.fixture(autouse=True) +def reset_component_state() -> Generator[None]: + """Clear the process-wide component state around every case. + + ``build()`` runs a real ``AppBuilder.build()``, which injects the configuration once and + registers components under process-wide names -- so without this the second case in the file + fails on "Config is already set" or a duplicate registry name rather than on anything it + was testing. + """ + Component.reset_shared_state() + yield + Component.reset_shared_state() + + +@pytest.fixture +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """A project root the entry point will pick up, with the working directory moved into it. + + The entry point loads ``settings.toml`` relative to the working directory, because that is + what the container's ``WORKDIR`` provides. So this fixture reproduces the container's shape + rather than passing paths the real entry point has no parameter for. + """ + (tmp_path / "agents.toml").write_text(f'[agents.order]\nmodule = "{_THIS}:order_registration"\n') + (tmp_path / "settings.toml").write_text('[development]\napp_environment = "development"\napp_name = "the-process"\napp_port = 8000\n') + monkeypatch.chdir(tmp_path) + return tmp_path + + +def component_names() -> list[str]: + registry = Component.shared_registry + assert registry is not None + return sorted(registry.get_component_names_by_type(Component)) + + +class TestBuildGroupApp: + def test_it_is_not_called_build(self) -> None: + """AppBuilder.build() returns a FastAPI; a second 'build' returning a tuple misleads.""" + assert not hasattr(entrypoint, "build") + + def test_it_builds_the_group_the_environment_names(self, project: Path) -> None: + app, config = entrypoint.build_group_app(environ={"BLUEPRINT_AGENTS": "order", "BLUEPRINT_GROUP": "finance"}) + + assert app is not None + assert config.get("app_name") == "the-process" + assert "order_order_service" in component_names() + + def test_it_reads_the_group_file_when_there_is_one(self, project: Path) -> None: + (project / "deployment-groups.yaml").write_text("groups:\n - name: finance\n agents: [order]\n") + + entrypoint.build_group_app(environ={}) + + assert "order_order_service" in component_names() + + def test_a_resolution_failure_propagates(self, project: Path) -> None: + """It raises; deciding what to do about it is main()'s job.""" + from blueprint.agents.group_config import GroupConfigError + + with pytest.raises(GroupConfigError): + entrypoint.build_group_app(environ={"BLUEPRINT_AGENTS": "not-in-this-image"}) + + +class TestMain: + def test_it_serves_the_application(self, project: Path) -> None: + with patch.object(entrypoint, "run_app") as run: + status = entrypoint.main(environ={"BLUEPRINT_AGENTS": "order", "BLUEPRINT_GROUP": "finance"}) + + assert status == 0 + run.assert_called_once() + + def test_the_application_it_serves_is_the_one_it_built(self, project: Path) -> None: + with patch.object(entrypoint, "run_app") as run: + entrypoint.main(environ={"BLUEPRINT_AGENTS": "order"}) + + app, config = run.call_args[0] + assert app is not None + assert config.get("app_port") == 8000 + + def test_a_bad_group_exits_non_zero(self, project: Path) -> None: + with patch.object(entrypoint, "run_app") as run: + status = entrypoint.main(environ={"BLUEPRINT_AGENTS": "not-in-this-image"}) + + assert status == 1 + run.assert_not_called() + + def test_nothing_is_served_when_the_group_is_bad(self, project: Path) -> None: + """The port must not be bound: a bound port is a pod that reports itself healthy.""" + with patch.object(entrypoint, "run_app") as run: + entrypoint.main(environ={"BLUEPRINT_AGENTS": "not-in-this-image"}) + + run.assert_not_called() + + def test_the_reason_reaches_stderr(self, project: Path, capsys: pytest.CaptureFixture[str]) -> None: + """Printed as well as logged: logging is configured by AppBuilder, which has not run.""" + with patch.object(entrypoint, "run_app"): + entrypoint.main(environ={"BLUEPRINT_AGENTS": "not-in-this-image"}) + + assert "Cannot start:" in capsys.readouterr().err + + def test_the_message_names_what_was_wrong(self, project: Path, capsys: pytest.CaptureFixture[str]) -> None: + with patch.object(entrypoint, "run_app"): + entrypoint.main(environ={"BLUEPRINT_AGENTS": "not-in-this-image"}) + + assert "not-in-this-image" in capsys.readouterr().err + + def test_a_critical_agent_that_cannot_be_loaded_exits_non_zero(self, project: Path) -> None: + (project / "agents.toml").write_text('[agents.order]\nmodule = "no.such.module:registration"\n') + + with patch.object(entrypoint, "run_app") as run: + status = entrypoint.main(environ={"BLUEPRINT_AGENTS": "order"}) + + assert status == 1 + run.assert_not_called() + + def test_it_returns_a_status_rather_than_exiting(self, project: Path) -> None: + """So a test asserts on the status; the __main__ guard is what turns it into an exit.""" + with patch.object(entrypoint, "run_app"): + assert entrypoint.main(environ={"BLUEPRINT_AGENTS": "order"}) == 0 + + +class TestItIsRunnableAsAModule: + def test_the_module_has_a_main_guard(self) -> None: + """`python -m blueprint.agents.entrypoint` is the container's command.""" + source = Path(entrypoint.__file__).read_text(encoding="utf-8") + + assert 'if __name__ == "__main__":' in source + assert "sys.exit(main())" in source + + +class TestOneDeclarationServesBothDeploymentShapes: + """The same module, run standalone and run as a group -- spec sec. 11's single ``main.py``. + + ``order_registration`` above is the whole of what a project's ``main.py`` needs to contain: + no ``AppBuilder``, no ``Config``, no ``run_app``, no ``if __name__``, no namespace and no + group. These cases prove that one such module serves both shapes, so there is nothing to + keep in sync between them. + """ + + def test_the_declaration_runs_standalone(self, project: Path) -> None: + """What an existing main.py does, unchanged: build it at the root and serve it.""" + config = Config(settings_files=["settings.toml"]) + + app = AppBuilder(config).with_registration(order_registration).build() + + assert app is not None + assert component_names() == ["order_service"] + + def test_the_same_declaration_runs_as_a_group_of_one(self, project: Path) -> None: + """The entry point path: group size 1 is how an agent gets a process to itself.""" + app, _ = entrypoint.build_group_app(environ={"BLUEPRINT_AGENTS": "order"}) + + assert app is not None + assert component_names() == ["order_order_service"] + + def test_the_same_declaration_runs_beside_another_agent(self, project: Path) -> None: + (project / "agents.toml").write_text( + f'[agents.order]\nmodule = "{_THIS}:order_registration"\n\n[agents.billing]\nmodule = "{_THIS}:order_registration"\n' + ) + + entrypoint.build_group_app(environ={"BLUEPRINT_AGENTS": "order,billing"}) + + assert component_names() == ["billing_order_service", "order_order_service"] + + def test_a_group_of_one_uses_the_agents_real_name(self, project: Path) -> None: + """Deliberate, and the migration consequence to know about (spec sec. 11). + + Standalone runs at the root, so its component is ``order_service`` and its routes sit + under ``/api``. A group of one runs under the agent's own name, so the component is + ``order_order_service`` and the routes move to ``/api/order`` -- which is what makes + local URLs and consumer identity match production instead of differing from it. + """ + entrypoint.build_group_app(environ={"BLUEPRINT_AGENTS": "order"}) + + assert component_names() == ["order_order_service"] diff --git a/tests/unit/agents/test_group_config.py b/tests/unit/agents/test_group_config.py new file mode 100644 index 00000000..4eb4c861 --- /dev/null +++ b/tests/unit/agents/test_group_config.py @@ -0,0 +1,269 @@ +"""Resolving which agents a process hosts, from a mounted file and from the environment. + +Both mechanisms are required and neither is preferred (spec sec. 5.1): a file suits a ConfigMap +mount and local development, environment variables suit ``docker run`` and CI and are what makes +Kubernetes roll a Deployment when the group changes. They compose, key by key. + +The failures matter more than the successes here. A group that resolves to the wrong contents +produces a pod that passes its probes with a queue nobody is consuming, so every way of getting +it wrong has to fail while the process is starting. +""" + +from pathlib import Path + +import pytest + +from blueprint.agents.config import Config +from blueprint.agents.group_config import AgentSpec, GroupConfig, GroupConfigError + +AGENT_MAP = """ +[agents.invoice] +module = "agents.invoice.declaration:registration" + +[agents.order] +module = "agents.order.declaration:registration" + +[agents.dunning] +module = "agents.dunning.declaration:registration" +""" + +GROUP_FILE = """ +groups: + - name: finance + agents: [invoice, order] + cache_names: [sessions] + - name: contracts + agents: [dunning] +""" + + +@pytest.fixture +def project(tmp_path: Path) -> Config: + """A project root with an agent map, a group file and a settings tree.""" + (tmp_path / "agents.toml").write_text(AGENT_MAP) + (tmp_path / "deployment-groups.yaml").write_text(GROUP_FILE) + settings = tmp_path / "settings.toml" + settings.write_text('[development]\napp_environment = "development"\napp_name = "the-process"\n') + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + +class TestFromTheGroupFile: + def test_the_named_group_is_loaded(self, project: Config) -> None: + group = GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "finance"}) + + assert group.name == "finance" + assert group.agent_names == ("invoice", "order") + + def test_the_agents_module_comes_from_the_image(self, project: Config) -> None: + """What an agent *is* belongs to the image; only which agents run is the deployment's.""" + group = GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "finance"}) + + assert group.agents[0] == AgentSpec(name="invoice", module="agents.invoice.declaration:registration", critical=True) + + def test_declared_caches_are_carried(self, project: Config) -> None: + """A cache is process-wide, so it is the group's to declare rather than an agent's.""" + group = GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "finance"}) + + assert group.cache_names == ("sessions",) + + def test_another_group_in_the_same_file(self, project: Config) -> None: + group = GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "contracts"}) + + assert group.agent_names == ("dunning",) + + def test_a_single_group_file_needs_no_group_name(self, tmp_path: Path) -> None: + (tmp_path / "agents.toml").write_text(AGENT_MAP) + (tmp_path / "deployment-groups.yaml").write_text("groups:\n - name: only\n agents: [invoice]\n") + settings = tmp_path / "settings.toml" + settings.write_text('[development]\napp_environment = "development"\n') + config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + assert GroupConfig.resolve(config, environ={}).name == "only" + + def test_several_groups_and_no_name_is_ambiguous(self, project: Config) -> None: + with pytest.raises(GroupConfigError, match="which one to run is ambiguous"): + GroupConfig.resolve(project, environ={}) + + def test_an_unknown_group_name_is_refused(self, project: Config) -> None: + with pytest.raises(GroupConfigError, match="Group 'nope' is not declared"): + GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "nope"}) + + def test_the_refusal_lists_what_the_file_has(self, project: Config) -> None: + with pytest.raises(GroupConfigError, match="contracts, finance"): + GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "nope"}) + + def test_a_configured_path_is_honoured(self, project: Config, tmp_path: Path) -> None: + """The path is configuration, so one image serves a mount, a bind mount and a repo file.""" + elsewhere = tmp_path / "mounted" / "group.yaml" + elsewhere.parent.mkdir() + elsewhere.write_text("groups:\n - name: mounted\n agents: [order]\n") + + group = GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP_CONFIG": str(elsewhere)}) + + assert (group.name, group.agent_names) == ("mounted", ("order",)) + + def test_a_malformed_file_is_an_error(self, project: Config, tmp_path: Path) -> None: + """An absent file is fine; a mounted one that cannot be parsed was meant to be used.""" + broken = tmp_path / "broken.yaml" + broken.write_text("groups: [oops\n") + + with pytest.raises(GroupConfigError, match="could not be read"): + GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP_CONFIG": str(broken)}) + + def test_a_file_without_groups_is_an_error(self, project: Config, tmp_path: Path) -> None: + empty = tmp_path / "empty.yaml" + empty.write_text("something_else: 1\n") + + with pytest.raises(GroupConfigError, match="declares no 'groups' list"): + GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP_CONFIG": str(empty)}) + + +class TestFromTheEnvironmentAlone: + def test_agents_can_come_from_the_environment_with_no_file(self, tmp_path: Path) -> None: + """The docker run and CI shape: no file, no mount.""" + (tmp_path / "agents.toml").write_text(AGENT_MAP) + settings = tmp_path / "settings.toml" + settings.write_text('[development]\napp_environment = "development"\n') + config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + group = GroupConfig.resolve(config, environ={"BLUEPRINT_AGENTS": "invoice,dunning", "BLUEPRINT_GROUP": "adhoc"}) + + assert (group.name, group.agent_names) == ("adhoc", ("invoice", "dunning")) + + def test_whitespace_around_names_is_tolerated(self, project: Config) -> None: + group = GroupConfig.resolve(project, environ={"BLUEPRINT_AGENTS": " invoice , order "}) + + assert group.agent_names == ("invoice", "order") + + def test_a_group_with_no_name_is_called_ungrouped(self, project: Config) -> None: + """An empty segment in the connection name and the telemetry resource reads as a bug.""" + group = GroupConfig.resolve(project, environ={"BLUEPRINT_AGENTS": "invoice"}) + + assert group.name == "ungrouped" + + def test_no_agents_anywhere_is_an_error(self, tmp_path: Path) -> None: + (tmp_path / "agents.toml").write_text(AGENT_MAP) + settings = tmp_path / "settings.toml" + settings.write_text('[development]\napp_environment = "development"\n') + config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + with pytest.raises(GroupConfigError, match="No agents were resolved"): + GroupConfig.resolve(config, environ={}) + + +class TestPrecedence: + def test_the_environment_overrides_the_files_agent_list(self, project: Config) -> None: + """Key by key: a Deployment changes the list without restating the group.""" + group = GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "finance", "BLUEPRINT_AGENTS": "dunning"}) + + assert group.agent_names == ("dunning",) + + def test_the_files_other_values_survive_the_override(self, project: Config) -> None: + group = GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "finance", "BLUEPRINT_AGENTS": "dunning"}) + + assert (group.name, group.cache_names) == ("finance", ("sessions",)) + + def test_the_source_of_each_value_is_logged(self, project: Config, caplog: pytest.LogCaptureFixture) -> None: + """The first question asked of a group with the wrong contents is where they came from.""" + with caplog.at_level("INFO", logger="blueprint.agents.group_config"): + GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "finance", "BLUEPRINT_AGENTS": "dunning"}) + + assert "'agents' resolved from $BLUEPRINT_AGENTS" in caplog.text + assert "'name' resolved from file" in caplog.text + + def test_the_resolved_group_is_logged(self, project: Config, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level("INFO", logger="blueprint.agents.group_config"): + GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "finance"}) + + assert "Resolved group 'finance' with 2 agent(s): invoice, order" in caplog.text + + +class TestCriticality: + def test_every_agent_is_critical_by_default(self, project: Config) -> None: + """A group missing a consumer is worse than no pod: the default cannot be permissive.""" + group = GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "finance"}) + + assert all(agent.critical for agent in group.agents) + + def test_a_critical_subset_marks_only_those(self, project: Config) -> None: + group = GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "finance", "BLUEPRINT_CRITICAL_AGENTS": "invoice"}) + + assert {agent.name: agent.critical for agent in group.agents} == {"invoice": True, "order": False} + + def test_the_file_can_declare_the_subset(self, project: Config, tmp_path: Path) -> None: + path = tmp_path / "with-critical.yaml" + path.write_text("groups:\n - name: finance\n agents: [invoice, order]\n critical_agents: [order]\n") + + group = GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP_CONFIG": str(path)}) + + assert {agent.name: agent.critical for agent in group.agents} == {"invoice": False, "order": True} + + +class TestAgainstTheAgentMap: + def test_an_agent_the_image_does_not_contain_is_refused(self, project: Config) -> None: + """The seam that turns a config typo into a crash-loop with a readable message.""" + with pytest.raises(GroupConfigError, match="which this image does not contain"): + GroupConfig.resolve(project, environ={"BLUEPRINT_AGENTS": "invoice,typo"}) + + def test_the_refusal_lists_what_the_image_has(self, project: Config) -> None: + with pytest.raises(GroupConfigError, match="dunning, invoice, order"): + GroupConfig.resolve(project, environ={"BLUEPRINT_AGENTS": "typo"}) + + def test_a_non_critical_missing_agent_is_skipped(self, project: Config, caplog: pytest.LogCaptureFixture) -> None: + """The deployment said it would rather run the rest, so it does -- loudly.""" + with caplog.at_level("ERROR", logger="blueprint.agents.group_config"): + group = GroupConfig.resolve(project, environ={"BLUEPRINT_AGENTS": "invoice,typo", "BLUEPRINT_CRITICAL_AGENTS": "invoice"}) + + assert group.agent_names == ("invoice",) + assert "is not in this image's agent map" in caplog.text + + def test_a_missing_agent_map_is_an_error(self, tmp_path: Path) -> None: + settings = tmp_path / "settings.toml" + settings.write_text('[development]\napp_environment = "development"\n') + config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + with pytest.raises(GroupConfigError, match="No agent map at"): + GroupConfig.resolve(config, environ={"BLUEPRINT_AGENTS": "invoice"}) + + def test_an_entry_without_a_module_is_an_error(self, project: Config, tmp_path: Path) -> None: + path = tmp_path / "bad-map.toml" + path.write_text("[agents.invoice]\ndescription = 'no module'\n") + + with pytest.raises(GroupConfigError, match="has no 'module'"): + GroupConfig.resolve(project, environ={"BLUEPRINT_AGENTS": "invoice", "BLUEPRINT_AGENT_MAP": str(path)}) + + def test_an_empty_agent_map_is_an_error(self, project: Config, tmp_path: Path) -> None: + path = tmp_path / "empty-map.toml" + path.write_text("# nothing here\n") + + with pytest.raises(GroupConfigError, match="declares no \\[agents"): + GroupConfig.resolve(project, environ={"BLUEPRINT_AGENTS": "invoice", "BLUEPRINT_AGENT_MAP": str(path)}) + + +class TestAgentNamesAreAgentNames: + def test_a_name_that_cannot_be_a_namespace_is_refused(self, project: Config) -> None: + """It becomes a namespace, so rejecting it here names the group file instead of a constructor.""" + with pytest.raises(GroupConfigError, match="cannot be a namespace"): + GroupConfig.resolve(project, environ={"BLUEPRINT_AGENTS": "Invoice"}) + + def test_a_name_with_a_hyphen_is_refused(self, project: Config) -> None: + with pytest.raises(GroupConfigError, match="cannot be a namespace"): + GroupConfig.resolve(project, environ={"BLUEPRINT_AGENTS": "in-voice"}) + + def test_the_same_agent_twice_is_refused(self, project: Config) -> None: + with pytest.raises(GroupConfigError, match="more than once"): + GroupConfig.resolve(project, environ={"BLUEPRINT_AGENTS": "invoice,invoice"}) + + +class TestTheValueObject: + def test_it_performs_no_io_once_constructed(self) -> None: + """Constructed literally, so a test states a composition instead of arranging files.""" + group = GroupConfig(name="finance", agents=(AgentSpec(name="invoice", module="pkg:reg"),)) + + assert (group.name, group.agent_names, group.cache_names) == ("finance", ("invoice",), ()) + + def test_it_is_frozen(self) -> None: + group = GroupConfig(name="finance", agents=()) + + with pytest.raises(Exception, match="cannot assign to field"): + group.name = "other" # type: ignore[misc] From 4b9eaa12242d899b0502ce051f76d38b8b66a967 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:44:55 +0200 Subject: [PATCH 011/133] refactor(app-builder): one declaration surface, assembled into a group Phase 8b. Every with_* call is recorded and built in build(), AgentBuilder records and builds against the agent's own configuration view, and AgentGroup collects named declarations into one process. The three duplicate declaration surfaces are deleted (AgentRegistration, RegisteredComponent, NamespaceBuilder, with_namespace/with_registration). A cache is private to the agent that declared it, keyed on (namespace, name) with its own directory and Redis prefix; every health check is attributed to its agent; an agent's own settings file merges under its scope. Co-Authored-By: Claude Opus 5 (1M context) --- ...26-08-28-multi-agent-grouping-changelog.md | 1124 ++++++++++++++- docs/plans/2026-08-28-multi-agent-grouping.md | 377 +++++- docs/plans/2026-09-10-builder-unification.md | 296 ++++ ...026-09-10-config-validation-unification.md | 159 +++ docs/specs/2026-08-28-multi-agent-grouping.md | 170 ++- src/blueprint/agents/__init__.py | 6 +- src/blueprint/agents/agent/agent_builder.py | 150 ++- src/blueprint/agents/agent_group.py | 363 +++++ src/blueprint/agents/app_builder.py | 1200 +++++++++-------- src/blueprint/agents/component/component.py | 17 +- src/blueprint/agents/component/namespace.py | 49 + src/blueprint/agents/component/registry.py | 156 ++- src/blueprint/agents/config/__init__.py | 4 +- src/blueprint/agents/config/config.py | 235 ++++ src/blueprint/agents/entrypoint.py | 24 +- src/blueprint/agents/group_config.py | 35 +- .../agents/handler/event_handler_base.py | 11 + .../agents/io/api/actuators/actuator_api.py | 50 +- .../io/api/actuators/health/__init__.py | 3 +- .../io/api/actuators/health/health_base.py | 42 +- .../io/api/actuators/health/health_cache.py | 40 +- .../agents/io/api/utilities/cache.py | 32 +- .../infrastructure/agent_scoped_cache.py | 157 --- .../infrastructure/cache_backend_factory.py | 91 +- src/blueprint/agents/services/service_base.py | 6 +- tests/unit/agents/agent/test_agent_builder.py | 126 +- tests/unit/agents/app_builder/TESTS.md | 12 +- tests/unit/agents/app_builder/conftest.py | 13 + .../app_builder/test_agent_registration.py | 217 --- .../agents/app_builder/test_app_builder.py | 43 +- .../app_builder/test_build_namespaces.py | 106 +- .../app_builder/test_declaration_surface.py | 216 +++ .../app_builder/test_deferred_wiring.py | 348 +++++ .../agents/app_builder/test_named_caches.py | 123 +- .../app_builder/test_namespace_builder.py | 315 ----- .../app_builder/test_namespace_placement.py | 293 ++++ .../app_builder/test_route_namespacing.py | 104 +- .../agents/app_builder/test_with_group.py | 270 ---- .../agents/component/test_name_uniqueness.py | 30 + tests/unit/agents/component/test_registry.py | 105 ++ .../config/test_agent_settings_fragments.py | 251 ++++ .../api/actuators/health/test_health_cache.py | 100 +- .../io/api/actuators/test_actuator_api.py | 53 +- .../test_event_processing_namespaces.py | 11 +- .../infrastructure/test_agent_scoped_cache.py | 169 --- .../test_cache_backend_factory.py | 44 + tests/unit/agents/test_agent_group.py | 493 +++++++ tests/unit/agents/test_entrypoint.py | 25 +- .../unit/agents/test_frozen_compatibility.py | 256 ++++ tests/unit/agents/test_group_config.py | 16 +- 50 files changed, 6402 insertions(+), 2134 deletions(-) create mode 100644 docs/plans/2026-09-10-builder-unification.md create mode 100644 docs/plans/2026-09-10-config-validation-unification.md create mode 100644 src/blueprint/agents/agent_group.py delete mode 100644 src/blueprint/agents/services/infrastructure/agent_scoped_cache.py delete mode 100644 tests/unit/agents/app_builder/test_agent_registration.py create mode 100644 tests/unit/agents/app_builder/test_declaration_surface.py create mode 100644 tests/unit/agents/app_builder/test_deferred_wiring.py delete mode 100644 tests/unit/agents/app_builder/test_namespace_builder.py create mode 100644 tests/unit/agents/app_builder/test_namespace_placement.py delete mode 100644 tests/unit/agents/app_builder/test_with_group.py create mode 100644 tests/unit/agents/config/test_agent_settings_fragments.py delete mode 100644 tests/unit/agents/services/infrastructure/test_agent_scoped_cache.py create mode 100644 tests/unit/agents/test_agent_group.py create mode 100644 tests/unit/agents/test_frozen_compatibility.py diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index ca7ef424..3b3c48fd 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -20,8 +20,8 @@ platform of 100 agents pays the ~154 MB Python and library baseline 100 times. T **which agents share a process a deployment parameter rather than an architectural commitment.** Components gain an optional **namespace** (`""` by default, so nothing existing changes). A -namespace owns its own handlers, agent runtime, REST routes, AI client, thread pool and broker -connection, while genuinely shared infrastructure -- the port, the health endpoint, the caches -- +namespace owns its own handlers, agent runtime, REST routes, AI client, thread pool, caches and +broker connection, while genuinely shared infrastructure -- the port and the health endpoint -- stays single. Which namespaces a process hosts is resolved at startup from a group configuration, and Kubernetes runs one Deployment per group: a group of one gives today's process isolation, a group of twenty gives the shared-interpreter memory profile, and moving an agent between groups @@ -3897,6 +3897,529 @@ existing agent from standalone to a group of one therefore moves its routes and identity, which is a migration with consequences rather than a rename; phase 10 is where that gets written up for a project to follow. +### The builder surface: one class, and the group's rules in the class that imposes them + +**No code changed. Two proposals written, and the spec and plan amended to match.** Recorded here +because the decisions are the reviewable artefact, and because the next phase is their +implementation. + +`docs/plans/2026-09-10-builder-unification.md` -- **phase 8b**, decided, not written. +`docs/plans/2026-09-10-config-validation-unification.md` -- deliberately **not** part of this +feature. + +**The problem, restated correctly.** Adding one `with_*` method today means editing four places: +`AppBuilder`, `AgentRegistration`, `NamespaceBuilder`, and `AgentRegistration.apply`'s `appliers` +dict. Three of those fail *silently* -- the capability is simply absent from that surface -- and +nothing tells the next developer the four exist. The duplication looked like a style problem and +is not: `AppBuilder.with_handler(H)` **constructs `H` immediately**, and a component constructed +before a namespace exists belongs to the root for ever, so a second class had to exist to defer +construction until a namespace was in force. `AgentRegistration` is that class, `NamespaceBuilder` +is its block-form sugar, and `appliers` is the bridge. So the fix is not to share the methods but +to remove the reason they diverged: an `AppBuilder` that **records** instead of constructing +serves both shapes, and the other three have no purpose left. Four sites become one. + +**Collection is its own class.** An intermediate design put an `absorb(builder, namespace=...)` +method on `AppBuilder`; the user's objection retired it -- an `AppBuilder` does not know it is +being collected, because the collection happens elsewhere. So `AgentGroup` (new class, new module) +takes named builders and one configuration and drives one wiring pass, `AppBuilder` keeps exactly +one job, and `with_group` / `from_group` move off `AppBuilder` too. The refusals move with them, +which is the better half of the change: the group's restrictions belong to the thing imposing +them, so **standalone stays permissive and the collector enforces**. That is also the rule stated +plainly -- standalone allows more; to join a group you accept the group's constraints. + +**Decisions, D1-D7 in the proposal:** + +- **Standalone knows nothing about namespaces.** `build()` wires at the root, and the agent's name + lives only in the group configuration. Consequence, stated rather than hidden: a standalone agent + moved into a group changes its queue group and durable once, on the first grouped deploy. +- **Refusals at assembly, each named:** instances (their namespace and registry key were fixed + before the group existed), `AppBuilder(config)` (one process, one settings tree, one port), a + builder already built. Nothing loses a capability -- the factory form recovers the instance case. + No deprecation warnings: sec. 10 makes the standalone shape supported indefinitely, so warning + about it every startup would be crying wolf. +- **A cache is private to the agent that declared it.** Names qualified per namespace, no root + fallback, no shared-cache opt-in. This finally implements what spec sec. 8 always said and only + half of which was built. It **deletes** `GroupConfig.cache_names` and `AgentScopedCache`: + separate stores make the isolation structural, so the prefixing lens has nothing left to prevent. +- **A health checker's key carries its agent.** Two agents calling + `with_health_checker("db", ...)` currently collide in a dict and one disappears silently. + `(namespace, name)` is stored as data, the prefix is its rendering -- phase 9's + `readiness_policy = "critical"` has to attribute a failing checker to an agent, and recovering + that by splitting a string breaks the moment a name contains the separator. +- **Group settings are defaults, and only defaults**; each agent's own `settings.toml` merges under + that agent's scope. So an agent may set any key for itself and can never change what another + agent or the process sees -- which closes the fragment-merge open point below rather than + answering it. +- **`AgentBuilder` records too**, and this fixes a live defect rather than only changing a shape. + `AgentBuilder.__init__` requires a `Config`, and `Component._shared_config` deliberately has no + public read path -- so the factory form phase 8 documents, + `lambda: AgentBuilder(config, runtime_name="orders").build()`, **cannot be written at all** in a + declaration-only `main.py`. Passing the unbuilt builder to `with_agent` and calling + `agent.build(config.for_namespace(ns))` at wiring time removes the lambda and a second latent bug + with it: a lambda closes over whichever configuration was in scope where it was written, which in + a group is the wrong one. + +**Two behavioural changes worth knowing.** `configure_logging()` moves from `__init__` into +`build()` -- with nothing constructed before `build()`, that is where it belongs. And registration +order keeps its meaning, but an instance recorded *after* a class registers *before* it, which can +flip equal-priority tie-breaking; `build()` knows both the recorded order and which entries were +instances, so it raises on that combination instead of silently reordering. + +**Checked against the four Builder anti-patterns**, which was the user's question. Collect-then-wire +is the pattern, not an abuse of it; what exists today is the smell. (1) Side effects during +accumulation -- removed. (2) A silently single-use builder -- `build()` calls +`Component.configure`, which refuses a second call and surfaces as someone else's error; it gets +its own message. (3) Requiring the product's context in the constructor -- `config` moves to +`build()`. (4) Replay drift -- mitigated by storing the *method name* and resolving it with +`getattr`, plus a test asserting the declaration surface and the replay agree. + +**Deferred, and not to be touched during 8b:** configuration validation. Four mechanisms disagree +about what a missing key means, and two findings are worth recording because they are not visible +from reading the code: + +- **The three root validators cannot fail.** `must_exist=True` together with `default=` never + fires -- Dynaconf injects the default. Verified against the installed version: + `Validator("app_name", must_exist=True, default="agent_blueprint")` yields + `'agent_blueprint'`; drop the default and the same declaration raises. So the only condition + among the three that can actually fail is `is_type_of=int` on `app_port`, and an application with + no `settings.toml` starts and calls itself `agent_blueprint`. The defaults are defensible; the + code *claiming* `must_exist=True` is not, because the next genuinely required key gets copied + from it. +- **The actuator's configuration branches are dead.** `Config.validate()` runs inside + `__init__` and raises, so a `Config` that exists has always passed and `_validation_errors` is + always empty -- making `actuator_api.py:95` (readiness 503 carrying the reasons) and `:149` + (liveness warning) unreachable. The readiness probe was written for a behaviour the process does + not have. + +**Amended in the spec:** sec. 2 (Registration -> Declaration), 4.1 (`AgentGroup`, no cache list), +4.2 (deferred wiring normative, the refusal table, config resolution order, order semantics), 4.3 +(the ContextVar's owner), 5.3 (defaults-only group settings; process-scope keys raise), 8 (caches +declared-only), 9 (startup sequence), 10 (three new compatibility rows), 11 (`main.py` and the +optional `create_app`). + +**Amended in the plan:** phase 8b added between 8 and 9 with an eight-step breakdown, and it is +before 9 deliberately because 9 needs D4's attribution data; phases 0 and 3 carry superseded +banners rather than being deleted, because their ContextVar and `with_cache`-signature reasoning +still stands; the migration path corrected from two file changes to **three** (`agents.toml` was +missing) and its `main.py` rewritten; the dual-branch migration recipe under *File change summary* +removed, since it contradicted the rejection stated 600 lines above it; `python -m +blueprint.agents.orchestrator` corrected to `entrypoint`; the *not a separate orchestrator* +argument reconciled with `AgentGroup`; cache and executor sharing rows corrected; testing +expectations extended. + +### Phase 8b, step 1 -- `AppBuilder` records, and `build()` is the only thing that builds + +**`Declaration` (`app_builder.py`), the five `with_*` and `with_cache` store instead of +constructing, `build(config=None)` replays them.** This is the change the whole unification rests +on: `with_handler(H)` used to construct `H` on the spot, so a component declared before any +namespace existed belonged to the root for ever -- which is the only reason `AgentRegistration` +had to exist as a second class. It no longer does. + +- **`Declaration`** is a frozen value object holding `kind`, `target`, `name`, `namespace` and + `kwargs`. `target` is a class, a zero-argument factory, an already-built component, or `None` + for a cache. `is_built` reports whether `target` is already a `Component`, which is what the + order check below reads. +- **`_record(kind, target, namespace, kwargs, *, name, method)`** replaces `_register`. It + resolves the namespace **at the call**, not at construction -- `namespace or + current_namespace()` -- because the caller's scope is what carries it and by the time the + replay runs no scope is in force. Two checks stay at record time, both answerable there and + both better reported at the offending line: `validate_namespace(namespace)`, and the + already-built-instance-for-another-namespace refusal (unchanged wording, moved from + `_register`). +- **`_construct(declaration)`** is the other half of the old `_register`: it enters + `_construction_scope(declaration.namespace)` and calls `declaration.target(**kwargs)`, or + adopts the instance, then assigns the explicit name. A class and a factory are now handled by + the same branch, because a class *is* a zero-argument factory once its keyword arguments are + applied -- which is what lets `lambda: AgentBuilder(...).build()` be deferred exactly as far as + a class is. +- **`declarations`** is a public read-only snapshot, for the collector in step 3 and for a test + that wants to assert what a `main.py` declares without building any of it. +- **`_construct_declarations()`** replays in call order, then creates the caches. Caches last on + purpose: a cache backend is itself a `Component`, so building one mid-pass would interleave it + into the registry's insertion order and shift every component declared after it. + +**`build(config=None)`** gained three things. It refuses a second call with its own message +rather than surfacing `Component.configure`'s "already set" from three frames down. It settles +the configuration -- given to `__init__`, given here, or, when neither, loaded from +`DEFAULT_SETTINGS_FILES`, which is what makes the migrated `AppBuilder().build()` shape work. +And it injects the configuration **before** constructing anything, which is strictly more correct +than the old order: every component now exists in a process that already has its configuration. + +**`_check_declaration_order`** is the one new refusal. An instance is constructed by the caller +at its own source line and is therefore in the registry *before* `build()` runs, while a class is +constructed during the replay -- so an instance recorded after a class registers before it. +That is not cosmetic: `DispatchIndex.build` resolves handler priority ties by registration order. +The check runs **after** construction, deliberately, because a class's priority is a property of +the object and reading it off the class would mean parsing a default argument and being wrong +about every handler that computes one; the application is not returned when it raises, so the +components already in the registry go nowhere. It fires only for handlers, only within one +namespace, and only at equal priority -- the only case where the order decides anything. + +**`configure_logging()` moves, but not all the way to `build()`.** The plan says `build()`; that +is right for a declaration-only `main.py` and wrong for the shape the scaffolder still generates, +where `with_service(OrderService())` constructs at its source line and the builder's own +`with_namespace` / `with_cache` calls log as they go. So the call lives in one place, +`_use_config`, which runs from `__init__` when a configuration is given there and from `build()` +when it is not. An existing `AppBuilder(config)` chain therefore logs exactly as it did. + +**Smaller changes that this needed:** + +- `EventHandlerBase.priority` -- a public property over `_priority`. The ordering rule is + enforced from outside the class, and `__lt__` answers the sorting question, not that one. +- `CacheBackendFactory._validate_name` -> `validate_name`. `with_cache` calls it at record time, + because a cache name becomes a directory segment and a Redis key prefix: it crosses the process + boundary, so it is validated where it is written. The factory still validates when it creates + the backend -- it owns the rule, and nothing reaches it only through the builder. +- `DEFAULT_SETTINGS_FILES` moved from `entrypoint.py` to `config/config.py` and is exported from + the `config` package. Two callers now need the same answer: the container entry point, and + `build()` when the application handed it no configuration. +- `AgentRegistration.apply` hands a factory to the builder instead of calling it. A factory used + to be invoked at apply time -- producing an instance that landed in the registry before every + class of the same agent -- and now defers as far as a class does. +- The registry-creation fallback considered for `build()` was **not** added: `AppBuilder.__init__` + constructs a `TelemetryManager`, which is a `Component`, so the shared registry always exists by + the time `build()` runs. Verified rather than assumed. + +**Behavioural change, stated for the migration guide:** nothing is in the registry until +`build()`, so code that looks a component up between `with_*` calls breaks. The framework's own +convention already forbids it -- collaborators are resolved in `on_startup` -- so the fix is the +documented pattern. + +**Tests.** New `tests/unit/agents/app_builder/test_deferred_wiring.py` (32 cases): nothing is +constructed or registered before `build()`, what a declaration records, the order refusal and the +three cases it must *not* fire on, where the configuration may be handed over, the single-use +guard, and an application that declares nothing. The existing suites that asserted on the registry +straight after a `with_*` call now say when construction happens, through a `realize()` helper in +`conftest.py` that runs `build()`'s own replay pass without the actuator, root API and FastAPI +application that would drown the assertion. 1962 unit tests pass, 34 more than before this step. + +--- + +### Phase 8b gains a step 9: the rules this overhaul establishes, written where they will be read + +**No code changed. A step was added to the plan, and a documentation audit was run to decide where +it lands.** Recorded here because the audit's findings are the reviewable artefact and because they +changed the answer. + +**The question.** This overhaul settles principles -- collect then wire, the namespace is ambient, +a name that leaves the process is validated and never repaired -- that a later feature can violate +without anyone noticing. They exist today only in this changelog, which is now over 4600 lines and +which nobody will read end to end. So: write them down as rules, and put a test behind the ones a +test can hold. Placed **last** in phase 8b, because a rule can only describe something that exists. + +**The finding that decided the location.** `CLAUDE.md:5` has always said *"See `AGENTS.md` for +architecture, component patterns, and testing conventions shared across all AI assistants."* +**`AGENTS.md` has never existed.** `git log --all --diff-filter=A -- AGENTS.md` returns nothing -- +it was not written and later deleted, it was cited into existence. Worse, +`docs/plans/2026-06-10-sessions-job-handler.md:122` quotes what it *states* about versioning, so a +claim has already been sourced to a document that is not there. + +That inverted the recommendation. A new `docs/concepts/design-rules.md` would have added a file and +left the dead pointer beside a live one; writing `AGENTS.md` turns a reference that resolves nowhere +into one that resolves, at no net cost in files. + +**The rest of the audit**, over all 61 tracked markdown files. Two real problems, both duplication +rather than absence: + +- **`docs/superpowers/`** holds `plans/` and `specs/` mirroring `docs/plans` and `docs/specs` -- + 3 files, 2079 lines -- and **nothing in the repository links to any of them.** A second, + abandoned home for the same two document types. +- **Four cache documents totalling 968 lines:** `docs/concepts/caching.md` (347), + `docs/concepts/cache-system-overview.md` (232), `docs/concepts/cache-architecture.md` (181), + `docs/guides/caching-getting-started.md` (208). `docs/README.md` links one of the four. + +Two further references resolve nowhere and are legitimate: `docs/guides/multi-agent-setup.md` is a +phase 10 deliverable, and `agent_group.py` is phase 8b step 3. One is not: +`docs/development-workflow.md`, cited by this plan's own file summary and never written. Everything +else that a naive sweep flags -- `nats.py`, `config.py`, `settings.toml` -- is this repository's +bare-filename shorthand, which is convention rather than rot; the audit script resolves those +against `src/blueprint/agents/` before reporting. + +**What step 9 will do**, in three commits: write `AGENTS.md`; add +`tests/unit/agents/test_design_rules.py` with one guard per mechanically checkable rule -- including +a reference-resolution guard, which is the check that would have caught `AGENTS.md` and is what +makes the rest durable; and clean up the duplication above. Step 8's surfaces-agree test moves into +that file rather than being written twice. + +**The user's instruction, recorded because it widened the step:** `AGENTS.md` alone is not enough -- +everything else has to be coherent too. Hence part 3, which is documentation debt this feature did +not create. + +--- + +### Phase 8b, step 2 -- `AgentBuilder` records too, and is built against its own agent's configuration + +**This fixes a live defect, not only a shape.** `AgentBuilder.__init__` required a `Config`, and +`Component._shared_config` deliberately has no public read path (config rework step 2b). So in a +`main.py` that only declares -- which is every grouped agent -- there was no configuration in +scope to pass, and the factory form phase 8 documents, +`lambda: AgentBuilder(config, runtime_name="orders").build()`, **could not be written at all**. +`AgentBuilder` was unusable in exactly the deployment shape this feature exists for. + +**`agent/agent_builder.py`** + +- **`__init__(config: Config | None = None, ...)`.** `config` stays the first positional + parameter, so `AgentBuilder(config, runtime_name="x")` is untouched; it is now optional, which + is what makes an unbuilt builder declarable. +- **`with_model_from_config` records.** It used to call `self._config.get_ai_config(...)` on the + spot, apply the `model_name` override and raise all three of its refusals. Now it sets + `_model_from_config` and `_model_name_override` and returns. The reading moved to a new + `_resolve_ai_config`, called from `build()`, which carries the same three refusals with the + same messages, naming the same runtime. +- **`build(config: Config | None = None, **kwargs)`.** The single-use guard moved to the top, + ahead of the "model must be configured" check it used to follow -- with `_ai_config` now + resolved *inside* `build`, the old first check tested a field that is `None` on every call, so + the two had to be reordered and the model check rewritten to ask whether + `with_model_from_config()` was called rather than whether it left a result. Then + `_resolve_config`, `_resolve_ai_config`, and the AI client, prompt and metrics as before, all + reading the resolved configuration rather than `self._config` directly. +- **`_resolve_config` -- and its precedence is the opposite of `AppBuilder`'s, deliberately.** + `build(config)` **wins** over `AgentBuilder(config)`. An `AppBuilder` is the application, so + nothing above it knows better and two configurations mean the author is confused -- step 1 made + that a refusal. An `AgentBuilder` sits *inside* an application, and what the application passes + is the view scoped to this agent's namespace (C5), which is the whole point of D6. A + constructor argument is a convenience for the standalone chain, so it yields. When the two + differ the choice is logged at DEBUG. At the root `for_namespace("")` returns the loader + itself, so for a single-agent application they are the same object and nothing is chosen. +- **`_require_config`** raises when neither was given, naming both places one can be passed. + Not defaulted to `DEFAULT_SETTINGS_FILES` the way `AppBuilder.build()` is: an `AgentBuilder` + always sits inside an application that already has a configuration, so a missing one is a + wiring mistake rather than a case to guess a settings file for. +- **`runtime_name`** is now a public property. The application names the agent in its logs and + its failures before the agent exists. +- `get_model_settings()` reads through `_require_config()`, so it is unchanged for anyone who + constructed with a configuration and raises a named error for anyone who did not. + +**`app_builder.py`** + +- **`with_agent` accepts an unbuilt `AgentBuilder`** -- a class, an unbuilt builder, a factory, + or an instance (D6). `_record` had to learn it, because an `AgentBuilder` is neither a + `Component` nor callable and would have been refused by the `not callable(target)` branch. It + is accepted for `kind == "agent"` only; passed to any other `with_*` it is refused with a + message saying where it belongs. +- **`_construct(declaration, config)`** gained the configuration and a third branch: + + elif isinstance(declaration.target, AgentBuilder): + with _construction_scope(declaration.namespace): + instance = declaration.target.build(config.for_namespace(declaration.namespace), **declaration.kwargs) + + That one line is D6: the model, prompt and metrics of a grouped agent are read from its own + configuration section rather than from the root or from a neighbour's. `_construct_declarations` + takes the configuration and passes it through; `build()` hands it the one it resolved. +- `AgentRegistration.with_agent` and `_add` learned the same, and the docstring's `lambda` + example is replaced by the builder form. The factory form still works and is still the escape + hatch for anything a plain call cannot express -- but it is no longer what the documentation + recommends, because a lambda closes over whichever configuration was in scope where it was + written, which in a group is another agent's. +- Importing `AgentBuilder` into `app_builder.py` introduces no cycle: `agent_builder.py` imports + the config package, the AI clients and `AgentRuntime`, and none of them import the builder. + Verified by import, not by reading. + +**Behavioural change:** the three model refusals move from `with_model_from_config()` to +`build()`. An application that misconfigures its model now learns at build time rather than at +declaration time. Nothing else about them changed -- same conditions, same messages, same runtime +named. + +**Tests.** `tests/unit/agents/agent/test_agent_builder.py` gains `TestTheModelRefusalsMovedToBuild` +(the three refusals, plus one asserting the message still names the runtime) and +`TestWhereTheConfigurationComesFrom` (constructible without a config; `build(config)` supplies +one; neither is refused with a message naming both places; `build`'s wins over the constructor's; +`get_model_settings` without one is refused; `runtime_name` readable before building), and +`TestWithModelFromConfig` now pins that it reads no configuration at all. +`test_deferred_wiring.py` gains `TestAnUnbuiltAgentBuilder`: recorded rather than refused, not +built by the `with_` call, handed the namespace-scoped view, handed the loader itself at the root, +constructor arguments forwarded to `build`, and refused by the other `with_*` methods. The +`realize()` helper passes the builder's configuration through the replay. 1979 unit tests pass, +17 more than before this step. + +--- + +### Phase 8b, step 3 -- `AgentGroup`: named declarations in, one application out + +**New module `agent_group.py`.** Collection is its own unit, in a class `AppBuilder` has never +heard of. That is the correction that killed the earlier `absorb(builder)` design: an +`AppBuilder` records what *one* agent is made of and never learns it can be collected, so every +rule that exists only because agents share a process lives in the new file rather than being +scattered into the builder, where it would punish the single-agent case for a situation it is +not in. + +**`AgentGroup(name, agents, *, cache_names=())`** takes a `Mapping[str, AppBuilder]` -- a mapping +rather than a list because two agents cannot share a name, and a mapping says so structurally +instead of needing a check. Each key is validated as a namespace and the root is refused. +`cache_names` is D3's casualty and is marked as such; it is what `GroupConfig` still carries. + +**Three things happen there and nowhere else:** + +- **`resolve(config, *, environ=None)`** -- the only I/O: `GroupConfig.resolve` reads the + environment and the group file. It is `AppBuilder.from_group` moved and renamed. +- **`from_config(group)`** -- imports each agent's module and reads the named attribute, which + must now be an **`AppBuilder`**, not an `AgentRegistration`. `_load_declaration` and + `_skip_or_raise` moved across with the critical/non-critical rule intact: a critical agent + that cannot be loaded raises, a non-critical one is skipped with an ERROR. Reads no + environment and no files, so a test states an exact composition literally. +- **`assemble(config)`** -- one root `AppBuilder`, one `build()`, one `FastAPI`: + + for namespace, builder in self._agents.items(): + root.host_agent(namespace) + with namespace_scope(namespace): + for declaration in builder.declarations: + declaration.replay(root) + + The namespace is never passed as an argument. The collector opens a `namespace_scope` and + `_record` reads it from there -- the same ambient mechanism a component uses, and the reason + step 4 can delete the `namespace=` keyword without the group losing anything. + +**`Declaration.replay(builder)`** is how a recorded call moves onto another builder: + + arguments = () if self.target is None else (self.target,) + getattr(builder, f"with_{self.kind}")(*arguments, name=self.name, **self.kwargs) + +Resolved by name with `getattr` rather than through a table, which is the fourth Builder +anti-pattern -- replay drift -- mitigated as the proposal specified: a table is a second place +to edit, and a missing method fails just as loudly as a `KeyError` while needing no maintenance. +One branch above it handles `with_health_checker(name, checker)`, whose name is positional where +every other `with_*` takes it as a keyword; the irregularity is cheaper in one commented branch +than as a breaking change to published API. + +**The refusals** (spec sec. 4.2), all in `_refuse_what_a_group_cannot_honour`, all run before +anything is replayed so a bad group leaves no half-populated registry: + +| Refused | Because | +|---|---| +| the builder has already been built | its components exist and belong to the root, and `build()` injects the configuration process-wide, which happens once | +| `AppBuilder(config)` | one process has one settings tree, one logging configuration and one port, and the group supplies all three | +| a declaration holding an instance | it was constructed at that line, before the group existed, so its namespace and registry key are already the root's | + +**Order matters and is documented in the code:** the already-built check runs *first*, because +`build()` adopts whatever configuration it resolved, so a built builder always reports one too -- +check the configuration first and its message is the only one anybody ever sees. Found by a test +that asserted the wrong message. + +**`app_builder.py`** + +- **`host_agent(namespace)`** -- extracted from `with_namespace`, which now calls it. Not a + `with_*`: it declares no component, it states a fact about the process. `build()` needs that + fact because two of the things it does are per agent rather than per component -- it wires one + transport per hosted agent, and asks each agent's configuration whether that agent publishes. + Neither can be derived from the declarations, because an agent may declare nothing and still + have opted into publishing. The builder is *told*; it never learns another builder exists. +- **`has_config` and `is_built`** -- two public booleans, which is what the collector reads. + Booleans rather than the objects: handing out the configuration would hand out the *unscoped* + loader, and config rework step 2b removed every path to that. +- **`with_health_checker` records** a `Declaration` with `kind="health_checker"` instead of + stashing into a lazily-created `_custom_health_checkers` attribute behind a `hasattr` check. + This is what stops a group silently dropping an agent's readiness checks, and it hands step 6 + the `(namespace, name)` pair it needs as data. The key is still the bare name, so a readiness + payload is unchanged and two agents declaring `"db"` still collide -- that is step 6's fix. + Calling it *after* `build()` still adds straight to the live `ActuatorApi`, because by then + the declarations have been replayed and recording would do nothing. +- `_UNCONSTRUCTED_KINDS` names the two kinds the replay pass does not construct: a cache is + created by `CacheBackendFactory`, and a health checker is not a `Component` at all. +- **Deleted:** `from_group`, `with_group`, `_load_registration`, `_skip_or_raise` -- 126 lines, + and with them the `importlib` and `group_config` imports. `AppBuilder` no longer references + `GroupConfig` in any form. + +**`entrypoint.py`** now reads: + + config = Config(settings_files=DEFAULT_SETTINGS_FILES) + app = AgentGroup.resolve(config, environ=environ).assemble(config) + +so the module holds the one thing neither `AppBuilder` nor `assemble` may do: exit the process. +Its header said it held "the three things `AppBuilder` must not: reading the environment, reading +files, and exiting the process"; two of those now belong to `AgentGroup.resolve`, and the +docstring says so. + +`AgentGroup` is exported from `blueprint.agents`. + +**Tests.** `test_with_group.py` becomes `tests/unit/agents/test_agent_group.py`, rewritten +against the new surface: one namespace per agent, a group of one, one declaration serving two +agents, a declaration not consumed by being assembled, an empty group, name validation, all +three refusals with the messages that name the agent and the fix, a factory accepted where an +instance is refused, nothing assembled when a refusal fires, the group's caches and an agent's +own cache, a health checker carried over, loading and the critical flag, no I/O in `from_config`, +`resolve`, and a case asserting `AppBuilder` has neither `with_group` nor `from_group`. +`test_entrypoint.py`'s declaration is now an unbuilt `AppBuilder`, and its standalone case builds +a separate one -- a builder builds once, and only that file runs both shapes in one process. +1994 unit tests pass, 15 more than before this step. + +--- + +### Phase 8b, step 4 -- four declaration surfaces become one + +**Deleted: `RegisteredComponent`, `AgentRegistration`, `NamespaceBuilder`, +`AppBuilder.with_registration`, `AppBuilder.with_namespace` and its two `@overload`s, and the +`namespace=` keyword on all five `with_*`.** `app_builder.py` goes from 1566 lines to 1236. +`AgentRegistration.apply` and its `appliers` dict go with the class. + +This is the payoff the phase was for. Adding one `with_*` method meant editing four places -- +`AppBuilder`, `AgentRegistration`, `NamespaceBuilder`, and `apply`'s `appliers` dict -- and +three of those failed *silently*, the capability simply absent from that surface. There is now +one place. The other three existed only to defer construction until a namespace was in force, +and step 1 removed that reason. + +**What replaced each of them** + +| Deleted | Now | +|---|---| +| `AgentRegistration` | an unbuilt `AppBuilder` -- used without `build()`, it *is* the declaration | +| `NamespaceBuilder` + `with_namespace` | `AgentGroup`, which takes named builders | +| `AgentRegistration.apply` + `appliers` | `Declaration.replay`, resolving the method with `getattr` | +| `namespace=` on the five `with_*` | the ambient scope the group opens | + +**`_record` lost its namespace parameter**, and that is the point rather than a tidy-up: + + namespace = current_namespace() + +A declaration takes the namespace in force *where it is written* -- the root for a standalone +application, the agent's own for a declaration a group is replaying inside `namespace_scope`. +So nothing a developer writes names a namespace, and the same file serves both deployment +shapes unchanged. + +**A removed keyword that would have kept working is refused.** `namespace` is not an error to +Python once the parameter is gone -- it falls into `**kwargs` and is forwarded to the +component's constructor, and `ServiceBase` accepts one. So `with_service(OrderService, +namespace="orders")` would have gone on placing the component in `orders`, by an entirely +different mechanism, until the first component with its own `__init__` failed at build time +instead. `_record` therefore refuses the keyword by name and says what it would otherwise do. +Found by writing the test that asserts the keyword is gone and watching it not raise. + +**Smaller changes:** + +- The five `with_*` type hints gained `| Callable[[], T]`. Factories were always accepted and + were only ever in `AgentRegistration`'s signatures; with that class gone, `AppBuilder`'s + signatures have to say what it takes. +- The instance-namespace refusal is still there and still reachable -- ``with_service(instance)`` + with a scope open -- but its message no longer suggests a `namespace=` argument as the fix. +- `blueprint.agents` no longer exports `AgentRegistration` or `NamespaceBuilder`. +- `AgentSpec.module`'s docstring says `AppBuilder` rather than `AgentRegistration`; it is what + step 3 made true and this is where it is written down. + +**Tests.** `test_agent_registration.py` deleted -- its subject no longer exists. +`test_namespace_builder.py` becomes `test_namespace_placement.py`, keeping every case whose +subject survives the API change: the ambient scope qualifies the registry name, reaches the +component, is never forwarded to its constructor, and is captured at the call rather than at +construction; explicit names are qualified; an already-built instance is refused for another +namespace; `host_agent` records the composition and refuses a duplicate, the root and an illegal +name; a scoped declaration is not a hosted agent. It gains `TestTheDeletedSurfaces`, four cases +pinning that the other three surfaces stay deleted and unexported. + +`test_build_namespaces.py` and `test_route_namespacing.py` were written against +`with_namespace(...)`. The route tests now use `AgentGroup(...).assemble(config)` directly, +because they assert on the application. The transport tests need the *root builder* -- the +endpoints they assert on register nowhere, and `assemble()` returns the application and keeps +its builder private -- so they use a local `hosting()` helper that runs `assemble`'s loop +through the same public `Declaration.replay`, with a docstring pointing at `test_agent_group.py` +for the group's own behaviour. + +`tests/unit/agents/app_builder/TESTS.md` updated: it documented two files that no longer exist +and a `with_health_checker` that no longer works that way. + +1963 unit tests pass, zero failures. The count is 31 *lower* than after step 3, and that is the +deletion showing up rather than coverage lost: the cases for two classes that no longer exist +went with them. + +--- + --- ## Compatibility @@ -4252,6 +4775,557 @@ stay keyword-only and last, or an existing `with_cache(False)` would silently be --- +### Phase 8b, step 5 -- a cache is private to the agent that declared it + +**D3, and the half of spec sec. 8 that was never built.** Sec. 8 requires that cache names be +namespace-scoped and that `get_cache(name)` resolve within the declaring agent and raise +otherwise. What existed was the *data-partition* half: `AgentScopedCache`, a lens that prefixed +each call's partition argument with the agent, over one shared backend. Two agents therefore +still shared a store, a `size_limit` and a Redis keyspace, and the isolation held only as long +as every call site went through the lens. + +The isolation is now **structural**: separate registry entries, separate directories, separate +key prefixes. There is nothing left for a prefixing lens to prevent, so it is deleted. + +**`Registry` -- the store is keyed on `(namespace, name)`** + + self._caches: dict[tuple[str, str], CacheService] = {} + +and every cache method takes the owning agent, defaulted from the object it is called on: + + def _cache_owner(self, namespace: str | None) -> str: + if namespace is not None: + return namespace + return self._default_namespace or ROOT_NAMESPACE + +That default is the whole developer-facing story: `Component.registry` hands a component its own +namespace's view, so `self.registry.get_cache("sessions")` reaches this agent's store with no +namespace at the call site -- and `add_cache`, `has_cache`, `get_all_caches` and the +`cache_service` alias resolve the same way. `add_cache(name, cache, namespace=...)` names one +explicitly, which is what `build()` uses. + +**`_cache_owner` deliberately differs from `_effective_namespace`.** For components an omitted +namespace on the application's registry means *every* namespace, which is what `build()` and the +lifespan need when they iterate. For caches it means *the root*, because every cache operation +names exactly one cache: there is no cache that belongs to all agents, and a lookup ranging over +the process would be the cross-agent sharing sec. 8 exists to prevent. + +- `get_cache` has **two fallbacks that do not exist** -- none from an unknown name to the + default, and none from an agent to the root or a neighbour. The message names the agent and + lists what *that* agent has: `No cache registered as 'sessions' for agent 'billing' + (registered: none)`. +- `get_all_caches(namespace=None)` is **one agent's**, keyed by bare name. +- **`cache_entries()` is new** and is the only cache view that crosses agents: + `list[tuple[str, str, CacheService]]`, `(namespace, name, cache)`. It **raises on a view** + (C6) -- a view is what agent code holds, and an agent that can enumerate its neighbours' caches + can be written to depend on them. The agent is returned **as data**, not folded into the name, + because a cache name may legally contain the separator (`v2.sessions`), so a caller that has to + attribute a cache to an agent must not be splitting a string. `clear()` iterates the tuple keys + and names the agent in its log line. + +**`CacheBackendFactory` -- one argument carries every consequence of ownership** + +`create(config, enable_locking, name, *, namespace="")`. The bare name stays what is validated +and what appears in the registry; the *storage* name is composed here, in the same class that +already owned "how a name becomes a separate store": + + @staticmethod + def storage_name(namespace: str, name: str) -> str: + return name if not namespace else f"{namespace}.{name}" + +`_scoped_cache_dir` and `_scoped_key_prefix` now take that storage name, so agent `orders` +declaring `sessions` gets `/orders.sessions` on disk and `:orders.sessions` on +Redis, and its *default* cache gets `/orders.default` -- only the root keeps the +configured directory itself, which is what leaves a single-agent application reading exactly the +store it always did. The directory stays a **subdirectory** of `cache.cache_dir` for the reason +named caches already did: under `readOnlyRootFilesystem` only the mount is writable, so one +volume per group still works and a group does not multiply the writable paths a pod needs. + +`.` is the separator because it is in the cache-name alphabet and not in the namespace alphabet: +an agent's storage name is still a legal cache name, and no cache name can forge one. `_` is in +both, which would make `orders_sessions` ambiguous between agent `orders` and a root cache of +that name. + +**`create` also enters the namespace scope itself**: + + storage = CacheBackendFactory.storage_name(namespace, name) + with construction_scope(namespace): + if config.backend == "redis": + return CacheBackendFactory._create_redis(config, enable_locking, name, storage) + return CacheBackendFactory._create_disk(config, enable_locking, name, storage) + +A cache backend is itself a `Component`, so two agents' caches both derive +`disk_cache_service` and collide on that one registry name unless each is constructed inside its +agent's scope. Doing it in the factory rather than at the call site means the `namespace` +argument alone decides *both* where the cache stores and what it registers as, whatever scope +the caller happens to be in -- **found by a test**: the first version scoped only in `build()`, +and a direct `create(..., namespace="orders")` produced an agent-scoped store with a root +registry name, which failed the moment a second agent did the same. + +**`construction_scope` moved to `component/namespace.py`** and is now public. It was +`app_builder._construction_scope`: the guarded form of `namespace_scope` that leaves the ambient +namespace alone for the root, because `namespace_scope("")` is not a no-op -- it *sets* the root. +The factory needs exactly that guard, and the trap is one that gets re-derived wrongly, so the +one implementation lives beside the thing it guards. + +**`AppBuilder` -- three things are per agent at build time** + +`_create_cache(declaration, config)` now takes the configuration and reads the agent's own view: + + cache_service = CacheBackendFactory.create( + config.for_namespace(namespace).get_cache_config(), + enable_locking=enable_locking, + name=name, + namespace=namespace, + ) + registry.add_cache(name, cache_service, namespace=namespace) + +So the *backend* is chosen per agent too (C5): one agent in a group can run on redis while its +neighbour uses the disk, which a process-wide read of `cache.backend` could not express. + +**The readiness probe attributes each cache to its agent:** + + for namespace, cache_name, cache in registry.cache_entries(): + entry = "cache" if cache_name == DEFAULT_CACHE_NAME else f"cache:{cache_name}" + health_providers[f"{namespace}.{entry}" if namespace else entry] = CacheHealthChecker(cache) + +Two agents' default caches were previously one entry keyed `cache`, so the payload reported +whichever registered last and one agent's Redis outage was invisible. The root keeps the bare +`cache` / `cache:sessions` entries, so an existing readiness payload does not change. (Step 6 +generalises this to every health checker and stores the attribution as data; this is the cache +half, which step 5 cannot leave broken.) + +**`/cache/*` became per agent:** + + for namespace in self._cache_owners(registry): + with construction_scope(namespace): + cache_api = CacheManagementApi() + self._mount(app, cache_api, root_prefix="/api") + +One router per agent that declared a cache, mounted under that agent's `/api/` prefix by +the `route_prefix` mechanism phase 6 built, each resolving names through its own registry view. +So `/api/orders/cache/stats` reports the orders agent's caches and cannot reach billing's -- +where one process-wide endpoint would have reported one agent's keys to another. `_cache_owners` +derives the list from `cache_entries()` rather than from `hosted_namespaces`, because a cache is +declared and not implied: an agent that declared none gets no endpoint, exactly as an application +built without `with_cache()` has never served `/cache/*`. A standalone application keeps +`/api/cache/*` unchanged, and its 503/404 branches now speak about that agent's caches. + +**Deleted** + +- **`AgentScopedCache`** (`services/infrastructure/agent_scoped_cache.py`) and `Registry`'s + `_scoped_cache` / `_scoped_caches` machinery, including the reset of `_scoped_caches` in + `for_namespace`. Separate stores make the isolation structural, so the lens has nothing left to + prevent -- and it had a real weakness: it was per registry *view*, so framework code holding + `Component.shared_registry` directly still reached the shared store. +- **`GroupConfig.cache_names`**, its env-override slot and its line in the resolution log; the + `cache_names` argument to `AgentGroup` and the `with_cache` replay loop in `assemble`. A group + declares no caches because there is no process-wide cache to declare. `cache_names` in a + mounted group file is now **read by nothing** -- ignored rather than refused, because a + rollout must not fail over a key that has become inert, and `GroupConfig` reports only what it + understands. + +**Knock-on, as D3 predicted:** `has_cache()` and `cache_service` answer per agent, so an agent +with `idempotency_enabled = true` must itself declare `with_cache()`; a neighbour's cache no +longer satisfies it. The existing error message already says exactly what to add. This is what +changed `test_event_processing_namespaces.py`'s fixture, whose `orders` agent enables dedup: its +cache is now registered *for* `orders` instead of at the root. + +**Tests.** `test_agent_scoped_cache.py` deleted with its subject. New: `TestCachesPerAgent` in +`test_registry.py` (13 cases -- two agents holding one name, no fallback by name, through the +root or by enumeration, the per-agent alias and `has_cache`, `cache_entries` carrying the agent +as data and refused on a view, `clear` reaching every agent); +`TestACacheBelongsToTheAgentThatDeclaredIt` in `test_named_caches.py` (registration, directory, +two agents' separate stores, both backends registering as components, the agent's own config view, +and the readiness entry); `TestAgentIsolation` in `test_cache_backend_factory.py` (the storage +name at the root and for an agent, the separator staying a legal cache name, separate directories +and Redis prefixes, the directory staying inside the mount); `TestCacheEndpointsPerAgent` in +`test_route_namespacing.py` (per-agent paths through `app.openapi()`, no endpoint for an agent +that declared none, and the standalone paths unchanged). `test_agent_group.py`'s +`TestTheGroupsCaches` is rewritten around agents owning caches, including the D3 case -- two +agents declaring `sessions` get separate stores and neither can read the other's. + +1975 unit tests pass, zero failures. + +--- + +### Phase 8b, step 6 -- a health check carries the agent it belongs to + +**D4.** A readiness check was a dict entry, `name -> checker`, and that lost the attribution +twice over. Two agents calling `with_health_checker("db", ...)` collided on one key and one +disappeared with nothing logged; and even where the keys differed -- a client's registry name is +already unique -- nothing recorded *whose* check a failing entry was, which is exactly what +`readiness_policy = "critical"` (phase 9) has to answer. + +**`HealthCheckEntry`, in `health/health_base.py`** -- the value object the dict becomes: + + @dataclass(frozen=True) + class HealthCheckEntry: + name: str + namespace: str + checker: HealthCheckerBase + + @property + def key(self) -> str: + return qualified_entry_name(self.namespace, self.name) + + @property + def agent(self) -> str: + return self.namespace or ROOT_LABEL + +The agent is **data**; `key` is only its rendering. Recovering the namespace by splitting the key +would break on the first name containing the separator, and `cache:v2.sessions` is one. `agent` +exists so a log line can name the root without every caller writing the `or ROOT_LABEL`. + +**`qualified_entry_name` in `component/namespace.py`** is the rendering, and it is a *second* +naming rule rather than a reuse of `qualified_component_name`: + + def qualified_entry_name(namespace: str, name: str) -> str: + return name if not namespace else f"{namespace}.{name}" + +`.` rather than `_`, deliberately. A registry name is an identifier other code looks up, and `_` +is what every lookup qualifies with; an entry name is a label nothing resolves, and it may +contain characters a registry name never does -- `cache:sessions` already does. Rendering both +the same way would suggest a readiness key can be passed to `get_component`, and it cannot. The +route-tag prefixing in `_mount` now calls it too, so the dotted form has one definition instead +of two spellings. + +**`HealthCheckCache` polls entries, not a mapping.** `set_health_check_provider(dict)` becomes +`set_health_entries(Sequence[HealthCheckEntry])`, and the poll loop lost its intermediate dict: + + results = await asyncio.gather(*(entry.checker.health_check() for entry in self._entries), return_exceptions=True) + + for entry, result in zip(self._entries, results, strict=True): + if isinstance(result, BaseException): + logger.warning("Health check '%s' of agent '%s' failed: %s", entry.name, entry.agent, result) + components[entry.key] = ComponentHealth(status="unhealthy", message=f"Check failed: {result}") + else: + components[entry.key] = result + +The payload is still `dict[str, ComponentHealth]` keyed by `entry.key`, so the response *shape* +is unchanged and the root's keys do not move. What is new is that the object doing the ANDing +knows whose each result is -- phase 9 groups these by `entry.namespace` and needs no string +surgery to do it. The failure log names the agent separately from the entry, because "whose +check is failing" is the question asked of a group. + +**`ActuatorApi.add_health_providers` accumulates, and refuses a duplicate key.** It took a +mapping and **assigned** it: + + self._pending_providers = providers # before + self._health_cache.set_health_check_provider(providers) + +That is a live defect, not just a shape: the method's own docstring documents calling +`with_health_checker` *after* `build()`, and doing so replaced every client and cache check the +build had wired -- before startup by overwriting `_pending_providers`, after startup by +overwriting the cache's mapping. The readiness probe then reported one component and nothing +else. It now appends to `self._health_entries`, re-pushes the whole list to a live cache, and +raises on a key that is already taken: + + raise ValueError( + f"Health check '{entry.name}' of agent '{entry.agent}' would appear in the readiness payload as " + f"'{entry.key}', which is already taken by a {type(existing.checker).__name__} of agent " + f"'{existing.agent}'. Two checks under one entry cannot be told apart in the payload, so one of " + "them has to be renamed." + ) + +Refused rather than kept-last, because silent loss is the whole of what D4 is about. It is +checked here rather than at `with_health_checker` because this is the single funnel every source +passes through -- clients, caches, declared checkers, and post-build additions -- and a collision +between two *different* sources is only visible at this point. `health_entries` is a public +read-only property; `_pending_providers` is gone. + +**`AppBuilder` attributes every source.** `_health_checkers` is a `list[HealthCheckEntry]`, and +the three sources compose their entries: + + health_providers: list[HealthCheckEntry] = [ + HealthCheckEntry(name=client.base_name, namespace=client.namespace, checker=ClientHealthChecker([client])) + for client in registry.get_clients() + ] + for namespace, cache_name, cache in registry.cache_entries(): + name = "cache" if cache_name == DEFAULT_CACHE_NAME else f"cache:{cache_name}" + health_providers.append(HealthCheckEntry(name=name, namespace=namespace, checker=CacheHealthChecker(cache))) + health_providers.extend(self._health_checkers) + +and `with_health_checker` records `current_namespace()` on the entry for the post-build path as +well, so a checker declared inside an agent's scope belongs to that agent wherever it is flushed. + +**`Component.base_name` is new, and the client entry is why.** A client's registry name is +already qualified -- `orders_nats_client` -- so passing it as the entry name rendered +`orders.orders_nats_client`. Stripping the prefix back off is not available: +`qualified_component_name` is deliberately not idempotent, precisely because "does +`billing_handler` in agent `billing` carry a prefix?" is not decidable from the string. So the +unqualified half is kept at construction instead of being recovered later: + + self._base_name = name or camel_to_snake(self.__class__.__name__) + self._name = qualified_component_name(self._namespace, self._base_name) + +The setter updates both. A grouped client's readiness key is therefore `orders.nats_client`, and +a root client's is `nats_client` -- the key it has always had. + +**What a payload looks like now**, from a probe against real objects (two agents, each with a +handler, a cache and a `db` checker): + + orders.nats_client | orders | ClientHealthChecker + billing.nats_client | billing | ClientHealthChecker + orders.cache | orders | CacheHealthChecker + billing.cache:sessions | billing | CacheHealthChecker + orders.db | orders | DbChecker + billing.db | billing | DbChecker + +Every entry reads `.`, and the same probe confirmed the duplicate refusal fires and +that a post-build checker now adds a seventh entry instead of replacing the six. + +**Unchanged on purpose:** the policy. Every checker is still polled on a timer and ANDed, so one +unhealthy check still returns 503 for the whole pod -- in a group, one agent's outage still +removes every agent from rotation. That is `readiness_policy = "all"`, which phase 9 makes +selectable; this step only makes the attribution available to it. `ComponentHealth` and +`ReadinessResponse` are untouched, so nothing about the response schema changes. + +**Tests.** `test_health_cache.py` moved onto entries and gained `TestAnEntryIsAttributedToItsAgent` +(root keeps the bare name, an agent's is prefixed, two agents declaring one name are two +components, the failure log names the agent). `test_actuator_api.py` gained +`TestRegisteringChecks` (accumulation across calls, two agents sharing a name, a duplicate +refused across calls and within one call, a post-startup addition reaching the live cache). +`test_build_namespaces.py` gained `TestEveryReadinessEntryNamesItsAgent` against real components +-- including that the key does not carry the agent twice, and that `namespace` is readable +without splitting the key. `test_name_uniqueness.py` gained `TestBaseName`, whose last case pins +the non-idempotence that `base_name` exists to work around. The app_builder, named-cache and +agent-group tests that asserted on the old dict now read `health_entries`. + +1996 unit tests pass, zero failures. + +--- + +### Phase 8b, step 7 -- an agent's own settings file becomes that agent's scope + +**D5, spec sec. 5.3.** An agent author writes plain keys in their own directory's +`settings.toml` -- `model_name = "..."`, or a `[default]` section, which is what every scaffolded +project has -- and the build merges that file **under that agent's scope**. The author never +learns that a scope exists, and the same file serves the project standalone and as one agent of a +group. That is the requirement the whole feature rests on: only `main.py` may differ between the +two. + +**`Config.merge_agent_settings(namespace, path)`** is the whole of it, and it is on the loader +only -- calling it on a view raises, because authoring another agent's configuration through a +view is the breach that reading one is (C6). + + fragment = self._layer_fragment(document) + fragment = self._drop_process_scope_keys(namespace, resolved, fragment) + ... + existing = self._settings.get(namespace) + merged = dict(existing.items()) if hasattr(existing, "items") else {} + added = self._fill_missing(merged, fragment) + self._settings[namespace] = merged + +Writing a subsection into the loaded tree is all the "merge" a scope needs: probed first, and +`for_namespace("orders").get("model_name")`, `_scoped_get("cache.cache_dir")` and +`resolved_settings("orders")` all pick it up, because the tree is what they read and a view +shares it by reference. + +**Precedence: what is already in the tree wins, and the fragment fills the gaps.** +`_fill_missing` recurses so a fragment's `[cache] cache_dir` joins a group's +`[default..cache] size_limit` instead of replacing the table or being dropped by it. Two +things this protects at once: a value the group's own settings state under `[]` -- the +deployment named the agent, so it meant it, and a file baked into the image does not overrule it +-- and an environment override (`DYNACONF___KEY`), which Dynaconf has already put in the +tree by the time this runs and which a file read afterwards must not clobber. + +**`_layer_fragment` resolves the file itself rather than handing it to Dynaconf**, and that is +forced rather than chosen. Dynaconf always reads `DYNACONF_*` from the environment and cannot be +told not to (`loaders/env_loader.py`, established in config rework step 3a), so a Dynaconf-loaded +fragment would pull *process-wide* environment overrides into one agent's scope -- including the +very keys the next paragraph refuses, which would then be reported against a file that does not +contain them. So the file is read with `tomllib` and layered explicitly, lowest first: keys +written at the top level, `[default]`, the section for the environment in force, then `[global]`, +matching what Dynaconf does with the process's own file. A top-level table that is *not* one of +those three names is a value, not an environment: `[cache]` beside `[default]` is this agent's +cache configuration. + +**Process-scope keys are dropped, loudly** -- `PROCESS_SCOPE_KEYS` in `config.py`: + + {"app_port", "app_host", "app_workers", "app_environment", "envvar_prefix", "event_bus", + "log_level", "log_format", "suppress_noisy_loggers", "health_check_interval_seconds", + "dot_placeholder", "nats_stream_name"} + +plus `DEPLOYMENT_IDENTITY_KEYS`, which `get()` refuses to answer at all. One process binds one +port, loads one environment section, reads its environment through one prefix, speaks one event +bus and configures logging once, so every one of those is read from the group's configuration and +never from an agent's scope: a copy under `[]` would be read by nothing. +`nats_stream_name` is the one entry whose reason differs -- it *is* read through an agent's own +view, so a scoped value would take effect, and it is dropped because the stream is a server-side +object shared with every other deployment on that broker. + +**Departure from the spec, argued: sec. 5.3 says such a key MUST raise; it warns instead.** The +evidence is in this repository. Every one of the seven example projects declares `app_port` and +`app_environment` in its `settings.toml`, and several declare `log_level` and `event_bus`: + + [default] + app_name = "Order Event Pipeline" + app_port = 8000 + app_environment = "development" + log_level = "INFO" + event_bus = "dapr" + +Raising would mean **no existing project could be hosted as an agent without first editing a file +that is correct for its own standalone deployment** -- which contradicts the constraint the spec +itself serves, and would fail a rollout over a key the file has every right to contain. The +purpose of the MUST is that the author can discover the value is inert, and that is what the +warning does, naming the agent, the key, the file and the value in force: + + Agent 'orders' sets 'app_port' in /app/pkg/orders/settings.toml, and that is a process-wide + setting: one process has one of it, so this value (8000) is ignored and the group's own value + (8080) is used. Remove it from the agent's settings file, or set it in the group's. + +**Display metadata is deliberately not in the list.** `app_name`, `app_version` and +`app_description` are in every scaffolded file, and a scoped `app_name` is genuinely read -- the +NATS queue group falls back to it, and so does the telemetry service name -- so an agent naming +itself is its own business. + +**Where the file is looked for: beside the module that declares the agent.** + + module_path = module_spec.partition(":")[0] + module = sys.modules.get(module_path) + file = getattr(module, "__file__", None) + ... + return Path(file).parent / "settings.toml" + +One rule, and one an author can see without reading the framework: an agent is a directory of +handlers, services and a declaration, and its settings belong to that directory the same way. +Read from `sys.modules` rather than by importing again, so the answer is the file Python actually +loaded rather than one guessed from a dotted path. `AgentGroup.from_config` records it per agent +that loaded -- a skipped non-critical agent has no scope to merge into -- and +`AgentGroup(name, agents, settings={...})` takes them directly, which is what the tests use. + +**`assemble` merges before the root builder exists:** + + for namespace in self._agents: + path = self._settings.get(namespace) + if path is not None: + config.merge_agent_settings(namespace, path) + + root = AppBuilder(config) + +Ordering is the load-bearing part: `build()` is where components are constructed and where each +one reads its keys through its agent's view, so a fragment merged afterwards would be a file read +too late to matter. A test pins it by having a service read `model_name` in its constructor. + +**One guard found by its own test.** A fragment path that resolves to one of the process's own +settings files is skipped, with DEBUG naming it. Without it, an agent whose declaration module +sits beside the group's `settings.toml` would have every root key merged under its scope a second +time -- and every process-scope key reported against the group's own file. It fired immediately: +the first version of the group tests wrote the fragment into `tmp_path`, which is where the +fixture's own settings file lives, and the merge correctly did nothing. + +**Not done, deliberately:** `.secrets.toml` per agent. The spec names `settings.toml`, and an +agent's secret belongs in the environment, where `DYNACONF___KEY` already resolves per +agent (verified during the config rework). One file, one rule. + +**Tests.** New `tests/unit/agents/config/test_agent_settings_fragments.py`, 38 cases in five +classes: what an agent reads (a plain key, a `[default]` section, the environment section winning +over it, another environment's section ignored, nested tables, a top-level table as a value, the +root default still the fallback); isolation (the root and a neighbour unchanged, two agents +declaring one key, a view refused, the root refused); precedence (the group's own value for the +agent wins, the fragment fills the rest, a nested table merged key by key); process-scope keys +(dropped, reported with the file and the value in force, an existing project's file hosted +unchanged, every listed key parameterised, deployment identity dropped too); and files that are +not there (absent, the process's own, empty, unparseable -> `ConfigError`). +`test_agent_group.py` gained `TestEachAgentsOwnSettings`: where the file is looked for, an agent +that ships none, a fragment merged under its scope, merged *before* the components are built, one +agent's file not reaching another, and a group given none. + +2040 unit tests pass, zero failures. + +--- + +### Phase 8b, step 8 -- what a group does to each declaration, said where it is read, and gated + +Three parts, and the first one is documentation on purpose. The decision taken when `AgentGroup` +was designed was **RTFM, not authoring-time validation**: a group refuses what it cannot honour +at assembly, and everything else it does to a declaration -- moving routes, scoping a cache, +resolving a scheduler's mode per agent -- is *behaviour*, not an error, so the place it has to be +written is the method a developer is already reading. + +**Part 1: group behaviour on each `with_*`.** Every declaration method now carries an **In a +group:** paragraph, and each says something that method does not share with the others: + +- `with_handler` -- its own `HandlerChain` and its own subscription, so it is never offered a + neighbour's events, and `idempotency_enabled` needs a cache *this* agent declared. +- `with_service` -- only the registry name changes (`orders_order_service`), plus what + `self.registry` and `self.config` answer for. +- `with_agent` -- the class and factory forms work, but only the `AgentBuilder` form is handed + the scoped configuration view, so a runtime reading its own model wants that one. +- `with_scheduler` -- `scheduler_mode` resolves per agent, so an in-process timer can sit beside + an event-driven neighbour; `"in_process"` claims each tick in *this* agent's cache and + `"event"` needs the group's `event_bus`; its routes move with the agent's. +- `with_rest_api` -- **the routes move**: `/api/`, tags prefixed, nothing in the component + changed, but a client of a grouped agent addresses the prefixed path. +- `with_cache` -- private to the declaring agent, separate stores for the same name, backend from + this agent's configuration, `/cache/*` per agent. +- `with_health_checker` -- the entry becomes `.`, a collision is refused rather than + silently reduced, and the readiness *policy* is unchanged (still ANDed, still 503 for the pod). + +**Part 2: the surfaces-agree gate**, `tests/unit/agents/app_builder/test_declaration_surface.py`. +Adding a capability is now one edit, but the group still has to move a recorded call from one +builder to another, and `Declaration.replay` does that with +`getattr(builder, f"with_{self.kind}")`. So there are exactly two ways for the halves to part +company, and **neither is visible in a single-agent application**: a method that records a `kind` +no method answers to, and a replay that does not reproduce the call. Both would be found in +production by whoever first grouped two agents. + +The gate discovers the methods rather than listing them -- + + return sorted(name for name in dir(AppBuilder) if name.startswith("with_")) + +-- and pairs each with a sample call, so **a new `with_*` fails this file until it is listed**. +Per method it asserts: exactly one declaration recorded; the registry untouched (collect, then +wire); `replay` onto a fresh builder reproduces the declaration exactly; a replay inside +`namespace_scope("orders")` takes the namespace from the scope and not from the source; and the +recorded `kind` has a `with_` to go back to. + +**Probed, because a gate that cannot fail is decoration.** Three drift modes injected against +the real classes: + + 1. uncovered methods the gate would report: ['with_widget'] + 2. recorded kind 'gadget'; AppBuilder has with_gadget(): False + replay of that kind fails, as the gate predicts: 'AppBuilder' object has no attribute 'with_gadget' + 3. declarations equal after a lossy replay: False + recorded name: planner | replayed name: None + +A `with_widget` added to `AppBuilder` is reported as uncovered; one recording `kind="gadget"` is +caught by the kind assertion *and* fails replay with the `AttributeError` the docstring predicts; +and a `replay` that drops `name` breaks the equality. + +**Part 3: the frozen compatibility suite**, `tests/unit/agents/test_frozen_compatibility.py` -- +spec sec. 10.2, which asks for a suite "never updated to the new API; if it needs editing, a +break shipped". It did not exist; it does now, and its module docstring says exactly that. Twenty +cases, every one written the way a project in `examples/` writes it today, instance forms +included, because four of the seven examples pass constructed objects: + + app = AppBuilder(config).with_service(InventoryService).with_rest_api(InventoryApi()).with_cache().build() + +and asserting the observable things such a project depends on: `with_cache(False)` and +`with_cache(True, False)` positionally (sec. 10.1 names both); `get_component("inventory_service")` +and `get_component("disk_cache_service")` resolving unprefixed; `registry.cache_service` as the +alias; two services resolving *one* cache object; `/api/inventory` with its own tag unrewritten; +`/api/cache/stats` unprefixed; `/health/ready`, `/health/live` and `/info` where they were; the +readiness entries `cache` and a bare `database`; and a component constructed with +`super().__init__()` getting `("inventory_service", "")`. + +The fixture is an example's `settings.toml` key for key -- `app_name`, `app_port`, +`app_environment`, `log_level`, `[default.cache]` -- which is the same file step 7 refuses to +raise over. The one fixture that is *not* frozen usage is the autouse +`Component.reset_shared_state()`, and it says so: a test file is many processes in one, which a +deployment never is. + +**Not done, and belongs in this open point rather than this step:** sec. 10.2's second half, the +generated-project smoke test (`asbs setup`, then build and start the result unchanged). It needs +Docker, which this machine does not have, and it is the only part of the compatibility guarantee +that covers the Dockerfile and `main.py` paths a unit test cannot reach. + +2100 unit tests pass, zero failures. The 60 added are the two new files. + +--- + ## Open points - **Phase 7's ambiguity error needs a spec amendment.** The plan asks `process_event` to raise @@ -4302,7 +5376,21 @@ stay keyword-only and last, or an existing `with_cache(False)` would silently be generated `CronJob` is the remaining silent-failure case -- the missing `event_bus` and the missing mode both fail at startup now, but a mode and a transport with nothing publishing does not. Validate is where it should be caught. -- **The settings-fragment merge has two unanswered questions, both raised by step 3a.** Spec +- ~~**The settings-fragment merge has two unanswered questions, both raised by step 3a.**~~ + **Answered 2026-09-10 (D5), and by dissolving the questions rather than deciding them.** A + group's settings supply *defaults only*, and each agent's own `settings.toml` merges under that + agent's scope -- so a fragment and a root key never occupy the same slot and there is no + collision to report or refuse. The second sub-question therefore has no subject, and the first is + generalised: process-scope keys in a fragment (`app_port`, `event_bus`, `envvar_prefix`, + `nats_stream_name`) **raise**, from an explicit list, because scoped they are read by nothing and + reported by nothing. **Implemented in phase 8b step 7** (`Config.merge_agent_settings`), with one departure: a + process-scope key in a fragment is **reported and ignored**, not raised, because every example + project declares `app_port` and `app_environment` in its settings file and raising would mean no + existing project could be hosted as an agent without editing it. Spec sec. 5.3's MUST should + become a MUST-report. The original text follows, because the probe in it is the evidence for + what the merge had to be built around. + + Spec sec. 5.3 requires each agent to keep writing plain top-level keys in its own `settings.toml` and the build to merge each fragment under that agent's scope, reporting collisions with a root key. Confirmed by probe that nothing does this yet: handing two fragments to @@ -4382,16 +5470,26 @@ stay keyword-only and last, or an existing `with_cache(False)` would silently be - **Nothing observes dead-lettering.** It is logged, but there is no counter, so "how many messages did we give up on today" cannot be answered from metrics. It belongs with the telemetry work in phase 9, next to `blueprint.events.unhandled`. -- ~~**Cache names are not namespace-scoped**~~ -- **done**, by prefixing the partition - (`AgentScopedCache`). The deployment constraint decided it: a backend per agent per name would - multiply the writable paths a group needs and split one `emptyDir`'s budget N ways. Two things - it leaves open. The lens is per *registry view*, so framework code that reaches - `Component.shared_registry` directly still gets the shared store -- correct today, and worth - re-checking whenever a framework component starts caching on an agent's behalf. And nothing - migrates keys written before the prefix existed: an application upgrading with a persistent - redis cache sees its old entries as absent, which is a cold cache rather than an error, but - should be said in the migration guide (phase 10). -- **The examples are not migrated to `AgentRegistration`, by decision (2026-09-08).** Asked +- ~~**Cache names are not namespace-scoped**~~ -- **done twice.** First by prefixing the + partition (`AgentScopedCache`), then properly in phase 8b step 5, which keys the registry on + `(namespace, name)` and gives each agent its own directory and Redis prefix; the lens is + deleted, and with it the hole that framework code reaching `Component.shared_registry` + directly still got the shared store. The deployment constraint that argued for one shared + backend still holds and is still honoured: an agent's store is a *subdirectory* of + `cache.cache_dir`, so a group still needs exactly one writable mount. What remains open is + migration -- **the key layout changed twice**, so an application upgrading with a persistent + redis cache or a mounted disk cache sees its old entries as absent. A cold cache rather than + an error, and it must be said in the migration guide (phase 10), for both hops. +- **The cache documentation is wrong about the endpoints, and now about their paths too.** + `docs/concepts/caching.md` documents `GET`/`PUT /api/cache/{namespace}/{key}`, which have never + existed (the API is `stats`, `namespaces`, `evict`), and step 5 moved a grouped agent's routes + to `/api//cache/*`. Left for step 9 part 3, which owns the four overlapping cache + documents; fixing one of them here would have been the fifth version of the same content. +- **The examples are not migrated, by decision (2026-09-08).** Note that phase 8b changes what + blocks them: `AgentRegistration` is deleted, and passing instances (`with_rest_api(MonitorApi())`) + stays legal standalone -- it is refused only when a builder is collected into a group. So the + examples keep working untouched, and converting them is only needed if they are to be *grouped*. + Asked whether to convert one project's `main.py` as proof, the user chose not to touch the examples part-way through the changes, and to revisit them when the integration tests are written -- where two real example projects grouped into one process would be a better test of C1 and C5 diff --git a/docs/plans/2026-08-28-multi-agent-grouping.md b/docs/plans/2026-08-28-multi-agent-grouping.md index d8b12f23..0e7a3dda 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping.md +++ b/docs/plans/2026-08-28-multi-agent-grouping.md @@ -2,7 +2,9 @@ | | | |---|---| -| **Status** | P0-P6 landed on `feature/multi-agent-namespaces`; the prerequisites are done. No phase (0-10) started. | +| **Status** | P0-P6, phases 0-8 and **phase 8b step 1** landed on `feature/multi-agent-namespaces`. Next: 8b steps 2-9, then phase 9, then 10. | +| **Amendment** | `docs/plans/2026-09-10-builder-unification.md` -- decided 2026-09-10. Phase 8b below is its work breakdown; phases 0 and 3 are superseded by it. Step 9 was added on 2026-09-10 and is not in that proposal's original breakdown. | +| **Deferred out** | `docs/plans/2026-09-10-config-validation-unification.md` -- configuration validation is not part of this feature and **must not** be touched during 8b. | | **Spec (normative)** | `docs/specs/2026-08-28-multi-agent-grouping.md` | | **What landed, and why** | `docs/plans/2026-08-28-multi-agent-grouping-changelog.md` -- read before resuming | @@ -272,7 +274,8 @@ Root Registry (namespace="") **No change (stays standalone):** developer does nothing — existing `main.py` and Dockerfile work as-is forever. -**Opt in to multi-agent:** two file changes only. +**Opt in to multi-agent:** three file changes. Earlier drafts of this plan said two and +forgot `agents.toml`, which is required even for a group of one. `main.py` before: ```python @@ -288,48 +291,74 @@ app = ( ``` Dockerfile before: `CMD uvicorn src.main:app --host 0.0.0.0 --port 8000` -`main.py` after — **one declaration, no branches**: +`main.py` after — **the same builder**, minus its `config` argument and minus the `.build()`: ```python -from blueprint.agents import AgentRegistration - -registration = ( - AgentRegistration() +agent = ( + AppBuilder() .with_service(OrderService) .with_handler(OrderValidationHandler) .with_handler(OrderEnrichmentHandler) .with_rest_api(OrderApi) + .with_cache() ) + +def create_app(): # only if this agent is still to be served on its own + return agent.build() ``` Dockerfile after: `CMD python -m blueprint.agents.entrypoint` +`agents.toml` (third change): `[agents.order]` / `module = "agents.order.main:agent"`. + +Note what did *not* change: `with_cache()` stays exactly where it was, and so does every other +`with_*` call. That is the point of the single builder surface — migration removes two things and +adds nothing, because the declaration and the application builder are the same class (spec +sec. 4.2). + +One declaration, three deployment shapes: + +| Shape | Command | +|---|---| +| Standalone, unmigrated | `uvicorn src.main:app` | +| Standalone, migrated | `uvicorn src.main:create_app --factory --reload` | +| Grouped (including a group of one) | `python -m blueprint.agents.entrypoint` | + An earlier draft of this plan used a dual-branch `main.py` — `if __name__ == "__main__": AppBuilder(...)...run_app()` / `else: registration = ...`. That is **rejected**: it makes the developer write the component list twice and keep both copies in sync, -and it exposes the existence of two worlds. Running a single agent is `asbs dev agents/order`, -which wraps the registration as a group of one. No `AppBuilder`, no `Config`, no `run_app`, no -`if __name__` in agent code (C6). +and it exposes the existence of two worlds. `create_app` above is not that: it repeats no +component, and it is optional. + +**The consequence to state plainly.** A migrated agent run in a group uses its group name, so its +queue group and its JetStream durable change — standalone runs at the root and takes its identity +from `app_name`. Moving from standalone into a group is therefore a consumer migration on the +first grouped deploy, not a rename (C1, phase 5's migration note). Regrouping *afterwards* changes +nothing, which is the property the whole feature is built for. -Because the module is imported into a shared runtime, it **must** contain only the registration — +Because the module is imported into a shared runtime, it **must** contain only the declaration — no client construction at import time, no module-level mutable state, no `logging.basicConfig()`. CI check: import each agent module, assert the registry is still empty and the root logger has no handlers. -The global orchestrating `main.py` (no uvicorn, just a FastAPI app): +A hand-written group `main.py`, for a project that wants one rather than the module entry +point (no uvicorn, just a FastAPI app): ```python -from blueprint.agents import AppBuilder, Config -from order_agent.src.main import registration as order_reg -from invoice_agent.src.main import registration as invoice_reg +from blueprint.agents import AgentGroup, Config +from order_agent.src.main import agent as order_agent +from invoice_agent.src.main import agent as invoice_agent config = Config(settings_files=["settings.toml"]) app = ( - AppBuilder(config) - .with_cache("orders") - .with_namespace("order", registration=order_reg) - .with_namespace("invoice", registration=invoice_reg) + AgentGroup(config) + .add("order", order_agent) + .add("invoice", invoice_agent) .build() ) ``` +`AgentGroup` is a different class from `AppBuilder` on purpose: an `AppBuilder` never absorbs +another builder and never learns it can be collected, so the group's refusals live in the class +that imposes them (spec sec. 4.1). No cache is declared here — each agent declares its own, and +gets only what it declared (spec sec. 8). --- @@ -353,9 +382,9 @@ app = ( | `EventPublishingService` | **Per-namespace** | Must publish on its own namespace's client, or outbound traffic is unattributable | | `EventProcessingService` | Shared (root) | Namespace passed per-call | | `ActuatorApi` | Shared (root) | One health endpoint | -| `CacheService` | **Namespace-scoped by default** | Explicit opt-in for genuinely shared caches. A flat store lets two independently developed agents both call `get_cache("sessions")` and silently share it once grouped. Sync ops via `run_in_executor` + namespace executor | +| `CacheService` | **Per-namespace, declared only** | An agent gets exactly the caches it passed to `with_cache`, and no others: names qualified per namespace, no root fallback, no shared-cache opt-in. A flat store lets two independently developed agents both call `get_cache("sessions")` and silently share it once grouped. Sync ops via `run_in_executor` + namespace executor | | `AIClientBase` | Per-namespace strongly recommended | Shared async HTTP pool causes one agent's LLM calls to starve another's | -| `ThreadPoolExecutor` | Per-namespace | Provisioned by `with_namespace`; prevents blocking DiskCache/SQLite from stalling event loop of other namespaces | +| `ThreadPoolExecutor` | Per-namespace | Provisioned during wiring, lazily on first `Component.executor` access; prevents blocking DiskCache/SQLite from stalling event loop of other namespaces | | `EventHandlerBase` | Per-namespace | Core routing unit | | `AgentRuntime` | Per-namespace | Each agent in its own namespace | | `RestApiBase` | Per-namespace | Routes prefixed `/api/{namespace}/` | @@ -367,6 +396,12 @@ app = ( ## Phase 0 — `run_app` utility + `AgentRegistration` (no breaking changes) +> **Superseded in part by phase 8b.** `run_app` stands. `AgentRegistration` does not: phase 8b +> deletes it, because an `AppBuilder` that records instead of constructing serves the same purpose +> without a second class. The namespace-injection mechanism described below is unchanged — only its +> owner moves, from `AgentRegistration._apply` to `AgentGroup`. Read this phase for the ContextVar +> reasoning, not for the API. + **Files:** `utils/utils.py`, `app_builder.py`, `__init__.py` `run_app(app: FastAPI, config: Config) -> None` in `utils/utils.py`: @@ -432,8 +467,8 @@ Export both `run_app` and `AgentRegistration` from `blueprint.agents.__init__`. - `add_executor(namespace: str, executor: ThreadPoolExecutor) -> None`. - `get_executor(namespace: str = "") -> ThreadPoolExecutor` — falls back to root `""` if the namespace has no executor; raises `ValueError` if root is also missing. -- The root executor is provisioned in `AppBuilder.build()` (not in `with_namespace`) so - standalone apps always have one. +- The root executor is provisioned in `AppBuilder.build()`, not while a declaration is being + collected, so standalone apps always have one. **Backwards compatibility:** All callers omitting `namespace` use `""` and see today's flat registry. Existing `registry.cache_service` access is unaffected. @@ -459,6 +494,12 @@ registry. Existing `registry.cache_service` access is unaffected. ## Phase 3 — NamespaceBuilder and AppBuilder extension +> **Superseded by phase 8b**, except for `with_cache`'s signature rule and the lazy-executor +> decision, both of which stand. `NamespaceBuilder`, `with_namespace` and the `namespace=` keyword +> are deleted there: they existed only because `with_handler` constructed its component +> immediately, and deferred wiring removes that reason. The C5 scoped-config wiring described below +> still happens, but at `AgentGroup` wiring time rather than in `with_namespace`. + **File:** `app_builder.py` - Add `NamespaceBuilder` class (same file): @@ -635,13 +676,17 @@ same as today. Turns the group configuration into a running app. Everything here is additive; standalone `main.py` deployments are untouched. -**Not a separate "orchestrator" component.** The split is resolution versus wiring, and the -looping-over-agents half belongs in `AppBuilder` — it already reads config to make wiring -decisions (`with_cache` picks a backend, `with_namespace` sizes an executor). What stays outside -is the I/O: env reads, file reads, `sys.exit`, and knowledge of the agent repo's file layout. -`AppBuilder` must remain a pure function of its call sequence so tests can construct exact -compositions without controlling env or filesystem — the same layering mistake as putting retry -logic in `EventHandlingBase` (see the event-client resilience decision record). +**Not a separate "orchestrator" component.** The split is resolution versus wiring: the +looping-over-agents half is builder work, and what stays outside it is the I/O — env reads, file +reads, `sys.exit`, and knowledge of the agent repo's file layout. Wiring must remain a pure +function of its call sequence so tests can construct exact compositions without controlling env or +filesystem — the same layering mistake as putting retry logic in `EventHandlingBase` (see the +event-client resilience decision record). + +Phase 8b moves that half from `AppBuilder` onto `AgentGroup`, which is **not** an orchestrator +either: it is the wiring half, in a class of its own so that an `AppBuilder` never learns it can be +collected and the group's refusals sit with the thing imposing them (spec sec. 4.1). Same layering, +one fewer job per class. Avoid the name "orchestrator": it names the App-of-Apps supervisor process that this design rejected, and reusing it invites confusion with a component that deliberately does not exist. @@ -676,7 +721,7 @@ baked into the image. `./deployment-groups.yaml`) plus `BLUEPRINT_GROUP` to pick the group. The path is configuration, not a constant, so one image serves a ConfigMap mount in Kubernetes, a bind mount in `docker run`, and the repo file in local dev. Falling back to the repo file is what - makes `python -m blueprint.agents.orchestrator` work with no cluster and no mount. + makes `python -m blueprint.agents.entrypoint` work with no cluster and no mount. `BLUEPRINT_GROUP` may be omitted when the file declares exactly one group. What gets mounted is the **resolved slice** for one group, not the full multi-group document. 2. **Environment variables injected directly.** `BLUEPRINT_AGENTS=invoice,order,dunning` and @@ -699,12 +744,14 @@ Entry point, in full: def main() -> None: config = Config(settings_files=["settings.toml"]) group = GroupConfig.resolve(config) # env + file, validated; the only I/O - app = AppBuilder(config).with_group(group).build() + app = AgentGroup(config).with_group(group).build() run_app(app, config) ``` -`AppBuilder.from_group(config)` collapses lines 2-3 for callers who want one call; `with_group` -takes an in-memory `GroupConfig` and performs no I/O, so tests construct one literally. +`AgentGroup.from_group(config)` collapses lines 2-3 for callers who want one call; `with_group` +takes an in-memory `GroupConfig` and reads neither environment nor filesystem, so tests construct +one literally. (As shipped this reads `AppBuilder(config).with_group(group)`; phase 8b moves the +two group methods onto `AgentGroup` and nothing else about this phase changes.) Flow: 1. `GroupConfig.resolve`: read the YAML at `BLUEPRINT_GROUP_CONFIG` if present, apply env-var @@ -714,7 +761,8 @@ Flow: a readable message instead of a silently short-staffed pod. 3. Resolve each name via `importlib.import_module` + `getattr`, **lazily and per group** — only the modules this group needs are imported, so cold start stays proportional to group size. -4. `with_group` calls `with_namespace(agent, registration=reg)` per agent; `build()`; `run_app`. +4. `with_group` records one declaration per agent (`add(name, builder)`); `build()` constructs + every component inside its own namespace scope; `run_app`. **Resolution must complete before the first `Component.__init__`,** because namespace injection happens through the ContextVar read during construction. No incremental resolution, no namespace @@ -750,12 +798,209 @@ sets or hard tenant boundaries only — it does not change this format. **Deployment note (agent repo, not this repo):** when mounting a file, give the ConfigMap a content-hashed name (`finance-group-a1b2c3`) — kustomize's `configMapGenerator` default, or a Helm `checksum/config` annotation. A plain ConfigMap edit leaves the pod template unchanged, so -nothing restarts and the orchestrator keeps running the group it resolved at startup. One +nothing restarts and the running process keeps the group it resolved at startup. One ConfigMap per group, not one shared: a shared one rolls all twenty agents whenever any group changes. --- +## Phase 8b — Builder unification (before 9, because 9 depends on it) + +**Amendment:** `docs/plans/2026-09-10-builder-unification.md` carries the reasoning, the decisions +D1-D7 and the refusal table. This section is the work breakdown only; where the two differ, that +document is the argument and the spec is normative. + +**Files:** `app_builder.py`, new `agent_group.py`, `agent/agent_builder.py`, `group_config.py`, +`entrypoint.py`, `component/registry.py`, `config/config.py`, `services/infrastructure/` +(cache scoping), `io/api/actuators/` (per-agent `/cache/*`, health-checker keys) + +**Not numbered 11.** Phase 10 is documentation and must stay last, and this must precede phase 9: +D4 makes a health checker's owning agent available *as data*, which is exactly what phase 9's +`readiness_policy = "critical"` needs in order to attribute a failing checker to an agent. + +**Why now rather than never.** Adding one `with_*` method today means editing four places +(`AppBuilder`, `AgentRegistration`, `NamespaceBuilder`, and `AgentRegistration.apply`'s `appliers` +dict), and three of those fail *silently* — the capability is simply absent from that surface. The +duplication is not stylistic: `AppBuilder.with_handler(H)` constructs `H` immediately, and a +component constructed before a namespace exists belongs to the root for ever, so a second class had +to exist to defer construction. Deferred wiring removes the reason they diverged, and the other +three classes then have no purpose. Four sites become one. + +**Steps, each its own commit, reported before the next begins:** + +1. **`AppBuilder` records.** A `Declaration` value object; the five `with_*` store instead of + constructing; `build(config=None)` wires at the root. `configure_logging()` moves from + `__init__` into `build()` — with nothing constructed before `build()`, that is where logging + configuration belongs. A builder is single-use and says so, rather than surfacing + `Component.configure`'s "already set" error. Order semantics preserved: `build()` raises on an + instance recorded after a class at equal priority (spec sec. 4.2). +2. **`AgentBuilder` records too.** `config` optional in `__init__`, accepted by `build(config)`. + This fixes a live defect, not just a shape: `AgentBuilder.__init__` requires a `Config` and + `Component._shared_config` has no public read path, so the factory form phase 8 documents + (`lambda: AgentBuilder(config, ...).build()`) **cannot be written** in a declaration-only + `main.py`. Wiring calls `agent.build(config.for_namespace(ns))`, which also removes a second + latent bug: a lambda closes over whichever config was in scope where it was written, which in a + group is the wrong one. +3. **`AgentGroup`** in its own module: named builders in, one `FastAPI` out. Every refusal from + the spec's sec. 4.2 table, each naming the agent and the fix. `with_group` and `from_group` + move here from `AppBuilder`; `entrypoint.build_group_app` calls it. +4. **Delete** `AgentRegistration`, `NamespaceBuilder`, `AppBuilder.with_namespace`, the + `namespace=` keyword on the five `with_*`, `AgentRegistration.apply` and the `appliers` dict. +5. **Caches per agent (D3):** qualify names by namespace, `get_cache` resolves within the + declaring agent and raises otherwise, `/cache/*` becomes per-agent. Deletes + `GroupConfig.cache_names` and `AgentScopedCache` — separate stores make the isolation + structural, so the prefixing lens has nothing left to prevent. Knock-on: an agent with + `idempotency_enabled` must declare `with_cache()`, which its existing error message already + says. +6. **Health-checker attribution (D4):** `(namespace, name)` recorded as data, the qualified key + its rendering. Root keeps the bare name, so an existing readiness payload does not change. +7. **Settings fragments (D5):** group settings are defaults only; each agent's own `settings.toml` + merges under that agent's scope; a process-scope key in an agent fragment raises. This closes + the fragment-merge open point that has been outstanding since config-rework step 3a. +8. **Docstrings and gates:** group behaviour stated on each `with_*` (the decision was RTFM, not + authoring-time validation); a test asserting the declaration surface and `AgentGroup`'s replay + agree, so the recorder cannot drift from the API it replays; the frozen compatibility suite + extended to pin the standalone shape (spec sec. 10.2). +9. **The rules, and the documents that carry them.** Last, because a rule can only be written + once the thing it describes exists. Three parts, each its own commit -- see the section below. + +**Done when** an existing standalone `main.py` runs unchanged, the same file with two lines removed +runs in a group, adding a hypothetical `with_widget` requires exactly one edit, and every principle +this overhaul established is written down in one place with a test behind the ones a test can hold. + +--- + +## Phase 8b step 9 -- the rules, and the documents that carry them + +**Decided 2026-09-10 with the user, after an audit of every markdown reference in the repo.** The +problem this solves is not documentation for its own sake: this overhaul establishes principles -- +collect then wire, ambient namespaces, validate never repair -- that a later feature can violate +without anyone noticing, because they are currently recorded only in a 4600-line changelog nobody +will read end to end. + +### Where they go, and why it is `AGENTS.md` + +`CLAUDE.md:5` says *"See `AGENTS.md` for architecture, component patterns, and testing conventions +shared across all AI assistants."* **`AGENTS.md` has never existed.** +`git log --all --diff-filter=A -- AGENTS.md` returns nothing: it was not written and later deleted, +it was cited into existence. `docs/plans/2026-06-10-sessions-job-handler.md:122` goes further and +quotes what it "states" about versioning. + +So writing it adds no node to the graph -- it turns a pointer that resolves nowhere into one that +resolves. The alternatives were a new `docs/concepts/design-rules.md` (a fresh file in a tree that +already has orphans, leaving the `AGENTS.md` pointer dead beside a new live one) and folding the +rules into `docs/concepts/architecture.md` (descriptive prose for users; binding rules read badly +mixed into it). Both were rejected for the same reason: they add, and this repository's +documentation problem is that it already has more homes than content. + +### Part 1 -- `AGENTS.md` + +One document, grouped by what a rule governs. Each rule states the rule, the reason, and **the +failure it prevents** -- a rule without its failure is advice, and advice gets argued away. Draft +list; wording is settled when the step runs. + +**Construction and assembly** + +- **Collect, then wire.** A declaration API records; nothing is constructed, registered or + connected until `build()`. *Failure:* a component constructed during accumulation exists before + any namespace does and belongs to the root for ever -- which is what forced a second builder + class to exist for three phases. +- **One declaration surface.** Adding a capability is one edit. A second class whose only job is + to defer construction is the smell this phase removed, not a pattern to copy. +- **A builder is single-use, and says so**, rather than surfacing someone else's "already set". +- **Group policy belongs to the collector.** Standalone stays permissive; the group refuses what + it cannot honour, at assembly, naming the agent and the fix. *Failure:* restrictions scattered + into the builder punish the single-agent case for the group's constraints. + +**Namespaces and isolation** + +- **A component never learns it is in a group.** The namespace is ambient, read by + `Component.__init__`; it is never a constructor parameter of a project's component, and never + enumerable from anything a component can reach (C6). *Failure:* an agent that can read its + neighbours can be written to depend on them, and regrouping then breaks it. +- **Isolation is structural where it can be, audited where it cannot.** Separate stores beat a + prefix; where walling off would break a supported use, log and name the reader instead. +- **A lookup never falls back across agents.** *Failure:* two agents that both asked for + `sessions` silently share one store, and only in production. +- **An omitted namespace on the root registry means every namespace, not the root.** Framework + code that dispatches per agent names its namespace explicitly, even where it looks redundant. + +**Names and values that leave the process** + +- **A name that crosses the process boundary is validated, never repaired.** Queue groups, + durables, subjects, cache names, environment prefixes. *Failure:* silent rewriting breaks an + external dependency with nothing in the logs to debug. +- **A check answerable at the call stays at the call.** *Failure:* an error reported several + `with_*` calls later names the wrong line. + +**Declarations and defaults** + +- **An empty declaration means everything, not nothing.** *Failure:* treating an empty set as + authoritative silences the application, and an unhandled event acknowledges -- so the deliveries + vanish rather than piling up where somebody would see them. +- **A key whose absence changes behaviour is required, not defaulted**, and `must_exist=True` + beside a `default=` is a lie Dynaconf never enforces. + +**Configuration and logging** + +- **Configuration is injected before any component exists**, and is read through the component's + own scoped view. There is no public read path to the unscoped loader. +- **Logging is configured by the application**, never by library code, a constructor, or import + time. + +**How the work is done** + +- **No unused code in the framework.** Git history is where removed work belongs; a plausible + unused abstraction misleads the next session into building on it. +- **Probe against real objects.** Every real defect this feature surfaced was found by testing + against a real registry rather than a mock; a mock registry hides resolution bugs by + construction. +- **The spec wins on precedence, not on correctness.** Challenge a requirement's premise, and + argue any departure in the changelog rather than quietly complying or quietly diverging. + +### Part 2 -- the guard tests + +Prose alone has already failed once here: `AGENTS.md` was cited for months without existing. So +every rule that is mechanically checkable gets a test in +`tests/unit/agents/test_design_rules.py`, whose failure message names the rule it enforces. + +| Guard | What it asserts | +|---|---| +| declaration surface | every `AppBuilder.with_*` records and constructs nothing -- called reflectively, registry asserted untouched | +| replay agreement | the declaration surface and `AgentGroup`'s replay agree (step 8's test, moved here and generalised) | +| no unscoped config | no attribute on `Component` or its metaclass returns the loader; `for_namespace` on a view raises | +| no cross-agent fallback | `get_cache` raises on an unknown name; `get_known_namespaces` does not exist | +| validated names | each namespace-bearing entry point refuses an illegal input rather than rewriting it | +| logging ownership | no `basicConfig`, handler or formatter attachment in `src/` outside `LoggingManager` | +| no diagnostics via print | `print(` absent from `src/` except the entry point's deliberate stderr line | +| **references resolve** | every markdown link and document reference in the repo points at a file that exists -- the check that would have caught `AGENTS.md` | + +The last one is what makes the rest durable, and it is why this part is not optional. + +### Part 3 -- clean up the puddle + +The same audit found real duplication, and the instruction was that `AGENTS.md` alone is not +enough: everything else has to be coherent too. + +- **`docs/superpowers/`** -- `plans/` and `specs/` mirroring `docs/plans` and `docs/specs`: + 3 files, 2079 lines, and **nothing in the repo links to any of them.** A second, abandoned home + for the same two document types. Fold into `docs/plans` / `docs/specs` or delete; git history + keeps them either way. +- **Four cache documents, 968 lines** -- `docs/concepts/caching.md` (347), + `docs/concepts/cache-system-overview.md` (232), `docs/concepts/cache-architecture.md` (181), + `docs/guides/caching-getting-started.md` (208). `docs/README.md` links one of the four. + Consolidate, and link whatever survives. +- **The false quotation** at `docs/plans/2026-06-10-sessions-job-handler.md:122`, which attributes + a versioning statement to a document that has never existed. Verify the claim against reality, + or remove it. +- **`docs/development-workflow.md`**, cited by this plan's own file summary and never written: + write it, or drop the reference. + +Phase 10's documentation work is unaffected: it writes the multi-agent setup guide, which is +content, not coherence. + +--- + ## Phase 9 — Deployment-facing constraints (telemetry, probes) **Files:** `io/telemetry/telemetry.py`, `io/api/actuators/actuator_api.py`, @@ -782,6 +1027,15 @@ grouping was paid for. (ready while at least one namespace is up). - Per-namespace degradation surfaces as a `blueprint_namespace_up{agent="..."}` gauge plus an ERROR-level event. Alerting decides who is woken; the probe decides only where traffic goes. +- `readiness_policy = "critical"` needs to know which agent a failing health checker belongs to. + Phase 8b step 6 records that as `(namespace, name)` data, so read it from there rather than + splitting the qualified key on a separator — a name containing the separator would silently + attribute a failure to the wrong agent, which is a C7 violation dressed as a string bug. +- The actuator's two configuration-error branches (`actuator_api.py:95`, `:149`) are **dead**: + `Config.validate()` raises during `__init__`, so no live `Config` ever carries validation + errors. Out of scope here — it belongs to + `docs/plans/2026-09-10-config-validation-unification.md`, which decides whether the fix is to + delete them or to make readiness able to report a bad configuration at all. **C4 — a degraded namespace stops consuming.** Readiness gates HTTP only; a not-ready pod still holds its NATS subscriptions and still consumes events, so for an event-driven agent readiness @@ -832,8 +1086,8 @@ hidden by API design — so they must be caught mechanically rather than documen **Files:** `docs/guides/multi-agent-setup.md` (new), `docs/guides/deployment.md` (rewrite), `agent_generator` CLI (`asbs setup`, `asbs create agent`, `asbs validate`) -**Last on purpose.** Everything a migration guide would describe -- `AgentRegistration`, the -group configuration, the entry point, the single image -- is built in phases 0, 2 and 8. A guide +**Last on purpose.** Everything a migration guide would describe -- the single builder surface, the +group configuration, the entry point, the single image -- is built in phases 0, 2, 8 and 8b. A guide written before them documents an API that does not exist, which is worse than no guide: a reader cannot tell which half is aspiration. So this phase adds no framework behaviour; it makes what the earlier phases built usable by someone who has only ever written a single-agent service. @@ -848,10 +1102,14 @@ it is a claim the reader can check. 1. Scaffolding a fresh multi-agent repository -- what `asbs setup` produces and why one image serves every group. -2. Migrating an existing single-agent project -- the two file changes from *Migration path for an - existing agent* above, and nothing else. +2. Migrating an existing single-agent project -- the three file changes from *Migration path for + an existing agent* above (`main.py`, `Dockerfile`, `agents.toml`), and nothing else. 3. What stays byte-identical and why: registry names, queue group, durable, telemetry - `service.name` (C1, C2). This is the section that decides whether anyone trusts the migration. + `service.name` (C1, C2) -- **for an agent left standalone**. This is the section that decides + whether anyone trusts the migration, so it must be equally explicit about the other half: an + agent moved *into a group* takes its identity from its agent name rather than `app_name`, so its + queue group, durable and route prefix change once, on the first grouped deploy. Regrouping after + that changes nothing. Say which of the two the reader is doing before showing either. 4. The one decision to get right **before** migrating: the agent name becomes the queue group and part of the durable name, so renaming it afterwards is a consumer migration (sec. 7.7), and it must satisfy the namespace alphabet (C1) -- `""` or `[a-z][a-z0-9_]*`, no `-`. @@ -882,7 +1140,11 @@ the guide alone that nothing broker-side changed. | File | Phase | |---|---| | `utils/utils.py` | 0 | -| `app_builder.py` | 0 (`AgentRegistration`), 3 (`NamespaceBuilder` + executor provisioning), 6 | +| `app_builder.py` | 0 (`AgentRegistration`), 3 (`NamespaceBuilder` + executor provisioning), 6, 8b (records instead of constructing; `AgentRegistration`, `NamespaceBuilder`, `with_namespace` and the `namespace=` keyword deleted) | +| `agent_group.py` (new) | 8b (collection, and every group refusal) | +| `agent/agent_builder.py` | 8b (records; `config` optional in `__init__`, accepted by `build`) | +| `services/infrastructure/cache_service.py`, `io/api/actuators/` | 8b (per-agent caches and `/cache/*`; health-checker keys qualified) | +| `AGENTS.md` (new), `tests/unit/agents/test_design_rules.py` (new) | 8b step 9 (the rules this overhaul establishes, and the guards that hold them) | | `__init__.py` | 0 | | `component/registry.py` | 1 (namespace storage, named caches, executor registry) | | `component/component.py` | 2 (`namespace` param, `executor` property) | @@ -903,7 +1165,7 @@ the guide alone that nothing broker-side changed. | `io/telemetry/telemetry.py` | 9 (C2 — per-namespace providers + empty-namespace path) | | `io/api/actuators/actuator_api.py`, `io/api/actuators/health.py` | 9 (C3, C4, C7 — gauge and ERROR event on every removal-from-service path) | | `clients/io/nats_client.py`, `clients/io/dapr_client.py` | 9 (C7 — done-callbacks on detached tasks; `subscriptions_ready` drives the per-namespace gauge) | -| `config/config.py` | 3 (C5 — `agent_scope` wiring via `with_namespace`), 8 (fragment merge) | +| `config/config.py` | 3 (C5 — `agent_scope` wiring), 8 (fragment merge), 8b (group defaults + per-agent fragments; process-scope keys raise) | | `services/eventing/event_publishing_service.py` | P6 (per-namespace client) | **Scaffolding tracks the framework, every step.** `blueprint/agent_generator` is part of this @@ -937,10 +1199,15 @@ queue group. A dev mode at `namespace=""` would give every developer URLs and in that differ from production. Consequently `namespace=""` is reserved for pre-migration agents; every newly scaffolded agent has a real namespace in every environment. -**Per-agent migration (opt-in only):** -- `main.py`: wrap builder in `if __name__ == "__main__": ... run_app(app, config)`, - add `else: registration = AgentRegistration()...` -- `Dockerfile`: `CMD uvicorn src.main:app` → `CMD python src/main.py` +**Per-agent migration (opt-in only)** — three changes, and no branches in `main.py`: +- `main.py`: drop the `config` argument from `AppBuilder(...)` and drop the trailing `.build()`, + leaving `agent = AppBuilder()...`; add `def create_app(): return agent.build()` only if the agent + is still to be served on its own. +- `Dockerfile`: `CMD uvicorn src.main:app` → `CMD python -m blueprint.agents.entrypoint`. +- `agents.toml`: add the agent's entry, pointing at `main:agent`. + +The dual-branch recipe an earlier draft of this line described is rejected — see *Migration path +for an existing agent* above and spec sec. 11. ## Testing expectations @@ -948,9 +1215,19 @@ New test coverage required alongside the implementation: - **Registry:** namespace isolation (component in `"order"` not visible from `"invoice"`), two-level fallback resolution, named cache CRUD, executor registry add/get/fallback. -- **`AppBuilder` / `NamespaceBuilder`:** `with_namespace` wires components into the - correct namespace; `AgentRegistration._apply` delegates all stored entries correctly; - ContextVar is reset after `_apply` (no namespace leak between calls). +- **`AppBuilder` / `AgentGroup` (8b):** nothing is constructed or registered until `build()`; + `build()` wires at the root; `AgentGroup` wires each agent into the correct namespace and resets + the ContextVar after each (no namespace leak between agents); every refusal in spec sec. 4.2's + table raises and names the agent; a class, a factory and an instance all work standalone while + only the instance is refused in a group; an instance recorded after a class at equal priority + raises at `build()`; the declaration surface and `AgentGroup`'s replay agree, so the recorder + cannot drift from the API it replays. +- **Per-agent caches (8b):** two agents both declaring `sessions` get separate stores; an agent + reading a cache it did not declare raises rather than falling back to root; `/cache/*` reports + only the calling agent's caches. +- **Settings fragments (8b):** a key in an agent's own `settings.toml` resolves for that agent and + is invisible to every other; a group default is served to an agent that declares nothing; a + process-scope key in an agent fragment raises at startup. - **Handler chain:** namespace-scoped handler selection — handlers registered under namespace A are not invoked when processing events for namespace B. - **NATS:** per-namespace subscription closures capture and forward the correct namespace diff --git a/docs/plans/2026-09-10-builder-unification.md b/docs/plans/2026-09-10-builder-unification.md new file mode 100644 index 00000000..c311107e --- /dev/null +++ b/docs/plans/2026-09-10-builder-unification.md @@ -0,0 +1,296 @@ +# Proposal -- One builder, collected into a group + +| | | +|---|---| +| **Status** | Proposal. Decided in discussion 2026-09-09/10; not implemented. | +| **Amends** | `docs/specs/2026-08-28-multi-agent-grouping.md` sec. 4.1, 4.2, 8, 11; `docs/plans/2026-08-28-multi-agent-grouping.md` phases 0 (part 3), 3, 6, 8 | +| **Does not touch** | Configuration validation -- see `2026-09-10-config-validation-unification.md` | + +## The problem this solves + +Adding one `with_*` method today means editing **four** places: + +| Place | If forgotten | +|---|---| +| `AppBuilder.with_*` | standalone cannot use it | +| `AgentRegistration.with_*` | grouped agents cannot declare it | +| `NamespaceBuilder.with_*` | the block form cannot use it | +| `AgentRegistration.apply`'s `appliers` dict | `KeyError` at apply time | + +Three of those fail **silently** -- the capability simply is not there on that surface. Only the +fourth is loud. Nothing tells the next developer that the four exist. + +The duplication is not an accident of style. `AppBuilder.with_handler(H)` **constructs `H` +immediately**, and a component constructed before a namespace exists belongs to the root for +ever -- so a second class had to exist to defer construction until a namespace was in force. +`AgentRegistration` is that class, `NamespaceBuilder` is the block-form sugar over it, and the +`appliers` dict is the bridge between them. + +**So the fix is not to share the methods -- it is to remove the reason they diverged.** If +`AppBuilder` records instead of constructing, one class serves both roles and the other two have +no purpose. + +## The shape + +### One builder, which records + +```python +class AppBuilder: + def __init__(self, config: Config | None = None) -> None: ... + def with_handler(self, handler, *, name=None, **kwargs) -> Self: ... # records + def with_service(self, service, *, name=None, **kwargs) -> Self: ... # records + def with_agent(self, agent, *, name=None, **kwargs) -> Self: ... # records + def with_scheduler(self, scheduler, *, name=None, **kwargs) -> Self: ... # records + def with_rest_api(self, api, *, name=None, **kwargs) -> Self: ... # records + def with_cache(self, enabled=True, enable_locking=True, *, name="default") -> Self: ... + def with_health_checker(self, name: str, checker) -> Self: ... + def build(self, config: Config | None = None) -> FastAPI: ... # wires, at the root + @property + def declarations(self) -> tuple[Declaration, ...]: ... # read by the collector +``` + +Nothing is constructed until `build()`. `build()` wires everything at the **root namespace**: +standalone knows nothing about namespaces, which is the decision below. + +### A collector, which is a different thing + +`AppBuilder` does not know it can be collected. Assembling a group is its own unit -- it takes +named builders and one configuration, enforces the group's rules, and drives one process-level +wiring pass: + +```python +def assemble(agents: Mapping[str, AppBuilder], config: Config) -> FastAPI: ... +``` + +This is where `with_group` and `from_group` move to, and where every refusal below lives. The +division is the one the plan already states for phase 8 -- resolution versus wiring, with the I/O +outside the builder -- extended one step: **group policy is not the builder's business either.** + +### Deleted + +- `AgentRegistration` -- `AppBuilder` used without `build()` is the declaration. +- `NamespaceBuilder` and `AppBuilder.with_namespace` -- the collector takes named builders instead. +- The `namespace=` parameter on the five `with_*` -- it existed only for `NamespaceBuilder`. +- `AgentRegistration.apply` and its `appliers` dict. + +Four duplication sites become **one**. Adding a `with_*` method is one edit, and the collector +replays whatever was recorded without knowing what it is. + +## Decisions + +### D1 -- Standalone knows nothing about namespaces + +`build()` wires at the root. An agent's name exists only in a group context, so it has exactly +one home: the group configuration. `main.py` never names its agent, which is what keeps +*a developer never sees namespaces* true. + +**Consequence, already documented:** moving an agent from standalone into a group changes its +queue group and its JetStream durable, so the first grouped deploy is a consumer migration. See +the phase 5 migration note. + +### D2 -- Standalone is permissive; the group has rules + +Everything that works today keeps working standalone. The group refuses what it cannot honour, +at assembly time, with a message naming the agent and the fix. No deprecation warnings: spec +sec. 10 makes the standalone shape supported indefinitely, so warning about it every startup +would be crying wolf, and `DeprecationWarning` is invisible by default anyway. + +The refusals follow from what a group *is* -- one process, one configuration, one port, every +component constructed inside a namespace scope, and no agent deciding for another: + +| Recorded call | In a group | Capability lost? | +|---|---|---| +| the five `with_*` with a class + kwargs | allowed | -- | +| the five `with_*` with a factory | allowed; called inside the namespace scope | -- | +| the five `with_*` with an **instance** | **refused** -- its namespace and registry key were fixed at construction | No: the factory form recovers it | +| `with_cache(...)` | allowed; name qualified per agent (D3) | -- | +| `with_health_checker(...)` | allowed; key qualified per agent (D4) | No: a checker is not a `Component` | +| `AppBuilder(config)` | **refused** -- one process, one settings tree and one port | No, once D5 lands | +| `build()` already called | **refused** -- already wired at the root | No | + +The instance refusal reuses wording that already exists in `AppBuilder._register`; it moves from +record time to assembly time. + +### D3 -- A cache is private to the agent that declared it + +An agent has access to **exactly** the caches it declared, and to nothing else. `get_cache(name)` +resolves within the declaring agent and raises otherwise -- no fallback of any kind. Cache names +are qualified by namespace, so two agents may both declare `sessions` and get separate stores. + +This implements what spec sec. 8 actually requires -- *"Cache names MUST therefore be +namespace-scoped by default"* -- of which only the data-partition half was ever built. + +**Deleted by this decision:** + +- `GroupConfig.cache_names` -- there is no shared cache, so a group has none to declare. +- `AgentScopedCache` -- the partition-prefixing lens exists only to stop two agents colliding + inside one shared store, which can no longer happen. Separate stores make the isolation + structural rather than dependent on a prefix being applied correctly. + +**Knock-ons:** an agent with `idempotency_enabled` must declare `with_cache()` (its existing +error message already says so), and `/cache/*` becomes per-agent rather than process-wide. + +### D4 -- A health checker's key carries its agent + +Two agents calling `with_health_checker("db", ...)` currently collide in a dict and one +disappears silently. The key is qualified by namespace; the root keeps the bare name, so a +standalone application's `/health/ready` payload does not change. + +The attribution is stored **as data** -- `(namespace, name)` -- and the prefix is its rendering. +Phase 9's `readiness_policy = "critical"` needs to know which agent a failing checker belongs to, +and recovering that by splitting a string breaks the moment a name contains the separator. + +For the record, the current policy this inherits: every checker is polled on a timer and ANDed +(`health_cache.py:139`), so one unhealthy checker returns 503 for the whole pod. In a group that +means one agent's outage removes every agent from rotation. That is `readiness_policy = "all"`, +which phase 9 makes selectable; nothing here changes it. + +### D5 -- A group's settings are the defaults; an agent's own file is only its own + +- The group's `settings.toml` supplies **defaults, and only defaults**. +- Each agent ships its own `settings.toml`, merged **under that agent's scope** -- never at root. + +Therefore an agent may set any key for itself, and can **never** change what another agent or the +process sees. There is no collision to detect, because the two never occupy the same slot. + +This closes the settings-fragment merge open point outstanding since config rework step 3a; both +of its unanswered questions dissolve. The one hole to close deliberately: **process-scope keys in +an agent's file must raise**, from an explicit list (`app_port`, `event_bus`, `envvar_prefix`, +`nats_stream_name`, ...). Scoped, they would be silently inert -- read by nothing, reported by +nothing. + +### D6 -- `AgentBuilder` records too, and is wired with the agent's own configuration view + +`AgentBuilder.__init__` requires a `Config` as its first argument, and `Component._shared_config` +deliberately has **no public read path**. So in a declaration-only `main.py` there is no +configuration in scope, and the documented factory form + +```python +.with_agent(lambda: AgentBuilder(config, runtime_name="orders").build()) +``` + +**cannot be written at all.** That is a live defect in what phase 8 shipped, not a consequence of +this proposal. + +The fix is the same change as for `AppBuilder`: `config` optional in `__init__`, accepted by +`build()`. An unbuilt `AgentBuilder` is then handed straight to `with_agent`, and the wiring calls +`agent.build(config)` with **that namespace's configuration view**: + +```python +agent = AgentBuilder(runtime_name="orders").with_model_from_config() +app_builder.with_agent(agent) # recorded, not built +``` + +This deletes the lambda escape hatch for the common case and fixes a second latent bug with it: a +lambda closes over whichever configuration was in scope where it was written, which in a group is +the wrong one. Handing the scoped view in at wiring time makes the right one structural. + +`with_agent` accepts: a class, an unbuilt `AgentBuilder`, a factory, or -- standalone only -- a +built `AgentRuntime`. + +### D7 -- Group rules are documented on the methods + +Each `with_*` docstring states what the group does with it. There is no authoring-time +validation: every refusal necessarily lands at assembly, because `with_cache()` is called at +import, long before anything knows whether this builder will be collected. `asbs validate` is +where authoring-time gates would go if they are ever wanted. + +## Behavioural changes to state + +**Registration order.** An instance passed to `with_*` is constructed by the caller at its source +line; a class is constructed during `build()`. So an instance recorded *after* a class registers +*before* it, which can flip equal-priority handler tie-breaking -- resolved by registration order +today, as `DispatchIndex.build` already documents. `build()` can detect exactly this case, since +it knows both the recorded order and which entries were instances, and raise. Order therefore +still means what it means; the violation surfaces at `build()`. + +**Nothing is in the registry until `build()`.** Code that looks a component up between `with_*` +calls breaks. The framework's own convention already forbids it -- collaborators are resolved in +`on_startup`, and components must not read configuration in `__init__` -- so the fix is the +documented pattern. + +**`configure_logging()` moves into `build()`.** It runs in `__init__` today so that component +construction is logged with the right format. With deferred wiring nothing is constructed until +`build()`, so configuring logging there is strictly more correct. + +**A builder is single-use, and says so.** `build()` calls `Component.configure`, which refuses a +second call -- today that surfaces as someone else's error. It gets its own message. + +## Why this is not a Builder anti-pattern + +It is the pattern. GoF Builder accumulates parts; `build()` produces the product. What exists +today is the smell: `with_handler` constructs a component and registers it into a process-global +registry *during accumulation*, which is exactly why a second class was needed. + +The four anti-patterns this design is checked against: + +1. **Side effects during accumulation** -- removed; recording only. +2. **A silently single-use builder** -- made explicit (above). +3. **Requiring the product's context in the constructor** -- `config` moves to `build()`; + remaining in `__init__` only as the compatibility concession. +4. **Replay drift** -- a recorder can diverge from the API it replays. Mitigated by storing the + *method name* and resolving it with `getattr`, which fails loudly, plus a test asserting the + builder's declaration surface and the collector's replay agree. + +`AppBuilder` is deliberately **not** a composite builder: it never absorbs another builder, and +does not know it can be collected. Collection is the collector's job, and so are the group's +rules. + +## Migration + +Unchanged for an existing project -- spec sec. 10's MUST holds: `AppBuilder(config)...build()` and +`uvicorn src.main:app` behave exactly as today. + +To become groupable, `main.py` drops one argument and splits the last call off: + +```python +agent = AppBuilder().with_service(OrderService).with_handler(OrderHandler) + +def create_app(): # uvicorn src.main:create_app --factory --reload + return agent.build() +``` + +`uvicorn` resolves dotted attributes after the colon (`importer.py`), so +`uvicorn src.main:agent.build --factory` also works -- and because it is an import string, +`--reload` works, which `run_app` cannot offer today. + +Three shapes, one implementation: + +| Shape | Command | +|---|---| +| Standalone, today's | `uvicorn src.main:app` | +| Standalone, migrated | `uvicorn src.main:create_app --factory` | +| Grouped | `python -m blueprint.agents.entrypoint` | + +## Work breakdown + +1. `Declaration` value object; `AppBuilder` records; `build(config=None)` wires at the root. +2. `AgentBuilder` records; `config` optional in `__init__`, accepted by `build()` (D6). +3. The collector: named builders in, one `FastAPI` out; every refusal in D2; `with_group` and + `from_group` move here; the entry point calls it. +4. Delete `AgentRegistration`, `NamespaceBuilder`, `with_namespace`, the `namespace=` parameter, + `apply` and the `appliers` dict. +5. Caches per agent (D3): qualify names, delete `cache_names` and `AgentScopedCache`, per-agent + `/cache/*`. +6. Health-checker attribution (D4). +7. Settings fragments (D5), including the process-scope key refusal. +8. Docstrings (D7); the surfaces-agree test; the frozen compatibility suite that pins the + standalone shape. +9. **The rules, last.** `AGENTS.md` -- the file `CLAUDE.md` already cites and that has never + existed -- carrying every principle this overhaul establishes, each with its reason and the + failure it prevents; a guard test for each rule a test can hold, including one asserting that + every document reference in the repo resolves; and the documentation duplication the audit + found cleaned up. Last, because a rule can only describe something that exists. Breakdown in + the plan's *Phase 8b step 9* section. + +Each step is its own commit, reported before the next begins, per `CLAUDE.md`. + +## Explicitly out of scope + +- **Configuration validation and its unification** -- `2026-09-10-config-validation-unification.md`. +- **`readiness_policy` and per-namespace degradation** -- phase 9. +- **Generating `agents.toml` and the group file** -- parked with manifest generation. +- **Whether the group's composition should live in `settings.toml` rather than its own YAML.** + Raised in discussion and worth doing: the spec's justification for a separate mechanism is that + resolution happens "before `Config` is constructed", and it does not -- the entry point builds + `Config` first and passes it in. Deferred so that this proposal changes one thing at a time. diff --git a/docs/plans/2026-09-10-config-validation-unification.md b/docs/plans/2026-09-10-config-validation-unification.md new file mode 100644 index 00000000..1fdf4c8b --- /dev/null +++ b/docs/plans/2026-09-10-config-validation-unification.md @@ -0,0 +1,159 @@ +# Proposal -- One startup pass that says everything the configuration is missing + +| | | +|---|---| +| **Status** | Proposal. Raised in discussion 2026-09-10; not implemented, not scheduled. | +| **Relation to the grouping work** | **None. Do not touch this during the builder rewrite.** Explicitly carved out of `2026-09-10-builder-unification.md`. | +| **Intended to be** | Non-breaking: the set of keys that must exist does not change. | + +## Why this is separate + +The builder rewrite changes *where* configuration is handed in (`build(config)` instead of +`__init__`) and *how* an agent's fragment is merged. It does not change what happens when a key is +missing -- and it should not, because the two would then fail together and neither could be +reviewed on its own. This document is the second half, kept apart on purpose. + +## What exists today + +There are **four** unrelated mechanisms deciding what happens when a setting is absent, and they +disagree about whether that is an error, a default, or nothing at all. + +### 1. Three Dynaconf validators that cannot fail + +`config.py:161-168` declares `app_name`, `app_port` and `app_environment` with +`must_exist=True` -- and with `default=`. Verified against the installed Dynaconf: + +``` +Validator("app_name", must_exist=True, default="agent_blueprint") -> 'agent_blueprint' +Validator("app_name", must_exist=True) -> ValidationError +``` + +When a default is present it is injected and `must_exist` never fires. So of the three +declarations, the only condition that can actually fail is `is_type_of=int` on `app_port`. An +application with no `settings.toml` at all starts, and calls itself `agent_blueprint`. + +That is a defensible policy -- these three have sensible defaults. It is not defensible that the +code says `must_exist=True`, because the next person to add a genuinely required key will copy the +pattern and get a silent default. + +### 2. `Config.validate()`, whose two real checks run somewhere unreachable + +`validate()` (`config.py:836`) is called from `Config.__init__` (`config.py:187`) and **raises** +`ConfigError`. Beyond the validators it checks two things by hand: `app_port` in range, and an +API key when the provider is `vllm`. + +Because it raises during construction, a `Config` object that exists has always passed. Therefore +`_validation_errors` is always empty on any live instance, and the two places that read it -- +`actuator_api.py:95` in readiness and `actuator_api.py:149` in liveness -- are **dead branches**. +The readiness probe was written to report configuration failure as a 503 with the reasons in the +payload; it cannot, because the process never reaches the point of serving. Worth deciding +deliberately which of the two behaviours is wanted rather than leaving both in the tree. + +### 3. Typed getters that turn a missing key into a default, silently + +`get_ai_config`, `get_cache_config`, `get_observability_config`, `get_event_publishing_config`, +`get_prompt_config`, `get_runtime_config`, `get_nats_subscription_config` each read keys with +`self.get(key, )` and hand back a Pydantic model. A typo'd or absent key is +indistinguishable from one deliberately left out: the model is fully populated either way. + +This is where a missing *required* setting hides longest, because the value only turns out to be +wrong much later, in a component, as a connection failure or an empty result. + +### 4. Per-component checks, each at a different moment + +| Check | Where | When it fires | +|---|---|---| +| `model_name`, `provider`, provider supported | `agent_builder.py:108-114` | declaration time, in `main.py` | +| `sessions_service` present, `base_url`, `agent_id`, `api_key` | `sessions_bus.py:88-107`, `api_client.py:50-58`, `key_provider.py:71-185` | first connect | +| `idempotency_ttl` numeric | `handler_chain.py:563` | first event | +| `scheduler_mode` in range | `scheduler.py:352` | startup | +| any numeric NATS key | `nats_client.py:444-451` | on read | + +Each message is good in isolation -- most name the key and the accepted values. The problem is the +aggregate: a deployment missing three keys is fixed in three deploy cycles, because each failure +hides the next, and some of them wait for the first request. + +## What to build + +### One declaration point + +A component declares what it needs, next to the code that reads it: + +```python +class SessionsBus(ApiBase): + required_config = ( + Required("sessions_service.base_url"), + Required("sessions_service.agent_id"), + Required("sessions_service.api_key", secret=True), + Required("sessions_service.max_concurrent_jobs", default=10, is_type=int), + ) +``` + +`secret=True` keeps the value out of the message: a validation error may say the key is missing, +never what it holds. + +### One pass, reporting everything at once + +At the end of `build()`, after every component is registered and each one's namespace is known, +one pass walks the declarations, resolves each key **through that component's own configuration +view**, and collects failures. If there are any, it raises once: + +``` +Configuration is incomplete. 3 required settings are missing or invalid: + + billing.sessions_service.agent_id missing required by SessionsBus (agent 'billing') + orders.idempotency_ttl not an int required by HandlerChain (agent 'orders'), got 'thirty' + cache.redis_host missing required by RedisCacheService (agent 'orders') +``` + +Three properties this needs to have: + +- **Every failure, not the first.** That is the whole point. +- **The agent named.** In a group, "missing `sessions_service.agent_id`" does not say whose, and + D5 of the builder proposal makes each agent's fragment its own -- so the answer is per agent. +- **Before the port is bound.** Same rule as the group resolution failure in `entrypoint.main`: + a pod that binds its port has told Kubernetes it is a healthy replica. + +### Keep the required set exactly as it is + +The migration risk here is entirely in scope creep. Declaring a key required that today has a +silent default breaks a running deployment at its next restart, and it will not be obvious that a +configuration-validation change did it. So the first implementation transcribes what the four +mechanisms require **today** and nothing more: + +- The three root validators keep their defaults, declared as defaults rather than as + `must_exist=True`. +- Every check in mechanism 4 keeps the same condition, moved to a declaration. +- The typed getters' defaults stay defaults. + +Anything that *should* become required is a second, separate change with its own migration note. + +### Decide what the actuator reports + +Once the pass exists, the dead branches resolve one way or the other: + +- **Fail the process** (today's actual behaviour): drop `has_validation_errors`, + `get_validation_errors` and both actuator branches. Simplest, and matches + "a misconfigured pod must not serve". +- **Fail readiness** (what the actuator was written for): keep the errors as data, serve + `/health/live` as UP and `/health/ready` as 503 with the reasons, and let an operator read them + from the probe rather than from pod logs. + +The second is more useful in a cluster and is what the code intends; the first is what the code +does. Not decided here. + +## What this does not cover + +- `models/config.py`'s topic-mapping parser, which validates *shape* rather than presence and is + already loud and well-tested. +- Making anything newly required (above). +- `asbs validate`, which could run the same pass at authoring time once it exists -- worth doing, + but after. + +## Sequence, when it is picked up + +1. `Required` value object and the `required_config` class attribute; no behaviour change. +2. The startup pass, reporting collected failures, wired into `build()`. +3. Transcribe mechanisms 1, 2 and 4 into declarations; delete the hand-written checks as each is + covered by a declaration and a test. +4. Decide the actuator question and remove whichever half loses. diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md index 8c42b943..27f5d2c5 100644 --- a/docs/specs/2026-08-28-multi-agent-grouping.md +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -6,6 +6,8 @@ | **Resolves** | #75 (deployment model decision), #73 (duplicate cron ticks) | | **Unblocks** | #32 (100 agents in 4 GB), #35 (shared interpreter), #20 (worker scaling) | | **Related** | #33 (lazy heavy imports), #34 / #74 (dependency slimming), #36 (concurrency bounds + benchmark), #43 (scheduler double-start), #6 (config service) | +| **Amended by** | `docs/plans/2026-09-10-builder-unification.md` -- decided 2026-09-10, folded into sec. 2, 4, 5.3, 8, 9, 10 and 11 below. | +| **Deferred out of** | `docs/plans/2026-09-10-config-validation-unification.md` -- configuration validation is not part of this feature. | Requirement keywords (**MUST**, **MUST NOT**, **SHOULD**, **MAY**) are used in the RFC 2119 sense. @@ -45,7 +47,7 @@ into processes a deployment-time parameter rather than a code-time one. | **Agent** | A unit of business capability: handlers, services, prompts, optionally a REST API and scheduler. Authored as one directory. | | **Namespace** | The registry partition an agent's components live in. Equal to the agent name. `""` is the root namespace and means "pre-migration single-agent app". | | **Group** | The set of agents loaded into one process, and therefore into one pod. | -| **Registration** | An `AgentRegistration` -- component classes collected without instantiation. | +| **Declaration** | An `AppBuilder` whose `build()` has not been called -- component classes recorded without instantiation. | | **Root** | Namespace `""`, holding process-wide shared components. | --- @@ -200,21 +202,22 @@ deliberately rather than inferred from a restart. ### 4.1 New ```python -class AgentRegistration: - """Fluent collector. Stores component classes; instantiates nothing.""" - def with_handler(self, handler, *, name=None, **kwargs) -> "AgentRegistration" - def with_service(self, service, *, name=None, **kwargs) -> "AgentRegistration" - def with_agent(self, agent, *, name=None, **kwargs) -> "AgentRegistration" - def with_scheduler(self, scheduler, *, name=None, **kwargs) -> "AgentRegistration" - def with_rest_api(self, api, *, name=None, **kwargs) -> "AgentRegistration" - # No with_cache -- caches are registered on the AppBuilder. +class AgentGroup: + """Collects one declaration per agent and wires them into a single application.""" + def __init__(self, config: Config) -> None: ... + def add(self, namespace: str, agent: AppBuilder) -> "AgentGroup" + def with_group(self, group: GroupConfig) -> "AgentGroup" # import each module, add each + def build(self) -> FastAPI + + @classmethod + def from_group(cls, config: Config) -> "AgentGroup" # resolve + with_group class GroupConfig: """Resolved group composition. A value object; performs no I/O once constructed.""" name: str agents: tuple[AgentSpec, ...] # name, critical flag, module path - cache_names: tuple[str, ...] + # No cache list: an agent may use only the caches it declared itself (sec. 8). @classmethod def resolve(cls, config: Config) -> "GroupConfig": @@ -224,27 +227,75 @@ class GroupConfig: def run_app(app: FastAPI, config: Config) -> None: ... ``` -`GroupConfig.resolve` is the only member that touches the environment or the filesystem. -`with_group` **MUST NOT** perform I/O, so tests can construct a `GroupConfig` literally. +`GroupConfig.resolve` is the only member that reads the environment or the filesystem. +`AgentGroup.with_group` **MUST NOT** read either -- importing the agent modules a `GroupConfig` +names is not a configuration read -- so tests can construct a `GroupConfig` literally. + +**Collection is its own class, and `AppBuilder` MUST NOT know it can be collected.** An +`AppBuilder` never absorbs another builder and exposes no group concept; `AgentGroup` constructs +its own and replays what each agent recorded. This is what keeps one fluent surface honest: the +group's restrictions belong to the thing imposing them, so `AppBuilder` stays permissive and every +refusal in sec. 4.2 is raised by `AgentGroup`. ### 4.2 Changed ```python class AppBuilder: - def with_namespace(self, name: str, *, registration: AgentRegistration | None = None, - config: Config | None = None) -> "AppBuilder | NamespaceBuilder" - def with_group(self, group: GroupConfig) -> "AppBuilder" - - @classmethod - def from_group(cls, config: Config) -> "AppBuilder" # resolve + with_group + """One declaration surface. Records what it is told; wires nothing until build().""" + def __init__(self, config: Config | None = None) -> None: ... - # namespace: str = "" added to with_handler / with_service / with_agent / - # with_scheduler / with_rest_api -- keyword-only. + # with_handler / with_service / with_agent / with_scheduler / with_rest_api: + # signatures unchanged. They record; nothing is constructed until build(). def with_cache(self, enabled: bool = True, enable_locking: bool = True, *, name: str = "default") -> "AppBuilder" + def with_health_checker(self, name: str, checker) -> "AppBuilder" + + def build(self, config: Config | None = None) -> FastAPI + + @property + def declarations(self) -> tuple[Declaration, ...] # what AgentGroup replays ``` +**Deferred wiring is normative.** A `with_*` call **MUST NOT** construct a component or enter +anything into the registry; both happen only in `build()`. This is not a style preference: +constructing a component reads the namespace from a `ContextVar` (sec. 4.3), so one built during a +`with_*` call belongs to whichever namespace was in force at that line and can never be moved +afterwards. Recording instead of constructing is what lets one class serve both the standalone and +the grouped shape, and it is why no second collector type (`AgentRegistration`, `NamespaceBuilder`) +needs to exist. + +`AppBuilder.build()` wires at the **root** namespace. There **MUST** be no `with_namespace` method +and no `namespace` parameter on any `with_*` method: standalone has no namespace to name, and an +agent's name lives only in the group configuration (sec. 11). + +**Configuration resolution order, highest first:** `build(config)`, then `AppBuilder(config)`, then +the default settings files. `AgentGroup` **MUST** refuse a builder that carries its own +configuration -- one process has one settings tree and one port -- and **MUST** wire each agent +with that agent's own scoped view (C5). + +**What `AgentGroup` refuses, each because a group cannot honour it:** + +| Recorded call | In a group | Capability lost | +|---|---|---| +| a class plus kwargs | allowed | -- | +| a factory or lambda | allowed; called inside the namespace scope | -- | +| an already-constructed **instance** | **refused** -- its namespace and registry key were fixed before the group existed | none: the factory form recovers it | +| `AppBuilder(config)` | **refused** -- one process, one settings tree, one port | none | +| `with_cache(...)` | allowed; the name is qualified per agent (sec. 8) | -- | +| `with_health_checker(...)` | allowed; the key is qualified per agent | none | +| a builder whose `build()` already ran | **refused** -- already wired at the root | none | + +Every refusal **MUST** name the agent and the fix. Refusals land at assembly, not at authoring +time: `with_cache()` runs at import, long before anything knows whether this builder will be +collected. + +**Registration order keeps its meaning.** An instance is constructed by the caller at its own +source line, a class during `build()`, so an instance recorded *after* a class would register +*before* it -- which can flip equal-priority handler tie-breaking, resolved by registration order +today. `build()` knows both the recorded order and which entries were instances, and **MUST** +raise on that combination rather than silently reordering. + **`with_cache` is the one place where the obvious design breaks compatibility.** The current signature is `with_cache(enabled: bool = True, enable_locking: bool = True)` (`app_builder.py:117`). Making `name` the first parameter would turn an existing @@ -255,8 +306,8 @@ two existing positional parameters. ### 4.3 Component `Component.__init__` **MUST NOT** gain a namespace parameter. The namespace is read from a -module-level `ContextVar` set by `AgentRegistration._apply`, so no user subclass constructor -signature changes and no positional argument shifts. +module-level `ContextVar` set by `AgentGroup` around each agent's wiring, so no user subclass +constructor signature changes and no positional argument shifts. `Component.executor` returns the namespace's `ThreadPoolExecutor`, falling back to root. The executor **MUST** be created lazily on first access; an app that never performs blocking work @@ -305,11 +356,24 @@ changing them triggers a rolling update on their own. ### 5.3 Settings authoring -An agent author writes plain top-level keys in their own directory's `settings.toml` -(`model_name = "..."`), not `[default.]`. The build **MUST** merge each agent's fragment -under its own scope so C5 resolves them, without the author knowing the scope exists. +A group's own `settings.toml` supplies **defaults, and only defaults**. An agent author writes +plain top-level keys in their own directory's `settings.toml` (`model_name = "..."`), not +`[default.]`, and the build **MUST** merge that fragment **under that agent's scope** so C5 +resolves it, without the author knowing the scope exists. + +An agent may therefore set any key for itself, and **MUST NOT** be able to change what another +agent or the process sees. There is consequently no collision to report: a fragment and a root key +never occupy the same slot, and a default restated in an agent's fragment is simply that agent's +own value. + +Process-scope keys in an agent fragment **MUST** raise at startup, from an explicit list +(`app_port`, `event_bus`, `envvar_prefix`, `nats_stream_name`). Scoped, such a key is read by +nothing and reported by nothing -- C7's failure mode in configuration form -- and its author has +no way to discover that the value they set is inert. -Collisions between an agent fragment and a root key **MUST** be reported at build time. +What happens when a *required* key is absent is deliberately not specified here. It is +`docs/plans/2026-09-10-config-validation-unification.md`, kept out of this feature so that the +two cannot fail together. --- @@ -551,8 +615,10 @@ seconds field in particular -- are not portable to one. **In-process coordination is a per-tick claim, not a leader lease.** An earlier form of this section called for a NATS KV or cache-backed leader lease. A slot claim satisfies the same requirement and is preferred, because it removes rather than answers the failover question: every -replica's timer fires, each tries to store a marker keyed on `(scheduler, minute)` in the shared -cache, and the one that stores it runs the tick. Nothing is elected and nothing is held, so there +replica's timer fires, each tries to store a marker keyed on `(scheduler, minute)` in the agent's +own cache -- shared across that agent's replicas, and per sec. 8 invisible to every other agent, so +two agents each running a scheduler of the same name cannot claim each other's slots -- and the +replica that stores it runs the tick. Nothing is elected and nothing is held, so there is no renewal task to schedule (and therefore none to leak, C7), no lease left behind by a replica that dies holding one, and no takeover bound to specify -- the next slot is claimed from scratch by whoever is alive. @@ -668,9 +734,16 @@ Caches are looked up by name with no namespace dimension, which makes them a cro collision surface: two independently developed agents both calling `get_cache("sessions")` share one cache the moment they are grouped, invisibly and only in production. -Cache names **MUST** therefore be namespace-scoped by default, with an explicit opt-in for -genuinely shared caches. Agents share no cache by design, so isolation is the correct -default. +An agent **MUST** have access to exactly the caches it declared with `with_cache`, and to no +others. Cache names **MUST** be qualified by namespace, so two agents may both declare `sessions` +and receive separate stores; `get_cache(name)` **MUST** resolve within the declaring agent and +raise otherwise, with no root fallback and no shared-cache opt-in. Agents share no cache by +design, and separate stores make that isolation structural rather than dependent on a key prefix +being applied correctly at every call site. + +Two things follow. A group declares no caches of its own, so `GroupConfig` carries no cache list +(sec. 4.1). And `/cache/*` is per agent: one process-wide cache endpoint would report one agent's +keys to another, which is the collision this section exists to close. `registry.cache_service` (getter and setter) **MUST** be retained as an alias for the `"default"` cache in the root namespace. @@ -683,8 +756,9 @@ cache in the root namespace. 2. Validate every agent name against the in-image agent map. Fail with the group and the missing agent named. 3. Import each agent module lazily; read its module-level `registration`. -4. `AppBuilder(config).with_group(group)` -- one `with_namespace` per agent. -5. `build()`, then `run_app(app, config)`. +4. `AgentGroup(config).with_group(group)` -- one recorded declaration added per agent. +5. `build()`, then `run_app(app, config)`. Every component is constructed here, inside its own + namespace scope; steps 1-4 construct nothing. Resolution **MUST** complete before the first `Component.__init__`, because namespace injection happens through a `ContextVar` read during construction. No incremental resolution. @@ -721,7 +795,10 @@ change, and `uvicorn src.main:app` as its entrypoint. Specifically: | Concern | Guarantee | |---|---| -| `AppBuilder` fluent API | Unchanged; `namespace` added keyword-only. | +| `AppBuilder` fluent API | Unchanged. `AppBuilder(config)...build()` behaves as today, and no `namespace` parameter is added to anything. | +| Passing a constructed instance to `with_*` | Unchanged standalone; refused only when the builder is collected into a group (sec. 4.2). | +| Component construction timing | Deferred to `build()`. Reading a component out of the registry between `with_*` calls was never supported -- collaborators resolve in `on_startup` -- and now breaks. | +| `with_health_checker` keys | Bare name at the root, so an existing readiness payload is unchanged; qualified per agent in a group. | | `with_cache(False)` / `with_cache(True, False)` | Unchanged (sec. 4.2). | | `Component` subclasses | No constructor change (sec. 4.3). | | `registry.cache_service` | Retained as alias. | @@ -760,18 +837,26 @@ grouping work. An agent author's `main.py` is, in full: ```python -registration = ( - AgentRegistration() +agent = ( + AppBuilder() .with_service(OrderService) .with_handler(OrderValidationHandler) .with_rest_api(OrderApi) ) ``` -No `AppBuilder`, no `Config`, no `run_app`, no `if __name__`, no namespace, no group. The -dual-branch `main.py` in the current plan -- which duplicates the component list under -`if __name__ == "__main__"` and `else:` -- **MUST** be collapsed to this single declaration; two -branches to keep in sync is itself a leak of the grouping model. +No `Config`, no `run_app`, no `if __name__`, no namespace, no group -- and no `.build()`: the +declaration is the file. A project that also wants to serve this agent alone adds one function and +nothing else: + +```python +def create_app(): # uvicorn src.main:create_app --factory --reload + return agent.build() +``` + +The component list appears **once** either way. The dual-branch `main.py` of an earlier draft -- +the same components repeated under `if __name__ == "__main__"` and `else:` -- **MUST NOT** be +used; two copies to keep in sync is itself a leak of the grouping model. `asbs dev agents/` runs one agent as a group of one, using its **real** namespace. Local routes are therefore `/api/order/orders/{id}`, identical to production, and local consumer @@ -863,8 +948,9 @@ Two things an author still needs to know: their agent's name, and that handlers duplication itself, and that is mechanically checkable -- the in-image agent map already enumerates every agent, so the CI gate **SHOULD** require each environment's declaration to account for all of them. Open: which shape, and how many environments actually differ. -- Is the dedup cache per-namespace or shared, and what TTL is defensible against the redelivery - window? +- What dedup TTL is defensible against the redelivery window? (Whether the dedup cache is + per-namespace or shared is **answered**: sec. 8 gives an agent only the caches it declared, so it + is necessarily per-namespace.) - **#32's metric needs restating.** "Per-agent RAM" stops being meaningful once the interpreter is shared; the correct unit is *baseline per group + marginal per agent*. Its "as-is 160-250 MB per agent" row describes the model being retired, and its acceptance criteria should be re-expressed diff --git a/src/blueprint/agents/__init__.py b/src/blueprint/agents/__init__.py index 8d6db750..03da4ae5 100644 --- a/src/blueprint/agents/__init__.py +++ b/src/blueprint/agents/__init__.py @@ -1,16 +1,16 @@ """Base framework components for the agent blueprint.""" from .agent import AgentBuilder, AgentRuntime -from .app_builder import AgentRegistration, AppBuilder, NamespaceBuilder +from .agent_group import AgentGroup +from .app_builder import AppBuilder from .config import Config from .utils import run_app __all__ = [ "AgentBuilder", - "AgentRegistration", + "AgentGroup", "AgentRuntime", "AppBuilder", "Config", - "NamespaceBuilder", "run_app", ] diff --git a/src/blueprint/agents/agent/agent_builder.py b/src/blueprint/agents/agent/agent_builder.py index 3c5f09f1..b6e1aaba 100644 --- a/src/blueprint/agents/agent/agent_builder.py +++ b/src/blueprint/agents/agent/agent_builder.py @@ -36,29 +36,31 @@ class AgentBuilder: This builder allows handlers to create agents with custom configuration without requiring inheritance or abstract methods. + Like ``AppBuilder``, a ``with_*()`` call **records**: no configuration is read and no + component is created until ``build()``. That is what lets an unbuilt builder be declared + where no configuration is in scope, and handed to ``AppBuilder.with_agent`` to be built + later, inside its agent's namespace and against its agent's configuration view. + Example: - # Simple agent - agent = await ( - AgentBuilder(config) + # Declared, and built by the application -- the form a grouped agent needs + AppBuilder().with_agent( + AgentBuilder(runtime_name="invoice_analyzer") .with_model_from_config() - .with_system_prompt("system") - .build() + .with_system_prompt("invoice_analyzer_system") ) - # Fully configured agent - agent = await ( - AgentBuilder(config, runtime_name="invoice_analyzer") + # Built here, by the caller + agent = ( + AgentBuilder(config) .with_model_from_config() - .with_system_prompt("invoice_analyzer_system") - .with_tools([calculate_tool, validate_tool]) - .with_result_type(InvoiceOutput) + .with_system_prompt("system") .build() ) """ def __init__( self, - config: Config, + config: Config | None = None, runtime_name: str = "default", meter: Any | None = None, package_root: Path | str | None = None, @@ -66,16 +68,23 @@ def __init__( """Initialize the agent builder. Args: - config: Application configuration + config: Application configuration. **Optional**, and omitting it is what makes this + builder declarable: ``AgentBuilder.__init__`` used to require one, while + ``Component._shared_config`` deliberately has no public read path, so in a + ``main.py`` that only declares -- which is every grouped agent -- there was no + configuration to pass and this class could not be used at all. Pass it to + :meth:`build` instead, or let ``AppBuilder`` pass the agent's own view. runtime_name: Name for runtime-specific config lookup meter: Optional OpenTelemetry Meter for metrics recording package_root: Optional root path for the package (e.g., where main.py resides). Used to locate prompts in package_root/prompts directory. """ - self._config = config + self._config: Config | None = config self._runtime_name = runtime_name self._ai_config: AIConfig | None = None self._ai_client: AIClientBase | None = None + self._model_from_config: bool = False + self._model_name_override: str = "" self._system_prompt: str | None = None self._tools: list[Tool] = [] self._result_type: type[BaseModel] = BaseModel @@ -86,8 +95,66 @@ def __init__( self._recorder: MetricsRecorder | None = None self._built: bool = False + @property + def runtime_name(self) -> str: + """Which runtime's configuration section this agent reads. + + Public because the application names the agent in its logs before it is built: an + ``AgentBuilder`` handed to ``AppBuilder.with_agent`` is a declaration, and a failure + while building it has to be able to say which one. + """ + return self._runtime_name + + def _require_config(self) -> Config: + """Return the configuration, which exists only once one has been supplied. + + Raises: + ValueError: if neither ``__init__`` nor ``build()`` was given one. Named rather + than defaulted: an ``AgentBuilder`` always sits inside an application that has + a configuration, so a missing one is a wiring mistake and not a case to guess + a settings file for. + """ + if self._config is None: + raise ValueError( + f"AgentBuilder for runtime '{self._runtime_name}' has no configuration: none was given to " + "AgentBuilder(config) and none to build(config). Pass one to either -- or hand the unbuilt " + "builder to AppBuilder.with_agent(), which builds it with its agent's own configuration view." + ) + return self._config + + def _resolve_config(self, config: Config | None) -> Config: + """Settle which configuration to build against. + + ``build(config)`` **wins** over ``AgentBuilder(config)``, which is the opposite of + ``AppBuilder``'s rule and deliberately so. An ``AppBuilder`` is the application, so + nothing above it knows better and two configurations mean the author is confused. An + ``AgentBuilder`` sits *inside* an application, and what the application passes is the + view scoped to this agent's namespace (C5) -- the whole point of D6. A constructor + argument is a convenience for the standalone ``AgentBuilder(config)...build()`` chain, + so it yields to the scoped view rather than overriding it. + + At the root ``for_namespace("")`` returns the loader itself, so for a single-agent + application the two are the same object and there is nothing to choose between. + """ + if config is None: + return self._require_config() + if self._config is not None and self._config is not config: + logger.debug( + "AgentBuilder for runtime '%s' was given a configuration in its constructor and another to build(); " + "building against the one passed to build(), which is the view scoped to this agent", + self._runtime_name, + ) + self._config = config + return config + def with_model_from_config(self, model_name: str = "", runtime_name: str = "") -> "AgentBuilder": - """Configure the model from application config. + """Take the model from application configuration when the agent is built. + + Records the intent; the configuration is read in :meth:`build`. It has to be, because + there may be no configuration yet -- and in a group the one that matters is the view + scoped to this agent, which only the application can supply. So the three refusals + this used to raise here (no model name, no provider, unsupported provider) now raise + from ``build()``, naming the same runtime. Args: model_name: Optional model name override. If omitted, uses the value from config. @@ -99,10 +166,21 @@ def with_model_from_config(self, model_name: str = "", runtime_name: str = "") - if runtime_name: logger.warning("Deprecation warning: runtime_name is not necessary anymore. Set the runtime in constructor instead.") - ai_config = self._config.get_ai_config(self._runtime_name) + self._model_from_config = True + self._model_name_override = model_name + return self + + def _resolve_ai_config(self) -> AIConfig: + """Read this runtime's AI configuration and check it can produce a client. + + Raises: + ValueError: if the model name or provider is missing, or the provider is one this + framework has no client for. + """ + ai_config = self._require_config().get_ai_config(self._runtime_name) - if model_name: - ai_config.model_name = model_name + if self._model_name_override: + ai_config.model_name = self._model_name_override if not ai_config.model_name: raise ValueError(f"No model name for runtime agent '{self._runtime_name}' configured") @@ -113,9 +191,8 @@ def with_model_from_config(self, model_name: str = "", runtime_name: str = "") - if ai_config.provider not in _CLIENT_MAP: raise ValueError(f"Unsupported provider: '{ai_config.provider}'. Supported: {list(_CLIENT_MAP.keys())}") - self._ai_config = ai_config logger.info("Configured agent with provider=%s, model=%s", ai_config.provider, ai_config.model_name) - return self + return ai_config def with_system_prompt(self, name: str | None = None) -> "AgentBuilder": """Configure the system prompt by name. @@ -205,8 +282,13 @@ def get_model_settings(self) -> dict[str, Any]: Returns: ModelSettings object with configuration from runtime settings + + Raises: + ValueError: if no configuration has been supplied yet. See + :meth:`_require_config`; ``build()`` adopts the one it is given before calling + this, so a built agent's settings are always read from the right tree. """ - ai_config = self._config.get_ai_config(self._runtime_name) + ai_config = self._require_config().get_ai_config(self._runtime_name) settings: dict[str, Any] = {} if ai_config.max_tokens is not None: @@ -219,12 +301,17 @@ def get_model_settings(self) -> dict[str, Any]: return settings - def build(self, **kwargs: Any) -> AgentRuntime: + def build(self, config: Config | None = None, **kwargs: Any) -> AgentRuntime: """Build the configured agent. - Creates the model and resolves the system prompt. + Reads the configuration, creates the AI client and resolves the system prompt. Nothing + before this point touched configuration or created a component, which is what lets the + application decide *when* and *against which configuration view* an agent is built. Args: + config: The configuration to build against. Wins over the one given to + ``__init__`` -- see :meth:`_resolve_config` for why the precedence runs this + way round. ``AppBuilder`` passes the view scoped to this agent's namespace. **kwargs: Additional keyword arguments for instantiating the agent Returns: @@ -232,13 +319,18 @@ def build(self, **kwargs: Any) -> AgentRuntime: Raises: ValueError: If required configuration is missing + RuntimeError: If this builder has already been built """ - if self._ai_config is None: - raise ValueError("Model must be configured before building agent. Call with_model_from_config() first.") - if self._built: raise RuntimeError("AgentBuilder.build() has already been called. Create a new builder instance.") + resolved_config = self._resolve_config(config) + + if not self._model_from_config: + raise ValueError("Model must be configured before building agent. Call with_model_from_config() first.") + + self._ai_config = self._resolve_ai_config() + # Create AI client Component — registers in registry; model is created in AgentRuntime.on_startup() self._ai_client = _CLIENT_MAP[self._ai_config.provider](self._runtime_name) # type: ignore[index] @@ -246,7 +338,7 @@ def build(self, **kwargs: Any) -> AgentRuntime: prompt_name = self._system_prompt if prompt_name is None: try: - prompt_config = self._config.get_prompt_config(self._runtime_name) + prompt_config = resolved_config.get_prompt_config(self._runtime_name) prompt_name = prompt_config.system_prompt_name except Exception as exc: raise ValueError( @@ -263,7 +355,7 @@ def build(self, **kwargs: Any) -> AgentRuntime: try: self._system_prompt = PromptLoader.load_prompt( prompt_name, - self._config, + resolved_config, path=self._package_root, provider=self._ai_config.provider, # type: ignore[arg-type] ) @@ -292,7 +384,7 @@ def build(self, **kwargs: Any) -> AgentRuntime: self._built = True if self._metrics_enabled: - self._recorder = MetricsRecorder(self._config, self._meter) + self._recorder = MetricsRecorder(resolved_config, self._meter) runtime._recorder = self._recorder runtime._model_settings = self.get_model_settings() # type: ignore[assignment] diff --git a/src/blueprint/agents/agent_group.py b/src/blueprint/agents/agent_group.py new file mode 100644 index 00000000..ddac680c --- /dev/null +++ b/src/blueprint/agents/agent_group.py @@ -0,0 +1,363 @@ +"""Assembling one process out of several agents' declarations. + +This module holds what an :class:`~blueprint.agents.app_builder.AppBuilder` deliberately does +not: the knowledge that several agents can share a process, and the rules a group imposes on +each of them. + +**An ``AppBuilder`` does not know it can be collected.** It records what one agent is made of +and, asked to, builds that agent alone. Collection happens here, in a class the builder has +never heard of, which is what keeps the standalone shape free of the group's constraints -- +*standalone is permissive; the group refuses what it cannot honour*. Every refusal therefore +lives in this file rather than being scattered into the builder, where it would punish the +single-agent case for a situation it is not in. + +Three things happen here and nowhere else: + +- **Resolution** -- which agents this process runs, and where their declarations live. + :meth:`AgentGroup.resolve` performs the I/O; :meth:`AgentGroup.from_config` performs only the + imports, so a test can state an exact composition without touching the environment. +- **Refusal** -- the group's rules, applied at assembly, each message naming the agent and the + fix (spec sec. 4.2). +- **Replay** -- every agent's recorded declarations re-issued onto one root builder, inside that + agent's namespace, and built once. +""" + +import importlib +import logging +import sys +from collections.abc import Mapping +from pathlib import Path + +from fastapi import FastAPI + +from .app_builder import AppBuilder +from .component.namespace import namespace_scope, validate_namespace +from .config import Config +from .group_config import AgentSpec, GroupConfig, GroupConfigError + +logger = logging.getLogger(__name__) + + +class AgentGroup: + """The agents one process hosts, and the single application they become. + + Constructed from named, **unbuilt** ``AppBuilder`` declarations:: + + group = AgentGroup("finance", {"orders": orders_builder, "billing": billing_builder}) + app = group.assemble(config) + + or resolved from the deployment:: + + app = AgentGroup.resolve(config).assemble(config) + + A group of one is an ordinary group: nothing about it is special, and it is how an agent + gets a process to itself while still being deployed by the group mechanism. + """ + + def __init__(self, name: str, agents: Mapping[str, AppBuilder], *, settings: Mapping[str, Path] | None = None) -> None: + """Declare a group. + + Args: + name: The deployment group's name, for logging. Not a namespace: it names the + process, and C6 keeps it out of reach of agent code. + agents: The agents to host, keyed by the name each one runs under. The key becomes + the agent's namespace, and with it its registry key prefix, queue group, + durable name, cache partition and telemetry service name. A mapping rather + than a list because two agents cannot share a name, and a mapping says so + structurally instead of needing a check. + settings: Each agent's own settings file, keyed by the same agent name. + :meth:`assemble` merges each one under that agent's scope (spec sec. 5.3), so an + agent keeps writing plain keys in its own directory and never learns that a scope + exists. :meth:`from_config` derives these from the declaration modules it + imports; a group constructed literally passes them, or passes none and every + agent's settings then come from the group's own file. + + Raises: + ValueError: if an agent's name is not a legal namespace, or is the root. + """ + self._name = name + self._agents: dict[str, AppBuilder] = {} + for agent_name, builder in agents.items(): + namespace = validate_namespace(agent_name) + if not namespace: + raise ValueError( + "An agent in a group cannot be named '': that is the root namespace, which is where a " + "standalone application's components live and where the framework's own root components go. " + "Give the agent the name it is deployed under." + ) + self._agents[namespace] = builder + self._settings: dict[str, Path] = {name: Path(path) for name, path in (settings or {}).items()} + + @property + def name(self) -> str: + """The deployment group's name.""" + return self._name + + @property + def agents(self) -> Mapping[str, AppBuilder]: + """The agents this group hosts, keyed by namespace, in declaration order.""" + return dict(self._agents) + + @property + def settings(self) -> Mapping[str, Path]: + """Where each agent's own settings file is, for the agents that have one.""" + return dict(self._settings) + + # ------------------------------------------------------------------ + # Resolution + # ------------------------------------------------------------------ + + @classmethod + def resolve(cls, config: Config, *, environ: dict[str, str] | None = None) -> "AgentGroup": + """Work out which agents this process runs, and load their declarations. + + The one entry point here that reaches outside the process: ``GroupConfig.resolve`` + reads the environment and the group file. Separated from :meth:`from_config` for that + reason -- a test that wants an exact composition uses the half that performs no I/O. + + Args: + config: The application's configuration. + environ: The environment to resolve from, for tests. + + Returns: + The group this process is asked to host. + + Raises: + GroupConfigError: if the group cannot be resolved, or a critical agent cannot be + loaded. + """ + return cls.from_config(GroupConfig.resolve(config, environ=environ)) + + @classmethod + def from_config(cls, group: GroupConfig) -> "AgentGroup": + """Import each agent named by ``group``, and return the group they form. + + **Reads no environment and no files.** Importing an agent's module is the one thing + here that reaches outside, and it is driven entirely by the ``module`` strings the + group carries -- so a test points them at test modules and controls neither the + environment nor the filesystem to do it. Imports happen per group, so cold start is + proportional to the number of agents this process actually hosts rather than to the + number the image contains. + + A critical agent that cannot be loaded raises, which the entry point turns into a + non-zero exit before the port is bound. A non-critical one is skipped with an ERROR: + that flag is the deployment saying it would rather run the rest (spec sec. 9.1). The + flag is read *before* the agent is wired rather than after an exception, because there + is no partial build to unwind -- one process, one ``assemble()``. + + Args: + group: The resolved group. + + Returns: + The group, with every loadable agent's declaration in hand. + + Raises: + GroupConfigError: if a critical agent's module or declaration cannot be loaded. + """ + logger.info("Resolving group '%s': %d agent(s)", group.name, len(group.agents)) + + agents: dict[str, AppBuilder] = {} + settings: dict[str, Path] = {} + for spec in group.agents: + builder = cls._load_declaration(spec) + if builder is None: + continue + agents[spec.name] = builder + # Only for an agent that loaded: a skipped non-critical agent has no scope to merge + # anything into. + fragment = cls._settings_path(spec.module) + if fragment is not None: + settings[spec.name] = fragment + + return cls(group.name, agents, settings=settings) + + @staticmethod + def _load_declaration(spec: AgentSpec) -> AppBuilder | None: + """Import an agent's declaration, or report why it could not be loaded. + + Returns: + The agent's unbuilt ``AppBuilder``, or ``None`` when a non-critical agent could not + be loaded and is to be skipped. + + Raises: + GroupConfigError: if a critical agent cannot be loaded. The message names the agent + and the module path it came from, because the two are declared in different + files -- the agent name in the group file or an environment variable, the + module in the image's agent map -- and which of them is wrong is the first + thing to establish. + """ + module_path, _, attribute = spec.module.partition(":") + if not module_path or not attribute: + return AgentGroup._skip_or_raise( + spec, + f"'{spec.module}' is not a valid declaration path. Write it as 'package.module:attribute', naming the " + "AppBuilder the module assigns.", + ) + + try: + module = importlib.import_module(module_path) + except Exception as exc: + # Every exception, not only ImportError: importing a module runs it, so anything its + # top level does can fail here, and an agent whose declaration raises on import is + # exactly as unloadable as one whose module is absent. + return AgentGroup._skip_or_raise(spec, f"importing '{module_path}' raised {type(exc).__name__}: {exc}", exc) + + declaration = getattr(module, attribute, None) + if declaration is None: + return AgentGroup._skip_or_raise( + spec, f"module '{module_path}' has no attribute '{attribute}', so its declaration cannot be read." + ) + if not isinstance(declaration, AppBuilder): + return AgentGroup._skip_or_raise( + spec, + f"'{spec.module}' is a {type(declaration).__name__}, not an AppBuilder. An agent's declaration is the " + "builder its components are declared on, handed over without build() having been called.", + ) + logger.debug("Loaded the declaration for agent '%s' from '%s'", spec.name, spec.module) + return declaration + + @staticmethod + def _settings_path(module_spec: str) -> Path | None: + """Return where an agent's own settings file is: beside the module that declares it. + + One rule, and it has to be one an author can see without reading this code: the + ``settings.toml`` in the same directory as the declaration module named in the agent + map. An agent is a directory of handlers, services and a declaration, and its settings + belong to that directory the same way. + + Read from ``sys.modules`` rather than by importing again, because this runs only after + :meth:`_load_declaration` has imported the module -- so the answer is the file Python + actually loaded, not one guessed from a dotted path that may resolve differently. + + Returns: + The path, or ``None`` for a module with no file at all -- a namespace package or one + built in memory, neither of which has a directory to ship settings in. + """ + module_path = module_spec.partition(":")[0] + module = sys.modules.get(module_path) + file = getattr(module, "__file__", None) + if not file: + logger.debug("Module '%s' has no file, so the agent can ship no settings of its own", module_path) + return None + return Path(file).parent / "settings.toml" + + @staticmethod + def _skip_or_raise(spec: AgentSpec, reason: str, cause: BaseException | None = None) -> None: + """Raise for a critical agent, or log and skip a non-critical one. + + Raises: + GroupConfigError: when ``spec`` is critical. + """ + if spec.critical: + raise GroupConfigError(f"Agent '{spec.name}' could not be loaded and is critical: {reason}") from cause + logger.error("Agent '%s' could not be loaded and is not critical, so it is skipped: %s", spec.name, reason) + return None + + # ------------------------------------------------------------------ + # Assembly + # ------------------------------------------------------------------ + + def assemble(self, config: Config) -> FastAPI: + """Build one application out of every agent's declarations. + + One root builder, one ``build()``, one FastAPI application -- because a group *is* one + process. Each agent's recorded calls are re-issued onto that builder inside + :func:`namespace_scope`, so every component it creates reads the agent's name from the + ambient scope and no component, and no ``main.py``, ever mentions a namespace. + + The refusals run before anything is replayed, so a group that cannot be honoured fails + without half-populating a registry. + + Each agent's own ``settings.toml`` is merged under that agent's scope first, which is + the one thing here that reads a file (spec sec. 5.3). It happens before the root builder + exists, because ``build()`` is where components read their configuration and a fragment + merged after that would have been read too late to matter. + + Args: + config: The process's configuration. One tree for the whole group -- which is why + an agent that brought its own is refused below. The group's own settings are the + defaults; each agent's file supplies that agent's own values. + + Returns: + The application. + + Raises: + ValueError: if an agent's declaration is one a group cannot honour. See + :meth:`_refuse_what_a_group_cannot_honour`. + ConfigError: if an agent ships a settings file that cannot be read. + """ + logger.info("Assembling group '%s': %s", self._name, ", ".join(self._agents) or "no agents") + + for namespace, builder in self._agents.items(): + self._refuse_what_a_group_cannot_honour(namespace, builder) + + # Before anything is constructed, and before the root builder adopts the configuration: + # every component reads its keys through its agent's scoped view during build(), so a + # fragment merged afterwards would be a file that was read too late to matter. + for namespace in self._agents: + path = self._settings.get(namespace) + if path is not None: + config.merge_agent_settings(namespace, path) + + root = AppBuilder(config) + for namespace, builder in self._agents.items(): + # Recorded before anything is replayed, so that an agent declaring no component is + # still an agent this process hosts: build() wires one transport per hosted agent + # and asks each one's own configuration whether it publishes, and neither of those + # can be derived from a declaration list that may be empty. + root.host_agent(namespace) + with namespace_scope(namespace): + for declaration in builder.declarations: + declaration.replay(root) + + return root.build() + + @staticmethod + def _refuse_what_a_group_cannot_honour(namespace: str, builder: AppBuilder) -> None: + """Refuse a declaration a group cannot place, naming the agent and the fix. + + These are the rules of spec sec. 4.2's table, and they live here rather than in + ``AppBuilder`` because they are the *group's* rules: everything refused below works + perfectly well in a standalone application, and will go on working, because sec. 10 + makes that shape supported indefinitely. + + Args: + namespace: The agent being checked, for the message. + builder: Its declaration. + + Raises: + ValueError: if the builder has already been built, carries its own configuration, + or declares an already-constructed component. + + Note: + The already-built check comes first on purpose: ``build()`` adopts whatever + configuration it resolved, so a built builder always reports one too, and the + configuration message would otherwise be the only one anybody ever saw. + """ + if builder.is_built: + raise ValueError( + f"Agent '{namespace}' has already been built, so its components exist and belong to the root " + "namespace: a component's namespace and registry key are fixed at construction, and build() also " + "injects the configuration process-wide, which can happen once. Hand the group the builder before " + "build() is called, and let the group build it." + ) + + if builder.has_config: + raise ValueError( + f"Agent '{namespace}' was declared as AppBuilder(config), and a group cannot honour that: one " + "process has one settings tree, one logging configuration and one HTTP port, and the group supplies " + "all three. Declare it as AppBuilder() with no argument -- a declaration, not an application -- and " + "the group hands each agent its own scoped view of the process's configuration when it builds it." + ) + + for declaration in builder.declarations: + if not declaration.is_built: + continue + raise ValueError( + f"{type(declaration.target).__name__} was passed to with_{declaration.kind}() as an instance by " + f"agent '{namespace}', and a group cannot place it: it was constructed at that line, before the " + "group existed, so its namespace and its registry key are already the root's -- and two agents " + f"declaring one would collide on that key. Pass the class -- with_{declaration.kind}(" + f"{type(declaration.target).__name__}, ...) with its constructor arguments as keyword arguments -- " + "or a callable returning it, so the group builds it inside this agent's namespace." + ) diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index 8c41a490..a8283f92 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -1,11 +1,10 @@ """Generic FastAPI application setup and configuration.""" -import importlib import logging -from collections.abc import AsyncIterator, Callable, Iterator, Mapping -from contextlib import asynccontextmanager, contextmanager +from collections.abc import AsyncIterator, Callable, Mapping +from contextlib import asynccontextmanager from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, TypeVar, overload +from typing import TYPE_CHECKING, Any, TypeVar from fastapi import FastAPI from fastapi.routing import APIRoute @@ -14,14 +13,23 @@ from .io.api.actuators.health import HealthCheckerBase from .component.component import Component -from .component.namespace import ROOT_LABEL, ROOT_NAMESPACE, namespace_of, namespace_scope, validate_namespace +from .component.namespace import ( + ROOT_LABEL, + ROOT_NAMESPACE, + construction_scope, + current_namespace, + namespace_of, + qualified_entry_name, + validate_namespace, +) from .component.registry import DEFAULT_CACHE_NAME, Registry +from .agent.agent_builder import AgentBuilder from .agent.agent_runtime import AgentRuntime from .handler.event_handler_base import EventHandlerBase from .io.api.rest_api_base import RestApiBase from .io.api.scheduling.scheduler import SchedulerBase from .io.api.actuators.actuator_api import ActuatorApi -from .io.api.actuators.health import CacheHealthChecker, ClientHealthChecker +from .io.api.actuators.health import CacheHealthChecker, ClientHealthChecker, HealthCheckEntry from .io.api.eventing.dapr import DaprEventing from .io.api.eventing.nats import NatsEventing from .io.api.eventing.sessions_bus import SessionsBus @@ -35,10 +43,16 @@ from .services.eventing.event_publishing_service import EventPublishingService from .services.sessions import SessionKeyProvider, SessionsApiClient from .services.infrastructure.cache_backend_factory import CacheBackendFactory -from .config import Config, TelemetryManager -from .group_config import AgentSpec, GroupConfig, GroupConfigError +from .config import DEFAULT_SETTINGS_FILES, Config, TelemetryManager from .utils import parse_bool +_UNCONSTRUCTED_KINDS = frozenset({"cache", "health_checker"}) +"""Declaration kinds the replay pass does not construct. + +A cache is created by ``CacheBackendFactory`` rather than by calling a class, and a health +checker is not a ``Component`` at all -- the object declared is the object used. +""" + HandlerT = TypeVar("HandlerT", bound=EventHandlerBase) ServiceT = TypeVar("ServiceT", bound=ServiceBase) AgentT = TypeVar("AgentT", bound=AgentRuntime) @@ -48,272 +62,72 @@ logger = logging.getLogger(__name__) -@contextmanager -def _construction_scope(namespace: str) -> Iterator[None]: - """Construct inside ``namespace``, or leave the ambient namespace exactly as it is. - - The difference matters because ``namespace_scope("")`` is not a no-op: it *sets* the current - namespace to the root. :meth:`AgentRegistration.apply` opens one scope per agent and then - calls the builder's ``with_*`` methods, which default ``namespace`` to the root -- so - entering a scope unconditionally would reset every component of every agent back to the - root, silently, and the ambient mechanism would apply to nothing. - - Args: - namespace: The agent to construct for, or ``""`` to keep whatever is already in force. - - Yields: - Nothing; the scope is ambient. - """ - if not namespace: - yield - return - with namespace_scope(namespace): - yield - - @dataclass(frozen=True) -class RegisteredComponent: - """One component an :class:`AgentRegistration` will build when it is applied. +class Declaration: + """One ``with_*`` call recorded by an :class:`AppBuilder`, replayed by ``build()``. + + Recording rather than constructing is what lets one builder class serve both deployment + shapes. A component built while a ``with_*`` call is running is built *before any namespace + exists*, so it belongs to the root for ever -- which is why declaring an agent used to need + a second class. Deferring construction to ``build()`` removes that reason. Attributes: - kind: Which ``with_*`` on the builder this entry is applied through. - target: A component class, or a zero-argument callable returning a component. - name: Registry name override, or ``None`` to let the component derive its own. - kwargs: Constructor arguments, forwarded when ``target`` is a class. + kind: Which ``with_*`` recorded this. It names both how ``build()`` constructs it + and, through :meth:`replay`, the method that records it again. + target: A component class, a zero-argument factory returning one, an unbuilt + ``AgentBuilder``, or an already-built component. ``None`` for a cache, which + names no class. + name: Registry name override, or ``None`` to let the component derive its own. For a + cache this is the cache's name, which is never ``None``. + namespace: The agent this belongs to, resolved when the call was recorded: the explicit + ``namespace=`` argument if one was given, otherwise whatever scope was in force. + kwargs: Constructor arguments, forwarded when ``target`` is a class or a factory. For a + cache, the remaining ``with_cache`` arguments. """ kind: str target: Any name: str | None + namespace: str kwargs: Mapping[str, Any] - -class AgentRegistration: - """What an agent is made of, declared without building any of it. - - This is the shape a project's ``main.py`` takes so that the same agent can run alone or - inside a group. It collects component *classes*; whoever applies it decides the namespace - they are built in, which is why nothing here -- and nothing in the components themselves -- - mentions a namespace:: - - registration = AgentRegistration().with_service(OrderService).with_handler(OrderHandler) - - app = AppBuilder(config).with_registration(registration).build() # alone - # a group applies the same object under the agent's own namespace instead - - **Nothing is instantiated until :meth:`apply` runs**, and that is the point rather than an - optimisation: a component built here would be built before any namespace exists, and would - belong to the root whichever agent it was declared for. So an already-constructed component - is refused -- see :meth:`with_rest_api` for what to write instead. - - **There is no ``with_cache``.** A cache is process-wide and is registered on the - ``AppBuilder`` that hosts the group; an agent that declared its own would either duplicate - another agent's or quietly take it over. Ask for a cache by name from the registry instead. - """ - - def __init__(self) -> None: - self._components: list[RegisteredComponent] = [] - @property - def components(self) -> tuple[RegisteredComponent, ...]: - """What has been declared, in declaration order. + def is_built(self) -> bool: + """Whether ``target`` is a component that already exists. - Order is preserved because it is meaningful: handler priority and scheduler wiring both - read it, so a registration applied twice must produce the same application twice. + An already-built component was constructed at the caller's own source line, so it is in + the registry before ``build()`` runs, while a class or factory is constructed during the + replay. That difference is what ``AppBuilder._check_declaration_order`` inspects, and + what a group refuses outright. """ - return tuple(self._components) - - def with_handler(self, handler: type[HandlerT], *, name: str | None = None, **kwargs: Any) -> "AgentRegistration": - """Declare an event handler class.""" - return self._add("handler", handler, name, kwargs) + return isinstance(self.target, Component) - def with_service(self, service: type[ServiceT], *, name: str | None = None, **kwargs: Any) -> "AgentRegistration": - """Declare a business service class.""" - return self._add("service", service, name, kwargs) + def replay(self, builder: "AppBuilder") -> None: + """Re-issue this call on ``builder``, which records it again. - def with_agent(self, agent: type[AgentT] | Callable[[], AgentT], *, name: str | None = None, **kwargs: Any) -> "AgentRegistration": - """Declare an agent runtime, as a class or as a factory. + How a collector moves one agent's declarations onto the root builder that wires the + process. The namespace is *not* passed: the collector opens a + :func:`~blueprint.agents.component.namespace.namespace_scope` around the replay and + ``_record`` reads it from there, which is the same ambient mechanism a component uses + and the reason no namespace appears in any signature. - The factory form exists for the fluent builder: an ``AgentRuntime`` assembled by - ``AgentBuilder(...).with_model_from_config()...build()`` cannot be expressed as a class - plus keyword arguments. Wrapping that chain in a ``lambda`` defers it into - :meth:`apply`, so the model and prompt are resolved inside the agent's own namespace - rather than at import time:: - - AgentRegistration().with_agent(lambda: AgentBuilder(config, runtime_name="orders").build()) - """ - return self._add("agent", agent, name, kwargs) - - def with_scheduler( - self, scheduler: type[SchedulerT] | Callable[[], SchedulerT], *, name: str | None = None, **kwargs: Any - ) -> "AgentRegistration": - """Declare a scheduler class, or a factory returning one.""" - return self._add("scheduler", scheduler, name, kwargs) - - def with_rest_api(self, api: type[RestApiT] | Callable[[], RestApiT], *, name: str | None = None, **kwargs: Any) -> "AgentRegistration": - """Declare a REST API class, or a factory returning one. - - Pass the class, not an instance: ``with_rest_api(OrderApi)`` rather than - ``with_rest_api(OrderApi())``. The instance form is what an ``AppBuilder`` chain - accepts, and it is refused here because the object would already exist -- built at - import time, before any namespace, and therefore belonging to the root no matter which - agent declared it. Two grouped agents each declaring one would collide on its registry - name. Constructor arguments go here as keyword arguments; anything a plain call cannot - express goes in a ``lambda``. - """ - return self._add("rest_api", api, name, kwargs) - - def _add(self, kind: str, target: Any, name: str | None, kwargs: Mapping[str, Any]) -> "AgentRegistration": - """Store one declaration, rejecting anything already built.""" - if isinstance(target, Component): - raise TypeError( - f"{type(target).__name__} was passed to AgentRegistration.with_{kind}() as an instance, but a " - "registration declares components rather than holding them: this object was built before any " - "namespace existed, so it belongs to the root namespace whichever agent declared it, and two " - f"grouped agents declaring one would collide on its registry name. Pass the class -- " - f"with_{kind}({type(target).__name__}, ...) with its constructor arguments as keyword arguments -- " - "or a callable returning it." - ) - if not callable(target): - raise TypeError(f"AgentRegistration.with_{kind}() needs a component class or a callable returning one, got {target!r}.") - self._components.append(RegisteredComponent(kind=kind, target=target, name=name, kwargs=dict(kwargs))) - return self - - def apply(self, builder: "AppBuilder", namespace: str = ROOT_NAMESPACE) -> None: - """Build everything declared here on ``builder``, inside ``namespace``. - - Public rather than private because the caller is another class: ``AppBuilder`` for a - single agent today, the group entry point per agent later. - - Every component is constructed inside :func:`namespace_scope`, which is the whole - mechanism -- ``Component.__init__`` reads the ambient namespace, so no component and no - constructor signature mentions one. A factory is called here for the same reason. + The method is resolved by name with ``getattr`` rather than looked up in a table. A + table is a second place to edit and fails with a ``KeyError`` at replay time; a missing + attribute fails the same way but needs no maintenance, and the surfaces-agree test + pins that every recorded ``kind`` has a method to go back to. Args: - builder: The builder to register on. - namespace: The agent these components belong to. ``""`` is the root, which is what - a single-agent application uses. - - Raises: - ValueError: if ``namespace`` is not a legal namespace. - """ - appliers: dict[str, Callable[..., Any]] = { - "handler": builder.with_handler, - "service": builder.with_service, - "agent": builder.with_agent, - "scheduler": builder.with_scheduler, - "rest_api": builder.with_rest_api, - } - - with namespace_scope(namespace): - for entry in self._components: - # A class goes to the builder, which instantiates it -- still inside this scope. - # A factory has to be called here, because the builder would take the callable - # itself for an already-built component. - target = entry.target if isinstance(entry.target, type) else entry.target() - appliers[entry.kind](target, name=entry.name, **entry.kwargs) - - logger.debug( - "Applied %d component(s) to namespace '%s': %s", - len(self._components), - namespace or ROOT_LABEL, - ", ".join(f"{entry.kind}:{getattr(entry.target, '__name__', entry.target)}" for entry in self._components), - ) - - -class NamespaceBuilder: - """One agent's view of an :class:`AppBuilder`: every ``with_*`` call lands in its namespace. - - Returned by :meth:`AppBuilder.with_namespace` when no registration is passed, for the - indent-and-close style:: - - app = ( - AppBuilder(config) - .with_namespace("orders") - .with_service(OrderService) - .with_handler(OrderHandler) - .end() - .with_namespace("billing") - .with_service(BillingService) - .end() - .with_cache() - .build() - ) - - This form is for a group assembled by hand -- a test, or agents that are not packaged as - registrations. The primary form is - ``with_namespace("orders", registration=orders.registration)``, which needs no ``end()`` - because it returns the ``AppBuilder`` itself. - - Every method delegates to the parent builder with ``namespace=`` filled in, so registering a - component has one implementation and this class only decides which namespace it goes to. - - **There is no** ``with_cache``. A cache is process-wide and belongs to the ``AppBuilder`` - that hosts the group: an agent registering its own would either duplicate a neighbour's or - quietly take it over, which is the collision spec sec. 8 exists to prevent. Ask the registry - for a cache by name instead. - """ - - def __init__(self, builder: "AppBuilder", namespace: str) -> None: - """Bind a namespace to a builder. - - Args: - builder: The builder every call is forwarded to. - namespace: The agent this view registers into. - - Raises: - ValueError: if ``namespace`` is not a legal namespace. - """ - self._builder = builder - self._namespace = validate_namespace(namespace) - - @property - def namespace(self) -> str: - """The agent this view registers into.""" - return self._namespace - - def with_handler(self, handler: type[HandlerT] | HandlerT, *, name: str | None = None, **kwargs: Any) -> "NamespaceBuilder": - """Register an event handler in this namespace.""" - self._builder.with_handler(handler, name=name, namespace=self._namespace, **kwargs) - return self - - def with_service(self, service: type[ServiceT] | ServiceT, *, name: str | None = None, **kwargs: Any) -> "NamespaceBuilder": - """Register a business service in this namespace.""" - self._builder.with_service(service, name=name, namespace=self._namespace, **kwargs) - return self - - def with_agent(self, agent: type[AgentT] | AgentT, *, name: str | None = None, **kwargs: Any) -> "NamespaceBuilder": - """Register an agent runtime in this namespace.""" - self._builder.with_agent(agent, name=name, namespace=self._namespace, **kwargs) - return self - - def with_scheduler(self, scheduler: type[SchedulerT] | SchedulerT, *, name: str | None = None, **kwargs: Any) -> "NamespaceBuilder": - """Register a scheduler in this namespace.""" - self._builder.with_scheduler(scheduler, name=name, namespace=self._namespace, **kwargs) - return self - - def with_rest_api(self, api: type[RestApiT] | RestApiT, *, name: str | None = None, **kwargs: Any) -> "NamespaceBuilder": - """Register a REST API in this namespace.""" - self._builder.with_rest_api(api, name=name, namespace=self._namespace, **kwargs) - return self - - def with_registration(self, registration: AgentRegistration) -> "NamespaceBuilder": - """Apply a whole :class:`AgentRegistration` in this namespace. - - The same thing ``with_namespace(name, registration=...)`` does, reachable from inside an - indented block so a hand-assembled agent and a packaged one can be mixed. + builder: The builder to record this call on. """ - self._builder.with_registration(registration, self._namespace) - return self - - def end(self) -> "AppBuilder": - """Close the namespace block and return the parent builder. - - Nothing is "left" in any real sense: this object holds no build state and the components - are already registered. ``end()`` exists so the chain can continue with another - namespace or with ``build()``. - """ - return self._builder + if self.kind == "health_checker": + # The one irregular signature: with_health_checker(name, checker) takes its name + # positionally, where every other with_* takes it as a keyword override of a + # derived name. Left that way because it is published API; the irregularity is + # cheaper here, in one branch, than as a breaking change to the method. + builder.with_health_checker(self.name or "", self.target) + return + arguments = () if self.target is None else (self.target,) + getattr(builder, f"with_{self.kind}")(*arguments, name=self.name, **self.kwargs) class AppBuilder: @@ -329,19 +143,46 @@ class AppBuilder: .build() ) - Components are instantiated via with_*() calls (accepting either a class or - an instance) and auto-register themselves in the shared registry. AppBuilder - injects the Config in build() before the lifespan starts. + A ``with_*()`` call **records** what to build; nothing is constructed and nothing reaches + the registry until ``build()``. That is the property that lets one builder serve both a + standalone application and one agent of a group: a component constructed while a ``with_*`` + call is running would be built before any namespace existed and would belong to the root + whichever agent declared it. + + Two consequences worth knowing: + + - **A component cannot be looked up between ``with_*`` calls.** Resolve collaborators in + ``on_startup``, which is the framework's convention anyway. + - **An already-built instance is the exception**, because the caller constructed it at its + own source line. It is in the registry before ``build()`` runs, so an instance recorded + after a class registers before it -- see :meth:`_check_declaration_order`, which refuses + the one case where that changes behaviour. + + The configuration may be given here or to ``build()``, but not both. Given here it is + adopted immediately, which is what an existing ``AppBuilder(config)...build()`` chain does + and what keeps its ``with_*`` logging formatted as it always was. """ - def __init__(self, config: Config) -> None: - # Logging is configured here rather than in Config.__init__: it is the application's - # decision, not the configuration loader's, and one Config per namespace would - # otherwise reconfigure the root logger once per agent. This runs before any - # with_*() call, so component construction is already logged with the right format. - config.configure_logging() - self._config = config + def __init__(self, config: Config | None = None) -> None: + """Start a declaration. + + Args: + config: The application's configuration. Optional so that a declaration can be + written where no configuration is in scope -- a ``main.py`` that is only a + declaration, or an agent of a group, whose configuration belongs to the + process rather than to it. ``build()`` takes it instead. + """ + self._config: Config | None = None + if config is not None: + self._use_config(config) self._telemetry_manager = TelemetryManager() + # Every with_*() call, in call order. Order is preserved because it is meaningful: + # handler priority ties are resolved by registration order, and build() replays this + # list to reproduce it. + self._declarations: list[Declaration] = [] + # build() runs once. Tracked here so that a second call says so, rather than surfacing + # as Component.configure's "already set" from three frames down. + self._built = False # One transport endpoint per agent that consumes. A list rather than a single slot # because a group's agents each subscribe on their own behalf (spec sec. 7.6); it holds # exactly one element for every application that declares no namespace. @@ -352,245 +193,158 @@ def __init__(self, config: Config) -> None: # special case in _build_rest_endpoints. self._lifecycle_components: list[Component] = [] self._actuator_api: ActuatorApi | None = None + # Health checkers declared before build(), collected out of the declarations by the + # replay pass. A dict rather than a list because the readiness payload is keyed on the + # entry name, and a later declaration of the same name replaces an earlier one. + self._health_checkers: list[HealthCheckEntry] = [] # Which agents this process hosts. See the 'namespaces' property for why the # builder is the thing that keeps the list rather than the registry. self._namespaces: list[str] = [] # ------------------------------------------------------------------ - # Fluent registration API + # Configuration # ------------------------------------------------------------------ - def with_registration(self, registration: AgentRegistration, namespace: str = ROOT_NAMESPACE) -> "AppBuilder": - """Register everything an :class:`AgentRegistration` declares. + def _use_config(self, config: Config) -> Config: + """Adopt ``config`` as this application's configuration and configure logging from it. - This is what lets one declaration serve both deployment shapes. A project keeps its - components in an ``AgentRegistration``, and a single-agent ``main.py`` builds it here:: - - app = AppBuilder(config).with_registration(registration).with_cache().build() - - while a group applies the same object once per agent, under that agent's namespace. - Everything above that last line is the same file in both cases. - - Equivalent to the individual ``with_*`` calls, in declaration order, so it composes with - them and with ``with_cache``. + Logging is configured the moment a configuration arrives, whether that is in + ``__init__`` or in ``build()``. It is the application's decision rather than the + configuration loader's -- ``Config.__init__`` deliberately does not do it, because one + ``Config`` per namespace would reconfigure the root logger once per agent -- and doing + it here means an ``AppBuilder(config)`` chain still logs its own ``with_*`` calls with + the application's format, exactly as it did when construction happened there. Args: - registration: The declaration to build. - namespace: The agent these components belong to. Defaults to the root, which is the - whole of a single-agent application. - """ - registration.apply(self, namespace) - return self - - @overload - def with_namespace(self, name: str, *, registration: AgentRegistration) -> "AppBuilder": ... - - @overload - def with_namespace(self, name: str, *, registration: None = None) -> "NamespaceBuilder": ... - - def with_namespace(self, name: str, *, registration: AgentRegistration | None = None) -> "AppBuilder | NamespaceBuilder": - """Declare an agent hosted by this process, and register its components into it. - - Two forms, and which one you get depends on whether you hand over a registration:: + config: The configuration to adopt. - # primary: the agent is packaged, so the chain never leaves the AppBuilder - AppBuilder(config).with_namespace("orders", registration=orders.registration) - - # hand-assembled: an indented block, closed with end() - AppBuilder(config).with_namespace("billing").with_service(BillingService).end() - - The overloads above are what make that union tolerable at a call site: passing a - registration is statically an ``AppBuilder`` and omitting it is statically a - ``NamespaceBuilder``, so no caller has to narrow a union or assert its way out of one. + Returns: + The same configuration, so callers can chain. + """ + config.configure_logging() + self._config = config + return config - **There is no** ``config`` **parameter**, and spec sec. 4.2 lists one. It would have - nothing to do: configuration is already resolved per namespace from the one loaded tree - -- ``Component.config`` hands each component ``Config.for_namespace(its own namespace)``, - which tries ``.`` before ```` (C5). A second ``Config`` here would - either be ignored, or re-parse the same files once per agent and then be ignored anyway, - because a component reads the shared one rather than anything the builder holds. Nothing - would read it, so it is not accepted; see the changelog entry for this phase. + def _resolve_config(self, config: Config | None) -> Config: + """Settle which configuration ``build()`` uses, and adopt it if it is new. Args: - name: The agent's namespace. Must be a legal namespace and must not be the root. - registration: The agent's declaration, applied immediately in ``name``. Omit it to - get a :class:`NamespaceBuilder` and register components one at a time. + config: What was passed to ``build()``, or ``None``. Returns: - This builder when ``registration`` was given, otherwise a :class:`NamespaceBuilder` - for ``name``. + The configuration to build with: the one given here, the one given to + ``__init__``, or -- when neither exists -- one loaded from + :data:`~blueprint.agents.config.DEFAULT_SETTINGS_FILES`. Raises: - ValueError: if ``name`` is the root namespace or is not a legal namespace. + ValueError: if a configuration was given to both ``__init__`` and ``build()``. + Refused rather than resolved by precedence: the two are different objects with + different trees, half the application would already have been declared against + the first, and silently discarding one of them is the failure mode that a + per-agent override is hardest to debug through. """ - namespace = validate_namespace(name) - if not namespace: + if config is not None and self._config is not None: raise ValueError( - "with_namespace('') names no agent: '' is the root namespace, which is where the plain with_*() calls " - "already register. Pass the agent's name, or drop the with_namespace() call for a single-agent " - "application." + "A Config was passed to both AppBuilder(config) and build(config), and there is no rule for " + "choosing between them: they are separate trees, and whichever lost would take its log level, its " + "app_name and every agent override with it. Pass it in exactly one place -- AppBuilder(config) for " + "an application that has its configuration where it is declared, build(config) for one that does not." ) - - if namespace in self._namespaces: - raise ValueError( - f"Namespace '{namespace}' is already hosted by this process, so it cannot be declared again. Two " - "agents cannot share a name: the name is what identifies an agent in every log line, span, queue " - "group, durable and cache partition, so a second agent under it would be indistinguishable from the " - "first and their components would merge into one registry namespace. Give one of them a different " - "name, or -- if this is one agent assembled from several parts -- compose the parts into a single " - "AgentRegistration and apply that once." - ) - - # Recorded before anything is built, so that a registration failing half way through - # still leaves the namespace declared: the startup log and the readiness policy have to - # be able to say that an agent was meant to be here. - self._namespaces.append(namespace) - logger.info("Hosting agent namespace '%s'", namespace) - - if registration is None: - return NamespaceBuilder(self, namespace) - return self.with_registration(registration, namespace) + if config is not None: + return self._use_config(config) + if self._config is not None: + return self._config + return self._use_config(Config(settings_files=DEFAULT_SETTINGS_FILES)) @property - def namespaces(self) -> tuple[str, ...]: - """The agent namespaces declared on this builder, in declaration order. - - The builder keeps this list because nothing else may. ``Registry`` deliberately has no - ``get_known_namespaces()``: it is reachable from every component (C6), so an agent could - use it to enumerate the neighbours it shares a process with -- and grouping is supposed - to be invisible from inside. The builder is the object that was *told* which agents to - host, and it is not reachable from a component, so the list lives here. - - The root namespace is not in it: a single-agent application declares no namespace at all, - so an empty tuple means "root only" rather than "nothing registered". + def has_config(self) -> bool: + """Whether a configuration has been supplied yet. + + A boolean rather than the object: handing out the configuration would hand out the + *unscoped* loader, which config rework step 2b removed every path to. What a caller + legitimately needs to know is whether this builder brought its own -- which is what + :class:`~blueprint.agents.agent_group.AgentGroup` refuses, one process having one + settings tree. """ - return tuple(self._namespaces) - - @classmethod - def from_group(cls, config: Config, *, environ: dict[str, str] | None = None) -> "AppBuilder": - """Resolve this process's group and apply it, in one call. + return self._config is not None - The convenience form of the entry point's first two lines. Kept separate from - :meth:`with_group` because this one performs I/O -- it is ``GroupConfig.resolve`` that - reads the environment and the group file -- while ``with_group`` does not, and a test - that wants an exact composition needs the half that does not. + @property + def is_built(self) -> bool: + """Whether ``build()`` has already run. - Args: - config: The application's configuration. - environ: The environment to resolve from, for tests. + Read by a collector, which cannot place an application that already exists: its + components are constructed and belong to the root namespace, and ``build()`` has + already injected the configuration process-wide. + """ + return self._built - Returns: - A builder with every agent in the group applied. + def _require_config(self) -> Config: + """Return the configuration, which exists only from ``build()`` onwards. Raises: - GroupConfigError: if the group cannot be resolved. See ``GroupConfig.resolve``. + RuntimeError: if called before ``build()`` has settled which configuration to use. + Internal: every caller runs during or after the wiring pass. """ - return cls(config).with_group(GroupConfig.resolve(config, environ=environ)) + if self._config is None: + raise RuntimeError("The application's configuration is not settled until build() runs.") + return self._config - def with_group(self, group: GroupConfig) -> "AppBuilder": - """Apply every agent in ``group``, and register the caches the group declares. + # ------------------------------------------------------------------ + # Fluent registration API + # ------------------------------------------------------------------ - **Performs no I/O of its own**, which is what keeps this class a pure function of its - call sequence: no environment reads, no file reads, no ``sys.exit``, and no knowledge of - an agent repo's layout. Those belong to ``GroupConfig.resolve`` and to the entry point, - so a test can state an exact composition by constructing a ``GroupConfig`` literally. + def host_agent(self, namespace: str) -> "AppBuilder": + """Record that this process serves ``namespace``, whether or not it declares anything. - Importing an agent's module is the one thing here that reaches outside, and it is - deliberately on this side of the line: it is driven entirely by the ``module`` strings - the group carries, so a test points them at test modules and controls neither the - environment nor the filesystem to do it. Imports happen **per group**, so cold start is - proportional to the number of agents this process actually hosts rather than to the - number the image contains. + Not a ``with_*``: it declares no component. It states a fact about the *process*, and + ``build()`` needs that fact because two of the things it does are per agent rather than + per component -- it wires one transport for each hosted agent, and it asks each agent's + own configuration whether that agent publishes. Neither can be derived from the + declarations, since an agent may declare no component and still have opted into + publishing. - A critical agent that cannot be loaded raises, which the entry point turns into a - non-zero exit before the port is bound. A non-critical one is skipped with an ERROR: - that flag is the deployment saying it would rather run the rest (spec sec. 9.1). The - flag is read *before* the agent is wired rather than after an exception, because there - is no partial build to unwind -- one process, one ``build()``. + Called by :class:`~blueprint.agents.agent_group.AgentGroup`, which is the object that + was *told* the composition. The builder is not: it is handed the list, and it never + learns that another builder exists. Args: - group: The resolved group. + namespace: The agent's name. Returns: This builder. Raises: - GroupConfigError: if a critical agent's module or registration cannot be loaded. + ValueError: if ``namespace`` is not a legal namespace, is the root, or is already + hosted by this process. """ - logger.info( - "Applying group '%s': %d agent(s), %d declared cache(s)", - group.name, - len(group.agents), - len(group.cache_names), - ) - - for spec in group.agents: - registration = self._load_registration(spec) - if registration is None: - continue - self.with_namespace(spec.name, registration=registration) - - for cache_name in group.cache_names: - self.with_cache(name=cache_name) - - return self - - @staticmethod - def _load_registration(spec: AgentSpec) -> AgentRegistration | None: - """Import an agent's declaration, or report why it could not be loaded. - - Returns: - The registration, or ``None`` when a non-critical agent could not be loaded and is - to be skipped. - - Raises: - GroupConfigError: if a critical agent cannot be loaded. The message names the agent - and the module path it came from, because the two are declared in different - files -- the agent name in the group file or an environment variable, the module - in the image's agent map -- and which of them is wrong is the first thing to - establish. - """ - module_path, _, attribute = spec.module.partition(":") - if not module_path or not attribute: - return AppBuilder._skip_or_raise( - spec, - f"'{spec.module}' is not a valid declaration path. Write it as 'package.module:attribute', naming the " - "AgentRegistration the module assigns.", + agent = validate_namespace(namespace) + if not agent: + raise ValueError("host_agent('') names no agent: '' is the root namespace, which every application already serves.") + if agent in self._namespaces: + raise ValueError( + f"Namespace '{agent}' is already hosted by this process, so it cannot be declared again. Two " + "agents cannot share a name: the name is what identifies an agent in every log line, span, queue " + "group, durable and cache partition, so a second agent under it would be indistinguishable from " + "the first and their components would merge into one registry namespace." ) + self._namespaces.append(agent) + logger.info("Hosting agent namespace '%s'", agent) + return self - try: - module = importlib.import_module(module_path) - except Exception as exc: - # Every exception, not only ImportError: importing a module runs it, so anything its - # top level does can fail here, and an agent whose declaration raises on import is - # exactly as unloadable as one whose module is absent. - return AppBuilder._skip_or_raise(spec, f"importing '{module_path}' raised {type(exc).__name__}: {exc}", exc) - - registration = getattr(module, attribute, None) - if registration is None: - return AppBuilder._skip_or_raise( - spec, f"module '{module_path}' has no attribute '{attribute}', so its declaration cannot be read." - ) - if not isinstance(registration, AgentRegistration): - return AppBuilder._skip_or_raise( - spec, - f"'{spec.module}' is a {type(registration).__name__}, not an AgentRegistration. An agent's " - "declaration is the object its components are declared on.", - ) - logger.debug("Loaded the declaration for agent '%s' from '%s'", spec.name, spec.module) - return registration + @property + def namespaces(self) -> tuple[str, ...]: + """The agent namespaces declared on this builder, in declaration order. - @staticmethod - def _skip_or_raise(spec: AgentSpec, reason: str, cause: BaseException | None = None) -> None: - """Raise for a critical agent, or log and skip a non-critical one. + The builder keeps this list because nothing else may. ``Registry`` deliberately has no + ``get_known_namespaces()``: it is reachable from every component (C6), so an agent could + use it to enumerate the neighbours it shares a process with -- and grouping is supposed + to be invisible from inside. The builder is *told* the composition, by + :meth:`host_agent`, and it is not reachable from a component, so the list lives here. - Raises: - GroupConfigError: when ``spec`` is critical. + The root namespace is not in it: a single-agent application declares no namespace at all, + so an empty tuple means "root only" rather than "nothing registered". """ - if spec.critical: - raise GroupConfigError(f"Agent '{spec.name}' could not be loaded and is critical: {reason}") from cause - logger.error("Agent '%s' could not be loaded and is not critical, so it is skipped: %s", spec.name, reason) - return None + return tuple(self._namespaces) @property def hosted_namespaces(self) -> tuple[str, ...]: @@ -602,112 +356,221 @@ def hosted_namespaces(self) -> tuple[str, ...]: pass over this list simply creates nothing -- the per-agent gates decide that, not this list. - Distinct from :attr:`namespaces`, which is only what ``with_namespace`` was told. That + Distinct from :attr:`namespaces`, which is only what :meth:`host_agent` was told. That one answers "which agents was this builder asked to host"; this one answers "which namespaces does ``build()`` have to iterate", and those differ by exactly the root. """ return (ROOT_NAMESPACE, *self._namespaces) def with_handler( - self, handler: type[HandlerT] | HandlerT, *, name: str | None = None, namespace: str = ROOT_NAMESPACE, **kwargs: Any + self, handler: type[HandlerT] | HandlerT | Callable[[], HandlerT], *, name: str | None = None, **kwargs: Any ) -> "AppBuilder": - """Register an event handler class or instance. + """Declare an event handler class, factory or instance. + + Recorded, not built: the handler is constructed by ``build()``. + + **In a group:** prefer the class or factory form -- an already-built instance is refused + at assembly, because its namespace and registry key were fixed where it was constructed + (see :class:`~blueprint.agents.agent_group.AgentGroup`). This agent gets its own + ``HandlerChain`` and its own broker subscription, so it is never offered a neighbour's + events, and ``idempotency_enabled`` needs a cache **this** agent declared: a cache is + private to the agent that declared it (:meth:`with_cache`). Args: - handler: The handler class to build, or an already-built instance. - name: Registry name override, qualified with the namespace like a derived one. - namespace: The agent this handler belongs to. ``""`` keeps whatever namespace is - already in force, which is what lets a registration applied per agent land in - the right one. - **kwargs: Constructor arguments, forwarded when a class is passed. + handler: The handler class to build, a zero-argument callable returning one, or an + already-built instance. + name: Registry name override, qualified with the agent's namespace like a derived + one. + **kwargs: Constructor arguments, forwarded when a class or factory is passed. """ if isinstance(handler, type) and not issubclass(handler, EventHandlerBase): raise TypeError(f"Expected EventHandlerBase subclass, got {handler.__name__}") - self._register(handler, namespace, kwargs, name=name, method="with_handler") - return self + return self._record("handler", handler, kwargs, name=name, method="with_handler") def with_service( - self, service: type[ServiceT] | ServiceT, *, name: str | None = None, namespace: str = ROOT_NAMESPACE, **kwargs: Any + self, service: type[ServiceT] | ServiceT | Callable[[], ServiceT], *, name: str | None = None, **kwargs: Any ) -> "AppBuilder": - """Register a business service class or instance. See :meth:`with_handler` for the arguments.""" - self._register(service, namespace, kwargs, name=name, method="with_service") - return self + """Declare a business service. See :meth:`with_handler` for the arguments. + + **In a group:** nothing about a service changes except its registry name, which is + qualified with the agent (``orders_order_service``), and what it resolves -- + ``self.registry`` and ``self.config`` answer for its own agent. An already-built + instance is refused at assembly, as for every other declaration. + """ + return self._record("service", service, kwargs, name=name, method="with_service") def with_agent( - self, agent: type[AgentT] | AgentT, *, name: str | None = None, namespace: str = ROOT_NAMESPACE, **kwargs: Any + self, agent: type[AgentT] | AgentT | AgentBuilder | Callable[[], AgentT], *, name: str | None = None, **kwargs: Any ) -> "AppBuilder": - """Register an agent runtime class or instance. See :meth:`with_handler` for the arguments.""" - self._register(agent, namespace, kwargs, name=name, method="with_agent") - return self + """Declare an agent runtime, as a class, an unbuilt ``AgentBuilder``, a factory or an instance. + + The ``AgentBuilder`` form is the one that works in a group. ``build()`` calls + ``agent.build(config.for_namespace(...))``, so the model, prompt and metrics are + resolved from *this agent's* configuration view rather than from whatever was in + scope where the chain was written:: + + AppBuilder().with_agent(AgentBuilder(runtime_name="orders").with_model_from_config()) + + **In a group:** the class and factory forms work too and are built inside this agent's + scope like anything else; what they do *not* get is the scoped configuration view, so a + runtime that reads its own model from configuration wants the ``AgentBuilder`` form. An + already-built ``AgentRuntime`` instance is refused at assembly. + + See :meth:`with_handler` for the arguments. + """ + return self._record("agent", agent, kwargs, name=name, method="with_agent") def with_scheduler( - self, scheduler: type[SchedulerT] | SchedulerT, *, name: str | None = None, namespace: str = ROOT_NAMESPACE, **kwargs: Any + self, scheduler: type[SchedulerT] | SchedulerT | Callable[[], SchedulerT], *, name: str | None = None, **kwargs: Any ) -> "AppBuilder": - """Register a scheduler class or instance. See :meth:`with_handler` for the arguments.""" - self._register(scheduler, namespace, kwargs, name=name, method="with_scheduler") - return self + """Declare a scheduler. See :meth:`with_handler` for the arguments. + + **In a group:** ``scheduler_mode`` is read through this agent's own configuration view, + so one agent may run an in-process timer beside a neighbour driven by external ticks. + Both modes need something of this agent's own -- ``"in_process"`` claims each tick in a + cache **this** agent declared (:meth:`with_cache`), and ``"event"`` needs ``event_bus``, + which is the group's to set. The scheduler's own REST routes move under + ``/api/`` with every other route of this agent. + """ + return self._record("scheduler", scheduler, kwargs, name=name, method="with_scheduler") def with_rest_api( - self, api: type[RestApiT] | RestApiT, *, name: str | None = None, namespace: str = ROOT_NAMESPACE, **kwargs: Any + self, api: type[RestApiT] | RestApiT | Callable[[], RestApiT], *, name: str | None = None, **kwargs: Any ) -> "AppBuilder": - """Register a custom REST API class or instance. See :meth:`with_handler` for the arguments.""" - self._register(api, namespace, kwargs, name=name, method="with_rest_api") + """Declare a custom REST API. See :meth:`with_handler` for the arguments. + + **In a group:** the routes move. A root component keeps the paths it always served + under ``/api``; a component belonging to an agent serves them under ``/api/``, + and its OpenAPI tags are prefixed with the agent, so two agents that declare the same + path do not collide and each agent's operations group together in Swagger UI. Nothing in + the component changes -- the prefix comes from ``RestApiBase.route_prefix``, which the + namespace decides -- but a client of a grouped agent addresses the prefixed path. + """ + return self._record("rest_api", api, kwargs, name=name, method="with_rest_api") + + @property + def declarations(self) -> tuple[Declaration, ...]: + """Everything recorded on this builder, in call order. + + The declaration is the builder's product until ``build()`` turns it into an + application. Exposed because a collector assembling a group replays these itself + instead of calling ``build()``, and because a test can assert what a ``main.py`` + declares without constructing any of it. + """ + return tuple(self._declarations) + + def _record(self, kind: str, target: Any, kwargs: Mapping[str, Any], *, name: str | None, method: str) -> "AppBuilder": + """Store one ``with_*`` call, settling the namespace it belongs to now rather than later. + + **There is no namespace argument, and that is the point.** A declaration takes the + namespace in force where it is written -- the root for a standalone application, and + the agent's own for a declaration a group is replaying inside + :func:`namespace_scope`. So nothing a developer writes mentions a namespace, and the + same file serves both deployment shapes unchanged. + + Settled here rather than at construction because *here* is where the caller's context + exists; by the time the replay pass runs no scope is in force. + + One check stays at record time: an already-built instance offered while another + agent's scope is open. It is answerable now, because the instance exists and + ``namespace_of`` can be asked, and the offending line is where to report it. + + Args: + kind: Which ``with_*`` this is, and therefore how ``build()`` replays it. + target: A component class, a zero-argument factory, or a built component. + kwargs: Constructor arguments. + name: Registry name override, or ``None``. + method: The builder method being called, for the error message. + + Returns: + This builder. + + Raises: + TypeError: if ``target`` is neither a component nor callable, or if a ``namespace`` + keyword is passed -- which was a parameter until this phase. + ValueError: if a built instance is declared under a namespace other than its own. + """ + if "namespace" in kwargs: + # It was a real parameter until this phase, and dropping it would have left it + # falling through to the component's constructor: ServiceBase and friends accept + # one, so the call would keep working while meaning something else. Refused rather + # than silently reinterpreted. + raise TypeError( + f"{method}() does not take a namespace. A declaration takes the namespace in force where it is " + "written -- the root for a standalone application, the agent's own inside a group -- so nothing a " + f"developer writes names one. Remove namespace={kwargs['namespace']!r}; left in place it would be " + "forwarded to the component's constructor, which is not what it used to mean." + ) + + namespace = current_namespace() + if isinstance(target, Component): + built_in = namespace_of(target) + if namespace and built_in != namespace: + raise ValueError( + f"{type(target).__name__} was passed to {method}() as an instance while namespace '{namespace}' " + f"was in force, but it was already built in namespace '{built_in or ROOT_LABEL}', and a component " + "cannot change namespace afterwards: both its namespace and its registry key are fixed at " + f"construction. Pass the class instead -- {method}({type(target).__name__}, ...) -- so that it is " + "built where it is declared." + ) + elif isinstance(target, AgentBuilder): + if kind != "agent": + raise TypeError( + f"An AgentBuilder was passed to {method}(), which declares a {kind}. An AgentBuilder produces an " + "AgentRuntime, so it belongs in with_agent()." + ) + elif not callable(target): + raise TypeError(f"{method}() needs a component class, a callable returning one, or a built component, got {target!r}.") + + self._declarations.append(Declaration(kind=kind, target=target, name=name, namespace=namespace, kwargs=dict(kwargs))) return self - @staticmethod - def _register(target: Any, namespace: str, kwargs: Mapping[str, Any], *, name: str | None, method: str) -> Any: - """Build ``target`` inside ``namespace`` -- or adopt it if it is already built -- and name it. + def _construct(self, declaration: Declaration, config: Config) -> Any: + """Build one declaration inside its namespace -- or adopt it if it is already built. Registration itself does not happen here: ``Component.__init__`` adds the instance to - the registry, so the only two things left are *which namespace it is constructed in* and - *what it is called*. + the registry, so the only two things left are *which namespace it is constructed in* + and *what it is called*. - **The namespace is never handed to** ``target``. A project's component takes the + **The namespace is never handed to the component.** A project's component takes the constructor arguments its author wrote and nothing else, so the namespace travels through the ambient scope and is read by ``Component.__init__``. That is why ``with_service(OrderService, namespace="orders")`` does not become ``OrderService(namespace="orders")`` and does not require ``OrderService`` to know what a namespace is -- which is the whole point of the ambient mechanism. - An already-built instance cannot be moved into a namespace: its namespace, and its - registry key with it, were fixed by the scope it was constructed in. A mismatch is - refused rather than ignored, because ignoring it registers the component at the root - while the caller believes it belongs to an agent. + A class and a factory are treated identically, because a class *is* a zero-argument + factory once its keyword arguments are applied. That is what lets a fluent chain be + deferred as far as a class is. + + An unbuilt ``AgentBuilder`` is the third case, and it is the only one handed a + configuration: ``AgentBuilder.build`` takes one, and what it must be given is the view + scoped to *this* agent (C5), so the model, prompt and metrics of a grouped agent are + read from its own section rather than from the root or from a neighbour's. That is the + whole of D6, and it is why this method takes ``config`` at all. Args: - target: A component class to build, or a built component to adopt. - namespace: The agent to build inside; ``""`` keeps the ambient namespace. - kwargs: Constructor arguments, used only when ``target`` is a class. - name: Registry name override, or ``None`` to keep the derived name. - method: The builder method being called, for the error message. + declaration: The recorded call to replay. + config: The application's configuration, scoped per declaration as needed. Returns: The component instance, already in the registry. - - Raises: - ValueError: if a built instance is offered to a namespace other than its own. """ - if isinstance(target, type): - with _construction_scope(namespace): - instance = target(**kwargs) + if declaration.is_built: + instance = declaration.target + elif isinstance(declaration.target, AgentBuilder): + with construction_scope(declaration.namespace): + instance = declaration.target.build(config.for_namespace(declaration.namespace), **declaration.kwargs) else: - built_in = namespace_of(target) - if namespace and built_in != namespace: - raise ValueError( - f"{type(target).__name__} was passed to {method}() as an instance for namespace '{namespace}', " - f"but it was already built in namespace '{built_in or ROOT_LABEL}', and a component cannot change " - "namespace afterwards: both its namespace and its registry key are fixed at construction. Pass " - f"the class instead -- {method}({type(target).__name__}, namespace='{namespace}', ...) -- so that " - "it is built inside that namespace." - ) - instance = target + with construction_scope(declaration.namespace): + instance = declaration.target(**declaration.kwargs) - if name is not None: + if declaration.name is not None: # Assigned bare: the setter qualifies it with the component's own namespace, which is # the single place that rule lives now. One registration applied to two agents # therefore registers 'orders_db' and 'billing_db' rather than colliding on 'db', # and either stays findable by the bare name because Registry._lookup qualifies too. - instance.name = name + instance.name = declaration.name return instance def with_cache(self, enabled: bool = True, enable_locking: bool = True, *, name: str = DEFAULT_CACHE_NAME) -> "AppBuilder": @@ -721,12 +584,24 @@ def with_cache(self, enabled: bool = True, enable_locking: bool = True, *, name: any component reads one back with ``self.registry.get_cache("sessions")``. There is deliberately no fallback from an unknown name to the default (spec sec. 8). + **In a group:** a cache belongs to the agent that declared it and to no other (spec + sec. 8). Two agents may both declare ``sessions`` and get separate stores -- separate + directories on disk, separate key prefixes on Redis -- and ``get_cache("sessions")`` + resolves within the declaring agent with no fallback to a neighbour's or to the root's. + The backend is chosen from this agent's own configuration, so one agent can run on + Redis beside a neighbour on disk, and ``/cache/*`` is served per agent under + ``/api/``. + ``name`` is **keyword-only and comes last**, which is a constraint rather than a style choice. ``with_cache(False)`` disables caching today; had ``name`` been the first parameter that call would have become a cache named ``False`` with caching silently switched *on*, with no ``TypeError`` to notice. So ``with_cache()``, ``with_cache(False)`` and ``with_cache(True, False)`` all still mean what they meant. + Recorded like every other ``with_*`` call and created by ``build()``, which is also + what lets it be declared before any configuration exists: the backend is chosen from + ``get_cache_config()``, and that configuration may not arrive until ``build(config)``. + Args: enabled: Whether to create the cache at all. ``False`` registers nothing. enable_locking: File-based locking for multi-process safety, for the disk backend. @@ -740,50 +615,235 @@ def with_cache(self, enabled: bool = True, enable_locking: bool = True, *, name: logger.info("Caching disabled; cache '%s' is not registered", name) return self - # The name goes to the factory rather than being resolved here: which store a name - # maps to is backend knowledge, and the factory is where a backend is chosen and where - # a new one would be added. - cache_service = CacheBackendFactory.create(self._config.get_cache_config(), enable_locking=enable_locking, name=name) - # Read after the service is built, never before: a cache service is itself a Component, - # and Component.__init__ is what creates the shared registry on first use. Capturing it - # first is an AttributeError on None for an application whose first builder call is - # with_cache(). - registry: Registry = Component.shared_registry # type: ignore[assignment] - registry.add_cache(name, cache_service) - logger.info("Registered cache '%s' as %s (locking=%s)", name, type(cache_service).__name__, enable_locking) + # Validated now, not at replay: the name becomes a directory segment and a Redis key + # prefix, so it crosses the process boundary, and the call that wrote it is where the + # mistake is. The factory validates again when it creates the backend -- it is the + # rule's owner, and nothing reaches it only through here. + CacheBackendFactory.validate_name(name) + self._declarations.append( + Declaration( + kind="cache", + target=None, + name=name, + namespace=current_namespace(), + kwargs={"enable_locking": enable_locking}, + ) + ) return self + def _create_cache(self, declaration: Declaration, config: Config) -> None: + """Create one declared cache and register it to the agent that declared it. + + Three things are per agent here, and each of them is what makes a cache private to the + agent that declared it (spec sec. 8, D3): + + - **The backend is chosen from the agent's own configuration view**, so one agent in a + group can run on redis while its neighbour uses the disk. + - **The store is isolated by the agent as well as the name**, which + ``CacheBackendFactory`` does from the namespace it is handed -- two agents declaring + ``sessions`` get separate directories or separate key prefixes, not one shared store. + - **The registry entry is keyed on the agent**, so ``get_cache("sessions")`` reaches + this agent's and can never reach a neighbour's. + + The backend is constructed inside the agent's construction scope -- entered by the + factory, from the namespace it is handed -- because a cache backend is itself a + ``Component``: without it two agents' caches would both derive ``disk_cache_service`` + and collide on that one registry name. + + Args: + declaration: A ``kind="cache"`` declaration; its ``name`` is the cache's name. + config: The application's configuration, scoped to the declaring agent here. + """ + name = declaration.name or DEFAULT_CACHE_NAME + namespace = declaration.namespace + enable_locking = bool(declaration.kwargs["enable_locking"]) + # The name and the namespace go to the factory rather than being resolved here: which + # store they map to is backend knowledge, and the factory is where a backend is chosen + # and where a new one would be added. + cache_service = CacheBackendFactory.create( + config.for_namespace(namespace).get_cache_config(), + enable_locking=enable_locking, + name=name, + namespace=namespace, + ) + registry: Registry = Component.shared_registry # type: ignore[assignment] + registry.add_cache(name, cache_service, namespace=namespace) + logger.info( + "Registered cache '%s' for agent '%s' as %s (locking=%s)", + name, + namespace or ROOT_LABEL, + type(cache_service).__name__, + enable_locking, + ) + def with_health_checker(self, name: str, checker: "HealthCheckerBase") -> "AppBuilder": - """Register a custom health checker on the ActuatorApi. + """Declare a custom health checker for the readiness probe. + + Recorded like every other declaration, and flushed into the ``ActuatorApi`` by + ``build()``. Recording it is what lets a group carry an agent's checkers over with the + rest of its declaration instead of silently dropping them. - Must be called after build() has created the ActuatorApi, or the checker - will be added during build() automatically. Prefer calling before build(). + A checker is not a ``Component``, so it is never constructed here: the object passed + is the object used, whichever namespace it was created in. + + **In a group:** the *agent* it belongs to is the one in force where this call is + written, and it travels with the checker as data -- so two agents may both declare + ``"db"`` and appear as ``orders.db`` and ``billing.db`` instead of one of them vanishing + into the other's dict slot. Two checks that would still share one entry are refused + rather than silently reduced to one. The readiness *policy* is unchanged: every check is + ANDed, so one agent's failing check takes the whole pod out of rotation. + + Args: + name: What this checker is called within its agent. It appears in the readiness + payload under that name at the root, and under ``.`` in a group. + checker: The checker. + + Note: + Calling this *after* ``build()`` adds the checker straight to the live + ``ActuatorApi``, because by then the declarations have already been replayed and + recording it would do nothing. """ if self._actuator_api is not None: - self._actuator_api.add_health_providers({name: checker}) - else: - # Stored temporarily; flushed into ActuatorApi during build() - if not hasattr(self, "_custom_health_checkers"): - self._custom_health_checkers: dict[str, HealthCheckerBase] = {} - self._custom_health_checkers[name] = checker + self._actuator_api.add_health_providers([HealthCheckEntry(name=name, namespace=current_namespace(), checker=checker)]) + return self + self._declarations.append(Declaration(kind="health_checker", target=checker, name=name, namespace=current_namespace(), kwargs={})) return self # ------------------------------------------------------------------ # Build # ------------------------------------------------------------------ - def build(self) -> FastAPI: - """Create and configure the FastAPI application. + def _construct_declarations(self, config: Config) -> None: + """Replay every recorded declaration, in the order it was recorded. + + This is the whole of what deferred wiring costs: one pass, in call order, each entry + constructed inside the namespace it was recorded with. Components register themselves + from ``Component.__init__``, so after this pass the registry holds exactly what the + ``with_*`` calls used to put there directly. + + Caches come last, after every component. They are created through + ``CacheBackendFactory`` rather than by a constructor, and nothing about a cache depends + on a component or the other way round -- but a cache backend is itself a ``Component``, + so building it in the middle of the pass would interleave it into the registry's + insertion order and shift the components declared after it. + + Health checkers are constructed by nobody: a checker is not a ``Component``, so the + pass only collects them for ``build()`` to hand to the actuator. + + Args: + config: The application's configuration, handed to the declarations that take one. + + Raises: + ValueError: if the recorded order cannot be reproduced. See + :meth:`_check_declaration_order`. + """ + built: list[tuple[Declaration, Any]] = [] + for entry in self._declarations: + if entry.kind not in _UNCONSTRUCTED_KINDS: + built.append((entry, self._construct(entry, config))) + + # After construction, not before: a class's priority is a property of the object, and + # asking the class for it means reading a default argument and being wrong about every + # handler that computes one. The application is not returned when this raises, so the + # components already in the registry go nowhere. + self._check_declaration_order(built) + + for entry in self._declarations: + if entry.kind == "cache": + self._create_cache(entry, config) + elif entry.kind == "health_checker": + self._health_checkers.append(HealthCheckEntry(name=entry.name or "", namespace=entry.namespace, checker=entry.target)) + + logger.debug("Constructed %d declaration(s)", len(self._declarations)) + + @staticmethod + def _check_declaration_order(built: list[tuple[Declaration, Any]]) -> None: + """Refuse a declaration order that construction cannot reproduce. + + An already-built instance is constructed by the caller at its own source line, so it is + in the registry before ``build()`` runs; a class or a factory is constructed during the + replay. So an instance recorded *after* a class registers *before* it, and registration + order is not decoration: ``DispatchIndex.build`` resolves handler priority ties by it, + which a project may well be relying on without having said so. + + Only handlers, only within one agent, and only at equal priority, because that is the + only case where the order decides anything. Different priorities sort deterministically + whichever way round the two were registered, two agents never share a chain, and + nothing else the registry holds is order sensitive. + + Detected rather than repaired: the fix is one keyword away -- pass the class -- and + reordering the registry behind the caller's back would make the file say one thing and + the application do another. + + Args: + built: Each non-cache declaration paired with the component it produced, in + declaration order. + + Raises: + ValueError: if a handler instance was recorded after a handler class or factory of + the same priority in the same namespace. + """ + handlers = [ + (position, entry, component) for position, (entry, component) in enumerate(built) if isinstance(component, EventHandlerBase) + ] + + for position, entry, component in handlers: + if entry.is_built: + continue + for later_position, later, later_component in handlers: + if later_position <= position or not later.is_built: + continue + if later.namespace != entry.namespace or later_component.priority != component.priority: + continue + raise ValueError( + f"{type(later_component).__name__} was passed to with_handler() as an instance after " + f"{type(component).__name__} was declared as a class, and both have priority " + f"{component.priority}. An instance is built where it is written and a class is built by " + "build(), so the instance registers first and is tried first -- the reverse of what this file " + f"says. Pass {type(later_component).__name__} as a class as well, so that both are built in " + "declaration order, or give one of them a different priority so the order stops depending on " + "registration at all." + ) + + def build(self, config: Config | None = None) -> FastAPI: + """Construct everything declared, wire it, and return the FastAPI application. This method: + 0. Settles the configuration and constructs every recorded declaration 1. Injects Config into the Component class hierarchy 2. Wires each registered scheduler for its scheduler_mode 3. Creates the IO client, and the eventing endpoint only if something consumes 4. Wires health checkers from all registered clients 5. Returns a FastAPI app with lifespan management + + Args: + config: The application's configuration, for a builder that was constructed + without one. Omit it when ``AppBuilder(config)`` already has it. + + Returns: + The application. + + Raises: + ValueError: if a configuration was given twice, or if the recorded order cannot be + reproduced (see :meth:`_check_declaration_order`). + RuntimeError: if this builder has already been built. """ - # 1. Inject config — enforced once-only by metaclass guard - Component.configure(self._config) + if self._built: + raise RuntimeError( + "This AppBuilder has already been built, and a builder produces one application: build() injects " + "the configuration into the Component hierarchy and constructs every declaration, both of which are " + "once-per-process. Declare a new AppBuilder for a second application -- and note that the " + "components of the first are still in the process-wide registry, so a test doing this wants " + "Component.reset_shared_state() between cases." + ) + self._built = True + resolved_config = self._resolve_config(config) + + # 0. Inject config first, then construct. Nothing was built while the with_*() calls + # ran, so this is the first moment any component exists -- and every one of them is + # created with the configuration already in place, rather than the other way round. + Component.configure(resolved_config) + self._construct_declarations(resolved_config) registry: Registry = Component.shared_registry # type: ignore[assignment] @@ -806,7 +866,7 @@ def build(self) -> FastAPI: # per process -- 'event_bus' is read from the root config, and mixing NATS with Dapr # is out of scope for this plan -- but which agents get a client, and which of them # get an endpoint, is decided per agent below. - event_bus_type = str(self._config.get("event_bus", "") or "").strip().lower() + event_bus_type = str(resolved_config.get("event_bus", "") or "").strip().lower() for namespace in self.hosted_namespaces: self._wire_transport(registry, namespace, event_bus_type) self._wire_dapr_endpoint(registry, event_bus_type) @@ -828,26 +888,34 @@ def build(self) -> FastAPI: # 5. Create ActuatorApi and wire health checkers from all registered clients self._actuator_api = ActuatorApi() - health_providers: dict[str, HealthCheckerBase] = {client.name: ClientHealthChecker([client]) for client in registry.get_clients()} + # The client's *base* name, not its registry name: the registry name is already + # qualified with '_' ('orders_nats_client'), and the entry composes its own rendering, + # so passing the registry name would read 'orders.orders_nats_client'. A root client's + # base name is its registry name, so an existing payload key does not move. + health_providers: list[HealthCheckEntry] = [ + HealthCheckEntry(name=client.base_name, namespace=client.namespace, checker=ClientHealthChecker([client])) + for client in registry.get_clients() + ] # Pull every registered cache into the readiness probe so a Redis outage takes the pod # out of service rotation instead of letting it silently serve cache misses. Every # cache, not just the default one: a named cache is a real backend with a real # connection, and one that only the default cache was probed would be an unreachable # Redis nobody was told about. The default keeps the entry name 'cache' it has always # had, so an existing /readiness payload is unchanged. - for cache_name, cache in registry.get_all_caches().items(): - entry = "cache" if cache_name == DEFAULT_CACHE_NAME else f"cache:{cache_name}" - health_providers[entry] = CacheHealthChecker(cache) - if hasattr(self, "_custom_health_checkers"): - health_providers.update(self._custom_health_checkers) + for namespace, cache_name, cache in registry.cache_entries(): + name = "cache" if cache_name == DEFAULT_CACHE_NAME else f"cache:{cache_name}" + # The agent is carried on the entry, so two agents' default caches are two entries + # rather than one that silently reports whichever was registered last. + health_providers.append(HealthCheckEntry(name=name, namespace=namespace, checker=CacheHealthChecker(cache))) + health_providers.extend(self._health_checkers) if health_providers: self._actuator_api.add_health_providers(health_providers) # 6. Build FastAPI app app = FastAPI( - title=self._config.get("app_name", "blueprint-service"), - description=self._config.get("app_description", ""), - version=self._config.get("app_version", "0.0.0"), + title=resolved_config.get("app_name", "blueprint-service"), + description=resolved_config.get("app_description", ""), + version=resolved_config.get("app_version", "0.0.0"), lifespan=self._create_lifespan_manager(), docs_url="/docs", redoc_url="/redoc", @@ -964,7 +1032,7 @@ def _publishing_requested(self, namespace: str = ROOT_NAMESPACE) -> bool: Raises: ValueError: if the key holds a non-empty value that is not a boolean. """ - raw = self._config.for_namespace(namespace).get("event_publishing_enabled", False) + raw = self._require_config().for_namespace(namespace).get("event_publishing_enabled", False) if raw is None or (isinstance(raw, str) and not raw.strip()): return False return parse_bool(raw, "event_publishing_enabled") @@ -984,8 +1052,14 @@ def _build_rest_endpoints(self, app: FastAPI, registry: Registry) -> None: for eventing_component in self._eventing_components: self._mount(app, eventing_component, root_prefix="") - if registry.has_cache(): - app.include_router(CacheManagementApi().router, prefix="/api", tags=["cache"]) + for namespace in self._cache_owners(registry): + # One router per agent that has a cache, mounted under that agent's prefix, so + # ``/api/orders/cache/stats`` reports the orders agent's cache and nothing else. + # A process-wide endpoint would report one agent's keys to another, which is the + # collision spec sec. 8 exists to close. + with construction_scope(namespace): + cache_api = CacheManagementApi() + self._mount(app, cache_api, root_prefix="/api") if self._actuator_api is not None: app.include_router(self._actuator_api.router, tags=["actuators"]) @@ -1016,6 +1090,24 @@ def _wire_dapr_endpoint(self, registry: Registry, event_bus_type: str) -> None: "One Dapr endpoint serves this process, fanning each delivery out to the agents that declared its topic", ) + @staticmethod + def _cache_owners(registry: Registry) -> list[str]: + """Return the namespaces that have at least one cache, in registration order. + + Derived from the registry rather than from :attr:`hosted_namespaces` because a cache is + declared, not implied: an agent that declared none gets no endpoint at all, exactly as + an application built without ``with_cache()`` has never served ``/cache/*``. + + Args: + registry: The application's registry. Read process-wide, which is why this takes + the application's own and not a component's view. + """ + owners: list[str] = [] + for namespace, _, _ in registry.cache_entries(): + if namespace not in owners: + owners.append(namespace) + return owners + @staticmethod def _mount(app: FastAPI, component: RestApiBase, *, root_prefix: str) -> None: """Include one component's router, under its agent's prefix if it has one. @@ -1043,7 +1135,7 @@ def _mount(app: FastAPI, component: RestApiBase, *, root_prefix: str) -> None: # A Starlette BaseRoute has no tags; an APIRoute does, and those are the # ones the decorators produce. Anything else is left alone. if isinstance(route, APIRoute) and route.tags: - route.tags = [f"{component.namespace}.{tag}" for tag in route.tags] + route.tags = [qualified_entry_name(component.namespace, str(tag)) for tag in route.tags] app.include_router(component.router, prefix=prefix) # ------------------------------------------------------------------ diff --git a/src/blueprint/agents/component/component.py b/src/blueprint/agents/component/component.py index 877ea795..2559e651 100644 --- a/src/blueprint/agents/component/component.py +++ b/src/blueprint/agents/component/component.py @@ -149,7 +149,8 @@ def __init__(self, should_register: bool = True, name: str | None = None, namesp # line, health entry and span -- say nothing about which agent it belonged to. Two # agents in a group each with a 'planner' were then one indistinguishable 'planner' in # the logs, and the second one to register collided on the key. - self._name = qualified_component_name(self._namespace, name or camel_to_snake(self.__class__.__name__)) + self._base_name = name or camel_to_snake(self.__class__.__name__) + self._name = qualified_component_name(self._namespace, self._base_name) if should_register: self.registry.add_component(self.name, self) @@ -174,6 +175,20 @@ def name(self, value: str) -> None: qualified = qualified_component_name(self._namespace, value) self.registry.update_component_name(self._name, qualified) self._name = qualified + self._base_name = value + + @property + def base_name(self) -> str: + """The name without its namespace: what this component is called *within* its agent. + + Kept because :attr:`name` cannot be un-qualified afterwards -- + ``qualified_component_name`` is deliberately not idempotent, so stripping a prefix from + a name is guesswork ("does ``billing_handler`` in agent ``billing`` carry a prefix or + not?"). Anything that has to render the pair itself needs the two halves separately: the + readiness payload does, where an entry reads ``orders.nats_client`` rather than + ``orders.orders_nats_client``. + """ + return self._base_name @property def namespace(self) -> str: diff --git a/src/blueprint/agents/component/namespace.py b/src/blueprint/agents/component/namespace.py index 32d523fd..7fd7e928 100644 --- a/src/blueprint/agents/component/namespace.py +++ b/src/blueprint/agents/component/namespace.py @@ -175,6 +175,34 @@ def namespace_scope(namespace: str) -> Iterator[str]: _CURRENT_NAMESPACE.reset(token) +@contextmanager +def construction_scope(namespace: str) -> Iterator[None]: + """Construct inside ``namespace``, or leave the ambient namespace exactly as it is. + + The difference matters because :func:`namespace_scope` with ``""`` is not a no-op: it + *sets* the current namespace to the root. Anything recorded outside a scope carries ``""``, + and entering a scope for it would reset the namespace in force -- which is what happens + when a whole agent's declarations are replayed inside one scope, and would silently move + every one of them back to the root. + + Lives here rather than in one of its callers because it is the guarded form of + :func:`namespace_scope`, and every place that constructs on behalf of a namespace it was + *handed* needs it: the builder replaying a declaration, and the cache factory, which is + given the owning agent as an argument. + + Args: + namespace: The agent to construct for, or ``""`` to keep whatever is already in force. + + Yields: + Nothing; the scope is ambient. + """ + if not namespace: + yield + return + with namespace_scope(namespace): + yield + + def display_segment(value: str, placeholder: str) -> str: """Return ``value`` reduced to one safe segment of a dot-separated identity string. @@ -220,6 +248,27 @@ def qualified_component_name(namespace: str, base_name: str) -> str: return base_name if not namespace else f"{namespace}_{base_name}" +def qualified_entry_name(namespace: str, name: str) -> str: + """Return the name ``name`` is *displayed* under inside ``namespace``. + + For the names that identify something in a payload or a document rather than in the + registry: a readiness entry, an OpenAPI tag. The root keeps the bare name, so a + single-agent application's readiness payload and Swagger groups do not change. + + ``.`` rather than the ``_`` of :func:`qualified_component_name`, and the two are not + interchangeable. A registry name is an identifier that other code *looks up*, and ``_`` is + what every lookup qualifies with; an entry name is a label nothing resolves, and it may + contain characters a registry name never does -- ``cache:sessions`` is one. Rendering both + the same way would suggest a readiness key can be passed to ``get_component``, and it + cannot. + + The namespace is kept **as data** wherever this is used, and this is only its rendering: + recovering an agent by splitting the result breaks on the first name containing a dot, and + ``v2.sessions`` is a legal cache name. + """ + return name if not namespace else f"{namespace}.{name}" + + def namespace_of(component: Any) -> str: """Return the namespace a component belongs to, or the root for one that has none. diff --git a/src/blueprint/agents/component/registry.py b/src/blueprint/agents/component/registry.py index dcda4ad9..c2201c99 100644 --- a/src/blueprint/agents/component/registry.py +++ b/src/blueprint/agents/component/registry.py @@ -82,12 +82,11 @@ def __init__(self, component_class: Any) -> None: Registry._component_class = component_class self._correlation_context = CorrelationContextProvider.get_correlation_context() - self._caches: dict[str, CacheService] = {} + self._caches: dict[tuple[str, str], CacheService] = {} self._components: dict[str, Any] = {} self._executors: dict[str, ThreadPoolExecutor] = {} self._default_namespace: str | None = None self._views: dict[str, Registry] = {} - self._scoped_caches: dict[str, CacheService] = {} logger.info("ComponentRegistry initialized") @@ -157,9 +156,6 @@ def for_namespace(self, namespace: str) -> "Registry": view = copy(self) view._default_namespace = namespace view._views = {} - # Its own, because the entries are per agent: the shallow copy would otherwise have - # every view handing out the first agent's lens. - view._scoped_caches = {} self._views[namespace] = view return view @@ -266,8 +262,31 @@ def shutdown_executors(self) -> None: executor.shutdown(wait=True) self._executors.clear() - def add_cache(self, name: str, cache: CacheService) -> None: - """Register a cache under ``name``, replacing any cache already registered under it. + def _cache_owner(self, namespace: str | None) -> str: + """Return which agent a cache call is about. + + An omitted ``namespace`` means **this agent**: that agent on a view, and the root on + the application's own registry. It deliberately does *not* mean "every namespace" the + way it does for components (see :meth:`_effective_namespace`), because every cache + operation names exactly one cache -- there is no cache that belongs to all agents, and + a lookup that ranged over the process would be the cross-agent sharing spec sec. 8 + exists to prevent. + + Args: + namespace: The agent named at the call site, or ``None`` to take it from this + object. + """ + if namespace is not None: + return namespace + return self._default_namespace or ROOT_NAMESPACE + + def add_cache(self, name: str, cache: CacheService, *, namespace: str | None = None) -> None: + """Register a cache under ``name`` for one agent, replacing any cache already there. + + A cache belongs to the agent that declared it (spec sec. 8): the store is keyed on + ``(namespace, name)``, so two agents may both register ``sessions`` and neither can + reach the other's. The agent is taken from this object -- a view registers for its own + namespace, the application's registry for the root -- unless ``namespace`` names one. Replacing is allowed rather than refused, because a cache is not tied to the build the way a component is: one can legitimately be swapped or added after startup. It is logged @@ -278,92 +297,110 @@ def add_cache(self, name: str, cache: CacheService) -> None: Args: name: What to register it as. See :data:`DEFAULT_CACHE_NAME`. cache: The cache to register. + namespace: The agent it belongs to. Omitted means this object's agent. """ - if name in self._caches: + agent = self._cache_owner(namespace) + key = (agent, name) + if key in self._caches: logger.warning( - "Cache '%s' is already registered as %s and is being replaced by %s", + "Cache '%s' of agent '%s' is already registered as %s and is being replaced by %s", name, - type(self._caches[name]).__name__, + agent or ROOT_LABEL, + type(self._caches[key]).__name__, type(cache).__name__, ) else: - logger.info("Registering cache '%s': %s", name, type(cache).__name__) - self._caches[name] = cache + logger.info("Registering cache '%s' for agent '%s': %s", name, agent or ROOT_LABEL, type(cache).__name__) + self._caches[key] = cache - def get_cache(self, name: str = DEFAULT_CACHE_NAME) -> CacheService: - """Get the cache registered under ``name``. + def get_cache(self, name: str = DEFAULT_CACHE_NAME, *, namespace: str | None = None) -> CacheService: + """Get the cache one agent registered under ``name``. - There is deliberately **no fallback to the default cache**. Caches are the one thing - agents must not share by accident (spec sec. 8): two independently written agents both - asking for ``"sessions"`` would silently share one store the moment they were grouped, - and only in production. A name that is not registered is therefore an error, not an - invitation to hand over some other cache. + There are deliberately **two fallbacks that do not exist**: none from an unknown name to + the default cache, and none from an agent to the root or to a neighbour. An agent has + exactly the caches it declared with ``with_cache`` and no others (spec sec. 8), because + two independently written agents both asking for ``"sessions"`` would otherwise share + one store the moment they were grouped, and only in production. A name this agent did + not declare is therefore an error, not an invitation to hand over some other cache. Args: name: Which cache. Defaults to :data:`DEFAULT_CACHE_NAME`. + namespace: The agent asking. Omitted means this object's agent, which is what lets + a component write ``self.registry.get_cache("sessions")`` with no namespace in + sight and still reach its own store. Returns: - The cache registered under that name. + The cache that agent registered under that name. Raises: - ValueError: If no cache is registered under ``name``. + ValueError: If that agent registered no cache under ``name``. """ - cache = self._caches.get(name) + agent = self._cache_owner(namespace) + cache = self._caches.get((agent, name)) if cache is None: - registered = ", ".join(sorted(self._caches)) or "none" - raise ValueError(f"No cache registered as '{name}' (registered: {registered})") - if self._default_namespace: - return self._scoped_cache(name, cache) + registered = ", ".join(sorted(self.get_all_caches(agent))) or "none" + raise ValueError(f"No cache registered as '{name}' for agent '{agent or ROOT_LABEL}' (registered: {registered})") return cache - def _scoped_cache(self, name: str, cache: CacheService) -> CacheService: - """Return this view's agent-scoped lens on ``cache`` (spec sec. 8). + def get_all_caches(self, namespace: str | None = None) -> dict[str, CacheService]: + """Return one agent's caches by name, as a copy. + + One agent's, not the process's: the keys are bare cache names, and two agents' caches + share those. What ranges over the process is :meth:`cache_entries`, whose entries carry + the agent. - Built here rather than at registration because the same backend serves every agent: one - cache, N views of it, each prefixing its own partitions. Cached per name so an agent - asking twice gets one object, which keeps the lens as cheap as the raw cache. + A copy so that a caller iterating the caches -- the cache management endpoints do -- + cannot mutate the registry by accident. + + Args: + namespace: The agent asking. Omitted means this object's agent. """ - # Imported here: agent_scoped_cache imports CacheService, which is a ServiceBase, which - # is a Component -- and component.py imports this module. - from ..services.infrastructure.agent_scoped_cache import AgentScopedCache - agent = self._default_namespace - assert agent is not None # nosec B101 -- guarded by the caller; a view always has one - scoped = self._scoped_caches.get(name) - if scoped is None: - scoped = AgentScopedCache(cache, agent) - self._scoped_caches[name] = scoped - return scoped + agent = self._cache_owner(namespace) + return {name: cache for (owner, name), cache in self._caches.items() if owner == agent} - def get_all_caches(self) -> dict[str, CacheService]: - """Return every registered cache by name, as a copy. + def cache_entries(self) -> list[tuple[str, str, CacheService]]: + """Return every cache in the process as ``(namespace, name, cache)``, in registration order. - A copy so that a caller iterating the caches -- the health checks and the cache - management endpoints do -- cannot mutate the registry by accident. + The one cache view that crosses agents, for the callers that build the process rather + than live in it: ``build()``, which puts every cache into the readiness probe and mounts + the management endpoints. The agent is returned **as data** rather than folded into the + name, so a caller that has to attribute a cache to an agent -- the readiness payload + does -- never has to split a string that may legally contain the separator. + + Raises: + RuntimeError: if called on a view. A view is what agent code holds, and an agent + that can enumerate its neighbours' caches can be written to depend on them + (C6). Assembly reads this from the application's own registry. """ - return dict(self._caches) + if self._default_namespace is not None: + raise RuntimeError( + f"The registry view for namespace '{self._default_namespace}' was asked for every cache in the " + "process. An agent sees only the caches it declared; use get_all_caches() for those." + ) + return [(namespace, name, cache) for (namespace, name), cache in self._caches.items()] @property def cache_service(self) -> CacheService: - """The default cache. Retained as an alias for ``get_cache()`` (spec sec. 8). + """This agent's default cache. Retained as an alias for ``get_cache()`` (spec sec. 8). Returns: - The cache registered as :data:`DEFAULT_CACHE_NAME` + The cache registered as :data:`DEFAULT_CACHE_NAME` for this object's agent Raises: - ValueError: If no cache service is registered + ValueError: If no cache service is registered for it """ - if not self._caches: - raise ValueError("No cache service registered") + if not self.get_all_caches(): + raise ValueError(f"No cache service registered for agent '{self._cache_owner(None) or ROOT_LABEL}'") return self.get_cache() @cache_service.setter def cache_service(self, cache_service: CacheService) -> None: - """Register the default cache. Retained as an alias for ``add_cache()`` (spec sec. 8). + """Register this agent's default cache. Retained as an alias for ``add_cache()`` (spec sec. 8). Args: cache_service: The cache service instance to register @@ -568,23 +605,26 @@ def clear(self) -> None: logger.info("Clearing all components from registry") self.clear_components() self.shutdown_executors() - for name, cache in self._caches.items(): - logger.info("Clearing cache '%s'", name) + for (namespace, name), cache in self._caches.items(): + logger.info("Clearing cache '%s' of agent '%s'", name, namespace or ROOT_LABEL) cache.clear() self._caches.clear() - def has_cache(self, name: str = DEFAULT_CACHE_NAME) -> bool: - """Check whether a cache is registered under ``name``. + def has_cache(self, name: str = DEFAULT_CACHE_NAME, *, namespace: str | None = None) -> bool: + """Check whether this agent registered a cache under ``name``. Args: name: Which cache. Defaults to :data:`DEFAULT_CACHE_NAME`, so an existing caller asking whether "the" cache exists keeps its meaning. + namespace: The agent asking. Omitted means this object's agent, so a component + asking whether it has a cache is answered about its own -- which is what makes + ``idempotency_enabled`` a per-agent requirement rather than a process-wide one. Returns: - True if a cache is registered under that name, False otherwise + True if that agent has a cache under that name, False otherwise """ - return name in self._caches + return (self._cache_owner(namespace), name) in self._caches def has_event_handler(self, name: str | None = None, namespace: str | None = None) -> bool: """Check if a handler is registered. diff --git a/src/blueprint/agents/config/__init__.py b/src/blueprint/agents/config/__init__.py index 6953b982..85a76d2e 100644 --- a/src/blueprint/agents/config/__init__.py +++ b/src/blueprint/agents/config/__init__.py @@ -1,10 +1,12 @@ """Configuration module for the application.""" -from .config import Config, ConfigError +from .config import DEFAULT_SETTINGS_FILES, PROCESS_SCOPE_KEYS, Config, ConfigError from .custom_logging import LoggingManager from ..io.telemetry.telemetry import TelemetryManager, TracingContext __all__ = [ + "DEFAULT_SETTINGS_FILES", + "PROCESS_SCOPE_KEYS", "Config", "ConfigError", "LoggingManager", diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index 08ae01e4..eaee92c3 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -4,6 +4,7 @@ import logging import os import re +import tomllib from copy import copy from pathlib import Path from typing import Any @@ -36,6 +37,56 @@ class ConfigError(Exception): """ +PROCESS_SCOPE_KEYS = frozenset( + { + "app_port", + "app_host", + "app_workers", + "app_environment", + "envvar_prefix", + "event_bus", + "log_level", + "log_format", + "suppress_noisy_loggers", + "health_check_interval_seconds", + "dot_placeholder", + "nats_stream_name", + } +) +"""Keys that describe the *process*, and that an agent's own settings file therefore cannot set. + +One process binds one port, loads one environment section, reads its environment through one +prefix, speaks one event bus and configures logging once, so all of those are read from the +group's configuration and never from an agent's scope. A copy under ``[]`` would be read +by nothing at all -- which is spec sec. 5.3's reason for refusing it, and it is why +:meth:`Config.merge_agent_settings` drops these keys with a WARNING that names the agent, the +key and the file rather than merging them where nothing will look. + +``nats_stream_name`` is the one entry whose reason is different: it *is* read through an agent's +own view, so a scoped value would take effect. It is dropped anyway, because the stream is a +server-side object shared with every other deployment on that broker -- an agent that quietly +moved its group's events into a stream of its own would be a broker-side change made by editing +a file in one agent's directory. + +Display metadata is deliberately **not** here. ``app_name``, ``app_version`` and +``app_description`` are what a scaffolded project's settings file always contains, and a scoped +``app_name`` is genuinely read -- the NATS queue group falls back to it, and so does the +telemetry service name. Refusing them would mean an existing project could not be hosted as an +agent without editing its settings file, which is exactly what grouping must not require. +""" + + +DEFAULT_SETTINGS_FILES = ["settings.toml", ".secrets.toml"] +"""The settings files the framework loads when the application names none. + +Dynaconf's usual pair, in its usual order. It lives here rather than in whichever caller needed +it first because two of them need the same answer: the container entry point, whose contract with +the image is which files it reads, and ``AppBuilder.build()`` when it has to construct a ``Config`` +because the application handed it none. A project that needs something else passes its own +``Config``; nothing guesses twice. +""" + + DEFAULT_ENVVAR_PREFIX = "DYNACONF" """The prefix an environment override carries unless the project declares another one. @@ -112,6 +163,11 @@ def __init__( self._agent_scope = agent_scope self._is_view = False self._views: dict[str, Config] = {} + # Kept so that :meth:`merge_agent_settings` can recognise a file the process has already + # loaded as its own. An agent whose declaration module sits beside the group's settings + # file would otherwise have every root key merged under its scope a second time. + names = [settings_files] if isinstance(settings_files, str) else list(settings_files or []) + self._settings_files = tuple((self._root_path / name).resolve() for name in names if name) # First pass: load config to get envvar_prefix and app_environment. # @@ -136,6 +192,10 @@ def __init__( envvar_prefix=self._envvar_prefix, ) app_env = temp_settings.get("app_environment", "development") + # Kept for merge_agent_settings, which has to resolve an agent's fragment for the same + # environment the process loaded -- a fragment's [development] section is that agent's + # development section, not a table it happens to have called that. + self._environment = str(app_env) logger.info( "Loading configuration properties for environment: %s (environment overrides read from %s)", app_env, @@ -402,6 +462,181 @@ def namespaces(self) -> tuple[str, ...]: ) return tuple(sorted(self._views)) + def merge_agent_settings(self, namespace: str, path: str | Path) -> tuple[str, ...]: + """Merge one agent's own settings file under that agent's scope (spec sec. 5.3, D5). + + An agent author writes plain keys in their own directory's ``settings.toml`` -- + ``model_name = "..."``, or a ``[default]`` section, exactly as a standalone project's + file does -- and never ``[default.]``. This is what turns that file into the + agent's scope, so C5 resolves it and the author never learns that a scope exists. The + same file therefore serves the project standalone and as one agent of a group, which is + the whole requirement: only ``main.py`` may differ between the two. + + **A fragment can only ever add to its own agent.** It is merged under ``[]`` + and nowhere else, so an agent cannot change what the process or a neighbour reads. There + is consequently no collision to report: a fragment key and a root key never occupy the + same slot, and a group's own value for a key is simply the default this agent's value + overrides. + + **What is already in the tree wins.** A key the group's own settings file states under + ``[]``, or an environment override (``DYNACONF___KEY``), is left alone and + the fragment fills in only what neither of them said. The deployment's word beats a file + baked into the image, and this is also what keeps an environment override from being + overwritten by a file read after it. + + **Process-scope keys are dropped with a WARNING**, one per key, naming the agent, the + key, the file and the value the process actually uses. See :data:`PROCESS_SCOPE_KEYS` + for what counts and why -- and note that spec sec. 5.3 asks for a *raise* here. It is a + warning instead, deliberately: every example project in this repository declares + ``app_port`` and ``app_environment`` in its settings file, and three declare + ``log_level``, so raising would mean no existing project could be hosted as an agent + without first editing a file that is correct for its own standalone deployment. The + purpose of the MUST -- that the author can discover the value is inert -- is served by a + line that names the file and the key. + + Args: + namespace: The agent the file belongs to. Never the root: the root's configuration is + the process's own settings files, which are loaded by ``__init__``. + path: The agent's settings file. It need not exist; an agent that ships none is + simply an agent with no settings of its own. + + Returns: + The keys merged, sorted. Empty when the file is absent, holds nothing, or is one of + the process's own settings files. + + Raises: + RuntimeError: if called on a view. A view is what agent code holds, and authoring + another agent's configuration through it is the same breach as reading one (C6). + ValueError: if ``namespace`` is empty. + ConfigError: if the file exists and cannot be read or parsed. Reported rather than + skipped: a file that is there was meant to be used. + """ + if self._is_view: + raise RuntimeError( + f"The configuration view for namespace '{self._agent_scope}' was asked to merge settings for " + f"namespace '{namespace}'. A view resolves its own keys; the process's configuration is assembled " + "before any view exists." + ) + if not namespace: + raise ValueError( + "merge_agent_settings() needs an agent's namespace. The root namespace's configuration is the " + "process's own settings files, which __init__ loads." + ) + + candidate = Path(path) + resolved = (self._root_path / candidate).resolve() + if resolved in self._settings_files: + logger.debug( + "Agent '%s' has no settings file of its own: %s is one of the process's own settings files", + namespace, + resolved, + ) + return () + if not resolved.is_file(): + logger.debug("Agent '%s' ships no settings file (looked for %s)", namespace, resolved) + return () + + try: + document = tomllib.loads(resolved.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError) as exc: + raise ConfigError(f"The settings file of agent '{namespace}' ({resolved}) could not be read: {exc}") from exc + + fragment = self._layer_fragment(document) + fragment = self._drop_process_scope_keys(namespace, resolved, fragment) + if not fragment: + logger.debug("The settings file of agent '%s' (%s) contributes nothing", namespace, resolved) + return () + + existing = self._settings.get(namespace) + merged = dict(existing.items()) if hasattr(existing, "items") else {} + added = self._fill_missing(merged, fragment) + self._settings[namespace] = merged + logger.info( + "Merged %d key(s) from %s under agent '%s': %s", + len(added), + resolved, + namespace, + ", ".join(added) or "none", + ) + return added + + def _layer_fragment(self, document: dict[str, Any]) -> dict[str, Any]: + """Flatten an agent's settings file the way Dynaconf flattens the process's own. + + Three layers, lowest first: keys written at the top level, ``[default]``, and the + section for the environment in force. ``[global]`` is applied last, as Dynaconf applies + it. Section names are matched case-insensitively, again as Dynaconf matches them. + + Resolved here rather than by handing the file to Dynaconf, and that is not a preference: + Dynaconf always reads ``DYNACONF_*`` from the environment and cannot be told not to, so + a Dynaconf-loaded fragment would pull process-wide environment overrides into this + agent's scope -- including the very keys :data:`PROCESS_SCOPE_KEYS` refuses, which would + then be reported against a file that does not contain them. + + Args: + document: The parsed file. + """ + sections = {str(key).lower(): value for key, value in document.items() if hasattr(value, "items")} + layered: dict[str, Any] = {key: value for key, value in document.items() if not hasattr(value, "items")} + for section in ("default", self._environment.lower(), "global"): + values = sections.get(section) + if values: + layered.update({str(key): value for key, value in values.items()}) + # A table the file wrote at the top level is a value, not a section: [cache] beside + # [default] is this agent's cache configuration, and it is only the three names above + # that mean "an environment". + for name, values in sections.items(): + if name not in ("default", self._environment.lower(), "global"): + layered.setdefault(name, values) + return layered + + def _drop_process_scope_keys(self, namespace: str, path: Path, fragment: dict[str, Any]) -> dict[str, Any]: + """Return ``fragment`` without the keys an agent cannot set, warning about each. + + The warning carries what the process uses instead, because "your value is not used" is + only actionable next to the value that is. + """ + refused = PROCESS_SCOPE_KEYS | DEPLOYMENT_IDENTITY_KEYS + kept: dict[str, Any] = {} + for key, value in fragment.items(): + if str(key).lower() not in refused: + kept[key] = value + continue + current = self._settings.get(str(key)) + logger.warning( + "Agent '%s' sets '%s' in %s, and that is a process-wide setting: one process has one of it, so this " + "value (%r) is ignored and %s. Remove it from the agent's settings file, or set it in the group's.", + namespace, + key, + path, + value, + f"the group's own value ({current!r}) is used" if current is not None else "the group's settings do not set it", + ) + return kept + + @staticmethod + def _fill_missing(target: dict[str, Any], incoming: dict[str, Any], prefix: str = "") -> tuple[str, ...]: + """Add what ``incoming`` says and ``target`` does not, in place, and report what was added. + + Recursive so that a fragment's ``[cache] cache_dir`` can join a group's + ``[default..cache] size_limit`` instead of replacing the table or being dropped + by it. A leaf already present is never overwritten -- see the precedence rule on + :meth:`merge_agent_settings`. + """ + added: list[str] = [] + for key, value in incoming.items(): + path = f"{prefix}{key}" + if key not in target: + target[key] = value + added.append(path) + continue + present = target[key] + if hasattr(present, "items") and hasattr(value, "items"): + nested = dict(present.items()) + added.extend(Config._fill_missing(nested, dict(value.items()), prefix=f"{path}.")) + target[key] = nested + return tuple(sorted(added)) + def resolved_settings(self, namespace: str = "") -> dict[str, Any]: """Return the configuration one namespace resolves, flattened as it would read it. diff --git a/src/blueprint/agents/entrypoint.py b/src/blueprint/agents/entrypoint.py index 59b43308..41c08495 100644 --- a/src/blueprint/agents/entrypoint.py +++ b/src/blueprint/agents/entrypoint.py @@ -4,9 +4,10 @@ injected at container start rather than baked in at build time -- so which agents a pod runs is a deployment decision and changing it is a Deployment edit, not a rebuild. -This module exists to hold the three things ``AppBuilder`` must not: reading the environment, -reading files, and exiting the process. Everything it does is four lines; the rest of the file is -about what happens when one of them fails. +This module exists to hold the one thing neither ``AppBuilder`` nor ``AgentGroup.assemble`` +may do: exit the process. The environment and file reads belong to ``AgentGroup.resolve``, which +is separated from ``assemble`` for that reason. Everything this module does is three lines; the +rest of the file is about what happens when one of them fails. **Why exit rather than raise.** A group that cannot be resolved must stop the process *before the port is bound* (spec sec. 9.1), so that Kubernetes crash-loops the pod with a readable message @@ -23,21 +24,13 @@ from fastapi import FastAPI -from .app_builder import AppBuilder -from .config import Config -from .group_config import GroupConfig, GroupConfigError +from .agent_group import AgentGroup +from .config import DEFAULT_SETTINGS_FILES, Config +from .group_config import GroupConfigError from .utils import run_app logger = logging.getLogger(__name__) -DEFAULT_SETTINGS_FILES = ["settings.toml", ".secrets.toml"] -"""Settings the entry point loads, in Dynaconf's usual order. - -Named here rather than left to a default because this module *is* the deployment's entry point: -what it loads is part of the contract with the image, and a project that needs something else -writes its own ``main.py`` rather than discovering that this one guessed. -""" - def build_group_app(*, environ: dict[str, str] | None = None) -> tuple[FastAPI, Config]: """Resolve the group, build the application, and return it with its configuration. @@ -61,8 +54,7 @@ def build_group_app(*, environ: dict[str, str] | None = None) -> tuple[FastAPI, GroupConfigError: if the group cannot be resolved or a critical agent cannot be loaded. """ config = Config(settings_files=DEFAULT_SETTINGS_FILES) - group = GroupConfig.resolve(config, environ=environ) - app = AppBuilder(config).with_group(group).build() + app = AgentGroup.resolve(config, environ=environ).assemble(config) return app, config diff --git a/src/blueprint/agents/group_config.py b/src/blueprint/agents/group_config.py index 48cb7ec8..249f062b 100644 --- a/src/blueprint/agents/group_config.py +++ b/src/blueprint/agents/group_config.py @@ -45,7 +45,7 @@ import logging import os import tomllib -from dataclasses import dataclass, field +from dataclasses import dataclass from pathlib import Path from typing import Any @@ -85,7 +85,7 @@ class AgentSpec: prefix, queue group, durable name, cache partition and telemetry service name. Held to the namespace alphabet, so a group file cannot name an agent the rest of the system could not identify. - module: Where the agent's ``AgentRegistration`` lives, as ``"module.path:attribute"``. + module: Where the agent's ``AppBuilder`` declaration lives, as ``"module.path:attribute"``. Comes from the agent map, never from the group file: what an agent *is* belongs to the image, and only which agents run belongs to the deployment. critical: Whether this agent failing to load must stop the process. Defaults to @@ -114,14 +114,17 @@ class GroupConfig: broker-side identifier may derive from it, or moving an agent between groups would be visible to the broker (C1). agents: The agents to host, in the order the group declared them. - cache_names: Caches to register for the process, beyond the default one. A cache is - process-wide (spec sec. 8), so it is the group's to declare rather than any single - agent's. + + Note: + A group declares **no caches**. A cache belongs to the agent that declared it with + ``with_cache`` and is reachable from no other (spec sec. 8), so there is no + process-wide cache for a group to name. ``cache_names`` in a group file is therefore + read by nothing; it is ignored rather than refused, so a file written against the + earlier shape still starts the process it describes. """ name: str agents: tuple[AgentSpec, ...] - cache_names: tuple[str, ...] = field(default=()) @property def agent_names(self) -> tuple[str, ...]: @@ -158,7 +161,7 @@ def resolve(cls, config: Config, *, environ: dict[str, str] | None = None) -> "G root = config.get_package_root() declared = cls._read_group_file(env, root) - name, agent_names, critical_names, cache_names = cls._apply_env_overrides(env, declared) + name, agent_names, critical_names = cls._apply_env_overrides(env, declared) if not agent_names: raise GroupConfigError( @@ -170,13 +173,12 @@ def resolve(cls, config: Config, *, environ: dict[str, str] | None = None) -> "G agent_map = cls._read_agent_map(env, root) agents = cls._resolve_agents(agent_names, critical_names, agent_map, name) - group = cls(name=name, agents=tuple(agents), cache_names=tuple(cache_names)) + group = cls(name=name, agents=tuple(agents)) logger.info( - "Resolved group '%s' with %d agent(s): %s%s", + "Resolved group '%s' with %d agent(s): %s", group.name, len(group.agents), ", ".join(f"{agent.name}{'' if agent.critical else ' (non-critical)'}" for agent in group.agents), - f"; caches: {', '.join(group.cache_names)}" if group.cache_names else "", ) return group @@ -313,13 +315,13 @@ def _read_agent_map(cls, env: dict[str, str] | Any, root: Path) -> dict[str, str # ------------------------------------------------------------------ @staticmethod - def _apply_env_overrides(env: dict[str, str] | Any, declared: dict[str, Any]) -> tuple[str, list[str], set[str], list[str]]: + def _apply_env_overrides(env: dict[str, str] | Any, declared: dict[str, Any]) -> tuple[str, list[str], set[str]]: """Overlay environment variables on the file's slice, key by key, logging each source. Key by key rather than all-or-nothing (spec sec. 5.1): a Deployment that wants a - different agent list should not have to restate the group's name and caches to get it. - The log line per value is what answers "where did this pod's agent list come from", - which is the first question asked of a group that started with the wrong contents. + different agent list should not have to restate the group's name to get it. The log + line per value is what answers "where did this pod's agent list come from", which is + the first question asked of a group that started with the wrong contents. """ def _split(raw: str) -> list[str]: @@ -328,8 +330,7 @@ def _split(raw: str) -> list[str]: name = str(declared.get("name", "") or "").strip() agents = [str(agent).strip() for agent in declared.get("agents", []) or [] if str(agent).strip()] critical = {str(agent).strip() for agent in declared.get("critical_agents", []) or [] if str(agent).strip()} - caches = [str(cache).strip() for cache in declared.get("cache_names", []) or [] if str(cache).strip()] - sources = {"name": "file", "agents": "file", "critical_agents": "file", "cache_names": "file"} + sources = {"name": "file", "agents": "file", "critical_agents": "file"} if override := str(env.get(GROUP_ENV, "") or "").strip(): if not name: @@ -347,7 +348,7 @@ def _split(raw: str) -> list[str]: for key, source in sources.items(): if source != "file" or declared: logger.info("Group value '%s' resolved from %s", key, source) - return name, agents, critical, caches + return name, agents, critical @staticmethod def _resolve_agents(agent_names: list[str], critical_names: set[str], agent_map: dict[str, str], group_name: str) -> list[AgentSpec]: diff --git a/src/blueprint/agents/handler/event_handler_base.py b/src/blueprint/agents/handler/event_handler_base.py index 7f0c2a3b..538fb2fa 100644 --- a/src/blueprint/agents/handler/event_handler_base.py +++ b/src/blueprint/agents/handler/event_handler_base.py @@ -72,6 +72,17 @@ def __init__(self, priority: int = 100): super().__init__() self._priority = priority + @property + def priority(self) -> int: + """Execution priority; lower numbers are tried first. + + Public because the ordering rule is enforced from outside this class: + ``AppBuilder.build()`` compares two handlers' priorities to decide whether the order + they were declared in still decides which of them is tried first, and ``__lt__`` + answers only the sorting question, not that one. + """ + return self._priority + @traced("event") async def can_handle(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: """Framework method that adds tracing around capability checks. diff --git a/src/blueprint/agents/io/api/actuators/actuator_api.py b/src/blueprint/agents/io/api/actuators/actuator_api.py index c5f4ffff..320fc36d 100644 --- a/src/blueprint/agents/io/api/actuators/actuator_api.py +++ b/src/blueprint/agents/io/api/actuators/actuator_api.py @@ -3,6 +3,7 @@ import logging import os import platform +from collections.abc import Sequence from importlib import metadata from importlib.metadata import PackageNotFoundError from typing import Any @@ -18,7 +19,7 @@ from ....models.status import BuildStatus, EnvironmentStatus, LLMStatus, ServiceInfo, VLLMInfo from .health.health_cache import HealthCheckCache from ..rest_api_base import RestApiBase -from .health.health_base import HealthCheckerBase +from .health.health_base import HealthCheckEntry logger = logging.getLogger(__name__) @@ -44,24 +45,53 @@ class ActuatorApi(RestApiBase): def __init__(self) -> None: super().__init__(should_register=False) self._health_cache: HealthCheckCache | None = None - self._pending_providers: dict[str, HealthCheckerBase] = {} + self._health_entries: list[HealthCheckEntry] = [] - def add_health_providers(self, providers: dict[str, HealthCheckerBase]) -> None: - """Register health check providers. + @property + def health_entries(self) -> tuple[HealthCheckEntry, ...]: + """Every check registered so far, in registration order.""" + return tuple(self._health_entries) + + def add_health_providers(self, providers: Sequence[HealthCheckEntry]) -> None: + """Register health checks, adding to the ones already registered. + + **Accumulates rather than replaces**, which is a fix rather than a refinement: the + previous version assigned the whole mapping, so a ``with_health_checker`` call made + after ``build()`` -- the shape the method's own docstring documents -- discarded every + client and cache check the build had wired, and the readiness probe then reported one + component and nothing else. + + A duplicate key is refused. Two checks under one name is exactly the silent loss D4 + exists to remove: a dict kept the last one, so an agent's check could vanish with + nothing logged and nothing failing. Args: - providers: Mapping of component name to HealthCheckerBase instance + providers: The checks to add, each carrying the agent it belongs to. + + Raises: + ValueError: if a key is already registered. """ + registered = {entry.key: entry for entry in self._health_entries} + for entry in providers: + existing = registered.get(entry.key) + if existing is not None: + raise ValueError( + f"Health check '{entry.name}' of agent '{entry.agent}' would appear in the readiness payload as " + f"'{entry.key}', which is already taken by a {type(existing.checker).__name__} of agent " + f"'{existing.agent}'. Two checks under one entry cannot be told apart in the payload, so one of " + "them has to be renamed." + ) + registered[entry.key] = entry + self._health_entries.append(entry) + if self._health_cache is not None: - self._health_cache.set_health_check_provider(providers) - else: - self._pending_providers = providers + self._health_cache.set_health_entries(self._health_entries) async def on_startup(self) -> None: """Start the health check cache.""" self._health_cache = HealthCheckCache(check_interval_seconds=self.config.get("health_check_interval_seconds", 30)) - if hasattr(self, "_pending_providers") and self._pending_providers: - self._health_cache.set_health_check_provider(self._pending_providers) + if self._health_entries: + self._health_cache.set_health_entries(self._health_entries) await self._health_cache.start() async def on_shutdown(self) -> None: diff --git a/src/blueprint/agents/io/api/actuators/health/__init__.py b/src/blueprint/agents/io/api/actuators/health/__init__.py index f4563bb5..13d1d8a7 100644 --- a/src/blueprint/agents/io/api/actuators/health/__init__.py +++ b/src/blueprint/agents/io/api/actuators/health/__init__.py @@ -1,11 +1,12 @@ """Health check providers for the agent application.""" -from .health_base import HealthCheckerBase +from .health_base import HealthCheckEntry, HealthCheckerBase from .cache_health import CacheHealthChecker from .client_health import ClientHealthChecker from .sessions_health import SessionsServiceHealthChecker __all__ = [ + "HealthCheckEntry", "HealthCheckerBase", "CacheHealthChecker", "ClientHealthChecker", diff --git a/src/blueprint/agents/io/api/actuators/health/health_base.py b/src/blueprint/agents/io/api/actuators/health/health_base.py index 38e54f19..45a8144c 100644 --- a/src/blueprint/agents/io/api/actuators/health/health_base.py +++ b/src/blueprint/agents/io/api/actuators/health/health_base.py @@ -1,7 +1,9 @@ -"""Abstract base class for health check providers.""" +"""Abstract base class for health check providers, and what a registered check is.""" from abc import ABC, abstractmethod +from dataclasses import dataclass +from .....component.namespace import ROOT_LABEL, qualified_entry_name from .....models.api import ComponentHealth @@ -31,3 +33,41 @@ async def health_check(self) -> ComponentHealth: Exception: Any exceptions are caught by the caller and logged. """ raise NotImplementedError() + + +@dataclass(frozen=True) +class HealthCheckEntry: + """One registered check: what it is called, **which agent it belongs to**, and the checker. + + A dict of ``name -> checker`` was what this replaces, and it lost the attribution twice + over. Two agents calling ``with_health_checker("db", ...)`` collided on one key and one + disappeared with nothing logged; and even where the keys differed, nothing recorded whose + check a failing entry was -- ``readiness_policy = "critical"`` (phase 9) has to answer + exactly that. + + So the agent is carried **as data**, and :attr:`key` is only its rendering. Recovering the + namespace by splitting the key would break on the first name containing the separator, and + ``cache:v2.sessions`` is one. + + Attributes: + name: What this check is called within its agent. + namespace: The agent it belongs to; ``""`` for the root. + checker: The checker to poll. + """ + + name: str + namespace: str + checker: HealthCheckerBase + + @property + def key(self) -> str: + """The entry name this check appears under in the readiness payload. + + The root keeps the bare name, so an existing single-agent payload is unchanged. + """ + return qualified_entry_name(self.namespace, self.name) + + @property + def agent(self) -> str: + """The owning agent, as it is written where a value is required (```` at the root).""" + return self.namespace or ROOT_LABEL diff --git a/src/blueprint/agents/io/api/actuators/health/health_cache.py b/src/blueprint/agents/io/api/actuators/health/health_cache.py index e5c37723..17000d94 100644 --- a/src/blueprint/agents/io/api/actuators/health/health_cache.py +++ b/src/blueprint/agents/io/api/actuators/health/health_cache.py @@ -4,10 +4,12 @@ import asyncio import logging +from collections.abc import Sequence from datetime import datetime from typing import TYPE_CHECKING, Any from .....models.api import ComponentHealth, ReadinessResponse +from .health_base import HealthCheckEntry if TYPE_CHECKING: from apscheduler.schedulers.asyncio import AsyncIOScheduler @@ -52,15 +54,22 @@ def __init__( ) self._last_update: datetime = datetime.now() self._lock = asyncio.Lock() - self._health_check_provider: dict[str, Any] | None = None + self._entries: tuple[HealthCheckEntry, ...] = () - def set_health_check_provider(self, provider: dict[str, Any]) -> None: - """Set the health check provider dependencies. + def set_health_entries(self, entries: Sequence[HealthCheckEntry]) -> None: + """Set the checks to poll, replacing whatever was set before. + + Entries rather than a ``name -> checker`` mapping because each one carries the agent it + belongs to as data (see :class:`HealthCheckEntry`). The payload is still keyed by + ``entry.key``, so nothing about the response shape changes; what is new is that this + object knows *whose* check each result is, which is what a per-agent readiness policy + needs (phase 9). Args: - provider: Dictionary of component_name -> HealthCheckProvider + entries: The checks to poll. The whole set, not an addition: ``ActuatorApi`` + accumulates and re-pushes, so this object holds one authoritative list. """ - self._health_check_provider = provider + self._entries = tuple(entries) async def start(self) -> None: """Start the background health check scheduler.""" @@ -108,7 +117,7 @@ async def get_health_status(self) -> ReadinessResponse: async def _run_health_checks(self) -> None: """Run all health checks and update cache.""" - if not self._health_check_provider: + if not self._entries: logger.debug("No health check providers configured") return @@ -117,23 +126,26 @@ async def _run_health_checks(self) -> None: components: dict[str, ComponentHealth] = {} # Run all health checks concurrently - tasks = {name: provider.health_check() for name, provider in self._health_check_provider.items()} - - results: list[ComponentHealth | BaseException] = await asyncio.gather(*tasks.values(), return_exceptions=True) + results: list[ComponentHealth | BaseException] = await asyncio.gather( + *(entry.checker.health_check() for entry in self._entries), return_exceptions=True + ) - for name, result in zip(tasks.keys(), results, strict=True): + for entry, result in zip(self._entries, results, strict=True): if isinstance(result, BaseException): + # The agent is named separately from the entry key, because that is the + # question asked of a group: whose check is failing, not only which one. logger.warning( - "Health check failed for %s: %s", - name, + "Health check '%s' of agent '%s' failed: %s", + entry.name, + entry.agent, result, ) - components[name] = ComponentHealth( + components[entry.key] = ComponentHealth( status="unhealthy", message=f"Check failed: {result}", ) else: - components[name] = result + components[entry.key] = result # Determine overall status all_healthy = all(component.status == "healthy" for component in components.values()) diff --git a/src/blueprint/agents/io/api/utilities/cache.py b/src/blueprint/agents/io/api/utilities/cache.py index b7a0a30d..3ec15e17 100644 --- a/src/blueprint/agents/io/api/utilities/cache.py +++ b/src/blueprint/agents/io/api/utilities/cache.py @@ -15,13 +15,21 @@ class CacheManagementApi(RestApiBase): """API for managing cache operations. - One router for the process, and every endpoint takes an optional ``?name=`` naming which - cache to act on. It defaults to :data:`DEFAULT_CACHE_NAME`, so a request that names nothing - reaches the cache a single-cache application has always had. - - A router per cache was the alternative and is wrong: caches can be registered after startup - (``registry.add_cache``), and routes cannot, so anything keyed on the set of caches at build - time would serve a stale list. Resolving the name per request has no such window. + **One router per agent, not one per process** (spec sec. 8): ``build()`` mounts one of + these for each agent that declared a cache, under that agent's ``/api/`` prefix, and + each resolves names through its own registry view -- so ``/api/orders/cache/stats`` can + report only the orders agent's caches. A single process-wide endpoint would report one + agent's keys to another, which is the collision that section exists to close. A standalone + application has one root component and keeps the ``/api/cache/*`` paths it always served. + + Within one agent, every endpoint takes an optional ``?name=`` naming which of its caches to + act on. It defaults to :data:`DEFAULT_CACHE_NAME`, so a request that names nothing reaches + the cache a single-cache application has always had. + + A router per *cache* was the alternative and is wrong: caches can be registered after + startup (``registry.add_cache``), and routes cannot, so anything keyed on the set of caches + at build time would serve a stale list. Resolving the name per request has no such window -- + and the set of *agents* is fixed at assembly, which is why the per-agent split is safe. """ def __init__(self) -> None: @@ -36,9 +44,13 @@ async def on_shutdown(self) -> None: def _cache(self, name: str) -> CacheService: """Return the cache called ``name``, or answer the request with an HTTP error. - Two distinct failures, answered differently. **503** when no cache is registered at all: - the application was built without one, the condition is not the caller's doing, and it - may resolve without a redeploy -- which is what 503 says. **404** when caches exist but + "Registered" means *this agent's*, in both branches: ``self.registry`` is this + component's namespace view, so a neighbour's cache of the same name is neither found nor + counted. + + Two distinct failures, answered differently. **503** when this agent has no cache at + all: it was built without one, the condition is not the caller's doing, and it may + resolve without a redeploy -- which is what 503 says. **404** when it has caches but none has this name: that is a bad request for a resource that is not there, and answering 503 would invite a retry that can never succeed. diff --git a/src/blueprint/agents/services/infrastructure/agent_scoped_cache.py b/src/blueprint/agents/services/infrastructure/agent_scoped_cache.py deleted file mode 100644 index 995daec7..00000000 --- a/src/blueprint/agents/services/infrastructure/agent_scoped_cache.py +++ /dev/null @@ -1,157 +0,0 @@ -"""A per-agent lens on one shared cache backend (spec sec. 8).""" - -import logging -from collections.abc import Iterator -from typing import Any - -from .cache_service import CacheService - -logger = logging.getLogger(__name__) - -AGENT_SEPARATOR = "." -"""Separates the agent from the partition it asked for, inside one cache. - -A ``.`` rather than a ``:`` because ``:`` is already the separator between the partition and the -hashed key (``cache_key_mixin._make_key``), and ``list_namespaces`` splits on the first one -- so -a ``:`` here would make ``orders:prices`` read back as the partition ``orders``. A namespace -cannot contain ``.`` (its alphabet is ``[a-z][a-z0-9_]*``), so stripping ``.`` back off is -unambiguous whatever the agent called its own partition. -""" - - -class AgentScopedCache(CacheService): - """One agent's view of a shared cache, isolating its keys from its neighbours'. - - Spec sec. 8: two independently written agents both storing under ``"sessions"`` must not - share a store the moment they are grouped. This is what enforces that, and it does so - *without a second backend*: every call has its partition prefixed with the agent's - namespace, so ``orders`` writing ``sessions`` lands in ``orders.sessions`` and ``billing`` - writing the same name lands in ``billing.sessions``. - - **Why prefix the partition rather than register a cache per agent.** A cache backend is a - filesystem directory (``DiskCacheService``) or a connection (``RedisCacheService``). One - backend per agent per name would multiply both, and on Kubernetes the directory is the - binding constraint: a pod with a read-only root filesystem can write only where a volume is - mounted, and that mount is declared in the pod spec, not discovered at runtime. Prefixing - keys means grouping agents changes no path, needs no additional mount, and keeps one - ``size_limit`` budget over one volume rather than N budgets over one. - - The agent never sees this. ``Component.registry`` hands a namespaced component its - namespace's registry view, and that view's ``get_cache`` returns this object, so a service - writing ``self.registry.cache_service.set(key, value, namespace="prices")`` is isolated - without naming a namespace. A **root** component gets the raw backend, which is also the - opt-in for a deliberately shared cache. - """ - - def __init__(self, cache: CacheService, agent: str) -> None: - """Wrap ``cache`` for ``agent``. - - Args: - cache: The shared backend. Not owned: this object never closes it. - agent: The namespace to prefix partitions with. Must not be empty -- the root - namespace uses the backend directly, so wrapping it would add a ``.`` prefix - that changes where an existing single-agent application's keys live. - - Raises: - ValueError: if ``agent`` is empty. - """ - if not agent: - raise ValueError( - "AgentScopedCache needs an agent namespace: the root namespace reads the cache backend directly, and " - "wrapping it would move every key of an existing application." - ) - super().__init__(name=f"{agent}_scoped_cache", should_register=False) - self._cache = cache - self._agent = agent - - @property - def agent(self) -> str: - """The namespace whose keys this view reads and writes.""" - return self._agent - - @property - def backend(self) -> CacheService: - """The shared cache underneath, for the framework code that owns it.""" - return self._cache - - def _scoped(self, namespace: str) -> str: - """Return the partition ``namespace`` becomes for this agent.""" - return f"{self._agent}{AGENT_SEPARATOR}{namespace}" - - def _owns(self, namespace: str) -> bool: - """Whether a partition in the shared cache belongs to this agent.""" - return namespace.startswith(f"{self._agent}{AGENT_SEPARATOR}") - - async def on_startup(self) -> None: - """Nothing to start: the backend is started by whoever registered it.""" - - async def on_shutdown(self) -> None: - """Nothing to stop: the backend outlives any one agent's view of it.""" - - def get(self, key: str | list[str] | dict[str, Any], namespace: str = "default") -> Any | None: - return self._cache.get(key, self._scoped(namespace)) - - def set( - self, - key: str | list[str] | dict[str, Any], - value: Any, - namespace: str = "default", - ttl: int | None = None, - ) -> None: - self._cache.set(key, value, self._scoped(namespace), ttl) - - def delete(self, key: str | list[str] | dict[str, Any], namespace: str = "default") -> bool: - return self._cache.delete(key, self._scoped(namespace)) - - def exists(self, key: str | list[str] | dict[str, Any], namespace: str = "default") -> bool: - return self._cache.exists(key, self._scoped(namespace)) - - def claim(self, key: str | list[str] | dict[str, Any], value: Any, namespace: str = "default", ttl: int | None = None) -> bool: - return self._cache.claim(key, value, self._scoped(namespace), ttl) - - def clear(self, namespace: str | None = None) -> None: - """Clear one of this agent's partitions, or all of them. - - ``None`` means *this agent's* partitions, never the whole cache -- the backend's own - ``clear(None)`` would take its neighbours' data with it, which is the accident this - class exists to prevent. - """ - if namespace is not None: - self._cache.clear(self._scoped(namespace)) - return - for owned in (name for name in self._cache.list_namespaces() if self._owns(name)): - self._cache.clear(owned) - - def list_namespaces(self) -> list[str]: - """This agent's partitions, named as it named them.""" - prefix = f"{self._agent}{AGENT_SEPARATOR}" - return [name.removeprefix(prefix) for name in self._cache.list_namespaces() if self._owns(name)] - - def list_values(self, namespace: str = "default", limit: int = 100, offset: int = 0) -> Iterator[Any]: - return self._cache.list_values(self._scoped(namespace), limit, offset) - - def get_stats(self) -> dict[str, Any]: - """The backend's statistics, which are process-wide rather than per agent. - - Size, hit counts and eviction are properties of the one store every agent shares, so - there is nothing per-agent to report and nothing gained by pretending otherwise. The - agent is named in the result so a reader knows whose view produced it. - """ - return {**self._cache.get_stats(), "agent": self._agent} - - def hash(self, value: str | list[str] | dict[str, Any]) -> str: - return self._cache.hash(value) - - def close(self) -> None: - """Refuse: the backend belongs to the process, not to one agent. - - Closing it here would take every other agent's cache down with it, and the caller would - have no way to know it had happened. - - Raises: - RuntimeError: always. - """ - raise RuntimeError( - f"Namespace '{self._agent}' tried to close the cache, which is shared with every other agent in this " - "process. The application closes it, through the registry that owns it." - ) diff --git a/src/blueprint/agents/services/infrastructure/cache_backend_factory.py b/src/blueprint/agents/services/infrastructure/cache_backend_factory.py index 7c6bc86f..e878dd86 100644 --- a/src/blueprint/agents/services/infrastructure/cache_backend_factory.py +++ b/src/blueprint/agents/services/infrastructure/cache_backend_factory.py @@ -4,6 +4,7 @@ import re from pathlib import PurePosixPath +from blueprint.agents.component.namespace import ROOT_NAMESPACE, construction_scope from blueprint.agents.component.registry import DEFAULT_CACHE_NAME from blueprint.agents.models.config import CacheConfig from blueprint.agents.services.infrastructure.redis_url_utils import _sanitize_redis_url @@ -12,7 +13,7 @@ logger = logging.getLogger(__name__) _ALLOWED_CACHE_NAME = re.compile(r"\A[a-z0-9][a-z0-9_.-]*\Z") -"""What a cache name may look like. See :meth:`CacheBackendFactory._validate_name`.""" +"""What a cache name may look like. See :meth:`CacheBackendFactory.validate_name`.""" class CacheBackendFactory: @@ -30,16 +31,25 @@ class CacheBackendFactory: """ @staticmethod - def create(config: CacheConfig, enable_locking: bool = True, name: str = DEFAULT_CACHE_NAME) -> CacheService: - """Create the cache called ``name``, on the backend ``config`` selects. + def create( + config: CacheConfig, enable_locking: bool = True, name: str = DEFAULT_CACHE_NAME, *, namespace: str = ROOT_NAMESPACE + ) -> CacheService: + """Create the cache called ``name`` for one agent, on the backend ``config`` selects. Args: - config: The application's cache configuration, as loaded. It is *not* pre-scoped: + config: The agent's cache configuration, as loaded. It is *not* pre-scoped: scoping is per backend and happens below. enable_locking: File-based locking, for the disk backend. name: Which cache this is. :data:`DEFAULT_CACHE_NAME` reproduces exactly what a single-cache application has always got -- same directory, same Redis keyspace, same registry name. + namespace: The agent that declared it. The root namespace stores exactly where it + always did; an agent's cache is isolated from every other agent's, including + one of the same name (spec sec. 8). It is also the namespace the backend is + *constructed* in -- a cache backend is a ``Component``, and two agents' caches + would otherwise collide on the one registry name derived from their class -- so + one argument carries every consequence of the cache belonging to that agent, + whatever scope the caller happens to be in. Returns: The cache service, already registered in the component registry under the name @@ -48,13 +58,39 @@ def create(config: CacheConfig, enable_locking: bool = True, name: str = DEFAULT Raises: ValueError: if ``name`` cannot serve as a cache name. """ - CacheBackendFactory._validate_name(name) - if config.backend == "redis": - return CacheBackendFactory._create_redis(config, enable_locking, name) - return CacheBackendFactory._create_disk(config, enable_locking, name) + CacheBackendFactory.validate_name(name) + # The bare name is what was written and what is validated; the storage name is what + # this factory isolates by, and it is composed here rather than by the caller so that + # "how a name becomes a separate store" stays in one place. + storage = CacheBackendFactory.storage_name(namespace, name) + with construction_scope(namespace): + if config.backend == "redis": + return CacheBackendFactory._create_redis(config, enable_locking, name, storage) + return CacheBackendFactory._create_disk(config, enable_locking, name, storage) @staticmethod - def _validate_name(name: str) -> None: + def storage_name(namespace: str, name: str) -> str: + """Return the name the store is isolated by: ``.``, or ``name`` at the root. + + Two agents may both declare ``sessions`` and must get **separate stores** (spec + sec. 8), so the agent has to reach the directory and the Redis prefix -- a name alone + no longer identifies a cache. The root keeps the bare name, so a single-agent + application reads and writes exactly the store it always did. + + ``.`` is the separator because it is in the cache-name alphabet + (:data:`_ALLOWED_CACHE_NAME`) and not in the namespace alphabet, so an agent's cache + name is still a legal cache name and no cache name can forge one. ``_`` would be in + both, and ``orders_sessions`` would then be ambiguous between agent ``orders`` cache + ``sessions`` and a root cache of that name. + + Args: + namespace: The agent that declared the cache; ``""`` for the root. + name: The cache's name, as declared. + """ + return name if not namespace else f"{namespace}.{name}" + + @staticmethod + def validate_name(name: str) -> None: """Reject a cache name that cannot serve as one. The name becomes a filesystem path segment and a segment of a Redis key prefix, so @@ -90,8 +126,8 @@ def _component_name(name: str) -> str | None: return None if name == DEFAULT_CACHE_NAME else f"cache_{name}" @staticmethod - def _scoped_cache_dir(config: CacheConfig, name: str) -> str: - """Return the directory the disk cache called ``name`` stores in. + def _scoped_cache_dir(config: CacheConfig, storage: str) -> str: + """Return the directory the disk cache stored as ``storage`` writes to. ``/`` -- a *subdirectory* of the configured directory and not a sibling of it, which is the only form that is always writable. A deployment may mount its volume @@ -101,13 +137,13 @@ def _scoped_cache_dir(config: CacheConfig, name: str) -> str: diskcache ignores directories it did not create, and the alternative is a path that fails in production only. """ - if name == DEFAULT_CACHE_NAME: + if storage == DEFAULT_CACHE_NAME: return config.cache_dir - return str(PurePosixPath(config.cache_dir.replace("\\", "/")) / name) + return str(PurePosixPath(config.cache_dir.replace("\\", "/")) / storage) @staticmethod - def _scoped_key_prefix(config: CacheConfig, name: str) -> str: - """Return the Redis key prefix the cache called ``name`` writes under. + def _scoped_key_prefix(config: CacheConfig, storage: str) -> str: + """Return the Redis key prefix the cache stored as ``storage`` writes under. On Redis the prefix is the whole of the separation: ``RedisCacheService`` scopes every key by ``key_prefix`` and nothing else, so two caches named ``sessions`` and ``prompts`` @@ -115,18 +151,21 @@ def _scoped_key_prefix(config: CacheConfig, name: str) -> str: backend's directory has no analogue here, so without this the name would isolate nothing at all. """ - if name == DEFAULT_CACHE_NAME: + if storage == DEFAULT_CACHE_NAME: return config.key_prefix - return f"{config.key_prefix}:{name}" if config.key_prefix else name + return f"{config.key_prefix}:{storage}" if config.key_prefix else storage @staticmethod - def _create_redis(config: CacheConfig, enable_locking: bool, name: str = DEFAULT_CACHE_NAME) -> CacheService: + def _create_redis( + config: CacheConfig, enable_locking: bool, name: str = DEFAULT_CACHE_NAME, storage: str | None = None + ) -> CacheService: + storage = name if storage is None else storage try: from blueprint.agents.services.infrastructure.redis_cache_service import RedisCacheService except ImportError as e: if config.fallback_to_local: logger.warning("Redis extra not installed, falling back to DiskCacheService: %s", e) - return CacheBackendFactory._create_disk(config, enable_locking, name) + return CacheBackendFactory._create_disk(config, enable_locking, name, storage) raise resolved_url = config.redis_url or "redis://localhost:6379/0" @@ -136,7 +175,7 @@ def _create_redis(config: CacheConfig, enable_locking: bool, name: str = DEFAULT password=config.redis_password, db=config.redis_db, tls=config.redis_tls, - key_prefix=CacheBackendFactory._scoped_key_prefix(config, name), + key_prefix=CacheBackendFactory._scoped_key_prefix(config, storage), default_ttl=config.default_ttl, fallback_to_local=config.fallback_to_local, component_name=CacheBackendFactory._component_name(name), @@ -157,19 +196,21 @@ def _create_redis(config: CacheConfig, enable_locking: bool, name: str = DEFAULT _sanitize_redis_url(resolved_url), e, ) - # The unscoped config plus the name, never the redis-scoped one: the fallback is - # a different backend and needs its own isolation -- a directory, not a prefix. - return CacheBackendFactory._create_disk(config, enable_locking, name) + # The unscoped config plus the names, never the redis-scoped one: the fallback + # is a different backend and needs its own isolation -- a directory, not a prefix. + return CacheBackendFactory._create_disk(config, enable_locking, name, storage) raise return service @staticmethod - def _create_disk(config: CacheConfig, enable_locking: bool = True, name: str = DEFAULT_CACHE_NAME) -> CacheService: + def _create_disk( + config: CacheConfig, enable_locking: bool = True, name: str = DEFAULT_CACHE_NAME, storage: str | None = None + ) -> CacheService: from blueprint.agents.services.infrastructure.cache_service import DiskCacheService return DiskCacheService( - cache_dir=CacheBackendFactory._scoped_cache_dir(config, name), + cache_dir=CacheBackendFactory._scoped_cache_dir(config, name if storage is None else storage), size_limit=config.size_limit, eviction_policy=config.eviction_policy, enable_locking=enable_locking, diff --git a/src/blueprint/agents/services/service_base.py b/src/blueprint/agents/services/service_base.py index b261bd90..411c8093 100644 --- a/src/blueprint/agents/services/service_base.py +++ b/src/blueprint/agents/services/service_base.py @@ -22,9 +22,7 @@ def __init__(self, name: str | None = None, namespace: str = ROOT_NAMESPACE, *, Forwarded to ``Component``, which validates it and qualifies the name. should_register: Whether to add this instance to the registry. Keyword-only and default ``True``, so no existing subclass changes. ``False`` is for a - service-shaped object that is not a collaborator anyone looks up -- - ``AgentScopedCache``, which is one agent's lens on a registered cache and - would otherwise register a second entry per agent. ``RestApiBase`` has taken - the same parameter since before namespaces. + service-shaped object that is not a collaborator anyone looks up. + ``RestApiBase`` has taken the same parameter since before namespaces. """ super().__init__(should_register=should_register, name=name, namespace=namespace) diff --git a/tests/unit/agents/agent/test_agent_builder.py b/tests/unit/agents/agent/test_agent_builder.py index 558b0d1a..ed96d5f4 100644 --- a/tests/unit/agents/agent/test_agent_builder.py +++ b/tests/unit/agents/agent/test_agent_builder.py @@ -6,6 +6,7 @@ from pydantic import BaseModel from blueprint.agents.agent.agent_builder import AgentBuilder +from blueprint.agents.config import Config @pytest.fixture @@ -36,30 +37,127 @@ def builder_with_model(builder: AgentBuilder, mock_registry: MagicMock) -> Agent class TestWithModelFromConfig: - def test_raises_when_no_model_name(self, builder: AgentBuilder, mock_ai_config: MagicMock) -> None: + """It records the intent; the configuration is read by build().""" + + def test_it_reads_no_configuration(self, builder: AgentBuilder, mock_config: MagicMock) -> None: + """The point of the change: there may be no configuration yet, and in a group the one + that matters is the view scoped to this agent, which only the application can supply.""" + mock_config.get_ai_config.reset_mock() + builder.with_model_from_config() + mock_config.get_ai_config.assert_not_called() + + def test_it_records_and_returns_self(self, builder: AgentBuilder) -> None: + result = builder.with_model_from_config() + assert builder._ai_config is None + assert result is builder + + def test_build_resolves_the_ai_config(self, builder: AgentBuilder, mock_ai_config: MagicMock, mock_registry: MagicMock) -> None: + builder.with_model_from_config().with_system_prompt("system") + with patch.dict( + "blueprint.agents.agent.agent_builder._CLIENT_MAP", + {"openai": MagicMock(return_value=MagicMock())}, + ): + with patch("blueprint.agents.agent.agent_builder.PromptLoader.load_prompt", return_value="prompt"): + with patch("blueprint.agents.agent.agent_builder.AgentRuntime"): + builder.build() + assert builder._ai_config is mock_ai_config + + def test_a_model_name_override_is_applied_at_build(self, builder: AgentBuilder, mock_ai_config: MagicMock) -> None: + builder.with_model_from_config(model_name="override-model") + assert mock_ai_config.model_name == "gpt-4o" + + with pytest.raises(Exception): # noqa: B017 -- the build path beyond the override is not under test + builder.build() + assert mock_ai_config.model_name == "override-model" + + def test_deprecated_runtime_name_logs_warning(self, builder: AgentBuilder, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level("WARNING"): + builder.with_model_from_config(runtime_name="ignored") + assert "Deprecation" in caplog.text + + +class TestTheModelRefusalsMovedToBuild: + """The three refusals with_model_from_config used to raise, now raised by build().""" + + def test_raises_when_no_model_name(self, builder_with_model: AgentBuilder, mock_ai_config: MagicMock) -> None: mock_ai_config.model_name = "" with pytest.raises(ValueError, match="No model name"): - builder.with_model_from_config() + builder_with_model.build() - def test_raises_when_no_provider(self, builder: AgentBuilder, mock_ai_config: MagicMock) -> None: + def test_raises_when_no_provider(self, builder_with_model: AgentBuilder, mock_ai_config: MagicMock) -> None: mock_ai_config.provider = "" with pytest.raises(ValueError, match="No provider"): - builder.with_model_from_config() + builder_with_model.build() - def test_raises_for_unsupported_provider(self, builder: AgentBuilder, mock_ai_config: MagicMock) -> None: + def test_raises_for_unsupported_provider(self, builder_with_model: AgentBuilder, mock_ai_config: MagicMock) -> None: mock_ai_config.provider = "unsupported" with pytest.raises(ValueError, match="Unsupported provider"): - builder.with_model_from_config() + builder_with_model.build() - def test_stores_ai_config_and_returns_self(self, builder: AgentBuilder, mock_ai_config: MagicMock) -> None: - result = builder.with_model_from_config() - assert builder._ai_config is mock_ai_config - assert result is builder + def test_the_refusal_names_the_runtime(self, builder_with_model: AgentBuilder, mock_ai_config: MagicMock) -> None: + mock_ai_config.model_name = "" + with pytest.raises(ValueError, match="test-agent"): + builder_with_model.build() - def test_deprecated_runtime_name_logs_warning(self, builder: AgentBuilder, caplog: pytest.LogCaptureFixture) -> None: - with caplog.at_level("WARNING"): - builder.with_model_from_config(runtime_name="ignored") - assert "Deprecation" in caplog.text + +class TestWhereTheConfigurationComesFrom: + """D6: __init__ no longer requires one, and build()'s wins because it is the scoped view.""" + + def test_it_can_be_constructed_without_one(self) -> None: + """The defect this fixes: a declaration-only main.py has no Config in scope at all.""" + assert AgentBuilder(runtime_name="orders")._config is None + + def test_build_supplies_it(self, mock_config: MagicMock, mock_ai_config: MagicMock, mock_registry: MagicMock) -> None: + mock_config.get_ai_config.return_value = mock_ai_config + agent = AgentBuilder(runtime_name="test-agent").with_model_from_config().with_system_prompt("system") + + with patch.dict( + "blueprint.agents.agent.agent_builder._CLIENT_MAP", + {"openai": MagicMock(return_value=MagicMock())}, + ): + with patch("blueprint.agents.agent.agent_builder.PromptLoader.load_prompt", return_value="prompt"): + with patch("blueprint.agents.agent.agent_builder.AgentRuntime"): + agent.build(mock_config) + + assert agent._config is mock_config + + def test_no_configuration_anywhere_is_refused(self) -> None: + agent = AgentBuilder(runtime_name="orders").with_model_from_config() + with pytest.raises(ValueError, match="has no configuration"): + agent.build() + + def test_the_refusal_names_both_places_to_pass_one(self) -> None: + agent = AgentBuilder(runtime_name="orders").with_model_from_config() + with pytest.raises(ValueError, match=r"AgentBuilder\(config\).*build\(config\)"): + agent.build() + + def test_builds_config_wins_over_the_constructors( + self, builder: AgentBuilder, mock_ai_config: MagicMock, mock_registry: MagicMock + ) -> None: + """The scoped view the application passes must beat whatever the chain closed over.""" + scoped = MagicMock(spec=Config) + scoped.for_namespace.return_value = scoped + scoped.get_ai_config.return_value = mock_ai_config + builder.with_model_from_config().with_system_prompt("system") + + with patch.dict( + "blueprint.agents.agent.agent_builder._CLIENT_MAP", + {"openai": MagicMock(return_value=MagicMock())}, + ): + with patch("blueprint.agents.agent.agent_builder.PromptLoader.load_prompt", return_value="prompt"): + with patch("blueprint.agents.agent.agent_builder.AgentRuntime"): + builder.build(scoped) + + scoped.get_ai_config.assert_called_with("test-agent") + assert builder._config is scoped + + def test_get_model_settings_without_a_configuration_is_refused(self) -> None: + with pytest.raises(ValueError, match="has no configuration"): + AgentBuilder(runtime_name="orders").get_model_settings() + + def test_the_runtime_name_is_readable_before_building(self) -> None: + """The application names the agent in its logs before it exists.""" + assert AgentBuilder(runtime_name="orders").runtime_name == "orders" # --------------------------------------------------------------------------- diff --git a/tests/unit/agents/app_builder/TESTS.md b/tests/unit/agents/app_builder/TESTS.md index 63bf2d90..d9730a7b 100644 --- a/tests/unit/agents/app_builder/TESTS.md +++ b/tests/unit/agents/app_builder/TESTS.md @@ -8,8 +8,10 @@ Test coverage for `src/blueprint/agents/app_builder.py`. | File | Class under test | What is covered | |---|---|---| -| `test_agent_registration.py` | `AgentRegistration`, `AppBuilder.with_registration` | Nothing is constructed at declaration time; declaration order, names and constructor kwargs survive the round trip; no `with_cache`; an already-built component and a non-callable are refused; root application keeps the bare registry name and a namespace qualifies it; one declaration applied twice yields two independently configured agents (each with its own scoped `Config` view); the ambient namespace is left behind afterwards; factories are deferred and called inside the namespace | -| `test_app_builder.py` | `AppBuilder` | `with_handler` (TypeError for non-subclass, class instantiated, instance accepted without re-instantiation, name propagated, returns self); `with_service`/`with_agent`/`with_scheduler`/`with_rest_api` (instance accepted, returns self); `with_cache` (enabled creates DiskCacheService, disabled skips config read); `with_health_checker` (stored pending before build, added immediately after build, multiple checkers accumulated, returns self); `build()` (event_bus=dapr/nats/unknown/no-handlers routing, EventPublishingService conditional on IO clients, pending health checkers wired, returns FastAPI instance); scheduler wiring (an event-mode scheduler is wired before the transport decision, so its tick handler is what causes a NATS client and eventing endpoint to be created; an in-process scheduler alone creates neither); the publish/consume split (`event_publishing_enabled` off means no client; on means a client with no eventing component and no `EventProcessingService`; the string form an environment variable delivers; rejections for no transport, `"sessions"` and a non-boolean; and a consuming application still publishing without the key) | +| `test_deferred_wiring.py` | `AppBuilder`, `Declaration` | Nothing is constructed or registered before `build()`; what a declaration records (kind, target, name, ambient namespace, kwargs); the declaration-order refusal and the three cases it must *not* fire on; where the configuration may be handed over and the refusal when it is given twice; the single-use guard; an application that declares nothing; an unbuilt `AgentBuilder` handed to `with_agent` and built with its agent's scoped view | +| `test_namespace_placement.py` | `AppBuilder`, `namespace_scope`, `host_agent` | A component reaches the right agent without anyone naming a namespace: the ambient scope qualifies the registry name, reaches the component and is never forwarded to its constructor; it is captured at the call, not at construction; explicit names are qualified too; an already-built instance is refused for another namespace; `host_agent` records the composition and refuses a duplicate, the root and an illegal name; and the four deleted surfaces (`AgentRegistration`, `RegisteredComponent`, `NamespaceBuilder`, `with_namespace`/`with_registration`) stay deleted | +| `test_declaration_surface.py` | `AppBuilder`, `Declaration.replay` | The gate that keeps the declaration API and the group's replay in agreement: every public `with_*` is discovered rather than listed (a new one fails the file until it has a sample call), and per method -- one declaration recorded, the registry untouched, `replay` onto a fresh builder reproducing the declaration exactly, a replay inside `namespace_scope` taking the namespace from the scope, and the recorded `kind` having a `with_` to replay onto; plus the irregular positional name of `with_health_checker` surviving a replay | +| `test_app_builder.py` | `AppBuilder` | `with_handler` (TypeError for non-subclass, class instantiated, instance accepted without re-instantiation, name propagated, returns self); `with_service`/`with_agent`/`with_scheduler`/`with_rest_api` (instance accepted, returns self); `with_cache` (enabled creates DiskCacheService, disabled skips config read); `with_health_checker` (recorded as a `Declaration` before build, added straight to the actuator after build, several accumulate, a checker is never constructed, returns self); `build()` (event_bus=dapr/nats/unknown/no-handlers routing, EventPublishingService conditional on IO clients, pending health checkers wired, returns FastAPI instance); scheduler wiring (an event-mode scheduler is wired before the transport decision, so its tick handler is what causes a NATS client and eventing endpoint to be created; an in-process scheduler alone creates neither); the publish/consume split (`event_publishing_enabled` off means no client; on means a client with no eventing component and no `EventProcessingService`; the string form an environment variable delivers; rejections for no transport, `"sessions"` and a non-boolean; and a consuming application still publishing without the key) | --- @@ -19,7 +21,7 @@ Test coverage for `src/blueprint/agents/app_builder.py`. | Fixture | Scope | Purpose | |---|---|---| -| `reset_component_state` | function / **autouse** | Patches `CorrelationContextProvider`, resets `Component.shared_config` and `Component.shared_registry` after every test | +| `reset_component_state` | function / **autouse** | Patches `CorrelationContextProvider`, then calls `Component.reset_shared_state()` after every test | | `mock_config` | function | `MagicMock(spec=Config)` injected via `Component.configure` | | `mock_registry` | function | `MagicMock(spec=Registry)` stored in `Component.shared_registry` | | `builder` | function | `AppBuilder(mock_config)` — for fluent-setter tests where shared_config is pre-set | @@ -31,6 +33,10 @@ Test coverage for `src/blueprint/agents/app_builder.py`. `StubHandler` is defined in `conftest.py` as a minimal concrete `EventHandlerBase` for tests that need to pass a real handler type to `with_handler`. +`realize(builder)` is a helper (not a fixture) that runs `build()`'s own replay pass on its own. A `with_*()` call records rather than constructs, so a test asserting on the registry has to say when construction happens; `build()` would do it but also creates the actuator, the root API and a FastAPI application, which would drown the one or two components the test is about. + +**Group assembly is tested in `tests/unit/agents/test_agent_group.py`**, not here: collection is `AgentGroup`'s job and an `AppBuilder` never learns it can be collected. + --- ## Decisions diff --git a/tests/unit/agents/app_builder/conftest.py b/tests/unit/agents/app_builder/conftest.py index 8cbfc189..40829936 100644 --- a/tests/unit/agents/app_builder/conftest.py +++ b/tests/unit/agents/app_builder/conftest.py @@ -125,6 +125,19 @@ def all_build_mocks(): ) +def realize(builder: AppBuilder) -> AppBuilder: + """Construct everything ``builder`` has recorded, and nothing else. + + ``with_*()`` records rather than constructs, so a test asserting on the registry has to say + when construction happens. ``build()`` would do it, but it also creates the actuator, the + root API and a FastAPI application, and those components would drown the one or two the + test is about. This runs the same replay pass ``build()`` runs, on its own, against the + configuration the builder was given. + """ + builder._construct_declarations(builder._require_config()) + return builder + + def wire_empty_registry(mock_registry: MagicMock) -> None: """Set all registry collection methods to return empty lists/False.""" mock_registry.get_event_handler.return_value = [] diff --git a/tests/unit/agents/app_builder/test_agent_registration.py b/tests/unit/agents/app_builder/test_agent_registration.py deleted file mode 100644 index 5b4f2afc..00000000 --- a/tests/unit/agents/app_builder/test_agent_registration.py +++ /dev/null @@ -1,217 +0,0 @@ -"""Unit tests for ``AgentRegistration`` and ``AppBuilder.with_registration``. - -What these are really testing is the constraint the design exists for: one declaration, no -namespace anywhere in it or in the components it names, applied either alone or once per agent. -""" - -from pathlib import Path -from typing import Any - -import pytest - -from blueprint.agents.app_builder import AgentRegistration, AppBuilder -from blueprint.agents.component.component import Component -from blueprint.agents.component.namespace import ROOT_NAMESPACE, current_namespace -from blueprint.agents.config import Config -from blueprint.agents.io.api.rest_api_base import RestApiBase -from blueprint.agents.services.service_base import ServiceBase - -from .conftest import StubHandler - - -class OrderService(ServiceBase): - """A service written the way a project writes one: no namespace, no arguments.""" - - async def on_startup(self) -> None: - pass - - async def on_shutdown(self) -> None: - pass - - -class ConfiguredService(ServiceBase): - """A service that takes constructor arguments, to check they survive the round trip.""" - - def __init__(self, retries: int = 0) -> None: - super().__init__() - self.retries = retries - - async def on_startup(self) -> None: - pass - - async def on_shutdown(self) -> None: - pass - - -class OrderApi(RestApiBase): - async def on_startup(self) -> None: - pass - - async def on_shutdown(self) -> None: - pass - - -@pytest.fixture -def two_agent_config(tmp_path: Path) -> Config: - """A settings tree with a root and two agents, injected as the shared component config.""" - settings = tmp_path / "settings.toml" - content = """ - [development] - app_name = "root-app" - app_port = 8000 - model_name = "root-model" - - [development.orders] - app_name = "orders" - model_name = "orders-model" - - [development.billing] - app_name = "billing" - """ - settings.write_text(content.replace("\n ", "\n")) - return Config(settings_files=[str(settings)], root_path=str(tmp_path)) - - -def service_names() -> list[str]: - registry = Component.shared_registry - assert registry is not None - return sorted(registry.get_component_names_by_type(ServiceBase)) - - -class TestDeclaration: - def test_nothing_is_built_when_a_component_is_declared(self) -> None: - """The point of a registration: a component built now would predate every namespace.""" - AgentRegistration().with_service(OrderService) - assert Component.shared_registry is None - - def test_declarations_are_kept_in_order(self) -> None: - """Handler priority and scheduler wiring read this order.""" - registration = AgentRegistration().with_handler(StubHandler).with_service(OrderService) - assert [(entry.kind, entry.target) for entry in registration.components] == [ - ("handler", StubHandler), - ("service", OrderService), - ] - - def test_the_fluent_calls_return_the_same_registration(self) -> None: - registration = AgentRegistration() - assert registration.with_service(OrderService) is registration - - def test_constructor_arguments_and_names_are_stored(self) -> None: - registration = AgentRegistration().with_service(ConfiguredService, name="orders_svc", retries=3) - entry = registration.components[0] - assert (entry.name, entry.kwargs) == ("orders_svc", {"retries": 3}) - - def test_there_is_no_with_cache(self) -> None: - """A cache is process-wide and belongs to the AppBuilder that hosts the group.""" - assert not hasattr(AgentRegistration(), "with_cache") - - -class TestRejections: - def test_an_already_built_component_is_refused(self, two_agent_config: Config) -> None: - """It was built before any namespace existed, so it belongs to the root whoever declared it.""" - Component.configure(two_agent_config) - service = OrderService() - with pytest.raises(TypeError, match="as an instance"): - AgentRegistration().with_service(service) - - def test_the_refusal_names_the_class_and_the_method(self, two_agent_config: Config) -> None: - Component.configure(two_agent_config) - with pytest.raises(TypeError, match=r"with_rest_api\(OrderApi, \.\.\.\)"): - AgentRegistration().with_rest_api(OrderApi()) - - @pytest.mark.parametrize("target", ["OrderService", 42, None]) - def test_something_that_cannot_be_called_is_refused(self, target: Any) -> None: - with pytest.raises(TypeError, match="component class or a callable"): - AgentRegistration().with_handler(target) - - -class TestApplyToOneAgent: - def test_a_single_agent_application_registers_at_the_root(self, two_agent_config: Config) -> None: - """Unchanged naming: this is what an existing project gets, whichever way it declares.""" - AppBuilder(two_agent_config).with_registration(AgentRegistration().with_service(OrderService)) - assert service_names() == ["order_service"] - - def test_applying_under_a_namespace_qualifies_the_name(self, two_agent_config: Config) -> None: - AppBuilder(two_agent_config).with_registration(AgentRegistration().with_service(OrderService), "orders") - assert service_names() == ["orders_order_service"] - - def test_with_registration_returns_the_builder(self, two_agent_config: Config) -> None: - builder = AppBuilder(two_agent_config) - assert builder.with_registration(AgentRegistration()) is builder - - def test_constructor_arguments_reach_the_component(self, two_agent_config: Config) -> None: - AppBuilder(two_agent_config).with_registration(AgentRegistration().with_service(ConfiguredService, retries=3)) - registry = Component.shared_registry - assert registry is not None - assert registry.get_component("configured_service").retries == 3 - - def test_an_explicit_name_is_forwarded(self, two_agent_config: Config) -> None: - AppBuilder(two_agent_config).with_registration(AgentRegistration().with_service(OrderService, name="svc")) - assert service_names() == ["svc"] - - def test_an_illegal_namespace_is_refused(self, two_agent_config: Config) -> None: - with pytest.raises(ValueError, match="legal namespace"): - AppBuilder(two_agent_config).with_registration(AgentRegistration().with_service(OrderService), "Orders") - - -class TestOneDeclarationTwoAgents: - """The constraint, end to end: the same object applied twice, under two namespaces.""" - - def test_one_declaration_becomes_two_independently_named_agents(self, two_agent_config: Config) -> None: - registration = AgentRegistration().with_service(OrderService) - builder = AppBuilder(two_agent_config) - - builder.with_registration(registration, "orders") - builder.with_registration(registration, "billing") - - assert service_names() == ["billing_order_service", "orders_order_service"] - - def test_each_agent_reads_its_own_configuration(self, two_agent_config: Config) -> None: - """C5 through the ambient namespace: neither the service nor the declaration mentions one.""" - registration = AgentRegistration().with_service(OrderService) - builder = AppBuilder(two_agent_config) - builder.with_registration(registration, "orders") - builder.with_registration(registration, "billing") - Component.configure(two_agent_config) - - registry = Component.shared_registry - assert registry is not None - orders = registry.get_component("orders_order_service") - billing = registry.get_component("billing_order_service") - - assert (orders.config.get("model_name"), billing.config.get("model_name")) == ("orders-model", "root-model") - assert (orders.config.get("app_name"), billing.config.get("app_name")) == ("orders", "billing") - - def test_the_namespace_is_left_behind_afterwards(self, two_agent_config: Config) -> None: - """Otherwise the builder's own root components would join the last agent applied.""" - AppBuilder(two_agent_config).with_registration(AgentRegistration().with_service(OrderService), "orders") - assert current_namespace() == ROOT_NAMESPACE - - -class TestFactories: - def test_a_factory_is_called_inside_the_namespace(self, two_agent_config: Config) -> None: - """The form the fluent AgentBuilder needs: a chain that cannot be a class plus kwargs.""" - registration = AgentRegistration().with_service(lambda: ConfiguredService(retries=7)) - - AppBuilder(two_agent_config).with_registration(registration, "orders") - - registry = Component.shared_registry - assert registry is not None - built = registry.get_component("orders_configured_service") - assert (built.namespace, built.retries) == ("orders", 7) - - def test_a_factory_sees_the_ambient_namespace_while_it_runs(self, two_agent_config: Config) -> None: - seen: list[str] = [] - - def build_service() -> OrderService: - seen.append(current_namespace()) - return OrderService() - - AppBuilder(two_agent_config).with_registration(AgentRegistration().with_service(build_service), "orders") - - assert seen == ["orders"] - - def test_a_factory_is_not_called_at_declaration_time(self) -> None: - calls: list[int] = [] - AgentRegistration().with_service(lambda: calls.append(1) or OrderService()) - assert calls == [] diff --git a/tests/unit/agents/app_builder/test_app_builder.py b/tests/unit/agents/app_builder/test_app_builder.py index e8aba902..7788887a 100644 --- a/tests/unit/agents/app_builder/test_app_builder.py +++ b/tests/unit/agents/app_builder/test_app_builder.py @@ -6,8 +6,9 @@ import pytest from blueprint.agents.app_builder import AppBuilder +from blueprint.agents.component.namespace import namespace_scope from blueprint.agents.services.service_base import ServiceBase -from tests.unit.agents.app_builder.conftest import StubHandler, wire_empty_registry +from tests.unit.agents.app_builder.conftest import StubHandler, realize, wire_empty_registry # --------------------------------------------------------------------------- # logging ownership @@ -53,9 +54,14 @@ class NotAHandler: builder.with_handler(NotAHandler) def test_class_is_instantiated_and_registered(self, builder: AppBuilder, mock_registry: MagicMock) -> None: - builder.with_handler(StubHandler) + realize(builder.with_handler(StubHandler)) mock_registry.add_component.assert_called_once() + def test_a_class_is_not_instantiated_before_build(self, builder: AppBuilder, mock_registry: MagicMock) -> None: + """Recording is the whole of a with_*() call: a component built now predates every namespace.""" + builder.with_handler(StubHandler) + mock_registry.add_component.assert_not_called() + def test_instance_is_accepted_without_re_instantiation(self, builder: AppBuilder, mock_registry: MagicMock) -> None: instance = StubHandler() mock_registry.reset_mock() # clear the add_component call from StubHandler() @@ -63,7 +69,7 @@ def test_instance_is_accepted_without_re_instantiation(self, builder: AppBuilder mock_registry.add_component.assert_not_called() def test_name_set_on_created_instance(self, builder: AppBuilder, mock_registry: MagicMock) -> None: - builder.with_handler(StubHandler, name="custom_handler") + realize(builder.with_handler(StubHandler, name="custom_handler")) mock_registry.update_component_name.assert_called_once() def test_returns_self_for_chaining(self, builder: AppBuilder, mock_registry: MagicMock) -> None: @@ -133,16 +139,34 @@ def test_returns_self_for_chaining(self, builder: AppBuilder, mock_config: Magic class TestWithHealthChecker: - def test_stored_pending_before_build(self, builder: AppBuilder) -> None: + def test_recorded_before_build(self, builder: AppBuilder) -> None: + """Recorded like every other declaration, so a group carries it over with the rest.""" checker = MagicMock() builder.with_health_checker("my_service", checker) - assert builder._custom_health_checkers["my_service"] is checker + declaration = builder.declarations[0] + assert (declaration.kind, declaration.name, declaration.target) == ("health_checker", "my_service", checker) def test_multiple_checkers_accumulated_before_build(self, builder: AppBuilder) -> None: a, b = MagicMock(), MagicMock() builder.with_health_checker("svc_a", a) builder.with_health_checker("svc_b", b) - assert len(builder._custom_health_checkers) == 2 + realize(builder) + assert [(entry.name, entry.checker) for entry in builder._health_checkers] == [("svc_a", a), ("svc_b", b)] + + def test_a_checker_is_never_constructed(self, builder: AppBuilder) -> None: + """A checker is not a Component: the object declared is the object used.""" + checker = MagicMock() + realize(builder.with_health_checker("db", checker)) + assert builder._health_checkers[0].checker is checker + + def test_a_checker_carries_the_agent_it_was_declared_in(self, builder: AppBuilder) -> None: + """D4: the agent travels with the checker as data, not folded into its name.""" + with namespace_scope("orders"): + builder.with_health_checker("db", MagicMock()) + realize(builder) + + entry = builder._health_checkers[0] + assert (entry.name, entry.namespace, entry.key) == ("db", "orders", "orders.db") def test_added_immediately_after_build(self, builder: AppBuilder) -> None: mock_actuator = MagicMock() @@ -151,7 +175,8 @@ def test_added_immediately_after_build(self, builder: AppBuilder) -> None: checker = MagicMock() builder.with_health_checker("live_service", checker) - mock_actuator.add_health_providers.assert_called_once_with({"live_service": checker}) + entries = mock_actuator.add_health_providers.call_args[0][0] + assert [(entry.name, entry.namespace, entry.checker) for entry in entries] == [("live_service", "", checker)] def test_returns_self_for_chaining(self, builder: AppBuilder) -> None: assert builder.with_health_checker("svc", MagicMock()) is builder @@ -310,8 +335,8 @@ def test_custom_health_checkers_wired_during_build( actuator_instance = all_build_mocks.actuator.return_value actuator_instance.add_health_providers.assert_called_once() - call_kwargs = actuator_instance.add_health_providers.call_args[0][0] - assert "my_svc" in call_kwargs + entries = actuator_instance.add_health_providers.call_args[0][0] + assert "my_svc" in [entry.key for entry in entries] # ---------------------------------------------------------------------- diff --git a/tests/unit/agents/app_builder/test_build_namespaces.py b/tests/unit/agents/app_builder/test_build_namespaces.py index 38ce6c83..35ef68eb 100644 --- a/tests/unit/agents/app_builder/test_build_namespaces.py +++ b/tests/unit/agents/app_builder/test_build_namespaces.py @@ -12,10 +12,10 @@ import pytest -from blueprint.agents.app_builder import AgentRegistration, AppBuilder +from blueprint.agents.app_builder import AppBuilder from blueprint.agents.clients.io.nats_client import NATSClient from blueprint.agents.component.component import Component -from blueprint.agents.component.namespace import ROOT_NAMESPACE +from blueprint.agents.component.namespace import ROOT_NAMESPACE, namespace_scope from blueprint.agents.config import Config from blueprint.agents.handler.event_handler_base import EventHandlerBase from blueprint.agents.io.api.eventing.nats import NatsEventing @@ -98,11 +98,30 @@ def build(builder: AppBuilder) -> None: builder.build() +def hosting(config: Config, **agents: AppBuilder) -> AppBuilder: + """The root builder ``AgentGroup.assemble`` would produce, kept in hand. + + These cases are about what ``build()`` wires *per agent*, and two of the things it wires -- + the transport endpoints -- register nowhere, so the assertions need the builder itself. + ``assemble()`` returns the application and keeps its builder private, so the loop below is + the one inside it, driven through the same public ``Declaration.replay``. The group's own + behaviour is tested in ``tests/unit/agents/test_agent_group.py``. + + Keyword arguments rather than a dict so an agent's name reads as a name at the call site, + which is how a group file names it too. + """ + root = AppBuilder(config) + for namespace, declaration in agents.items(): + root.host_agent(namespace) + with namespace_scope(namespace): + for entry in declaration.declarations: + entry.replay(root) + return root + + class TestOneClientPerConsumingAgent: def test_each_agent_gets_its_own_client(self, nats_config: Config) -> None: - builder = AppBuilder(nats_config) - builder.with_namespace("orders", registration=AgentRegistration().with_handler(OrderHandler)) - builder.with_namespace("billing", registration=AgentRegistration().with_handler(BillingHandler)) + builder = hosting(nats_config, orders=AppBuilder().with_handler(OrderHandler), billing=AppBuilder().with_handler(BillingHandler)) build(builder) @@ -117,8 +136,7 @@ def test_a_single_agent_application_gets_one_client_at_the_root(self, nats_confi def test_the_root_gets_no_client_when_it_has_nothing(self, nats_config: Config) -> None: """A grouped application usually has nothing at the root, and then the root pass is a no-op.""" - builder = AppBuilder(nats_config) - builder.with_namespace("orders", registration=AgentRegistration().with_handler(OrderHandler)) + builder = hosting(nats_config, orders=AppBuilder().with_handler(OrderHandler)) build(builder) @@ -126,17 +144,14 @@ def test_the_root_gets_no_client_when_it_has_nothing(self, nats_config: Config) def test_an_agent_that_neither_consumes_nor_publishes_gets_no_client(self, nats_config: Config) -> None: """Spec sec. 6: a connection for it is a readiness dependency on traffic that does not exist.""" - builder = AppBuilder(nats_config) - builder.with_namespace("orders", registration=AgentRegistration().with_handler(OrderHandler)) - builder.with_namespace("billing", registration=AgentRegistration().with_service(QuietService)) + builder = hosting(nats_config, orders=AppBuilder().with_handler(OrderHandler), billing=AppBuilder().with_service(QuietService)) build(builder) assert registry_names(NATSClient) == ["orders_nats_client"] def test_a_publish_only_agent_gets_a_client_and_no_endpoint(self, nats_config: Config) -> None: - builder = AppBuilder(nats_config) - builder.with_namespace("reporting", registration=AgentRegistration().with_service(QuietService)) + builder = hosting(nats_config, reporting=AppBuilder().with_service(QuietService)) build(builder) @@ -154,9 +169,7 @@ def test_publishing_is_opted_into_per_agent(self, nats_config: Config) -> None: class TestOneEndpointPerConsumingAgent: def test_each_consuming_agent_gets_an_endpoint(self, nats_config: Config) -> None: - builder = AppBuilder(nats_config) - builder.with_namespace("orders", registration=AgentRegistration().with_handler(OrderHandler)) - builder.with_namespace("billing", registration=AgentRegistration().with_handler(BillingHandler)) + builder = hosting(nats_config, orders=AppBuilder().with_handler(OrderHandler), billing=AppBuilder().with_handler(BillingHandler)) build(builder) @@ -177,9 +190,7 @@ def test_an_application_with_no_handler_gets_none(self, nats_config: Config) -> assert registry_names(NATSClient) == [] async def test_each_endpoint_subscribes_only_its_own_topics(self, nats_config: Config) -> None: - builder = AppBuilder(nats_config) - builder.with_namespace("orders", registration=AgentRegistration().with_handler(OrderHandler)) - builder.with_namespace("billing", registration=AgentRegistration().with_handler(BillingHandler)) + builder = hosting(nats_config, orders=AppBuilder().with_handler(OrderHandler), billing=AppBuilder().with_handler(BillingHandler)) build(builder) with patch.object(NATSClient, "subscribe", new_callable=AsyncMock) as subscribe: @@ -192,9 +203,7 @@ async def test_each_endpoint_subscribes_only_its_own_topics(self, nats_config: C class TestOnePublishingServicePerAgentWithAClient: def test_each_agent_with_a_client_gets_one(self, nats_config: Config) -> None: - builder = AppBuilder(nats_config) - builder.with_namespace("orders", registration=AgentRegistration().with_handler(OrderHandler)) - builder.with_namespace("billing", registration=AgentRegistration().with_handler(BillingHandler)) + builder = hosting(nats_config, orders=AppBuilder().with_handler(OrderHandler), billing=AppBuilder().with_handler(BillingHandler)) build(builder) @@ -209,9 +218,7 @@ def test_a_single_agent_application_gets_one_at_the_root(self, nats_config: Conf assert registry_names(EventPublishingService) == ["event_publishing_service"] def test_an_agent_without_a_client_gets_none(self, nats_config: Config) -> None: - builder = AppBuilder(nats_config) - builder.with_namespace("orders", registration=AgentRegistration().with_handler(OrderHandler)) - builder.with_namespace("billing", registration=AgentRegistration().with_service(QuietService)) + builder = hosting(nats_config, orders=AppBuilder().with_handler(OrderHandler), billing=AppBuilder().with_service(QuietService)) build(builder) @@ -223,8 +230,7 @@ def test_a_single_agent_application_hosts_the_root_only(self, nats_config: Confi assert AppBuilder(nats_config).hosted_namespaces == (ROOT_NAMESPACE,) def test_the_root_comes_first_and_the_agents_in_order(self, nats_config: Config) -> None: - builder = AppBuilder(nats_config) - builder.with_namespace("orders").end().with_namespace("billing").end() + builder = hosting(nats_config, orders=AppBuilder(), billing=AppBuilder()) assert builder.hosted_namespaces == (ROOT_NAMESPACE, "orders", "billing") @@ -243,8 +249,52 @@ def test_it_names_the_agent_that_asked(self, tmp_path: Path) -> None: event_publishing_enabled = true """.replace("\n ", "\n "), ) - builder = AppBuilder(config) - builder.with_namespace("reporting", registration=AgentRegistration().with_service(QuietService)) + builder = hosting(config, reporting=AppBuilder().with_service(QuietService)) with pytest.raises(ValueError, match="'reporting'"): build(builder) + + +def entry_keys(builder: AppBuilder) -> list[str]: + """The readiness entry names ``build()`` wired, in order.""" + assert builder._actuator_api is not None + return [entry.key for entry in builder._actuator_api.health_entries] + + +class TestEveryReadinessEntryNamesItsAgent: + """D4: a check is attributed to the agent it belongs to, as data, and rendered from it. + + Against real components, because the interesting entries are the ones ``build()`` derives + from what it wired -- a client per agent -- rather than the ones a test hands it. + """ + + def test_each_agents_client_is_its_own_entry(self, nats_config: Config) -> None: + builder = hosting(nats_config, orders=AppBuilder().with_handler(OrderHandler), billing=AppBuilder().with_handler(BillingHandler)) + + build(builder) + + assert {"orders.nats_client", "billing.nats_client"} <= set(entry_keys(builder)) + + def test_the_key_does_not_carry_the_agent_twice(self, nats_config: Config) -> None: + """The registry name is already qualified with '_', so passing it would double up.""" + builder = hosting(nats_config, orders=AppBuilder().with_handler(OrderHandler)) + + build(builder) + + assert "orders.orders_nats_client" not in entry_keys(builder) + + def test_a_single_agent_application_keeps_the_entry_it_had(self, nats_config: Config) -> None: + builder = AppBuilder(nats_config).with_handler(OrderHandler) + + build(builder) + + assert "nats_client" in entry_keys(builder) + + def test_the_agent_is_available_without_splitting_the_key(self, nats_config: Config) -> None: + """What phase 9's readiness_policy needs: whose check this is, as a value.""" + builder = hosting(nats_config, orders=AppBuilder().with_handler(OrderHandler)) + + build(builder) + + entries = {entry.key: entry for entry in builder._actuator_api.health_entries} # type: ignore[union-attr] + assert entries["orders.nats_client"].namespace == "orders" diff --git a/tests/unit/agents/app_builder/test_declaration_surface.py b/tests/unit/agents/app_builder/test_declaration_surface.py new file mode 100644 index 00000000..9d2e9ccc --- /dev/null +++ b/tests/unit/agents/app_builder/test_declaration_surface.py @@ -0,0 +1,216 @@ +"""The declaration surface and ``AgentGroup``'s replay must agree, and cannot drift apart. + +Adding a capability to the framework is now **one** edit -- a ``with_*`` method on +``AppBuilder`` -- which is the whole point of phase 8b. But the group still has to be able to +move a recorded call from one builder to another, and ``Declaration.replay`` does that by +resolving ``with_`` with ``getattr``. So there are exactly two ways for the two halves to +part company: + +- a ``with_*`` method records a ``kind`` that no method answers to, and replay dies with an + ``AttributeError`` at assembly -- in a group, never standalone; +- a ``with_*`` method whose replayed arguments do not reproduce the call, so an agent is + assembled from a declaration that says something slightly different from what its ``main.py`` + said. + +Neither is visible in a single-agent application, and both would be found in production by +somebody grouping two agents. Hence a gate: every public declaration method is called +reflectively, its declaration is replayed onto a fresh builder, and the result must be equal to +what was recorded. + +**A new ``with_*`` method fails this file until it is listed in ``SAMPLE_CALLS``.** That is +deliberate -- the list is what proves the method was thought about -- and the failure message +says so. +""" + +from typing import Any +from unittest.mock import MagicMock + +import pytest + +from blueprint.agents.agent.agent_builder import AgentBuilder +from blueprint.agents.app_builder import AppBuilder, Declaration +from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import namespace_scope +from blueprint.agents.io.api.actuators.health.health_base import HealthCheckerBase +from blueprint.agents.io.api.rest_api_base import RestApiBase +from blueprint.agents.io.api.scheduling.scheduler import SchedulerBase +from blueprint.agents.models.api import ComponentHealth +from blueprint.agents.services.service_base import ServiceBase + +from .conftest import StubHandler + + +class StubService(ServiceBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class StubApi(RestApiBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class StubScheduler(SchedulerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class StubChecker(HealthCheckerBase): + async def health_check(self) -> ComponentHealth: + return ComponentHealth(status="healthy", message="ok") + + +SAMPLE_CALLS: dict[str, tuple[tuple[Any, ...], dict[str, Any]]] = { + "with_handler": ((StubHandler,), {"name": "a_handler"}), + "with_service": ((StubService,), {"name": "a_service"}), + "with_agent": ((AgentBuilder(runtime_name="a_runtime"),), {}), + "with_scheduler": ((StubScheduler,), {"name": "a_scheduler"}), + "with_rest_api": ((StubApi,), {"name": "an_api"}), + "with_cache": ((), {"name": "a_cache"}), + "with_health_checker": (("a_check", StubChecker()), {}), +} +"""One call per declaration method, as a project would write it. + +Keyword arguments are given where the method takes a name, because a name is the part replay is +most able to lose: ``with_health_checker`` takes it positionally and every other method takes it +as a keyword, and that irregularity lives in exactly one branch of ``Declaration.replay``. +""" + + +def declaration_methods() -> list[str]: + """Every public declaration method on ``AppBuilder``, discovered rather than listed. + + Discovered, so that a method added without a sample call fails this file instead of being + quietly untested. The ``with_`` prefix is what makes a method a declaration: ``host_agent`` + records no ``Declaration`` -- it states a fact about the process -- and is not one of these. + """ + return sorted(name for name in dir(AppBuilder) if name.startswith("with_")) + + +def registry_contents() -> dict[str, object]: + """Every component in the shared registry, or nothing when there is not even a registry yet. + + Read through ``_components`` because there is no public "list everything" method, and there + should not be: C6 keeps a process-wide view out of reach of the components themselves. + """ + registry = Component.shared_registry + return dict(registry._components) if registry is not None else {} + + +class TestEveryDeclarationMethodIsCovered: + def test_the_sample_calls_name_every_method(self) -> None: + missing = set(declaration_methods()) - set(SAMPLE_CALLS) + assert not missing, ( + f"{', '.join(sorted(missing))} is a declaration method with no sample call in this file. Add one: the " + "list is what proves a new with_* was checked against the group's replay, which is the only place a " + "recorder and its API can drift apart." + ) + + def test_the_sample_calls_name_nothing_that_is_gone(self) -> None: + extra = set(SAMPLE_CALLS) - set(declaration_methods()) + assert not extra, f"{', '.join(sorted(extra))} no longer exists on AppBuilder; remove the sample call." + + +@pytest.mark.parametrize("method", declaration_methods()) +class TestRecordingAndReplayAgree: + def test_the_call_records_exactly_one_declaration(self, mock_config: MagicMock, method: str) -> None: + builder = AppBuilder() + arguments, keywords = SAMPLE_CALLS[method] + + getattr(builder, method)(*arguments, **keywords) + + assert len(builder.declarations) == 1 + + def test_nothing_is_constructed_by_recording_it(self, mock_config: MagicMock, method: str) -> None: + """Collect, then wire: a component built during accumulation belongs to the root for ever.""" + builder = AppBuilder() + arguments, keywords = SAMPLE_CALLS[method] + before = registry_contents() + + getattr(builder, method)(*arguments, **keywords) + + assert registry_contents() == before + + def test_replay_reproduces_the_declaration(self, mock_config: MagicMock, method: str) -> None: + """What a group does to move an agent's calls onto the root builder, and it must be lossless.""" + source = AppBuilder() + arguments, keywords = SAMPLE_CALLS[method] + getattr(source, method)(*arguments, **keywords) + + target = AppBuilder() + for declaration in source.declarations: + declaration.replay(target) + + assert target.declarations == source.declarations + + def test_replay_takes_the_namespace_from_the_scope_it_runs_in(self, mock_config: MagicMock, method: str) -> None: + """The ambient mechanism: no namespace is passed, and none appears in any signature.""" + source = AppBuilder() + arguments, keywords = SAMPLE_CALLS[method] + getattr(source, method)(*arguments, **keywords) + + target = AppBuilder() + with namespace_scope("orders"): + for declaration in source.declarations: + declaration.replay(target) + + assert [entry.namespace for entry in target.declarations] == ["orders"] + assert [entry.namespace for entry in source.declarations] == [""] + + def test_the_recorded_kind_has_a_method_to_replay_onto(self, mock_config: MagicMock, method: str) -> None: + """``Declaration.replay`` resolves ``with_`` with getattr, and this is that contract.""" + builder = AppBuilder() + arguments, keywords = SAMPLE_CALLS[method] + + getattr(builder, method)(*arguments, **keywords) + + for declaration in builder.declarations: + assert hasattr(AppBuilder, f"with_{declaration.kind}"), ( + f"{method}() records kind '{declaration.kind}', but there is no with_{declaration.kind}() for " + "Declaration.replay to call. A group would fail at assembly with an AttributeError while the same " + "declaration worked standalone." + ) + + +class TestTheNameSurvivesTheIrregularSignature: + """``with_health_checker(name, checker)`` is the one method whose name is positional.""" + + def test_a_replayed_checker_keeps_its_name(self, mock_config: MagicMock) -> None: + checker = StubChecker() + source = AppBuilder().with_health_checker("db", checker) + + target = AppBuilder() + for declaration in source.declarations: + declaration.replay(target) + + recorded = target.declarations[0] + assert (recorded.name, recorded.target) == ("db", checker) + + def test_a_replayed_component_keeps_its_name_override(self, mock_config: MagicMock) -> None: + source = AppBuilder().with_service(StubService, name="planner") + + target = AppBuilder() + for declaration in source.declarations: + declaration.replay(target) + + assert target.declarations[0].name == "planner" + + def test_a_replayed_declaration_keeps_its_constructor_arguments(self, mock_config: MagicMock) -> None: + source = AppBuilder().with_cache(True, False, name="sessions") + + target = AppBuilder() + for declaration in source.declarations: + declaration.replay(target) + + assert target.declarations[0] == Declaration( + kind="cache", target=None, name="sessions", namespace="", kwargs={"enable_locking": False} + ) diff --git a/tests/unit/agents/app_builder/test_deferred_wiring.py b/tests/unit/agents/app_builder/test_deferred_wiring.py new file mode 100644 index 00000000..5a655629 --- /dev/null +++ b/tests/unit/agents/app_builder/test_deferred_wiring.py @@ -0,0 +1,348 @@ +"""Unit tests for ``AppBuilder`` recording rather than constructing. + +The property under test is the one the whole builder unification rests on: a ``with_*()`` call +stores what to build, and ``build()`` is the only thing that builds it. Everything else here -- +the single-use guard, where the configuration may be handed over, the declaration-order refusal +-- follows from that one change and is pinned so it cannot drift back. +""" + +from pathlib import Path +from unittest.mock import MagicMock + +import pytest + +from blueprint.agents.agent.agent_builder import AgentBuilder +from blueprint.agents.app_builder import AppBuilder, Declaration +from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import namespace_scope +from blueprint.agents.config import Config +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.events import GenericCloudEvent +from blueprint.agents.services.service_base import ServiceBase + +from .conftest import StubHandler, realize + + +class OrderService(ServiceBase): + """A service written the way a project writes one: no namespace, no arguments.""" + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class CountingService(ServiceBase): + """Counts its own constructions, which is how 'nothing is built yet' is observable.""" + + built = 0 + + def __init__(self) -> None: + super().__init__() + CountingService.built += 1 + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class FirstHandler(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + async def can_handle_event(self, event: GenericCloudEvent, context: dict) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict) -> None: + return None + + +class SecondHandler(FirstHandler): + """Same priority as FirstHandler, so which of them wins is decided by registration order.""" + + +class LowPriorityHandler(FirstHandler): + def __init__(self) -> None: + super().__init__(priority=500) + + +def settings_file(tmp_path: Path, app_name: str = "root-app") -> Path: + settings = tmp_path / "settings.toml" + settings.write_text(f'[development]\napp_name = "{app_name}"\napp_port = 8000\n') + return settings + + +@pytest.fixture +def config(tmp_path: Path) -> Config: + return Config(settings_files=[str(settings_file(tmp_path))], root_path=str(tmp_path)) + + +@pytest.fixture(autouse=True) +def reset_counting_service() -> None: + CountingService.built = 0 + + +class TestNothingIsBuiltUntilBuild: + def test_a_class_is_not_constructed_by_with_service(self, config: Config) -> None: + AppBuilder(config).with_service(CountingService) + assert CountingService.built == 0 + + def test_nothing_reaches_the_registry(self, config: Config) -> None: + """The registry exists -- the builder's own TelemetryManager makes it -- but it is empty.""" + AppBuilder(config).with_service(OrderService).with_handler(StubHandler) + registry = Component.shared_registry + assert registry is not None + assert registry.get_component_names_by_type(Component) == [] + + def test_a_factory_is_not_called(self, config: Config) -> None: + calls: list[int] = [] + AppBuilder(config).with_service(lambda: calls.append(1) or CountingService()) + assert calls == [] + + def test_build_constructs_it(self, config: Config) -> None: + AppBuilder(config).with_service(CountingService).build() + assert CountingService.built == 1 + + def test_an_instance_is_the_exception(self, config: Config) -> None: + """A caller who writes ``with_service(X())`` built it themselves, at that line.""" + Component.configure(config) + assert CountingService.built == 0 + + CountingService() + + assert CountingService.built == 1 + + +class TestWhatIsRecorded: + def test_the_declarations_are_kept_in_call_order(self, config: Config) -> None: + builder = AppBuilder(config).with_handler(StubHandler).with_service(OrderService) + assert [(entry.kind, entry.target) for entry in builder.declarations] == [ + ("handler", StubHandler), + ("service", OrderService), + ] + + def test_the_name_and_the_constructor_arguments_are_kept(self, config: Config) -> None: + builder = AppBuilder(config).with_service(OrderService, name="db", retries=3) + entry = builder.declarations[0] + assert (entry.name, entry.kwargs) == ("db", {"retries": 3}) + + def test_the_ambient_namespace_is_captured_at_the_call(self, config: Config) -> None: + """Not looked up at construction time: by then no scope is in force any more.""" + builder = AppBuilder(config) + with namespace_scope("orders"): + builder.with_service(OrderService) + assert builder.declarations[0].namespace == "orders" + + def test_a_namespace_keyword_is_refused(self, config: Config) -> None: + """It was a parameter until step 4; dropped, it would reach the constructor instead.""" + with pytest.raises(TypeError, match="does not take a namespace"): + AppBuilder(config).with_service(OrderService, namespace="billing") + + def test_a_cache_is_recorded_too(self, config: Config) -> None: + builder = AppBuilder(config).with_cache(name="sessions") + entry = builder.declarations[0] + assert (entry.kind, entry.name, entry.target) == ("cache", "sessions", None) + + def test_declarations_is_a_snapshot(self, config: Config) -> None: + builder = AppBuilder(config).with_service(OrderService) + declared = builder.declarations + builder.with_handler(StubHandler) + assert len(declared) == 1 + + def test_a_built_component_is_marked_as_built(self, config: Config) -> None: + Component.configure(config) + builder = AppBuilder(config).with_service(OrderService()).with_handler(StubHandler) + assert [entry.is_built for entry in builder.declarations] == [True, False] + + def test_something_that_cannot_be_called_is_refused(self, config: Config) -> None: + with pytest.raises(TypeError, match="component class, a callable returning one"): + AppBuilder(config).with_service(42) # type: ignore[arg-type] + + +class TestDeclarationOrder: + def test_an_instance_after_a_class_at_equal_priority_is_refused(self, config: Config) -> None: + """The instance is already registered, so it would be tried first -- the reverse of the file.""" + builder = AppBuilder(config).with_handler(FirstHandler).with_handler(SecondHandler()) + + with pytest.raises(ValueError, match="SecondHandler was passed to with_handler"): + builder.build() + + def test_the_refusal_names_both_handlers_and_the_priority(self, config: Config) -> None: + builder = AppBuilder(config).with_handler(FirstHandler).with_handler(SecondHandler()) + + with pytest.raises(ValueError, match=r"FirstHandler was declared as a class.*priority 100"): + builder.build() + + def test_different_priorities_are_accepted(self, config: Config) -> None: + """Priority decides, so registration order decides nothing and cannot be reversed.""" + builder = AppBuilder(config).with_handler(FirstHandler).with_handler(LowPriorityHandler()) + + builder.build() + + def test_an_instance_before_a_class_is_accepted(self, config: Config) -> None: + """The order the caller wrote is the order construction produces, so nothing is wrong.""" + builder = AppBuilder(config).with_handler(SecondHandler()).with_handler(FirstHandler) + + builder.build() + + def test_two_classes_are_accepted(self, config: Config) -> None: + AppBuilder(config).with_handler(FirstHandler).with_handler(SecondHandler).build() + + def test_two_agents_do_not_collide(self, config: Config) -> None: + """Handlers of different agents are never in one chain, so their order is not shared.""" + with namespace_scope("billing"): + billing_handler = SecondHandler() + builder = AppBuilder(config) + with namespace_scope("orders"): + builder.with_handler(FirstHandler) + with namespace_scope("billing"): + builder.with_handler(billing_handler) + + builder.build() + + +class TestWhereTheConfigurationComesFrom: + def test_build_accepts_it(self, config: Config) -> None: + app = AppBuilder().with_service(OrderService).build(config) + assert app.title == "root-app" + + def test_the_constructor_still_accepts_it(self, config: Config) -> None: + app = AppBuilder(config).with_service(OrderService).build() + assert app.title == "root-app" + + def test_giving_it_twice_is_refused(self, config: Config, tmp_path: Path) -> None: + elsewhere = tmp_path / "other" + elsewhere.mkdir() + other = Config(settings_files=[str(settings_file(elsewhere, "other-app"))], root_path=str(elsewhere)) + with pytest.raises(ValueError, match="passed to both AppBuilder"): + AppBuilder(config).build(other) + + def test_neither_loads_the_default_settings_files(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """``AppBuilder().build()`` is the migrated standalone shape; it has to find settings.toml.""" + settings_file(tmp_path, "found-by-default") + monkeypatch.chdir(tmp_path) + + app = AppBuilder().with_service(OrderService).build() + + assert app.title == "found-by-default" + + def test_logging_is_configured_when_the_constructor_is_given_one(self, tmp_path: Path) -> None: + config = MagicMock(spec=Config) + AppBuilder(config) + config.configure_logging.assert_called_once() + + def test_logging_is_configured_by_build_otherwise(self, config: Config, monkeypatch: pytest.MonkeyPatch) -> None: + calls: list[int] = [] + monkeypatch.setattr(Config, "configure_logging", lambda self: calls.append(1)) + builder = AppBuilder().with_service(OrderService) + assert calls == [] + + builder.build(config) + + assert calls == [1] + + +class TestSingleUse: + def test_building_twice_is_refused(self, config: Config) -> None: + builder = AppBuilder(config).with_service(OrderService) + builder.build() + + with pytest.raises(RuntimeError, match="already been built"): + builder.build() + + def test_the_second_call_reports_the_builder_not_the_config(self, config: Config) -> None: + """Previously this surfaced as Component.configure's 'already set', three frames down.""" + builder = AppBuilder(config) + builder.build() + + with pytest.raises(RuntimeError, match="a builder produces one application"): + builder.build() + + +class TestAnApplicationWithNoComponents: + def test_it_builds(self, config: Config) -> None: + """Nothing constructs a registry when nothing is declared, so build() has to.""" + app = AppBuilder(config).build() + assert app.title == "root-app" + + def test_the_registry_exists_afterwards(self, config: Config) -> None: + AppBuilder(config).build() + assert Component.shared_registry is not None + + +class TestRealizeMatchesBuild: + def test_the_same_components_are_registered(self, config: Config) -> None: + """The test helper runs build()'s own replay pass, so it cannot drift from it.""" + realize(AppBuilder(config).with_service(OrderService)) + registry = Component.shared_registry + assert registry is not None + assert registry.get_component("order_service").namespace == "" + + +class TestTheDeclarationValueObject: + def test_a_class_is_not_built(self) -> None: + assert Declaration(kind="service", target=OrderService, name=None, namespace="", kwargs={}).is_built is False + + def test_a_component_is_built(self, config: Config) -> None: + Component.configure(config) + assert Declaration(kind="service", target=OrderService(), name=None, namespace="", kwargs={}).is_built is True + + +class TestAnUnbuiltAgentBuilder: + """D6: with_agent takes the builder itself, and build() hands it this agent's config view.""" + + def test_it_is_recorded_rather_than_refused(self, config: Config) -> None: + """An AgentBuilder is neither a Component nor callable, so _record has to know it.""" + agent = AgentBuilder(runtime_name="orders").with_model_from_config() + builder = AppBuilder(config).with_agent(agent) + assert builder.declarations[0].target is agent + + def test_it_is_not_built_by_the_with_call(self, config: Config) -> None: + agent = AgentBuilder(runtime_name="orders").with_model_from_config() + AppBuilder(config).with_agent(agent) + assert agent._ai_config is None + + def test_build_hands_it_the_namespace_scoped_view(self, config: Config) -> None: + """The bug D6 removes: a lambda closes over whichever config was in scope where it was + written, which in a group is a neighbour's. The view is passed in instead.""" + agent = AgentBuilder(runtime_name="orders") + seen: list[Config] = [] + agent.build = lambda cfg=None, **kwargs: seen.append(cfg) or MagicMock() # type: ignore[method-assign] + + builder = AppBuilder(config) + with namespace_scope("orders"): + builder.with_agent(agent) + builder.build() + + assert len(seen) == 1 + assert seen[0] is config.for_namespace("orders") + + def test_a_root_agent_gets_the_loader_itself(self, config: Config) -> None: + """for_namespace("") returns the loader, so a single-agent app is unchanged.""" + agent = AgentBuilder(runtime_name="orders") + seen: list[Config] = [] + agent.build = lambda cfg=None, **kwargs: seen.append(cfg) or MagicMock() # type: ignore[method-assign] + + AppBuilder(config).with_agent(agent).build() + + assert seen == [config] + + def test_constructor_arguments_are_forwarded_to_build(self, config: Config) -> None: + seen: list[dict] = [] + agent = AgentBuilder(runtime_name="orders") + agent.build = lambda cfg=None, **kwargs: seen.append(kwargs) or MagicMock() # type: ignore[method-assign] + + AppBuilder(config).with_agent(agent, retries=3).build() + + assert seen == [{"retries": 3}] + + def test_it_is_refused_by_the_other_with_methods(self, config: Config) -> None: + agent = AgentBuilder(runtime_name="orders") + with pytest.raises(TypeError, match="belongs in with_agent"): + AppBuilder(config).with_service(agent) # type: ignore[arg-type] diff --git a/tests/unit/agents/app_builder/test_named_caches.py b/tests/unit/agents/app_builder/test_named_caches.py index 6eae3517..e71042e3 100644 --- a/tests/unit/agents/app_builder/test_named_caches.py +++ b/tests/unit/agents/app_builder/test_named_caches.py @@ -11,17 +11,21 @@ """ from pathlib import Path +from typing import Any from unittest.mock import MagicMock, patch import pytest from blueprint.agents.app_builder import AppBuilder from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import namespace_scope from blueprint.agents.component.registry import DEFAULT_CACHE_NAME, Registry from blueprint.agents.config import Config from blueprint.agents.models.config import CacheConfig from blueprint.agents.services.infrastructure.cache_service import CacheService, DiskCacheService +from .conftest import realize + @pytest.fixture def cache_dir(tmp_path: Path) -> Path: @@ -50,44 +54,56 @@ def registry() -> Registry: return Component.shared_registry +def entry_keys(builder: AppBuilder) -> list[str]: + """The readiness entry names ``build()`` wired, in order.""" + assert builder._actuator_api is not None + return [entry.key for entry in builder._actuator_api.health_entries] + + +def checkers(builder: AppBuilder) -> dict[str, Any]: + """The wired checkers by readiness entry name.""" + assert builder._actuator_api is not None + return {entry.key: entry.checker for entry in builder._actuator_api.health_entries} + + class TestTheDefaultCacheIsUnchanged: def test_it_registers_under_the_default_name(self, builder: AppBuilder) -> None: - builder.with_cache() + realize(builder.with_cache()) assert isinstance(registry().get_cache(DEFAULT_CACHE_NAME), CacheService) def test_it_keeps_the_configured_directory(self, builder: AppBuilder, cache_dir: Path) -> None: - builder.with_cache() + realize(builder.with_cache()) cache = registry().get_cache() assert isinstance(cache, DiskCacheService) assert cache.cache_dir == cache_dir def test_it_keeps_the_derived_registry_name(self, builder: AppBuilder) -> None: """Renaming this would move a key that existing lookups and health entries use.""" - builder.with_cache() + realize(builder.with_cache()) assert registry().get_component("disk_cache_service") is registry().get_cache() def test_the_cache_service_alias_still_reads_it(self, builder: AppBuilder) -> None: - builder.with_cache() + realize(builder.with_cache()) assert registry().cache_service is registry().get_cache() def test_it_works_as_the_first_builder_call(self, builder: AppBuilder) -> None: """A cache service is itself a Component, so it is what creates the shared registry.""" Component.shared_registry = None - builder.with_cache() + realize(builder.with_cache()) assert registry().has_cache() class TestPositionalCompatibility: def test_disabled_registers_nothing(self, builder: AppBuilder) -> None: - builder.with_cache(False) + realize(builder.with_cache(False)) assert Component.shared_registry is None or not Component.shared_registry.has_cache() def test_disabled_does_not_read_the_cache_config(self, builder: AppBuilder) -> None: - builder.with_cache(False) + realize(builder.with_cache(False)) builder._config.get_cache_config.assert_not_called() # type: ignore[attr-defined] def test_locking_is_still_the_second_positional(self, builder: AppBuilder) -> None: - builder.with_cache(True, False) + realize(builder.with_cache(True, False)) cache = registry().get_cache() assert isinstance(cache, DiskCacheService) assert cache._enable_locking is False @@ -98,45 +114,45 @@ def test_returns_self_for_chaining(self, builder: AppBuilder) -> None: class TestNamedCaches: def test_a_named_cache_is_reachable_by_its_name(self, builder: AppBuilder) -> None: - builder.with_cache(name="sessions") + realize(builder.with_cache(name="sessions")) assert isinstance(registry().get_cache("sessions"), CacheService) def test_a_named_cache_gets_its_own_directory(self, builder: AppBuilder, cache_dir: Path) -> None: - builder.with_cache(name="sessions") + realize(builder.with_cache(name="sessions")) cache = registry().get_cache("sessions") assert isinstance(cache, DiskCacheService) assert cache.cache_dir == cache_dir / "sessions" def test_the_directory_is_inside_the_configured_one(self, builder: AppBuilder, cache_dir: Path) -> None: """A sibling of the configured directory is not writable when that directory is the mount.""" - builder.with_cache(name="sessions") + realize(builder.with_cache(name="sessions")) assert (cache_dir / "sessions").is_dir() def test_a_named_cache_gets_its_own_registry_name(self, builder: AppBuilder) -> None: - builder.with_cache(name="sessions") + realize(builder.with_cache(name="sessions")) assert registry().get_component("cache_sessions") is registry().get_cache("sessions") def test_the_default_and_a_named_cache_coexist(self, builder: AppBuilder) -> None: """Both are Components: without distinct registry names the second would fail to register.""" - builder.with_cache().with_cache(name="sessions") + realize(builder.with_cache().with_cache(name="sessions")) assert registry().get_cache() is not registry().get_cache("sessions") assert sorted(registry().get_all_caches()) == ["default", "sessions"] def test_two_named_caches_do_not_share_a_directory(self, builder: AppBuilder) -> None: - builder.with_cache(name="sessions").with_cache(name="prompts") + realize(builder.with_cache(name="sessions").with_cache(name="prompts")) sessions, prompts = registry().get_cache("sessions"), registry().get_cache("prompts") assert isinstance(sessions, DiskCacheService) assert isinstance(prompts, DiskCacheService) assert sessions.cache_dir != prompts.cache_dir def test_an_unregistered_name_is_an_error_not_the_default(self, builder: AppBuilder) -> None: - builder.with_cache() + realize(builder.with_cache()) with pytest.raises(ValueError, match="No cache registered as 'sessions'"): registry().get_cache("sessions") def test_a_named_cache_is_closed_by_the_lifespan(self, builder: AppBuilder) -> None: """It is closed because it is a registered service; the lifespan drives get_services().""" - builder.with_cache(name="sessions") + realize(builder.with_cache(name="sessions")) assert registry().get_cache("sessions") in registry().get_services() @@ -168,7 +184,7 @@ def test_the_default_cache_keeps_the_entry_name_it_has_always_had(self, builder: with patch("blueprint.agents.app_builder.FastAPI"): builder.build() - assert "cache" in builder._actuator_api._pending_providers # type: ignore[union-attr] + assert "cache" in entry_keys(builder) def test_a_named_cache_gets_its_own_entry(self, builder: AppBuilder) -> None: builder.with_cache().with_cache(name="sessions") @@ -176,8 +192,7 @@ def test_a_named_cache_gets_its_own_entry(self, builder: AppBuilder) -> None: with patch("blueprint.agents.app_builder.FastAPI"): builder.build() - providers = builder._actuator_api._pending_providers # type: ignore[union-attr] - assert {"cache", "cache:sessions"} <= set(providers) + assert {"cache", "cache:sessions"} <= set(entry_keys(builder)) def test_a_named_cache_alone_still_reaches_readiness(self, builder: AppBuilder) -> None: """Previously the probe was keyed on the default name, so this cache went unprobed.""" @@ -186,7 +201,7 @@ def test_a_named_cache_alone_still_reaches_readiness(self, builder: AppBuilder) with patch("blueprint.agents.app_builder.FastAPI"): builder.build() - assert "cache:sessions" in builder._actuator_api._pending_providers # type: ignore[union-attr] + assert "cache:sessions" in entry_keys(builder) def test_each_entry_probes_its_own_cache(self, builder: AppBuilder) -> None: builder.with_cache().with_cache(name="sessions") @@ -194,6 +209,72 @@ def test_each_entry_probes_its_own_cache(self, builder: AppBuilder) -> None: with patch("blueprint.agents.app_builder.FastAPI"): builder.build() - providers = builder._actuator_api._pending_providers # type: ignore[union-attr] + providers = checkers(builder) assert providers["cache"]._cache is registry().get_cache() assert providers["cache:sessions"]._cache is registry().get_cache("sessions") + + +class TestACacheBelongsToTheAgentThatDeclaredIt: + """``with_cache()`` inside an agent's scope registers to that agent, and stores apart (D3).""" + + def test_it_is_registered_to_the_declaring_agent(self, builder: AppBuilder) -> None: + with namespace_scope("orders"): + builder.with_cache(name="sessions") + realize(builder) + + assert isinstance(registry().get_cache("sessions", namespace="orders"), CacheService) + assert registry().get_all_caches() == {}, "the root declared nothing" + + def test_its_directory_carries_the_agent(self, builder: AppBuilder, cache_dir: Path) -> None: + with namespace_scope("orders"): + builder.with_cache(name="sessions") + realize(builder) + + cache = registry().get_cache("sessions", namespace="orders") + assert isinstance(cache, DiskCacheService) + assert cache.cache_dir == cache_dir / "orders.sessions" + + def test_two_agents_declaring_one_name_get_two_caches(self, builder: AppBuilder) -> None: + with namespace_scope("orders"): + builder.with_cache(name="sessions") + with namespace_scope("billing"): + builder.with_cache(name="sessions") + realize(builder) + + orders = registry().get_cache("sessions", namespace="orders") + billing = registry().get_cache("sessions", namespace="billing") + assert orders is not billing + assert isinstance(orders, DiskCacheService) and isinstance(billing, DiskCacheService) + assert orders.cache_dir != billing.cache_dir + + def test_both_backends_still_register_as_components(self, builder: AppBuilder) -> None: + """Two of one class collide on the derived registry name unless each is built in its own scope.""" + with namespace_scope("orders"): + builder.with_cache() + with namespace_scope("billing"): + builder.with_cache() + realize(builder) + + assert registry().get_component("orders_disk_cache_service") is registry().get_cache(namespace="orders") + assert registry().get_component("billing_disk_cache_service") is registry().get_cache(namespace="billing") + + def test_the_backend_is_chosen_from_the_agents_own_configuration(self, builder: AppBuilder) -> None: + """C5: one agent in a group may run on redis while its neighbour uses the disk.""" + with namespace_scope("orders"): + builder.with_cache(name="sessions") + realize(builder) + + builder._config.for_namespace.assert_any_call("orders") # type: ignore[attr-defined] + + def test_a_readiness_entry_names_the_agent(self, builder: AppBuilder) -> None: + """Two agents' default caches are two entries, not one that reports the last registered.""" + with namespace_scope("orders"): + builder.with_cache().with_cache(name="sessions") + builder.host_agent("orders") + + with patch("blueprint.agents.app_builder.FastAPI"): + builder.build() + + providers = checkers(builder) + assert {"orders.cache", "orders.cache:sessions"} <= set(providers) + assert providers["orders.cache"]._cache is registry().get_cache(namespace="orders") diff --git a/tests/unit/agents/app_builder/test_namespace_builder.py b/tests/unit/agents/app_builder/test_namespace_builder.py deleted file mode 100644 index 1e639f75..00000000 --- a/tests/unit/agents/app_builder/test_namespace_builder.py +++ /dev/null @@ -1,315 +0,0 @@ -"""Unit tests for the namespace-aware ``AppBuilder`` and for ``NamespaceBuilder``. - -The behaviour under test is the one thing the whole design rests on: a component ends up in the -right agent without the component, its constructor, or the code that declares it ever mentioning -a namespace. So most of these assert on the registry key a component got, which is the only -externally visible consequence of the namespace it was built in. -""" - -from pathlib import Path -from typing import Any - -import pytest - -from blueprint.agents.app_builder import AgentRegistration, AppBuilder, NamespaceBuilder -from blueprint.agents.component.component import Component -from blueprint.agents.component.namespace import ROOT_NAMESPACE, current_namespace, namespace_scope -from blueprint.agents.config import Config -from blueprint.agents.io.api.rest_api_base import RestApiBase -from blueprint.agents.services.service_base import ServiceBase - -from .conftest import StubHandler - - -class OrderService(ServiceBase): - """A service written the way a project writes one: no namespace, no arguments.""" - - async def on_startup(self) -> None: - pass - - async def on_shutdown(self) -> None: - pass - - -class StrictService(ServiceBase): - """A service whose constructor accepts exactly one argument and no namespace. - - The point of the signature: if the builder ever forwarded ``namespace`` to the component, - constructing this would raise ``TypeError`` instead of registering. - """ - - def __init__(self, retries: int = 0) -> None: - super().__init__() - self.retries = retries - - async def on_startup(self) -> None: - pass - - async def on_shutdown(self) -> None: - pass - - -class OrderApi(RestApiBase): - async def on_startup(self) -> None: - pass - - async def on_shutdown(self) -> None: - pass - - -@pytest.fixture -def two_agent_config(tmp_path: Path) -> Config: - """A settings tree with a root and two agents, injected as the shared component config.""" - settings = tmp_path / "settings.toml" - content = """ - [development] - app_name = "root-app" - app_port = 8000 - - [development.orders] - app_name = "orders" - - [development.billing] - app_name = "billing" - """ - settings.write_text(content.replace("\n ", "\n")) - return Config(settings_files=[str(settings)], root_path=str(tmp_path)) - - -def component_names() -> list[str]: - registry = Component.shared_registry - assert registry is not None - return sorted(registry.get_component_names_by_type(Component)) - - -class TestNamespaceOnTheBuilderMethods: - def test_a_namespace_qualifies_the_registry_name(self, two_agent_config: Config) -> None: - AppBuilder(two_agent_config).with_service(OrderService, namespace="orders") - assert component_names() == ["orders_order_service"] - - def test_the_namespace_reaches_the_component_itself(self, two_agent_config: Config) -> None: - AppBuilder(two_agent_config).with_service(OrderService, namespace="orders") - registry = Component.shared_registry - assert registry is not None - assert registry.get_component("orders_order_service").namespace == "orders" - - def test_the_namespace_is_not_forwarded_to_the_constructor(self, two_agent_config: Config) -> None: - """StrictService takes no namespace argument, which is what every project's code looks like.""" - AppBuilder(two_agent_config).with_service(StrictService, namespace="orders", retries=3) - registry = Component.shared_registry - assert registry is not None - built = registry.get_component("orders_strict_service") - assert (built.namespace, built.retries) == ("orders", 3) - - def test_no_namespace_keeps_todays_names(self, two_agent_config: Config) -> None: - AppBuilder(two_agent_config).with_service(OrderService) - assert component_names() == ["order_service"] - - def test_the_default_does_not_reset_an_ambient_namespace(self, two_agent_config: Config) -> None: - """The trap: ``namespace_scope("")`` *sets* the root, so the default must not open a scope. - - This is the path ``AgentRegistration.apply`` takes -- it opens one scope per agent and - then calls these methods without a namespace argument. - """ - builder = AppBuilder(two_agent_config) - with namespace_scope("orders"): - builder.with_service(OrderService) - assert component_names() == ["orders_order_service"] - - def test_an_explicit_namespace_wins_over_the_ambient_one(self, two_agent_config: Config) -> None: - builder = AppBuilder(two_agent_config) - with namespace_scope("orders"): - builder.with_service(OrderService, namespace="billing") - assert component_names() == ["billing_order_service"] - - def test_the_ambient_namespace_is_restored_afterwards(self, two_agent_config: Config) -> None: - AppBuilder(two_agent_config).with_service(OrderService, namespace="orders") - assert current_namespace() == ROOT_NAMESPACE - - @pytest.mark.parametrize( - ("method", "target", "expected"), - [ - ("with_handler", StubHandler, "orders_stub_handler"), - ("with_service", OrderService, "orders_order_service"), - ("with_rest_api", OrderApi, "orders_order_api"), - ], - ) - def test_every_method_takes_a_namespace(self, two_agent_config: Config, method: str, target: Any, expected: str) -> None: - builder = AppBuilder(two_agent_config) - getattr(builder, method)(target, namespace="orders") - assert component_names() == [expected] - - def test_an_illegal_namespace_is_refused(self, two_agent_config: Config) -> None: - with pytest.raises(ValueError, match="legal namespace"): - AppBuilder(two_agent_config).with_service(OrderService, namespace="Orders") - - def test_the_handler_type_check_still_fires(self, two_agent_config: Config) -> None: - with pytest.raises(TypeError, match="EventHandlerBase subclass"): - AppBuilder(two_agent_config).with_handler(OrderService, namespace="orders") # type: ignore[type-var] - - -class TestExplicitNames: - def test_an_explicit_name_is_qualified_with_the_namespace(self, two_agent_config: Config) -> None: - AppBuilder(two_agent_config).with_service(OrderService, name="db", namespace="orders") - assert component_names() == ["orders_db"] - - def test_an_explicit_name_at_the_root_is_unchanged(self, two_agent_config: Config) -> None: - AppBuilder(two_agent_config).with_service(OrderService, name="db") - assert component_names() == ["db"] - - def test_one_declaration_with_an_explicit_name_serves_two_agents(self, two_agent_config: Config) -> None: - """Unqualified, the second agent would collide on the one literal name and fail to build.""" - registration = AgentRegistration().with_service(OrderService, name="db") - builder = AppBuilder(two_agent_config) - - builder.with_namespace("orders", registration=registration) - builder.with_namespace("billing", registration=registration) - - assert component_names() == ["billing_db", "orders_db"] - - def test_the_bare_name_still_finds_it(self, two_agent_config: Config) -> None: - """Registry._lookup tries '_' first, so qualifying costs the caller nothing.""" - AppBuilder(two_agent_config).with_service(OrderService, name="db", namespace="orders") - registry = Component.shared_registry - assert registry is not None - assert registry.get_component("db", namespace="orders").namespace == "orders" - - -class TestAlreadyBuiltInstances: - def test_an_instance_is_refused_for_another_namespace(self, two_agent_config: Config) -> None: - Component.configure(two_agent_config) - instance = OrderService() - - with pytest.raises(ValueError, match="cannot change namespace"): - AppBuilder(two_agent_config).with_service(instance, namespace="orders") - - def test_the_refusal_names_both_namespaces_and_the_method(self, two_agent_config: Config) -> None: - Component.configure(two_agent_config) - instance = OrderService() - - with pytest.raises(ValueError, match=r"with_service\(\).*'orders'.*''"): - AppBuilder(two_agent_config).with_service(instance, namespace="orders") - - def test_an_instance_from_the_same_namespace_is_accepted(self, two_agent_config: Config) -> None: - Component.configure(two_agent_config) - with namespace_scope("orders"): - instance = OrderService() - - AppBuilder(two_agent_config).with_service(instance, namespace="orders") - assert component_names() == ["orders_order_service"] - - def test_an_instance_at_the_root_is_unaffected(self, two_agent_config: Config) -> None: - Component.configure(two_agent_config) - instance = OrderService() - - AppBuilder(two_agent_config).with_service(instance) - assert component_names() == ["order_service"] - - -class TestWithNamespace: - def test_a_registration_keeps_the_chain_on_the_builder(self, two_agent_config: Config) -> None: - builder = AppBuilder(two_agent_config) - returned = builder.with_namespace("orders", registration=AgentRegistration().with_service(OrderService)) - assert returned is builder - assert component_names() == ["orders_order_service"] - - def test_no_registration_opens_a_namespace_block(self, two_agent_config: Config) -> None: - builder = AppBuilder(two_agent_config) - opened = builder.with_namespace("orders") - assert isinstance(opened, NamespaceBuilder) - assert opened.namespace == "orders" - - def test_the_root_namespace_is_refused(self, two_agent_config: Config) -> None: - with pytest.raises(ValueError, match="names no agent"): - AppBuilder(two_agent_config).with_namespace("") - - def test_an_illegal_namespace_is_refused(self, two_agent_config: Config) -> None: - with pytest.raises(ValueError, match="legal namespace"): - AppBuilder(two_agent_config).with_namespace("Orders") - - def test_the_ambient_namespace_is_left_behind(self, two_agent_config: Config) -> None: - AppBuilder(two_agent_config).with_namespace("orders", registration=AgentRegistration().with_service(OrderService)) - assert current_namespace() == ROOT_NAMESPACE - - -class TestDeclaredNamespaces: - def test_a_single_agent_application_declares_none(self, two_agent_config: Config) -> None: - builder = AppBuilder(two_agent_config).with_service(OrderService) - assert builder.namespaces == () - - def test_declaration_order_is_kept(self, two_agent_config: Config) -> None: - builder = AppBuilder(two_agent_config) - builder.with_namespace("orders").end().with_namespace("billing").end() - assert builder.namespaces == ("orders", "billing") - - def test_declaring_one_namespace_twice_is_refused(self, two_agent_config: Config) -> None: - """Two agents cannot share a name: the name is what tells them apart everywhere.""" - builder = AppBuilder(two_agent_config) - builder.with_namespace("orders", registration=AgentRegistration()) - - with pytest.raises(ValueError, match="already hosted by this process"): - builder.with_namespace("orders", registration=AgentRegistration().with_service(OrderService)) - - def test_the_refusal_points_at_composing_one_registration(self, two_agent_config: Config) -> None: - builder = AppBuilder(two_agent_config).with_namespace("orders").end() - - with pytest.raises(ValueError, match=r"single\s+AgentRegistration"): - builder.with_namespace("orders") - - def test_a_tagged_with_call_is_not_a_declaration(self, two_agent_config: Config) -> None: - """``namespaces`` is what the builder was *told* to host; a tagged call is not that. - - Recording it there would make ``with_service(X, namespace="orders")`` enough to make - 'orders' an agent of the group, and phases that iterate the list -- the startup log, - the readiness policy -- would then report an agent nobody declared. - """ - builder = AppBuilder(two_agent_config).with_service(OrderService, namespace="orders") - assert builder.namespaces == () - - -class TestNamespaceBlock: - def test_every_call_lands_in_the_namespace(self, two_agent_config: Config) -> None: - ( - AppBuilder(two_agent_config) - .with_namespace("orders") - .with_service(OrderService) - .with_handler(StubHandler) - .with_rest_api(OrderApi) - .end() - ) - assert component_names() == ["orders_order_api", "orders_order_service", "orders_stub_handler"] - - def test_the_calls_chain_on_the_block(self, two_agent_config: Config) -> None: - block = AppBuilder(two_agent_config).with_namespace("orders") - assert block.with_service(OrderService) is block - - def test_end_returns_the_parent_builder(self, two_agent_config: Config) -> None: - builder = AppBuilder(two_agent_config) - assert builder.with_namespace("orders").end() is builder - - def test_two_blocks_build_two_independent_agents(self, two_agent_config: Config) -> None: - ( - AppBuilder(two_agent_config) - .with_namespace("orders") - .with_service(OrderService) - .end() - .with_namespace("billing") - .with_service(OrderService) - .end() - ) - assert component_names() == ["billing_order_service", "orders_order_service"] - - def test_a_registration_can_be_applied_inside_a_block(self, two_agent_config: Config) -> None: - block = AppBuilder(two_agent_config).with_namespace("orders") - block.with_registration(AgentRegistration().with_service(OrderService)) - assert component_names() == ["orders_order_service"] - - def test_constructor_arguments_survive_the_delegation(self, two_agent_config: Config) -> None: - AppBuilder(two_agent_config).with_namespace("orders").with_service(StrictService, retries=5).end() - registry = Component.shared_registry - assert registry is not None - assert registry.get_component("orders_strict_service").retries == 5 - - def test_there_is_no_with_cache(self) -> None: - """A cache belongs to the process, not to an agent (spec sec. 8).""" - assert not hasattr(NamespaceBuilder, "with_cache") diff --git a/tests/unit/agents/app_builder/test_namespace_placement.py b/tests/unit/agents/app_builder/test_namespace_placement.py new file mode 100644 index 00000000..298ad049 --- /dev/null +++ b/tests/unit/agents/app_builder/test_namespace_placement.py @@ -0,0 +1,293 @@ +"""A component ends up in the right agent without anyone naming a namespace. + +The one thing the whole design rests on. No component, no constructor, and no line a developer +writes mentions a namespace: a declaration takes whichever namespace is in force where it is +recorded, which is the root for a standalone application and the agent's own for a declaration +a group is replaying. So most of these assert on the registry key a component got, which is the +only externally visible consequence of the namespace it was built in. + +``namespace_scope`` stands in for the group here on purpose: it is exactly what +``AgentGroup.assemble`` opens, and using it keeps these cases about placement rather than about +collection, which ``tests/unit/agents/test_agent_group.py`` covers. +""" + +from pathlib import Path +from typing import Any + +import pytest + +from blueprint.agents.app_builder import AppBuilder +from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import ROOT_NAMESPACE, current_namespace, namespace_scope +from blueprint.agents.config import Config +from blueprint.agents.io.api.rest_api_base import RestApiBase +from blueprint.agents.services.service_base import ServiceBase + +from .conftest import StubHandler, realize + + +class OrderService(ServiceBase): + """A service written the way a project writes one: no namespace, no arguments.""" + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class StrictService(ServiceBase): + """A service whose constructor accepts exactly one argument and no namespace. + + The point of the signature: if the builder ever forwarded ``namespace`` to the component, + constructing this would raise ``TypeError`` instead of registering. + """ + + def __init__(self, retries: int = 0) -> None: + super().__init__() + self.retries = retries + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class OrderApi(RestApiBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +@pytest.fixture +def two_agent_config(tmp_path: Path) -> Config: + """A settings tree with a root and two agents, injected as the shared component config.""" + settings = tmp_path / "settings.toml" + content = """ + [development] + app_name = "root-app" + app_port = 8000 + + [development.orders] + app_name = "orders" + + [development.billing] + app_name = "billing" + """ + settings.write_text(content.replace("\n ", "\n")) + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + +def component_names() -> list[str]: + registry = Component.shared_registry + assert registry is not None + return sorted(registry.get_component_names_by_type(Component)) + + +def declared_in(builder: AppBuilder, namespace: str, declare: Any) -> AppBuilder: + """Record ``declare(builder)`` with ``namespace`` in force, as a group's replay would.""" + with namespace_scope(namespace): + declare(builder) + return builder + + +class TestTheAmbientNamespaceDecidesPlacement: + def test_a_namespace_qualifies_the_registry_name(self, two_agent_config: Config) -> None: + builder = declared_in(AppBuilder(two_agent_config), "orders", lambda b: b.with_service(OrderService)) + + realize(builder) + + assert component_names() == ["orders_order_service"] + + def test_the_namespace_reaches_the_component_itself(self, two_agent_config: Config) -> None: + builder = declared_in(AppBuilder(two_agent_config), "orders", lambda b: b.with_service(OrderService)) + + realize(builder) + + registry = Component.shared_registry + assert registry is not None + assert registry.get_component("orders_order_service").namespace == "orders" + + def test_it_is_captured_at_the_call_not_at_construction(self, two_agent_config: Config) -> None: + """``realize`` runs with no scope in force, so a namespace read late would be the root.""" + builder = declared_in(AppBuilder(two_agent_config), "orders", lambda b: b.with_service(OrderService)) + + assert current_namespace() == ROOT_NAMESPACE + realize(builder) + + assert component_names() == ["orders_order_service"] + + def test_the_namespace_is_not_forwarded_to_the_constructor(self, two_agent_config: Config) -> None: + """StrictService takes no namespace argument, which is what every project's code looks like.""" + builder = declared_in(AppBuilder(two_agent_config), "orders", lambda b: b.with_service(StrictService, retries=3)) + + realize(builder) + + registry = Component.shared_registry + assert registry is not None + built = registry.get_component("orders_strict_service") + assert (built.namespace, built.retries) == ("orders", 3) + + def test_no_scope_keeps_todays_names(self, two_agent_config: Config) -> None: + realize(AppBuilder(two_agent_config).with_service(OrderService)) + + assert component_names() == ["order_service"] + + def test_the_scope_is_restored_afterwards(self, two_agent_config: Config) -> None: + declared_in(AppBuilder(two_agent_config), "orders", lambda b: b.with_service(OrderService)) + + assert current_namespace() == ROOT_NAMESPACE + + @pytest.mark.parametrize( + ("method", "target", "expected"), + [ + ("with_handler", StubHandler, "orders_stub_handler"), + ("with_service", OrderService, "orders_order_service"), + ("with_rest_api", OrderApi, "orders_order_api"), + ], + ) + def test_every_method_places_into_the_namespace(self, two_agent_config: Config, method: str, target: Any, expected: str) -> None: + builder = declared_in(AppBuilder(two_agent_config), "orders", lambda b: getattr(b, method)(target)) + + realize(builder) + + assert component_names() == [expected] + + def test_there_is_no_namespace_keyword(self, two_agent_config: Config) -> None: + """It existed only for NamespaceBuilder. The scope carries the namespace instead.""" + with pytest.raises(TypeError): + AppBuilder(two_agent_config).with_service(OrderService, namespace="orders") # type: ignore[call-arg] + + def test_the_handler_type_check_still_fires(self, two_agent_config: Config) -> None: + with pytest.raises(TypeError, match="EventHandlerBase subclass"): + AppBuilder(two_agent_config).with_handler(OrderService) # type: ignore[type-var] + + +class TestExplicitNames: + def test_an_explicit_name_is_qualified_with_the_namespace(self, two_agent_config: Config) -> None: + builder = declared_in(AppBuilder(two_agent_config), "orders", lambda b: b.with_service(OrderService, name="db")) + + realize(builder) + + assert component_names() == ["orders_db"] + + def test_an_explicit_name_at_the_root_is_unchanged(self, two_agent_config: Config) -> None: + realize(AppBuilder(two_agent_config).with_service(OrderService, name="db")) + + assert component_names() == ["db"] + + def test_the_bare_name_still_finds_it(self, two_agent_config: Config) -> None: + """Registry._lookup tries '_' first, so qualifying costs the caller nothing.""" + builder = declared_in(AppBuilder(two_agent_config), "orders", lambda b: b.with_service(OrderService, name="db")) + + realize(builder) + + registry = Component.shared_registry + assert registry is not None + assert registry.get_component("db", namespace="orders").namespace == "orders" + + +class TestAlreadyBuiltInstances: + def test_an_instance_is_refused_for_another_namespace(self, two_agent_config: Config) -> None: + Component.configure(two_agent_config) + instance = OrderService() + + with pytest.raises(ValueError, match="cannot change namespace"): + declared_in(AppBuilder(two_agent_config), "orders", lambda b: b.with_service(instance)) + + def test_the_refusal_names_both_namespaces_and_the_method(self, two_agent_config: Config) -> None: + Component.configure(two_agent_config) + instance = OrderService() + + with pytest.raises(ValueError, match=r"with_service\(\).*'orders'.*''"): + declared_in(AppBuilder(two_agent_config), "orders", lambda b: b.with_service(instance)) + + def test_an_instance_from_the_same_namespace_is_accepted(self, two_agent_config: Config) -> None: + Component.configure(two_agent_config) + with namespace_scope("orders"): + instance = OrderService() + + builder = declared_in(AppBuilder(two_agent_config), "orders", lambda b: b.with_service(instance)) + + realize(builder) + + assert component_names() == ["orders_order_service"] + + def test_an_instance_at_the_root_is_unaffected(self, two_agent_config: Config) -> None: + Component.configure(two_agent_config) + instance = OrderService() + + realize(AppBuilder(two_agent_config).with_service(instance)) + + assert component_names() == ["order_service"] + + +class TestHostedAgents: + def test_a_single_agent_application_hosts_none(self, two_agent_config: Config) -> None: + assert AppBuilder(two_agent_config).with_service(OrderService).namespaces == () + + def test_host_agent_records_them_in_order(self, two_agent_config: Config) -> None: + builder = AppBuilder(two_agent_config) + builder.host_agent("orders") + builder.host_agent("billing") + + assert builder.namespaces == ("orders", "billing") + + def test_hosting_one_agent_twice_is_refused(self, two_agent_config: Config) -> None: + """Two agents cannot share a name: the name is what tells them apart everywhere.""" + builder = AppBuilder(two_agent_config) + builder.host_agent("orders") + + with pytest.raises(ValueError, match="already hosted by this process"): + builder.host_agent("orders") + + def test_the_root_is_refused(self, two_agent_config: Config) -> None: + with pytest.raises(ValueError, match="names no agent"): + AppBuilder(two_agent_config).host_agent("") + + def test_an_illegal_name_is_refused(self, two_agent_config: Config) -> None: + with pytest.raises(ValueError, match="legal namespace"): + AppBuilder(two_agent_config).host_agent("Orders") + + def test_it_returns_the_builder(self, two_agent_config: Config) -> None: + builder = AppBuilder(two_agent_config) + assert builder.host_agent("orders") is builder + + def test_a_scoped_declaration_is_not_a_hosted_agent(self, two_agent_config: Config) -> None: + """``namespaces`` is what the builder was *told* to host, and a declaration is not that. + + Recording it there would make one scoped ``with_service`` enough to make 'orders' an + agent of the group, and the code that iterates the list -- the startup log, the + readiness policy -- would then report an agent nobody deployed. + """ + builder = declared_in(AppBuilder(two_agent_config), "orders", lambda b: b.with_service(OrderService)) + + assert builder.namespaces == () + + +class TestTheDeletedSurfaces: + """Four duplication sites became one. These pin that the other three are gone.""" + + def test_there_is_no_agent_registration(self) -> None: + import blueprint.agents.app_builder as module + + assert not hasattr(module, "AgentRegistration") + assert not hasattr(module, "RegisteredComponent") + + def test_there_is_no_namespace_builder(self) -> None: + import blueprint.agents.app_builder as module + + assert not hasattr(module, "NamespaceBuilder") + + def test_the_builder_has_neither_with_namespace_nor_with_registration(self) -> None: + assert not hasattr(AppBuilder, "with_namespace") + assert not hasattr(AppBuilder, "with_registration") + + def test_they_are_not_exported(self) -> None: + import blueprint.agents as package + + assert "AgentRegistration" not in package.__all__ + assert "NamespaceBuilder" not in package.__all__ diff --git a/tests/unit/agents/app_builder/test_route_namespacing.py b/tests/unit/agents/app_builder/test_route_namespacing.py index 9cdd0e2b..8a7341fe 100644 --- a/tests/unit/agents/app_builder/test_route_namespacing.py +++ b/tests/unit/agents/app_builder/test_route_namespacing.py @@ -17,7 +17,8 @@ import pytest from fastapi import FastAPI -from blueprint.agents.app_builder import AgentRegistration, AppBuilder +from blueprint.agents.agent_group import AgentGroup +from blueprint.agents.app_builder import AppBuilder from blueprint.agents.component.component import Component from blueprint.agents.component.namespace import namespace_scope from blueprint.agents.config import Config @@ -84,6 +85,23 @@ def nats_config(tmp_path: Path) -> Config: return Config(settings_files=[str(settings)], root_path=str(tmp_path)) +@pytest.fixture +def cache_config(tmp_path: Path) -> Config: + """One writable cache directory for the process, as a mounted volume would be. + + The agents share it and the *stores* inside it are separated per agent, which is the shape + a pod can actually satisfy -- see "Writable Cache Directory" in ``docs/guides/deployment.md``. + """ + settings = tmp_path / "settings.toml" + settings.write_text( + '[development]\napp_name = "root-app"\napp_port = 8000\n\n' + f'[development.cache]\ncache_dir = "{(tmp_path / "cache").as_posix()}"\n\n' + '[development.orders]\napp_name = "orders"\n\n' + '[development.billing]\napp_name = "billing"\n' + ) + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + def paths(app: FastAPI) -> list[str]: return sorted(app.openapi()["paths"]) @@ -117,50 +135,35 @@ def test_a_single_agent_applications_paths_do_not_move(self, dapr_config: Config assert "/api/orders" in paths(app) def test_an_agents_route_carries_its_namespace(self, dapr_config: Config) -> None: - builder = AppBuilder(dapr_config) - builder.with_namespace("orders", registration=AgentRegistration().with_rest_api(OrderApi)) - - app = builder.build() + app = AgentGroup("g", {"orders": AppBuilder().with_rest_api(OrderApi)}).assemble(dapr_config) assert "/api/orders/orders" in paths(app) def test_two_agents_declaring_one_route_do_not_collide(self, dapr_config: Config) -> None: """The failure without a prefix: FastAPI serves the first match for both agents.""" - registration = AgentRegistration().with_rest_api(OrderApi) - builder = AppBuilder(dapr_config) - builder.with_namespace("orders", registration=registration) - builder.with_namespace("billing", registration=registration) + declaration = AppBuilder().with_rest_api(OrderApi) - app = builder.build() + app = AgentGroup("g", {"orders": declaration, "billing": declaration}).assemble(dapr_config) assert {"/api/orders/orders", "/api/billing/orders"} <= set(paths(app)) class TestTags: def test_an_agents_tags_are_prefixed(self, dapr_config: Config) -> None: - builder = AppBuilder(dapr_config) - builder.with_namespace("orders", registration=AgentRegistration().with_rest_api(OrderApi)) - - app = builder.build() + app = AgentGroup("g", {"orders": AppBuilder().with_rest_api(OrderApi)}).assemble(dapr_config) assert tags_for(app, "/api/orders/orders") == ["orders.orders"] def test_the_bare_tag_is_replaced_rather_than_added_to(self, dapr_config: Config) -> None: """Appending would put the operation in two Swagger groups instead of one.""" - builder = AppBuilder(dapr_config) - builder.with_namespace("orders", registration=AgentRegistration().with_rest_api(OrderApi)) - - app = builder.build() + app = AgentGroup("g", {"orders": AppBuilder().with_rest_api(OrderApi)}).assemble(dapr_config) assert "orders" not in tags_for(app, "/api/orders/orders") def test_two_agents_tags_do_not_merge(self, dapr_config: Config) -> None: - registration = AgentRegistration().with_rest_api(OrderApi) - builder = AppBuilder(dapr_config) - builder.with_namespace("orders", registration=registration) - builder.with_namespace("billing", registration=registration) + declaration = AppBuilder().with_rest_api(OrderApi) - app = builder.build() + app = AgentGroup("g", {"orders": declaration, "billing": declaration}).assemble(dapr_config) assert tags_for(app, "/api/orders/orders") == ["orders.orders"] assert tags_for(app, "/api/billing/orders") == ["billing.orders"] @@ -180,22 +183,16 @@ def test_a_root_delivery_path_is_unchanged(self, dapr_config: Config) -> None: def test_the_dapr_delivery_path_never_moves(self, dapr_config: Config) -> None: """Dapr's two paths are fixed by its protocol, so its endpoint stays at the root.""" - builder = AppBuilder(dapr_config) - builder.with_namespace("orders", registration=AgentRegistration().with_handler(OrderHandler)) - - app = builder.build() + app = AgentGroup("g", {"orders": AppBuilder().with_handler(OrderHandler)}).assemble(dapr_config) assert {"/events/{topic}", "/dapr/subscribe"} <= set(paths(app)) assert "/api/orders/events/{topic}" not in paths(app) def test_two_agents_get_their_own_nats_delivery_paths(self, nats_config: Config) -> None: """Unprefixed, FastAPI would serve one agent's endpoint for both agents' deliveries.""" - registration = AgentRegistration().with_handler(OrderHandler) - builder = AppBuilder(nats_config) - builder.with_namespace("orders", registration=registration) - builder.with_namespace("billing", registration=registration) + declaration = AppBuilder().with_handler(OrderHandler) - app = builder.build() + app = AgentGroup("g", {"orders": declaration, "billing": declaration}).assemble(nats_config) assert {"/api/orders/events/{topic}", "/api/billing/events/{topic}"} <= set(paths(app)) @@ -206,3 +203,46 @@ async def test_a_root_document_is_unchanged(self, dapr_config: Config) -> None: document = await DaprEventing().subscribe() assert document == [{"pubsubname": "pubsub", "topic": "orders.created", "route": "/events/orders.created"}] + + +class TestCacheEndpointsPerAgent: + """``/cache/*`` is per agent, because one process-wide endpoint reports one agent's keys to another. + + The router is not keyed on the set of caches at request time -- a cache can be registered + after startup and routes cannot -- so what is per agent is the *mount*: one router per agent + that declared a cache, each resolving names within its own agent. + """ + + def test_an_agents_cache_endpoints_live_under_its_prefix(self, cache_config: Config) -> None: + declaration = AppBuilder().with_cache() + + app = AgentGroup("finance", {"orders": declaration}).assemble(cache_config) + + assert "/api/orders/cache/stats" in paths(app) + assert "/api/cache/stats" not in paths(app) + + def test_each_agent_gets_its_own(self, cache_config: Config) -> None: + orders = AppBuilder().with_cache() + billing = AppBuilder().with_cache(name="sessions") + + app = AgentGroup("finance", {"orders": orders, "billing": billing}).assemble(cache_config) + + assert {"/api/orders/cache/stats", "/api/billing/cache/stats"} <= set(paths(app)) + + def test_an_agent_that_declared_no_cache_gets_no_endpoint(self, cache_config: Config) -> None: + orders = AppBuilder().with_cache() + billing = AppBuilder() + + app = AgentGroup("finance", {"orders": orders, "billing": billing}).assemble(cache_config) + + assert "/api/billing/cache/stats" not in paths(app) + + def test_a_standalone_application_keeps_the_paths_it_had(self, cache_config: Config) -> None: + app = AppBuilder(cache_config).with_cache().build() + + assert "/api/cache/stats" in paths(app) + + def test_no_endpoint_at_all_without_a_cache(self, cache_config: Config) -> None: + app = AppBuilder(cache_config).build() + + assert not [path for path in paths(app) if "/cache/" in path] diff --git a/tests/unit/agents/app_builder/test_with_group.py b/tests/unit/agents/app_builder/test_with_group.py deleted file mode 100644 index 8c38ba14..00000000 --- a/tests/unit/agents/app_builder/test_with_group.py +++ /dev/null @@ -1,270 +0,0 @@ -"""Applying a resolved group: one namespace per agent, and the group's caches. - -``with_group`` is the wiring half of phase 8, and its contract is that it performs no I/O -- no -environment, no files, no ``sys.exit``, no knowledge of an agent repo's layout. That is why the -``GroupConfig`` here is always constructed literally: these tests state exact compositions -without arranging anything around the code under test. - -Importing an agent's module is the one thing it reaches outside for, and it is driven entirely by -the ``module`` strings the group carries -- so the declarations below live in this file and are -named by their real dotted paths. -""" - -from pathlib import Path -from typing import Any - -import pytest - -from blueprint.agents.app_builder import AgentRegistration, AppBuilder -from blueprint.agents.component.component import Component -from blueprint.agents.component.registry import DEFAULT_CACHE_NAME -from blueprint.agents.config import Config -from blueprint.agents.group_config import AgentSpec, GroupConfig, GroupConfigError -from blueprint.agents.models.config import CacheConfig -from blueprint.agents.services.service_base import ServiceBase - -_THIS = "tests.unit.agents.app_builder.test_with_group" - - -class OrderService(ServiceBase): - async def on_startup(self) -> None: - pass - - async def on_shutdown(self) -> None: - pass - - -class BillingService(ServiceBase): - async def on_startup(self) -> None: - pass - - async def on_shutdown(self) -> None: - pass - - -# The module-level declarations a group's `module` strings point at, exactly as an agent's own -# module would expose them. -order_registration = AgentRegistration().with_service(OrderService) -billing_registration = AgentRegistration().with_service(BillingService) -not_a_registration = "this is not an AgentRegistration" - - -@pytest.fixture -def config(tmp_path: Path) -> Config: - settings = tmp_path / "settings.toml" - settings.write_text( - '[development]\napp_environment = "development"\napp_name = "the-process"\napp_port = 8000\n\n' - "[development.order]\napp_port = 8000\n\n" - "[development.billing]\napp_port = 8000\n" - ) - return Config(settings_files=[str(settings)], root_path=str(tmp_path)) - - -def spec(name: str, attribute: str, *, critical: bool = True) -> AgentSpec: - return AgentSpec(name=name, module=f"{_THIS}:{attribute}", critical=critical) - - -def component_names() -> list[str]: - registry = Component.shared_registry - assert registry is not None - return sorted(registry.get_component_names_by_type(Component)) - - -class TestOneNamespacePerAgent: - def test_each_agent_is_applied_under_its_own_name(self, config: Config) -> None: - group = GroupConfig(name="finance", agents=(spec("order", "order_registration"), spec("billing", "billing_registration"))) - - AppBuilder(config).with_group(group) - - assert component_names() == ["billing_billing_service", "order_order_service"] - - def test_the_builder_records_the_agents_it_hosts(self, config: Config) -> None: - group = GroupConfig(name="finance", agents=(spec("order", "order_registration"), spec("billing", "billing_registration"))) - - builder = AppBuilder(config).with_group(group) - - assert builder.namespaces == ("order", "billing") - - def test_declaration_order_is_kept(self, config: Config) -> None: - group = GroupConfig(name="finance", agents=(spec("billing", "billing_registration"), spec("order", "order_registration"))) - - builder = AppBuilder(config).with_group(group) - - assert builder.namespaces == ("billing", "order") - - def test_it_returns_the_builder(self, config: Config) -> None: - builder = AppBuilder(config) - - assert builder.with_group(GroupConfig(name="empty", agents=())) is builder - - def test_a_group_of_one_is_an_ordinary_group(self, config: Config) -> None: - """Group size 1 is how an agent gets a process to itself; nothing about it is special.""" - group = GroupConfig(name="just-order", agents=(spec("order", "order_registration"),)) - - AppBuilder(config).with_group(group) - - assert component_names() == ["order_order_service"] - - def test_the_same_declaration_can_serve_two_agents(self, config: Config) -> None: - """One declaration, applied per agent -- the property the whole design rests on.""" - group = GroupConfig(name="two", agents=(spec("order", "order_registration"), spec("billing", "order_registration"))) - - AppBuilder(config).with_group(group) - - assert component_names() == ["billing_order_service", "order_order_service"] - - -class TestTheGroupsCaches: - def test_declared_caches_are_registered(self, config: Config, tmp_path: Path) -> None: - """A cache is process-wide, so the group declares it rather than any single agent.""" - config.get_cache_config = lambda: CacheConfig(cache_dir=str(tmp_path / "cache"), backend="disk") # type: ignore[method-assign] - group = GroupConfig(name="finance", agents=(spec("order", "order_registration"),), cache_names=("sessions", "prompts")) - - AppBuilder(config).with_group(group) - - registry = Component.shared_registry - assert registry is not None - assert sorted(registry.get_all_caches()) == ["prompts", "sessions"] - - def test_a_group_with_no_caches_registers_none(self, config: Config) -> None: - AppBuilder(config).with_group(GroupConfig(name="finance", agents=(spec("order", "order_registration"),))) - - registry = Component.shared_registry - assert registry is not None - assert registry.get_all_caches() == {} - - def test_the_default_cache_is_still_the_applications_to_add(self, config: Config, tmp_path: Path) -> None: - """with_cache() on the chain and the group's list compose.""" - config.get_cache_config = lambda: CacheConfig(cache_dir=str(tmp_path / "cache"), backend="disk") # type: ignore[method-assign] - group = GroupConfig(name="finance", agents=(), cache_names=("sessions",)) - - AppBuilder(config).with_cache().with_group(group) - - registry = Component.shared_registry - assert registry is not None - assert sorted(registry.get_all_caches()) == [DEFAULT_CACHE_NAME, "sessions"] - - -class TestLoadingADeclaration: - def test_a_missing_module_fails_a_critical_agent(self, config: Config) -> None: - group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module="no.such.module:registration"),)) - - with pytest.raises(GroupConfigError, match="could not be loaded and is critical"): - AppBuilder(config).with_group(group) - - def test_the_failure_names_the_agent_and_the_module(self, config: Config) -> None: - group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module="no.such.module:registration"),)) - - with pytest.raises(GroupConfigError, match=r"'order'.*no\.such\.module"): - AppBuilder(config).with_group(group) - - def test_a_missing_attribute_fails_a_critical_agent(self, config: Config) -> None: - group = GroupConfig(name="finance", agents=(spec("order", "nope"),)) - - with pytest.raises(GroupConfigError, match="has no attribute 'nope'"): - AppBuilder(config).with_group(group) - - def test_an_attribute_that_is_not_a_registration_is_refused(self, config: Config) -> None: - group = GroupConfig(name="finance", agents=(spec("order", "not_a_registration"),)) - - with pytest.raises(GroupConfigError, match="is a str, not an AgentRegistration"): - AppBuilder(config).with_group(group) - - @pytest.mark.parametrize("module", ["no_colon_at_all", ":registration", "module.path:"]) - def test_a_malformed_declaration_path_is_refused(self, config: Config, module: str) -> None: - group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module=module),)) - - with pytest.raises(GroupConfigError, match="is not a valid declaration path"): - AppBuilder(config).with_group(group) - - def test_a_non_critical_agent_is_skipped(self, config: Config, caplog: pytest.LogCaptureFixture) -> None: - """The flag is the deployment saying it would rather run the rest.""" - group = GroupConfig( - name="finance", - agents=( - AgentSpec(name="order", module="no.such.module:registration", critical=False), - spec("billing", "billing_registration"), - ), - ) - - with caplog.at_level("ERROR", logger="blueprint.agents.app_builder"): - builder = AppBuilder(config).with_group(group) - - assert builder.namespaces == ("billing",) - assert component_names() == ["billing_billing_service"] - assert "is not critical, so it is skipped" in caplog.text - - def test_a_skipped_agent_does_not_stop_the_ones_after_it(self, config: Config) -> None: - group = GroupConfig( - name="finance", - agents=( - AgentSpec(name="order", module="no.such.module:registration", critical=False), - spec("billing", "billing_registration"), - ), - ) - - AppBuilder(config).with_group(group) - - assert component_names() == ["billing_billing_service"] - - def test_a_critical_agent_stops_the_build_before_later_ones(self, config: Config) -> None: - """There is no partial build to unwind, so it fails rather than half-wiring the group.""" - group = GroupConfig( - name="finance", - agents=(AgentSpec(name="order", module="no.such.module:registration"), spec("billing", "billing_registration")), - ) - - with pytest.raises(GroupConfigError): - AppBuilder(config).with_group(group) - - assert "billing_billing_service" not in component_names() - - -class TestNoIoOfItsOwn: - def test_it_reads_no_environment(self, config: Config, monkeypatch: pytest.MonkeyPatch) -> None: - """The contract that keeps AppBuilder a pure function of its call sequence.""" - monkeypatch.setenv("BLUEPRINT_AGENTS", "something-else") - monkeypatch.setenv("BLUEPRINT_GROUP", "another-group") - group = GroupConfig(name="finance", agents=(spec("order", "order_registration"),)) - - builder = AppBuilder(config).with_group(group) - - assert builder.namespaces == ("order",) - - def test_a_group_can_be_constructed_literally(self, config: Config) -> None: - group = GroupConfig(name="finance", agents=(spec("order", "order_registration"),)) - - AppBuilder(config).with_group(group) - - assert component_names() == ["order_order_service"] - - -class TestFromGroup: - def test_it_resolves_and_applies_in_one_call(self, tmp_path: Path) -> None: - (tmp_path / "agents.toml").write_text(f'[agents.order]\nmodule = "{_THIS}:order_registration"\n') - settings = tmp_path / "settings.toml" - settings.write_text('[development]\napp_environment = "development"\napp_port = 8000\n') - config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) - - builder = AppBuilder.from_group(config, environ={"BLUEPRINT_AGENTS": "order", "BLUEPRINT_GROUP": "finance"}) - - assert builder.namespaces == ("order",) - assert component_names() == ["order_order_service"] - - def test_a_resolution_failure_propagates(self, tmp_path: Path) -> None: - settings = tmp_path / "settings.toml" - settings.write_text('[development]\napp_environment = "development"\napp_port = 8000\n') - config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) - - with pytest.raises(GroupConfigError, match="No agent map at"): - AppBuilder.from_group(config, environ={"BLUEPRINT_AGENTS": "order"}) - - def test_it_returns_a_builder_ready_to_chain(self, tmp_path: Path) -> None: - (tmp_path / "agents.toml").write_text(f'[agents.order]\nmodule = "{_THIS}:order_registration"\n') - settings = tmp_path / "settings.toml" - settings.write_text('[development]\napp_environment = "development"\napp_port = 8000\n') - config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) - - builder: Any = AppBuilder.from_group(config, environ={"BLUEPRINT_AGENTS": "order"}) - - assert isinstance(builder, AppBuilder) diff --git a/tests/unit/agents/component/test_name_uniqueness.py b/tests/unit/agents/component/test_name_uniqueness.py index 44b93c1c..9ebe3099 100644 --- a/tests/unit/agents/component/test_name_uniqueness.py +++ b/tests/unit/agents/component/test_name_uniqueness.py @@ -186,3 +186,33 @@ def test_renaming_an_unregistered_name_still_raises(self, config: Config) -> Non with pytest.raises(ValueError, match="does not exist"): planner.name = "something" + + +class TestBaseName: + """The unqualified half of a name, kept because it cannot be recovered from the qualified one.""" + + def test_it_is_the_derived_name_at_the_root(self, config: Config) -> None: + planner = Planner() + assert (planner.name, planner.base_name) == ("planner", "planner") + + def test_it_drops_the_namespace(self, config: Config) -> None: + with namespace_scope("orders"): + planner = Planner() + assert (planner.name, planner.base_name) == ("orders_planner", "planner") + + def test_an_explicit_name_is_kept_unqualified(self, config: Config) -> None: + with namespace_scope("orders"): + planner = Planner(name="scheduler") + assert (planner.name, planner.base_name) == ("orders_scheduler", "scheduler") + + def test_it_follows_a_rename(self, config: Config) -> None: + with namespace_scope("orders"): + planner = Planner() + planner.name = "scheduler" + assert (planner.name, planner.base_name) == ("orders_scheduler", "scheduler") + + def test_a_base_name_starting_with_its_namespace_is_not_stripped(self, config: Config) -> None: + """``qualified_component_name`` is not idempotent, which is why the half is stored.""" + with namespace_scope("billing"): + handler = BillingHandler() + assert (handler.name, handler.base_name) == ("billing_billing_handler", "billing_handler") diff --git a/tests/unit/agents/component/test_registry.py b/tests/unit/agents/component/test_registry.py index 01a34958..1637d665 100644 --- a/tests/unit/agents/component/test_registry.py +++ b/tests/unit/agents/component/test_registry.py @@ -369,6 +369,111 @@ def test_clear_empties_and_clears_every_cache(self, registry: Registry) -> None: assert registry.get_all_caches() == {} +class TestCachesPerAgent: + """A cache belongs to the agent that declared it, and to no other (spec sec. 8, D3). + + The store is keyed on ``(namespace, name)``, so the name alone no longer identifies a + cache. What each case below pins down is that there is **no route** from one agent to + another's cache: not by name, not through the root, and not by enumeration. + """ + + def test_a_view_registers_for_its_own_agent(self, registry: Registry) -> None: + """A component calls ``self.registry.add_cache(...)`` and names no namespace.""" + cache = MagicMock() + registry.for_namespace("orders").add_cache("sessions", cache) + assert registry.get_cache("sessions", namespace="orders") is cache + + def test_two_agents_may_both_declare_one_name(self, registry: Registry) -> None: + orders, billing = MagicMock(), MagicMock() + registry.add_cache("sessions", orders, namespace="orders") + registry.add_cache("sessions", billing, namespace="billing") + + assert registry.for_namespace("orders").get_cache("sessions") is orders + assert registry.for_namespace("billing").get_cache("sessions") is billing + + def test_one_name_registered_twice_for_one_agent_still_replaces(self, registry: Registry) -> None: + """Two agents are not a collision; the same agent twice still is, and warns.""" + first, second = MagicMock(), MagicMock() + registry.add_cache("sessions", first, namespace="orders") + registry.add_cache("sessions", second, namespace="orders") + assert registry.get_cache("sessions", namespace="orders") is second + + def test_an_agent_cannot_reach_a_neighbours_cache(self, registry: Registry) -> None: + registry.add_cache("sessions", MagicMock(), namespace="orders") + + with pytest.raises(ValueError, match="No cache registered as 'sessions' for agent 'billing'"): + registry.for_namespace("billing").get_cache("sessions") + + def test_an_agent_does_not_fall_back_to_the_root(self, registry: Registry) -> None: + """Components resolve namespace-then-root; caches deliberately do not.""" + registry.add_cache("sessions", MagicMock()) + + with pytest.raises(ValueError, match="for agent 'orders'"): + registry.for_namespace("orders").get_cache("sessions") + + def test_the_root_does_not_see_an_agents_cache(self, registry: Registry) -> None: + registry.add_cache("sessions", MagicMock(), namespace="orders") + assert registry.get_all_caches() == {} + assert registry.has_cache("sessions") is False + + def test_the_default_alias_is_per_agent(self, registry: Registry) -> None: + orders, billing = MagicMock(), MagicMock() + registry.for_namespace("orders").cache_service = orders + registry.for_namespace("billing").cache_service = billing + + assert registry.for_namespace("orders").cache_service is orders + assert registry.for_namespace("billing").cache_service is billing + + def test_the_alias_raises_for_an_agent_that_declared_none(self, registry: Registry) -> None: + """This is the check ``idempotency_enabled`` fails on, and it is now per agent.""" + registry.for_namespace("orders").cache_service = MagicMock() + + with pytest.raises(ValueError, match="No cache service registered for agent 'billing'"): + _ = registry.for_namespace("billing").cache_service + + def test_has_cache_answers_about_the_asking_agent(self, registry: Registry) -> None: + registry.for_namespace("orders").cache_service = MagicMock() + + assert registry.for_namespace("orders").has_cache() is True + assert registry.for_namespace("billing").has_cache() is False + + def test_get_all_caches_is_one_agents(self, registry: Registry) -> None: + registry.add_cache("sessions", MagicMock(), namespace="orders") + registry.add_cache("prompts", MagicMock(), namespace="billing") + + assert sorted(registry.get_all_caches("orders")) == ["sessions"] + assert sorted(registry.for_namespace("billing").get_all_caches()) == ["prompts"] + + def test_cache_entries_carries_the_agent_as_data(self, registry: Registry) -> None: + """As data, not as a prefix: a cache name may legally contain the separator.""" + orders, root = MagicMock(), MagicMock() + registry.add_cache("v2.sessions", orders, namespace="orders") + registry.add_cache("default", root) + + assert [(namespace, name) for namespace, name, _ in registry.cache_entries()] == [ + ("orders", "v2.sessions"), + ("", "default"), + ] + + def test_cache_entries_is_refused_on_a_view(self, registry: Registry) -> None: + """C6: a view is what agent code holds, so it must not enumerate the neighbours.""" + registry.add_cache("sessions", MagicMock(), namespace="orders") + + with pytest.raises(RuntimeError, match="asked for every cache in the process"): + registry.for_namespace("orders").cache_entries() + + def test_clear_clears_every_agents_cache(self, registry: Registry) -> None: + orders, billing = MagicMock(), MagicMock() + registry.add_cache("sessions", orders, namespace="orders") + registry.add_cache("sessions", billing, namespace="billing") + + registry.clear() + + orders.clear.assert_called_once() + billing.clear.assert_called_once() + assert registry.cache_entries() == [] + + class TestExecutors: """One thread pool per namespace, created only when something actually needs one.""" diff --git a/tests/unit/agents/config/test_agent_settings_fragments.py b/tests/unit/agents/config/test_agent_settings_fragments.py new file mode 100644 index 00000000..1ea969dc --- /dev/null +++ b/tests/unit/agents/config/test_agent_settings_fragments.py @@ -0,0 +1,251 @@ +"""An agent's own ``settings.toml`` becomes that agent's scope (spec sec. 5.3, D5). + +The requirement behind every case here is the one the whole feature rests on: **only ``main.py`` +may differ between a project deployed on its own and the same project hosted as one agent of a +group.** So an agent author keeps writing plain keys -- or a ``[default]`` section, which is what +every scaffolded project has -- in their own directory's file, and the build merges that file +under the agent's scope without the author knowing a scope exists. + +Two properties are pinned down. **Isolation**: a fragment can add to its own agent and to nothing +else, so there is no collision with a root key to report and no way for one agent to change what +a neighbour or the process reads. **Precedence**: what is already in the tree -- the group's own +``[default.]``, or an environment override -- wins, and the fragment fills the gaps. +""" + +from pathlib import Path + +import pytest + +from blueprint.agents.config import Config +from blueprint.agents.config.config import PROCESS_SCOPE_KEYS, ConfigError + + +@pytest.fixture +def config(tmp_path: Path) -> Config: + """A group's own settings: defaults for the process, plus one targeted agent value.""" + settings = tmp_path / "settings.toml" + settings.write_text( + '[default]\napp_name = "the-process"\napp_port = 8080\napp_environment = "development"\n' + 'model_name = "group-default"\n\n' + '[default.billing]\nmodel_name = "the-deployment-said-so"\n' + ) + return Config(settings_files=["settings.toml"], root_path=str(tmp_path)) + + +def fragment(tmp_path: Path, agent: str, body: str) -> Path: + """Write an agent's own settings file into its own directory, and return the path.""" + directory = tmp_path / "pkg" / agent + directory.mkdir(parents=True, exist_ok=True) + path = directory / "settings.toml" + path.write_text(body.replace("\n ", "\n")) + return path + + +class TestWhatAnAgentReads: + def test_a_plain_key_becomes_that_agents_value(self, config: Config, tmp_path: Path) -> None: + """Spec sec. 5.3: the author writes ``model_name``, not ``[default.orders]``.""" + config.merge_agent_settings("orders", fragment(tmp_path, "orders", 'model_name = "orders-model"\n')) + + assert config.for_namespace("orders").get("model_name") == "orders-model" + + def test_a_default_section_is_resolved_like_the_processs_own_file(self, config: Config, tmp_path: Path) -> None: + """Every scaffolded project writes ``[default]``, so a fragment has to mean the same by it.""" + config.merge_agent_settings("orders", fragment(tmp_path, "orders", '[default]\nmodel_name = "orders-model"\n')) + + assert config.for_namespace("orders").get("model_name") == "orders-model" + + def test_the_environment_section_wins_over_default(self, config: Config, tmp_path: Path) -> None: + body = """ + [default] + temperature = 0.2 + + [development] + temperature = 0.7 + """ + config.merge_agent_settings("orders", fragment(tmp_path, "orders", body)) + + assert config.for_namespace("orders").get("temperature") == 0.7 + + def test_another_environments_section_is_not_applied(self, config: Config, tmp_path: Path) -> None: + body = """ + [default] + temperature = 0.2 + + [production] + temperature = 0.0 + """ + config.merge_agent_settings("orders", fragment(tmp_path, "orders", body)) + + assert config.for_namespace("orders").get("temperature") == 0.2 + + def test_a_nested_table_stays_nested(self, config: Config, tmp_path: Path) -> None: + body = """ + [default.cache] + cache_dir = ".cache/orders" + """ + config.merge_agent_settings("orders", fragment(tmp_path, "orders", body)) + + assert config.for_namespace("orders").get("cache.cache_dir") == ".cache/orders" + + def test_a_top_level_table_is_a_value_not_an_environment(self, config: Config, tmp_path: Path) -> None: + """``[cache]`` beside ``[default]`` is this agent's cache configuration.""" + config.merge_agent_settings("orders", fragment(tmp_path, "orders", '[cache]\ncache_dir = ".cache/orders"\n')) + + assert config.for_namespace("orders").get("cache.cache_dir") == ".cache/orders" + + def test_a_root_default_is_still_the_fallback(self, config: Config, tmp_path: Path) -> None: + """A group's settings are defaults: a key the fragment does not mention still resolves.""" + config.merge_agent_settings("orders", fragment(tmp_path, "orders", "temperature = 0.7\n")) + + assert config.for_namespace("orders").get("model_name") == "group-default" + + def test_the_merged_keys_are_reported(self, config: Config, tmp_path: Path) -> None: + body = """ + model_name = "orders-model" + + [default.cache] + cache_dir = ".cache/orders" + """ + merged = config.merge_agent_settings("orders", fragment(tmp_path, "orders", body)) + + assert merged == ("cache", "model_name") + + +class TestIsolation: + def test_an_agent_cannot_change_what_the_root_reads(self, config: Config, tmp_path: Path) -> None: + config.merge_agent_settings("orders", fragment(tmp_path, "orders", 'model_name = "orders-model"\n')) + + assert config.get("model_name") == "group-default" + + def test_an_agent_cannot_change_what_a_neighbour_reads(self, config: Config, tmp_path: Path) -> None: + config.merge_agent_settings("orders", fragment(tmp_path, "orders", 'model_name = "orders-model"\n')) + + assert config.for_namespace("shipping").get("model_name") == "group-default" + + def test_two_agents_may_declare_the_same_key(self, config: Config, tmp_path: Path) -> None: + """The reason there is no collision to report: the two never occupy one slot.""" + config.merge_agent_settings("orders", fragment(tmp_path, "orders", 'model_name = "orders-model"\n')) + config.merge_agent_settings("shipping", fragment(tmp_path, "shipping", 'model_name = "shipping-model"\n')) + + assert ( + config.for_namespace("orders").get("model_name"), + config.for_namespace("shipping").get("model_name"), + ) == ("orders-model", "shipping-model") + + def test_a_view_cannot_merge_anything(self, config: Config, tmp_path: Path) -> None: + """C6: authoring another agent's configuration through a view is the breach reading one is.""" + view = config.for_namespace("orders") + + with pytest.raises(RuntimeError, match="A view resolves its own keys"): + view.merge_agent_settings("billing", fragment(tmp_path, "billing", 'model_name = "x"\n')) + + def test_the_root_is_not_an_agent(self, config: Config, tmp_path: Path) -> None: + with pytest.raises(ValueError, match="needs an agent's namespace"): + config.merge_agent_settings("", fragment(tmp_path, "orders", 'model_name = "x"\n')) + + +class TestPrecedence: + def test_the_groups_own_value_for_this_agent_wins(self, config: Config, tmp_path: Path) -> None: + """A deployment that named the agent meant it; the fragment is baked into the image.""" + config.merge_agent_settings("billing", fragment(tmp_path, "billing", 'model_name = "billing-model"\n')) + + assert config.for_namespace("billing").get("model_name") == "the-deployment-said-so" + + def test_the_fragment_fills_what_the_group_left_out(self, config: Config, tmp_path: Path) -> None: + body = """ + model_name = "billing-model" + temperature = 0.7 + """ + merged = config.merge_agent_settings("billing", fragment(tmp_path, "billing", body)) + + assert merged == ("temperature",) + assert config.for_namespace("billing").get("temperature") == 0.7 + + def test_a_nested_table_is_merged_key_by_key(self, config: Config, tmp_path: Path) -> None: + """Replacing the table would drop the group's value; being dropped by it would lose the agent's.""" + config._settings["orders"] = {"cache": {"size_limit": 500}} + body = """ + [default.cache] + cache_dir = ".cache/orders" + size_limit = 100 + """ + config.merge_agent_settings("orders", fragment(tmp_path, "orders", body)) + + view = config.for_namespace("orders") + assert (view.get("cache.size_limit"), view.get("cache.cache_dir")) == (500, ".cache/orders") + + +class TestProcessScopeKeys: + def test_a_port_is_ignored(self, config: Config, tmp_path: Path) -> None: + """One process, one HTTP server: a per-agent port is unbindable.""" + config.merge_agent_settings("orders", fragment(tmp_path, "orders", "app_port = 8000\n")) + + assert (config.get("app_port"), config.for_namespace("orders").get("app_port")) == (8080, 8080) + + def test_it_is_reported_with_the_file_and_the_value_in_force(self, config: Config, tmp_path: Path, caplog) -> None: + """The MUST this softens exists so the author can discover the value is inert.""" + path = fragment(tmp_path, "orders", "app_port = 8000\n") + + with caplog.at_level("WARNING", logger="blueprint.agents.config.config"): + config.merge_agent_settings("orders", path) + + assert "Agent 'orders' sets 'app_port'" in caplog.text + assert str(path) in caplog.text + assert "the group's own value (8080) is used" in caplog.text + + def test_the_report_says_when_the_group_sets_nothing(self, config: Config, tmp_path: Path, caplog) -> None: + with caplog.at_level("WARNING", logger="blueprint.agents.config.config"): + config.merge_agent_settings("orders", fragment(tmp_path, "orders", 'log_level = "DEBUG"\n')) + + assert "the group's settings do not set it" in caplog.text + + def test_an_existing_projects_file_is_hosted_unchanged(self, config: Config, tmp_path: Path) -> None: + """Every example project in this repository writes these three keys. Raising would fork the file.""" + body = """ + [default] + app_name = "Orders standalone" + app_port = 8000 + app_environment = "development" + log_level = "INFO" + model_name = "orders-model" + """ + merged = config.merge_agent_settings("orders", fragment(tmp_path, "orders", body)) + + assert merged == ("app_name", "model_name") + + def test_display_metadata_is_the_agents_own(self, config: Config, tmp_path: Path) -> None: + """A scoped app_name is read -- the NATS queue group falls back to it -- so it is not refused.""" + config.merge_agent_settings("orders", fragment(tmp_path, "orders", 'app_name = "Orders standalone"\n')) + + assert config.for_namespace("orders").get("app_name") == "Orders standalone" + assert config.get("app_name") == "the-process" + + @pytest.mark.parametrize("key", sorted(PROCESS_SCOPE_KEYS)) + def test_every_listed_key_is_dropped(self, config: Config, tmp_path: Path, key: str) -> None: + merged = config.merge_agent_settings("orders", fragment(tmp_path, "orders", f'{key} = "value"\nmodel_name = "kept"\n')) + + assert merged == ("model_name",) + + def test_a_deployment_identity_key_is_dropped_too(self, config: Config, tmp_path: Path) -> None: + """C6 makes these unreadable, so a fragment declaring one is writing into a wall.""" + merged = config.merge_agent_settings("orders", fragment(tmp_path, "orders", 'blueprint_group = "finance"\n')) + + assert merged == () + + +class TestAFileThatIsNotThere: + def test_an_agent_need_not_ship_one(self, config: Config, tmp_path: Path) -> None: + assert config.merge_agent_settings("orders", tmp_path / "pkg" / "orders" / "settings.toml") == () + + def test_the_processs_own_settings_file_is_not_merged_again(self, config: Config, tmp_path: Path) -> None: + """An agent declared beside the group's own file would otherwise inherit every root key.""" + assert config.merge_agent_settings("orders", tmp_path / "settings.toml") == () + assert config.for_namespace("orders").get("app_name") == "the-process" + + def test_an_empty_file_contributes_nothing(self, config: Config, tmp_path: Path) -> None: + assert config.merge_agent_settings("orders", fragment(tmp_path, "orders", "")) == () + + def test_a_broken_file_is_reported_not_skipped(self, config: Config, tmp_path: Path) -> None: + """A file that is there was meant to be used, so failing to read it is an error.""" + with pytest.raises(ConfigError, match="could not be read"): + config.merge_agent_settings("orders", fragment(tmp_path, "orders", "this is not = = toml\n")) diff --git a/tests/unit/agents/io/api/actuators/health/test_health_cache.py b/tests/unit/agents/io/api/actuators/health/test_health_cache.py index b94c0dc4..b72a5a04 100644 --- a/tests/unit/agents/io/api/actuators/health/test_health_cache.py +++ b/tests/unit/agents/io/api/actuators/health/test_health_cache.py @@ -2,7 +2,10 @@ from unittest.mock import AsyncMock, MagicMock, patch +import pytest + +from blueprint.agents.io.api.actuators.health.health_base import HealthCheckEntry from blueprint.agents.io.api.actuators.health.health_cache import HealthCheckCache from blueprint.agents.models.api import ComponentHealth @@ -14,6 +17,11 @@ def _make_provider(status: str, message: str = "ok") -> MagicMock: return provider +def _entry(name: str, status: str, message: str = "ok", namespace: str = "") -> HealthCheckEntry: + """A registered check: the checker plus the agent it belongs to.""" + return HealthCheckEntry(name=name, namespace=namespace, checker=_make_provider(status, message)) + + class TestHealthCheckCacheInit: def test_initial_status_is_up(self) -> None: cache = HealthCheckCache() @@ -25,7 +33,7 @@ def test_custom_initial_status(self) -> None: def test_no_providers_on_init(self) -> None: cache = HealthCheckCache() - assert cache._health_check_provider is None + assert cache._entries == () def test_default_interval_is_30(self) -> None: cache = HealthCheckCache() @@ -33,52 +41,46 @@ def test_default_interval_is_30(self) -> None: class TestHealthCheckCacheProviderUpdates: - def test_set_health_check_provider_stores_provider(self) -> None: + def test_set_health_entries_stores_them(self) -> None: cache = HealthCheckCache() - provider = {"db": _make_provider("healthy")} - cache.set_health_check_provider(provider) - assert cache._health_check_provider is provider + entry = _entry("db", "healthy") + cache.set_health_entries([entry]) + assert cache._entries == (entry,) + + def test_setting_again_replaces_the_whole_set(self) -> None: + """ActuatorApi accumulates and re-pushes, so this object holds one authoritative list.""" + cache = HealthCheckCache() + cache.set_health_entries([_entry("db", "healthy")]) + second = _entry("nats", "healthy") + cache.set_health_entries([second]) + assert cache._entries == (second,) class TestRunHealthChecks: async def test_all_healthy_providers_yield_up_status(self) -> None: cache = HealthCheckCache() - cache.set_health_check_provider( - { - "db": _make_provider("healthy"), - "nats": _make_provider("healthy"), - } - ) + cache.set_health_entries([_entry("db", "healthy"), _entry("nats", "healthy")]) await cache._run_health_checks() result = await cache.get_health_status() assert result.status == "UP" async def test_one_unhealthy_provider_yields_down_status(self) -> None: cache = HealthCheckCache() - cache.set_health_check_provider( - { - "db": _make_provider("healthy"), - "nats": _make_provider("unhealthy", "timeout"), - } - ) + cache.set_health_entries([_entry("db", "healthy"), _entry("nats", "unhealthy", "timeout")]) await cache._run_health_checks() result = await cache.get_health_status() assert result.status == "DOWN" async def test_all_unhealthy_yields_down_status(self) -> None: cache = HealthCheckCache() - cache.set_health_check_provider( - { - "db": _make_provider("unhealthy"), - } - ) + cache.set_health_entries([_entry("db", "unhealthy")]) await cache._run_health_checks() result = await cache.get_health_status() assert result.status == "DOWN" async def test_components_populated_after_run(self) -> None: cache = HealthCheckCache() - cache.set_health_check_provider({"db": _make_provider("healthy")}) + cache.set_health_entries([_entry("db", "healthy")]) await cache._run_health_checks() result = await cache.get_health_status() assert "db" in result.components @@ -87,7 +89,7 @@ async def test_exception_in_provider_marks_component_unhealthy(self) -> None: provider = MagicMock() provider.health_check = AsyncMock(side_effect=RuntimeError("boom")) cache = HealthCheckCache() - cache.set_health_check_provider({"flaky": provider}) + cache.set_health_entries([HealthCheckEntry(name="flaky", namespace="", checker=provider)]) await cache._run_health_checks() result = await cache.get_health_status() assert result.components["flaky"].status == "unhealthy" @@ -96,7 +98,7 @@ async def test_exception_message_included_in_component_health(self) -> None: provider = MagicMock() provider.health_check = AsyncMock(side_effect=RuntimeError("connection refused")) cache = HealthCheckCache() - cache.set_health_check_provider({"svc": provider}) + cache.set_health_entries([HealthCheckEntry(name="svc", namespace="", checker=provider)]) await cache._run_health_checks() result = await cache.get_health_status() assert "connection refused" in result.components["svc"].message @@ -128,7 +130,7 @@ class TestHealthCheckCacheStartStop: async def test_start_runs_initial_check(self) -> None: cache = HealthCheckCache(check_interval_seconds=3600) provider = _make_provider("healthy") - cache.set_health_check_provider({"svc": provider}) + cache.set_health_entries([HealthCheckEntry(name="svc", namespace="", checker=provider)]) with patch("blueprint.agents.io.api.actuators.health.health_cache.AsyncIOScheduler") as mock_scheduler_cls: mock_sched = MagicMock() mock_scheduler_cls.return_value = mock_sched @@ -149,3 +151,49 @@ async def test_start_is_idempotent(self) -> None: async def test_stop_is_safe_when_not_started(self) -> None: cache = HealthCheckCache() await cache.stop() # must not raise + + +class TestAnEntryIsAttributedToItsAgent: + """D4: the payload key is a rendering; the agent is carried as data beside it.""" + + async def test_the_root_keeps_the_bare_name(self) -> None: + cache = HealthCheckCache() + cache.set_health_entries([_entry("db", "healthy")]) + await cache._run_health_checks() + assert "db" in (await cache.get_health_status()).components + + async def test_an_agents_check_is_prefixed(self) -> None: + cache = HealthCheckCache() + cache.set_health_entries([_entry("db", "healthy", namespace="orders")]) + await cache._run_health_checks() + assert "orders.db" in (await cache.get_health_status()).components + + async def test_two_agents_declaring_one_name_are_two_components(self) -> None: + """A dict of name -> checker lost one of these, silently.""" + cache = HealthCheckCache() + cache.set_health_entries( + [ + _entry("db", "healthy", namespace="orders"), + _entry("db", "unhealthy", "down", namespace="billing"), + ] + ) + await cache._run_health_checks() + + components = (await cache.get_health_status()).components + assert set(components) == {"orders.db", "billing.db"} + assert (components["orders.db"].status, components["billing.db"].status) == ("healthy", "unhealthy") + + async def test_a_failure_is_logged_with_its_agent(self, caplog: pytest.LogCaptureFixture) -> None: + """Whose check is failing is the question asked of a group, not only which one.""" + provider = MagicMock() + provider.health_check = AsyncMock(side_effect=RuntimeError("boom")) + cache = HealthCheckCache() + cache.set_health_entries([HealthCheckEntry(name="db", namespace="orders", checker=provider)]) + + with caplog.at_level("WARNING", logger="blueprint.agents.io.api.actuators.health.health_cache"): + await cache._run_health_checks() + + assert "Health check 'db' of agent 'orders' failed" in caplog.text + + def test_the_root_agent_is_named_where_a_value_is_required(self) -> None: + assert (_entry("db", "healthy").agent, _entry("db", "healthy", namespace="orders").agent) == ("", "orders") diff --git a/tests/unit/agents/io/api/actuators/test_actuator_api.py b/tests/unit/agents/io/api/actuators/test_actuator_api.py index f4d37bcd..44f441c8 100644 --- a/tests/unit/agents/io/api/actuators/test_actuator_api.py +++ b/tests/unit/agents/io/api/actuators/test_actuator_api.py @@ -9,6 +9,7 @@ from blueprint.agents.component.component import Component from blueprint.agents.component.registry import Registry from blueprint.agents.config import Config +from blueprint.agents.io.api.actuators.health.health_base import HealthCheckEntry from blueprint.agents.io.api.actuators.actuator_api import ActuatorApi @@ -147,13 +148,13 @@ async def test_on_startup_uses_configured_interval(self, actuator_api: ActuatorA mock_cache_cls.assert_called_once_with(check_interval_seconds=60) async def test_on_startup_registers_pending_providers(self, actuator_api: ActuatorApi, mock_config: MagicMock) -> None: - provider = MagicMock() - actuator_api._pending_providers = {"db": provider} + entry = HealthCheckEntry(name="db", namespace="", checker=MagicMock()) + actuator_api.add_health_providers([entry]) with patch("blueprint.agents.io.api.actuators.actuator_api.HealthCheckCache") as mock_cache_cls: mock_cache_cls.return_value.start = AsyncMock() - mock_cache_cls.return_value.set_health_check_provider = MagicMock() + mock_cache_cls.return_value.set_health_entries = MagicMock() await actuator_api.on_startup() - mock_cache_cls.return_value.set_health_check_provider.assert_called_once_with({"db": provider}) + mock_cache_cls.return_value.set_health_entries.assert_called_once_with([entry]) async def test_on_shutdown_stops_health_cache(self, actuator_api: ActuatorApi, mock_config: MagicMock) -> None: mock_cache = MagicMock() @@ -338,3 +339,47 @@ async def test_an_agent_scoped_actuator_reports_only_its_own_scope(self, grouped assert result.namespaces == {} assert result.settings["APP_NAME"] == "root-app" + + +class TestRegisteringChecks: + """``add_health_providers`` is the one funnel, so the rules about entries live there.""" + + def test_checks_accumulate_across_calls(self, actuator_api: ActuatorApi) -> None: + """It used to assign: a with_health_checker() after build() wiped every wired check.""" + first = HealthCheckEntry(name="nats_client", namespace="", checker=MagicMock()) + second = HealthCheckEntry(name="db", namespace="", checker=MagicMock()) + + actuator_api.add_health_providers([first]) + actuator_api.add_health_providers([second]) + + assert actuator_api.health_entries == (first, second) + + def test_two_agents_may_use_one_name(self, actuator_api: ActuatorApi) -> None: + orders = HealthCheckEntry(name="db", namespace="orders", checker=MagicMock()) + billing = HealthCheckEntry(name="db", namespace="billing", checker=MagicMock()) + + actuator_api.add_health_providers([orders, billing]) + + assert [entry.key for entry in actuator_api.health_entries] == ["orders.db", "billing.db"] + + def test_a_duplicate_key_is_refused(self, actuator_api: ActuatorApi) -> None: + """A dict kept the last one, so a check could vanish with nothing logged.""" + actuator_api.add_health_providers([HealthCheckEntry(name="db", namespace="orders", checker=MagicMock())]) + + with pytest.raises(ValueError, match="already taken"): + actuator_api.add_health_providers([HealthCheckEntry(name="db", namespace="orders", checker=MagicMock())]) + + def test_a_duplicate_within_one_call_is_refused(self, actuator_api: ActuatorApi) -> None: + entry = HealthCheckEntry(name="db", namespace="", checker=MagicMock()) + + with pytest.raises(ValueError, match="already taken"): + actuator_api.add_health_providers([entry, HealthCheckEntry(name="db", namespace="", checker=MagicMock())]) + + def test_a_check_added_after_startup_reaches_the_live_cache(self, actuator_api: ActuatorApi) -> None: + cache = MagicMock() + actuator_api._health_cache = cache + entry = HealthCheckEntry(name="db", namespace="", checker=MagicMock()) + + actuator_api.add_health_providers([entry]) + + cache.set_health_entries.assert_called_once_with([entry]) diff --git a/tests/unit/agents/services/eventing/test_event_processing_namespaces.py b/tests/unit/agents/services/eventing/test_event_processing_namespaces.py index 1c567c21..01c83bef 100644 --- a/tests/unit/agents/services/eventing/test_event_processing_namespaces.py +++ b/tests/unit/agents/services/eventing/test_event_processing_namespaces.py @@ -65,9 +65,10 @@ def calls() -> list[str]: def two_agent_config(tmp_path: Path) -> Config: """A root and two agents, one of which enables deduplication and the other does not. - A cache is registered as well, because ``orders`` opts into deduplication and a chain - refuses to resolve that policy with nowhere to keep the markers. It also puts the - agent-scoped cache lens in the dispatch path, which is where it will actually be used. + A cache is registered as well, and **for ``orders``** rather than at the root, because + ``orders`` is the agent that opts into deduplication and a chain refuses to resolve that + policy with nowhere to keep the markers. A root cache would not do: a cache belongs to the + agent that declared it and no other agent can reach it (spec sec. 8). """ settings = tmp_path / "settings.toml" content = """ @@ -88,10 +89,10 @@ def two_agent_config(tmp_path: Path) -> Config: config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) Component.configure(config) - cache = CacheBackendFactory.create(CacheConfig(cache_dir=str(tmp_path / "cache"))) + cache = CacheBackendFactory.create(CacheConfig(cache_dir=str(tmp_path / "cache")), namespace="orders") registry = Component.shared_registry assert registry is not None - registry.add_cache(DEFAULT_CACHE_NAME, cache) + registry.add_cache(DEFAULT_CACHE_NAME, cache, namespace="orders") return config diff --git a/tests/unit/agents/services/infrastructure/test_agent_scoped_cache.py b/tests/unit/agents/services/infrastructure/test_agent_scoped_cache.py deleted file mode 100644 index b8accc7b..00000000 --- a/tests/unit/agents/services/infrastructure/test_agent_scoped_cache.py +++ /dev/null @@ -1,169 +0,0 @@ -"""Unit tests for AgentScopedCache -- one cache, isolated per agent (spec sec. 8).""" - -from collections.abc import Iterator -from pathlib import Path - -import pytest - -from blueprint.agents.component.component import Component -from blueprint.agents.component.registry import Registry -from blueprint.agents.services.infrastructure.agent_scoped_cache import AgentScopedCache -from blueprint.agents.services.infrastructure.cache_service import DiskCacheService - - -@pytest.fixture -def backend(tmp_path: Path) -> Iterator[DiskCacheService]: - """A real disk cache, because what is under test is which keys end up where.""" - cache = DiskCacheService(cache_dir=str(tmp_path / "cache"), enable_locking=False) - yield cache - cache.close() - - -@pytest.fixture -def orders(backend: DiskCacheService) -> AgentScopedCache: - return AgentScopedCache(backend, "orders") - - -@pytest.fixture -def billing(backend: DiskCacheService) -> AgentScopedCache: - return AgentScopedCache(backend, "billing") - - -class TestIsolation: - def test_two_agents_do_not_see_each_others_values(self, orders: AgentScopedCache, billing: AgentScopedCache) -> None: - """The whole point: the same key in the same partition name, kept apart.""" - orders.set("laptop", {"price": 1}, namespace="prices") - billing.set("laptop", {"price": 2}, namespace="prices") - - assert orders.get("laptop", namespace="prices") == {"price": 1} - assert billing.get("laptop", namespace="prices") == {"price": 2} - - def test_a_neighbours_key_reads_as_absent(self, orders: AgentScopedCache, billing: AgentScopedCache) -> None: - billing.set("laptop", {"price": 2}, namespace="prices") - assert orders.get("laptop", namespace="prices") is None - assert orders.exists("laptop", namespace="prices") is False - - def test_one_backend_serves_every_agent(self, orders: AgentScopedCache, billing: AgentScopedCache, backend: DiskCacheService) -> None: - """No second directory and no second connection -- that is why the keys carry the agent.""" - assert orders.backend is billing.backend is backend - - def test_the_partition_carries_the_agent(self, orders: AgentScopedCache, billing: AgentScopedCache, backend: DiskCacheService) -> None: - orders.set("laptop", 1, namespace="prices") - billing.set("laptop", 2, namespace="prices") - assert backend.list_namespaces() == ["billing.prices", "orders.prices"] - - def test_an_agent_lists_its_partitions_by_the_names_it_used(self, orders: AgentScopedCache, billing: AgentScopedCache) -> None: - orders.set("laptop", 1, namespace="prices") - orders.set("session", 1, namespace="sessions") - billing.set("laptop", 2, namespace="prices") - - assert orders.list_namespaces() == ["prices", "sessions"] - - def test_the_default_partition_is_scoped_too(self, orders: AgentScopedCache, billing: AgentScopedCache) -> None: - orders.set("k", 1) - billing.set("k", 2) - assert (orders.get("k"), billing.get("k")) == (1, 2) - - def test_delete_only_reaches_this_agent(self, orders: AgentScopedCache, billing: AgentScopedCache) -> None: - orders.set("laptop", 1, namespace="prices") - billing.set("laptop", 2, namespace="prices") - - orders.delete("laptop", namespace="prices") - - assert orders.get("laptop", namespace="prices") is None - assert billing.get("laptop", namespace="prices") == 2 - - def test_claim_is_per_agent(self, orders: AgentScopedCache, billing: AgentScopedCache) -> None: - """Two agents' schedulers must not steal each other's tick slots.""" - assert orders.claim("tick", "held", namespace="ticks", ttl=60) is True - assert billing.claim("tick", "held", namespace="ticks", ttl=60) is True - assert orders.claim("tick", "held", namespace="ticks", ttl=60) is False - - -class TestClear: - def test_clearing_one_partition_leaves_the_neighbour(self, orders: AgentScopedCache, billing: AgentScopedCache) -> None: - orders.set("laptop", 1, namespace="prices") - billing.set("laptop", 2, namespace="prices") - - orders.clear("prices") - - assert orders.get("laptop", namespace="prices") is None - assert billing.get("laptop", namespace="prices") == 2 - - def test_clearing_everything_means_everything_of_this_agent(self, orders: AgentScopedCache, billing: AgentScopedCache) -> None: - """The backend's own clear(None) would take the neighbours with it.""" - orders.set("a", 1, namespace="prices") - orders.set("b", 1, namespace="sessions") - billing.set("c", 2, namespace="prices") - - orders.clear() - - assert orders.list_namespaces() == [] - assert billing.get("c", namespace="prices") == 2 - - -class TestOwnership: - def test_closing_the_shared_backend_is_refused(self, orders: AgentScopedCache, backend: DiskCacheService) -> None: - with pytest.raises(RuntimeError, match="shared with every other agent"): - orders.close() - - def test_the_root_namespace_cannot_be_wrapped(self, backend: DiskCacheService) -> None: - """The root reads the backend directly; wrapping it would move an existing app's keys.""" - with pytest.raises(ValueError, match="needs an agent namespace"): - AgentScopedCache(backend, "") - - def test_it_does_not_register_itself(self, backend: DiskCacheService) -> None: - """One lens per agent per cache would otherwise add a registry entry each.""" - Component.reset_shared_state() - registry = Registry(Component) - Component.shared_registry = registry - - AgentScopedCache(backend, "orders") - - assert registry.get_component_names_by_type(AgentScopedCache) == [] - - def test_stats_come_from_the_backend_and_name_the_agent(self, orders: AgentScopedCache) -> None: - """Size and eviction belong to the one shared store; there is nothing per-agent to report.""" - assert orders.get_stats()["agent"] == "orders" - - def test_hash_is_the_backends(self, orders: AgentScopedCache, backend: DiskCacheService) -> None: - assert orders.hash("laptop") == backend.hash("laptop") - - -class TestThroughTheRegistry: - """How a component actually gets one: it asks for a cache and is handed its own view.""" - - @pytest.fixture - def registry(self, backend: DiskCacheService) -> Registry: - Component.reset_shared_state() - registry = Registry(Component) - Component.shared_registry = registry - registry.add_cache("default", backend) - return registry - - def test_a_namespaced_view_gets_a_scoped_cache(self, registry: Registry) -> None: - cache = registry.for_namespace("orders").cache_service - assert isinstance(cache, AgentScopedCache) - assert cache.agent == "orders" - - def test_the_root_gets_the_backend_itself(self, registry: Registry, backend: DiskCacheService) -> None: - """Unchanged for every single-agent application, and the opt-in for a shared cache.""" - assert registry.cache_service is backend - - def test_asking_twice_gives_one_lens(self, registry: Registry) -> None: - view = registry.for_namespace("orders") - assert view.cache_service is view.cache_service - - def test_two_agents_get_different_lenses(self, registry: Registry) -> None: - orders = registry.for_namespace("orders").cache_service - billing = registry.for_namespace("billing").cache_service - assert orders is not billing - - def test_a_named_cache_is_scoped_too(self, registry: Registry, backend: DiskCacheService) -> None: - registry.add_cache("sessions", backend) - cache = registry.for_namespace("orders").get_cache("sessions") - assert isinstance(cache, AgentScopedCache) - - def test_an_unregistered_name_still_raises_on_a_view(self, registry: Registry) -> None: - with pytest.raises(ValueError, match="No cache registered as 'prompts'"): - registry.for_namespace("orders").get_cache("prompts") diff --git a/tests/unit/agents/services/infrastructure/test_cache_backend_factory.py b/tests/unit/agents/services/infrastructure/test_cache_backend_factory.py index 16a6929e..63c57430 100644 --- a/tests/unit/agents/services/infrastructure/test_cache_backend_factory.py +++ b/tests/unit/agents/services/infrastructure/test_cache_backend_factory.py @@ -254,3 +254,47 @@ def test_the_name_is_checked_before_anything_is_built(self, disk_config: CacheCo with pytest.raises(ValueError): CacheBackendFactory.create(disk_config, name="../evil") assert not (tmp_path / "evil").exists() + + +class TestAgentIsolation: + """Two agents declaring one name get two stores, not one shared by accident (D3). + + The isolation is structural: it is the directory and the key prefix that differ, so it + cannot be defeated by a call site that forgets to pass something. + """ + + def test_the_root_stores_where_it_always_did(self, disk_config: CacheConfig) -> None: + assert CacheBackendFactory.storage_name("", "sessions") == "sessions" + + def test_an_agents_cache_carries_the_agent(self) -> None: + assert CacheBackendFactory.storage_name("orders", "sessions") == "orders.sessions" + + def test_the_separator_keeps_it_a_legal_cache_name(self) -> None: + """``.`` is in the cache alphabet and not in the namespace alphabet, so neither can forge the other.""" + CacheBackendFactory.validate_name(CacheBackendFactory.storage_name("orders", "sessions")) + + def test_two_agents_do_not_share_a_directory(self, disk_config: CacheConfig) -> None: + orders = CacheBackendFactory.create(disk_config, name="sessions", namespace="orders") + billing = CacheBackendFactory.create(disk_config, name="sessions", namespace="billing") + + assert orders.cache_dir != billing.cache_dir # type: ignore[attr-defined] + + def test_an_agents_default_cache_is_its_own_directory(self, disk_config: CacheConfig) -> None: + """The default name is not special once an agent owns it: only the root keeps the mount itself.""" + agent = CacheBackendFactory.create(disk_config, namespace="orders") + root = CacheBackendFactory.create(disk_config) + + assert str(agent.cache_dir) == str(Path(root.cache_dir) / "orders.default") # type: ignore[attr-defined] + + def test_the_directory_stays_inside_the_configured_one(self, disk_config: CacheConfig) -> None: + """Under ``readOnlyRootFilesystem`` only the mount is writable, so a sibling would fail.""" + agent = CacheBackendFactory.create(disk_config, name="sessions", namespace="orders") + + assert Path(disk_config.cache_dir) in Path(agent.cache_dir).parents # type: ignore[attr-defined] + + def test_the_redis_prefix_carries_the_agent(self, disk_config: CacheConfig) -> None: + config = CacheConfig(cache_dir=disk_config.cache_dir, backend="redis", key_prefix="app") + + assert CacheBackendFactory._scoped_key_prefix(config, CacheBackendFactory.storage_name("orders", "sessions")) == ( + "app:orders.sessions" + ) diff --git a/tests/unit/agents/test_agent_group.py b/tests/unit/agents/test_agent_group.py new file mode 100644 index 00000000..a6f1aa59 --- /dev/null +++ b/tests/unit/agents/test_agent_group.py @@ -0,0 +1,493 @@ +"""Collecting several agents into one process: what a group accepts, and what it refuses. + +``AgentGroup`` is the only object that knows several agents can share a process, and it is +therefore the only one that imposes the group's rules. Two properties are under test here and +neither belongs to ``AppBuilder``: + +- **Assembly.** Named, unbuilt declarations in; one application out, with each agent's recorded + calls replayed inside its own namespace. +- **Refusal.** Everything a group cannot honour, refused at assembly with a message naming the + agent -- while the same declaration goes on working standalone, which is what + *standalone is permissive, the group has rules* means. + +``from_config`` performs no I/O, which is why the ``GroupConfig`` here is always constructed +literally: these cases state exact compositions without arranging anything around the code under +test. Importing an agent's module is the one thing it reaches outside for, and that is driven +entirely by the ``module`` strings the group carries -- so the declarations below live in this +file and are named by their real dotted paths. +""" + +from collections.abc import Generator +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock, patch + +import pytest + +from blueprint.agents.agent_group import AgentGroup +from blueprint.agents.app_builder import AppBuilder +from blueprint.agents.component.component import Component +from blueprint.agents.config import Config +from blueprint.agents.group_config import AgentSpec, GroupConfig, GroupConfigError +from blueprint.agents.models.config import CacheConfig +from blueprint.agents.services.service_base import ServiceBase + +_THIS = "tests.unit.agents.test_agent_group" + + +class OrderService(ServiceBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class BillingService(ServiceBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +# The module-level declarations a group's `module` strings point at, exactly as an agent's own +# module would expose them: an AppBuilder that has never been built. +order_declaration = AppBuilder().with_service(OrderService) +billing_declaration = AppBuilder().with_service(BillingService) +not_a_declaration = "this is not an AppBuilder" + + +def registry() -> Any: + """The process's registry, which every assertion below reads after assembly.""" + assert Component.shared_registry is not None + return Component.shared_registry + + +@pytest.fixture(autouse=True) +def reset_component_state() -> Generator[None]: + with patch( + "blueprint.agents.component.registry.CorrelationContextProvider.get_correlation_context", + return_value=MagicMock(), + ): + yield + Component.reset_shared_state() + + +@pytest.fixture +def config(tmp_path: Path) -> Config: + settings = tmp_path / "settings.toml" + settings.write_text( + '[development]\napp_environment = "development"\napp_name = "the-process"\napp_port = 8000\n\n' + "[development.order]\napp_port = 8000\n\n" + "[development.billing]\napp_port = 8000\n" + ) + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + +def spec(name: str, attribute: str, *, critical: bool = True) -> AgentSpec: + return AgentSpec(name=name, module=f"{_THIS}:{attribute}", critical=critical) + + +def component_names() -> list[str]: + registry = Component.shared_registry + if registry is None: + return [] + return sorted(registry.get_component_names_by_type(Component)) + + +def service_names() -> list[str]: + registry = Component.shared_registry + if registry is None: + return [] + return sorted(registry.get_component_names_by_type(ServiceBase)) + + +class TestOneNamespacePerAgent: + def test_each_agent_is_assembled_under_its_own_name(self, config: Config) -> None: + group = AgentGroup("finance", {"order": order_declaration, "billing": billing_declaration}) + + group.assemble(config) + + assert service_names() == ["billing_billing_service", "order_order_service"] + + def test_a_group_of_one_is_an_ordinary_group(self, config: Config) -> None: + """Group size 1 is how an agent gets a process to itself; nothing about it is special.""" + AgentGroup("just-order", {"order": order_declaration}).assemble(config) + + assert service_names() == ["order_order_service"] + + def test_the_same_declaration_can_serve_two_agents(self, config: Config) -> None: + """One declaration, replayed per agent -- the property the whole design rests on.""" + AgentGroup("two", {"order": order_declaration, "billing": order_declaration}).assemble(config) + + assert service_names() == ["billing_order_service", "order_order_service"] + + def test_a_declaration_is_not_consumed_by_being_assembled(self, config: Config) -> None: + """Replay reads the declarations; it does not build the agent's own builder.""" + AgentGroup("finance", {"order": order_declaration}).assemble(config) + + assert order_declaration.is_built is False + assert len(order_declaration.declarations) == 1 + + def test_the_root_builder_hosts_every_agent(self, config: Config) -> None: + """build() wires one transport per hosted agent, so the list has to reach it.""" + group = AgentGroup("finance", {"order": order_declaration, "billing": billing_declaration}) + + app = group.assemble(config) + + assert app is not None + assert service_names() == ["billing_billing_service", "order_order_service"] + + def test_it_returns_one_application(self, config: Config) -> None: + assert AgentGroup("finance", {"order": order_declaration}).assemble(config).title == "the-process" + + def test_an_empty_group_still_builds(self, config: Config) -> None: + """A process hosting nothing is a legitimate, if useless, thing to assemble.""" + assert AgentGroup("empty", {}).assemble(config) is not None + + +class TestAgentNames: + def test_an_illegal_name_is_refused(self) -> None: + with pytest.raises(ValueError, match="legal namespace"): + AgentGroup("finance", {"Order": order_declaration}) + + def test_the_root_is_refused(self) -> None: + with pytest.raises(ValueError, match="cannot be named"): + AgentGroup("finance", {"": order_declaration}) + + def test_the_names_are_kept_in_order(self) -> None: + group = AgentGroup("finance", {"order": order_declaration, "billing": billing_declaration}) + assert list(group.agents) == ["order", "billing"] + + def test_the_group_name_is_readable(self) -> None: + assert AgentGroup("finance", {}).name == "finance" + + +class TestWhatAGroupRefuses: + """Spec sec. 4.2's table. Each of these works standalone and will go on working.""" + + def test_a_declaration_that_brought_its_own_config_is_refused(self, config: Config) -> None: + group = AgentGroup("finance", {"order": AppBuilder(config).with_service(OrderService)}) + + with pytest.raises(ValueError, match="one process has one settings tree"): + group.assemble(config) + + def test_that_refusal_names_the_agent_and_the_fix(self, config: Config) -> None: + group = AgentGroup("finance", {"order": AppBuilder(config)}) + + with pytest.raises(ValueError, match=r"Agent 'order'.*AppBuilder\(\) with no argument"): + group.assemble(config) + + def test_an_already_built_declaration_is_refused(self, config: Config) -> None: + """Checked before the configuration rule: build() adopts a config, so a built builder + reports one too, and the configuration message would otherwise be the only one seen.""" + already = AppBuilder().with_service(OrderService) + already.build(config) + Component.reset_shared_state() + + with pytest.raises(ValueError, match="has already been built"): + AgentGroup("finance", {"order": already}).assemble(config) + + def test_an_instance_is_refused(self, config: Config) -> None: + Component.configure(config) + declaration = AppBuilder().with_service(OrderService()) + Component.reset_shared_state() + + with pytest.raises(ValueError, match="as an instance by agent 'order'"): + AgentGroup("finance", {"order": declaration}).assemble(config) + + def test_the_instance_refusal_points_at_the_class_form(self, config: Config) -> None: + Component.configure(config) + declaration = AppBuilder().with_service(OrderService()) + Component.reset_shared_state() + + with pytest.raises(ValueError, match=r"with_service\(OrderService, \.\.\.\)"): + AgentGroup("finance", {"order": declaration}).assemble(config) + + def test_a_factory_is_accepted(self, config: Config) -> None: + """The capability the instance refusal costs nothing, because this recovers it.""" + declaration = AppBuilder().with_service(lambda: OrderService()) + + AgentGroup("finance", {"order": declaration}).assemble(config) + + assert service_names() == ["order_order_service"] + + def test_nothing_is_assembled_when_a_refusal_fires(self, config: Config) -> None: + """The refusals run before any replay, so a bad group leaves no half-built registry.""" + group = AgentGroup("finance", {"order": order_declaration, "billing": AppBuilder(config)}) + + with pytest.raises(ValueError): + group.assemble(config) + + assert service_names() == [] + + +class TestTheGroupsCaches: + """A group declares no caches: every cache belongs to the agent that declared it (D3).""" + + def test_a_group_cannot_declare_a_cache(self) -> None: + """There is no process-wide cache, so there is no argument for naming one.""" + with pytest.raises(TypeError): + AgentGroup("finance", {"order": order_declaration}, cache_names=("sessions",)) # type: ignore[call-arg] + + def test_a_group_whose_agents_declare_none_registers_none(self, config: Config) -> None: + AgentGroup("finance", {"order": order_declaration}).assemble(config) + + assert registry().cache_entries() == [] + + def test_an_agents_own_cache_is_carried_over_and_belongs_to_it(self, config: Config, tmp_path: Path) -> None: + """A with_cache() in an agent's declaration is replayed like everything else.""" + config.get_cache_config = lambda: CacheConfig(cache_dir=str(tmp_path / "cache"), backend="disk") # type: ignore[method-assign] + declaration = AppBuilder().with_service(OrderService).with_cache(name="sessions") + + AgentGroup("finance", {"order": declaration}).assemble(config) + + assert [(namespace, name) for namespace, name, _ in registry().cache_entries()] == [("order", "sessions")] + assert registry().get_all_caches() == {}, "the root declared none, so the root has none" + + def test_two_agents_declaring_one_name_get_separate_stores(self, config: Config, tmp_path: Path) -> None: + """The whole of D3: ``sessions`` in two agents is two caches, not one shared by accident.""" + config.get_cache_config = lambda: CacheConfig(cache_dir=str(tmp_path / "cache"), backend="disk") # type: ignore[method-assign] + order = AppBuilder().with_service(OrderService).with_cache(name="sessions") + billing = AppBuilder().with_service(BillingService).with_cache(name="sessions") + + AgentGroup("finance", {"order": order, "billing": billing}).assemble(config) + + theirs = registry().get_cache("sessions", namespace="order") + neighbours = registry().get_cache("sessions", namespace="billing") + assert theirs is not neighbours + assert theirs.cache_dir != neighbours.cache_dir # type: ignore[attr-defined] + + def test_neither_agent_can_read_the_others_cache(self, config: Config, tmp_path: Path) -> None: + config.get_cache_config = lambda: CacheConfig(cache_dir=str(tmp_path / "cache"), backend="disk") # type: ignore[method-assign] + order = AppBuilder().with_service(OrderService).with_cache(name="sessions") + billing = AppBuilder().with_service(BillingService) + + AgentGroup("finance", {"order": order, "billing": billing}).assemble(config) + + with pytest.raises(ValueError, match="No cache registered as 'sessions' for agent 'billing'"): + registry().for_namespace("billing").get_cache("sessions") + + def test_a_health_checker_is_carried_over(self, config: Config) -> None: + """Recording it is what stops a group silently dropping an agent's readiness checks.""" + checker = MagicMock() + declaration = AppBuilder().with_service(OrderService).with_health_checker("db", checker) + + with patch("blueprint.agents.app_builder.ActuatorApi") as actuator, patch("blueprint.agents.app_builder.FastAPI"): + AgentGroup("finance", {"order": declaration}).assemble(config) + + entries = actuator.return_value.add_health_providers.call_args[0][0] + assert [(entry.key, entry.checker) for entry in entries] == [("order.db", checker)] + + +class TestLoadingADeclaration: + def test_a_missing_module_fails_a_critical_agent(self) -> None: + group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module="no.such.module:declaration"),)) + + with pytest.raises(GroupConfigError, match="could not be loaded and is critical"): + AgentGroup.from_config(group) + + def test_the_failure_names_the_agent_and_the_module(self) -> None: + group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module="no.such.module:declaration"),)) + + with pytest.raises(GroupConfigError, match=r"'order'.*no\.such\.module"): + AgentGroup.from_config(group) + + def test_a_missing_attribute_fails_a_critical_agent(self) -> None: + with pytest.raises(GroupConfigError, match="has no attribute 'nope'"): + AgentGroup.from_config(GroupConfig(name="finance", agents=(spec("order", "nope"),))) + + def test_an_attribute_that_is_not_a_builder_is_refused(self) -> None: + with pytest.raises(GroupConfigError, match="is a str, not an AppBuilder"): + AgentGroup.from_config(GroupConfig(name="finance", agents=(spec("order", "not_a_declaration"),))) + + @pytest.mark.parametrize("module", ["no_colon_at_all", ":declaration", "module.path:"]) + def test_a_malformed_declaration_path_is_refused(self, module: str) -> None: + group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module=module),)) + + with pytest.raises(GroupConfigError, match="is not a valid declaration path"): + AgentGroup.from_config(group) + + def test_a_non_critical_agent_is_skipped(self, caplog: pytest.LogCaptureFixture) -> None: + """The flag is the deployment saying it would rather run the rest.""" + group = GroupConfig( + name="finance", + agents=( + AgentSpec(name="order", module="no.such.module:declaration", critical=False), + spec("billing", "billing_declaration"), + ), + ) + + with caplog.at_level("ERROR", logger="blueprint.agents.agent_group"): + assembled = AgentGroup.from_config(group) + + assert list(assembled.agents) == ["billing"] + assert "is not critical, so it is skipped" in caplog.text + + def test_a_skipped_agent_does_not_stop_the_ones_after_it(self, config: Config) -> None: + group = GroupConfig( + name="finance", + agents=( + AgentSpec(name="order", module="no.such.module:declaration", critical=False), + spec("billing", "billing_declaration"), + ), + ) + + AgentGroup.from_config(group).assemble(config) + + assert service_names() == ["billing_billing_service"] + + def test_a_critical_agent_stops_resolution_before_later_ones(self, config: Config) -> None: + """There is no partial build to unwind, so it fails rather than half-wiring the group.""" + group = GroupConfig( + name="finance", + agents=(AgentSpec(name="order", module="no.such.module:declaration"), spec("billing", "billing_declaration")), + ) + + with pytest.raises(GroupConfigError): + AgentGroup.from_config(group) + + assert service_names() == [] + + +class TestNoIoOfItsOwn: + def test_from_config_reads_no_environment(self, config: Config, monkeypatch: pytest.MonkeyPatch) -> None: + """The contract that keeps a group a pure function of the composition it was given.""" + monkeypatch.setenv("BLUEPRINT_AGENTS", "something-else") + monkeypatch.setenv("BLUEPRINT_GROUP", "another-group") + + assembled = AgentGroup.from_config(GroupConfig(name="finance", agents=(spec("order", "order_declaration"),))) + + assert list(assembled.agents) == ["order"] + + def test_a_group_can_be_constructed_literally(self, config: Config) -> None: + AgentGroup("finance", {"order": order_declaration}).assemble(config) + + assert service_names() == ["order_order_service"] + + +class TestResolve: + def test_it_resolves_and_loads_in_one_call(self, tmp_path: Path) -> None: + (tmp_path / "agents.toml").write_text(f'[agents.order]\nmodule = "{_THIS}:order_declaration"\n') + settings = tmp_path / "settings.toml" + settings.write_text('[development]\napp_environment = "development"\napp_port = 8000\n') + config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + group = AgentGroup.resolve(config, environ={"BLUEPRINT_AGENTS": "order", "BLUEPRINT_GROUP": "finance"}) + + assert group.name == "finance" + assert list(group.agents) == ["order"] + + def test_a_resolution_failure_propagates(self, tmp_path: Path) -> None: + settings = tmp_path / "settings.toml" + settings.write_text('[development]\napp_environment = "development"\napp_port = 8000\n') + config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + with pytest.raises(GroupConfigError, match="No agent map at"): + AgentGroup.resolve(config, environ={"BLUEPRINT_AGENTS": "order"}) + + def test_it_returns_a_group_ready_to_assemble(self, tmp_path: Path) -> None: + (tmp_path / "agents.toml").write_text(f'[agents.order]\nmodule = "{_THIS}:order_declaration"\n') + settings = tmp_path / "settings.toml" + settings.write_text('[development]\napp_environment = "development"\napp_port = 8000\n') + config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + group: Any = AgentGroup.resolve(config, environ={"BLUEPRINT_AGENTS": "order"}) + + assert isinstance(group, AgentGroup) + + +class TestTheBuilderKnowsNothingAboutGroups: + def test_app_builder_has_no_group_methods(self) -> None: + """Collection is the collector's job. An AppBuilder never learns it can be collected.""" + assert not hasattr(AppBuilder, "with_group") + assert not hasattr(AppBuilder, "from_group") + + +def agent_settings(tmp_path: Path, body: str) -> Path: + """Write an agent's own settings file into a directory of its own, and return the path. + + Not ``tmp_path`` itself: that is where the group's own settings file lives, and a fragment + that *is* one of the process's settings files is skipped rather than merged a second time. + """ + directory = tmp_path / "agent" + directory.mkdir(exist_ok=True) + path = directory / "settings.toml" + path.write_text(f"{body}\n") + return path + + +class ConfigReadingService(ServiceBase): + """A service that reads its configuration where a project's own service would: at construction.""" + + seen: dict[str, object] = {} + + def __init__(self) -> None: + super().__init__() + ConfigReadingService.seen[self.namespace] = self.config.get("model_name") + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class TestEachAgentsOwnSettings: + """An agent's own ``settings.toml`` is merged under its scope at assembly (spec sec. 5.3, D5). + + What the merge itself does is pinned down in + ``tests/unit/agents/config/test_agent_settings_fragments.py``; these cases are about the + group -- where the file is looked for, and that it is merged early enough to be read. + """ + + def test_the_file_is_looked_for_beside_the_declaration_module(self) -> None: + """One rule an author can see: the settings.toml in the agent's own directory.""" + group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module=f"{_THIS}:order_declaration"),)) + + resolved = AgentGroup.from_config(group) + + assert resolved.settings["order"] == Path(__file__).parent / "settings.toml" + + def test_an_agent_that_ships_none_is_simply_an_agent_without_settings(self, config: Config) -> None: + """This test package has no settings.toml, so the path resolves to nothing to merge.""" + group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module=f"{_THIS}:order_declaration"),)) + + AgentGroup.from_config(group).assemble(config) + + assert service_names() == ["order_order_service"] + + def test_a_fragment_is_merged_under_its_agents_scope(self, config: Config, tmp_path: Path) -> None: + fragment = agent_settings(tmp_path, 'model_name = "orders-own-model"') + + AgentGroup("finance", {"order": order_declaration}, settings={"order": fragment}).assemble(config) + + assert config.for_namespace("order").get("model_name") == "orders-own-model" + + def test_it_is_merged_before_the_agents_components_are_built(self, config: Config, tmp_path: Path) -> None: + """A file merged after build() would have been read too late to matter.""" + ConfigReadingService.seen = {} + fragment = agent_settings(tmp_path, 'model_name = "orders-own-model"') + declaration = AppBuilder().with_service(ConfigReadingService) + + AgentGroup("finance", {"order": declaration}, settings={"order": fragment}).assemble(config) + + assert ConfigReadingService.seen == {"order": "orders-own-model"} + + def test_one_agents_file_does_not_reach_another(self, config: Config, tmp_path: Path) -> None: + ConfigReadingService.seen = {} + fragment = agent_settings(tmp_path, 'model_name = "orders-own-model"') + order = AppBuilder().with_service(ConfigReadingService) + billing = AppBuilder().with_service(BillingService) + + AgentGroup("finance", {"order": order, "billing": billing}, settings={"order": fragment}).assemble(config) + + assert config.for_namespace("billing").get("model_name") is None + + def test_a_group_that_was_given_none_merges_nothing(self, config: Config) -> None: + group = AgentGroup("finance", {"order": order_declaration}) + + group.assemble(config) + + assert group.settings == {} diff --git a/tests/unit/agents/test_entrypoint.py b/tests/unit/agents/test_entrypoint.py index 381e462f..a1a7e91b 100644 --- a/tests/unit/agents/test_entrypoint.py +++ b/tests/unit/agents/test_entrypoint.py @@ -13,7 +13,7 @@ import pytest from blueprint.agents import entrypoint -from blueprint.agents.app_builder import AgentRegistration, AppBuilder +from blueprint.agents.app_builder import AppBuilder from blueprint.agents.config import Config from blueprint.agents.component.component import Component from blueprint.agents.services.service_base import ServiceBase @@ -29,7 +29,8 @@ async def on_shutdown(self) -> None: pass -order_registration = AgentRegistration().with_service(OrderService) +# What a project's main.py contains: an AppBuilder that has never been built. +order_declaration = AppBuilder().with_service(OrderService) @pytest.fixture(autouse=True) @@ -54,7 +55,7 @@ def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: what the container's ``WORKDIR`` provides. So this fixture reproduces the container's shape rather than passing paths the real entry point has no parameter for. """ - (tmp_path / "agents.toml").write_text(f'[agents.order]\nmodule = "{_THIS}:order_registration"\n') + (tmp_path / "agents.toml").write_text(f'[agents.order]\nmodule = "{_THIS}:order_declaration"\n') (tmp_path / "settings.toml").write_text('[development]\napp_environment = "development"\napp_name = "the-process"\napp_port = 8000\n') monkeypatch.chdir(tmp_path) return tmp_path @@ -163,17 +164,21 @@ def test_the_module_has_a_main_guard(self) -> None: class TestOneDeclarationServesBothDeploymentShapes: """The same module, run standalone and run as a group -- spec sec. 11's single ``main.py``. - ``order_registration`` above is the whole of what a project's ``main.py`` needs to contain: - no ``AppBuilder``, no ``Config``, no ``run_app``, no ``if __name__``, no namespace and no - group. These cases prove that one such module serves both shapes, so there is nothing to - keep in sync between them. + ``order_declaration`` above is the whole of what a project's ``main.py`` needs to contain: + one unbuilt ``AppBuilder``, and no ``Config``, no ``run_app``, no ``if __name__``, no + namespace and no group. These cases prove that one such module serves both shapes, so + there is nothing to keep in sync between them. """ def test_the_declaration_runs_standalone(self, project: Path) -> None: - """What an existing main.py does, unchanged: build it at the root and serve it.""" + """What a migrated main.py does: build the declaration at the root and serve it. + + A builder separate from ``order_declaration`` only because a builder builds once and + this file exercises both shapes; a real process runs one of them. + """ config = Config(settings_files=["settings.toml"]) - app = AppBuilder(config).with_registration(order_registration).build() + app = AppBuilder().with_service(OrderService).build(config) assert app is not None assert component_names() == ["order_service"] @@ -187,7 +192,7 @@ def test_the_same_declaration_runs_as_a_group_of_one(self, project: Path) -> Non def test_the_same_declaration_runs_beside_another_agent(self, project: Path) -> None: (project / "agents.toml").write_text( - f'[agents.order]\nmodule = "{_THIS}:order_registration"\n\n[agents.billing]\nmodule = "{_THIS}:order_registration"\n' + f'[agents.order]\nmodule = "{_THIS}:order_declaration"\n\n[agents.billing]\nmodule = "{_THIS}:order_declaration"\n' ) entrypoint.build_group_app(environ={"BLUEPRINT_AGENTS": "order,billing"}) diff --git a/tests/unit/agents/test_frozen_compatibility.py b/tests/unit/agents/test_frozen_compatibility.py new file mode 100644 index 00000000..79978c01 --- /dev/null +++ b/tests/unit/agents/test_frozen_compatibility.py @@ -0,0 +1,256 @@ +"""The frozen compatibility suite: what an existing single-agent project already does. + +**Never update this file to accommodate an API change.** That is the whole of its value, and it +is spec sec. 10.2's requirement in one sentence: if a case here needs editing, a break shipped, +and the break is the finding -- not the test. A deliberate break is recorded in the changelog and +released with notes (sec. 10.1); anything else is a regression to fix in the framework. + +Every case below is written the way a project in `examples/` writes it today -- instance forms +included, because four of the seven examples pass constructed objects +(``.with_rest_api(InventoryApi())``) -- and asserts the observable thing that project depends on: +the paths it serves, the registry names its lookups use, the readiness entries its probe reports, +the cache its services share. Nothing here mentions a namespace, a group, or an agent, because a +single-agent application has none of those and must not have to learn about them. + +Scope: what unit tests can hold. The generated-project smoke test sec. 10.2 also asks for -- +``asbs setup``, then build and start the result unchanged -- needs Docker and is not written; see +the changelog's open points. +""" + +from collections.abc import Generator +from pathlib import Path +from typing import Any + +import pytest +from fastapi import FastAPI + +from blueprint.agents import AppBuilder, Config +from blueprint.agents.component.component import Component +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.io.api.actuators.health.health_base import HealthCheckerBase +from blueprint.agents.io.api.rest_api_base import RestApiBase +from blueprint.agents.models.api import ComponentHealth +from blueprint.agents.models.events import GenericCloudEvent +from blueprint.agents.services.infrastructure.cache_service import CacheService +from blueprint.agents.services.service_base import ServiceBase + +# --------------------------------------------------------------------------- +# A project, written the way the examples are +# --------------------------------------------------------------------------- + + +class InventoryService(ServiceBase): + async def on_startup(self) -> None: + self.cache = self.registry.cache_service + + async def on_shutdown(self) -> None: + pass + + +class PricingService(ServiceBase): + async def on_startup(self) -> None: + self.cache = self.registry.cache_service + + async def on_shutdown(self) -> None: + pass + + +class InventoryApi(RestApiBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + @RestApiBase.get("/inventory", tags=["inventory"]) + async def list_inventory(self) -> list[str]: + return [] + + +class StockHandler(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return ["stock.changed"] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict) -> Any: + return None + + +class DatabaseChecker(HealthCheckerBase): + async def health_check(self) -> ComponentHealth: + return ComponentHealth(status="healthy", message="ok") + + +@pytest.fixture(autouse=True) +def reset_component_state() -> Generator[None]: + """One process per case, as a deployment has one. + + Test infrastructure, not an accommodation: ``Component`` holds the registry and the + configuration for the life of a process, and a test file is many processes in one. + """ + yield + Component.reset_shared_state() + + +@pytest.fixture +def config(tmp_path: Path) -> Config: + """An example project's settings.toml, key for key.""" + settings = tmp_path / "settings.toml" + settings.write_text( + '[default]\napp_name = "Inventory API"\napp_port = 8000\napp_environment = "development"\n' + 'log_level = "INFO"\n\n' + f'[default.cache]\ncache_dir = "{(tmp_path / ".cache" / "inventory").as_posix()}"\nsize_limit = 100000000\n' + "default_ttl = 300\n" + ) + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + +def registry() -> Any: + assert Component.shared_registry is not None + return Component.shared_registry + + +def paths(app: FastAPI) -> list[str]: + return sorted(app.openapi()["paths"]) + + +class TestTheShapeEveryExampleUses: + """``AppBuilder(config)...build()`` in one expression, assigned to ``app``.""" + + def test_a_service_an_api_and_a_cache(self, config: Config) -> None: + app = AppBuilder(config).with_service(InventoryService).with_rest_api(InventoryApi()).with_cache().build() + + assert isinstance(app, FastAPI) + + def test_a_chain_of_handlers_and_services(self, config: Config) -> None: + app = AppBuilder(config).with_service(InventoryService).with_handler(StockHandler).with_rest_api(InventoryApi).with_cache().build() + + assert isinstance(app, FastAPI) + + def test_an_instance_is_accepted(self, config: Config) -> None: + """Four of the seven examples pass a constructed object. Standalone, that is supported.""" + AppBuilder(config).with_rest_api(InventoryApi()).with_cache().build() + + assert registry().get_component("inventory_api") is not None + + def test_the_builder_is_still_fluent(self, config: Config) -> None: + builder = AppBuilder(config) + + assert builder.with_service(InventoryService) is builder + + +class TestPositionalCacheArguments: + """Spec sec. 10.1 names these two calls explicitly. They are written positionally in the wild.""" + + def test_with_cache_disabled(self, config: Config) -> None: + AppBuilder(config).with_service(InventoryService).with_cache(False).build() + + assert registry().get_all_caches() == {} + + def test_with_cache_without_locking(self, config: Config) -> None: + AppBuilder(config).with_service(InventoryService).with_cache(True, False).build() + + cache = registry().get_cache() + assert cache._enable_locking is False + + def test_with_cache_default(self, config: Config) -> None: + AppBuilder(config).with_service(InventoryService).with_cache().build() + + assert isinstance(registry().get_cache(), CacheService) + + +class TestTheRegistryNamesLookupsUse: + def test_a_component_keeps_its_derived_name(self, config: Config) -> None: + """No namespace, so no prefix: ``get_component("inventory_service")`` still resolves.""" + AppBuilder(config).with_service(InventoryService).with_cache().build() + + assert registry().get_component("inventory_service") is not None + + def test_an_explicit_name_is_kept_verbatim(self, config: Config) -> None: + AppBuilder(config).with_service(InventoryService, name="stock").with_cache().build() + + assert registry().get_component("stock") is not None + + def test_the_default_cache_keeps_its_backend_name(self, config: Config) -> None: + AppBuilder(config).with_service(InventoryService).with_cache().build() + + assert registry().get_component("disk_cache_service") is registry().get_cache() + + def test_the_cache_service_alias_reads_the_default_cache(self, config: Config) -> None: + AppBuilder(config).with_service(InventoryService).with_cache().build() + + assert registry().cache_service is registry().get_cache() + + def test_two_services_share_one_cache(self, config: Config) -> None: + """The shared-cache example's whole point: what one service writes, the other reads.""" + AppBuilder(config).with_service(InventoryService).with_service(PricingService).with_cache().build() + + first = registry().get_service(InventoryService) + second = registry().get_service(PricingService) + assert first.registry.cache_service is second.registry.cache_service + + +class TestThePathsAProjectServes: + def test_a_rest_api_is_mounted_under_api(self, config: Config) -> None: + app = AppBuilder(config).with_rest_api(InventoryApi()).build() + + assert "/api/inventory" in paths(app) + + def test_its_tags_are_not_rewritten(self, config: Config) -> None: + app = AppBuilder(config).with_rest_api(InventoryApi()).build() + + operations = app.openapi()["paths"]["/api/inventory"] + assert sorted({tag for operation in operations.values() for tag in operation.get("tags", [])}) == ["inventory"] + + def test_the_cache_endpoints_are_unprefixed(self, config: Config) -> None: + app = AppBuilder(config).with_service(InventoryService).with_cache().build() + + assert "/api/cache/stats" in paths(app) + + def test_the_actuators_are_where_they_were(self, config: Config) -> None: + app = AppBuilder(config).with_service(InventoryService).build() + + assert {"/health/ready", "/health/live", "/info"} <= set(paths(app)) + + +class TestTheReadinessPayload: + def test_the_default_cache_is_the_entry_called_cache(self, config: Config) -> None: + builder = AppBuilder(config).with_service(InventoryService).with_cache() + + builder.build() + + assert "cache" in [entry.key for entry in builder._actuator_api.health_entries] + + def test_a_custom_checker_keeps_its_bare_name(self, config: Config) -> None: + """Sec. 10: ``with_health_checker`` keys are unchanged at the root.""" + builder = AppBuilder(config).with_health_checker("database", DatabaseChecker()) + + builder.build() + + assert "database" in [entry.key for entry in builder._actuator_api.health_entries] + + +class TestComponentsNeedNoChange: + def test_a_service_takes_no_new_constructor_argument(self, config: Config) -> None: + """Sec. 4.3: a project's component is written exactly as before, ``super().__init__()``.""" + Component.configure(config) + + service = InventoryService() + + assert (service.name, service.namespace) == ("inventory_service", "") + + def test_a_component_resolves_the_registry_and_config_it_always_did(self, config: Config) -> None: + Component.configure(config) + + service = InventoryService() + + assert service.registry is Component.shared_registry + assert service.config is config diff --git a/tests/unit/agents/test_group_config.py b/tests/unit/agents/test_group_config.py index 4eb4c861..2affbd29 100644 --- a/tests/unit/agents/test_group_config.py +++ b/tests/unit/agents/test_group_config.py @@ -60,11 +60,17 @@ def test_the_agents_module_comes_from_the_image(self, project: Config) -> None: assert group.agents[0] == AgentSpec(name="invoice", module="agents.invoice.declaration:registration", critical=True) - def test_declared_caches_are_carried(self, project: Config) -> None: - """A cache is process-wide, so it is the group's to declare rather than an agent's.""" + def test_a_declared_cache_list_is_read_by_nothing(self, project: Config) -> None: + """A cache belongs to the agent that declared it (D3), so a group declares none. + + The group file in this fixture still carries ``cache_names``. It is *ignored* rather + than refused, so a file written against the earlier shape still starts the process it + describes -- a rollout must not fail over a key that has become inert. + """ group = GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "finance"}) - assert group.cache_names == ("sessions",) + assert group.agent_names == ("invoice", "order") + assert not hasattr(group, "cache_names") def test_another_group_in_the_same_file(self, project: Config) -> None: group = GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "contracts"}) @@ -161,7 +167,7 @@ def test_the_environment_overrides_the_files_agent_list(self, project: Config) - def test_the_files_other_values_survive_the_override(self, project: Config) -> None: group = GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "finance", "BLUEPRINT_AGENTS": "dunning"}) - assert (group.name, group.cache_names) == ("finance", ("sessions",)) + assert (group.name, group.agent_names) == ("finance", ("dunning",)) def test_the_source_of_each_value_is_logged(self, project: Config, caplog: pytest.LogCaptureFixture) -> None: """The first question asked of a group with the wrong contents is where they came from.""" @@ -260,7 +266,7 @@ def test_it_performs_no_io_once_constructed(self) -> None: """Constructed literally, so a test states a composition instead of arranging files.""" group = GroupConfig(name="finance", agents=(AgentSpec(name="invoice", module="pkg:reg"),)) - assert (group.name, group.agent_names, group.cache_names) == ("finance", ("invoice",), ()) + assert (group.name, group.agent_names) == ("finance", ("invoice",)) def test_it_is_frozen(self) -> None: group = GroupConfig(name="finance", agents=()) From 2ff4b0ed3e3be1572499cf34230dd26e1a0adac1 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:44:56 +0200 Subject: [PATCH 012/133] docs: write AGENTS.md, guard its design rules, and settle the cache documents AGENTS.md is the file CLAUDE.md has been citing for months and did not exist. Its design rules now have test guards, which found and fixed real violations. Four overlapping cache documents became one, rewritten against the code -- which turned up a 500 in GET /cache/stats, fixed in the same change. Co-Authored-By: Claude Opus 5 (1M context) --- AGENTS.md | 246 +++++ CHANGELOG.md | 2 +- CLAUDE.md | 3 +- README.md | 2 +- docs/README.md | 2 +- docs/concepts/cache-architecture.md | 181 ---- docs/concepts/cache-system-overview.md | 232 ----- docs/concepts/caching.md | 506 ++++----- docs/guides/caching-getting-started.md | 208 ---- .../2026-04-01-component-naming-refactor.md | 0 .../2026-07-06-sessions-agent-registration.md | 2 +- ...26-08-28-multi-agent-grouping-changelog.md | 275 ++++- ...7-06-sessions-agent-registration-design.md | 0 .../agent_generator/generator/generator.py | 16 +- .../agents/clients/io/dapr_client.py | 4 - .../agents/io/api/utilities/cache.py | 15 +- src/blueprint/agents/models/api.py | 35 +- tests/unit/agents/TESTS.md | 28 + tests/unit/agents/app_builder/TESTS.md | 1 - .../app_builder/test_declaration_surface.py | 216 ---- tests/unit/agents/io/TESTS.md | 2 +- .../agents/io/api/utilities/test_cache.py | 82 +- tests/unit/agents/services/TESTS.md | 1 - tests/unit/agents/test_design_rules.py | 980 ++++++++++++++++++ 24 files changed, 1930 insertions(+), 1109 deletions(-) create mode 100644 AGENTS.md delete mode 100644 docs/concepts/cache-architecture.md delete mode 100644 docs/concepts/cache-system-overview.md delete mode 100644 docs/guides/caching-getting-started.md rename docs/{superpowers => }/plans/2026-04-01-component-naming-refactor.md (100%) rename docs/{superpowers => }/plans/2026-07-06-sessions-agent-registration.md (99%) rename docs/{superpowers => }/specs/2026-07-06-sessions-agent-registration-design.md (100%) create mode 100644 tests/unit/agents/TESTS.md delete mode 100644 tests/unit/agents/app_builder/test_declaration_surface.py create mode 100644 tests/unit/agents/test_design_rules.py diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..d1ca24ca --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,246 @@ +# AGENTS.md + +Architecture, component patterns, testing conventions and **design rules** for this repository, +shared across every AI assistant and every human working in it. `CLAUDE.md` holds the commands +and the per-feature process; this file holds what the code has to be like and why. + +Each rule below states the rule, the reason, and **the failure it prevents**. That last part is +not decoration: a rule without its failure is advice, and advice gets argued away by the next +person with a deadline. Most of these were bought with a defect -- either one that shipped or one +found by probing -- and the failure line is the receipt. + +If a rule and the code disagree, one of them is wrong and it is worth finding out which before +writing anything. If a rule and a specification disagree, see *The spec wins on precedence, not +on correctness* below. + +--- + +## Where things are + +`src/blueprint/agents/` is the framework; `src/blueprint/agent_generator/` is the `asbs` +scaffolder that generates projects against it. Inside the framework: + +| Path | What lives there | +|---|---| +| `app_builder.py` | The declaration API. `with_*` records; `build()` constructs, wires and returns the `FastAPI` app | +| `agent_group.py` | Several agents in one process: named declarations in, one application out | +| `group_config.py` | Which agents *this* process runs, resolved from the environment and the group file | +| `entrypoint.py` | `python -m blueprint.agents.entrypoint` -- the container's command | +| `component/` | `Component` (registry name, namespace, config view, executor), `Registry`, `namespace.py` | +| `handler/` | `EventHandlerBase`, the `HandlerChain`, dispatch and deduplication | +| `services/` | `ServiceBase`, the eventing services, and the infrastructure services (caches) | +| `io/api/` | `RestApiBase`, the actuators (`/health`, `/info`, `/status`), the eventing endpoints, schedulers | +| `clients/` | `ClientBase`, `IOClientBase` (NATS, Dapr), the AI clients | +| `agent/` | `AgentRuntime` and `AgentBuilder` -- an LLM runtime and its fluent declaration | +| `config/` | `Config` (Dynaconf), the logging manager | +| `models/` | Pydantic models: events, configuration, API payloads, status | + +Prose for users lives in `docs/`: `docs/concepts/architecture.md` for the assembly model, +`docs/concepts/event-processing.md` for the dispatch pipeline, `docs/concepts/configuration.md` +for settings, `docs/guides/` for deployment, testing and the CLI. Specifications and plans are in +`docs/specs/` and `docs/plans/`; a feature's changelog beside its plan is the running record of +what was done and why. + +--- + +## Component patterns + +A project's component is an ordinary class extending one base: + +| Base | For | +|---|---| +| `EventHandlerBase` | Reacting to an event. Declares its topics, decides whether it can handle a delivery, handles it | +| `ServiceBase` | Business logic with no transport of its own | +| `RestApiBase` | HTTP endpoints, declared with the `@RestApiBase.get/post/...` decorators | +| `SchedulerBase` | Recurring work, either from an in-process timer or from an external tick | +| `ClientBase` / `IOClientBase` | Talking to something outside the process | +| `HealthCheckerBase` | One entry in the readiness payload. Not a `Component` | + +What every one of them has in common: + +- **The constructor takes what its author wrote, and nothing the framework added.** + `super().__init__()` is enough. A component is never handed a namespace, a registry or a + configuration object -- it reads them from `self`. +- **`self.registry`, `self.config` and `self.executor` answer for the component's own agent.** + A lookup written as `self.registry.get_service(OrderService)` finds this agent's service, and + `self.config.get("model_name")` reads this agent's value, with no namespace at the call site. +- **Collaborators are resolved in `on_startup`, not in `__init__`.** Nothing is constructed until + `build()` runs, and within that pass the order is the declaration order, so a component's + collaborator may not exist yet while it is being constructed. +- **`on_startup` / `on_shutdown` are the lifecycle.** The application's lifespan drives them; a + component that opens something in the first closes it in the second. +- **`should_register=False`** is for a component nobody looks up -- the actuator API, the eventing + endpoints. It keeps a second registry entry per agent from existing. + +**The acknowledgement contract, for handlers:** a normal return acknowledges the delivery; a +raised exception does not. `NO_HANDLER_FOUND` acknowledges too -- an event nobody declared is not +a failure of this process. `ProcessingResult` describes the outcome and never controls delivery. +*Failure:* if a result object could nak, two independent concerns -- "what happened" and "should +the broker send this again" -- would be encoded in one value, and a handler returning a failure +result would silently loop the broker. + +--- + +## Design rules + +Every rule below that a machine can check is checked by `tests/unit/agents/test_design_rules.py`, +one section per rule, each failure message naming the rule it enforces. Prose alone has already +failed here once: this file was cited by `CLAUDE.md` for months while it did not exist, so the +guards -- including the one that checks that a cited file exists -- are what keep the rest of this +document true. + +### Construction and assembly + +**Collect, then wire.** A declaration API records; nothing is constructed, registered or +connected until `build()`. *Failure:* a component constructed during accumulation exists before +any namespace does and belongs to the root for ever -- which is what forced a second builder +class to exist for three phases, until deferred wiring removed the reason for it. + +**One declaration surface.** Adding a capability is one edit: a `with_*` method on `AppBuilder`. +A second class whose only job is to defer construction is the smell that was removed, not a +pattern to copy. *Failure:* four places to edit, three of which fail *silently* -- the capability +is simply absent from that surface, and only in the deployment shape nobody tested. + +**A builder is single-use, and says so.** *Failure:* a second `build()` surfaces +`Component.configure`'s "already set" error, which names neither the builder nor the second call +and sends the reader into framework internals. + +**Group policy belongs to the collector.** Standalone stays permissive; the group refuses what it +cannot honour, at assembly, naming the agent and the fix. *Failure:* restrictions scattered into +the builder punish the single-agent case for constraints that only a group has. + +### Namespaces and isolation + +**A component never learns it is in a group.** The namespace is ambient, read by +`Component.__init__` from the scope in force; it is never a constructor parameter of a project's +component, and never enumerable from anything a component can reach. *Failure:* an agent that can +read its neighbours can be written to depend on them, and regrouping then breaks it in +production. + +**Isolation is structural where it can be, audited where it cannot.** Separate stores beat a +shared store with a key prefix; where walling something off would break a supported use, log the +access and name the reader instead. *Failure:* a prefix has to be applied correctly at every call +site, and the one site that forgets is a silent cross-agent read. + +**A lookup never falls back across agents.** Components resolve namespace-then-root, deliberately; +caches do not resolve at all outside the declaring agent. *Failure:* two agents that both asked +for `sessions` silently share one store, and only in production. + +**An omitted namespace on the root registry means every namespace, not the root.** Framework code +that dispatches or resolves per agent names its namespace explicitly, even where it looks +redundant. *Failure:* a root dispatch runs every agent's handlers, or `build()` sees only root +handlers and silently short-staffs a grouped process. + +**Entering a scope for the root is not a no-op.** `namespace_scope("")` *sets* the root, so code +that constructs on behalf of a namespace it was handed uses the guarded form +(`construction_scope`). *Failure:* replaying one agent's declarations resets every component of +every agent back to the root, silently. + +### Names and values that leave the process + +**A name that crosses the process boundary is validated, never repaired.** Queue groups, JetStream +durables, subjects, cache names, namespaces, environment-variable prefixes. *Failure:* silent +rewriting breaks an external dependency with nothing in the logs to debug -- a spaced `app_name` +becomes a subject the CronJob author cannot know they must match. + +**Two components of one class collide on the derived registry name.** A name is qualified with +its agent automatically, so a collision means two of one class in one agent, or two explicit +names that clash. Give one an explicit `name=`. *Failure:* the second registration raises at +startup, or -- worse, before names were qualified -- replaced the first. + +**A check answerable at the call stays at the call.** *Failure:* an error reported several +`with_*` calls later, or at `build()`, names the wrong line and the author looks for the mistake +where it is not. + +### Declarations and defaults + +**An empty declaration means everything, not nothing.** `get_handled_event_types() -> []` is the +wildcard bucket. *Failure:* treating an empty set as authoritative silences the application, and +an unhandled event acknowledges -- so the deliveries vanish rather than piling up where somebody +would see them. + +**A key whose absence changes behaviour is required, not defaulted.** `scheduler_mode` and +`idempotency_ttl` have no default because neither value is safe to inherit. `must_exist=True` +beside a `default=` is a lie: Dynaconf fills the default and the validator then passes. +*Failure:* a deployment gets a behaviour nobody chose -- every replica running every tick, or a +deduplication window shorter than the broker's redelivery window. + +### Configuration and logging + +**Configuration is injected before any component exists**, and is read through the component's +own scoped view. There is **no public read path to the unscoped loader**: `Component.config` is a +view, and the class-level accessor was deleted. *Failure:* a component reads a neighbour's or the +process's value under a name that means "mine", and the bug appears only once a second agent +exists. + +**Configuration isolation is audited, not enforced.** Reading the raw settings tree from a scoped +view logs a WARNING naming the reader, rather than raising. *Failure (of the alternative):* +legitimate framework reads break, and the ones that matter are not the ones a wall would catch. + +**A key that describes the process cannot be set per agent.** One process has one port, one +environment, one prefix, one event bus and one logging configuration. Such a key in an agent's +own settings file is dropped and reported. *Failure:* the author sets a value that is read by +nothing and reported by nothing, and the pod does something other than what the file says. + +**Logging is configured by the application**, never by library code, a constructor, or at import +time. Modules get `getLogger(__name__)` and emit; the application attaches handlers, once. +*Failure:* N scoped configurations each build a logging manager, each re-attaches filters, and +the last one to load decides the whole process's level. + +### Versioning and releases + +**The version is the git tag; the repository is never bumped by hand.** `.github/workflows/publish.yml` +extracts the version from the tag and rewrites `pyproject.toml` at build time. A change adds a +`CHANGELOG.md` entry under `[Unreleased]` and touches no version string. *Failure:* a +hand-edited version disagrees with the tag that published it, and the artefact on the index +cannot be traced back to a commit. + +--- + +## Testing conventions + +- **`tests/unit` needs nothing running.** `tests/integration` may, and anything requiring an + external service is marked `@pytest.mark.integration` (`pytest.ini`, `--strict-markers`). +- **Every package under `tests/unit/agents/` has a `TESTS.md`** listing each file, the class + under test, and what is covered; the one at the top level covers the files that sit directly in + it. It is updated with the tests, not after them. (`tests/unit/agent_generator/` and + `tests/integration/` have none yet.) +- **Probe against real objects.** Every real defect this framework's grouping work surfaced was + found by testing against a real `Registry`, a real `Config` and a real cache rather than a + mock. *Failure:* a mock registry answers every lookup and hides resolution bugs by + construction -- six ownership tests passed against a `MagicMock` while the code could not have + worked. +- **Assert on the observable thing, not on the call.** Paths from `app.openapi()`, names from the + registry, values from `config.get`, files on disk. A test that asserts a mock was called with + certain arguments passes when the arguments are wrong for the caller. +- **A test says what it pins down.** The docstring is the reason the case exists, and for a + regression it names the failure. `test_that_it_works` is not a name. +- **The frozen compatibility suite is frozen.** `tests/unit/agents/test_frozen_compatibility.py` + exercises what existing projects already do. **Never edit it to accommodate an API change**: if + it needs editing, a break shipped, and the break is the finding. +- **A guard test states the rule it enforces in its failure message.** Someone hitting it should + learn the rule from the failure, not from this file. The guards for the design rules above live + in `tests/unit/agents/test_design_rules.py`; a rule that is not mechanically checkable says so + there, so that its absence is not read as an oversight. + +--- + +## How the work is done + +**No unused code in the framework.** Git history is where removed work belongs. *Failure:* a +plausible unused abstraction misleads the next reader into building on something nothing has ever +exercised -- a renderer written and deleted before it was committed cost less than one left in +place would have. + +**Probe, do not assume**, and say which it was. "Verified by probe" and "read from the code" are +different claims, and a report that blurs them cannot be checked. + +**The spec wins on precedence, not on correctness.** Where a specification and this repository +disagree, the specification decides what ships -- but challenge a requirement's premise before +building it, and record every departure, with its argument, in the feature's changelog. *Failure:* +a requirement is implemented as written although its premise is false (a key that is "read by +nothing" turns out to be read per agent), or quietly diverged from, and nobody can tell which. + +**Report the code, not the wrapper.** A change is reported by walking through what the production +code now does -- the functions, the branches, the call sites -- and showing the lines that matter. +"Tests pass and lint is clean" is the wrapper around a change, not the change. diff --git a/CHANGELOG.md b/CHANGELOG.md index d965fb9c..df840254 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -191,7 +191,7 @@ default_ttl = 3600 # 1 hour default TTL ### Added - New `/info` actuator endpoint exposing app name, version, and all dependency versions. -- [ServiceInfo](/src/blueprint/agents/models/status.py:8:0-25:5) model for structured `/info` responses. +- `ServiceInfo` model (`src/blueprint/agents/models/status.py`) for structured `/info` responses. - Actuator links (`/info`, `/status/env`, `/status/llm`, `/status/build`) in root `/` metadata. - Supporting classes in component registry in addition to names - Fetching an unregistered component now throws an exception diff --git a/CLAUDE.md b/CLAUDE.md index 8cc76729..fad0de68 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,7 +2,8 @@ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. -See `AGENTS.md` for architecture, component patterns, and testing conventions shared across all AI assistants. +See `AGENTS.md` for the architecture, the component patterns, the testing conventions and the **design rules** -- +each with the failure it prevents -- shared across all AI assistants and every human working here. ## Dev Commands diff --git a/README.md b/README.md index a96a2239..69927b26 100644 --- a/README.md +++ b/README.md @@ -241,7 +241,7 @@ See the [Deployment Guide](docs/guides/deployment.md) for detailed instructions. - [Architecture](docs/concepts/architecture.md) -- Component model, registry, and lifecycle - [Event Processing](docs/concepts/event-processing.md) -- CloudEvents, handler chain, Dapr/NATS - [Configuration](docs/concepts/configuration.md) -- Settings, secrets, and environment variables -- [Caching](docs/concepts/caching.md) -- Persistent disk cache with TTL and namespaces +- [Caching](docs/concepts/caching.md) -- Disk and Redis caches, TTL, namespaces, and per-agent isolation - [Observability](docs/concepts/observability.md) -- OpenTelemetry tracing, metrics, and logging ### Component Guides diff --git a/docs/README.md b/docs/README.md index 893ec163..1ba438f8 100644 --- a/docs/README.md +++ b/docs/README.md @@ -19,7 +19,7 @@ Blueprint Agents is a Python 3.13+ framework for building AI-powered microservic | [Architecture](concepts/architecture.md) | AppBuilder pattern, component lifecycle, and dependency injection | | [Event Processing](concepts/event-processing.md) | Event handler pipeline, message routing, and processing model | | [Configuration](concepts/configuration.md) | Dynaconf-based config with `settings.toml` and `secrets.toml` | -| [Caching](concepts/caching.md) | Built-in caching strategies and cache provider integration | +| [Caching](concepts/caching.md) | Declaring caches, the disk and Redis backends, TTL, namespaces, readiness and the management API | | [Observability](concepts/observability.md) | Logging, metrics, tracing, and health checks | --- diff --git a/docs/concepts/cache-architecture.md b/docs/concepts/cache-architecture.md deleted file mode 100644 index b1886d2e..00000000 --- a/docs/concepts/cache-architecture.md +++ /dev/null @@ -1,181 +0,0 @@ -# Cache Architecture - -This document describes the **pluggable cache architecture** introduced for centralised caching support. It explains the components, their responsibilities, and the design choices behind them. - -For end-user setup instructions, see [Caching — Getting Started](../guides/caching-getting-started.md). For a higher-level system overview with diagrams, see [Cache System Overview](./cache-system-overview.md). - ---- - -## Goals - -The architecture solves three problems: - -| Problem | Solution | -|---|---| -| Scaling out causes cache misses on every replica | Shared backend (Redis) so all replicas see the same cache | -| Different deployments need different storage backends | Pluggable backend behind a single interface | -| Existing single-replica services should not be forced to change | Local DiskCache stays the default | - -## Components - -``` - ┌─────────────────────────────────────┐ - │ CacheService (abstract interface) │ - │ │ - │ get / set / delete / exists │ - │ clear / hash / get_stats │ - └─────────────────────────────────────┘ - ▲ ▲ - │ │ - ┌───────────────┘ └───────────────┐ - │ │ - ┌──────────────────────┐ ┌──────────────────────┐ - │ DiskCacheService │ │ RedisCacheService │ - │ (default, local) │ │ (centralised) │ - │ │ │ │ - │ diskcache-rs │ │ redis-py 7.x │ - │ per-process file │ │ shared TCP client │ - └──────────────────────┘ └──────────────────────┘ - - ▲ - │ creates the right one based on - │ CacheConfig.backend - │ - ┌─────────────────────────────────────┐ - │ CacheBackendFactory │ - │ .create(CacheConfig) → CacheService│ - └─────────────────────────────────────┘ - ▲ - │ reads from settings.toml - │ - ┌─────────────────────────────────────┐ - │ Config.get_cache_config() │ - │ returns a CacheConfig (Pydantic) │ - └─────────────────────────────────────┘ - ▲ - │ wires the cache into the registry - │ - ┌─────────────────────────────────────┐ - │ AppBuilder.with_cache() │ - │ → Component.shared_registry │ - │ .cache_service = … │ - └─────────────────────────────────────┘ - ▲ - │ pulled by every service / handler - │ in their on_startup() - │ - ┌───────────────┴────────────────┐ - │ │ - ┌──────────┐ ┌──────────┐ - │ ServiceA │ │ ServiceB │ - │ │ │ │ - │ self. │ │ self. │ - │ registry │ │ registry │ - │ .cache_ │ │ .cache_ │ - │ service │ │ service │ - └──────────┘ └──────────┘ -``` - -### `CacheService` — the abstract interface -`src/blueprint/agents/services/infrastructure/cache_service.py` - -Five operations every backend must implement: `get`, `set`, `delete`, `exists`, `clear`. Plus `hash` for normalised key generation, `get_stats` for the management API, and `list_namespaces` / `list_values` for the cache REST endpoints. - -Code that uses the cache only sees this interface — it never imports `DiskCacheService` or `RedisCacheService` directly. - -### `DiskCacheService` — local default -Same file. Backed by `diskcache-rs` (a Rust-accelerated diskcache port). Persists to a directory on disk. Thread-safe via an optional `RLock`. **Default** — services that don't change anything continue to work exactly as before. - -### `RedisCacheService` — centralised, shared -`src/blueprint/agents/services/infrastructure/redis_cache_service.py` - -Backed by `redis-py 7.x`. Uses Redis-native TTL via the `EX` argument on `SET`. Namespace + key are joined with `:` and prefixed by an optional `key_prefix` so multiple services can share one Redis instance without collisions. - -### `CacheBackendFactory` — Strategy selector -`src/blueprint/agents/services/infrastructure/cache_backend_factory.py` - -A simple `@staticmethod` that returns a `DiskCacheService` or a `RedisCacheService` depending on `CacheConfig.backend`. This is where the **Strategy pattern** lives — it picks the concrete strategy at runtime based on configuration. - -### `CacheConfig` — typed configuration -`src/blueprint/agents/models/config.py` - -Pydantic model. Holds: `backend`, `cache_dir`, `default_ttl`, `key_prefix`, `redis_url`, `redis_password`, `redis_db`, `redis_tls`, `fallback_to_local`. Read from `settings.toml` via Dynaconf in `Config.get_cache_config()`. - -### `AppBuilder.with_cache()` — wiring -`src/blueprint/agents/app_builder.py` - -```python -def with_cache(self, enabled: bool = True, enable_locking: bool = True) -> "AppBuilder": - if enabled: - cache_config = self._config.get_cache_config() - cache_service = CacheBackendFactory.create(cache_config, enable_locking=enable_locking) - Component.shared_registry.cache_service = cache_service - return self -``` - -Calling `with_cache()` is the **only** thing a service author needs to do to opt in. The factory picks the backend, the registry stores the singleton, and every component can pull it from `self.registry.cache_service`. - ---- - -## Design choices - -### Why a Strategy pattern, not subclassing the cache? - -Because the **calling code** (services, handlers, agents) does not know — and should not know — which backend is in use. With Strategy: - -- Services depend only on `CacheService` (the interface). -- Choosing backend is a one-line change in `settings.toml`. -- New backends (Memcached, DynamoDB, …) can be added by implementing `CacheService` without touching any caller. - -### Why keep DiskCache as default? - -Two reasons: -1. **No breaking changes** — every existing service that already used the cache keeps working. -2. **Zero-dependency baseline** — single-replica deployments don't need Redis just to use the cache. - -### Why a single global registry instead of injecting the cache per service? - -Because `Component.shared_registry` is the existing mechanism for cross-component dependency lookup (services look up other services there too). Reusing it keeps the API uniform and the singleton guarantee enforced by the registry's "set once" check. - -### Why `key_prefix` AND `namespace`? - -Two layers of isolation, two scopes: -- **`namespace`** is *per-call* (`cache.get(k, namespace="prices")`) — used by code to organise its own keys. -- **`key_prefix`** is *per-instance* (configured once in `settings.toml`) — used to keep multiple services that share one Redis instance from colliding. - -A Redis key looks like `{key_prefix}:{namespace}:{hash(key)}`. - -### Why a sync redis-py client in async services? - -Redis operations are normally sub-millisecond and the cache is on the hot path. The sync client is simpler, well-tested, and the latency cost is negligible for typical agent workloads. If that ever becomes a bottleneck, an `AsyncRedisCacheService` can be added without changing any caller. - -### What about fallback when Redis is unreachable? - -Two failure modes are distinguished: -1. **`redis` package not installed** — `CacheBackendFactory` falls back to `DiskCacheService` if `fallback_to_local=True`. This is a **real backend swap** — the app runs with disk thereafter. -2. **Redis unreachable at startup or runtime** — `RedisCacheService` keeps trying Redis. With `fallback_to_local=True`, `on_startup()` does not raise; with `fallback_to_local=False`, it raises and the pod crashes (K8s restarts it). - -In case (2) the cache is not silently swapped to disk. Operations against an unreachable Redis return `None`/`False` and log warnings. - -To prevent a pod from silently serving cache misses while looking healthy to K8s, the framework registers a `CacheHealthChecker` for the readiness probe automatically when `with_cache()` is called: - -- `/health/ready` → returns **HTTP 503** with full diagnostic payload when Redis is unreachable -- `/health/live` → unaffected (always 200) — the pod stays alive -- Recovery is automatic — when Redis returns, the next health-check tick (≤ `health_check_interval_seconds`, default 30s) flips readiness back to UP and K8s re-adds the pod to the service pool - -For DiskCache, the health check is trivially UP (the local filesystem doesn't fail in the same way a network service does). - ---- - -## What's now possible with this architecture - -| Before | After | -|---|---| -| Each replica had its own DiskCache → cache misses after every restart and on every new replica | Replicas share a single Redis cache → warm cache survives restarts and scales horizontally | -| Cache backend hard-coded into the framework | `settings.toml` switches backends; new backends slot in via `CacheService` | -| Services that scaled out had to pin to one replica or accept duplicate work | Two replicas of the same service deduplicate work via the shared cache | -| Two different services on the same Redis would collide on identical keys | `key_prefix` per service guarantees isolation | -| No way to verify multi-instance behaviour without spinning up real replicas | `examples/shared_cache_demo/demo_multiprocess.py` proves cross-process sharing in 2 seconds | -| No automated test for "two services in one app share cache via the registry" | `tests/unit/agents/services/infrastructure/test_cache_sharing_via_registry.py` covers it | -| `Config.get_cache_config()` only read 4 of 11 fields (backend/redis_* ignored) | All fields are read; Redis is reachable purely through `settings.toml` | -| Redis outage → pod looks healthy to K8s, silently serves cache misses | Readiness probe flips to HTTP 503 within one health-check interval; K8s drops pod from service pool until Redis recovers | diff --git a/docs/concepts/cache-system-overview.md b/docs/concepts/cache-system-overview.md deleted file mode 100644 index 0deba1f1..00000000 --- a/docs/concepts/cache-system-overview.md +++ /dev/null @@ -1,232 +0,0 @@ -# Cache System Overview - -A diagram-led tour of how the cache is structured, where the **Strategy pattern** sits, and how data flows from a service call to a Redis key. - -For the design rationale, see [Cache Architecture](./cache-architecture.md). For setup steps, see [Caching — Getting Started](../guides/caching-getting-started.md). - ---- - -## Strategy pattern in one picture - -The cache is a textbook Strategy pattern. The **context** (the calling code) holds a reference to a **strategy** (a `CacheService`) and uses it through a fixed interface. The concrete strategy is selected once, at startup, by a factory that reads configuration. - -``` - ┌──────────────────────────────────────────────┐ - │ Context: any service, handler, or API │ - │ │ - │ self._cache = self.registry │ - │ .cache_service │ - │ │ - │ self._cache.set("k", v, namespace="ns") │ - │ self._cache.get("k", namespace="ns") │ - └──────────────────────┬───────────────────────┘ - │ uses - ▼ - ┌──────────────────────────────────────────────┐ - │ Strategy interface: CacheService │ - │ │ - │ get(key, namespace) -> Any | None │ - │ set(key, value, namespace, ttl) -> None │ - │ delete(key, namespace) -> bool │ - │ exists(key, namespace) -> bool │ - │ clear(namespace) -> None │ - └────────┬─────────────────────────────┬───────┘ - │ implemented by │ - ▼ ▼ - ┌────────────────────────┐ ┌─────────────────────────┐ - │ ConcreteStrategy: │ │ ConcreteStrategy: │ - │ DiskCacheService │ │ RedisCacheService │ - │ │ │ │ - │ • diskcache-rs (Rust) │ │ • redis-py 7.x │ - │ • file-system, local │ │ • TCP, shared │ - │ • per-process │ │ • across processes │ - └────────────────────────┘ └─────────────────────────┘ - ▲ ▲ - │ │ - │ chooses one of these │ - │ │ - └──────────────┬──────────────┘ - │ - │ creates - ┌─────────┴─────────────┐ - │ CacheBackendFactory │ - │ │ - │ if config.backend │ - │ == "redis": │ - │ RedisCacheService│ - │ else: │ - │ DiskCacheService │ - └─────────┬──────────────┘ - │ reads - ▼ - ┌────────────────────────┐ - │ CacheConfig (Pydantic) │ - │ │ - │ backend, redis_url, │ - │ key_prefix, … │ - └─────────┬──────────────┘ - │ produced by - ▼ - ┌────────────────────────┐ - │ Config.get_cache_ │ - │ config() │ - │ │ - │ reads [default.cache] │ - │ from settings.toml │ - │ via Dynaconf │ - └────────────────────────┘ -``` - -**Why this matters**: a service that calls `self._cache.set(...)` has no idea — and does not need to know — whether that write goes to a local `.cache/` folder or to a Redis cluster on the other side of the world. Switching backends is a one-line change in `settings.toml`. - ---- - -## Lifecycle: from `AppBuilder.build()` to a Redis key - -The end-to-end timeline of one cache write, from app startup through the actual Redis command: - -``` - APP STARTUP - ─────────── - - AppBuilder(config) [1] - .with_service(PricingService) [2] - .with_service(RecommendationService) [3] - .with_cache() [4] - .build() [5] - - - [4] with_cache() [5] build() → on_startup() - ───────────── ──────────────────────── - - Config.get_cache_config() For every component: - ↓ component.on_startup() - CacheConfig( ↓ - backend="redis", Pricing ← registry.cache_service - redis_url="redis://...", Recommend ← registry.cache_service - key_prefix="my-svc", (both get the SAME instance) - ... - ) - ↓ - CacheBackendFactory.create(cfg) - ↓ - RedisCacheService(redis_url=..., key_prefix=...) - ↓ - Component.shared_registry.cache_service = ↑ - - - APP RUNTIME - ─────────── - - PricingService.store_price("laptop", 49.99) - ↓ - self._cache.set( - "price:laptop", - {"amount": 49.99}, - namespace="products", - ttl=600 - ) - ↓ - RedisCacheService._full_key(...) → "my-svc:products:7f8a…" - ↓ - json.dumps({"amount": 49.99}) → '{"amount": 49.99}' - ↓ - redis_client.set( - "my-svc:products:7f8a…", ← SET command on Redis - '{"amount": 49.99}', - ex=600 ← Redis-native TTL - ) - - RecommendationService.read_price("laptop") - ↓ - self._cache.get("price:laptop", namespace="products") - ↓ - RedisCacheService._full_key(...) → "my-svc:products:7f8a…" (same hash!) - ↓ - redis_client.get("my-svc:products:7f8a…") - ↓ - '{"amount": 49.99}' → json.loads() → {"amount": 49.99} -``` - -The key insight: both services produce the **same** Redis key from the same logical key, namespace, and prefix. That's how they see each other's writes through the registry. - ---- - -## Multi-process / multi-replica view - -This is the case the issue asks for. Two replicas of the same service running in two different processes (or two different pods) — both connected to one Redis: - -``` - ┌─────────────────────────────┐ ┌─────────────────────────────┐ - │ Replica A (PID 1234) │ │ Replica B (PID 5678) │ - │ │ │ │ - │ Component.shared_registry │ │ Component.shared_registry │ - │ ┌────────────────────────┐ │ │ ┌────────────────────────┐ │ - │ │ cache_service: │ │ │ │ cache_service: │ │ - │ │ RedisCacheService │ │ │ │ RedisCacheService │ │ - │ │ (instance #A) │ │ │ │ (instance #B) │ │ - │ │ │ │ │ │ │ │ - │ │ key_prefix="my-svc" │ │ │ │ key_prefix="my-svc" │ │ - │ └─────────┬──────────────┘ │ │ └─────────┬──────────────┘ │ - │ │ │ │ │ │ - └─────────────┼────────────────┘ └─────────────┼────────────────┘ - │ TCP │ TCP - │ │ - └────────────────┬───────────────────────┘ - ▼ - ┌──────────────────────┐ - │ Redis │ - │ │ - │ my-svc:ns:hash1 ───┐│ - │ ││ shared - │ my-svc:ns:hash2 ───┘│ - │ │ - └──────────────────────┘ -``` - -Each replica owns its own `RedisCacheService` Python object and its own TCP connection to Redis. They have **no shared memory and no shared Python objects**. The only shared state is Redis itself, which is exactly what makes the cache "centralised". - -This is what `examples/shared_cache_demo/demo_multiprocess.py` demonstrates programmatically (using two `multiprocessing.Process` workers to simulate the two replicas). - ---- - -## Data layout in Redis - -Every cache write goes through the same key formula: - -``` - ┌────────────────┬──────────────┬──────────────────────────────┐ - │ key_prefix │ namespace │ sha256(normalised key) │ - ├────────────────┼──────────────┼──────────────────────────────┤ - │ "my-svc" │ "products" │ "7f8a9c1e2b…" │ - └────────────────┴──────────────┴──────────────────────────────┘ - │ │ │ - └──────────────┴────────────────────┘ - │ - ▼ - "my-svc:products:7f8a9c1e2b…" -``` - -- **`key_prefix`** isolates whole services from each other (e.g. `payments-svc` vs. `inventory-svc`). -- **`namespace`** isolates logical groups within one service (e.g. `prices` vs. `recommendations`). -- **`hash`** is the SHA-256 of the key, after JSON-normalising it so that `["a", "b"]` and `["b", "a"]` produce the same hash, and `{"x": 1, "y": 2}` and `{"y": 2, "x": 1}` produce the same hash. - -The two-layer prefix system means **multiple services can share one Redis without ever colliding**, and within a service you can subdivide cleanly by namespace. - ---- - -## Component responsibilities at a glance - -| Component | Role | Knows about | Does NOT know about | -|---|---|---|---| -| `CacheService` | Interface every backend implements | – | Concrete backends | -| `DiskCacheService` | Local disk-backed implementation | `diskcache-rs`, file system | Redis, Dynaconf, AppBuilder | -| `RedisCacheService` | Redis-backed implementation | `redis-py`, key-prefix scheme | DiskCache, Dynaconf, AppBuilder | -| `CacheBackendFactory` | Strategy selector | Both backends, `CacheConfig` | Settings files, AppBuilder | -| `CacheConfig` | Typed Pydantic config model | Field shapes only | Dynaconf, AppBuilder, backends | -| `Config.get_cache_config()` | Reads `[default.cache]` from settings | Dynaconf, `CacheConfig` | Backends, registry | -| `AppBuilder.with_cache()` | Wires the cache into the registry | Factory, registry, `Config` | Backends | -| `Component.shared_registry` | Singleton store, dependency lookup | `CacheService` (interface only) | Backends, settings | -| Application services | Use the cache through `self.registry.cache_service` | The interface | Everything else | - -Each layer touches only the layers immediately above and below it. This is what makes the architecture extensible: add a new backend by implementing `CacheService` + extending the factory, and nothing else has to change. diff --git a/docs/concepts/caching.md b/docs/concepts/caching.md index 55af35f6..2c4469e0 100644 --- a/docs/concepts/caching.md +++ b/docs/concepts/caching.md @@ -1,10 +1,19 @@ # Caching -Blueprint Agents includes a built-in persistent key-value cache backed by diskcache-rs. The cache provides fast local storage with TTL expiration, namespace isolation, and a management REST API. +A cache in Blueprint Agents is a persistent key-value store that an application **declares** and +the framework creates. It has TTL expiry, namespaces for partitioning keys, a readiness check, a +small management API, and two interchangeable backends: a local disk store (the default) and Redis +(for state shared between replicas). -## Enabling the Cache +This is the one document for the cache. It replaces four that overlapped and disagreed -- a cache +architecture note, a system overview, a Redis getting-started guide, and an earlier version of +this file; see the git history for those. -Enable caching by calling `.with_cache()` on the `AppBuilder`: +--- + +## Declaring a cache + +`with_cache()` on the builder: ```python from blueprint.agents import AppBuilder, Config @@ -20,328 +29,359 @@ app = ( ) ``` -Once enabled, the cache service is registered in the component registry and a management REST API is automatically mounted. +Like every `with_*` call, this **records a declaration and constructs nothing**. The backend is +chosen and the store opened by `build()`, which is also why a cache can be declared before any +configuration exists. -## Accessing the Cache +### Several caches -The cache is available through the component registry from `on_startup()` onward: +Call it again with a name: ```python -from blueprint.agents.handler.event_handler_base import EventHandlerBase -from blueprint.agents.models.events import CloudEvent, HandlerResult - - -class DeduplicationHandler(EventHandlerBase): - priority = 1 - - async def on_startup(self) -> None: - self.cache = self.registry.cache_service - - def can_handle_event(self, event: CloudEvent, context: dict[str, Any]) -> bool: - return event.type == "document.received" - - async def handle_event(self, event: CloudEvent, context: dict[str, Any]) -> HandlerResult | None: - doc_id = event.subject - - # Check if already processed - if await self.cache.get(doc_id, namespace="processed"): - return None # Skip duplicate - - # Mark as processed with a 1-hour TTL - await self.cache.set(doc_id, True, namespace="processed", ttl=3600) - - return HandlerResult( - event_type="document.accepted", - data=event.data, - ) +AppBuilder(config).with_cache().with_cache(name="sessions").build() ``` -## Cache Operations +Each name gets its own store -- its own directory on disk, its own key prefix on Redis -- and a +component reads one back by name. There is deliberately **no fallback from an unknown name to the +default**: asking for a cache that was not declared raises, rather than quietly handing over some +other cache. -### get(key, namespace) +| Call | Meaning | +|---|---| +| `with_cache()` | The default cache, named `default` | +| `with_cache(name="sessions")` | A second cache called `sessions` | +| `with_cache(False)` | Declares nothing; caching off | +| `with_cache(True, False)` | The default cache with file locking disabled | -Retrieve a value by key within a namespace. Returns `None` if the key does not exist or has expired. +`name` is keyword-only and comes last, which is a constraint rather than a style choice: +`with_cache(False)` has always meant "no cache", and had `name` come first that call would have +become a cache named `False` with caching silently switched *on*. -```python -value = await self.cache.get("user:12345", namespace="profiles") -if value is None: - # Cache miss -- fetch from source - value = await self.fetch_profile(12345) - await self.cache.set("user:12345", value, namespace="profiles", ttl=900) -``` +--- -### set(key, value, namespace, ttl) +## Using a cache -Store a value under a key. The `ttl` parameter specifies the time-to-live in seconds. If omitted, the `default_ttl` from configuration is used. +Resolve it in `on_startup`, never in `__init__` -- nothing is constructed until `build()` runs, so +a collaborator may not exist yet while a component is being constructed. ```python -# Cache for 30 minutes -await self.cache.set("result:abc", {"score": 0.95}, namespace="results", ttl=1800) - -# Cache using the default TTL from settings.toml -await self.cache.set("result:def", {"score": 0.87}, namespace="results") +class DeduplicationHandler(EventHandlerBase): + async def on_startup(self) -> None: + self.cache = self.registry.get_cache("sessions") # a named cache + self.default = self.registry.cache_service # the default one + + async def handle_event(self, event: GenericCloudEvent, context: dict) -> HandlerResult | None: + if self.cache.get(event.subject, namespace="processed"): + return None # already seen + self.cache.set(event.subject, True, namespace="processed", ttl=3600) + return HandlerResult(event_type="document.accepted", data=event.data) ``` -### delete(key, namespace) +**The cache interface is synchronous.** `get`, `set` and the rest are ordinary methods; they are +not awaited, even inside `async def`. Operations are sub-millisecond on both backends. -Remove a specific key from a namespace. +`self.registry` answers for the component's own agent, so `get_cache("sessions")` reaches this +agent's `sessions` cache and cannot reach anyone else's. -```python -await self.cache.delete("user:12345", namespace="profiles") -``` +### Operations -### clear(namespace) +| Method | What it does | +|---|---| +| `get(key, namespace="default")` | The value, or `None` if absent or expired | +| `set(key, value, namespace="default", ttl=None)` | Store a value. `ttl` in seconds | +| `delete(key, namespace="default")` | Remove one key; `True` if it was there | +| `exists(key, namespace="default")` | Whether the key is present and unexpired | +| `clear(namespace=None)` | Empty one namespace, or the whole cache | +| `claim(key, value, namespace="default", ttl=None)` | Store **only if absent**; `True` if this caller stored it | +| `hash(value)` | The key hash this cache would use | +| `get_stats()` | Backend statistics (see the management API below) | +| `list_namespaces()` | Namespaces currently holding entries | +| `list_values(namespace="default", limit=100, offset=0)` | Iterate stored values, paginated | -Remove all entries in a namespace. Useful for bulk invalidation. +### `claim`: deciding which process does the work -```python -# Purge all cached search results -await self.cache.clear(namespace="search_results") -``` - -## TTL and Automatic Expiration - -Every cached entry can have an individual TTL (time-to-live) in seconds. Once the TTL elapses, the entry is no longer returned by `get()` and is eligible for eviction. +`exists` followed by `set` is not a lock. Two callers racing on the same key both pass the +`exists` check before either `set` lands, and both then believe they hold it. `claim` is the +set-if-absent primitive that closes the race -- `SET NX EX` on Redis, `add` on a lock-protected +disk cache -- and it is what event deduplication and the scheduler tick use to pick one winner +among several replicas. ```python -# Short-lived cache for rate limiting (60 seconds) -await self.cache.set(f"rate:{client_ip}", request_count, namespace="rate_limit", ttl=60) - -# Long-lived cache for expensive computations (24 hours) -await self.cache.set(embedding_key, vector, namespace="embeddings", ttl=86400) +if not self.cache.claim(event.id, "processing", namespace="dedup", ttl=600): + return None # another replica got there first ``` -If no TTL is provided, the `default_ttl` value from `[default.cache]` in `settings.toml` is applied. +### Keys and namespaces -## Namespace Isolation - -Namespaces partition the cache into logical segments. Different components can use separate namespaces without risk of key collisions. +A key may be a string, a list of strings, or a dictionary. Lists are sorted and dictionaries are +key-sorted before hashing, so `["a", "b"]` and `["b", "a"]` are the same key, and so are +`{"x": 1, "y": 2}` and `{"y": 2, "x": 1}`. ```python -# Handler uses one namespace -await self.cache.set("doc:1", metadata, namespace="documents") - -# Service uses a different namespace -await self.cache.set("doc:1", embedding, namespace="embeddings") - -# No collision -- these are independent entries +params = {"model": "gpt-4o", "prompt": "Summarise this", "temperature": 0.3} +answer = self.cache.get(params, namespace="llm_responses") +if answer is None: + answer = self.call_llm(params) + self.cache.set(params, answer, namespace="llm_responses", ttl=7200) ``` -Namespaces also allow targeted invalidation. Clearing one namespace does not affect others. +A **namespace** partitions keys *within one cache*. Two components can both write `doc:1` under +different namespaces without colliding, and `clear(namespace=...)` invalidates one group without +touching the others. The default namespace is `default`. -## Key Hashing for Complex Keys +### TTL -The cache supports complex keys such as lists, dictionaries, and tuples. These are automatically hashed to produce a stable string key. +Every write gets a TTL. When `ttl` is omitted the cache-wide `default_ttl` applies -- one hour +unless configured otherwise -- on both backends. `default_ttl` is an integer, so **there is no way +to configure "never expires"** through a settings file; pass a long `ttl` at the call instead. -```python -# Dictionary key -- automatically hashed -query_params = {"model": "gpt-4o", "prompt": "Summarize this document", "temperature": 0.3} -cached_response = await self.cache.get(query_params, namespace="llm_responses") +--- -if cached_response is None: - response = await self.call_llm(query_params) - await self.cache.set(query_params, response, namespace="llm_responses", ttl=7200) +## A cache belongs to the agent that declared it -# List key -- also automatically hashed -chunk_ids = ["chunk-a", "chunk-b", "chunk-c"] -await self.cache.set(chunk_ids, merged_result, namespace="merged_chunks") -``` +When several agents share one process, a cache is private to the one that declared it. Two agents +may both declare `sessions` and they get **separate stores**: separate directories on disk, +separate key prefixes on Redis. A lookup never falls back to a neighbour's cache or to the root's, +because two independently written agents both asking for `sessions` would otherwise share one +store the moment they were grouped -- and only in production. -## Cache Management REST API +Nothing about this is visible in an agent's code. `self.registry.get_cache("sessions")` is what +the author writes whether the agent runs alone or beside five others. -When the cache is enabled, the framework automatically registers a REST API for cache inspection and management at `/api/cache`. +Where the data goes: -### Endpoints - -| Method | Path | Description | +| | Disk backend | Redis backend | |---|---|---| -| `GET` | `/api/cache/{namespace}/{key}` | Retrieve a cached value | -| `PUT` | `/api/cache/{namespace}/{key}` | Set a cached value (JSON body) | -| `DELETE` | `/api/cache/{namespace}/{key}` | Delete a cached entry | -| `DELETE` | `/api/cache/{namespace}` | Clear an entire namespace | - -### Example Usage +| Standalone, default cache | `` | keys under `` | +| Standalone, cache `sessions` | `/sessions` | keys under `:sessions` | +| Agent `orders`, default cache | `/orders.default` | keys under `:orders.default` | +| Agent `orders`, cache `sessions` | `/orders.sessions` | keys under `:orders.sessions` | -```bash -# Retrieve a cached value -curl http://localhost:8000/api/cache/profiles/user:12345 +A named store is a **subdirectory** of `cache_dir` rather than a sibling, because a deployment may +mount its volume at `cache_dir` itself and nothing outside the mount can be created under +`readOnlyRootFilesystem`. See *Writable Cache Directory* in +[deployment.md](../guides/deployment.md). -# Set a cached value with a TTL -curl -X PUT http://localhost:8000/api/cache/results/query:abc \ - -H "Content-Type: application/json" \ - -d '{"value": {"score": 0.95}, "ttl": 1800}' +A single-agent application is unaffected in every respect: same directory, same Redis keyspace, +same registry names it always had. -# Delete a specific key -curl -X DELETE http://localhost:8000/api/cache/profiles/user:12345 +> **Upgrading:** the key layout changed when caches became per-agent. An application upgrading +> with a mounted disk cache or a persistent Redis sees its old entries as absent -- a cold cache, +> not an error. -# Clear all entries in a namespace -curl -X DELETE http://localhost:8000/api/cache/search_results -``` +--- ## Configuration -Cache settings are defined in `settings.toml` under the `[default.cache]` section: +Under `[default.cache]` in `settings.toml`: ```toml [default.cache] -cache_dir = "/tmp/blueprint-cache" -size_limit = 1073741824 # Maximum cache size in bytes (1 GB) -eviction_policy = "least-recently-used" # Eviction strategy when size_limit is reached -default_ttl = 3600 # Default TTL in seconds (1 hour) +cache_dir = ".cache/blueprint" +size_limit = 1000000000 # bytes +eviction_policy = "least-recently-used" +default_ttl = 3600 # seconds ``` -### Configuration Fields +| Field | Type | Default | Applies to | +|---|---|---|---| +| `backend` | `str` | `"disk"` | `"disk"` or `"redis"` | +| `cache_dir` | `str` | `".cache/blueprint"` | disk | +| `size_limit` | `int` | `1000000000` | disk | +| `eviction_policy` | `str` | `"least-recently-used"` | disk | +| `default_ttl` | `int` | `3600` | both | +| `key_prefix` | `str` | `""` | redis | +| `redis_url` | `str \| None` | `redis://localhost:6379/0` | redis | +| `redis_password` | `str \| None` | `None` | redis -- read it from a secrets file | +| `redis_db` | `int` | `0` | redis | +| `redis_tls` | `bool` | `false` | redis | +| `fallback_to_local` | `bool` | `false` | redis | + +In a group each agent may configure its own cache under its own scope, so one agent can run on +Redis beside a neighbour on disk: -| Field | Type | Description | -|---|---|---| -| `cache_dir` | `str` | Filesystem path where cache data is stored | -| `size_limit` | `int` | Maximum total cache size in bytes | -| `eviction_policy` | `str` | Strategy for removing entries when the cache is full | -| `default_ttl` | `int` | Default time-to-live in seconds for entries without an explicit TTL | +```toml +[default.cache] # what every agent gets unless it says otherwise +backend = "disk" + +[default.orders.cache] # just the orders agent +backend = "redis" +redis_url = "redis://shared-redis:6379/0" +key_prefix = "orders-api" +``` + +--- + +## Backends -## Redis Backend +### Disk (default) -For deployments where multiple service instances need to share cache state (e.g. horizontal scaling, blue/green deployments, multi-pod Kubernetes setups), Blueprint Agents ships with an optional Redis backend. Cache reads and writes flow through a central Redis server so every replica sees the same data. +Backed by `diskcache-rs`, a Rust implementation of the diskcache format. Persists to +`cache_dir`, survives restarts, and uses file-based locking so replicas sharing one mounted +directory can read and write it safely. Nothing has to be installed and nothing has to be +configured. -### Installation +### Redis -The Redis client is an optional extra. Install it explicitly: +For state shared across replicas -- horizontal scaling, blue/green, several pods behind one +service. Install the extra: ```bash pip install 'avs-blueprint-agents[redis]' ``` -This pulls in `redis-py` with the `hiredis` parser for fast wire-protocol decoding. No code changes are required — the framework auto-selects the backend at startup based on `settings.toml`. - -### Configuration - -Switch backends by setting `backend = "redis"` and adding the connection fields: +and switch backends in the settings file: ```toml [default.cache] -backend = "redis" # "disk" (default) or "redis" -default_ttl = 3600 # Default TTL in seconds (used by both backends) -key_prefix = "inventory-api" # Prefix prepended to every cache key -redis_url = "redis://localhost:6379/0" # Connection URL (host, port, db) -redis_password = "secret" # Optional password -redis_db = 0 # Database index (0–15 for default Redis) -redis_tls = false # Set true for TLS (rediss://) -fallback_to_local = false # If true: fall back to DiskCacheService when Redis is unreachable +backend = "redis" +redis_url = "redis://localhost:6379/0" +key_prefix = "inventory-api" ``` -### Field Reference +No code changes: `with_cache()` picks up the backend from configuration. -| Field | Type | Description | -|---|---|---| -| `backend` | `str` | `"disk"` (default) or `"redis"`. Controls which cache implementation is instantiated. | -| `key_prefix` | `str` | Global prefix prepended to every key in the form `{prefix}:{namespace}:{hash}`. Lets you safely share a single Redis database between multiple services without key collisions. Empty string disables prefixing. | -| `redis_url` | `str` | Standard Redis URL (`redis://...` or `rediss://...` for TLS). Defaults to `redis://localhost:6379/0`. | -| `redis_password` | `str \| None` | Password for Redis AUTH. Read this from a secrets file, never commit it. | -| `redis_db` | `int` | Numeric database index. Default is `0`. | -| `redis_tls` | `bool` | Enable TLS — equivalent to using `rediss://` in `redis_url`. | -| `fallback_to_local` | `bool` | If `True`, the framework starts up with `DiskCacheService` when (a) the Redis extra is not installed or (b) the Redis server is unreachable on `on_startup()`. Useful for graceful degradation in non-production environments. | +Every Redis key is `{key_prefix}:{namespace}:{sha256(key)}`, so several services can share one +Redis database as long as each sets a distinct `key_prefix`. `clear()` uses `SCAN` + `DELETE` +within the prefix and never `FLUSHDB`, so it cannot touch another service's keys. -### Multi-Service Shared Redis +**Startup is a real connection.** `build()` pings Redis while creating the cache, so a +`RedisCacheService` in the registry always means a Redis that answered. If the ping fails: -When several microservices share one Redis cluster, set a unique `key_prefix` per service: +- with `fallback_to_local = true`, the framework logs a warning and uses a disk cache instead -- + a genuine backend swap, and the application runs on disk thereafter; +- with `fallback_to_local = false` (the default), startup fails. In production that is what you + want: a pod that cannot reach its cache should crash-loop visibly rather than serve misses. -```toml -# Service A -[default.cache] -backend = "redis" -key_prefix = "inventory-api" -redis_url = "redis://shared-redis:6379/0" +The same applies when the `redis` extra is not installed at all. -# Service B -[default.cache] -backend = "redis" -key_prefix = "billing-api" -redis_url = "redis://shared-redis:6379/0" -``` +--- -Each service's `clear()`, `list_namespaces()`, and `list_values()` calls only operate within its own prefix. `clear()` uses `SCAN` + `DELETE` (never `FLUSHDB`), so it never touches keys belonging to other services. +## Readiness -### Graceful Degradation +Every declared cache is added to the readiness probe, so a Redis outage takes the pod out of the +service pool instead of letting it serve cache misses while looking healthy. -In development or non-critical environments, set `fallback_to_local = true` to keep the service running when Redis is unavailable: +| Cache | Readiness entry | +|---|---| +| The default cache | `cache` | +| A cache named `sessions` | `cache:sessions` | +| Agent `orders`, default cache | `orders.cache` | +| Agent `orders`, cache `sessions` | `orders.cache:sessions` | -```toml -[default.cache] -backend = "redis" -redis_url = "redis://localhost:6379/0" -fallback_to_local = true -``` +`/health/ready` answers **503** with a diagnostic payload while any check is down; `/health/live` +is unaffected, so Kubernetes removes the pod from the service pool without killing it. Recovery is +automatic on the next health tick (`health_check_interval_seconds`, 30 seconds by default). For a +disk cache the check is trivially up -- a local filesystem does not fail the way a network service +does. -Behavior: -- If the `redis` extra is not installed: factory returns a `DiskCacheService`. -- If Redis is installed but unreachable on startup: `on_startup()` logs the failure and continues without raising. +--- -In production, leave `fallback_to_local = false` so startup fails loudly when the cache backend is misconfigured. +## The management API -## File-Based Locking +Declaring a cache mounts a small management API. A standalone application serves it at +`/api/cache/*`; in a group each agent that declared a cache gets its own under +`/api//cache/*`, so one agent's endpoint cannot report another's keys. -The DiskCacheService uses file-based locking to ensure safe concurrent access across multiple processes or deployment replicas sharing the same `cache_dir`. This means multiple instances of the same service can safely read and write to a shared cache directory without corruption. +| Method | Path | Body / query | Answers | +|---|---|---|---| +| `GET` | `/api/cache/stats` | `?name=` | Backend statistics for one cache | +| `GET` | `/api/cache/namespaces` | `?name=` | `{"namespaces": [...], "count": n}` | +| `POST` | `/api/cache/evict` | `{"namespace": "ns"}` | Clears that namespace, or the whole cache when `namespace` is omitted | -```toml -[default.cache] -# Shared cache directory across replicas -cache_dir = "/mnt/shared/blueprint-cache" +`?name=` selects which of the agent's caches to act on and defaults to `default`, so a request +that names nothing reaches the cache a single-cache application has always had. + +```bash +curl localhost:8000/api/cache/stats +curl 'localhost:8000/api/cache/stats?name=sessions' +curl localhost:8000/api/cache/namespaces +curl -X POST localhost:8000/api/cache/evict -H 'Content-Type: application/json' -d '{"namespace": "profiles"}' ``` -## Complete Example +Two failures, answered differently: **503** when the agent has no cache at all (it was built +without one, which may change without a redeploy), and **404** for a name that is not among the +ones it has -- a retry can never fix a typo. The 404 body lists the registered names, because +nothing else does. -```python -from blueprint.agents import AppBuilder, Config -from blueprint.agents.services.service_base import ServiceBase -from blueprint.agents.handler.event_handler_base import EventHandlerBase -from blueprint.agents.models.events import CloudEvent, HandlerResult +**The statistics are the backend's own**, not a fixed schema. A disk cache reports its directory, +entry count, size limit and eviction policy; Redis reports a server version, client count, memory +and uptime. Fields the backend in use did not fill in are omitted. +```jsonc +// disk +{"size": 4, "cache_dir": "/var/cache/blueprint", "size_limit": 1000000000, "eviction_policy": "least-recently-used"} +// redis +{"backend": "redis", "key_prefix": "orders-api", "redis_version": "7.2.4", "connected_clients": 3, ...} +``` -class EmbeddingService(ServiceBase): - async def on_startup(self) -> None: - self.cache = self.registry.cache_service - self.agent = self.registry.get_agent("embedder") +> `size` on the disk backend counts stored keys, and each cached value is stored with a parallel +> TTL entry -- so a cache holding two values reports `size: 4`. `list_values` and +> `list_namespaces` filter the TTL entries out; `size` does not. + +--- + +## How it fits together - async def get_embedding(self, text: str) -> list[float]: - # Check cache first - cached = await self.cache.get(text, namespace="embeddings") - if cached is not None: - return cached +The cache is a Strategy: calling code holds a `CacheService` and uses it through a fixed +interface, and which implementation that is gets decided once, at build time, from configuration. - # Compute and cache - embedding = await self.agent.run(text) - await self.cache.set(text, embedding, namespace="embeddings", ttl=86400) - return embedding +``` + settings.toml [default.cache] -- or [default..cache] for one agent in a group + | + v + Config.get_cache_config() -> CacheConfig (pydantic) + | + v + CacheBackendFactory.create(config, name=..., namespace=...) + | | + | +-- isolates the store: a directory, or a Redis key prefix + v + DiskCacheService or RedisCacheService (both are CacheService) + | + v + registry.add_cache(name, cache, namespace=...) keyed on (agent, name) + | + v + self.registry.get_cache("sessions") in any component of that agent +``` +Two design points worth knowing: -class DocumentHandler(EventHandlerBase): - priority = 10 +- **The factory isolates the store, not the caller.** How a backend separates two caches is + knowledge only that backend has -- the disk cache separates by directory, Redis by key prefix -- + so a new backend answers that question in the method that creates it, and no caller has to. +- **`key_prefix` and `namespace` are different tools.** `key_prefix` is configured once per + deployment and keeps whole services apart in a shared Redis. `namespace` is passed per call and + organises one cache's own keys. Both appear in every Redis key. - async def on_startup(self) -> None: - self.embedding_svc = self.registry.get_service(EmbeddingService) +A new backend means implementing `CacheService` and extending the factory. Nothing that uses a +cache has to change. - def can_handle_event(self, event: CloudEvent) -> bool: - return event.type == "document.received" +--- - async def handle_event(self, event: CloudEvent) -> HandlerResult: - embedding = await self.embedding_svc.get_embedding(event.data["content"]) - return HandlerResult( - event_type="document.embedded", - data={"doc_id": event.subject, "embedding": embedding}, - ) +## Where things live - def get_published_event_types(self) -> list[str]: - return ["document.embedded"] +| Path | What | +|---|---| +| `services/infrastructure/cache_service.py` | `CacheService` (the interface) and `DiskCacheService` | +| `services/infrastructure/redis_cache_service.py` | `RedisCacheService` | +| `services/infrastructure/cache_backend_factory.py` | Backend selection and store isolation | +| `io/api/utilities/cache.py` | The management API | +| `io/api/actuators/health/cache_health.py` | The readiness check | +| `models/config.py` | `CacheConfig` | +--- -config = Config(settings_files=["settings.toml"]) +## Troubleshooting -app = ( - AppBuilder(config) - .with_service(EmbeddingService) - .with_handler(DocumentHandler) - .with_agent("embedder", EmbedderAgent) - .with_cache() - .build() -) -``` +| Symptom | Cause | Fix | +|---|---|---| +| `ImportError: Redis backend requires ...[redis]` | The extra is not installed | `pip install 'avs-blueprint-agents[redis]'` | +| Logs show `DiskCacheService` with `backend = "redis"` set | The settings file is not the one being read, or the section is misspelt | Confirm `[default.cache]` and the `settings_files` path | +| `No cache registered as 'sessions'` | That agent never declared it | Add `.with_cache(name="sessions")`; there is no fallback to the default | +| Two replicas do not see each other's writes | Different `key_prefix` or `redis_url` | They must match exactly for replicas of one service | +| Two services overwrite each other's keys | The same `key_prefix` for different services | Give each service its own | +| An agent cannot see a cache its neighbour declared | Working as designed | Declare one in that agent too | +| `/api/cache/stats` answers 503 | The application built no cache | `with_cache()` | +| Entries vanished after an upgrade | The per-agent key layout changed | Expected once; the cache refills | diff --git a/docs/guides/caching-getting-started.md b/docs/guides/caching-getting-started.md deleted file mode 100644 index b70dad25..00000000 --- a/docs/guides/caching-getting-started.md +++ /dev/null @@ -1,208 +0,0 @@ -# Caching — Getting Started - -This guide walks a developer who is **already using `avs-blueprint-agents`** through enabling the centralised Redis cache for their service. Estimated time: 5 minutes once Redis is reachable. - -For the architectural background, see [Cache Architecture](../concepts/cache-architecture.md). - ---- - -## 1. Add the Redis extra to your project - -The `redis` Python package is shipped as an **optional extra** of `avs-blueprint-agents` so single-replica deployments don't pull in extra dependencies. - -In your project's `pyproject.toml`: - -```toml -[project] -dependencies = [ - "avs-blueprint-agents[redis]>=0.6.0", - # ... your other dependencies -] -``` - -If you use `requirements.txt`: - -``` -avs-blueprint-agents[redis]>=0.6.0 -``` - -If you use `uv`: - -```bash -uv add "avs-blueprint-agents[redis]" -``` - -What this pulls in: `redis>=5.0.0` with the `hiredis` C-parser for performance. - ---- - -## 2. Tell the blueprint which backend to use - -In your `settings.toml` (or whichever Dynaconf settings file you use): - -```toml -[default.cache] -backend = "redis" # was "disk" — switch here -key_prefix = "my-service-name" # avoids collisions in shared Redis -redis_url = "redis://localhost:6379/0" # full URL incl. db index -default_ttl = 600 # seconds; null = no expiry - -# --- Optional --- -# redis_password = "@format {env[REDIS_PASSWORD]}" -# redis_db = 0 -# redis_tls = false # true → uses rediss:// scheme -# fallback_to_local = false # true → fallback to DiskCache if Redis is down -``` - -**That's the only required change.** Your existing `AppBuilder().with_cache()` line picks up the new config automatically — no code change. - -### Required vs. optional fields - -| Field | Required? | Default | Notes | -|---|---|---|---| -| `backend` | yes (to switch) | `"disk"` | `"disk"` or `"redis"` | -| `redis_url` | yes for Redis | `"redis://localhost:6379/0"` | Standard URL, `redis://[user[:password]]@host:port/db` | -| `key_prefix` | recommended | `""` | Pick something distinctive per service — avoids collisions when multiple services share Redis | -| `default_ttl` | optional | `3600` | Seconds; `null` means no TTL is set on writes that don't supply one | -| `redis_password` | only if needed | `null` | Use Dynaconf env-var injection: `"@format {env[REDIS_PASSWORD]}"` | -| `redis_db` | optional | `0` | Redis DB index; usually `0` | -| `redis_tls` | only for TLS | `false` | When `true`, the connection upgrades to `rediss://` | -| `fallback_to_local` | optional | `false` | Soft fallback when Redis is unreachable at startup | - ---- - -## 3. Use the cache from your services - -Nothing changes here. Every service / handler / API resolves the cache from the registry in `on_startup()`: - -```python -from blueprint.agents.services.service_base import ServiceBase - -class MyService(ServiceBase): - async def on_startup(self) -> None: - self._cache = self.registry.cache_service - - async def on_shutdown(self) -> None: - return None - - def remember(self, key: str, value: dict) -> None: - self._cache.set(key, value, namespace="my-namespace") - - def recall(self, key: str) -> dict | None: - return self._cache.get(key, namespace="my-namespace") -``` - -The `self._cache` you receive is the **same instance** for every service in this app — that's what makes "two agents writing to the same cache" work. - ---- - -## 4. Verify it works - -Run a real Redis (Docker is fine): - -```bash -docker run -d --rm --name dev-redis -p 6379:6379 redis:alpine -``` - -Start your app: - -```bash -python -m uvicorn src.main:app --port 8000 -``` - -You should see in the log: - -``` -Adding component: redis_cache_service to registry -Registering cache service: RedisCacheService -RedisCacheService connected to redis://localhost:6379/0 (prefix='my-service-name') -``` - -Hit any endpoint that writes to the cache, then peek at Redis to see your keys: - -```bash -docker exec dev-redis redis-cli KEYS "my-service-name:*" -``` - -You should see one or more keys like `my-service-name:my-namespace:`. - ---- - -## 5. Multiple replicas — the actual point of the feature - -The whole reason for switching to Redis is **shared state across replicas**. To prove it works in your setup: - -```bash -# Terminal 1 — replica A -python -m uvicorn src.main:app --port 8001 - -# Terminal 2 — replica B (same code, same settings.toml, different port) -python -m uvicorn src.main:app --port 8002 - -# Write to replica A -curl -X POST 'http://localhost:8001/your-write-endpoint?...' - -# Read on replica B — should return what A just wrote -curl 'http://localhost:8002/your-read-endpoint' -``` - -If A's writes show up on B, you're done. If not, double-check `key_prefix` and `redis_url` are identical between the two replicas. - ---- - -## 6. Operations checklist - -Before you ship to production: - -- [ ] Use a managed Redis (or your platform's Redis service) — don't run `redis:alpine` in prod -- [ ] Set `redis_password` via env var, not literally in `settings.toml` -- [ ] Use TLS for any Redis that is not in the same VPC: `redis_tls = true` -- [ ] Pick a `key_prefix` that includes the service name *and* environment (e.g. `payments-svc-prod`) -- [ ] Decide on `fallback_to_local`: ON keeps the service up if Redis is down, OFF surfaces the issue immediately. Both are valid — choose the one that matches your operational posture -- [ ] Set `default_ttl` so abandoned keys eventually disappear -- [ ] Wire K8s probes to `/health/ready` (readiness) and `/health/live` (liveness) — the framework reflects Redis reachability via the readiness probe automatically - -### How the readiness probe interacts with Redis outages - -When `with_cache()` is called, a `CacheHealthChecker` is registered automatically and pings Redis on every health-check tick (default 30 s, configurable via `health_check_interval_seconds`). - -| Scenario | `/health/ready` | `/health/live` | K8s reaction | -|---|---|---|---| -| Redis healthy | `200 UP` with `cache: healthy` | `200 UP` | Pod in service pool, traffic flows | -| Redis stops mid-flight | Within ≤ 30 s flips to `503 DOWN` with full diagnostic payload | stays `200 UP` | Pod removed from service pool, **not** killed | -| Redis recovers | Within ≤ 30 s flips back to `200 UP` | stays `200 UP` | Pod re-added to service pool automatically | -| `fallback_to_local=true`, Redis unreachable at startup | `503 DOWN` once first health tick runs | `200 UP` | Pod alive but won't take traffic until Redis returns | -| `fallback_to_local=false`, Redis unreachable at startup | never reached (boot crashes) | never reached | CrashLoopBackOff → pager | - -A K8s `httpGet` probe on `/health/ready` only inspects the HTTP status code, so the 503 propagation is what makes the cache check actually take effect at the orchestration layer. - -Example K8s probe configuration: - -```yaml -readinessProbe: - httpGet: - path: /health/ready - port: 8000 - initialDelaySeconds: 10 # give the cache health check one tick - periodSeconds: 10 - failureThreshold: 3 # tolerate one missed tick before pulling the pod -livenessProbe: - httpGet: - path: /health/live - port: 8000 - initialDelaySeconds: 10 - periodSeconds: 30 -``` - ---- - -## Troubleshooting - -| Symptom | Cause | Fix | -|---|---|---| -| `ImportError: Redis backend requires 'avs-blueprint-agents[redis]'` | Forgot to install the extra | `pip install 'avs-blueprint-agents[redis]'` | -| Log shows `DiskCacheService` instead of `RedisCacheService` | `settings.toml` not picked up — wrong path or wrong section | Confirm `[default.cache]` section, confirm `Config(settings_files=["settings.toml"])` finds the file | -| `redis.exceptions.ConnectionError: Error 111 connecting to localhost:6379` | Redis not running | `docker ps` to check; `docker run -d -p 6379:6379 redis:alpine` to start | -| Two replicas don't see each other's keys | Different `key_prefix` between replicas | Identical `key_prefix` for replicas of the same service | -| Two services collide on the same key | Same `key_prefix` for different services | Pick distinct `key_prefix` values per service | -| `Component with name redis_cache_service already exists` (in tests) | A previous test already constructed a cache and the Component registry rejects duplicate names | Use the autouse fixture pattern from `tests/integration/test_shared_redis_cache.py` to clear the registry between tests | diff --git a/docs/superpowers/plans/2026-04-01-component-naming-refactor.md b/docs/plans/2026-04-01-component-naming-refactor.md similarity index 100% rename from docs/superpowers/plans/2026-04-01-component-naming-refactor.md rename to docs/plans/2026-04-01-component-naming-refactor.md diff --git a/docs/superpowers/plans/2026-07-06-sessions-agent-registration.md b/docs/plans/2026-07-06-sessions-agent-registration.md similarity index 99% rename from docs/superpowers/plans/2026-07-06-sessions-agent-registration.md rename to docs/plans/2026-07-06-sessions-agent-registration.md index bdce2225..487cbaf1 100644 --- a/docs/superpowers/plans/2026-07-06-sessions-agent-registration.md +++ b/docs/plans/2026-07-06-sessions-agent-registration.md @@ -8,7 +8,7 @@ **Tech Stack:** Python 3.12+, httpx / httpx-sse, pydantic v2, pytest (async), OpenTelemetry. Line length 140. Quality gate: `black`, `ruff`, `mypy`. -**Spec:** `docs/superpowers/specs/2026-07-06-sessions-agent-registration-design.md`. Closes #45 and #44. +**Spec:** `docs/specs/2026-07-06-sessions-agent-registration-design.md`. Closes #45 and #44. **Branch:** work on `feature/sessions-agent-registration` (already created). **All commits end with the repo's standard trailer** (`Co-Authored-By: Claude Opus 4.8 (1M context) …` + `Claude-Session: …`) — append it to every commit message; it is omitted from the command examples below only for brevity. diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 3b3c48fd..e7696851 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -5326,6 +5326,260 @@ that covers the Dockerfile and `main.py` paths a unit test cannot reach. --- +### Phase 8b, step 9 part 1 -- `AGENTS.md` exists + +`CLAUDE.md:5` has said *"See `AGENTS.md` for architecture, component patterns, and testing +conventions shared across all AI assistants"* for months, and +`git log --all --diff-filter=A -- AGENTS.md` returns nothing: the file was never written and +later deleted, it was **cited into existence**. `docs/plans/2026-06-10-sessions-job-handler.md:122` +goes further and quotes what it "states" about versioning. So this part adds no new home for +documentation -- it turns a pointer that resolves nowhere into one that resolves. + +**What it contains**, in the order it is read: + +- **Where things are** -- one table for `src/blueprint/agents/`, module by module, and one + paragraph pointing at the prose in `docs/` for users. Every path in it was checked to exist. +- **Component patterns** -- the six base classes and the five things every component of any of + them has in common (its constructor takes only what its author wrote; `self.registry`, + `self.config` and `self.executor` answer for its own agent; collaborators are resolved in + `on_startup`, not `__init__`; the lifecycle pair; what `should_register=False` is for), plus + the acknowledgement contract for handlers. +- **Design rules**, in six groups, each rule stating the rule, the reason, and **the failure it + prevents**: construction and assembly (collect then wire; one declaration surface; single-use + builders; group policy belongs to the collector), namespaces and isolation (a component never + learns it is in a group; structural where it can be and audited where it cannot; no cross-agent + fallback; an omitted namespace on the root registry means every namespace; entering the root + scope is not a no-op), names that leave the process (validated never repaired; two components of + one class collide on the derived name; a check answerable at the call stays at the call), + declarations and defaults (an empty declaration means everything; a key whose absence changes + behaviour is required), configuration and logging (injected before any component exists, read + through the component's own view, no public read path to the loader; isolation audited not + enforced; a process-scope key cannot be set per agent; logging belongs to the application), and + versioning. +- **Testing conventions** -- the unit/integration split and the `integration` marker, the + `TESTS.md` per package, probing against real objects, asserting on the observable thing rather + than on the call, what a test's docstring is for, that the frozen suite is frozen, and that a + guard test states its rule in its failure message. +- **How the work is done** -- no unused code; probe rather than assume, and say which it was; the + spec wins on precedence, not on correctness; report the code, not the wrapper. + +**The failure line is the point.** A rule without the failure it prevents is advice, and advice +gets argued away by the next person with a deadline. Most of these were bought with a defect -- +`namespace_scope("")` silently resetting every component to the root, a `MagicMock` registry +hiding six ownership bugs, `must_exist=True` beside a `default=` passing while the key is unset -- +and the failure line is the receipt. + +**Two claims in it were wrong when written, and were fixed rather than softened.** + +- *"Every test package has a `TESTS.md`."* Ten of them do, all under `tests/unit/agents/`, but + the top level -- where `test_agent_group.py`, `test_group_config.py`, `test_entrypoint.py` and + the new frozen suite live -- had none, and `tests/unit/agent_generator/` and + `tests/integration/` still have none. So `tests/unit/agents/TESTS.md` was written as part of + this commit, and the rule now says what is true, exceptions included. A rule that is already + violated by the tree it governs is the same failure as a document cited into existence. +- *"A `CHANGELOG.md` entry under the unreleased section."* The section is spelled `[Unreleased]`; + checked against the file. + +**The versioning quotation now resolves.** `.github/workflows/publish.yml` extracts the version +from the git tag and rewrites `pyproject.toml` at build time, so the sessions plan's claim that +"`AGENTS.md` states versioning is handled by CI publishing; manual bumps are forbidden" is true +of the pipeline -- and is now stated in `AGENTS.md`, which is where that plan said to look. Part 3 +has one less thing to fix. + +`CLAUDE.md:5` was extended to name the design rules as well, since the file it points at now +carries them. + +No production code changed; 2100 unit tests still pass. Parts 2 (the guard tests) and 3 (the +documentation cleanup) follow as their own commits. + +### Phase 8b, step 9 part 2 -- the guards, and the four defects they found + +`tests/unit/agents/test_design_rules.py`: one section per rule from `AGENTS.md`, and **every +failure message names the rule it enforces**, because someone who hits one of these has not made +an ordinary mistake in a test -- they have crossed a design decision and need to read the +decision. 565 cases, all of them cheap. + +| Guard | What it asserts | +|---|---| +| *Collect, then wire* | every `with_*` on `AppBuilder` **and** `AgentBuilder`, called reflectively: the registry is untouched, **no configuration is linked at all**, and the builder comes back for the next call | +| *One declaration surface* | per `AppBuilder` method: one declaration recorded, `replay` reproducing it, the namespace taken from the scope in force, and the recorded `kind` having a `with_` to replay onto | +| *A lookup never falls back across agents* | two agents' `sessions` caches kept apart, and no fallback to a neighbour, to the root, or from an unknown name to the default | +| *A component never learns it is in a group* | the ambient namespace reaching a component nobody passed one to; no `get_known_namespaces` on `Registry`, `Component` or `Config`; and the two refusals a view gives (`cache_entries`, `for_namespace`) | +| *A name is validated, never repaired* | five namespace entry points and the deployment route against seven illegal names, the cache alphabet at the `with_cache` call, and a legal name coming back unchanged | +| *No public read path to the unscoped loader* | the public configuration surface is exactly `config`, `configure`, `has_config`; no public attribute *is* the loader; a namespaced component reads through its own view | +| *Logging is configured by the application* | no logging configuration at import time anywhere under `src/`, and none in the framework outside `LoggingManager` | +| *No diagnostics via print* | nothing in the framework prints except the two listed stderr writes, each of which must still write to stderr | +| *References resolve* | every markdown link, every cited path in the documents that describe the tree as it stands, and every document cited by name | + +**The declaration-surface test moved here from `tests/unit/agents/app_builder/`** and was +generalised: the collect-then-wire half now runs over `AgentBuilder` as well, which records fields +rather than `Declaration` objects but is bound by the same rule -- `with_model_from_config` is the +method that used to read configuration while accumulating, and that one read is what forced an +agent to be built before its namespace existed. The stronger form of the assertion is that +**nothing is configured at all** while declarations are recorded: a `with_*` that reads a key +cannot pass it. + +**Four defects, found by the guards rather than by reading.** Two are production code: + +- **`clients/io/dapr_client.py` configured logging at import time.** Two `setLevel` calls on the + `httpx` and `httpcore` loggers at module level, so importing the Dapr client silenced those + loggers process-wide for an application that never asked. Both levels are already in + `LoggingManager._suppress_noisy_loggers`, which the `suppress_noisy_loggers` setting turns off + -- so the lines were duplication that also **overrode the application that had turned it off**. + Deleted; the setting is now the only thing that decides. +- **`agent_generator/generator/generator.py` configured logging at import time**, and that one + had a visible symptom: `asbs setup` imports `AgentGenerator`, so the module-level `basicConfig` + ran first and installed a root handler, and `setup.py`'s own `basicConfig` -- the one that reads + `--verbose` -- then found the root already configured and **did nothing**. `asbs setup --verbose` + has not been verbose. Moved into `cli()`, which is an entry point and may configure logging; + the flag works again. + +Two are documentation, both of which the references guard found: + +- **`CHANGELOG.md`** linked `ServiceInfo` to `/src/blueprint/agents/models/status.py:8:0-25:5` -- + an editor-pasted location, not a path. Rewritten as a citation. +- **`tests/unit/agents/services/TESTS.md`** still listed + `infrastructure/test_agent_scoped_cache.py`, deleted with `AgentScopedCache` in step 5. Row + removed. + +**One finding is listed rather than fixed.** `README.md` links twice to a `LICENSE` file that has +never been committed, while the README text and `pyproject.toml`'s classifier both say MIT. +Writing a licence file is a legal artefact and a human decision, so it is in the guard's +`KNOWN_GAPS` with that reason -- and a further case asserts every listed gap is **still** broken, +since an allowlist that outlives its entries is how a guard stops guarding. + +**The evidence corrected the guard twice**, which is worth recording because both were premises +that looked obviously right: + +- *A padded agent name is refused everywhere.* It is not, and should not be: the agent list is a + list, and both routes into it (`BLUEPRINT_AGENTS="orders, billing"`, or a YAML sequence) strip + each element before validating it. That is list parsing, not name repair -- the whitespace + belongs to the separator. The guard now uses `" Orders "` there instead, which is trimmed and + then still refused on the capital, so the trim cannot grow into a general repair. +- *A document cited by name must exist, in every document.* Not in the records: a proposal names + the documents it intends to write (`docs/guides/multi-agent-setup.md`, phase 10's deliverable) + and the alternatives it rejected (`docs/concepts/design-rules.md`), and both would fail. So that + check skips `docs/plans`, `docs/specs`, `docs/superpowers` and `CHANGELOG.md`, whose **links** + are still checked. The citation that motivated the whole guard was in `CLAUDE.md`, which is not + a record. + +The reference guard's scope is stated in the file with its reasoning, since a check on prose has +to say what it holds prose to: links are checked everywhere; path citations only in the documents +that describe this repository as it stands -- not in the records, which correctly name deleted +files, and not in the project-facing guides, whose `src/main.py` resolves in a generated project. +`docs/adr/` and `CLAUDE.local.md` are not scanned at all: neither is part of the repository, and a +guard has to give the same answer on every machine. + +**Every guard was verified by injection**: an import-time `setLevel` and a `print()` in +`utils/utils.py`, a dead link, a dead path citation and a fictitious `NOTHING.md` in `AGENTS.md`, a +root fallback in `Registry.get_cache`, and a construction inside `AppBuilder._record`. Each failed +exactly one guard, with the rule in the message, and nothing else. + +`AGENTS.md` now cites the file -- part 1 deliberately did not, since it did not yet exist -- both +under *Design rules* and beside the testing convention that requires a guard to state its rule. +`tests/unit/agents/TESTS.md` gained the row; `tests/unit/agents/app_builder/TESTS.md` lost the one +for the moved file. + +2625 unit tests pass, zero failures. Part 3, the documentation cleanup, follows. + +### Phase 8b, step 9 part 3 -- one home per document, and the 500 that documenting one found + +The audit behind step 9 listed four pieces of documentation debt. Two were real and are fixed, one +had already been closed by part 1, and **one turned out to rest on a misreading** -- recorded here +rather than quietly dropped, because an audit item that dissolves on inspection is worth the same +sentence as one that holds. + +**`docs/superpowers/` is gone.** It held `plans/` and `specs/` mirroring `docs/plans` and +`docs/specs` -- 3 files, 2079 lines, linked from nothing. They are ordinary plan and spec +documents, so they were **moved** rather than deleted: `2026-04-01-component-naming-refactor.md` +and `2026-07-06-sessions-agent-registration.md` into `docs/plans/`, +`2026-07-06-sessions-agent-registration-design.md` into `docs/specs/`. The plan's one citation of +its own spec was repointed; the only other links in the three files are same-document anchors. +`test_design_rules.py` lost `docs/superpowers` from `HISTORICAL_DOCUMENTS`, which would otherwise +have been a prefix matching nothing -- dead configuration in the guard that exists to catch dead +pointers. + +**Four cache documents became one.** `docs/concepts/caching.md` (347), +`docs/concepts/cache-system-overview.md` (232), `docs/concepts/cache-architecture.md` (181) and +`docs/guides/caching-getting-started.md` (208) -- 968 lines, one of which `docs/README.md` linked +-- are now a single 387-line `docs/concepts/caching.md`, the path both READMEs already pointed at. +The other three are deleted; git history keeps them. + +It is a rewrite rather than a merge, because the linked one was wrong about nearly everything a +reader would try: + +- **The REST API section documented four endpoints that have never existed** + (`GET`/`PUT`/`DELETE /api/cache/{namespace}/{key}`, `DELETE /api/cache/{namespace}`). The real + API is `GET /cache/stats`, `GET /cache/namespaces` and `POST /cache/evict`, each taking `?name=`. +- **Every example awaited a synchronous method.** `CacheService.get`/`set`/`delete` are ordinary + `def`s; `await self.cache.get(...)` does not work and never did. +- The closing example called `with_agent("embedder", EmbedderAgent)`, a signature that does not + exist. +- Nothing mentioned per-agent caches, named caches, `claim`, or `/api//cache/*`. +- `caching-getting-started.md` documented `default_ttl = null` as "no expiry". `CacheConfig.default_ttl` + is an `int`, and TOML has no null: **there is no way to configure "never expires"**, and an + omitted `ttl` gets the 3600-second default on both backends. + +The new document states what the code does, verified against it: declaration and the +`with_cache(False)` / `name=` shapes, the synchronous operations table, `claim` and the race it +closes, key hashing, namespaces, TTL, per-agent isolation with the storage layout for both +backends, the configuration table with per-agent `[default..cache]`, the Redis startup ping +and `fallback_to_local`, readiness entry names, the three real endpoints with their 503/404 split, +a short design section, and troubleshooting. + +**`GET /cache/stats` answered 500, on both backends, for as long as it has existed.** +`CacheStatsResponse` required five fields. `DiskCacheService.get_stats()` returns four of them -- +never `ttl_tracked_keys`, which **no backend has ever produced** -- so constructing the model +raised `ValidationError`. `RedisCacheService.get_stats()` returns a different shape entirely +(`backend`, `key_prefix`, `redis_version`, `connected_clients`, ...), so on Redis all five were +missing. Confirmed by probe before anything was changed: + +``` +real get_stats() -> {'cache_dir': ..., 'size': 2, 'size_limit': 1000000000, 'eviction_policy': 'least-recently-used'} +CacheStatsResponse RAISED: ValidationError -- ttl_tracked_keys: Field required +``` + +It was invisible because the endpoint's only test fed a hand-written dictionary through a +`MagicMock` -- a dictionary that contained `ttl_tracked_keys`, invented to satisfy a model nothing +satisfied. *Probe against real objects*, exactly. + +The fix says what was true all along: **the statistics are the backend's, not a fixed schema.** +`CacheStatsResponse` keeps the disk backend's four fields as optional, allows extras so Redis's +seven pass through, and the route carries `response_model_exclude_none=True` so each backend +answers with its own fields and no nulls. `ttl_tracked_keys` is deleted, and so is +`CacheEvictResponse`, which was referenced by nothing and described a shape (`success`, +`evicted_keys`) that the evict endpoint does not return. The test now constructs a real +`DiskCacheService` and a real `RedisCacheService` over `fakeredis`, and a third case pins the +behaviour when a backend's own stats call fails: `get_stats` returns `{}` and the endpoint answers +200 with an empty payload rather than taking itself down. End-to-end through a built application: + +``` +/api/cache/stats -> 200 {'size': 0, 'cache_dir': '...', 'size_limit': 1000000000, 'eviction_policy': 'least-recently-used'} +/api/cache/stats?name=sessions -> 200 {'size': 0, 'cache_dir': '.../sessions', ...} +/api/cache/stats?name=nope -> 404 {'detail': "No cache registered as 'nope' for agent '' (registered: default, sessions)"} +``` + +**The false quotation was already closed.** `docs/plans/2026-06-10-sessions-job-handler.md:122` +attributes to `AGENTS.md` that versioning is handled by CI publishing and manual bumps are +forbidden. Part 1 verified that against `.github/workflows/publish.yml` and wrote the rule into +`AGENTS.md`, so the attribution now resolves. Nothing to change; checked, not assumed. + +**`docs/development-workflow.md` is not a dead pointer.** The audit called it "cited by this +plan's own file summary and never written". It is not cited anywhere as existing: its three +mentions are this plan's part 3 item, the changelog, and the plan's *Planned, not yet written* +section, whose own preamble says "each is a deliverable, not an open question". So there is no +reference to drop, and writing the end-to-end walkthrough now would pre-empt phase 10, which owns +the narrative documentation. Left where it is. This is the same distinction the references guard +draws by not holding a record to the tree as it stands -- and the audit item was, in effect, the +guard's rejected premise in prose form. + +`README.md` and `docs/README.md` keep their one caching link, with descriptions that now say what +the document covers. + +2620 unit tests pass, zero failures. + +--- + ## Open points - **Phase 7's ambiguity error needs a spec amendment.** The plan asks `process_event` to raise @@ -5480,11 +5734,17 @@ that covers the Dockerfile and `main.py` paths a unit test cannot reach. migration -- **the key layout changed twice**, so an application upgrading with a persistent redis cache or a mounted disk cache sees its old entries as absent. A cold cache rather than an error, and it must be said in the migration guide (phase 10), for both hops. -- **The cache documentation is wrong about the endpoints, and now about their paths too.** - `docs/concepts/caching.md` documents `GET`/`PUT /api/cache/{namespace}/{key}`, which have never - existed (the API is `stats`, `namespaces`, `evict`), and step 5 moved a grouped agent's routes - to `/api//cache/*`. Left for step 9 part 3, which owns the four overlapping cache - documents; fixing one of them here would have been the fifth version of the same content. +- ~~**The cache documentation is wrong about the endpoints**~~ -- **done in step 9 part 3.** + The four overlapping documents became one, rewritten against the code: the three real endpoints + with their `?name=` and their 503/404 split, the per-agent `/api//cache/*` paths, and the + synchronous interface every old example awaited. Writing it turned up a 500 in + `GET /cache/stats`, fixed in the same commit. +- **`size` in the cache statistics counts the TTL metadata entries.** The disk backend stores a + parallel `:ttl` entry beside every value, and `get_stats()["size"]` is the raw key count -- so a + cache holding two values reports `size: 4`, exactly double. `list_values` and `list_namespaces` + already filter those entries out; `size` does not. Documented as it is rather than changed, + because a reported metric is somebody's dashboard: the fix is to count filtered keys, and it + wants a decision rather than a drive-by. - **The examples are not migrated, by decision (2026-09-08).** Note that phase 8b changes what blocks them: `AgentRegistration` is deleted, and passing instances (`with_rest_api(MonitorApi())`) stays legal standalone -- it is refused only when a builder is collected into a group. So the @@ -5525,4 +5785,9 @@ that covers the Dockerfile and `main.py` paths a unit test cannot reach. on by default in the generated settings. - **The two design questions in spec sec. 13** that change the shape rather than the parameters: 20 or 100 agents, and whether the 4 GB host budget is real. +- **There is no `LICENSE` file.** `README.md` links to one twice -- a badge and the closing line + -- and `pyproject.toml` carries the MIT classifier, but no licence text has ever been committed. + Found by step 9 part 2's reference guard and listed in its `KNOWN_GAPS`, because adding a + licence is a legal artefact and somebody's decision rather than a documentation fix. Whoever + settles it removes that entry, which a guard case then requires. - **#80** -- the failing example tests and the unenforced test split. diff --git a/docs/superpowers/specs/2026-07-06-sessions-agent-registration-design.md b/docs/specs/2026-07-06-sessions-agent-registration-design.md similarity index 100% rename from docs/superpowers/specs/2026-07-06-sessions-agent-registration-design.md rename to docs/specs/2026-07-06-sessions-agent-registration-design.md diff --git a/src/blueprint/agent_generator/generator/generator.py b/src/blueprint/agent_generator/generator/generator.py index dac234f0..78060f7d 100644 --- a/src/blueprint/agent_generator/generator/generator.py +++ b/src/blueprint/agent_generator/generator/generator.py @@ -21,10 +21,6 @@ SecretsPartGenerator, ) -# Configure logging -logging.basicConfig( - level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", handlers=[logging.StreamHandler(sys.stdout)] -) logger = logging.getLogger(__name__) @@ -383,9 +379,19 @@ def main(config_path: str, output_dir: str) -> None: def cli() -> None: - """Command line interface for the generator.""" + """Command line interface for the generator. + + Logging is configured here rather than at module level: this function is an entry point, so + it is the application. Configured on import, it would install a root handler for anything + that merely imports ``AgentGenerator`` -- which is what ``asbs setup`` does, and its own + ``basicConfig`` (and with it ``--verbose``) would then silently do nothing. + """ import argparse + logging.basicConfig( + level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", handlers=[logging.StreamHandler(sys.stdout)] + ) + parser = argparse.ArgumentParser(description="Generate an agent microservice from a template.") parser.add_argument("config", help="Path to the JSON configuration file") parser.add_argument( diff --git a/src/blueprint/agents/clients/io/dapr_client.py b/src/blueprint/agents/clients/io/dapr_client.py index 40bf4044..a5fa06b0 100644 --- a/src/blueprint/agents/clients/io/dapr_client.py +++ b/src/blueprint/agents/clients/io/dapr_client.py @@ -16,10 +16,6 @@ logger = logging.getLogger(__name__) -# Suppress httpx and httpcore INFO logs during health checks -logging.getLogger("httpx").setLevel(logging.WARNING) -logging.getLogger("httpcore").setLevel(logging.WARNING) - class DaprClient(IOClientBase): """Dapr client for publishing CloudEvents via Dapr pub/sub. diff --git a/src/blueprint/agents/io/api/utilities/cache.py b/src/blueprint/agents/io/api/utilities/cache.py index 3ec15e17..73606def 100644 --- a/src/blueprint/agents/io/api/utilities/cache.py +++ b/src/blueprint/agents/io/api/utilities/cache.py @@ -67,9 +67,20 @@ def _cache(self, name: str) -> CacheService: except ValueError as exc: raise HTTPException(status_code=404, detail=str(exc)) from exc - @RestApiBase.get("/cache/stats", response_model=CacheStatsResponse, tags=["cache"], summary="Get cache statistics.") + @RestApiBase.get( + "/cache/stats", + response_model=CacheStatsResponse, + response_model_exclude_none=True, + tags=["cache"], + summary="Get cache statistics.", + ) async def get_cache_stats(self, name: str = DEFAULT_CACHE_NAME) -> CacheStatsResponse: - """Get statistics for one cache.""" + """Get statistics for one cache, in whatever shape its backend reports. + + ``exclude_none`` because the model's named fields are the disk backend's: a Redis cache + fills none of them and would otherwise answer four nulls alongside the seven fields it + did report. + """ stats = self._cache(name).get_stats() return CacheStatsResponse(**stats) diff --git a/src/blueprint/agents/models/api.py b/src/blueprint/agents/models/api.py index 93605c34..91a1bf61 100644 --- a/src/blueprint/agents/models/api.py +++ b/src/blueprint/agents/models/api.py @@ -244,13 +244,28 @@ class CustomCheckHealth(BaseModel): class CacheStatsResponse(BaseModel): - """Cache statistics response model.""" + """What one cache reports about itself. **The fields are the backend's, not this model's.** + + A disk cache and a Redis cache have almost nothing to report in common: the disk backend + answers with its directory, its entry count and its eviction policy, while Redis answers + with a server version, a client count and its key prefix. So every field here is optional + and extras are kept -- the payload is whatever ``CacheService.get_stats`` returned, and the + route drops the fields the backend in use did not fill in. + + It was not always so: the four disk fields were required and a fifth, ``ttl_tracked_keys``, + was required and produced by **no** backend, so ``GET /cache/stats`` raised a + ``ValidationError`` and answered 500 -- on Redis it was missing all five. The endpoint's only + test passed a hand-written dictionary through a ``MagicMock``, inventing the field that does + not exist; a real cache was never asked. That is the failure *probe against real objects* + names, and the test now constructs a `DiskCacheService`. + """ + + model_config = ConfigDict(extra="allow") - size: int - cache_dir: str - ttl_tracked_keys: int - size_limit: int - eviction_policy: str + size: int | None = Field(default=None, description="Entries held, for a backend that counts them") + cache_dir: str | None = Field(default=None, description="Directory the disk backend writes to") + size_limit: int | None = Field(default=None, description="Configured maximum size in bytes, for the disk backend") + eviction_policy: str | None = Field(default=None, description="Eviction policy in force, for the disk backend") class CacheNamespacesResponse(BaseModel): @@ -266,14 +281,6 @@ class CacheEvictRequest(BaseModel): namespace: str | None = None -class CacheEvictResponse(BaseModel): - """Response for cache eviction operation.""" - - success: bool = Field(..., description="Whether the eviction was successful") - namespace: str | None = Field(None, description="The namespace that was evicted") - evicted_keys: int = Field(0, description="Number of keys evicted") - - class AgentHealthDependencies(BaseModel): """Dependencies checked during agent health check.""" diff --git a/tests/unit/agents/TESTS.md b/tests/unit/agents/TESTS.md new file mode 100644 index 00000000..65521609 --- /dev/null +++ b/tests/unit/agents/TESTS.md @@ -0,0 +1,28 @@ +# Unit Tests — `blueprint.agents` (top level) + +Test coverage for the modules that describe a whole *process* rather than one component: +`src/blueprint/agents/agent_group.py`, `src/blueprint/agents/group_config.py` and +`src/blueprint/agents/entrypoint.py` -- plus the frozen compatibility suite and the design-rule +guards, which are about the framework as a whole and therefore belong to no single package. + +Each subdirectory has its own `TESTS.md` for the package it covers. + +--- + +## File overview + +| File | Class under test | What is covered | +|---|---|---| +| `test_agent_group.py` | `AgentGroup` | One namespace per agent (each agent's components qualified, a group of one, a mapping refusing two agents under one name); agent names (illegal names and the root refused); what a group refuses and does not (an already-built builder, `AppBuilder(config)`, a constructed instance, a factory accepted, nothing assembled when a refusal fires); caches (a group declares none, an agent's own is registered to it, two agents declaring one name get separate stores, neither can read the other's); loading a declaration (a missing module, a missing attribute, a non-`AppBuilder`, an import that raises -- each fatal for a critical agent and skipped with an ERROR otherwise); `from_config` performing no I/O of its own; `resolve` reading the environment and the group file; that the builder learns nothing about groups; and each agent's own settings file (looked for beside the declaration module, merged under that agent's scope, merged *before* its components are built, and not reaching a neighbour) | +| `test_group_config.py` | `GroupConfig`, `AgentSpec` | Reading the group file (the named group, another group in the same file, a single group needing no name, the agent's module coming from the image's agent map, a `cache_names` list now read by nothing); resolution from the environment alone; precedence (the environment overriding the file key by key, the file's other values surviving, the source of each value logged, the resolved group logged); criticality (a critical agent's failure fatal, a non-critical one skipped); validation against the agent map (an unknown name refused, a duplicate); agent names held to the namespace alphabet; and the value object itself (constructed literally, frozen) | +| `test_entrypoint.py` | `build_group_app`, `main` | `build_group_app` resolving the group and returning the application with its configuration; `main` returning `0` on a clean run and `1` for a group that cannot be resolved, printing the reason to stderr as well as logging it; that the module is runnable as `python -m blueprint.agents.entrypoint`; and that one declaration serves both deployment shapes -- the same `AppBuilder` built standalone and assembled into a group | +| `test_design_rules.py` | The design rules in `AGENTS.md` | One section per rule, each failure message naming the rule it enforces. *Collect, then wire* and *one declaration surface*: every `with_*` on `AppBuilder` and `AgentBuilder` is discovered rather than listed (a new one fails the file until it has a sample call) and called reflectively -- nothing constructed, no configuration needed, the builder returned; and per `AppBuilder` method, one declaration recorded, `replay` reproducing it, the namespace taken from the scope, and the recorded `kind` having a `with_`. *A lookup never falls back across agents*: two agents' caches of one name kept apart, and no fallback to a neighbour, to the root, or from an unknown name to the default. *A component never learns it is in a group*: the ambient namespace, no `get_known_namespaces`, and the two refusals a view gives (`cache_entries`, `for_namespace`). *A name is validated, never repaired*: five namespace entry points and the deployment route against seven illegal names, the cache alphabet, and a legal name coming back unchanged. *No public read path to the unscoped loader*: the public configuration surface is exactly `config`, `configure`, `has_config`, and a namespaced component reads through its view. *Logging is configured by the application*: no logging configuration at import time anywhere in `src/`, and none in the framework outside `LoggingManager`. *No diagnostics via print*: none in the framework beyond the two listed stderr writes. *References resolve*: every markdown link, every cited path in the documents that describe the tree as it stands, and every document cited by name | +| `test_frozen_compatibility.py` | `AppBuilder`, `Registry`, `Component` | **Frozen (spec sec. 10.2): never updated for an API change.** What an existing single-agent project already does -- the builder shapes the examples use including instance forms; `with_cache(False)` and `with_cache(True, False)` positionally; the registry names lookups use (derived, explicit, the cache backend's, the `cache_service` alias, two services resolving one cache); the paths a project serves (`/api/` with its own tags, `/api/cache/stats`, the actuators); the readiness entries (`cache`, a bare custom name); and a component constructed with `super().__init__()` needing no change | + +--- + +## Fixtures (`conftest.py`) + +| Fixture | Scope | Purpose | +|---|---|---| +| `mock_prompt_loader` | function / **autouse** | Stubs `PromptLoader.load_prompt` for every test under `tests/unit/agents`, so no test reads a prompt file from disk. Skipped by node id for the prompt-loader tests and the three `AgentBuilder` cases that patch it themselves | diff --git a/tests/unit/agents/app_builder/TESTS.md b/tests/unit/agents/app_builder/TESTS.md index d9730a7b..d9206c64 100644 --- a/tests/unit/agents/app_builder/TESTS.md +++ b/tests/unit/agents/app_builder/TESTS.md @@ -10,7 +10,6 @@ Test coverage for `src/blueprint/agents/app_builder.py`. |---|---|---| | `test_deferred_wiring.py` | `AppBuilder`, `Declaration` | Nothing is constructed or registered before `build()`; what a declaration records (kind, target, name, ambient namespace, kwargs); the declaration-order refusal and the three cases it must *not* fire on; where the configuration may be handed over and the refusal when it is given twice; the single-use guard; an application that declares nothing; an unbuilt `AgentBuilder` handed to `with_agent` and built with its agent's scoped view | | `test_namespace_placement.py` | `AppBuilder`, `namespace_scope`, `host_agent` | A component reaches the right agent without anyone naming a namespace: the ambient scope qualifies the registry name, reaches the component and is never forwarded to its constructor; it is captured at the call, not at construction; explicit names are qualified too; an already-built instance is refused for another namespace; `host_agent` records the composition and refuses a duplicate, the root and an illegal name; and the four deleted surfaces (`AgentRegistration`, `RegisteredComponent`, `NamespaceBuilder`, `with_namespace`/`with_registration`) stay deleted | -| `test_declaration_surface.py` | `AppBuilder`, `Declaration.replay` | The gate that keeps the declaration API and the group's replay in agreement: every public `with_*` is discovered rather than listed (a new one fails the file until it has a sample call), and per method -- one declaration recorded, the registry untouched, `replay` onto a fresh builder reproducing the declaration exactly, a replay inside `namespace_scope` taking the namespace from the scope, and the recorded `kind` having a `with_` to replay onto; plus the irregular positional name of `with_health_checker` surviving a replay | | `test_app_builder.py` | `AppBuilder` | `with_handler` (TypeError for non-subclass, class instantiated, instance accepted without re-instantiation, name propagated, returns self); `with_service`/`with_agent`/`with_scheduler`/`with_rest_api` (instance accepted, returns self); `with_cache` (enabled creates DiskCacheService, disabled skips config read); `with_health_checker` (recorded as a `Declaration` before build, added straight to the actuator after build, several accumulate, a checker is never constructed, returns self); `build()` (event_bus=dapr/nats/unknown/no-handlers routing, EventPublishingService conditional on IO clients, pending health checkers wired, returns FastAPI instance); scheduler wiring (an event-mode scheduler is wired before the transport decision, so its tick handler is what causes a NATS client and eventing endpoint to be created; an in-process scheduler alone creates neither); the publish/consume split (`event_publishing_enabled` off means no client; on means a client with no eventing component and no `EventProcessingService`; the string form an environment variable delivers; rejections for no transport, `"sessions"` and a non-boolean; and a consuming application still publishing without the key) | --- diff --git a/tests/unit/agents/app_builder/test_declaration_surface.py b/tests/unit/agents/app_builder/test_declaration_surface.py deleted file mode 100644 index 9d2e9ccc..00000000 --- a/tests/unit/agents/app_builder/test_declaration_surface.py +++ /dev/null @@ -1,216 +0,0 @@ -"""The declaration surface and ``AgentGroup``'s replay must agree, and cannot drift apart. - -Adding a capability to the framework is now **one** edit -- a ``with_*`` method on -``AppBuilder`` -- which is the whole point of phase 8b. But the group still has to be able to -move a recorded call from one builder to another, and ``Declaration.replay`` does that by -resolving ``with_`` with ``getattr``. So there are exactly two ways for the two halves to -part company: - -- a ``with_*`` method records a ``kind`` that no method answers to, and replay dies with an - ``AttributeError`` at assembly -- in a group, never standalone; -- a ``with_*`` method whose replayed arguments do not reproduce the call, so an agent is - assembled from a declaration that says something slightly different from what its ``main.py`` - said. - -Neither is visible in a single-agent application, and both would be found in production by -somebody grouping two agents. Hence a gate: every public declaration method is called -reflectively, its declaration is replayed onto a fresh builder, and the result must be equal to -what was recorded. - -**A new ``with_*`` method fails this file until it is listed in ``SAMPLE_CALLS``.** That is -deliberate -- the list is what proves the method was thought about -- and the failure message -says so. -""" - -from typing import Any -from unittest.mock import MagicMock - -import pytest - -from blueprint.agents.agent.agent_builder import AgentBuilder -from blueprint.agents.app_builder import AppBuilder, Declaration -from blueprint.agents.component.component import Component -from blueprint.agents.component.namespace import namespace_scope -from blueprint.agents.io.api.actuators.health.health_base import HealthCheckerBase -from blueprint.agents.io.api.rest_api_base import RestApiBase -from blueprint.agents.io.api.scheduling.scheduler import SchedulerBase -from blueprint.agents.models.api import ComponentHealth -from blueprint.agents.services.service_base import ServiceBase - -from .conftest import StubHandler - - -class StubService(ServiceBase): - async def on_startup(self) -> None: - pass - - async def on_shutdown(self) -> None: - pass - - -class StubApi(RestApiBase): - async def on_startup(self) -> None: - pass - - async def on_shutdown(self) -> None: - pass - - -class StubScheduler(SchedulerBase): - async def on_startup(self) -> None: - pass - - async def on_shutdown(self) -> None: - pass - - -class StubChecker(HealthCheckerBase): - async def health_check(self) -> ComponentHealth: - return ComponentHealth(status="healthy", message="ok") - - -SAMPLE_CALLS: dict[str, tuple[tuple[Any, ...], dict[str, Any]]] = { - "with_handler": ((StubHandler,), {"name": "a_handler"}), - "with_service": ((StubService,), {"name": "a_service"}), - "with_agent": ((AgentBuilder(runtime_name="a_runtime"),), {}), - "with_scheduler": ((StubScheduler,), {"name": "a_scheduler"}), - "with_rest_api": ((StubApi,), {"name": "an_api"}), - "with_cache": ((), {"name": "a_cache"}), - "with_health_checker": (("a_check", StubChecker()), {}), -} -"""One call per declaration method, as a project would write it. - -Keyword arguments are given where the method takes a name, because a name is the part replay is -most able to lose: ``with_health_checker`` takes it positionally and every other method takes it -as a keyword, and that irregularity lives in exactly one branch of ``Declaration.replay``. -""" - - -def declaration_methods() -> list[str]: - """Every public declaration method on ``AppBuilder``, discovered rather than listed. - - Discovered, so that a method added without a sample call fails this file instead of being - quietly untested. The ``with_`` prefix is what makes a method a declaration: ``host_agent`` - records no ``Declaration`` -- it states a fact about the process -- and is not one of these. - """ - return sorted(name for name in dir(AppBuilder) if name.startswith("with_")) - - -def registry_contents() -> dict[str, object]: - """Every component in the shared registry, or nothing when there is not even a registry yet. - - Read through ``_components`` because there is no public "list everything" method, and there - should not be: C6 keeps a process-wide view out of reach of the components themselves. - """ - registry = Component.shared_registry - return dict(registry._components) if registry is not None else {} - - -class TestEveryDeclarationMethodIsCovered: - def test_the_sample_calls_name_every_method(self) -> None: - missing = set(declaration_methods()) - set(SAMPLE_CALLS) - assert not missing, ( - f"{', '.join(sorted(missing))} is a declaration method with no sample call in this file. Add one: the " - "list is what proves a new with_* was checked against the group's replay, which is the only place a " - "recorder and its API can drift apart." - ) - - def test_the_sample_calls_name_nothing_that_is_gone(self) -> None: - extra = set(SAMPLE_CALLS) - set(declaration_methods()) - assert not extra, f"{', '.join(sorted(extra))} no longer exists on AppBuilder; remove the sample call." - - -@pytest.mark.parametrize("method", declaration_methods()) -class TestRecordingAndReplayAgree: - def test_the_call_records_exactly_one_declaration(self, mock_config: MagicMock, method: str) -> None: - builder = AppBuilder() - arguments, keywords = SAMPLE_CALLS[method] - - getattr(builder, method)(*arguments, **keywords) - - assert len(builder.declarations) == 1 - - def test_nothing_is_constructed_by_recording_it(self, mock_config: MagicMock, method: str) -> None: - """Collect, then wire: a component built during accumulation belongs to the root for ever.""" - builder = AppBuilder() - arguments, keywords = SAMPLE_CALLS[method] - before = registry_contents() - - getattr(builder, method)(*arguments, **keywords) - - assert registry_contents() == before - - def test_replay_reproduces_the_declaration(self, mock_config: MagicMock, method: str) -> None: - """What a group does to move an agent's calls onto the root builder, and it must be lossless.""" - source = AppBuilder() - arguments, keywords = SAMPLE_CALLS[method] - getattr(source, method)(*arguments, **keywords) - - target = AppBuilder() - for declaration in source.declarations: - declaration.replay(target) - - assert target.declarations == source.declarations - - def test_replay_takes_the_namespace_from_the_scope_it_runs_in(self, mock_config: MagicMock, method: str) -> None: - """The ambient mechanism: no namespace is passed, and none appears in any signature.""" - source = AppBuilder() - arguments, keywords = SAMPLE_CALLS[method] - getattr(source, method)(*arguments, **keywords) - - target = AppBuilder() - with namespace_scope("orders"): - for declaration in source.declarations: - declaration.replay(target) - - assert [entry.namespace for entry in target.declarations] == ["orders"] - assert [entry.namespace for entry in source.declarations] == [""] - - def test_the_recorded_kind_has_a_method_to_replay_onto(self, mock_config: MagicMock, method: str) -> None: - """``Declaration.replay`` resolves ``with_`` with getattr, and this is that contract.""" - builder = AppBuilder() - arguments, keywords = SAMPLE_CALLS[method] - - getattr(builder, method)(*arguments, **keywords) - - for declaration in builder.declarations: - assert hasattr(AppBuilder, f"with_{declaration.kind}"), ( - f"{method}() records kind '{declaration.kind}', but there is no with_{declaration.kind}() for " - "Declaration.replay to call. A group would fail at assembly with an AttributeError while the same " - "declaration worked standalone." - ) - - -class TestTheNameSurvivesTheIrregularSignature: - """``with_health_checker(name, checker)`` is the one method whose name is positional.""" - - def test_a_replayed_checker_keeps_its_name(self, mock_config: MagicMock) -> None: - checker = StubChecker() - source = AppBuilder().with_health_checker("db", checker) - - target = AppBuilder() - for declaration in source.declarations: - declaration.replay(target) - - recorded = target.declarations[0] - assert (recorded.name, recorded.target) == ("db", checker) - - def test_a_replayed_component_keeps_its_name_override(self, mock_config: MagicMock) -> None: - source = AppBuilder().with_service(StubService, name="planner") - - target = AppBuilder() - for declaration in source.declarations: - declaration.replay(target) - - assert target.declarations[0].name == "planner" - - def test_a_replayed_declaration_keeps_its_constructor_arguments(self, mock_config: MagicMock) -> None: - source = AppBuilder().with_cache(True, False, name="sessions") - - target = AppBuilder() - for declaration in source.declarations: - declaration.replay(target) - - assert target.declarations[0] == Declaration( - kind="cache", target=None, name="sessions", namespace="", kwargs={"enable_locking": False} - ) diff --git a/tests/unit/agents/io/TESTS.md b/tests/unit/agents/io/TESTS.md index 79f69bcf..1f3a7719 100644 --- a/tests/unit/agents/io/TESTS.md +++ b/tests/unit/agents/io/TESTS.md @@ -18,7 +18,7 @@ Test coverage for `src/blueprint/agents/io/`. | `api/eventing/test_nats.py` | `NatsEventing` | `subscribe`/`publish` delegate to `_client`, RuntimeError when client is None; `on_startup` fetches client, subscribes to handler-declared and config-declared topics, deduplicates, preserves handler-first order, skips when no topics; `_subscribe_to_topic` RuntimeError when client None, calls `_client.subscribe` with topic and callback | | `api/eventing/test_sessions_bus.py` | `SessionsBus` | `on_startup` validation (no config/base_url/agent_id/api_key, already started, task created); `on_shutdown` (no task, running task cancelled); `_convert_to_cloud_event` (type/id/subject/source/data); `_process_job_notification` (no handler logged, `InvalidEventError`→cancel job, cancel failure swallowed, `RetryableHandlerError`→log, 403→invalidate+retry, 403 retry failure propagates `InvalidEventError`, non-403 propagates) | | `api/scheduling/test_scheduler.py` | `SchedulerBase`, `SchedulerTickHandler` | `_trigger_tick` calls `tick()` and returns `{"status": "triggered"}`; `scheduler_mode` reads both values case-insensitively, has no default so an absent, empty or missing key raises with both values named, rejects an unrecognised value and resolves once; `tick_topic` derives from `app_name` and the (possibly renamed) scheduler name, honours the `topic=` override, rejects a missing identity and a wildcard, rejects whitespace in an explicit topic and rewrites it in a derived one; `wire()` creates the tick handler in event mode only, is idempotent, registers the trigger route once in both modes, refuses event mode without a topic-carrying `event_bus` and accepts both broker transports; `on_startup` starts no timer in event mode, creates and starts `AsyncIOScheduler` on the declared crontab in in-process mode, and starts no second timer or route when called twice (#43); `on_shutdown` calls `shutdown(wait=True)` only when running and allows a later restart; the in-process tick claim -- the winner ticks and a loser does not, the key carries the scheduler and the minute, the claim carries the tick TTL and its own namespace, three replicas sharing a real `DiskCacheService` run one tick between them, a later slot is claimable again, no cache means every replica ticks and startup warns, the timer is wired to the claimed wrapper rather than to `tick`, and event mode claims nothing; `validate_crontab` accepting the five standard fields, stripping whitespace and rejecting empty, nonsense and six-field (apscheduler) expressions, with event-mode wiring failing on a bad crontab and in-process wiring not reaching the check; the tick handler declares its topic, outranks the default handler priority, claims a delivery under `nats_topic`/`dapr_topic`/`topic`, declines other or absent topics, ticks its scheduler without publishing an event, lets a failing tick reach the transport edge, and two schedulers register under distinct names in a real `Registry` | -| `api/utilities/test_cache.py` | `CacheManagementApi` | 503 when no cache, `get_cache_stats`/`list_cache_namespaces`/`evict_cache_entry` delegate to registry cache service | +| `api/utilities/test_cache.py` | `CacheManagementApi` | Which cache each endpoint reaches (`?name=` selecting a named cache, the default when none is given, evict clearing only the one it names) and how it fails (503 with no cache registered at all, 404 for an unknown name, the 404 listing the registered names); and the statistics payload **against real backends** -- a real `DiskCacheService` reporting its four fields, a real `RedisCacheService` over `fakeredis` reporting a different seven, and a backend whose own stats call fails answering an empty payload rather than a 500 | | `api/utilities/test_root.py` | `RootApi` | Service name/version/description from config (and defaults when `None`); both/one/neither doc links rendered; non-`APIRoute` routes skipped; `GET` route → direct link; non-`GET` route with `docs_url` → Swagger anchor link, without `docs_url` → plain path; route summary and sorted methods in row; cache hit skips config on second call | | `telemetry/test_telemetry.py` | `TelemetryManager`, `TracingContext` | `configure_tracing` raises when config None, no-op when disabled, creates TracerProvider when enabled; `_build_exporters` OTLP/empty; `TracingContext` span lifecycle + attribute filtering | diff --git a/tests/unit/agents/io/api/utilities/test_cache.py b/tests/unit/agents/io/api/utilities/test_cache.py index d5a18b6b..3a2f2b43 100644 --- a/tests/unit/agents/io/api/utilities/test_cache.py +++ b/tests/unit/agents/io/api/utilities/test_cache.py @@ -7,21 +7,33 @@ retry that can never succeed. """ +from pathlib import Path from unittest.mock import MagicMock +import fakeredis import pytest from fastapi import HTTPException from blueprint.agents.io.api.utilities.cache import CacheManagementApi from blueprint.agents.models.api import CacheEvictRequest +from blueprint.agents.models.config import CacheConfig +from blueprint.agents.services.infrastructure.cache_backend_factory import CacheBackendFactory +from blueprint.agents.services.infrastructure.redis_cache_service import RedisCacheService STATS = { "size": 10, "cache_dir": "/tmp/cache", - "ttl_tracked_keys": 5, "size_limit": 1_000_000_000, "eviction_policy": "least-recently-used", } +"""What a disk cache reports, as it reports it. + +It is the shape :meth:`DiskCacheService.get_stats` really returns, and +:class:`TestTheStatsPayloadIsTheBackends` holds it to that against a real cache. It once carried +a fifth key, ``ttl_tracked_keys``, that no backend has ever produced -- invented here, accepted +by a ``MagicMock``, and required by ``CacheStatsResponse``, so the endpoint answered 500 while +these tests passed. +""" @pytest.fixture @@ -113,6 +125,74 @@ async def test_response_reports_all_when_no_namespace(self, cache_api_with_cache assert result["namespace"] == "all" +class TestTheStatsPayloadIsTheBackends: + """Against real caches: the endpoint reports what its backend reports, and nothing else. + + The routing cases above use doubles because what they pin down is *which* cache is reached. + The payload is a different question, and a double cannot answer it: a hand-written stats + dictionary is exactly what hid a 500 here for as long as the endpoint has existed. The two + backends report almost disjoint field sets -- a directory and an eviction policy against a + server version and a client count -- so both are constructed for real. + """ + + async def test_a_real_disk_cache_reports_its_own_fields( + self, cache_api: CacheManagementApi, mock_registry: MagicMock, tmp_path: Path + ) -> None: + cache = CacheBackendFactory.create(CacheConfig(cache_dir=str(tmp_path / "store")), enable_locking=False) + register(mock_registry, default=cache) + + result = await cache_api.get_cache_stats() + + assert set(result.model_dump(exclude_none=True)) == {"size", "cache_dir", "size_limit", "eviction_policy"} + assert result.eviction_policy == "least-recently-used" + + async def test_a_real_redis_cache_reports_a_different_shape_entirely( + self, cache_api: CacheManagementApi, mock_registry: MagicMock + ) -> None: + """None of the disk backend's fields, seven of its own -- and the endpoint keeps them. + + ``fakeredis`` answers every command the service issues except ``INFO``, which it does + not implement, so that one response is stubbed: the payload is still built by + ``RedisCacheService.get_stats`` from a server's answer, which is the part under test. + """ + server_info = {"redis_version": "7.2.4", "connected_clients": 3, "used_memory_human": "1.2M", "uptime_in_seconds": 99} + cache = RedisCacheService.__new__(RedisCacheService) + cache._client = fakeredis.FakeRedis(decode_responses=True) + cache._client.info = lambda: server_info + cache._key_prefix = "orders.sessions" + cache._safe_redis_url = "redis://fake:6379/0" + register(mock_registry, default=cache) + + result = await cache_api.get_cache_stats() + + reported = result.model_dump(exclude_none=True) + assert reported["backend"] == "redis" + assert reported["key_prefix"] == "orders.sessions" + assert reported["redis_version"] == "7.2.4" + assert not {"size", "cache_dir", "size_limit", "eviction_policy"} & set(reported) + cache._client.close() + + async def test_a_backend_that_cannot_report_answers_an_empty_payload( + self, cache_api: CacheManagementApi, mock_registry: MagicMock + ) -> None: + """``get_stats`` returns ``{}`` when its own call fails, and that is an answer, not a 500. + + Here the Redis server does not implement ``INFO`` -- which is what ``fakeredis`` really + does, so nothing is stubbed. The cache itself is working; only the statistics call + failed, and an empty payload says so without taking the endpoint down with it. + """ + cache = RedisCacheService.__new__(RedisCacheService) + cache._client = fakeredis.FakeRedis(decode_responses=True) + cache._key_prefix = "" + cache._safe_redis_url = "redis://fake:6379/0" + register(mock_registry, default=cache) + + result = await cache_api.get_cache_stats() + + assert result.model_dump(exclude_none=True) == {} + cache._client.close() + + class TestNamedCaches: async def test_stats_read_the_named_cache(self, cache_api: CacheManagementApi, mock_registry: MagicMock) -> None: default, sessions = cache_double(), cache_double() diff --git a/tests/unit/agents/services/TESTS.md b/tests/unit/agents/services/TESTS.md index a83e145e..c70976fa 100644 --- a/tests/unit/agents/services/TESTS.md +++ b/tests/unit/agents/services/TESTS.md @@ -12,7 +12,6 @@ Test coverage for `src/blueprint/agents/services/`. | `eventing/test_event_publishing_service.py` | `EventPublishingService` | `on_startup` wires client and config, `_get_pub_config` raises before startup, `get_topic_for_event_type` / `get_available_event_types`, `publish_event` (topic mapping, explicit topic override, missing mapping raises, sets default source, result shape), `publish_handler_event` (no mapping → skip, loop prevention → skip, normal → publishes), `publish_status_event` type format and delegation | | `infrastructure/test_disk_cache_service.py` | `DiskCacheService` | `set`/`get` (string/dict/list keys, namespace isolation), `delete` (return values), `exists` (before/after set/delete), `clear` (namespace-scoped and full), TTL expiration via mocked `time.time`, `hash` consistency for string/list/dict inputs, `list_namespaces`, `list_values` (content, TTL-entry exclusion, limit), `get_stats` field presence, lifecycle, context-manager protocol, an unwritable cache directory failing with a message that names the path and the options (and keeping the OSError as the cause); `claim` set-if-absent (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, keys and namespaces independent, dict keys hashed consistently, TTL recorded so readers see expiry, a logically expired claim taken over, no TTL never expires, and an unreachable cache failing open) | | `infrastructure/test_redis_cache_service.py` | `RedisCacheService` | Backed by `fakeredis`. `claim` via `SET NX EX` (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, the TTL is applied to the key, namespaces are independent, and an unreachable cache fails open). *The rest of this file's coverage predates this table and is not itemised here.* | -| `infrastructure/test_agent_scoped_cache.py` | `AgentScopedCache` | Per-agent isolation over one shared backend (same key and partition name kept apart, a neighbour's key reading as absent, the partition carrying the agent, `list_namespaces` stripped back, the default partition scoped, per-agent `delete` and `claim`); `clear` for one partition and for all of this agent's, never the neighbours'; the `close` refusal, the root-namespace refusal, not registering itself, stats naming the agent; and the six paths through a registry view (scoped for a namespace, raw at the root, one lens per view, different lenses per agent, named caches scoped, unknown name still raising) | | `infrastructure/test_cache_backend_factory.py`, `infrastructure/test_cache_sharing_via_registry.py`, `infrastructure/test_redis_url_utils.py` | `CacheBackendFactory`, registry cache sharing, Redis URL helpers | Present but not itemised in this table. | | `sessions/test_api_client.py` | `SessionsApiClient` | `on_startup` (valid config, missing config/base_url/api_key → ValueError), `on_shutdown` (closes client, no-op when uninitialised), `get_job_detail`/`start_job`/`complete_job`/`cancel_job` (URL shape, required headers, payload contents, uninitialised guard) | | `sessions/test_key_provider.py` | `SessionKeyProvider` | `on_startup` (initialises cache, reads source/env_var from config, missing config → ValueError), `on_shutdown` (clears cache, no-op when uninitialised), `get_session_key` (env hit/miss, config source, vault → NotImplementedError, remote source via respx — happy path/caching/404/missing session_id/missing URL, unknown source, cache-hit bypass, result cached after fetch), `invalidate_cache` (default and per-session key removal, no-op when empty/uninitialised) | diff --git a/tests/unit/agents/test_design_rules.py b/tests/unit/agents/test_design_rules.py new file mode 100644 index 00000000..e743b34a --- /dev/null +++ b/tests/unit/agents/test_design_rules.py @@ -0,0 +1,980 @@ +"""Guards for the design rules in ``AGENTS.md``, one section per rule. + +Prose has already failed once here: ``CLAUDE.md`` cited ``AGENTS.md`` for months while no such +file existed, and nothing noticed. A rule that lives only as a paragraph is a rule the next +feature can break without anyone seeing it, so every rule that can be checked mechanically is +checked here -- and **every failure message names the rule it enforces**, because someone who +hits one of these has not made an ordinary mistake in a test, they have crossed a design decision +and need to read the decision. + +What is guarded, in the order ``AGENTS.md`` states the rules: + +- *Collect, then wire* -- :class:`TestCollectThenWire` +- *One declaration surface* -- :class:`TestOneDeclarationSurface` +- *A lookup never falls back across agents* -- :class:`TestNoLookupFallsBackAcrossAgents` +- *A component never learns it is in a group* -- :class:`TestNothingEnumeratesTheProcess` +- *A name that crosses the process boundary is validated, never repaired* -- + :class:`TestNamesAreValidatedNeverRepaired` +- *There is no public read path to the unscoped loader* -- :class:`TestNoPublicPathToTheLoader` +- *Logging is configured by the application* -- :class:`TestLoggingIsConfiguredByTheApplication` +- *No diagnostics via print* -- :class:`TestNoDiagnosticsViaPrint` +- *A reference points at a file that exists* -- :class:`TestEveryReferenceResolves` + +The last one is what makes the rest durable: a rule recorded in a document nobody can reach is +back to being a paragraph. + +Rules that are deliberately **not** guarded here, so that their absence is not read as an +oversight: *a builder is single-use*, *group policy belongs to the collector*, *an empty +declaration means everything* and *a key whose absence changes behaviour is required* are +behaviours with their own suites (``app_builder/test_app_builder.py``, ``test_agent_group.py``, +``handler/``, ``config/``), and asserting them again here would give one rule two homes. *Isolation +is structural where it can be*, *probe against real objects* and *the spec wins on precedence, not +on correctness* cannot be checked by a machine at all. +""" + +import ast +import re +from collections.abc import Callable, Generator, Iterator +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock, patch + +import pytest +from pydantic import BaseModel + +from blueprint.agents.agent.agent_builder import AgentBuilder +from blueprint.agents.agent_group import AgentGroup +from blueprint.agents.app_builder import AppBuilder, Declaration +from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import namespace_scope, validate_namespace +from blueprint.agents.component.registry import Registry +from blueprint.agents.config import Config +from blueprint.agents.group_config import GroupConfig, GroupConfigError +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.io.api.actuators.health.health_base import HealthCheckerBase +from blueprint.agents.io.api.rest_api_base import RestApiBase +from blueprint.agents.io.api.scheduling.scheduler import SchedulerBase +from blueprint.agents.models.api import ComponentHealth +from blueprint.agents.models.events import GenericCloudEvent +from blueprint.agents.services.infrastructure.cache_backend_factory import CacheBackendFactory +from blueprint.agents.services.infrastructure.cache_service import CacheService +from blueprint.agents.services.service_base import ServiceBase + +REPO_ROOT = Path(__file__).resolve().parents[3] +"""The repository root, for the guards that read the tree rather than import it.""" + +FRAMEWORK = REPO_ROOT / "src" / "blueprint" / "agents" +"""The framework package: library code, which is where the rules about library code bind.""" + + +@pytest.fixture(autouse=True) +def reset_component_state() -> Generator[None]: + """Leave no shared configuration or registry behind, and need no correlation context. + + ``Component`` holds the configuration and the registry as class state, so a guard that + configures one would otherwise decide what the next one sees. Reset before as well as after, + because these guards assert on the *absence* of configuration. + """ + Component.reset_shared_state() + with patch( + "blueprint.agents.component.registry.CorrelationContextProvider.get_correlation_context", + return_value=MagicMock(), + ): + yield + Component.reset_shared_state() + + +# ---------------------------------------------------------------------------------------------- +# Stubs: concrete and minimal, so that every guard below calls a real builder with a real class. +# ---------------------------------------------------------------------------------------------- + + +class StubHandler(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + async def can_handle_event(self, event: GenericCloudEvent, context: dict) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict) -> None: + return None + + +class StubService(ServiceBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class StubApi(RestApiBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class StubScheduler(SchedulerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class StubChecker(HealthCheckerBase): + async def health_check(self) -> ComponentHealth: + return ComponentHealth(status="healthy", message="ok") + + +class StubResult(BaseModel): + answer: str + + +SampleCall = tuple[tuple[Any, ...], dict[str, Any]] + +APP_BUILDER_CALLS: dict[str, SampleCall] = { + "with_handler": ((StubHandler,), {"name": "a_handler"}), + "with_service": ((StubService,), {"name": "a_service"}), + "with_agent": ((AgentBuilder(runtime_name="a_runtime"),), {}), + "with_scheduler": ((StubScheduler,), {"name": "a_scheduler"}), + "with_rest_api": ((StubApi,), {"name": "an_api"}), + "with_cache": ((), {"name": "a_cache"}), + "with_health_checker": (("a_check", StubChecker()), {}), +} +"""One call per ``AppBuilder`` declaration method, as a project would write it. + +Keyword arguments are given where the method takes a name, because a name is the part replay is +most able to lose: ``with_health_checker`` takes it positionally and every other method takes it +as a keyword, and that irregularity lives in exactly one branch of ``Declaration.replay``. +""" + +AGENT_BUILDER_CALLS: dict[str, SampleCall] = { + "with_model_from_config": ((), {}), + "with_system_prompt": (("a_prompt",), {}), + "with_tools": (([],), {}), + "with_tool": (("a_tool", lambda: None), {}), + "with_result_type": ((StubResult,), {}), + "with_deps_type": ((dict,), {}), + "with_metrics": ((), {}), +} +"""The same for ``AgentBuilder``, which records fields rather than ``Declaration`` objects. + +*Collect, then wire* binds it just as hard: ``with_model_from_config`` is the method that used to +read the configuration while accumulating, and that one read is what forced an agent to be built +before its namespace existed. +""" + +BUILDERS: dict[str, tuple[Callable[[], Any], dict[str, SampleCall]]] = { + "AppBuilder": (AppBuilder, APP_BUILDER_CALLS), + "AgentBuilder": (lambda: AgentBuilder(runtime_name="a_runtime"), AGENT_BUILDER_CALLS), +} +"""Every declaration surface in the framework, with the calls that exercise it.""" + + +def declaration_methods(builder_class: Any) -> list[str]: + """Every public declaration method on a builder, discovered rather than listed. + + Discovered, so that a method added without a sample call fails this file instead of being + quietly untested. The ``with_`` prefix is what makes a method a declaration: ``host_agent`` + records no ``Declaration`` -- it states a fact about the process -- and is not one of these. + """ + return sorted(name for name in dir(builder_class) if name.startswith("with_")) + + +def surfaces() -> Iterator[tuple[str, str]]: + """Every ``(builder, method)`` pair the reflective guards run over.""" + for builder_name, (_factory, calls) in BUILDERS.items(): + for method in sorted(calls): + yield builder_name, method + + +def record(builder_name: str, method: str) -> tuple[Any, Any]: + """Make a fresh builder, record one declaration on it from the sample call, and return both.""" + factory, calls = BUILDERS[builder_name] + builder = factory() + arguments, keywords = calls[method] + return builder, getattr(builder, method)(*arguments, **keywords) + + +def registry_contents() -> dict[str, object]: + """Every component in the shared registry, or nothing when there is not even a registry yet. + + Read through ``_components`` because there is no public "list everything" method, and there + should not be: an agent that can enumerate the process can be written to depend on it. + """ + registry = Component.shared_registry + return dict(registry._components) if registry is not None else {} + + +class TestCollectThenWire: + """**Collect, then wire.** A declaration API records; nothing is constructed until ``build()``. + + *Failure it prevents:* a component constructed while declarations are still being collected + exists before any namespace does, so it belongs to the root for ever -- which is what forced + a second builder class to exist for three phases. + """ + + @pytest.mark.parametrize(("builder_name", "method"), list(surfaces())) + def test_recording_a_declaration_constructs_nothing(self, builder_name: str, method: str) -> None: + before = registry_contents() + + record(builder_name, method) + + assert registry_contents() == before, ( + f"{builder_name}.{method}() put something in the registry while declarations were still being collected. " + "Collect, then wire: a component built during accumulation exists before any namespace does and belongs " + "to the root for ever. Record the call, and construct it in build()." + ) + + @pytest.mark.parametrize(("builder_name", "method"), list(surfaces())) + def test_recording_a_declaration_needs_no_configuration(self, builder_name: str, method: str) -> None: + """No configuration is linked here at all, and every declaration must still record. + + The sharper half of the rule: a ``with_*`` that reads a key cannot run before the + configuration exists, and the configuration does not exist until ``build()`` is handed + one. ``with_model_from_config`` used to read here, and that is why an agent had to be + built during accumulation. + """ + assert not Component.has_config() + + record(builder_name, method) + + assert not Component.has_config(), ( + f"{builder_name}.{method}() linked a configuration while recording. Configuration is injected at " + "build(), not while declarations are collected." + ) + + @pytest.mark.parametrize(("builder_name", "method"), list(surfaces())) + def test_a_declaration_returns_the_builder(self, builder_name: str, method: str) -> None: + """The fluent contract: a project chains these, so anything else breaks its ``main.py``.""" + builder, returned = record(builder_name, method) + + assert returned is builder, f"{builder_name}.{method}() must return the builder, so that declarations chain." + + +class TestOneDeclarationSurface: + """**One declaration surface.** Adding a capability is one edit: a ``with_*`` on ``AppBuilder``. + + A group still has to move a recorded call from one builder to another, and + ``Declaration.replay`` does that by resolving ``with_`` with ``getattr``. So there are + exactly two ways for the recorder and the API to part company: + + - a ``with_*`` records a ``kind`` that no method answers to, and replay dies with an + ``AttributeError`` at assembly -- in a group, never standalone; + - a ``with_*`` whose replayed arguments do not reproduce the call, so an agent is assembled + from a declaration that says something slightly different from what its ``main.py`` said. + + Neither is visible in a single-agent application, and both would be found in production by + somebody grouping two agents. + + *Failure it prevents:* four places to edit, three of which fail **silently** -- the capability + is simply absent from that deployment shape, and only in the one nobody tested. + """ + + def test_the_sample_calls_name_every_declaration_method(self) -> None: + missing = set(declaration_methods(AppBuilder)) - set(APP_BUILDER_CALLS) + assert not missing, ( + f"{', '.join(sorted(missing))} is a declaration method with no sample call in this file. Add one: the " + "list is what proves a new with_* was checked against the group's replay, which is the only place a " + "recorder and its API can drift apart." + ) + + def test_the_sample_calls_name_nothing_that_is_gone(self) -> None: + extra = set(APP_BUILDER_CALLS) - set(declaration_methods(AppBuilder)) + assert not extra, f"{', '.join(sorted(extra))} no longer exists on AppBuilder; remove the sample call." + + def test_the_agent_sample_calls_name_every_declaration_method(self) -> None: + missing = set(declaration_methods(AgentBuilder)) - set(AGENT_BUILDER_CALLS) + assert not missing, ( + f"{', '.join(sorted(missing))} is an AgentBuilder declaration method with no sample call in this file. " + "Add one: collect-then-wire is asserted reflectively, so an unlisted method is an unchecked one." + ) + + def test_the_agent_sample_calls_name_nothing_that_is_gone(self) -> None: + extra = set(AGENT_BUILDER_CALLS) - set(declaration_methods(AgentBuilder)) + assert not extra, f"{', '.join(sorted(extra))} no longer exists on AgentBuilder; remove the sample call." + + @pytest.mark.parametrize("method", sorted(APP_BUILDER_CALLS)) + def test_the_call_records_exactly_one_declaration(self, method: str) -> None: + builder, _ = record("AppBuilder", method) + + assert len(builder.declarations) == 1 + + @pytest.mark.parametrize("method", sorted(APP_BUILDER_CALLS)) + def test_the_recorded_kind_has_a_method_to_replay_onto(self, method: str) -> None: + """``Declaration.replay`` resolves ``with_`` with getattr, and this is that contract.""" + builder, _ = record("AppBuilder", method) + + for declaration in builder.declarations: + assert hasattr(AppBuilder, f"with_{declaration.kind}"), ( + f"{method}() records kind '{declaration.kind}', but there is no with_{declaration.kind}() for " + "Declaration.replay to call. A group would fail at assembly with an AttributeError while the same " + "declaration went on working standalone." + ) + + @pytest.mark.parametrize("method", sorted(APP_BUILDER_CALLS)) + def test_replay_reproduces_the_declaration(self, method: str) -> None: + """What a group does to move an agent's calls onto the root builder, and it must be lossless.""" + source, _ = record("AppBuilder", method) + + target = AppBuilder() + for declaration in source.declarations: + declaration.replay(target) + + assert target.declarations == source.declarations, ( + f"replaying {method}() onto another builder did not reproduce the declaration. A grouped agent would " + "then be assembled from something other than what its main.py declared." + ) + + @pytest.mark.parametrize("method", sorted(APP_BUILDER_CALLS)) + def test_replay_takes_the_namespace_from_the_scope_it_runs_in(self, method: str) -> None: + """The ambient mechanism: no namespace is passed, and none appears in any signature.""" + source, _ = record("AppBuilder", method) + + target = AppBuilder() + with namespace_scope("orders"): + for declaration in source.declarations: + declaration.replay(target) + + assert [entry.namespace for entry in target.declarations] == ["orders"] + assert [entry.namespace for entry in source.declarations] == [""] + + def test_a_replayed_checker_keeps_its_positional_name(self) -> None: + """``with_health_checker(name, checker)`` is the one method whose name is positional.""" + checker = StubChecker() + source = AppBuilder().with_health_checker("db", checker) + + target = AppBuilder() + for declaration in source.declarations: + declaration.replay(target) + + recorded = target.declarations[0] + assert (recorded.name, recorded.target) == ("db", checker) + + def test_a_replayed_declaration_keeps_its_name_override(self) -> None: + source = AppBuilder().with_service(StubService, name="planner") + + target = AppBuilder() + for declaration in source.declarations: + declaration.replay(target) + + assert target.declarations[0].name == "planner" + + def test_a_replayed_declaration_keeps_its_constructor_arguments(self) -> None: + source = AppBuilder().with_cache(True, False, name="sessions") + + target = AppBuilder() + for declaration in source.declarations: + declaration.replay(target) + + assert target.declarations[0] == Declaration( + kind="cache", target=None, name="sessions", namespace="", kwargs={"enable_locking": False} + ) + + +# ---------------------------------------------------------------------------------------------- +# Isolation: what one agent can reach, and what it must not. +# ---------------------------------------------------------------------------------------------- + + +@pytest.fixture +def registry() -> Registry: + """The application's own registry -- the real one, not a mock. + + A mock registry hides resolution bugs by construction, and resolution is the whole subject + of the guards that use it. + """ + return Registry(Component) + + +@pytest.fixture +def config(tmp_path: Path) -> Config: + """A real configuration with a root and two agents, loaded from a real settings file.""" + settings = tmp_path / "settings.toml" + settings.write_text( + '[development]\napp_environment = "development"\napp_name = "the-process"\napp_port = 8000\n' + 'model_name = "root-model"\n\n' + '[development.orders]\nmodel_name = "orders-model"\n\n' + '[development.billing]\nmodel_name = "billing-model"\n' + ) + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + +class TestNoLookupFallsBackAcrossAgents: + """**A lookup never falls back across agents.** Caches do not resolve outside the declaring agent. + + *Failure it prevents:* two agents that both asked for ``sessions`` silently share one store, + and only in production -- a single-agent test suite cannot see it, because there is no + neighbour to collide with. + """ + + def test_two_agents_declaring_one_name_get_two_stores(self, registry: Registry) -> None: + orders_cache = MagicMock(spec=CacheService) + billing_cache = MagicMock(spec=CacheService) + + registry.add_cache("sessions", orders_cache, namespace="orders") + registry.add_cache("sessions", billing_cache, namespace="billing") + + assert registry.get_cache("sessions", namespace="orders") is orders_cache + assert registry.get_cache("sessions", namespace="billing") is billing_cache + + def test_an_agent_cannot_reach_a_neighbours_cache(self, registry: Registry) -> None: + registry.add_cache("sessions", MagicMock(spec=CacheService), namespace="billing") + + with pytest.raises(ValueError, match="No cache registered as 'sessions' for agent 'orders'"): + registry.for_namespace("orders").get_cache("sessions") + + def test_an_unknown_name_is_an_error_not_the_default_cache(self, registry: Registry) -> None: + """The second fallback that does not exist: an unknown name never becomes the default.""" + registry.add_cache("default", MagicMock(spec=CacheService), namespace="orders") + + with pytest.raises(ValueError, match="No cache registered as 'sessions'"): + registry.for_namespace("orders").get_cache("sessions") + + def test_an_agent_cannot_fall_back_to_the_roots_cache(self, registry: Registry) -> None: + """Components resolve namespace-then-root; caches deliberately do not.""" + registry.add_cache("sessions", MagicMock(spec=CacheService)) + + with pytest.raises(ValueError, match="No cache registered as 'sessions' for agent 'orders'"): + registry.for_namespace("orders").get_cache("sessions") + + +class TestNothingEnumeratesTheProcess: + """**A component never learns it is in a group.** The namespace is ambient and not enumerable. + + *Failure it prevents:* an agent that can read its neighbours can be written to depend on + them, and regrouping then breaks it in production. + """ + + def test_a_component_takes_its_namespace_from_the_scope_in_force(self) -> None: + """The ambient mechanism, and the reason no project component has a namespace parameter.""" + Component.init_registry(Registry(Component)) + + with namespace_scope("orders"): + service = StubService() + + assert service.namespace == "orders" + + def test_no_agent_can_enumerate_the_namespaces_in_the_process(self) -> None: + for subject in (Registry, Component, Config): + assert not hasattr(subject, "get_known_namespaces"), ( + f"{subject.__name__}.get_known_namespaces exists. Nothing a component can reach may enumerate the " + "process: an agent that can list its neighbours can be written to depend on them. One endpoint per " + "agent needs no such list, and assembly reads the group from the group, not from the registry." + ) + + def test_a_registry_view_cannot_list_every_cache_in_the_process(self, registry: Registry) -> None: + """``cache_entries`` is for the code that builds the process, not for code living in it.""" + with pytest.raises(RuntimeError, match="asked for every cache in the process"): + registry.for_namespace("orders").cache_entries() + + def test_a_configuration_view_cannot_make_another_agents_view(self, config: Config) -> None: + with pytest.raises(RuntimeError, match="Views are created from the application's configuration"): + config.for_namespace("orders").for_namespace("billing") + + +class TestNoPublicPathToTheLoader: + """**Configuration is read through the component's own scoped view.** + + *Failure it prevents:* a component reads a neighbour's or the process's value under a name + that means "mine", and the bug appears only once a second agent exists. + """ + + def test_the_public_configuration_surface_is_exactly_three_names(self) -> None: + """A new public accessor has to be added to this list, which is where it gets argued. + + ``config`` is the read path and returns a view; ``configure`` and ``has_config`` are the + application's injection point. Anything else public that hands out configuration is a + second read path, and the class-level accessor that existed before this feature was + deleted for exactly that reason. + """ + on_component = {name for name in dir(Component) if "config" in name.lower() and not name.startswith("_")} + on_metaclass = {name for name in dir(type(Component)) if "config" in name.lower() and not name.startswith("_")} + + assert on_component | on_metaclass == {"config", "configure", "has_config"}, ( + "the public configuration surface of Component changed. There is no public read path to the unscoped " + "loader: config is a view, configure and has_config are the application's injection point. A new public " + "accessor is a second read path, and a component reading the unscoped tree reads a neighbour's value " + "under a name that means 'mine'." + ) + + def test_no_public_attribute_hands_out_the_loader(self, config: Config) -> None: + Component.configure(config) + + exposed = [ + name + for subject in (Component, type(Component)) + for name in dir(subject) + if not name.startswith("_") and getattr(subject, name, None) is config + ] + + assert not exposed, f"{', '.join(exposed)} hands out the application's own configuration object." + + def test_a_namespaced_component_reads_through_its_own_view(self, config: Config) -> None: + Component.configure(config) + Component.init_registry(Registry(Component)) + + with namespace_scope("orders"): + service = StubService() + + assert service.config.is_view + assert service.config.agent_scope == "orders" + assert service.config.get("model_name") == "orders-model" + + def test_a_root_component_reads_the_configuration_itself(self, config: Config) -> None: + """The documented exception, asserted so that it stays an exception and not a habit. + + The root namespace *is* the unscoped configuration, so a root component gets the object + itself. That is what keeps every existing single-agent application reading what it read + before; it is not a hole, because a root component has no neighbour to read from. + """ + Component.configure(config) + Component.init_registry(Registry(Component)) + + assert StubService().config is config + + +# ---------------------------------------------------------------------------------------------- +# Names that leave the process. +# ---------------------------------------------------------------------------------------------- + + +def group_with_agent(name: str) -> Callable[[], None]: + """A group literally declaring one agent under ``name``.""" + + def declare() -> None: + AgentGroup("a_group", {name: AppBuilder()}) + + return declare + + +def group_config_with_agent(name: str, tmp_path: Path, config: Config) -> Callable[[], None]: + """The deployment route to the same name: an agent map and a group naming it.""" + (tmp_path / "agents.toml").write_text(f'[agents."{name}"]\nmodule = "a.module:declaration"\n') + + def resolve() -> None: + GroupConfig.resolve(config, environ={"BLUEPRINT_AGENTS": name}) + + return resolve + + +NAMESPACE_ENTRY_POINTS: dict[str, Callable[[str], Callable[[], Any]]] = { + "validate_namespace": lambda name: lambda: validate_namespace(name), + "namespace_scope": lambda name: lambda: namespace_scope(name).__enter__(), + "Component(namespace=)": lambda name: lambda: StubService(namespace=name), + "AppBuilder.host_agent": lambda name: lambda: AppBuilder().host_agent(name), + "AgentGroup": group_with_agent, +} +"""Every way a namespace enters the framework, keyed by how the failure should read. + +The namespace becomes a registry key prefix, a NATS queue group, part of a JetStream durable and +a telemetry service name. Four consumers, four different repairs -- so one repaired value is four +names for one agent, which is why every one of these refuses instead. +""" + +ILLEGAL_NAMESPACES = ["Orders", "orders-eu", " orders ", "1st", "orders.eu", "orders/eu", "orders>eu"] +"""Each one legal to some consumer and fatal to another. ``-`` is the durable-name separator.""" + + +class TestNamesAreValidatedNeverRepaired: + """**A name that crosses the process boundary is validated, never repaired.** + + *Failure it prevents:* silent rewriting breaks an external dependency with nothing in the + logs to debug. A namespace lower-cased for the filesystem is one agent under two names, one + in the registry and another on the broker; nothing reports the second. + """ + + @pytest.mark.parametrize("entry_point", sorted(NAMESPACE_ENTRY_POINTS)) + @pytest.mark.parametrize("name", ILLEGAL_NAMESPACES) + def test_an_illegal_namespace_is_refused(self, entry_point: str, name: str) -> None: + Component.init_registry(Registry(Component)) + + with pytest.raises(ValueError) as refusal: + NAMESPACE_ENTRY_POINTS[entry_point](name)() + + assert name.strip() in str(refusal.value) or repr(name) in str(refusal.value), ( + f"{entry_point} refused {name!r} without naming it. A name that crosses the process boundary is " + "validated, never repaired -- and the refusal has to say which value, because the author sees only " + "the value they wrote." + ) + + @pytest.mark.parametrize("name", [name for name in ILLEGAL_NAMESPACES if name == name.strip()] + [" Orders "]) + def test_the_deployment_route_refuses_the_same_names(self, name: str, tmp_path: Path, config: Config) -> None: + """Same alphabet from the group file, so a typo fails at startup instead of inside a constructor. + + The agent list is a list -- a comma-separated environment variable, or a YAML sequence -- + and both routes strip each element before validating it. That is list parsing, not name + repair: ``BLUEPRINT_AGENTS="orders, billing"`` has to work, and the whitespace belongs to + the separator rather than to either name. So the padded-only case is excluded here and + ``" Orders "`` takes its place: the element is trimmed, and then held to the alphabet + exactly like any other, which is what keeps the trim from becoming a general repair. + """ + with pytest.raises(GroupConfigError, match="cannot be a namespace"): + group_config_with_agent(name, tmp_path, config)() + + @pytest.mark.parametrize("name", ["orders", "orders_eu", "a", "a1"]) + def test_a_legal_namespace_comes_back_unchanged(self, name: str) -> None: + assert validate_namespace(name) == name + + @pytest.mark.parametrize("name", ["Sessions", "../evil", "a b", "_leading", "a/b"]) + def test_an_illegal_cache_name_is_refused(self, name: str) -> None: + """A cache name becomes a directory and a Redis key prefix, so a repair writes elsewhere.""" + with pytest.raises(ValueError, match="not a legal cache name"): + CacheBackendFactory.validate_name(name) + + @pytest.mark.parametrize("name", ["Sessions", "../evil"]) + def test_an_illegal_cache_name_is_refused_where_it_is_declared(self, name: str) -> None: + """At the ``with_cache`` call, not at ``build()``: a check answerable at the call stays there.""" + with pytest.raises(ValueError, match="not a legal cache name"): + AppBuilder().with_cache(name=name) + + +# ---------------------------------------------------------------------------------------------- +# The two rules that are about the source tree rather than about its behaviour. Both read the +# files and parse them, because both failures are invisible at runtime: import-time logging +# configuration works perfectly until an application disagrees with it, and a print goes to a +# stream nobody collects. +# ---------------------------------------------------------------------------------------------- + +LOGGING_CONFIGURATION_CALLS = frozenset({"basicConfig", "dictConfig", "fileConfig", "addHandler", "setFormatter", "addFilter", "setLevel"}) +"""Calls that configure logging rather than emit a record: handlers, formatters, filters, levels.""" + +LOGGING_OWNER = FRAMEWORK / "config" / "custom_logging.py" +"""``LoggingManager``: the one place in the framework allowed to configure logging, once, for the +application that asked it to.""" + +ALLOWED_PRINTS = { + FRAMEWORK / "entrypoint.py": "a group that cannot start must say so on stderr, before AppBuilder configures logging", + LOGGING_OWNER: "the fallback for a failure of logging configuration itself, which cannot be logged", +} +"""The framework's two deliberate writes to stderr, with the reason each one cannot be a log call. + +Both happen where no logging configuration can be relied on. Anything else is a diagnostic, and a +diagnostic that bypasses the logger cannot be silenced, levelled or formatted by the application +carrying it. +""" + + +def python_files(root: Path) -> list[Path]: + """Every Python module under ``root``, excluding the caches.""" + return sorted(path for path in root.rglob("*.py") if "__pycache__" not in path.parts) + + +def calls_in(path: Path, wanted: Callable[[ast.Call], str | None]) -> list[tuple[int, str, bool]]: + """Return ``(line, what, at_import_time)`` for every call in ``path`` that ``wanted`` names. + + ``at_import_time`` is what distinguishes a rule violation from a legitimate entry point: a + call inside a function runs when the application calls it, and the same call at module level + runs for anyone who so much as imports the module. + """ + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + inside_function: set[ast.AST] = set() + for node in ast.walk(tree): + if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda): + for descendant in ast.walk(node): + inside_function.add(descendant) + + found = [] + for node in ast.walk(tree): + if isinstance(node, ast.Call) and (what := wanted(node)) is not None: + found.append((node.lineno, what, node not in inside_function)) + return found + + +def logging_configuration(node: ast.Call) -> str | None: + """Name the logging-configuration call this node makes, if it makes one.""" + if isinstance(node.func, ast.Attribute) and node.func.attr in LOGGING_CONFIGURATION_CALLS: + return node.func.attr + return None + + +def print_call(node: ast.Call) -> str | None: + """Name a call to the builtin ``print``, if that is what this node is.""" + if isinstance(node.func, ast.Name) and node.func.id == "print": + return "print" + return None + + +class TestLoggingIsConfiguredByTheApplication: + """**Logging is configured by the application**, never by library code or at import time. + + *Failure it prevents:* whoever loads first decides the whole process's logging. An + import-time ``basicConfig`` installs a root handler, and every later configuration -- the + application's own, or a CLI's ``--verbose`` -- then finds the root already configured and + does nothing. The symptom is a flag that has no effect, with nothing to point at. + """ + + @pytest.mark.parametrize("path", python_files(REPO_ROOT / "src"), ids=lambda path: str(path.relative_to(REPO_ROOT))) + def test_no_module_configures_logging_at_import_time(self, path: Path) -> None: + at_import_time = [(line, what) for line, what, import_time in calls_in(path, logging_configuration) if import_time] + + assert not at_import_time, ( + f"{path.relative_to(REPO_ROOT)} configures logging at import time: " + f"{', '.join(f'{what}() on line {line}' for line, what in at_import_time)}. Logging is configured by the " + "application, and importing a module is not the application deciding anything -- the root logger is " + "configured by whoever imports first, and every later configuration silently does nothing." + ) + + @pytest.mark.parametrize( + "path", [path for path in python_files(FRAMEWORK) if path != LOGGING_OWNER], ids=lambda path: str(path.relative_to(REPO_ROOT)) + ) + def test_only_the_logging_manager_configures_logging(self, path: Path) -> None: + """Inside the framework, which is library code from end to end, there is one owner.""" + configuration = calls_in(path, logging_configuration) + + assert not configuration, ( + f"{path.relative_to(REPO_ROOT)} configures logging: " + f"{', '.join(f'{what}() on line {line}' for line, what, _ in configuration)}. The framework is library " + "code: it emits through getLogger(__name__) and configures nothing. LoggingManager is the one owner, " + "driven by the application's log_level, log_format and suppress_noisy_loggers." + ) + + +class TestNoDiagnosticsViaPrint: + """**No diagnostics via print.** The framework emits through a logger. + + *Failure it prevents:* output the application cannot silence, level, format or route, in a + container where stdout is the log stream. Two writes to stderr survive, both from before + logging configuration can be relied on, and both are listed with their reason. + + Scope is the framework. ``src/blueprint/agent_generator`` is a command-line tool whose + standard output is its interface to the developer running it, not a diagnostic channel. + """ + + @pytest.mark.parametrize( + "path", [path for path in python_files(FRAMEWORK) if path not in ALLOWED_PRINTS], ids=lambda path: str(path.relative_to(REPO_ROOT)) + ) + def test_the_framework_prints_nothing(self, path: Path) -> None: + prints = calls_in(path, print_call) + + assert not prints, ( + f"{path.relative_to(REPO_ROOT)} prints on line(s) {', '.join(str(line) for line, _, _ in prints)}. Use " + "getLogger(__name__): print() bypasses the logging infrastructure, so the application cannot silence, " + "level or format it, and in a container it lands in the log stream unstructured." + ) + + @pytest.mark.parametrize("path", sorted(ALLOWED_PRINTS), ids=lambda path: str(path.relative_to(REPO_ROOT))) + def test_every_allowed_print_still_writes_to_stderr(self, path: Path) -> None: + """The allowance is for a message that cannot be logged, and it goes where errors go.""" + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + calls = [node for node in ast.walk(tree) if isinstance(node, ast.Call) and print_call(node)] + assert calls, f"{path.relative_to(REPO_ROOT)} no longer prints; remove it from ALLOWED_PRINTS." + + for node in calls: + streams = [keyword.value for keyword in node.keywords if keyword.arg == "file"] + rendered = [ast.unparse(stream) for stream in streams] + assert rendered == ["sys.stderr"], ( + f"{path.relative_to(REPO_ROOT)} line {node.lineno} prints to {rendered or 'stdout'}. The two " + f"allowed prints exist because {ALLOWED_PRINTS[path]}, and a message that replaces a log record " + "belongs on stderr." + ) + + +# ---------------------------------------------------------------------------------------------- +# References. The guard that would have caught AGENTS.md, and the reason the rest of this file +# stays findable. +# ---------------------------------------------------------------------------------------------- + +LINK = re.compile(r"\]\(\s*([^)\s]+)") +"""Every markdown link target, whatever its text. Written to match the ``](target)`` half so that +a nested form -- a badge image inside a link -- is read rather than skipped.""" + +TICKED = re.compile(r"`([^`\n]+)`") +"""Backticked spans: how this repository cites a file when it is not making a link of it.""" + +REFERENCE_SUFFIXES = frozenset({".md", ".py", ".toml", ".yaml", ".yml", ".json", ".cfg", ".ini", ".txt", ".sh"}) +"""Suffixes that make a backticked token a file reference rather than an expression.""" + +SEARCH_ROOTS = ("", "src/blueprint/agents", "tests/unit/agents") +"""Where a relative reference is looked for, besides the citing document's own directory. + +This repository writes paths relative to the tree under discussion -- ``component/namespace.py`` +means the framework package, ``app_builder/test_app_builder.py`` means the unit tests -- so those +two trees are roots as well as the repository itself. +""" + +HISTORICAL_DOCUMENTS = ("docs/plans", "docs/specs", "CHANGELOG.md") +"""Documents that record what was decided and what was done, at the time it was done. + +They name files that have since been deleted, and proposals name files not yet written; both are +correct in a record. Their **links** are still checked -- a link is an invitation to click -- but +their citations are not held to the tree as it stands today. +""" + +PROJECT_FACING_DOCUMENTS = ("docs/guides", "docs/getting-started.md", "src/blueprint/agent_generator") +"""Documents that describe the reader's generated project -- ``src/main.py``, ``settings.toml`` -- +rather than this repository. The paths in them resolve in a project this tool creates.""" + +EXCLUDED_FROM_THE_REPOSITORY = ("docs/adr", "CLAUDE.local.md") +"""Present in a working copy but not part of the repository: ADRs are authored and owned outside +it, and ``CLAUDE.local.md`` is one developer's machine. Neither is scanned, so that this guard +gives the same answer everywhere.""" + +KNOWN_GAPS: dict[tuple[str, str], str] = { + ("README.md", "LICENSE"): ( + "README states the MIT licence and pyproject.toml carries the MIT classifier, but no LICENSE file has ever " + "been committed. Adding one is a legal artefact and a human decision, not a documentation fix." + ), +} +"""References that are known not to resolve, each with why it has not been fixed. + +Listed rather than silently tolerated, and held to being genuinely broken by +:meth:`TestEveryReferenceResolves.test_no_known_gap_has_quietly_been_fixed` -- an allowlist that +outlives its entries is how a guard stops guarding. +""" + + +def strip_code(text: str) -> str: + """Drop fenced code blocks, whose contents are code rather than references.""" + kept, inside = [], False + for line in text.splitlines(): + if line.lstrip().startswith(("```", "~~~")): + inside = not inside + continue + kept.append("" if inside else line) + return "\n".join(kept) + + +def all_markdown() -> Iterator[Path]: + """Every markdown file present, ignoring the dot directories and the vendored trees.""" + for path in REPO_ROOT.rglob("*.md"): + parts = path.relative_to(REPO_ROOT).parts + if not any(part.startswith(".") or part in {"node_modules", "__pycache__"} for part in parts): + yield path + + +def markdown_documents() -> list[Path]: + """Every markdown document this guard reads, in a stable order.""" + excluded = {(REPO_ROOT / part) for part in EXCLUDED_FROM_THE_REPOSITORY} + return sorted(path for path in all_markdown() if not any(path == item or item in path.parents for item in excluded)) + + +def every_markdown_name() -> set[str]: + """The file name of every markdown document present, scanned or not. + + Wider than :func:`markdown_documents` on purpose: a document cited by name exists if a file + of that name is here, whether or not this guard reads it. An ADR is owned outside the + repository and is not scanned, but citing one is not a dead pointer. + """ + return {path.name for path in all_markdown()} + + +def document_id(path: Path) -> str: + return path.relative_to(REPO_ROOT).as_posix() + + +def is_a(path: Path, group: tuple[str, ...]) -> bool: + return document_id(path).startswith(group) + + +def resolves(token: str, origin: Path) -> bool: + """Whether ``token``, cited in ``origin``, names a file that exists.""" + if (origin.parent / token).exists(): + return True + return any((REPO_ROOT / root / token).exists() for root in SEARCH_ROOTS) + + +def link_targets(text: str) -> Iterator[str]: + """Every link target that names a file in this repository.""" + for raw in LINK.findall(strip_code(text)): + target = raw.strip("<>").split("#")[0] + if not target or re.match(r"^[A-Za-z][A-Za-z0-9+.-]*:", target): + continue + yield target.lstrip("/") + + +def cited_paths(text: str) -> Iterator[str]: + """Every backticked token that names a file: a path, or a document by name.""" + for raw in TICKED.findall(strip_code(text)): + token = raw.strip().split(":")[0] + if not token or " " in token or "<" in token or "..." in token: + continue + if Path(token).suffix not in REFERENCE_SUFFIXES: + continue + if "/" not in token and not token.endswith(".md"): + continue + yield token + + +class TestEveryReferenceResolves: + """**A reference points at a file that exists.** + + *Failure it prevents:* the one this file exists because of. ``CLAUDE.md`` said "see + ``AGENTS.md``" for months, another document quoted what that file "states", and no such file + had ever been committed -- it was cited into existence. A rule recorded in a document nobody + can reach is back to being a paragraph, so this is what makes the rest of this file durable. + + A bare document name is checked everywhere, because that is the form the ``AGENTS.md`` case + took. Path citations are checked in the documents that describe this repository as it stands; + see :data:`HISTORICAL_DOCUMENTS` and :data:`PROJECT_FACING_DOCUMENTS` for the two kinds that + are not, and why. + """ + + @pytest.mark.parametrize("document", markdown_documents(), ids=document_id) + def test_every_link_resolves(self, document: Path) -> None: + broken = [ + target + for target in link_targets(document.read_text(encoding="utf-8")) + if not resolves(target, document) and (document_id(document), target) not in KNOWN_GAPS + ] + + assert not broken, ( + f"{document_id(document)} links to {', '.join(sorted(set(broken)))}, which does not exist. A reference " + "points at a file that exists: AGENTS.md was cited for months without existing, and a rule recorded in " + "a document nobody can reach is not recorded." + ) + + @pytest.mark.parametrize( + "document", + [path for path in markdown_documents() if not is_a(path, HISTORICAL_DOCUMENTS) and not is_a(path, PROJECT_FACING_DOCUMENTS)], + ids=document_id, + ) + def test_every_cited_path_resolves(self, document: Path) -> None: + broken = [ + token + for token in cited_paths(document.read_text(encoding="utf-8")) + if not resolves(token, document) and (document_id(document), token) not in KNOWN_GAPS + ] + + assert not broken, ( + f"{document_id(document)} cites {', '.join(sorted(set(broken)))}, which does not exist. Either the file " + "moved and the citation did not, or the citation named a file that was never written -- which is exactly " + "how AGENTS.md came to be cited for months without existing." + ) + + @pytest.mark.parametrize("document", [path for path in markdown_documents() if not is_a(path, HISTORICAL_DOCUMENTS)], ids=document_id) + def test_a_document_cited_by_name_exists_somewhere(self, document: Path) -> None: + """The ``AGENTS.md`` case itself: a document pointed at by name has to be a document. + + A bare ``FOO.md`` in backticks is a pointer to a document, not a path relative to + anything, so it is satisfied by a file of that name anywhere in the repository -- + including the files this guard does not itself scan, since existing and being scanned are + different questions. + + Not run over the records, for the reason a record exists: a proposal names the documents + it intends to write, and the alternatives it rejected, and both would fail here. The + citation that motivated this check was in ``CLAUDE.md``, which is not a record. + """ + names = {name for name in (Path(token).name for token in cited_paths(document.read_text(encoding="utf-8"))) if name.endswith(".md")} + known = every_markdown_name() + missing = sorted(name for name in names - known if (document_id(document), name) not in KNOWN_GAPS) + + assert not missing, ( + f"{document_id(document)} cites the document(s) {', '.join(missing)}, which do not exist anywhere in " + "the repository. Write them, or stop pointing at them: AGENTS.md spent months being cited into " + "existence, and docs/plans/2026-06-10-sessions-job-handler.md went as far as quoting what it 'states'." + ) + + @pytest.mark.parametrize(("where", "reason"), sorted(KNOWN_GAPS.items())) + def test_no_known_gap_has_quietly_been_fixed(self, where: tuple[str, str], reason: str) -> None: + """An allowlist that outlives its entries is how a guard stops guarding.""" + document, token = where + complaint = f"{document} now resolves '{token}', so remove it from KNOWN_GAPS. It was listed because: {reason}" + + assert not resolves(token, REPO_ROOT / document), complaint From f07c97d728566314bef7789808af5a63c62cc21e Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:44:57 +0200 Subject: [PATCH 013/133] feat(observability): give each agent its own identity, probe and alarm Phase 9. Spans from namespace invoice carry service.name = "invoice" (C2); a degraded namespace reports liveness UP, readiness per policy and blueprint_namespace_up = 0 with its consumers stopped (C3, C4); every path that stops a namespace serving emits an ERROR carrying that namespace's identity (C7). Adds blueprint.scheduler.tick_age_seconds and blueprint.events.dead_lettered. Co-Authored-By: Claude Opus 5 (1M context) --- AGENTS.md | 16 + docs/concepts/observability.md | 451 ++++++++++-------- docs/guides/testing.md | 13 +- ...26-08-28-multi-agent-grouping-changelog.md | 422 +++++++++++++++- docs/plans/2026-08-28-multi-agent-grouping.md | 2 +- docs/specs/2026-08-28-multi-agent-grouping.md | 6 +- src/blueprint/agents/agent_group.py | 29 +- src/blueprint/agents/app_builder.py | 218 ++++++--- .../agents/clients/io/dapr_client.py | 10 +- .../agents/clients/io/io_client_base.py | 35 ++ .../agents/clients/io/nats_client.py | 174 +++++-- src/blueprint/agents/component/component.py | 28 +- src/blueprint/agents/config/config.py | 5 +- src/blueprint/agents/deployment.py | 67 +++ .../agents/io/api/actuators/actuator_api.py | 72 ++- .../io/api/actuators/health/health_cache.py | 77 ++- .../actuators/health/namespace_supervisor.py | 224 +++++++++ .../api/actuators/health/readiness_policy.py | 101 ++++ src/blueprint/agents/io/api/eventing/dapr.py | 26 + .../agents/io/api/eventing/sessions_bus.py | 29 +- .../agents/io/api/scheduling/scheduler.py | 64 ++- src/blueprint/agents/io/telemetry/inflight.py | 94 ++++ .../agents/io/telemetry/loop_watchdog.py | 159 ++++++ .../agents/io/telemetry/providers.py | 98 ++++ .../agents/io/telemetry/telemetry.py | 146 +++++- src/blueprint/agents/models/api.py | 38 ++ .../eventing/event_processing_service.py | 14 +- .../test_startup_failure_policy.py | 149 ++++++ .../agents/clients/io/test_nats_client.py | 88 +++- tests/unit/agents/component/test_component.py | 17 + .../api/actuators/health/test_health_cache.py | 81 ++++ .../health/test_namespace_supervisor.py | 133 ++++++ .../actuators/health/test_readiness_policy.py | 65 +++ .../io/api/actuators/test_actuator_api.py | 46 +- .../io/api/eventing/test_dapr_fanout.py | 38 ++ .../io/api/scheduling/test_scheduler.py | 53 ++ .../unit/agents/io/telemetry/test_inflight.py | 60 +++ .../agents/io/telemetry/test_loop_watchdog.py | 100 ++++ .../agents/io/telemetry/test_telemetry.py | 90 ++++ tests/unit/agents/test_agent_group.py | 40 ++ tests/unit/agents/test_design_rules.py | 88 ++++ 41 files changed, 3277 insertions(+), 389 deletions(-) create mode 100644 src/blueprint/agents/deployment.py create mode 100644 src/blueprint/agents/io/api/actuators/health/namespace_supervisor.py create mode 100644 src/blueprint/agents/io/api/actuators/health/readiness_policy.py create mode 100644 src/blueprint/agents/io/telemetry/inflight.py create mode 100644 src/blueprint/agents/io/telemetry/loop_watchdog.py create mode 100644 src/blueprint/agents/io/telemetry/providers.py create mode 100644 tests/unit/agents/app_builder/test_startup_failure_policy.py create mode 100644 tests/unit/agents/io/api/actuators/health/test_namespace_supervisor.py create mode 100644 tests/unit/agents/io/api/actuators/health/test_readiness_policy.py create mode 100644 tests/unit/agents/io/telemetry/test_inflight.py create mode 100644 tests/unit/agents/io/telemetry/test_loop_watchdog.py diff --git a/AGENTS.md b/AGENTS.md index d1ca24ca..854939b2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -136,6 +136,22 @@ that constructs on behalf of a namespace it was handed uses the guarded form (`construction_scope`). *Failure:* replaying one agent's declarations resets every component of every agent back to the root, silently. +**An agent's failure is attributed, whatever the pod does about it.** A degraded agent drives +`blueprint.namespace.up = 0` and an ERROR event naming it, its group and its pod, independently of +readiness. *Failure:* grouping removes the pod restart that used to be the alert, so nineteen +agents go on answering while the twentieth has silently stopped and nothing says so. Guarded by +`test_namespace_supervisor.py`. + +**Every detached task carries a done-callback that logs its exception with the agent.** A bare +`create_task` or `ensure_future` is a violation. *Failure:* the exception surfaces as asyncio's +"Task exception was never retrieved", at an unpredictable time and attributed to nobody. Guarded +by `test_design_rules.py::TestEveryDetachedTaskIsWatched`. + +**The probe decides where traffic goes; it never decides who is woken.** `readiness_policy` may +keep a degraded agent from taking the pod out of rotation; it never suppresses that agent's signal, +and it never stops it being taken off its topics. *Failure:* a deployment that chose `critical` to +avoid a noisy probe would also have switched off the alerting for the agents it stopped gating on. + ### Names and values that leave the process **A name that crosses the process boundary is validated, never repaired.** Queue groups, JetStream diff --git a/docs/concepts/observability.md b/docs/concepts/observability.md index ac97ea16..704743d7 100644 --- a/docs/concepts/observability.md +++ b/docs/concepts/observability.md @@ -1,298 +1,335 @@ # Observability -Blueprint Agents provides built-in observability through OpenTelemetry tracing, structured logging, metrics collection, and health check endpoints. These capabilities are designed to work out of the box with minimal configuration while remaining extensible for advanced use cases. +Traces, metrics, logs and probes, and -- the part that only matters once several agents share a +process -- **which agent each of them belongs to**. -## OpenTelemetry Tracing +A single-agent service gets its attribution for free: one process, one agent, so a pod restart, a +latency graph and an error log all name the same thing. Grouping takes that away. Twenty agents in +one process share a port, an event loop, a memory limit and a health endpoint, so "the pod is +unhealthy" stops being an answer. Everything below exists to keep the answer per agent while the +process stays shared. -The framework integrates with OpenTelemetry to produce distributed traces exported via the OTLP protocol. When enabled, traces capture the full request lifecycle including HTTP handling, event processing, and AI model invocations. +Two rules run through all of it: -### Configuration +- **Regrouping is invisible.** An agent's telemetry identity is its own name, not its group's, so + moving it between deployments changes no dashboard, alert or SLO (C2). +- **Nothing fails silently at agent granularity.** Every path that stops an agent serving emits an + ERROR event and drives a gauge to zero, whether or not anything else notices (C7). + +--- -Enable tracing in `settings.toml`: +## Tracing + +### Configuration ```toml [default] otel_enabled = true -otel_endpoint = "http://localhost:4317" +otel_endpoint = "localhost:4317" # OTLP over gRPC; host:port, no path otel_service_name = "document-processor" ``` -| Field | Type | Description | +| Key | Type | Meaning | |---|---|---| -| `otel_enabled` | `bool` | Enable or disable OpenTelemetry tracing | -| `otel_endpoint` | `str` | OTLP collector endpoint (gRPC) | -| `otel_service_name` | `str` | Service name attached to all spans and metrics | +| `otel_enabled` | `bool` | Off by default. Nothing below is configured while it is off. | +| `otel_endpoint` | `str` | The OTLP gRPC collector. With no endpoint, no exporter is built and tracing stays off. | +| `otel_service_name` | `str` | The `service.name` of the **root** namespace -- see below. | -### Automatic FastAPI Instrumentation +### One identity per agent -When tracing is enabled, the framework automatically instruments the FastAPI application. Every incoming HTTP request generates a span with method, path, status code, and duration attributes. No additional code is required. +The framework does not configure *a* tracer provider; it configures one per namespace, each with +its own resource: -### Automatic CloudEvent Attribute Extraction +| Attribute | Value | +|---|---| +| `service.name` | The agent's own name. `otel_service_name` for the root namespace. | +| `deployment.group` | `BLUEPRINT_GROUP`, or ``. Set by the framework; no supported API exposes it (C6). | +| `service.instance.id` | `POD_NAME`, else `HOSTNAME`, else the host name, else ``. | -When an event handler processes a CloudEvent, the framework automatically extracts event metadata and attaches it to the active span: +So an agent called `orders` reports `service.name = "orders"` whether it runs alone or beside +nineteen others, and a dashboard keyed on it cannot tell which. A single-agent application keeps +reporting `otel_service_name`, unchanged, because its components live in the root namespace. -- `cloudevent.id` -- The unique event identifier -- `cloudevent.type` -- The event type string -- `cloudevent.source` -- The event source URI -- `cloudevent.subject` -- The event subject +All the providers share one exporter and one `BatchSpanProcessor` -- one queue and one export +thread whatever the group size, since the resource travels on the span rather than on the +processor. Metric readers cannot be shared (the SDK binds a reader to the provider that registered +it), so each provider gets its own reader over the one shared exporter. -This makes it straightforward to correlate traces with specific events in your observability backend. +The root's provider is also installed as the global one, so every module-level +`trace.get_tracer(...)` -- in this framework, and in any library -- resolves exactly as it did +before agents had identities. -## The @traced() Decorator +### `@traced()` -For custom spans on application-specific logic, use the `@traced()` decorator on any async method: +`@traced()` wraps a `Component` method in a span named `{component.name}.{method_name}`, on +**that component's agent's** provider. ```python +from blueprint.agents.component.component import traced from blueprint.agents.services.service_base import ServiceBase -from blueprint.agents.observability import traced class EmbeddingService(ServiceBase): async def on_startup(self) -> None: - self.model = self.registry.get_agent("embedder") + self._model = self.registry.get_agent("embedder") @traced() - async def compute_embedding(self, text: str) -> list[float]: - # This method is wrapped in a span named "EmbeddingService.compute_embedding" - return await self.model.run(text) + async def compute(self, text: str) -> list[float]: + return await self._model.run(text) +``` - @traced() - async def batch_embed(self, texts: list[str]) -> list[list[float]]: - results = [] - for text in texts: - embedding = await self.compute_embedding(text) - results.append(embedding) - return results +The arguments are **parameter names to stamp onto the span**, not a span name: + +```python +@traced("topic", "cloud_event") +async def handle_event(self, topic: str, cloud_event: CloudEvent) -> dict: ... ``` -The decorator creates a span named `{ClassName}.{method_name}` by default. Nested `@traced()` calls produce parent-child span relationships, giving full visibility into call hierarchies. +- A `CloudEvent`-shaped value is stamped as `event.type`, `event.source` and `event.id`. +- Anything else is stamped as `{parameter_name} = str(value)`. +- With no arguments, the first parameter that looks like a CloudEvent is stamped automatically. -### Custom Span Names +Every span additionally carries `agent` -- the namespace of the component, or ``. That is +redundant with the resource for a span that reaches an exporter, and it is the only record for one +that does not: a span still open when the process is killed never gets a resource applied. -Pass a name argument to override the default span name: +An exception propagating out of the method sets the span status to `ERROR` before it is re-raised. -```python -@traced("embedding.compute") -async def compute_embedding(self, text: str) -> list[float]: - return await self.model.run(text) -``` +--- ## Metrics -The framework automatically collects and exports metrics related to AI model usage and request processing. +| Metric | Kind | Meaning | +|---|---|---| +| `blueprint.namespace.up` | gauge | `1` while an agent is serving, `0` once it is not. Carries `agent`. | +| `blueprint.namespace.inflight` | gauge | Dispatches that agent has in progress. Carries `agent`. | +| `blueprint.events.unhandled` | counter | Events an agent received and found nothing to do with. | +| `blueprint.events.duplicate` | counter | Events an agent recognised as already processed. | +| `llm.tokens.count` | counter | Tokens consumed, by an agent's model calls. | +| `llm.response.latency` | histogram | Model call duration. | -### Token Usage Metrics +The first two are recorded on the agent's own meter provider, so they arrive with that agent's +`service.name` as well as with the `agent` attribute -- a dashboard can group on either, and one +of them survives a collector that drops resource attributes. -For every AI agent invocation, the following metrics are recorded: +`blueprint.namespace.inflight` is counted around the handler chain rather than at a transport +edge, so it covers NATS, Dapr and the REST dispatch path with one measurement, and it means "work +this agent is doing" rather than "messages its client has taken". Its reason for existing is +post-mortem: an OOM kill, a native crash and a blocked loop raise nothing a handler could catch, so +the only attribution available is what was emitted *before* the process died. -| Metric | Description | -|---|---| -| `ai.tokens.prompt` | Number of tokens in the prompt | -| `ai.tokens.completion` | Number of tokens in the model response | -| `ai.tokens.total` | Total tokens consumed (prompt + completion) | +--- -### Request Metrics +## Probes -| Metric | Description | +| Endpoint | Answers | |---|---| -| `ai.request.latency` | Duration of the model request in milliseconds | -| `ai.request.model_provider` | The provider used (e.g., "openai", "anthropic") | -| `ai.request.model_name` | The specific model invoked (e.g., "gpt-4o") | - -These metrics are exported alongside traces through the configured OTLP endpoint and can be visualized in Grafana, Datadog, or any OpenTelemetry-compatible backend. +| `GET /health/live` | `200` while the process is running. Never namespace-dependent (C3). | +| `GET /health/ready` | `200` when the pod should receive traffic, `503` otherwise. | +| `GET /info`, `/status/env`, `/status/llm`, `/status/build` | Service, configuration, AI-provider and build metadata. | -## Structured Logging +**Liveness is never namespace-dependent, and that is a rule rather than an accident.** A failing +liveness probe restarts the pod, and in a group that restarts every agent in it -- reintroducing +exactly the blast radius the grouping was paid to remove. So liveness reflects the process and the +event loop, and nothing else. -Blueprint Agents uses structured logging with correlation context. Log messages are formatted with key-value pairs that are queryable in log aggregation systems. +### Readiness is a policy -### Formatting Convention - -Use `%s`-style string formatting in log statements, not f-strings. This allows log aggregators to group identical log patterns and enables lazy evaluation (the string is only formatted if the log level is active). +```toml +[default] +readiness_policy = "critical" # "all" (default) | "critical" | "any" +``` -```python -import logging +| Value | Behaviour | +|---|---| +| `all` | **Default.** Any degraded agent makes the pod not ready. What a single-agent application has always done. | +| `critical` | Only agents the group flagged `critical` gate readiness. | +| `any` | Ready while at least one agent is up. | + +The root namespace gates readiness under every policy: it holds the shared infrastructure, so its +failure is not a partial one. In a single-agent application the root is the whole application, and +all three policies therefore agree -- which is what makes the key safe to set in a settings file +that standalone projects also read. + +`readiness_policy` is process scope: one pod has one readiness probe, so an agent's own +`settings.toml` cannot set it. + +An unrecognised value **refuses to start** rather than falling back to the default. A misspelt +`critcal` silently read as `all` would remove a whole group from rotation the first time a +non-critical agent wobbled, and the operator who set the key would have no way to see that it had +never taken effect. + +The `critical` flag is the same one the group configuration uses to decide whether a failed import +stops the process, because it answers the same question -- can this deployment run without that +agent: + +```yaml +# deployment-groups.yaml +groups: + - name: finance + agents: [orders, billing, reporting] + critical_agents: [orders, billing] +``` -logger = logging.getLogger(__name__) +### The readiness payload +```json +{ + "status": "UP", + "policy": "critical", + "components": { + "orders.nats_client": {"status": "healthy", "message": "Connected to NATS server at ..."}, + "billing.cache": {"status": "unhealthy", "message": "redis is unreachable"} + }, + "namespaces": { + "": {"status": "UP", "critical": true, "failing": []}, + "orders": {"status": "UP", "critical": true, "failing": []}, + "billing": {"status": "DOWN", "critical": false, "failing": ["billing.cache"]} + } +} +``` -class DocumentHandler(EventHandlerBase): - async def handle_event(self, event: CloudEvent) -> HandlerResult: - # Correct: %s-style formatting - logger.info("Processing document %s from source %s", event.subject, event.source) +`components` is keyed by entry name -- bare at the root, `.` for an agent -- so a +single-agent payload's keys are unchanged. `namespaces` exists because the policy makes `status` +no longer derivable from `components`: the pod above answers `UP` with a failing check in it, and +without the per-agent section that reads as a contradiction. - # Incorrect: f-string formatting (defeats structured logging) - # logger.info(f"Processing document {event.subject} from source {event.source}") +### Custom health checks - result = await self.process(event) - logger.debug("Processing complete for %s, result size: %d", event.subject, len(result)) +A checker is an object implementing `HealthCheckerBase`, not a callable: - return HandlerResult(event_type="document.processed", data=result) -``` +```python +from blueprint.agents.io.api.actuators.health import HealthCheckerBase +from blueprint.agents.models.api import ComponentHealth -### Log Level Configuration -Set the log level in `settings.toml`: +class DatabaseHealth(HealthCheckerBase): + def __init__(self, database: DatabaseService) -> None: + self._database = database -```toml -[default] -log_level = "INFO" # DEBUG, INFO, WARNING, ERROR, CRITICAL + async def health_check(self) -> ComponentHealth: + try: + latency = await self._database.ping() + except Exception as exc: + return ComponentHealth(status="unhealthy", message=str(exc)) + return ComponentHealth(status="healthy", message=f"{latency} ms") ``` -### Correlation Context +Register it on the builder, where the agent it belongs to is whichever one is in force: -When tracing is enabled, the active trace ID and span ID are automatically injected into log records. This allows you to correlate log entries with specific traces in your observability stack. +```python +builder.with_health_checker("database", DatabaseHealth(database)) +``` -## Health Checks +Two agents may both call theirs `database`; they appear as `orders.database` and +`billing.database`. Two checks that would still collide on one entry name are refused at +registration rather than silently reduced to one. -The framework automatically registers health check endpoints on the FastAPI application. These endpoints follow standard conventions for container orchestration platforms such as Kubernetes. +The framework registers checks of its own: one per transport client, and one per declared cache +(`cache`, or `cache:` for a named one). -### Built-in Endpoints +--- -| Endpoint | Purpose | Description | -|---|---|---| -| `/health/live` | Liveness probe | Returns 200 if the process is running. Used by orchestrators to detect crashed processes. | -| `/health/ready` | Readiness probe | Returns 200 if the application is ready to accept traffic. Checks that all components have completed startup. | -| `/health/detailed` | Detailed status | Returns a JSON breakdown of each component's health status. Useful for debugging. | +## What happens when an agent stops serving -### Response Format +One state -- is this agent serving -- with three consequences, and they are deliberately not three +mechanisms. -The `/health/detailed` endpoint returns structured information about each component: +1. **It is reported.** `blueprint.namespace.up` goes to `0` and an ERROR event is logged naming + the agent, its group and its pod. This happens whatever the readiness policy says. Grouping + removed the pod restart that used to be the alert, so the alert is emitted deliberately. +2. **It stops consuming.** Readiness gates HTTP only -- a pod removed from service rotation still + holds its subscriptions -- so for an event-driven agent the probe alone changes nothing. Under + NATS the agent's subscriptions are drained, which lets already-queued messages finish and + acknowledge while new ones go to a healthy replica. Under Dapr the sidecar delivers whatever + the application thinks, so the fan-out answers `RETRY` for that agent without dispatching. + The connection is kept open, because a closed client reports itself unhealthy for ever and the + pause could then never lift. +3. **It may take the pod out of rotation**, according to `readiness_policy`. -```json -{ - "status": "healthy", - "components": { - "EmbeddingService": {"status": "healthy"}, - "DocumentHandler": {"status": "healthy"}, - "summarizer": {"status": "healthy", "type": "agent"}, - "cache": {"status": "healthy", "entries": 1523} - }, - "uptime_seconds": 3847 -} -``` +Recovery is the reverse and needs no operator: when the agent's checks pass again, it resumes +consuming and the gauge returns to `1`. -### Custom Health Checkers +The one exception is a startup failure. If a non-critical agent's `on_startup` raises, the process +starts without it and that agent is **latched** down -- its components can often still answer a +health check while the agent is unusable, so an observed-health signal would put it straight back +into service on the next poll. A critical agent's `on_startup` failure ends the startup instead, +before the port is bound, so Kubernetes crash-loops the pod with the traceback rather than +reporting a replica that is silently short a consumer. -Register custom health check logic using `.with_health_checker()` on the `AppBuilder`. This is useful for verifying connectivity to external dependencies. +--- -```python -from blueprint.agents import AppBuilder, Config - - -async def check_database(registry) -> dict: - """Custom health check for database connectivity.""" - try: - db = registry.get_service(DatabaseService) - await db.ping() - return {"status": "healthy", "latency_ms": 12} - except Exception as e: - return {"status": "unhealthy", "error": str(e)} - - -async def check_external_api(registry) -> dict: - """Custom health check for an external API.""" - try: - client = registry.get_service(ExternalApiClient) - await client.health_check() - return {"status": "healthy"} - except Exception as e: - return {"status": "unhealthy", "error": str(e)} - - -config = Config(settings_files=["settings.toml"]) - -app = ( - AppBuilder(config) - .with_service(DatabaseService) - .with_service(ExternalApiClient) - .with_handler(MyHandler) - .with_health_checker("database", check_database) - .with_health_checker("external_api", check_external_api) - .build() -) -``` +## Detecting a blocked event loop -Custom health checkers appear in the `/health/detailed` response and influence the `/health/ready` status. If any checker returns `"unhealthy"`, the readiness endpoint returns a 503 status code. +The one group-wide failure a process can detect about itself. A blocked loop raises nothing, logs +nothing and keeps the pod live, while every agent in the group stops responding at once. -## Complete Configuration Example +| Environment | Mechanism | +|---|---| +| Development | asyncio's own debug mode, which names the exact callback and its source location. | +| Production | A watchdog that measures how much longer a known sleep actually took, and names the agents that had work in flight. | ```toml [default] -app_name = "document-processor" -log_level = "INFO" - -# OpenTelemetry -otel_enabled = true -otel_endpoint = "http://otel-collector:4317" -otel_service_name = "document-processor" +event_loop_debug = false # defaults to true in development +event_loop_slow_callback_seconds = 0.2 # debug mode's threshold +event_loop_watchdog_enabled = true +event_loop_watchdog_interval_seconds = 1.0 +event_loop_block_threshold_seconds = 1.0 ``` -## Complete Code Example +Never both: debug mode already reports the callback, which is strictly better than the watchdog's +"one of these agents was busy". Setting `event_loop_debug = true` in production is available and +deliberate -- debug mode wraps coroutine creation and keeps tracebacks for every task, which is +why it is not the default there. -```python -import logging +The watchdog cannot name the culprit. By the time it runs again the blocking callback has +returned, so it reports the agents that have work in flight *now*, which is the set the culprit is +in. That is still the difference between "the pod was slow" and "one of these two agents blocked +the loop for four seconds". -from blueprint.agents import AppBuilder, Config -from blueprint.agents.handler.event_handler_base import EventHandlerBase -from blueprint.agents.services.service_base import ServiceBase -from blueprint.agents.models.events import CloudEvent, HandlerResult -from blueprint.agents.observability import traced +--- -logger = logging.getLogger(__name__) +## Detached tasks +Every task the framework starts carries a done-callback that logs its exception with the agent +attached. Without one, a task that raised holds its exception until garbage collection and what +reaches the log is asyncio's own *Task exception was never retrieved* -- at an unpredictable time, +with no agent on it. In a process per agent that was survivable because the pod told you; in a +group it is precisely the silent per-agent failure this section exists to remove. -class AnalyticsService(ServiceBase): - async def on_startup(self) -> None: - self.agent = self.registry.get_agent("analyzer") +The same applies to code you write: a bare `asyncio.create_task(...)` in a handler or a service is +a task whose failure nobody will see. - @traced() - async def analyze(self, content: str) -> dict: - logger.info("Starting analysis, content length: %d", len(content)) - result = await self.agent.run(content) - logger.info("Analysis complete, categories found: %d", len(result.get("categories", []))) - return result +--- +## Logging -class AnalyticsHandler(EventHandlerBase): - priority = 10 +Use `%`-style lazy formatting, not f-strings, and get a module-level logger: - async def on_startup(self) -> None: - self.analytics = self.registry.get_service(AnalyticsService) +```python +from logging import getLogger - def can_handle_event(self, event: CloudEvent) -> bool: - return event.type == "document.received" +_log = getLogger(__name__) - @traced() - async def handle_event(self, event: CloudEvent) -> HandlerResult: - logger.info("Handling event %s for subject %s", event.type, event.subject) - result = await self.analytics.analyze(event.data["content"]) - return HandlerResult( - event_type="document.analyzed", - data={"doc_id": event.subject, "analysis": result}, - ) - - def get_published_event_types(self) -> list[str]: - return ["document.analyzed", "document.analysis_error"] - - -async def check_model_health(registry) -> dict: - try: - agent = registry.get_agent("analyzer") - await agent.health_check() - return {"status": "healthy"} - except Exception as e: - return {"status": "unhealthy", "error": str(e)} - - -config = Config(settings_files=["settings.toml", "secrets.toml"]) - -app = ( - AppBuilder(config) - .with_service(AnalyticsService) - .with_handler(AnalyticsHandler) - .with_agent("analyzer", AnalyzerAgent) - .with_health_checker("analyzer_model", check_model_health) - .with_cache() - .build() -) +_log.info("Processing document %s from %s", event.subject, event.source) +``` + +Never configure logging in a component. The application does it once, from `log_level` and +`log_format`; a library that adds a handler cannot be silenced by the process that hosts it. + +```toml +[default] +log_level = "INFO" +log_format = "json" ``` + +Framework log lines that concern one agent name it -- `agent='orders'`, or `` for the root +namespace -- so a grouped process's log is readable per agent without a trace backend. + +--- + +## See also + +- `docs/concepts/caching.md` -- the per-agent cache, and the checks it registers +- `docs/specs/2026-08-28-multi-agent-grouping.md` -- C2, C3, C4, C6 and C7, normatively diff --git a/docs/guides/testing.md b/docs/guides/testing.md index 28f84c4b..de35afe1 100644 --- a/docs/guides/testing.md +++ b/docs/guides/testing.md @@ -295,17 +295,20 @@ class TestAppIntegration: async def test_health_liveness(self, client): response = await client.get("/health/live") assert response.status_code == 200 - assert response.json()["status"] == "alive" + assert response.json()["status"] == "UP" async def test_health_readiness(self, client): + # 503 when any check is unhealthy, and the body is the same shape either way. response = await client.get("/health/ready") assert response.status_code == 200 - - async def test_health_detailed(self, client): - response = await client.get("/health/detailed") - assert response.status_code == 200 data = response.json() + assert data["status"] == "UP" assert "components" in data + + async def test_readiness_reports_each_agent(self, client): + # One entry per agent the process hosts, "" for a single-agent application. + response = await client.get("/health/ready") + assert response.json()["namespaces"][""]["status"] == "UP" ``` ### Testing Endpoint Behavior diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index e7696851..c19932de 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -5580,8 +5580,416 @@ the document covers. --- +### Phase 9 -- an agent's identity, and its failure, survive being grouped + +Phase 9 is the deployment-facing half of the namespace model. Everything before it made agents +share a process correctly; this makes the sharing legible from outside. Grouping takes away three +things a process per agent got for free -- a `service.name` that means one agent, a pod restart +that named the failure, and a readiness probe with one subject -- and the four invariants here +(C2, C3, C4, C7) put each of them back deliberately. + +#### C2 -- one telemetry identity per agent, and the root unchanged + +`io/telemetry/telemetry.py` configured one `TracerProvider` for the whole process, with +`service.name` from `otel_service_name`. Setting that to the group would break every dashboard on +the day of a regrouping; leaving it would attribute twenty agents' spans to one service. + +`TelemetryManager.configure_tracing(namespaces)` now builds **one provider pair per namespace**, +through `_configure_namespace`: + +```python +service_name = root_service_name if namespace == ROOT_NAMESPACE else namespace +resource = Resource.create({"service.name": service_name, "deployment.group": group, "service.instance.id": pod}) +provider = TracerProvider(resource=resource) +for processor in span_processors: + provider.add_span_processor(processor) +readers = [PeriodicExportingMetricReader(exporter) for exporter in metric_exporters] +register_providers(namespace, provider, MeterProvider(resource=resource, metric_readers=readers)) +``` + +The root is always configured, first, and stays the global provider +(`trace.set_tracer_provider(tracer_provider(ROOT_NAMESPACE))`), so every module-level +`trace.get_tracer(...)` in the framework and in any library resolves as it always has -- which is +what keeps a single-agent application's traces identical. + +The **same `BatchSpanProcessor` object** goes on every provider: a processor owns a queue and an +export thread, and the resource travels on the span rather than on the processor, so a processor +per agent would multiply both by the group size for nothing. Metric readers are the exception and +each provider gets its own, because the SDK binds a reader's collect callback to the provider that +registered it -- a shared reader would only ever collect from the last provider built. The +exporter behind them is still one object. + +**`io/telemetry/providers.py` is new, and is a leaf.** It holds the two registers and +`agent_tracer` / `agent_meter`, and imports nothing from this framework. That is not tidiness: a +component reads its own agent's tracer, so with the register beside the manager, `component.py` +imports the module that imports `Config`, which imports the manager, which imports +`component.namespace` -- a cycle that was confirmed by building it and watching the import fail. +It is also why a component holds no reference to the manager: the group's shape would then be +reachable from the object graph, which is what C6 forbids. + +`Component.tracer` is the one seam that had to change: + +```python +@cached_property +def tracer(self) -> trace.Tracer: + return agent_tracer(self._namespace, type(self).__qualname__) +``` + +Cached, and therefore resolved at first *use* -- which is the only reason this works. Components +are constructed by `build()`; the providers do not exist until the lifespan's `configure_tracing` +call, which is now the first thing startup does, before the actuator and before any client. +`agent_tracer` falls back to the global provider for a namespace nothing configured, so the call +is safe unconditionally and no caller branches on whether telemetry is on. + +`traced()` additionally stamps `agent` on every span: + +```python +if span.is_recording(): + span.set_attribute("agent", self._namespace or ROOT_LABEL) +``` + +Redundant with the resource for a span that reaches an exporter, and not redundant at all for the +failure C7 is about: a span still open when the process is killed never has a resource applied, so +what the span itself carries is all a post-mortem has. + +**`deployment.py` is new**, holding `deployment_group()` and `pod_identity()` -- moved out of +`nats_client.py`, which had them privately. Two subsystems now need the same two values, and two +copies would be two answers to "which pod is this" the day one of them learned a new environment +variable. `nats_client.py` imports them; its connection name is unchanged, and the two tests that +patched `nats_client.socket.gethostname` now patch `deployment.socket.gethostname`. + +#### C3 -- readiness is a policy, and it is per agent + +`io/api/actuators/health/readiness_policy.py` is new: a `ReadinessPolicy` str-enum with `parse` +and `is_ready`. + +```python +def is_ready(self, namespace_status: Mapping[str, bool], critical_namespaces: Collection[str]) -> bool: + if not namespace_status.get(ROOT_NAMESPACE, True): + return False + agents = {ns: healthy for ns, healthy in namespace_status.items() if ns != ROOT_NAMESPACE} + if not agents: + return True + if self is ReadinessPolicy.ALL: + return all(agents.values()) + if self is ReadinessPolicy.CRITICAL: + return all(healthy for ns, healthy in agents.items() if ns in critical_namespaces) + return any(agents.values()) +``` + +Two decisions in that function are not in the spec's table. **The root gates under every policy** +-- it holds the shared infrastructure, and in a single-agent application it is the whole +application, so all three policies agree there and the key is safe to set in a settings file that +a standalone project also reads. And **an unrecognised value raises** rather than defaulting: a +misspelt `critcal` read as `all` would remove a whole group from rotation the first time a +non-critical agent wobbled, with nothing to say the key had never taken effect. + +`HealthCheckCache` reduces the individual results to one verdict per agent before applying the +policy. `_aggregate_by_agent` reads the agent **from the entry, never from the key** -- the reason +`HealthCheckEntry` has carried it as data since step 6, because splitting +`orders.cache:v2.sessions` on a separator attributes it correctly only by luck. Every supervised +namespace appears even with no checks of its own, so `any` and `critical` do not read a shorter +list than the group has. + +`ReadinessResponse` gained `policy` and `namespaces`, the latter a `NamespaceReadiness` per agent +(`status`, `critical`, `failing`). It exists because the policy makes `status` no longer derivable +from `components`: a pod can answer `UP` with a failing check in it, and without the per-agent +section that reads as a contradiction with no way to resolve it. The `components` keys are +untouched, so a single-agent payload is unchanged apart from the two added fields. + +The `critical` flag is plumbed from where it already was. `AgentSpec.critical` already decided +whether a failed import stops the process (spec sec. 9.1); `AgentGroup.from_config` now also +collects it, `AgentGroup.assemble` passes it to `root.host_agent(namespace, critical=...)`, and +`build()` hands `ActuatorApi` the composition: + +```python +self._actuator_api = ActuatorApi(self.hosted_namespaces, self.critical_namespaces) +``` + +One flag, twice, deliberately: both ask whether the deployment can run without that agent, so a +second flag would be a second answer to one question. `readiness_policy` joins +`PROCESS_SCOPE_KEYS` -- one pod, one readiness probe. + +#### C7 and C4 -- the failure is reported, and it has a consequence + +`io/api/actuators/health/namespace_supervisor.py` is new, and is where one piece of state becomes +three things. `NamespaceSupervisor` is constructed by `ActuatorApi.on_startup` -- after telemetry, +because it creates instruments -- with every hosted namespace and the critical set. + +**The signal.** One observable gauge per namespace, on that namespace's own meter, rather than one +instrument with an `agent` attribute: the resource carries C2's identity and the resource belongs +to the provider, so an instrument on the root's meter would report every agent's value under the +group's `service.name`. + +```python +def _observe_gauge(self, namespace: str, label: str) -> Callable[[CallbackOptions], Iterable[Observation]]: + def observe(_options: CallbackOptions) -> Iterable[Observation]: + return [Observation(1 if self._up.get(namespace, True) else 0, {"agent": label})] + return observe +``` + +`_set` acts only on **transitions**, and logs at ERROR with the deployment identity in the line: + +```python +logger.error( + "Agent '%s' has stopped serving (group '%s', pod '%s'): %s", + namespace or ROOT_LABEL, self._group, self._pod, reason, +) +await self._pause_consumption(namespace) +``` + +Transitions rather than states, because an alert repeated every poll stops being read, and because +the client is already paused. + +**The consequence (C4).** `IOClientBase` gained `consumption_paused`, `pause_consumption()` and +`resume_consumption()`. `NATSClient` overrides them: pausing **drains** the subscriptions -- +already-queued messages reach their handler and acknowledge over the connection that delivered +them, where an unsubscribe would strand every one of them -- and resuming calls `_subscribe_all()`. +`_on_reconnected` returns early while paused, or the broker dropping and restoring a connection +would silently resubscribe a degraded agent, and C4 would hold only until the next network blip. + +Under Dapr there is nothing client-side to unsubscribe: the sidecar posts to a fixed path whatever +the application thinks. So `DaprEventing.publish` checks before dispatching: + +```python +if self._is_paused(namespace): + dispositions.append(DeliveryDisposition.NAK) + ... + continue +``` + +which the fan-out renders as `RETRY`, redelivering to a replica whose agent is up. `_is_paused` +reads that agent's own client rather than a process-wide register of degraded agents, so both +transports answer the same question from the same state. + +**Two departures from the spec, both because the obvious reading latches.** Spec C4 says a +degraded namespace's client is *closed*. A closed client reports itself unhealthy for ever, so the +agent could never be seen to recover and a transient Redis outage would take it off its topics +permanently -- the connection is therefore kept open, and only consumption stops. For the same +reason `NATSClient.health_check` reports a **paused client as healthy**, with a message saying so: +the pause is a consequence of degradation, not a cause of it, and the check that actually failed is +still in the payload. Reporting it as unhealthy would make the pause self-sustaining. + +**Detached tasks.** `sessions_bus.py` gained `_report_task_failure`, added to both its +`create_task` sites -- the SSE consumer, which had no callback at all, and `_spawn_tracked`, whose +callback only discarded the task from a set. Both `_on_retry_done` implementations now name the +agent. A bare `create_task` is now a guarded rule (below). + +**In-flight accounting.** `io/telemetry/inflight.py` is new: a per-agent count exported as an +observable gauge, registered lazily on first sight of an agent because it is reached from the +dispatch path and has no list of agents to iterate. `EventProcessingService.process_event` counts +around the chain: + +```python +with IN_FLIGHT.track(namespace): + handler_result = await self._chain_for(namespace).process(event, context) +``` + +Around the chain rather than at a transport edge, so one measurement covers NATS, Dapr and the REST +dispatch path, and so it means "work this agent is doing" rather than "messages its client has +taken". Its whole purpose is post-mortem: an OOM kill, a native crash and a blocked loop raise +nothing catchable, so the only attribution available is what was emitted before the process died. + +#### Spec sec. 9.1 -- a failing `on_startup` no longer ends the group + +The lifespan re-raised every component's startup failure. In a single-agent process that was +right; in a group it is the blast radius grouping is paid to remove. All eight startup loops now +go through one helper: + +```python +async def _start_component(self, kind: str, component: Any, label: str) -> None: + try: + await component.on_startup() + except Exception as exc: + namespace = namespace_of(component) + if not namespace or namespace in self._critical_namespaces: + logger.error("%s %s startup failed: %s", kind, label, exc, exc_info=True) + raise + logger.error("%s %s startup failed and agent '%s' is not critical, so the process starts without it: %s", ...) + await self._mark_agent_down(namespace, f"its {kind.lower()} '{label}' failed to start: {exc}") + return + logger.info("%s %s startup completed", kind, label) +``` + +A critical agent's failure still propagates, which aborts the lifespan **before the port is +bound**, so Kubernetes crash-loops with the traceback rather than reporting a replica that is +silently short a consumer. The root is always critical: there is no rest of the process without it. +A non-critical agent's failure calls `supervisor.mark_down`, which **latches** -- unlike a +health-driven transition, because the components of an agent whose `on_startup` raised can often +still answer a health check while the agent is unusable, so an observed-health signal would put it +back into service on the next poll. + +#### Dev-mode detection -- the blocked loop + +`io/telemetry/loop_watchdog.py` is new, and is two mechanisms that are never both on. +`configure_loop_debug` turns on asyncio's debug mode -- which names the exact callback and its +source -- and returns whether it did; development defaults to on, production to off, and +`event_loop_debug` overrides either. When it returns `False`, `LoopWatchdog` starts instead: + +```python +before = loop.time() +await asyncio.sleep(self._interval) +lag = loop.time() - before - self._interval +if lag >= self._threshold: + self._report(lag) +``` + +The overshoot is time the loop could not run anything. It cannot name the culprit -- by the time it +runs again the callback has returned -- so it names the agents that have work in flight, which is +the set the culprit is in. That is the honest shape, and it is still the difference between "the +pod was slow" and "one of these two agents blocked the loop for four seconds". Both are wired from +`AppBuilder._start_loop_diagnostics`, immediately after telemetry and before the actuator. + +The other two rows of the plan's dev-mode table are already covered or belong elsewhere: +module-level side effects are guarded by +`test_design_rules.py::TestLoggingIsConfiguredByTheApplication`, which found two real ones in step +9 part 2, and the non-idempotent-handler flag is `asbs validate`, which is P4's and phase 10's. + +#### The two event-accounting metrics this changelog assigned to phase 9 + +Both were open points that said, in so many words, "it belongs with the telemetry work in phase +9". Both are one instrument each, and both measure a failure whose only other trace is silence. + +**Dead-lettering was counted nowhere.** It was logged, so "how many messages did we give up on +today" could not be answered from metrics -- and a dead letter is the one delivery outcome with no +other trace in a running system: not a retry that eventually succeeds, not an error a caller sees. +`NATSClient._count_dead_letter` records `blueprint.events.dead_lettered` with `agent`, `reason` +(`deliveries-exhausted` or `terminal-failure`) and `kept`, the last of which is what tells a +deployment with no `nats_dead_letter_subject` that it is losing payloads. Counted **once**, where +the outcome is known -- counting on entry and again on a failed publish would report two dead +letters for one message -- and the counter itself is a `cached_property` for the same reason +`Component.tracer` is: an instrument created in `__init__` would be bound to the no-op global +meter, because a client is constructed by `build()` and the providers do not exist until the +lifespan. + +**Nothing observed a tick.** A tick is an ordinary event, so a `CronJob` that stopped publishing +looked like silence rather than a fault. `SchedulerBase.run_tick` is new and is what all three +tick paths now call -- the in-process timer once it has won its slot, `SchedulerTickHandler`, and +the manual REST trigger -- so the gauge means "this scheduler did its work" rather than "one +mechanism fired": + +```python +async def run_tick(self) -> None: + try: + await self.tick() + finally: + self._last_tick = time.time() +``` + +The `finally` is deliberate: a tick that raised still happened, and "being driven and failing" is +a different alert from "not being driven". `blueprint.scheduler.tick_age_seconds` reports the age, +with `-1` before the first tick so that "never ticked" and "ticked a long time ago" are different +values -- a pod that has just started has missed nothing. Registered in `on_startup`, after +telemetry, and reported in both modes: in-process mode is where a stopped timer is already visible +as a missing pod, event mode is where it is not. + +#### The guard, and the documents + +`test_design_rules.py::TestEveryDetachedTaskIsWatched` walks every framework module's AST for a +`create_task` / `ensure_future` whose result is assigned and then given an `add_done_callback` in +the same block; a spawn whose result is discarded outright can never be watched and fails too. +Verified by deleting the callback added to `sessions_bus.py` above and watching it fail with the +file and the line. `AGENTS.md` gained three rules with the failure each prevents: attribution +independent of the probe, a done-callback on every detached task, and *the probe decides where +traffic goes, never who is woken*. + +`docs/concepts/observability.md` was **rewritten against the code** rather than extended, on the +same grounds as the caching document in step 9 part 3. It documented an endpoint that has never +existed (`/health/detailed`), an import path that does not exist (`blueprint.agents.observability`), +`@traced("some.span.name")` when the arguments are *parameter names to stamp*, and health checkers +as bare callables when `HealthCheckerBase` is a class with an `async health_check() -> +ComponentHealth`. Adding a readiness-policy section beside all that would have been worse than +either. Two smaller fixes found the same way: `docs/guides/testing.md` asserted `{"status": +"alive"}` and called `/health/detailed`, so its snippet could never have passed; and +`AppBuilder.with_health_checker`'s *In a group* paragraph still said every check is ANDed, which +phase 9 makes false. + +`docs/guides/deployment.md` also documents `/health/detailed`, and is **not** fixed here: phase 10 +owns its rewrite, and it needs more than an endpoint correction. + +#### Configuration added + +| Key | Default | Meaning | +|---|---|---| +| `readiness_policy` | `"all"` | `all` / `critical` / `any`. Process scope. | +| `event_loop_debug` | on in development | asyncio debug mode, which names the blocking callback. | +| `event_loop_slow_callback_seconds` | `0.2` | Debug mode's threshold. | +| `event_loop_watchdog_enabled` | `true` | The production watchdog, used when debug mode is off. | +| `event_loop_watchdog_interval_seconds` | `1.0` | How often it measures. | +| `event_loop_block_threshold_seconds` | `1.0` | How much lag it reports. | + +#### Metrics added + +| Metric | Attributes | +|---|---| +| `blueprint.namespace.up` | `agent` | +| `blueprint.namespace.inflight` | `agent` | +| `blueprint.events.dead_lettered` | `agent`, `reason`, `kept` | +| `blueprint.scheduler.tick_age_seconds` | `scheduler`, `agent`, `mode` | + +All four are recorded on the owning agent's meter provider, so each arrives with that agent's +`service.name` resource as well as with its `agent` attribute. + +The spec writes the first of these as `blueprint_namespace_up{agent="..."}`, which is the +Prometheus rendering of the OpenTelemetry name `blueprint.namespace.up` -- the instrument is +named in OTel's dotted form and the exporter does the substitution. They are the same metric, +not a drift. + +Three of spec sec. 12's acceptance criteria are ticked by this phase: per-namespace +`service.name` with the root unchanged (C2), a degraded namespace under all of liveness / +readiness / gauge / consumers (C3, C4), and every path that stops a namespace serving emitting +both signals (C7). The detached-task criterion asks for "a test that fails a task in each +background path"; what landed is an AST guard over every framework module, which is broader in +coverage and weaker in behaviour -- it proves the callback is attached, not that it logs what it +should -- so that box is left unticked. + +#### Tests + +`test_readiness_policy.py` (24 cases), `test_namespace_supervisor.py` (13), +`test_inflight.py` (8), `test_loop_watchdog.py` (9) and +`app_builder/test_startup_failure_policy.py` (9, driven through the real lifespan against real +components) are new. `test_telemetry.py` gained a per-agent identity class, `test_health_cache.py` +a per-agent verdict class, `test_nats_client.py` a pause/resume class, `test_dapr_fanout.py` a +paused-agent class, `test_component.py` two span-attribution cases, `test_agent_group.py` a +critical-flag class, `test_actuator_api.py` a readiness-policy class and `test_scheduler.py` a +tick-freshness class. + +One existing case changed rather than being added to: `test_actuator_api.py`'s +`test_on_startup_uses_configured_interval` asserted `assert_called_once_with(check_interval_seconds=60)` +on `HealthCheckCache`, which now also takes a policy and a supervisor; it asserts on the one kwarg +it is about instead. + +--- + ## Open points +- **Two spec amendments from phase 9, both because the spec's wording latches.** Spec C4 says a + degraded namespace's transport client is *closed*. Implemented as a **pause** -- subscriptions + drained, connection kept -- because a closed client reports itself unhealthy for ever, so the + agent could never be seen to recover and a transient fault would take it off its topics + permanently. The same reasoning makes `NATSClient.health_check` report a paused client as + *healthy*, which is the second amendment: the pause is a consequence of degradation, not a cause + of it, and the check that actually failed is still in the payload. Sec. 3's C4 should say "stops + consuming" rather than "closes its client". +- **Spec C2's shared `BatchSpanProcessor` holds; its shared metric reader cannot.** The + OpenTelemetry SDK binds a reader's collect callback to the provider that registered it, so a + reader shared across providers collects only from the last one built. Each provider therefore + has its own `PeriodicExportingMetricReader` over the one shared exporter -- one export thread per + agent for metrics, one for the whole process for spans. Worth stating in sec. 3's C2, which + currently says "all providers SHOULD share one exporter and one `BatchSpanProcessor`" and is + silent on readers. +- **The readiness policy's treatment of the root is not in the spec.** The root gates readiness + under all three policies, because it holds the shared infrastructure and because a single-agent + application is *entirely* root -- so the key has to be a no-op there or it could not be set in a + settings file that standalone projects read. Sec. 3's C3 table should say so. +- **The blocked-loop watchdog names candidates, not a culprit.** It measures the overshoot of a + known sleep, so by the time it runs the blocking callback has returned; it reports the agents + with work in flight, which is the set the culprit is in. asyncio's debug mode gives the exact + answer and is available in production behind `event_loop_debug`, at the cost of wrapping every + coroutine creation. There is no cheap way to have both. +- **`readiness_policy = "any"` is implemented but has no acceptance criterion.** Spec sec. 12 lists + criteria for `all` and `critical` and none for `any`, and no example project or group file uses + it. It is the one of the three that has never been exercised against a real deployment. - **Phase 7's ambiguity error needs a spec amendment.** The plan asks `process_event` to raise when a handler declares no runtime and several are registered. It is implemented as a once-per-handler WARNING with nothing bound, because raising would fail every delivery in an @@ -5689,11 +6097,10 @@ the document covers. which under JetStream means a durable's filter changes -- a migration, not a config change (sec. 7.7). The `topic=` override exists so an agent can opt out of the guess, but the default is what the generated `CronJob` will encode. -- **Nothing observes a tick.** A tick is counted as an ordinary event, so a `CronJob` that stopped - publishing looks like silence, not a fault: no metric says "this scheduler has not ticked within - two intervals". The declared crontab is in the process and the last tick is knowable, so this is - cheap, and it belongs with the telemetry work in phase 9. Until it exists, event mode trades a - duplicated tick for a possibly missing one, and only the second failure is invisible. +- ~~**Nothing observes a tick.**~~ **Done in phase 9.** `blueprint.scheduler.tick_age_seconds` + reports the age of the last tick, `-1` before the first, in both modes. What it does *not* do is + interpret the crontab: "two intervals" is an alerting expression written against the gauge, not + something the framework decides, because the framework has no view of what a missed tick costs. - **There is no generated README**, so the third surfacing channel spec sec. 7.4 asks for has nowhere to go. `asbs setup` writes a Dockerfile, settings, secrets and source, and the generated `CLAUDE.md` and `settings.toml` carry the idempotency note instead. If a README is @@ -5721,9 +6128,8 @@ the document covers. stream's retention, so a deployment that never reads it will silently lose dead letters when the stream ages them out. Draining it is an operational task the framework does not do, and no guidance for it is written yet. -- **Nothing observes dead-lettering.** It is logged, but there is no counter, so "how many messages - did we give up on today" cannot be answered from metrics. It belongs with the telemetry work in - phase 9, next to `blueprint.events.unhandled`. +- ~~**Nothing observes dead-lettering.**~~ **Done in phase 9.** `blueprint.events.dead_lettered`, + with `reason` and `kept`, next to `blueprint.events.unhandled`. - ~~**Cache names are not namespace-scoped**~~ -- **done twice.** First by prefixing the partition (`AgentScopedCache`), then properly in phase 8b step 5, which keys the registry on `(namespace, name)` and gives each agent its own directory and Redis prefix; the lens is diff --git a/docs/plans/2026-08-28-multi-agent-grouping.md b/docs/plans/2026-08-28-multi-agent-grouping.md index 0e7a3dda..9e751333 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping.md +++ b/docs/plans/2026-08-28-multi-agent-grouping.md @@ -2,7 +2,7 @@ | | | |---|---| -| **Status** | P0-P6, phases 0-8 and **phase 8b step 1** landed on `feature/multi-agent-namespaces`. Next: 8b steps 2-9, then phase 9, then 10. | +| **Status** | P0-P6, phases 0-8, the whole of 8b and **phase 9** landed on `feature/multi-agent-namespaces`. Next: phase 10. | | **Amendment** | `docs/plans/2026-09-10-builder-unification.md` -- decided 2026-09-10. Phase 8b below is its work breakdown; phases 0 and 3 are superseded by it. Step 9 was added on 2026-09-10 and is not in that proposal's original breakdown. | | **Deferred out** | `docs/plans/2026-09-10-config-validation-unification.md` -- configuration validation is not part of this feature and **must not** be touched during 8b. | | **Spec (normative)** | `docs/specs/2026-08-28-multi-agent-grouping.md` | diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md index 27f5d2c5..07eeefbf 100644 --- a/docs/specs/2026-08-28-multi-agent-grouping.md +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -887,13 +887,13 @@ Two things an author still needs to know: their agent's name, and that handlers - [ ] Two replicas of a two-agent group: each event processed exactly once per agent. - [ ] Durable and queue names byte-identical across two builds where the same agent sits in different groups (C1). -- [ ] Spans from namespace `invoice` carry `service.name = "invoice"`; a `namespace=""` app keeps +- [x] Spans from namespace `invoice` carry `service.name = "invoice"`; a `namespace=""` app keeps `otel_service_name` (C2). -- [ ] A degraded namespace: liveness `UP`, readiness per policy, `blueprint_namespace_up = 0`, +- [x] A degraded namespace: liveness `UP`, readiness per policy, `blueprint_namespace_up = 0`, that namespace's consumers stopped (C3, C4). - [ ] `.model_name` overrides root `model_name` for that namespace only (C5). - [ ] No supported API exposes group membership to agent code (C6). -- [ ] Every path that stops a namespace serving emits an ERROR event and +- [x] Every path that stops a namespace serving emits an ERROR event and `blueprint_namespace_up{agent} = 0` carrying that namespace's identity; a namespace whose subscriptions vanish while the process stays healthy is reported within one scrape interval (C7). diff --git a/src/blueprint/agents/agent_group.py b/src/blueprint/agents/agent_group.py index ddac680c..3733259d 100644 --- a/src/blueprint/agents/agent_group.py +++ b/src/blueprint/agents/agent_group.py @@ -25,7 +25,7 @@ import importlib import logging import sys -from collections.abc import Mapping +from collections.abc import Collection, Mapping from pathlib import Path from fastapi import FastAPI @@ -54,7 +54,14 @@ class AgentGroup: gets a process to itself while still being deployed by the group mechanism. """ - def __init__(self, name: str, agents: Mapping[str, AppBuilder], *, settings: Mapping[str, Path] | None = None) -> None: + def __init__( + self, + name: str, + agents: Mapping[str, AppBuilder], + *, + settings: Mapping[str, Path] | None = None, + critical: Collection[str] | None = None, + ) -> None: """Declare a group. Args: @@ -87,6 +94,7 @@ def __init__(self, name: str, agents: Mapping[str, AppBuilder], *, settings: Map ) self._agents[namespace] = builder self._settings: dict[str, Path] = {name: Path(path) for name, path in (settings or {}).items()} + self._critical: frozenset[str] = frozenset(self._agents) if critical is None else frozenset(critical) @property def name(self) -> str: @@ -103,6 +111,11 @@ def settings(self) -> Mapping[str, Path]: """Where each agent's own settings file is, for the agents that have one.""" return dict(self._settings) + @property + def critical_agents(self) -> frozenset[str]: + """The agents this deployment cannot run without.""" + return self._critical + # ------------------------------------------------------------------ # Resolution # ------------------------------------------------------------------ @@ -158,18 +171,26 @@ def from_config(cls, group: GroupConfig) -> "AgentGroup": agents: dict[str, AppBuilder] = {} settings: dict[str, Path] = {} + critical: set[str] = set() for spec in group.agents: builder = cls._load_declaration(spec) if builder is None: continue agents[spec.name] = builder + if spec.critical: + # The same flag twice, deliberately. It decided above whether a failed import + # stops the process (spec sec. 9.1); here it decides whether this agent may + # take the pod out of service rotation (C3). Both ask whether the deployment + # can run without the agent, so a second flag would be a second answer to one + # question. + critical.add(spec.name) # Only for an agent that loaded: a skipped non-critical agent has no scope to merge # anything into. fragment = cls._settings_path(spec.module) if fragment is not None: settings[spec.name] = fragment - return cls(group.name, agents, settings=settings) + return cls(group.name, agents, settings=settings, critical=critical) @staticmethod def _load_declaration(spec: AgentSpec) -> AppBuilder | None: @@ -305,7 +326,7 @@ def assemble(self, config: Config) -> FastAPI: # still an agent this process hosts: build() wires one transport per hosted agent # and asks each one's own configuration whether it publishes, and neither of those # can be derived from a declaration list that may be empty. - root.host_agent(namespace) + root.host_agent(namespace, critical=namespace in self._critical) with namespace_scope(namespace): for declaration in builder.declarations: declaration.replay(root) diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index a8283f92..4652d550 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -44,6 +44,15 @@ from .services.sessions import SessionKeyProvider, SessionsApiClient from .services.infrastructure.cache_backend_factory import CacheBackendFactory from .config import DEFAULT_SETTINGS_FILES, Config, TelemetryManager +from .io.telemetry.loop_watchdog import ( + BLOCK_THRESHOLD_KEY, + DEFAULT_BLOCK_THRESHOLD_SECONDS, + DEFAULT_INTERVAL_SECONDS, + WATCHDOG_ENABLED_KEY, + WATCHDOG_INTERVAL_KEY, + LoopWatchdog, + configure_loop_debug, +) from .utils import parse_bool _UNCONSTRUCTED_KINDS = frozenset({"cache", "health_checker"}) @@ -193,6 +202,9 @@ def __init__(self, config: Config | None = None) -> None: # special case in _build_rest_endpoints. self._lifecycle_components: list[Component] = [] self._actuator_api: ActuatorApi | None = None + # Replaced in the lifespan when the environment wants one; the default instance is + # never started, so shutdown can stop it unconditionally. + self._loop_watchdog = LoopWatchdog() # Health checkers declared before build(), collected out of the declarations by the # replay pass. A dict rather than a list because the readiness payload is keyed on the # entry name, and a later declaration of the same name replaces an earlier one. @@ -200,6 +212,9 @@ def __init__(self, config: Config | None = None) -> None: # Which agents this process hosts. See the 'namespaces' property for why the # builder is the thing that keeps the list rather than the registry. self._namespaces: list[str] = [] + # Of those, the ones the deployment said it cannot run without. Read by the + # readiness probe under readiness_policy = 'critical' (C3). + self._critical_namespaces: list[str] = [] # ------------------------------------------------------------------ # Configuration @@ -293,7 +308,7 @@ def _require_config(self) -> Config: # Fluent registration API # ------------------------------------------------------------------ - def host_agent(self, namespace: str) -> "AppBuilder": + def host_agent(self, namespace: str, *, critical: bool = True) -> "AppBuilder": """Record that this process serves ``namespace``, whether or not it declares anything. Not a ``with_*``: it declares no component. It states a fact about the *process*, and @@ -309,6 +324,12 @@ def host_agent(self, namespace: str) -> "AppBuilder": Args: namespace: The agent's name. + critical: Whether the deployment can run without this agent. Carried through to the + readiness probe, where ``readiness_policy = "critical"`` lets only the flagged + agents take the pod out of service rotation (C3). The same flag the group + configuration uses to decide whether a failed import stops the process + (spec sec. 9.1), because it answers the same question -- and the default is the + same ``True``, so an unflagged agent gates readiness exactly as it does today. Returns: This builder. @@ -328,9 +349,21 @@ def host_agent(self, namespace: str) -> "AppBuilder": "the first and their components would merge into one registry namespace." ) self._namespaces.append(agent) - logger.info("Hosting agent namespace '%s'", agent) + if critical: + self._critical_namespaces.append(agent) + logger.info("Hosting agent namespace '%s'%s", agent, "" if critical else " (not critical)") return self + @property + def critical_namespaces(self) -> tuple[str, ...]: + """The hosted agents that gate readiness under the ``critical`` policy. + + A subset of :attr:`namespaces`. The root is not in it and does not need to be: it gates + readiness under every policy, because it holds the shared infrastructure the rest of the + process depends on. + """ + return tuple(self._critical_namespaces) + @property def namespaces(self) -> tuple[str, ...]: """The agent namespaces declared on this builder, in declaration order. @@ -690,8 +723,12 @@ def with_health_checker(self, name: str, checker: "HealthCheckerBase") -> "AppBu written, and it travels with the checker as data -- so two agents may both declare ``"db"`` and appear as ``orders.db`` and ``billing.db`` instead of one of them vanishing into the other's dict slot. Two checks that would still share one entry are refused - rather than silently reduced to one. The readiness *policy* is unchanged: every check is - ANDed, so one agent's failing check takes the whole pod out of rotation. + rather than silently reduced to one. What a failing check then *does* is the + deployment's decision: ``readiness_policy`` (C3) decides whether one agent's failure + takes the whole pod out of rotation, and the default ``"all"`` says it does, which is + what a single-agent application has always done. Whatever the policy, a failing check + stops its agent consuming (C4) and is reported as ``blueprint.namespace.up = 0`` with + an ERROR event (C7) -- the policy decides where traffic goes, never who is woken. Args: name: What this checker is called within its agent. It appears in the readiness @@ -886,8 +923,10 @@ def build(self, config: Config | None = None) -> FastAPI: if registry.get_io_clients(namespace=namespace): EventPublishingService(namespace=namespace) - # 5. Create ActuatorApi and wire health checkers from all registered clients - self._actuator_api = ActuatorApi() + # 5. Create ActuatorApi and wire health checkers from all registered clients. It is + # told the composition because the readiness probe is per agent now (C3): which + # namespaces exist, and which of them the deployment cannot run without. + self._actuator_api = ActuatorApi(self.hosted_namespaces, self.critical_namespaces) # The client's *base* name, not its registry name: the registry name is already # qualified with '_' ('orders_nats_client'), and the entry composes its own rendering, # so passing the registry name would read 'orders.orders_nats_client'. A root client's @@ -1142,59 +1181,132 @@ def _mount(app: FastAPI, component: RestApiBase, *, root_prefix: str) -> None: # Lifespan # ------------------------------------------------------------------ + async def _start_component(self, kind: str, component: Any, label: str) -> None: + """Run one component's ``on_startup`` under spec sec. 9.1's failure policy. + + A failure used to end the process whoever it belonged to, and in a single-agent process + that was right: there was one agent, and a half-started one is worse than none. In a + group it is the blast radius grouping is paid to remove -- one agent's Redis client + raising in ``on_startup`` would take nineteen working agents down with it. + + So the ``critical`` flag decides, and it decides *before* anything is wired rather than + after the exception, because there is no partial build to unwind: one process, one + ``build()``. A critical agent's failure still propagates, which aborts the lifespan + before the port is bound, so Kubernetes crash-loops the pod with the traceback rather + than reporting a replica that is silently short a consumer. A non-critical agent's + failure marks that agent down and stops it consuming (C4, C7), and the rest start. + + The root is always critical: it holds the shared infrastructure, and there is no + "rest of the process" to keep running without it. + + Args: + kind: What sort of component this is, for the log line. + component: The component to start. + label: How to name it in the log line -- usually its registry name. + + Raises: + Exception: whatever ``on_startup`` raised, when the component belongs to the root or + to a critical agent. + """ + try: + await component.on_startup() + except Exception as exc: + namespace = namespace_of(component) + if not namespace or namespace in self._critical_namespaces: + logger.error("%s %s startup failed: %s", kind, label, exc, exc_info=True) + raise + logger.error( + "%s %s startup failed and agent '%s' is not critical, so the process starts without it: %s", + kind, + label, + namespace, + exc, + exc_info=True, + ) + await self._mark_agent_down(namespace, f"its {kind.lower()} '{label}' failed to start: {exc}") + return + logger.info("%s %s startup completed", kind, label) + + async def _start_loop_diagnostics(self, config: Config) -> None: + """Turn on asyncio debug mode, or start the watchdog, whichever this environment wants. + + Never both. Debug mode already reports the blocking callback with its source location, + which is strictly better than the watchdog's "one of these agents was busy", so running + the watchdog as well would add a second, vaguer line about the same event. + + Args: + config: The application's configuration. + """ + development = str(config.get("app_environment", "development")) == "development" + if configure_loop_debug(config, development=development): + return + if not parse_bool(config.get(WATCHDOG_ENABLED_KEY, True), WATCHDOG_ENABLED_KEY): + logger.info("Event loop watchdog is disabled by configuration") + return + self._loop_watchdog = LoopWatchdog( + interval_seconds=float(config.get(WATCHDOG_INTERVAL_KEY, DEFAULT_INTERVAL_SECONDS)), + threshold_seconds=float(config.get(BLOCK_THRESHOLD_KEY, DEFAULT_BLOCK_THRESHOLD_SECONDS)), + ) + await self._loop_watchdog.start() + + async def _mark_agent_down(self, namespace: str, reason: str) -> None: + """Take one agent out of service for a failure no health check can see. + + Latched, unlike a health-driven transition: the components of an agent whose + ``on_startup`` raised may well answer a health check perfectly while being unusable, so + an observed-health signal would put it straight back into service on the next poll. + + Args: + namespace: The agent to take out of service. + reason: Why, for the ERROR event and the readiness payload. + """ + supervisor = self._actuator_api.supervisor if self._actuator_api is not None else None + if supervisor is None: # pragma: no cover - the actuator is started first + logger.error("Agent '%s' cannot be marked down: no supervisor is running. Reason was: %s", namespace, reason) + return + await supervisor.mark_down(namespace, reason) + def _create_lifespan_manager(self) -> Any: @asynccontextmanager async def lifespan(_app: FastAPI) -> AsyncIterator[None]: """Application lifespan manager for startup and shutdown events.""" registry: Registry = Component.shared_registry # type: ignore[assignment] + resolved_config = self._require_config() logger.info("Starting up application components") - # Configure OpenTelemetry tracing + # Configure OpenTelemetry tracing, one identity per agent (C2). First in startup, + # because Component.tracer caches the provider it resolves on first use and every + # component's first traced call happens after this point. try: - self._telemetry_manager.configure_tracing() + self._telemetry_manager.configure_tracing(self.namespaces) except Exception as e: logger.warning("Failed to configure OpenTelemetry: %s", e) + # A blocked event loop stalls every agent in the process at once and raises + # nothing, so it is the one group-wide failure the process can detect about itself + # (C7). Debug mode names the callback and is on in development; production gets the + # watchdog instead, which names the agents that had work in flight. + await self._start_loop_diagnostics(resolved_config) + # ActuatorApi if self._actuator_api is not None: await self._actuator_api.on_startup() # Clients (IO + AI) — config reading and lazy-connect preparation for client in registry.get_clients(): - try: - await client.on_startup() - logger.info("Client %s startup completed", client.name) - except Exception as e: - logger.error("Client %s startup failed: %s", client.name, e, exc_info=True) - raise + await self._start_component("Client", client, client.name) # Services (includes EventProcessingService, EventPublishingService, user services) for service in registry.get_services(): - try: - await service.on_startup() - logger.info("Service %s startup completed", service.name) - except Exception as e: - logger.error("Service %s startup failed: %s", service.name, e, exc_info=True) - raise + await self._start_component("Service", service, service.name) # Handlers for handler in registry.get_event_handler(): - try: - await handler.on_startup() - logger.info("Handler %s startup completed", handler.name) - except Exception as e: - logger.error("Handler %s startup failed: %s", handler.name, e, exc_info=True) - raise + await self._start_component("Handler", handler, handler.name) # Agents for agent_name in registry.get_agents(): - try: - agent = registry.get_component(agent_name) - await agent.on_startup() - logger.info("Agent %s startup completed", agent_name) - except Exception as e: - logger.error("Agent %s startup failed: %s", agent_name, e, exc_info=True) - raise + await self._start_component("Agent", registry.get_component(agent_name), agent_name) # User REST APIs. Schedulers are excluded because SchedulerBase extends # RestApiBase for its trigger route, so every scheduler is in this list *and* in @@ -1205,49 +1317,19 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: # be stopped (#43). Their routers are still mounted from get_rest_apis() in # _build_rest_endpoints, which is where that inheritance is wanted. for rest_api in self._lifecycle_rest_apis(registry): - try: - await rest_api.on_startup() - logger.info("REST API %s startup completed", rest_api.name) - except Exception as e: - logger.error("REST API %s startup failed: %s", rest_api.name, e, exc_info=True) - raise + await self._start_component("REST API", rest_api, rest_api.name) # Schedulers for scheduler in registry.get_schedulers(): - try: - await scheduler.on_startup() - logger.info("Scheduler %s startup completed", scheduler.name) - except Exception as e: - logger.error("Scheduler %s startup failed: %s", scheduler.name, e, exc_info=True) - raise + await self._start_component("Scheduler", scheduler, scheduler.name) # Eventing components (one Dapr / NATS endpoint per agent that consumes) for eventing_component in self._eventing_components: - try: - await eventing_component.on_startup() - logger.info("Eventing component for namespace '%s' startup completed", eventing_component.namespace or ROOT_LABEL) - except Exception as e: - logger.error( - "Eventing component for namespace '%s' startup failed: %s", - eventing_component.namespace or ROOT_LABEL, - e, - exc_info=True, - ) - raise + await self._start_component("Eventing component", eventing_component, eventing_component.namespace or ROOT_LABEL) # Routerless lifecycle components (e.g. SessionsBus). for lifecycle_component in self._lifecycle_components: - try: - await lifecycle_component.on_startup() - logger.info("Lifecycle component %s startup completed", type(lifecycle_component).__name__) - except Exception as e: - logger.error( - "Lifecycle component %s startup failed: %s", - type(lifecycle_component).__name__, - e, - exc_info=True, - ) - raise + await self._start_component("Lifecycle component", lifecycle_component, type(lifecycle_component).__name__) logger.info("Application startup completed") yield @@ -1319,6 +1401,8 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: if self._actuator_api is not None: await self._actuator_api.on_shutdown() + await self._loop_watchdog.stop() + # Last, and after every on_shutdown: a component may well run its final blocking # work there. The pools hold non-daemon threads, so leaving them running keeps the # interpreter alive past the point the container was asked to stop. diff --git a/src/blueprint/agents/clients/io/dapr_client.py b/src/blueprint/agents/clients/io/dapr_client.py index a5fa06b0..393b5be8 100644 --- a/src/blueprint/agents/clients/io/dapr_client.py +++ b/src/blueprint/agents/clients/io/dapr_client.py @@ -9,7 +9,7 @@ import httpx -from ...component.namespace import ROOT_NAMESPACE +from ...component.namespace import ROOT_LABEL, ROOT_NAMESPACE from ...models.api import ComponentHealth from ...models.events import CloudEvent from .io_client_base import IOClientBase @@ -190,11 +190,17 @@ async def _start_with_retry(self) -> None: await asyncio.sleep(delay) def _on_retry_done(self, task: asyncio.Task[None]) -> None: + """Report a retry task that gave up, naming the agent whose transport it was (C7).""" 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) + logger.error( + "Agent '%s' permanently failed to reach its Dapr sidecar after exhausting retries: %s", + self.namespace or ROOT_LABEL, + exc, + exc_info=exc, + ) async def _connect_and_subscribe(self) -> None: """Connect the HTTP client and verify the Dapr sidecar is reachable.""" diff --git a/src/blueprint/agents/clients/io/io_client_base.py b/src/blueprint/agents/clients/io/io_client_base.py index 8101fadd..1a795ce5 100644 --- a/src/blueprint/agents/clients/io/io_client_base.py +++ b/src/blueprint/agents/clients/io/io_client_base.py @@ -47,6 +47,41 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: ValueError: if the namespace is not a legal namespace. """ super().__init__(namespace=namespace) + self._consumption_paused = False + + # ------------------------------------------------------------------ + # C4 -- a degraded agent stops consuming + # ------------------------------------------------------------------ + + @property + def consumption_paused(self) -> bool: + """Whether this agent has been taken off its topics because it is degraded. + + Readiness gates HTTP only: a pod removed from service rotation still holds its + subscriptions and still consumes, so for an event-driven agent the probe alone is + cosmetic (C4). This flag is what the transports and the Dapr fan-out read to stop + taking work while the agent cannot do it. + """ + return self._consumption_paused + + async def pause_consumption(self) -> None: + """Stop taking events for this agent, leaving the connection open. + + **Paused, not closed.** Spec sec. 3's C4 describes this as closing the namespace's + client, and closing it would satisfy the letter of it -- but a closed client reports + itself unhealthy for ever, so the agent that triggered the pause could never be seen to + recover and the pause would be a one-way latch on a transient fault. Keeping the + connection also keeps publishing available, which matters because an agent that has + stopped consuming may still need to report that it has. + + Overridden by a transport that can actually stop deliveries. The base implementation + records the state, which is what a push transport reads at its delivery edge. + """ + self._consumption_paused = True + + async def resume_consumption(self) -> None: + """Start taking events again after the agent's health checks pass once more.""" + self._consumption_paused = False TOPIC_TRANSPORTS = ("dapr", "nats") diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 0474cd74..63ada1fd 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -4,11 +4,10 @@ import contextlib import json import logging -import os import re -import socket from collections.abc import Awaitable, Callable from dataclasses import dataclass +from functools import cached_property from typing import Any import nats @@ -16,8 +15,11 @@ from nats.js import api as js_api from nats.js.client import JetStreamContext from nats.js.errors import NotFoundError +from opentelemetry.metrics import Counter -from ...component.namespace import ROOT_LABEL, ROOT_NAMESPACE, display_segment +from ...component.namespace import ROOT_LABEL, ROOT_NAMESPACE +from ...deployment import deployment_group, pod_identity +from ...io.telemetry.providers import agent_meter from ...models.api import ComponentHealth from ...models.errors import DeliveryDisposition, disposition_for from ...models.events import CloudEvent @@ -25,56 +27,17 @@ logger = logging.getLogger(__name__) -UNGROUPED_LABEL = "" -"""Stands in for an unset ``BLUEPRINT_GROUP`` in a connection name, so its three positions stay filled. +DEAD_LETTERED_COUNTER = "blueprint.events.dead_lettered" +"""Events the framework gave up on, whether or not their payload was kept. -Bracketed for the same reason as ``ROOT_LABEL``: ``display_segment`` strips brackets from every -environment-supplied segment, so no real group can produce this string and "not deployed as part of -a group" cannot be confused with a group that happens to be called ``ungrouped``. +Dead-lettering was logged and counted nowhere, so "how many messages did we give up on today" +could not be answered from metrics -- and a dead letter is the one delivery outcome that has +no other trace in the running system: it is not a retry that eventually succeeds, and it is +not an error a caller sees. ``reason`` separates a payload that was rejected as unprocessable +from one whose redeliveries ran out, and ``kept`` says whether the payload survived, because a +deployment with no dead-letter subject configured is losing them. """ -UNKNOWN_POD_LABEL = "" -"""Stands in when neither the environment nor the host can say which pod this is.""" - - -def _deployment_group() -> str: - """Return the deployment group this process was started as, or a placeholder. - - Read straight from the environment rather than through ``Config``: group composition - decides which agents get a ``Config`` at all, so it is resolved before Dynaconf exists - and carries the ``BLUEPRINT_`` prefix rather than Dynaconf's (spec sec. 5.1). The - group loader that will own this variable arrives with the group configuration; until - then an unset value simply means "not deployed as part of a group". - - The group is deployment identity, so it belongs in the connection name and nowhere - near the queue group or the durable (C1). - - Passed through ``display_segment`` because this value is owned by the deployment, not by - the framework: it keeps a group called ``a.b`` from turning a three-segment connection name - into four, and keeps any group from forging a placeholder. - """ - return display_segment(os.environ.get("BLUEPRINT_GROUP", ""), UNGROUPED_LABEL) - - -def _pod_identity() -> str: - """Return the replica this process runs in, for the connection name only. - - ``POD_NAME`` is the Kubernetes downward-API convention and is preferred because a - deployment can set it explicitly; ``HOSTNAME`` is what the kubelet sets anyway and is - the pod name in practice; the host name covers plain Docker and local runs. - - Sanitised on the same terms as the group: a host name is frequently an FQDN, and its dots - would otherwise split one segment into several. - """ - for variable in ("POD_NAME", "HOSTNAME"): - value = os.environ.get(variable, "").strip() - if value: - return display_segment(value, UNKNOWN_POD_LABEL) - try: - return display_segment(socket.gethostname(), UNKNOWN_POD_LABEL) - except OSError: - return UNKNOWN_POD_LABEL - @dataclass(frozen=True) class ConsumerTuning: @@ -197,6 +160,21 @@ def subscriptions_ready(self) -> bool: """``True`` once all managed subscriptions are active.""" return self._subscriptions_ready + @cached_property + def _dead_lettered(self) -> Counter: + """This agent's dead-letter counter, created on first use rather than at construction. + + Cached rather than eager for the same reason ``Component.tracer`` is: a client is + constructed by ``build()``, and the per-agent meter providers do not exist until the + lifespan configures telemetry. An instrument created in ``__init__`` would be bound to + the no-op global meter for the life of the process. + """ + return agent_meter(self.namespace, __name__).create_counter( + name=DEAD_LETTERED_COUNTER, + description="Events this agent gave up on after exhausting redelivery or rejecting the payload", + unit="{event}", + ) + @property def queue_group(self) -> str: """Queue group joined by this client's subscriptions; ``""`` before ``subscribe()``.""" @@ -472,7 +450,7 @@ def _resolve_connection_name(self) -> str: stored anywhere those two are resolved from. """ namespace = self.namespace or ROOT_LABEL - return f"{namespace}.{_deployment_group()}.{_pod_identity()}" + return f"{namespace}.{deployment_group()}.{pod_identity()}" # ------------------------------------------------------------------ # Connection @@ -514,6 +492,53 @@ async def connect(self) -> None: logger.error("Failed to connect to NATS: %s", str(e)) raise + async def pause_consumption(self) -> None: + """Drain this agent's subscriptions so its events redeliver elsewhere (C4). + + Drained rather than unsubscribed, for the same reason shutdown drains: a drain stops + new deliveries while letting the ones already in the client's buffer reach their + handler and be acknowledged over the connection that delivered them. An unsubscribe + strands those, and every one of them redelivers. + + The connection stays open. See :meth:`IOClientBase.pause_consumption` for why closing + it would make the pause permanent, and :meth:`health_check` for the other half of that. + """ + if self._consumption_paused: + return + self._consumption_paused = True + self._subscriptions_ready = False + if self._nats_client is not None: + timeout = float(self.config.get("event_client_drain_timeout", 30.0)) + deadline = asyncio.get_running_loop().time() + timeout + await self._drain_subscriptions(deadline) + await self._await_inflight(deadline) + logger.error( + "Agent '%s' stopped consuming: its subscriptions are drained while it is degraded, so its events " + "redeliver to a healthy replica", + self.namespace or ROOT_LABEL, + ) + + async def resume_consumption(self) -> None: + """Re-subscribe this agent's topics after its health checks pass again. + + Nothing is retried here: a failure to re-subscribe leaves the client paused, and the + next health poll finds the agent healthy again and calls this again. That is the whole + retry, and it is bounded by the poll interval rather than by a loop of its own. + """ + if not self._consumption_paused: + return + self._consumption_paused = False + if not self._subscriptions_managed or self._nats_client is None: + return + try: + await self._subscribe_all() + except Exception as exc: + self._consumption_paused = True + logger.error("Agent '%s' could not resume consuming: %s", self.namespace or ROOT_LABEL, exc, exc_info=True) + return + self._subscriptions_ready = True + logger.info("Agent '%s' resumed consuming: %d subscription(s) restored", self.namespace or ROOT_LABEL, len(self._subscriptions)) + async def close(self) -> None: """Stop consuming, let in-flight handlers finish, then close the connection. @@ -642,9 +667,18 @@ async def publish(self, topic: str, event: CloudEvent[Any], routing_key: str | N # ------------------------------------------------------------------ async def health_check(self) -> ComponentHealth: - """Return healthy only when connected and all managed subscriptions are active.""" + """Return healthy only when connected and all managed subscriptions are active. + + **A paused client reports healthy.** The pause is a consequence of the agent being + degraded (C4), not a cause of it, and the check that actually failed is still in the + readiness payload saying so. Reporting the pause as unhealthy would make it + self-sustaining: the agent could never be seen to recover, so consumption would never + resume, and a transient Redis outage would take the agent off its topics permanently. + """ if not self._is_connected(): return ComponentHealth(status="unhealthy", message="NATS client not connected") + if self._consumption_paused: + return ComponentHealth(status="healthy", message="connected; consumption paused while this agent is degraded") if self._subscriptions_managed and not self._subscriptions_ready: return ComponentHealth(status="unhealthy", message="connected but subscriptions not yet established") server_info = self._nats_client.connected_url # type: ignore[union-attr] @@ -674,11 +708,22 @@ async def _start_with_retry(self) -> None: await asyncio.sleep(delay) def _on_retry_done(self, task: asyncio.Task[None]) -> None: + """Report a retry task that gave up, naming the agent whose transport it was (C7). + + The agent is in the message because this is the one record that a namespace has + stopped consuming while the pod stays healthy: the task is detached, so nothing + awaits it, and without this the failure is a task exception nobody retrieves. + """ if task.cancelled(): return exc = task.exception() if exc is not None: - logger.error("NATSClient permanently failed to connect after exhausting retries: %s", exc, exc_info=exc) + logger.error( + "Agent '%s' permanently failed to connect to NATS after exhausting retries: %s", + self.namespace or ROOT_LABEL, + exc, + exc_info=exc, + ) async def _connect_and_subscribe(self) -> None: await self.connect() @@ -991,6 +1036,7 @@ async def _dead_letter(self, msg: Any, disposition: DeliveryDisposition, topic: reason = "deliveries-exhausted" if disposition is DeliveryDisposition.NAK else "terminal-failure" if not subject: + self._count_dead_letter(reason, kept=False) logger.warning( "Dropping event %s from topic '%s' after %s delivery attempt(s) (%s): no dead-letter " "subject is configured, so its payload is lost. Set 'nats_dead_letter_subject' to keep it.", @@ -1012,6 +1058,7 @@ async def _dead_letter(self, msg: Any, disposition: DeliveryDisposition, topic: try: await self._nats_client.jetstream().publish(subject, msg.data, headers=headers) # type: ignore[union-attr] except Exception as exc: + self._count_dead_letter(reason, kept=False) logger.error( "Could not move event %s from topic '%s' to dead-letter subject '%s' (%s); its payload is lost", event_id or "", @@ -1021,6 +1068,7 @@ async def _dead_letter(self, msg: Any, disposition: DeliveryDisposition, topic: ) return + self._count_dead_letter(reason, kept=True) logger.warning( "Moved event %s from topic '%s' to dead-letter subject '%s' after %s delivery attempt(s) (%s)", event_id or "", @@ -1030,6 +1078,20 @@ async def _dead_letter(self, msg: Any, disposition: DeliveryDisposition, topic: reason, ) + def _count_dead_letter(self, reason: str, *, kept: bool) -> None: + """Record one event this agent gave up on. + + Counted once per event, where the outcome is known, rather than once on entry: a + publish that fails has still lost the payload, and counting on entry and again on + failure would report two dead letters for one message. + + Args: + reason: ``deliveries-exhausted`` or ``terminal-failure``. + kept: Whether the payload reached the dead-letter subject. ``False`` is what tells a + deployment with no subject configured that it is losing them. + """ + self._dead_lettered.add(1, {"agent": self.namespace or ROOT_LABEL, "reason": reason, "kept": kept}) + # ------------------------------------------------------------------ # Internal — reconnect callbacks # ------------------------------------------------------------------ @@ -1042,6 +1104,12 @@ async def _on_reconnected(self) -> None: logger.info("NATSClient reconnected") if not self._subscriptions_managed: return + if self._consumption_paused: + # A reconnect must not undo a pause. Without this the broker dropping and + # restoring the connection would silently resubscribe a degraded agent, and C4 + # would hold only until the next network blip. + logger.info("Agent '%s' stays paused after the reconnect; it is still degraded", self.namespace or ROOT_LABEL) + return if self._use_jetstream and self._topic_callbacks: # JetStream durable consumers do not survive reconnects; re-subscribe manually. # Core NATS re-subscribes automatically via the client library. diff --git a/src/blueprint/agents/component/component.py b/src/blueprint/agents/component/component.py index 2559e651..71df5d43 100644 --- a/src/blueprint/agents/component/component.py +++ b/src/blueprint/agents/component/component.py @@ -20,8 +20,9 @@ from opentelemetry import trace from ..config import Config +from ..io.telemetry.providers import agent_tracer from ..utils import camel_to_snake -from .namespace import ROOT_NAMESPACE, current_namespace, qualified_component_name, validate_namespace +from .namespace import ROOT_LABEL, ROOT_NAMESPACE, current_namespace, qualified_component_name, validate_namespace if TYPE_CHECKING: from .registry import Registry @@ -261,8 +262,21 @@ def executor(self) -> ThreadPoolExecutor: @cached_property def tracer(self) -> trace.Tracer: - """OTel tracer named after the concrete class.""" - return trace.get_tracer(type(self).__qualname__) + """OTel tracer named after the concrete class, on **this agent's** provider (C2). + + The provider decides the ``service.name`` a span is exported under, so a component of + agent ``orders`` must not record on the root's: its spans would arrive under the group's + service name, and a dashboard keyed on the agent would lose them the day the agent was + grouped. :func:`agent_tracer` resolves the namespace's provider and falls back to the + global one, which is what a root component and an application with telemetry disabled + both get. + + Cached, and therefore resolved at first use rather than at construction -- which is the + only reason this works: components are constructed by ``build()``, and the providers do + not exist until the lifespan's ``configure_tracing`` call, which runs before anything + else in startup. + """ + return agent_tracer(self._namespace, type(self).__qualname__) @abstractmethod async def on_startup(self) -> None: @@ -311,6 +325,12 @@ def traced(*extract: str) -> Callable[..., Any]: Span name is auto-prefixed with the component's name: ``{self.name}.{method.__name__}`` + Every span carries ``agent`` -- the namespace of the component the method belongs to, or + ````. The provider already stamps ``service.name`` on the resource, so this is + redundant for a span that reaches an exporter; it is not redundant for the failure C7 cares + about, where a span is *in flight* when the process dies and the only record of whose work + it was is what the span itself carries. + Each name in ``extract`` refers to a parameter of the decorated method: - **CloudEvent-typed value** → stamped as ``event.type``, ``event.source``, @@ -363,6 +383,7 @@ async def async_wrapper(self: Component, *args: Any, **kwargs: Any) -> Any: span_name = f"{self.name}.{func.__name__}" with self.tracer.start_as_current_span(span_name) as span: if span.is_recording(): + span.set_attribute("agent", self._namespace or ROOT_LABEL) _stamp_from_args(span, self, args, kwargs) try: return await func(self, *args, **kwargs) @@ -378,6 +399,7 @@ def sync_wrapper(self: Component, *args: Any, **kwargs: Any) -> Any: span_name = f"{self.name}.{func.__name__}" with self.tracer.start_as_current_span(span_name) as span: if span.is_recording(): + span.set_attribute("agent", self._namespace or ROOT_LABEL) _stamp_from_args(span, self, args, kwargs) try: return func(self, *args, **kwargs) diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index eaee92c3..19645309 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -49,6 +49,7 @@ class ConfigError(Exception): "log_format", "suppress_noisy_loggers", "health_check_interval_seconds", + "readiness_policy", "dot_placeholder", "nats_stream_name", } @@ -56,8 +57,8 @@ class ConfigError(Exception): """Keys that describe the *process*, and that an agent's own settings file therefore cannot set. One process binds one port, loads one environment section, reads its environment through one -prefix, speaks one event bus and configures logging once, so all of those are read from the -group's configuration and never from an agent's scope. A copy under ``[]`` would be read +prefix, speaks one event bus, answers one readiness probe and configures logging once, so all of +those are read from the group's configuration and never from an agent's scope. A copy under ``[]`` would be read by nothing at all -- which is spec sec. 5.3's reason for refusing it, and it is why :meth:`Config.merge_agent_settings` drops these keys with a WARNING that names the agent, the key and the file rather than merging them where nothing will look. diff --git a/src/blueprint/agents/deployment.py b/src/blueprint/agents/deployment.py new file mode 100644 index 00000000..baf03e53 --- /dev/null +++ b/src/blueprint/agents/deployment.py @@ -0,0 +1,67 @@ +"""Where this process runs: the deployment group, and which replica this is. + +Two values, read straight from the environment, that describe the *deployment* rather than the +application. They are not configuration and are deliberately unreachable through ``Config`` +(C6): an agent that can read its group can be written to depend on it, and regrouping then +breaks it. See ``DEPLOYMENT_IDENTITY_KEYS`` in ``config/config.py`` for the other half of that +rule -- this module is where framework code reads them instead, and no agent can follow. + +They live here rather than in the one client that first needed them because two subsystems now +read the same two values and must agree on them: the NATS connection name (spec sec. 6) and the +telemetry resource (C2). Two copies would be two answers to "which pod is this" the day one of +them learned about a new environment variable. + +Both are passed through :func:`~blueprint.agents.component.namespace.display_segment`, because +these values are owned by the deployment and cannot be validated the way a namespace is: +rejecting a group name would fail a rollout over a display string. Sanitising is only safe +because nothing derives from them -- C1 forbids the queue group and the durable from reading +either -- so a mangled segment loses no information a consumer depends on. +""" + +import os +import socket + +from .component.namespace import display_segment + +UNGROUPED_LABEL = "" +"""Stands in for an unset ``BLUEPRINT_GROUP``, so every position that names a group stays filled. + +Bracketed for the same reason as ``ROOT_LABEL``: ``display_segment`` strips brackets from every +environment-supplied segment, so no real group can produce this string and "not deployed as part +of a group" cannot be confused with a group that happens to be called ``ungrouped``. +""" + +UNKNOWN_POD_LABEL = "" +"""Stands in when neither the environment nor the host can say which pod this is.""" + + +def deployment_group() -> str: + """Return the deployment group this process was started as, or :data:`UNGROUPED_LABEL`. + + Read straight from the environment rather than through ``Config``: group composition + decides which agents get a configuration view at all, so it cannot itself come from one. + + The group is deployment identity, so it belongs in the connection name and on the telemetry + resource, and nowhere near the queue group or the durable (C1). + """ + return display_segment(os.environ.get("BLUEPRINT_GROUP", ""), UNGROUPED_LABEL) + + +def pod_identity() -> str: + """Return the replica this process runs in, for attribution only. + + ``POD_NAME`` is the Kubernetes downward-API convention and is preferred because a deployment + can set it explicitly; ``HOSTNAME`` is what the kubelet sets anyway and is the pod name in + practice; the host name covers plain Docker and local runs. + + Sanitised on the same terms as the group: a host name is frequently an FQDN, and its dots + would otherwise split one segment into several. + """ + for variable in ("POD_NAME", "HOSTNAME"): + value = os.environ.get(variable, "").strip() + if value: + return display_segment(value, UNKNOWN_POD_LABEL) + try: + return display_segment(socket.gethostname(), UNKNOWN_POD_LABEL) + except OSError: + return UNKNOWN_POD_LABEL diff --git a/src/blueprint/agents/io/api/actuators/actuator_api.py b/src/blueprint/agents/io/api/actuators/actuator_api.py index 320fc36d..52182e90 100644 --- a/src/blueprint/agents/io/api/actuators/actuator_api.py +++ b/src/blueprint/agents/io/api/actuators/actuator_api.py @@ -13,13 +13,17 @@ from fastapi import HTTPException, status from opentelemetry import trace -from ....component.component import traced +from ....component.component import Component, traced +from ....component.namespace import ROOT_NAMESPACE +from ....component.registry import Registry from ....config import Config from ....models.api import LivenessResponse, ReadinessResponse from ....models.status import BuildStatus, EnvironmentStatus, LLMStatus, ServiceInfo, VLLMInfo from .health.health_cache import HealthCheckCache from ..rest_api_base import RestApiBase from .health.health_base import HealthCheckEntry +from .health.namespace_supervisor import NamespaceSupervisor +from .health.readiness_policy import CONFIG_KEY as READINESS_POLICY_KEY, ReadinessPolicy logger = logging.getLogger(__name__) @@ -42,16 +46,40 @@ class ActuatorApi(RestApiBase): """Encapsulates all actuator-related endpoints and logic.""" - def __init__(self) -> None: + def __init__(self, namespaces: Sequence[str] = (ROOT_NAMESPACE,), critical_agents: Sequence[str] = ()) -> None: + """Create the actuator, told which agents this process serves. + + Args: + namespaces: Every namespace the process serves, the root included. Needed before + the first health poll so that an agent with no checks of its own is still + supervised and still reports ``blueprint.namespace.up`` (C7). + critical_agents: The agents the group flagged critical, which is what + ``readiness_policy = "critical"`` reads (C3). The same flag that decides whether + a failed import stops the process (spec sec. 9.1), because it answers the same + question: can this deployment run without that agent. + """ super().__init__(should_register=False) self._health_cache: HealthCheckCache | None = None self._health_entries: list[HealthCheckEntry] = [] + self._namespaces: tuple[str, ...] = tuple(namespaces) + self._critical_agents: tuple[str, ...] = tuple(critical_agents) + self._supervisor: NamespaceSupervisor | None = None @property def health_entries(self) -> tuple[HealthCheckEntry, ...]: """Every check registered so far, in registration order.""" return tuple(self._health_entries) + @property + def supervisor(self) -> NamespaceSupervisor | None: + """Who decides whether each agent is serving; ``None`` before ``on_startup``. + + Public because the lifespan reaches it: spec sec. 9.1 requires a non-critical agent + whose ``on_startup`` raised to be marked down and to stop consuming, and that failure + happens outside any health check. + """ + return self._supervisor + def add_health_providers(self, providers: Sequence[HealthCheckEntry]) -> None: """Register health checks, adding to the ones already registered. @@ -88,8 +116,33 @@ def add_health_providers(self, providers: Sequence[HealthCheckEntry]) -> None: self._health_cache.set_health_entries(self._health_entries) async def on_startup(self) -> None: - """Start the health check cache.""" - self._health_cache = HealthCheckCache(check_interval_seconds=self.config.get("health_check_interval_seconds", 30)) + """Start the health check cache, under this deployment's readiness policy. + + The supervisor is built here rather than in ``build()`` because it creates + OpenTelemetry instruments, and the per-agent providers those belong to (C2) do not + exist until the lifespan has configured telemetry -- which it does immediately before + this runs. + + Raises: + ValueError: if ``readiness_policy`` names no policy. Refused rather than defaulted: + a misspelt value read as ``all`` would remove a whole group from rotation the + first time a non-critical agent wobbled, with nothing to say the key had not + taken effect. + """ + policy = ReadinessPolicy.parse(self.config.get(READINESS_POLICY_KEY, ReadinessPolicy.ALL.value)) + registry: Registry = Component.shared_registry # type: ignore[assignment] + self._supervisor = NamespaceSupervisor(registry, self._namespaces, critical=self._critical_agents) + logger.info( + "Readiness policy '%s' over %d namespace(s); critical: %s", + policy.value, + len(self._namespaces), + ", ".join(self._critical_agents) or "none flagged", + ) + self._health_cache = HealthCheckCache( + check_interval_seconds=self.config.get("health_check_interval_seconds", 30), + policy=policy, + supervisor=self._supervisor, + ) if self._health_entries: self._health_cache.set_health_entries(self._health_entries) await self._health_cache.start() @@ -148,7 +201,16 @@ async def readiness_probe(self) -> ReadinessResponse: # httpGet readiness probe (which only inspects the status code) sees # the failure and removes the pod from service rotation. if response.status != "UP": - logger.warning("Readiness probe failed: %s", response.components) + # The agents, not only the components: in a group the first question asked of a + # failing probe is whose failure took the pod out, and the payload's per-agent + # section is the only thing that answers it under a policy other than 'all'. + degraded = [name for name, agent in response.namespaces.items() if agent.status != "UP"] + logger.warning( + "Readiness probe failed under policy '%s'; degraded agent(s): %s; components: %s", + response.policy, + ", ".join(degraded) or "none reported", + response.components, + ) raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=response.model_dump(), diff --git a/src/blueprint/agents/io/api/actuators/health/health_cache.py b/src/blueprint/agents/io/api/actuators/health/health_cache.py index 17000d94..ac24cd96 100644 --- a/src/blueprint/agents/io/api/actuators/health/health_cache.py +++ b/src/blueprint/agents/io/api/actuators/health/health_cache.py @@ -8,8 +8,11 @@ from datetime import datetime from typing import TYPE_CHECKING, Any -from .....models.api import ComponentHealth, ReadinessResponse +from .....component.namespace import ROOT_LABEL +from .....models.api import ComponentHealth, NamespaceReadiness, ReadinessResponse from .health_base import HealthCheckEntry +from .namespace_supervisor import NamespaceSupervisor +from .readiness_policy import ReadinessPolicy if TYPE_CHECKING: from apscheduler.schedulers.asyncio import AsyncIOScheduler @@ -39,18 +42,29 @@ def __init__( self, check_interval_seconds: int = 30, initial_status: str = "UP", + *, + policy: ReadinessPolicy = ReadinessPolicy.ALL, + supervisor: NamespaceSupervisor | None = None, ) -> None: """Initialize the health check cache. Args: check_interval_seconds: How often to refresh health checks (default: 30s) initial_status: Initial status while first check runs (default: "UP") + policy: How a degraded agent affects the pod's readiness (C3). The default + reproduces what a single-agent application has always done. + supervisor: Told each agent's verdict after every poll, so it can emit the C7 + signal and stop a degraded agent consuming (C4). Optional so that a test of the + caching behaviour needs no metrics pipeline and no registry. """ self.check_interval_seconds = check_interval_seconds self._scheduler: AsyncIOScheduler | None = None + self._policy = policy + self._supervisor = supervisor self._cached_response: ReadinessResponse = ReadinessResponse( status=initial_status, components={}, + policy=policy.value, ) self._last_update: datetime = datetime.now() self._lock = asyncio.Lock() @@ -147,14 +161,15 @@ async def _run_health_checks(self) -> None: else: components[entry.key] = result - # Determine overall status - all_healthy = all(component.status == "healthy" for component in components.values()) - overall_status = "UP" if all_healthy else "DOWN" + namespace_status, namespaces = self._aggregate_by_agent(components) + overall_status = "UP" if self._policy.is_ready(namespace_status, self._critical_namespaces()) else "DOWN" # Update cache self._cached_response = ReadinessResponse( status=overall_status, components=components, + policy=self._policy.value, + namespaces=namespaces, ) self._last_update = datetime.now() @@ -164,9 +179,63 @@ async def _run_health_checks(self) -> None: self._last_update.isoformat(), ) + # Outside the lock. The supervisor pauses and resumes transports, which awaits a + # drain that can take seconds; holding the readiness lock across it would make + # every probe during a pause wait for it, and a probe that times out is read as a + # failure of the pod rather than of the one agent that is actually degraded. + if self._supervisor is not None: + await self._supervisor.observe(namespace_status) + except Exception as exc: # pragma: no cover logger.error("Unexpected error during health check refresh: %s", exc, exc_info=True) + def _critical_namespaces(self) -> frozenset[str]: + """The agents that gate readiness under the ``critical`` policy, or none known.""" + return self._supervisor.critical_namespaces if self._supervisor is not None else frozenset() + + def _aggregate_by_agent(self, components: dict[str, ComponentHealth]) -> tuple[dict[str, bool], dict[str, NamespaceReadiness]]: + """Reduce the individual check results to one verdict per agent. + + The agent comes from the entry, not from the key. ``HealthCheckEntry`` carries it as + data for exactly this reason: recovering it by splitting ``orders.cache:v2.sessions`` + on a separator would attribute that check to an agent called ``orders`` only by luck, + and to the wrong agent as soon as a name contained the separator -- a C7 violation + dressed as a string bug. + + Every supervised namespace appears in the result even when it registered no check at + all. An agent with nothing to check is up, and leaving it out would make ``any`` and + ``critical`` read a shorter list than the group actually has. + + Args: + components: This poll's results, keyed by entry key. + + Returns: + Whether each namespace passed, and the per-agent section of the readiness payload. + """ + supervised = set(self._supervisor.status) if self._supervisor is not None else set() + failing: dict[str, list[str]] = {namespace: [] for namespace in supervised} + + for entry in self._entries: + result = components.get(entry.key) + failing.setdefault(entry.namespace, []) + if result is not None and result.status != "healthy": + failing[entry.namespace].append(entry.key) + + critical = self._critical_namespaces() + namespace_status = {namespace: not keys for namespace, keys in failing.items()} + namespaces = { + (namespace or ROOT_LABEL): NamespaceReadiness( + status="UP" if not keys else "DOWN", + # The root is shared infrastructure, so it gates readiness under every policy + # -- see ReadinessPolicy. Reporting it as critical is what makes the payload + # explain the verdict rather than contradict it. + critical=not namespace or namespace in critical, + failing=keys, + ) + for namespace, keys in failing.items() + } + return namespace_status, namespaces + def get_cache_age_seconds(self) -> float: """Get the age of the cached health status in seconds. diff --git a/src/blueprint/agents/io/api/actuators/health/namespace_supervisor.py b/src/blueprint/agents/io/api/actuators/health/namespace_supervisor.py new file mode 100644 index 00000000..f09493ae --- /dev/null +++ b/src/blueprint/agents/io/api/actuators/health/namespace_supervisor.py @@ -0,0 +1,224 @@ +"""Whether each agent is serving, said out loud, and what happens when one is not (C3, C4, C7). + +Grouping removes the signal that used to be free. In a process per agent, an agent that stopped +working took its pod down with it, and the restart *was* the alert: somebody was paged, a +dashboard went red, and the blast radius told you whose it was. Twenty agents in one process have +none of that -- the pod stays up, the port stays bound, nineteen agents keep answering, and the +twentieth silently stops. So C7 makes attribution normative, and this class is where it is +produced. + +Three things follow from one state, and they are deliberately not three mechanisms: + +- **A signal.** ``blueprint.namespace.up`` is 0 for a degraded agent and an ERROR event is + emitted on the transition, carrying that agent's telemetry identity -- its name, its group and + its pod. This happens whatever the readiness policy says: the policy decides where traffic + goes, never who is woken. +- **A consequence.** A degraded agent stops consuming (C4), because readiness gates HTTP only. + A pod removed from service rotation still holds its subscriptions, so for an event-driven + agent the probe alone changes nothing at all -- events keep arriving at an agent that cannot + process them, and every one of them is lost or retried against the same broken replica. +- **A verdict.** :class:`~.readiness_policy.ReadinessPolicy` reads the same per-agent state to + decide the pod's readiness. + +**Down is latched only when something latched it.** A health-driven transition is reversible: +the checks pass again, the agent resumes, and the pause was a pause. :meth:`mark_down` is the +other kind -- a startup failure (spec sec. 9.1) that no health check knows about -- and it stays +until :meth:`clear_forced_down` releases it, because nothing that observes health could ever +discover that it was wrong. +""" + +import logging +from collections.abc import Callable, Collection, Iterable, Mapping, Sequence + +from opentelemetry.metrics import CallbackOptions, Observation + +from .....clients.io.io_client_base import IOClientBase +from .....component.namespace import ROOT_LABEL, ROOT_NAMESPACE +from .....component.registry import Registry +from .....deployment import deployment_group, pod_identity +from .....io.telemetry.providers import agent_meter + +logger = logging.getLogger(__name__) + +NAMESPACE_UP_GAUGE = "blueprint.namespace.up" +"""``1`` while an agent is serving, ``0`` once it is not. The C7 signal. + +Recorded on the agent's own meter provider, so it arrives with that agent's ``service.name`` +resource (C2) as well as the ``agent`` attribute -- a dashboard can group on either, and one of +them survives a collector that drops resource attributes. +""" + + +class NamespaceSupervisor: + """Tracks which agents are serving, reports it, and stops a degraded one consuming.""" + + def __init__(self, registry: Registry, namespaces: Sequence[str], *, critical: Collection[str] = ()) -> None: + """Start supervising the agents this process hosts. + + Args: + registry: The application's registry, used to reach an agent's transport clients + when it has to stop consuming. The application's own rather than a view: this + object acts on behalf of every agent, which is exactly the process-wide reach + C6 keeps away from agent code and grants to the framework. + namespaces: Every namespace this process serves, the root included. Supervised from + the start rather than discovered from the first health poll, so an agent with no + health checks of its own still reports ``blueprint.namespace.up = 1`` and is + visibly present rather than absent. + critical: The agents the group flagged critical, for the ``critical`` policy. + """ + self._registry = registry + self._critical = frozenset(critical) + self._up: dict[str, bool] = dict.fromkeys(namespaces, True) + self._forced_down: dict[str, str] = {} + self._group = deployment_group() + self._pod = pod_identity() + self._register_gauges() + + @property + def critical_namespaces(self) -> frozenset[str]: + """The agents that gate readiness under the ``critical`` policy.""" + return self._critical + + @property + def status(self) -> Mapping[str, bool]: + """Whether each supervised namespace is currently serving.""" + return dict(self._up) + + def is_up(self, namespace: str) -> bool: + """Whether ``namespace`` is currently serving. An unsupervised namespace counts as up.""" + return self._up.get(namespace, True) + + # ------------------------------------------------------------------ + # Signal + # ------------------------------------------------------------------ + + def _register_gauges(self) -> None: + """Create one observable gauge per namespace, on that namespace's own meter. + + One instrument per agent rather than one instrument with an ``agent`` attribute, + because the resource is what carries C2's identity and the resource belongs to the + provider: an instrument created on the root's meter would report every agent's value + under the group's ``service.name``, which is the exact thing regrouping must not change. + """ + for namespace in self._up: + meter = agent_meter(namespace, __name__) + label = namespace or ROOT_LABEL + meter.create_observable_gauge( + NAMESPACE_UP_GAUGE, + callbacks=[self._observe_gauge(namespace, label)], + description="1 while this agent is serving, 0 once it has stopped", + unit="1", + ) + + def _observe_gauge(self, namespace: str, label: str) -> Callable[[CallbackOptions], Iterable[Observation]]: + """Return the callback the metrics reader polls for ``namespace``. + + A closure over the namespace rather than a bound method taking one, because the + OpenTelemetry reader calls a callback with a single ``CallbackOptions`` argument and + offers no way to pass anything else. It runs on the reader's own thread, so it does no + more than read a dictionary. + """ + + def observe(_options: CallbackOptions) -> Iterable[Observation]: + return [Observation(1 if self._up.get(namespace, True) else 0, {"agent": label})] + + return observe + + # ------------------------------------------------------------------ + # State + # ------------------------------------------------------------------ + + async def observe(self, namespace_status: Mapping[str, bool]) -> None: + """Take one health poll's per-agent verdict and act on what changed. + + Only transitions are acted on. A namespace that has been down for an hour must not + re-emit its ERROR event on every poll -- that is how an alert becomes noise and stops + being read -- and must not re-pause a client that is already paused. + + Args: + namespace_status: ``True`` where every one of that agent's health checks passed. + A namespace this supervisor does not know about is added, so an agent whose + first health check appears after startup is still supervised. + """ + for namespace, healthy in namespace_status.items(): + await self._set(namespace, healthy and namespace not in self._forced_down, self._degraded_reason(namespace)) + + async def mark_down(self, namespace: str, reason: str) -> None: + """Take ``namespace`` out of service and keep it out until it is explicitly released. + + For the failures no health check can see: spec sec. 9.1's non-critical agent whose + ``on_startup`` raised. That agent's components may be perfectly able to answer a health + check while being unusable, so an observed-health signal would put it straight back into + service on the next poll. + + Args: + namespace: The agent to take out of service. + reason: Why, for the ERROR event and for the readiness payload. + """ + self._forced_down[namespace] = reason + await self._set(namespace, False, reason) + + async def clear_forced_down(self, namespace: str) -> None: + """Release a latch set by :meth:`mark_down`, letting health decide again.""" + self._forced_down.pop(namespace, None) + + def forced_down_reason(self, namespace: str) -> str | None: + """Why ``namespace`` was latched down, or ``None`` if it was not.""" + return self._forced_down.get(namespace) + + def _degraded_reason(self, namespace: str) -> str: + """The reason to report for a health-driven transition.""" + return self._forced_down.get(namespace) or "one or more of its health checks failed" + + async def _set(self, namespace: str, healthy: bool, reason: str) -> None: + """Record ``namespace``'s state and, if it changed, emit and act.""" + previous = self._up.get(namespace) + self._up[namespace] = healthy + if previous is None or previous == healthy: + return + + if healthy: + logger.info("Agent '%s' is serving again (group '%s', pod '%s')", namespace or ROOT_LABEL, self._group, self._pod) + await self._resume_consumption(namespace) + return + + # ERROR rather than WARNING, and unconditional: this is the alert that the pod restart + # used to be. Every value a dashboard keys on is in the line, because a grouped + # process's logs are the one place an agent's failure is attributable without one. + logger.error( + "Agent '%s' has stopped serving (group '%s', pod '%s'): %s", + namespace or ROOT_LABEL, + self._group, + self._pod, + reason, + ) + await self._pause_consumption(namespace) + + # ------------------------------------------------------------------ + # C4 -- consequence + # ------------------------------------------------------------------ + + async def _pause_consumption(self, namespace: str) -> None: + """Stop this agent taking events, so they redeliver to a replica that can serve them.""" + for client in self._clients(namespace): + try: + await client.pause_consumption() + except Exception as exc: # pragma: no cover - defensive + logger.error("Agent '%s' could not be paused: %s", namespace or ROOT_LABEL, exc, exc_info=True) + + async def _resume_consumption(self, namespace: str) -> None: + """Let this agent take events again.""" + for client in self._clients(namespace): + try: + await client.resume_consumption() + except Exception as exc: # pragma: no cover - defensive + logger.error("Agent '%s' could not resume consuming: %s", namespace or ROOT_LABEL, exc, exc_info=True) + + def _clients(self, namespace: str) -> list[IOClientBase]: + """This agent's transport clients, and nobody else's. + + The namespace is passed explicitly even for the root, where it looks redundant: on the + application's registry an *omitted* namespace means every namespace, so leaving it out + would pause every agent in the process the moment the root was degraded. + """ + return self._registry.get_io_clients(namespace=namespace or ROOT_NAMESPACE) diff --git a/src/blueprint/agents/io/api/actuators/health/readiness_policy.py b/src/blueprint/agents/io/api/actuators/health/readiness_policy.py new file mode 100644 index 00000000..5bc1ac24 --- /dev/null +++ b/src/blueprint/agents/io/api/actuators/health/readiness_policy.py @@ -0,0 +1,101 @@ +"""Which degraded agents take the pod out of service rotation (C3). + +Grouping changes what a readiness probe means. In a single-agent process the question "is this +pod ready" has one answer, because there is one agent; in a group of twenty, one agent's Redis +being unreachable would, under the old rule, remove nineteen healthy agents from rotation. That +is the blast radius grouping is supposed to remove, and the probe is where it comes back. + +So readiness is a policy, chosen by the deployment that knows what it is running: + +========== ===================================================================================== +``all`` **Default.** Any degraded namespace makes the pod not ready. Reproduces exactly what + a single-agent application has always done. +``critical`` Only namespaces the group flagged ``critical`` gate readiness. The same flag that + decides whether a failing import stops the process (spec sec. 9.1) -- an agent the + deployment said it would rather run without does not get to remove the others. +``any`` Ready while at least one agent is up. For a group whose members are independent and + whose traffic is routed per agent anyway. +========== ===================================================================================== + +**The root always gates, under every policy.** It is where a single-agent application's whole +world lives -- so that case must keep behaving as it does today, whatever the policy says -- and +in a grouped process it holds the shared infrastructure every agent depends on. A root that is +degraded is not a partial failure. + +**The probe decides where traffic goes; it does not decide who is woken.** A degraded namespace +is reported as ``blueprint.namespace.up = 0`` and an ERROR event whatever the policy (C3, C7), so +choosing ``critical`` or ``any`` suppresses a *routing* consequence and never a signal. +""" + +from collections.abc import Collection, Mapping +from enum import StrEnum + +from .....component.namespace import ROOT_NAMESPACE + +CONFIG_KEY = "readiness_policy" +"""The configuration key this is read from. Process-scope: one pod has one readiness probe.""" + + +class ReadinessPolicy(StrEnum): + """How a degraded namespace affects the pod's readiness probe.""" + + ALL = "all" + CRITICAL = "critical" + ANY = "any" + + @classmethod + def parse(cls, value: object) -> "ReadinessPolicy": + """Return the policy named by ``value``, or raise naming the three that exist. + + Raises rather than falling back to the default, because the two failures look identical + from outside the process and only one of them is safe: a misspelt ``critcal`` silently + read as ``all`` would remove a whole group from rotation the first time a non-critical + agent wobbled, and the operator who set the key would have no way to see that it had not + taken effect. + + Args: + value: The configured value, as it comes out of the settings tree. + + Returns: + The policy. + + Raises: + ValueError: if ``value`` is not one of the three policies. + """ + text = str(value or "").strip().lower() + try: + return cls(text) + except ValueError: + raise ValueError( + f"'{CONFIG_KEY}' is {value!r}, which is not a readiness policy. It must be one of " + f"{', '.join(repr(policy.value) for policy in cls)}." + ) from None + + def is_ready(self, namespace_status: Mapping[str, bool], critical_namespaces: Collection[str]) -> bool: + """Return whether the pod is ready, given each namespace's health. + + Args: + namespace_status: ``True`` where every one of that namespace's health checks passed. + The root (``""``) is expected to be present; a namespace with no checks at all + counts as up, because nothing about it can be failing. + critical_namespaces: The agents the group flagged critical. Read only by + :attr:`CRITICAL`. + + Returns: + Whether the readiness probe should answer ``UP``. + """ + if not namespace_status.get(ROOT_NAMESPACE, True): + return False + + agents = {namespace: healthy for namespace, healthy in namespace_status.items() if namespace != ROOT_NAMESPACE} + if not agents: + # A single-agent application: the root is the whole of it, and it is up. Every + # policy agrees here, which is what makes the key safe to set in a shared settings + # file that standalone projects also read. + return True + + if self is ReadinessPolicy.ALL: + return all(agents.values()) + if self is ReadinessPolicy.CRITICAL: + return all(healthy for namespace, healthy in agents.items() if namespace in critical_namespaces) + return any(agents.values()) diff --git a/src/blueprint/agents/io/api/eventing/dapr.py b/src/blueprint/agents/io/api/eventing/dapr.py index b46de40d..e60dbc2f 100644 --- a/src/blueprint/agents/io/api/eventing/dapr.py +++ b/src/blueprint/agents/io/api/eventing/dapr.py @@ -252,6 +252,16 @@ def _agents_for(self, topic: str) -> tuple[str, ...]: with_handlers = tuple(dict.fromkeys(namespace_of(handler) for handler in self.registry.get_event_handler())) return with_handlers or (ROOT_NAMESPACE,) + def _is_paused(self, namespace: str) -> bool: + """Whether ``namespace`` has been taken off its topics because it is degraded (C4). + + Read from that agent's own client rather than from any process-wide register of + degraded agents: the client is the per-agent object the supervisor pauses, and asking + it keeps the two transports answering the same question from the same state. An agent + with no client cannot be paused, and is not. + """ + return any(client.consumption_paused for client in self.registry.get_io_clients(namespace=namespace)) + @RestApiBase.post("/events/{topic}", tags=["dapr"]) async def publish(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[str, Any]: """Receive an event from the sidecar, offer it to every agent that wants it, and answer. @@ -278,6 +288,22 @@ async def publish(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[str, A reason: str | None = None for namespace in agents: + if self._is_paused(namespace): + # C4 under a push transport. NATS stops consuming by draining its + # subscriptions; the sidecar has no such notion -- it posts here whatever the + # application thinks -- so the equivalent is to nak without dispatching, + # which Dapr renders as RETRY and which redelivers the event to a replica + # whose agent is up. + dispositions.append(DeliveryDisposition.NAK) + if reason is None: + reason = f"agent '{namespace or ROOT_LABEL}' is degraded and is not consuming" + logger.warning( + "Event %s on topic '%s' was not offered to agent '%s': it is degraded and paused", + cloud_event.id, + topic, + namespace or ROOT_LABEL, + ) + continue try: await self._process_cloud_event(cloud_event, {"dapr_topic": topic}, topic, namespace=namespace) dispositions.append(DeliveryDisposition.ACK) diff --git a/src/blueprint/agents/io/api/eventing/sessions_bus.py b/src/blueprint/agents/io/api/eventing/sessions_bus.py index 2b85c0ed..186158f7 100644 --- a/src/blueprint/agents/io/api/eventing/sessions_bus.py +++ b/src/blueprint/agents/io/api/eventing/sessions_bus.py @@ -16,7 +16,7 @@ from opentelemetry import trace from ....component.component import Component -from ....component.namespace import ROOT_NAMESPACE +from ....component.namespace import ROOT_LABEL, ROOT_NAMESPACE from ....models.errors import InvalidEventError, RetryableHandlerError from ....models.events import GenericCloudEvent from ....models.sessions import JobNotification @@ -112,6 +112,7 @@ async def on_startup(self) -> None: self._semaphore = asyncio.Semaphore(self._max_concurrent_jobs) self._shutdown_event.clear() self._sse_task = asyncio.create_task(self._consume_sse_stream()) + self._sse_task.add_done_callback(self._report_task_failure) logger.info( "SessionsBus connected: agent_id=%s, capabilities=%s, max_concurrent=%d", @@ -263,6 +264,32 @@ def _spawn_tracked(self, coro: Coroutine[Any, Any, None]) -> None: task = asyncio.create_task(coro) self._inflight_tasks.add(task) task.add_done_callback(self._inflight_tasks.discard) + task.add_done_callback(self._report_task_failure) + + def _report_task_failure(self, task: asyncio.Task[None]) -> None: + """Log an exception that ended a detached task, naming the agent it belonged to (C7). + + Every task the framework starts carries one of these. Without it a task that raised + holds its exception until it is garbage-collected, and what reaches the log is asyncio's + own "Task exception was never retrieved" -- at an unpredictable time, with no agent on + it, and with nothing to say which of a group's agents stopped working. In a single + process per agent that was survivable because the pod told you; in a group it is + exactly the silent per-agent failure C7 exists to remove. + + Args: + task: The finished task. + """ + if task.cancelled(): + return + exc = task.exception() + if exc is None: + return + logger.error( + "A background task of agent '%s' ended with an exception: %s", + self.namespace or ROOT_LABEL, + exc, + exc_info=exc, + ) def _track_event_id(self, sse: ServerSentEvent) -> None: """Advance the resume cursor from a frame's ``id`` (server ids are monotonic ints).""" diff --git a/src/blueprint/agents/io/api/scheduling/scheduler.py b/src/blueprint/agents/io/api/scheduling/scheduler.py index f8d45d03..e50f3f16 100644 --- a/src/blueprint/agents/io/api/scheduling/scheduler.py +++ b/src/blueprint/agents/io/api/scheduling/scheduler.py @@ -40,16 +40,20 @@ async def tick(self) -> None: import logging import time from abc import abstractmethod +from collections.abc import Iterable from datetime import UTC, datetime from typing import Any from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.triggers.cron import CronTrigger +from opentelemetry.metrics import CallbackOptions, Observation from ....clients.io.io_client_base import TOPIC_TRANSPORTS, validate_subject_segment from ....component.component import traced +from ....component.namespace import ROOT_LABEL from ....handler.event_handler_base import EventHandlerBase from ....models.events import GenericCloudEvent +from ...telemetry.providers import agent_meter from ..rest_api_base import RestApiBase logger = logging.getLogger(__name__) @@ -62,6 +66,19 @@ async def tick(self) -> None: SCHEDULER_MODES = (SCHEDULER_MODE_EVENT, SCHEDULER_MODE_IN_PROCESS) +TICK_AGE_GAUGE = "blueprint.scheduler.tick_age_seconds" +"""Seconds since this scheduler last ticked, or ``-1`` before its first tick. + +A tick is counted as an ordinary event, so a ``CronJob`` that stopped publishing looks like +silence rather than a fault: nothing said "this scheduler has not ticked within two intervals". +Event mode trades a duplicated tick for a possibly missing one, and only the second failure was +invisible. The declared crontab is in the process and the last tick is knowable, so an alert can +be written against this without the framework having to interpret a crontab. + +``-1`` rather than a large age before the first tick, so "never ticked" and "ticked a long time +ago" are different values: a pod that has just started has not missed anything yet. +""" + TICK_CACHE_NAMESPACE = "scheduler_tick" """Cache namespace holding the per-tick claims, kept away from application data.""" @@ -184,7 +201,7 @@ async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) carries no ``event_type``, so nothing is published downstream. """ logger.info("Scheduler '%s' ticking from event '%s' on topic '%s'", self._scheduler.name, event.id, self._topic) - await self._scheduler.tick() + await self._scheduler.run_tick() return {"status": "ticked", "scheduler": self._scheduler.name} @@ -221,6 +238,8 @@ def __init__(self, crontab: str, *, topic: str | None = None) -> None: self._scheduler: AsyncIOScheduler | None = None self._started = False self._trigger_route_registered = False + # When this scheduler last ran its tick, for the freshness gauge. None until the first. + self._last_tick: float | None = None @abstractmethod async def tick(self) -> None: @@ -442,6 +461,7 @@ async def on_startup(self) -> None: logger.warning("Scheduler '%s' is already started; ignoring the repeated startup", self.name) return self._started = True + self._register_tick_gauge() # Normally already done by AppBuilder.build(); repeated here so a scheduler driven # without the builder still gets its handler and its route. @@ -478,6 +498,44 @@ async def on_startup(self) -> None: self._crontab, ) + def _register_tick_gauge(self) -> None: + """Export how long it has been since this scheduler ticked. + + Registered in ``on_startup`` rather than in the constructor, because the per-agent meter + providers do not exist until the lifespan configures telemetry -- an instrument created + at construction would be bound to the no-op global meter for the life of the process. + + Both modes report it. In-process mode is where a stopped timer is already visible as a + missing pod; event mode is where it is not, because a ``CronJob`` that stopped publishing + leaves a perfectly healthy process ticking never. + """ + name = self.name + + def observe(_options: CallbackOptions) -> Iterable[Observation]: + age = -1.0 if self._last_tick is None else max(0.0, time.time() - self._last_tick) + return [Observation(age, {"scheduler": name, "agent": self.namespace or ROOT_LABEL, "mode": self.scheduler_mode})] + + agent_meter(self.namespace, __name__).create_observable_gauge( + TICK_AGE_GAUGE, + callbacks=[observe], + description="Seconds since this scheduler last ticked; -1 before its first", + unit="s", + ) + + async def run_tick(self) -> None: + """Run the tick and record that it happened. + + Every path that ticks goes through here -- the in-process timer once it has won its + slot, the event handler, and the manual trigger -- so the freshness gauge means "this + scheduler did its work", not "one particular mechanism fired". + """ + try: + await self.tick() + finally: + # In `finally` because a tick that raised still happened: the gauge answers "is this + # scheduler being driven", and a failing tick is a different alert from a silent one. + self._last_tick = time.time() + async def on_shutdown(self) -> None: """Shut down APScheduler, waiting for any running tick to finish.""" if self._scheduler and self._scheduler.running: @@ -519,7 +577,7 @@ async def _claimed_tick(self) -> None: if not self._claim_tick_slot(): logger.debug("Scheduler '%s' did not win this tick; another replica is running it", self.name) return - await self.tick() + await self.run_tick() def _claim_tick_slot(self) -> bool: """Claim the current tick slot, reporting whether this replica may run it. @@ -558,5 +616,5 @@ async def _trigger_tick(self) -> dict[str, Any]: Status dictionary confirming the trigger. """ logger.info("Scheduler '%s' manually triggered via REST", self.name) - await self.tick() + await self.run_tick() return {"status": "triggered", "scheduler": self.name} diff --git a/src/blueprint/agents/io/telemetry/inflight.py b/src/blueprint/agents/io/telemetry/inflight.py new file mode 100644 index 00000000..1ce1edbc --- /dev/null +++ b/src/blueprint/agents/io/telemetry/inflight.py @@ -0,0 +1,94 @@ +"""How much work each agent has in flight, so a process-terminating failure is attributable (C7). + +Three failure classes take a whole group down and none of them raises anything a handler could +catch: the cgroup memory limit is breached and the kernel kills the process, a native extension +crashes without unwinding, or the event loop is blocked and nothing is an error at all. No +amount of exception handling changes which of those kill a group -- it only changes how often. + +What is left is attribution, and attribution has to be emitted *before* the failure, because +afterwards there is no process to emit it. So each agent reports how many dispatches it has in +progress. An OOM kill then has a last observation to be read against: the agent whose in-flight +count was climbing is the one to look at, and without this an OOM kill is indistinguishable +across a group's agents and the grouping dial cannot be turned in response to it. + +Counted around the handler chain rather than at a transport edge, so it covers both transports +and the REST dispatch path with one measurement, and so it means "work this agent is doing" +rather than "messages this agent's client has taken". +""" + +import logging +from collections.abc import Iterable, Iterator +from contextlib import contextmanager + +from opentelemetry.metrics import CallbackOptions, Observation + +from ...component.namespace import ROOT_LABEL +from .providers import agent_meter + +logger = logging.getLogger(__name__) + +IN_FLIGHT_GAUGE = "blueprint.namespace.inflight" +"""Dispatches an agent has in progress right now.""" + + +class InFlightRegister: + """Per-agent count of dispatches in progress, exported as an observable gauge.""" + + def __init__(self) -> None: + self._counts: dict[str, int] = {} + + def count(self, namespace: str) -> int: + """How many dispatches ``namespace`` has in progress.""" + return self._counts.get(namespace, 0) + + def namespaces(self) -> tuple[str, ...]: + """Every agent that has dispatched at least once, whether or not it is busy now.""" + return tuple(self._counts) + + def reset(self) -> None: + """Forget every count. For tests; the instruments themselves are not removable.""" + self._counts.clear() + + @contextmanager + def track(self, namespace: str) -> Iterator[None]: + """Count one dispatch for ``namespace`` for as long as the block runs. + + The instrument is created the first time an agent is seen rather than at startup, + because this is reached from the dispatch path and has no list of agents to iterate -- + and a first dispatch always happens long after the providers exist, which is the only + ordering requirement creating one has. + + Args: + namespace: The agent doing the work; ``""`` for the root. + + Yields: + Nothing; the count is ambient. + """ + if namespace not in self._counts: + self._counts[namespace] = 0 + self._register(namespace) + self._counts[namespace] += 1 + try: + yield + finally: + self._counts[namespace] -= 1 + + def _register(self, namespace: str) -> None: + """Create ``namespace``'s gauge on its own meter, so it carries that agent's resource.""" + label = namespace or ROOT_LABEL + + def observe(_options: CallbackOptions) -> Iterable[Observation]: + return [Observation(self._counts.get(namespace, 0), {"agent": label})] + + agent_meter(namespace, __name__).create_observable_gauge( + IN_FLIGHT_GAUGE, + callbacks=[observe], + description="Dispatches this agent has in progress", + unit="{dispatch}", + ) + logger.debug("In-flight gauge registered for agent '%s'", label) + + +IN_FLIGHT = InFlightRegister() +"""The process's register. One per process because the gauge is, and because the dispatch path +that reads it is reached from components that have no way to be handed one.""" diff --git a/src/blueprint/agents/io/telemetry/loop_watchdog.py b/src/blueprint/agents/io/telemetry/loop_watchdog.py new file mode 100644 index 00000000..35e7ca70 --- /dev/null +++ b/src/blueprint/agents/io/telemetry/loop_watchdog.py @@ -0,0 +1,159 @@ +"""Noticing that the event loop has been blocked, and saying which agent was working. + +The one group-wide failure class that is detectable from inside the process. A blocked loop is +not an error: no exception is raised, nothing is logged, the pod stays live, and every agent in +the group stops responding at once because there is one loop and they share it. Alone in a +process it shows up as latency in the one service that caused it; in a group it shows up as +latency in twenty services, nineteen of which did nothing wrong. + +Two mechanisms, because the two environments can afford different things: + +- **Development** turns on asyncio's own debug mode, which reports the exact callback that ran + too long, with its source location. It is the better diagnostic by far and it is too + expensive to leave on: debug mode wraps coroutine creation and keeps tracebacks for every + task. +- **Production** runs this watchdog instead. It sleeps for a known interval and measures how + much longer than that the sleep actually took; the excess is time the loop spent unable to + run anything. It cannot name the callback -- by the time it runs again, the callback has + returned -- so it names the agents that had work in flight, which is the set the culprit is + in. + +Naming candidates rather than the culprit is the honest shape here, and it is still the +difference between "the pod was slow" and "one of these two agents blocked the loop for four +seconds". Turning debug mode on in production to get the exact answer is available and +deliberate: set ``event_loop_debug`` and accept the cost. +""" + +import asyncio +import logging +from collections.abc import Mapping + +from ...component.namespace import ROOT_LABEL +from .inflight import IN_FLIGHT + +logger = logging.getLogger(__name__) + +WATCHDOG_ENABLED_KEY = "event_loop_watchdog_enabled" +WATCHDOG_INTERVAL_KEY = "event_loop_watchdog_interval_seconds" +BLOCK_THRESHOLD_KEY = "event_loop_block_threshold_seconds" +SLOW_CALLBACK_KEY = "event_loop_slow_callback_seconds" +DEBUG_KEY = "event_loop_debug" + +DEFAULT_INTERVAL_SECONDS = 1.0 +"""How often the watchdog wakes. Once a second costs one timer callback and one subtraction.""" + +DEFAULT_BLOCK_THRESHOLD_SECONDS = 1.0 +"""How much lag is worth reporting in production. + +A second is far above ordinary scheduling jitter and far below the point at which a probe times +out, so it catches a real block without reporting a busy loop as a broken one. +""" + +DEFAULT_SLOW_CALLBACK_SECONDS = 0.2 +"""asyncio's own threshold in development, where the exact callback is worth the overhead.""" + + +def configure_loop_debug(config: Mapping[str, object] | object, *, development: bool) -> bool: + """Turn on asyncio debug mode where it is wanted, and report whether it was turned on. + + Args: + config: The application's configuration, read with ``get``. + development: Whether this process is running in the development environment, which is + what makes the debug mode's cost acceptable by default. + + Returns: + Whether debug mode is now on, so the caller can skip the watchdog: with debug mode on, + asyncio reports the blocking callback itself and the watchdog would only add a vaguer + second line about the same event. + """ + getter = getattr(config, "get", None) + enabled = bool(getter(DEBUG_KEY, development)) if callable(getter) else development + if not enabled: + return False + + threshold = float(getter(SLOW_CALLBACK_KEY, DEFAULT_SLOW_CALLBACK_SECONDS)) if callable(getter) else DEFAULT_SLOW_CALLBACK_SECONDS + loop = asyncio.get_running_loop() + loop.set_debug(True) + loop.slow_callback_duration = threshold + logger.info("Event loop debug mode is on; a callback running longer than %.2fs will be reported by asyncio", threshold) + return True + + +class LoopWatchdog: + """Reports how long the event loop was unable to run anything, and who had work at the time.""" + + def __init__(self, interval_seconds: float = DEFAULT_INTERVAL_SECONDS, threshold_seconds: float = DEFAULT_BLOCK_THRESHOLD_SECONDS): + """Create the watchdog. + + Args: + interval_seconds: How often to wake and measure. + threshold_seconds: How much lag is reported. Lag is measured against the interval, + so this is genuinely "time the loop could not run", not "time since the last + check". + """ + self._interval = interval_seconds + self._threshold = threshold_seconds + self._task: asyncio.Task[None] | None = None + + @property + def running(self) -> bool: + """Whether the watchdog task is running.""" + return self._task is not None and not self._task.done() + + async def start(self) -> None: + """Start watching. A second call does nothing.""" + if self.running: + return + self._task = asyncio.create_task(self._watch()) + # C7 applies to this task like any other the framework starts: a watchdog that died + # silently would leave the process with no blocked-loop detection and no sign of it. + self._task.add_done_callback(self._report_failure) + logger.info("Event loop watchdog started: reporting a block longer than %.2fs", self._threshold) + + async def stop(self) -> None: + """Stop watching.""" + if self._task is None: + return + self._task.cancel() + try: + await self._task + except (asyncio.CancelledError, Exception): # noqa: B014 -- shutdown must not raise + pass + self._task = None + + async def _watch(self) -> None: + """Sleep, measure the overshoot, and report it if it is large enough.""" + loop = asyncio.get_running_loop() + while True: + before = loop.time() + await asyncio.sleep(self._interval) + lag = loop.time() - before - self._interval + if lag >= self._threshold: + self._report(lag) + + def _report(self, lag: float) -> None: + """Log the block, naming the agents that had work in flight when it happened. + + In flight *now*, which is a moment after the block rather than during it -- the + watchdog could not run while the loop was blocked, so there is no during. A handler + that blocked and then returned is therefore missed by the attribution while the block + itself is still reported, which is why the message says "had work in flight" rather + than naming a culprit. + """ + busy = [namespace or ROOT_LABEL for namespace in IN_FLIGHT.namespaces() if IN_FLIGHT.count(namespace)] + logger.error( + "The event loop was blocked for %.2fs, which stalls every agent in this process. Agents with work in " + "flight: %s. Turn on '%s' to have asyncio name the callback.", + lag, + ", ".join(busy) or "none", + DEBUG_KEY, + ) + + @staticmethod + def _report_failure(task: asyncio.Task[None]) -> None: + """Log an exception that ended the watchdog task (C7).""" + if task.cancelled(): + return + exc = task.exception() + if exc is not None: + logger.error("The event loop watchdog stopped with an exception: %s", exc, exc_info=exc) diff --git a/src/blueprint/agents/io/telemetry/providers.py b/src/blueprint/agents/io/telemetry/providers.py new file mode 100644 index 00000000..7e417a1f --- /dev/null +++ b/src/blueprint/agents/io/telemetry/providers.py @@ -0,0 +1,98 @@ +"""The per-agent tracer and meter providers, and how a component finds its own (C2). + +A leaf module on purpose. Every component reads this to get its own agent's tracer, and +``TelemetryManager`` writes it during startup -- so if the registry lived next to the manager, +``component.py`` would import the module that imports ``Config``, which imports the manager, +which imports ``component.namespace``. Nothing here imports anything from this framework, which +is what keeps that cycle from existing at all. + +It is also why a component does not hold a reference to the manager: the group's shape would +then be reachable from the object graph, and C6 forbids that. A component asks for "my +namespace's tracer" and gets one whether or not anything configured it. +""" + +from opentelemetry import metrics, trace +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.trace import TracerProvider + +_TRACER_PROVIDERS: dict[str, TracerProvider] = {} +"""The configured tracer provider per namespace, written once during startup.""" + +_METER_PROVIDERS: dict[str, MeterProvider] = {} +"""The configured meter provider per namespace, written once during startup.""" + + +def register_providers(namespace: str, tracer_provider: TracerProvider, meter_provider: MeterProvider) -> None: + """Record the two providers ``namespace`` records on. + + Args: + namespace: The agent they belong to; ``""`` for the root. + tracer_provider: The provider carrying that agent's resource. + meter_provider: The provider carrying that agent's resource. + """ + _TRACER_PROVIDERS[namespace] = tracer_provider + _METER_PROVIDERS[namespace] = meter_provider + + +def has_providers(namespace: str) -> bool: + """Whether ``namespace`` has already been configured.""" + return namespace in _TRACER_PROVIDERS + + +def tracer_provider(namespace: str) -> TracerProvider | None: + """The tracer provider configured for ``namespace``, or ``None`` if nothing configured one.""" + return _TRACER_PROVIDERS.get(namespace) + + +def meter_provider(namespace: str) -> MeterProvider | None: + """The meter provider configured for ``namespace``, or ``None`` if nothing configured one.""" + return _METER_PROVIDERS.get(namespace) + + +def agent_tracer(namespace: str, instrumentation_name: str) -> trace.Tracer: + """Return the tracer ``namespace`` should record spans on. + + Falls back to the global provider for a namespace nothing configured, which is every + namespace when OpenTelemetry is disabled and every namespace before startup has run. The + fallback is what keeps this safe to call unconditionally: a no-op tracer records nothing and + costs nothing, so callers never have to branch on whether telemetry is on. + + Args: + namespace: The agent asking; ``""`` for the root. + instrumentation_name: What is being instrumented, conventionally a class or module name. + """ + provider = _TRACER_PROVIDERS.get(namespace) + if provider is None: + return trace.get_tracer(instrumentation_name) + return provider.get_tracer(instrumentation_name) + + +def agent_meter(namespace: str, instrumentation_name: str) -> metrics.Meter: + """Return the meter ``namespace`` should record instruments on. + + Falls back to the global provider on the same terms as :func:`agent_tracer`. + + Args: + namespace: The agent asking; ``""`` for the root. + instrumentation_name: What is being instrumented, conventionally a class or module name. + """ + provider = _METER_PROVIDERS.get(namespace) + if provider is None: + return metrics.get_meter(instrumentation_name) + return provider.get_meter(instrumentation_name) + + +def configured_namespaces() -> tuple[str, ...]: + """The namespaces that have their own providers, for tests and diagnostics.""" + return tuple(_TRACER_PROVIDERS) + + +def reset_providers() -> None: + """Forget every configured provider. + + For tests. The global provider is deliberately not reset: the OpenTelemetry SDK refuses a + second ``set_tracer_provider`` and only logs about it, so nothing this function did could + make the next case's provider the global one anyway. + """ + _TRACER_PROVIDERS.clear() + _METER_PROVIDERS.clear() diff --git a/src/blueprint/agents/io/telemetry/telemetry.py b/src/blueprint/agents/io/telemetry/telemetry.py index 163b4227..a1ab73ab 100644 --- a/src/blueprint/agents/io/telemetry/telemetry.py +++ b/src/blueprint/agents/io/telemetry/telemetry.py @@ -1,16 +1,50 @@ -"""OpenTelemetry configuration and setup.""" +"""OpenTelemetry configuration and setup, with one identity per agent (C2). + +A grouped process hosts several agents, and a dashboard, an alert or an SLO keyed on +``service.name`` must not notice that. So this module does not configure *the* provider; it +configures **one provider per namespace**, each with its own ``Resource``: + +======================== ====================================================================== +``service.name`` The agent's name -- ``otel_service_name`` for the root namespace, so a + single-agent application's traces are identical to what it produced + before any of this existed. +``deployment.group`` Which group this pod runs, from the environment. Set by the framework + and readable through no supported API (C6). +``service.instance.id`` Which replica this is. +======================== ====================================================================== + +**The empty namespace is the one that must not regress.** Implemented naively -- one provider, +``service.name`` set to the group -- every existing dashboard would go dark on the day the +framework was upgraded, before anybody grouped anything. So the root is built first, from +``otel_service_name`` exactly as before, and it is the provider that stays global: every +module-level ``trace.get_tracer`` in the framework and in agent code keeps resolving through it. + +**One exporter and one span processor for the whole process.** A ``BatchSpanProcessor`` owns a +queue and a background thread, so a processor per agent would multiply both by the group size +for no gain -- the resource is attached to the span at creation, not at export. The same +processor object is therefore added to every provider. Metric readers cannot be shared the same +way: the SDK binds a reader to the provider that registered it, so each provider gets its own +reader over the one shared exporter. +""" import logging +from collections.abc import Sequence from typing import Any -from opentelemetry import trace +from opentelemetry import metrics, trace +from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader from opentelemetry.sdk.resources import Resource from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor +from ...component.namespace import ROOT_NAMESPACE +from ...deployment import deployment_group, pod_identity from ..io_base import IOBase +from .providers import has_providers, meter_provider, register_providers, tracer_provider logger = logging.getLogger(__name__) @@ -22,8 +56,14 @@ def __init__(self) -> None: # Do not add to component registry super().__init__(should_register=False) - def configure_tracing(self) -> None: - """Configure OpenTelemetry tracing using the provided settings.""" + def configure_tracing(self, namespaces: Sequence[str] = ()) -> None: + """Configure one tracer and meter provider per namespace, sharing one exporter. + + Args: + namespaces: The agents this process hosts. The root is configured whether or not it + appears here, because it is where a single-agent application's components live + and where the framework's own root components go. + """ if self.config is None: raise ValueError("TelemetryManager.configure_tracing requires a Config instance") @@ -36,26 +76,82 @@ def configure_tracing(self) -> None: logger.info("OpenTelemetry tracing is disabled") return - service_name = observability.otel_service_name - - resource = Resource.create({"service.name": service_name}) - tracer_provider = TracerProvider(resource=resource) - trace.set_tracer_provider(tracer_provider) - - exporters = self._build_exporters(observability) - if not exporters: + span_processors = [BatchSpanProcessor(exporter) for exporter in self._build_exporters(observability)] + if not span_processors: logger.warning("No trace exporters configured") return - - for exporter in exporters: - tracer_provider.add_span_processor(BatchSpanProcessor(exporter)) + metric_exporters = self._build_metric_exporters(observability) + + group = deployment_group() + pod = pod_identity() + # The root first and always: it is the provider that becomes global, and every + # module-level trace.get_tracer() in the framework resolves through it. + for namespace in (ROOT_NAMESPACE, *namespaces): + if has_providers(namespace): + continue + self._configure_namespace(namespace, observability.otel_service_name, group, pod, span_processors, metric_exporters) + + # The root's provider becomes the global one, so every module-level + # trace.get_tracer() and metrics.get_meter() -- in this framework and in any + # library -- keeps resolving exactly as it did before agents had identities. + root_tracers, root_meters = tracer_provider(ROOT_NAMESPACE), meter_provider(ROOT_NAMESPACE) + if root_tracers is not None and root_meters is not None: + trace.set_tracer_provider(root_tracers) + metrics.set_meter_provider(root_meters) self._setup_instrumentation() - logger.info("OpenTelemetry configured for service '%s'", service_name) except Exception as exc: # pragma: no cover - defensive logging logger.error("Failed to configure telemetry", exc_info=exc) + @staticmethod + def _configure_namespace( + namespace: str, + root_service_name: str, + group: str, + pod: str, + span_processors: Sequence[BatchSpanProcessor], + metric_exporters: Sequence[Any], + ) -> None: + """Build and record the two providers for one namespace. + + ``service.name`` is the agent's own name, which is the whole of C2: an agent moved + between groups keeps it, so a dashboard keyed on it cannot tell that the move happened. + The root is the exception and takes ``otel_service_name`` from configuration, because it + is what every single-agent application already reports. + + Args: + namespace: The agent to configure; ``""`` for the root. + root_service_name: ``otel_service_name``, used only for the root. + group: The deployment group, for ``deployment.group``. + pod: The replica, for ``service.instance.id``. + span_processors: The process's span processors, shared by every provider. + metric_exporters: The process's metric exporters, each wrapped in a reader of this + provider's own. + """ + service_name = root_service_name if namespace == ROOT_NAMESPACE else namespace + resource = Resource.create( + { + "service.name": service_name, + "deployment.group": group, + "service.instance.id": pod, + } + ) + + provider = TracerProvider(resource=resource) + for processor in span_processors: + # The same processor object on every provider: one queue and one export thread, + # whatever the group size. The resource travels on the span, not on the processor. + provider.add_span_processor(processor) + + # A reader cannot be shared -- the SDK binds its collect callback to the provider that + # registered it, so a shared one would only ever collect from the last provider built -- + # but the exporter behind it can be. + readers = [PeriodicExportingMetricReader(exporter) for exporter in metric_exporters] + register_providers(namespace, provider, MeterProvider(resource=resource, metric_readers=readers)) + + logger.info("OpenTelemetry configured for service '%s' in group '%s'", service_name, group) + def _setup_instrumentation(self) -> None: """Enable automatic instrumentation for supported libraries.""" @@ -86,6 +182,24 @@ def _build_exporters(self, observability: Any) -> list[Any]: return exporters + @staticmethod + def _build_metric_exporters(observability: Any) -> list[Any]: + """Return the metric exporters, of which none is a normal state rather than a failure. + + Unlike traces, an absent metric exporter is not a reason to configure nothing. The + per-namespace gauges C7 requires -- ``blueprint.namespace.up`` and the in-flight gauge -- + are recorded on these providers, and a provider with no reader still accepts them; they + simply go nowhere, which is the state every process without a metrics pipeline is in. + """ + otlp_endpoint = observability.otel_endpoint + if not otlp_endpoint: + return [] + try: + return [OTLPMetricExporter(endpoint=otlp_endpoint, insecure=True)] + except Exception as exc: + logger.warning("Failed to configure OTLP metric exporter: %s", exc) + return [] + async def on_startup(self) -> None: """Startup OpenTelemetry.""" diff --git a/src/blueprint/agents/models/api.py b/src/blueprint/agents/models/api.py index 91a1bf61..7e7bd8e3 100644 --- a/src/blueprint/agents/models/api.py +++ b/src/blueprint/agents/models/api.py @@ -181,6 +181,30 @@ class ComponentHealth(BaseModel): ) +class NamespaceReadiness(BaseModel): + """One agent's contribution to the readiness verdict. + + Present because ``readiness_policy`` makes the overall status no longer derivable from + ``components``: a pod can answer ``UP`` with a failing check on it, because the agent that + check belongs to was not flagged critical. Without this section an operator would see a + contradiction and no way to resolve it. + """ + + status: str = Field( + ..., + description="Whether every one of this agent's health checks passed.", + examples=["UP", "DOWN"], + ) + critical: bool = Field( + ..., + description="Whether this agent gates readiness under the 'critical' policy.", + ) + failing: list[str] = Field( + default_factory=list, + description="The entry keys of this agent's checks that are not healthy.", + ) + + class ReadinessResponse(BaseModel): """Response for the readiness probe, including downstream components.""" @@ -193,6 +217,15 @@ class ReadinessResponse(BaseModel): ..., description="Health status of individual components.", ) + policy: str = Field( + default="all", + description="The readiness policy in force, which decides how a degraded agent affects the overall status.", + examples=["all", "critical", "any"], + ) + namespaces: dict[str, NamespaceReadiness] = Field( + default_factory=dict, + description="Per-agent health, keyed by agent name ('' for the root namespace).", + ) model_config = ConfigDict( json_schema_extra={ @@ -208,6 +241,11 @@ class ReadinessResponse(BaseModel): "message": "Failed to connect to endpoint.", }, }, + "policy": "critical", + "namespaces": { + "": {"status": "UP", "critical": True, "failing": []}, + "orders": {"status": "DOWN", "critical": False, "failing": ["orders.cache"]}, + }, } } ) diff --git a/src/blueprint/agents/services/eventing/event_processing_service.py b/src/blueprint/agents/services/eventing/event_processing_service.py index 1a3f56e2..ada9c26b 100644 --- a/src/blueprint/agents/services/eventing/event_processing_service.py +++ b/src/blueprint/agents/services/eventing/event_processing_service.py @@ -9,6 +9,7 @@ from ...component.component import traced from ...component.namespace import ROOT_LABEL, ROOT_NAMESPACE, namespace_of from ...handler.handler_chain import RUNTIME_NAME_CONTEXT_KEY, HandlerChain +from ...io.telemetry.inflight import IN_FLIGHT from ...models import ProcessingResult, ProcessingStatus from ...models.events import GenericCloudEvent, HandlerResult, CloudEvent from ..service_base import ServiceBase @@ -119,7 +120,12 @@ async def process_event( request_id = str(uuid4()) context["request_id"] = request_id - trace.get_current_span().set_attribute("request_id", request_id) + span = trace.get_current_span() + span.set_attribute("request_id", request_id) + # The agent goes on the span as well as in the log line. A span that is still open when + # the process dies never reaches an exporter, so the resource that would have named its + # agent (C2) is never applied -- what is on the span itself is all a post-mortem has. + span.set_attribute("agent", namespace or ROOT_LABEL) # The caller's choice of runtime, put where the chain will look for it. This # parameter has existed since before there were agents to resolve and was only ever @@ -148,7 +154,11 @@ async def process_event( event = self._unwrap_dapr_event(event) try: - handler_result: Any | HandlerResult | list[HandlerResult] | None = await self._chain_for(namespace).process(event, context) + # Counted around the chain, not around the transport: this is the one place both + # transports and the REST path pass through, so one measurement covers all three + # and it means "work this agent is doing" rather than "messages it has taken". + with IN_FLIGHT.track(namespace): + handler_result: Any | HandlerResult | list[HandlerResult] | None = await self._chain_for(namespace).process(event, context) handler_results: list[HandlerResult] = self._extract_handler_results(handler_result) diff --git a/tests/unit/agents/app_builder/test_startup_failure_policy.py b/tests/unit/agents/app_builder/test_startup_failure_policy.py new file mode 100644 index 00000000..a3927182 --- /dev/null +++ b/tests/unit/agents/app_builder/test_startup_failure_policy.py @@ -0,0 +1,149 @@ +"""What a failing ``on_startup`` does to the rest of the group (spec sec. 9.1). + +There is no partial build -- one process, one ``build()`` -- so the ``critical`` flag is read +*before* an agent is wired rather than after an exception. A critical agent's failure still ends +the startup, which aborts the lifespan before the port is bound; a non-critical agent's failure +takes that agent out of service and lets the rest of the process start. + +Driven through the real lifespan against real components, because the interesting part is which +of the eight startup loops the failure came out of and what the actuator knew by then. +""" + +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import pytest +from fastapi import FastAPI + +from blueprint.agents.app_builder import AppBuilder +from blueprint.agents.component.namespace import namespace_scope +from blueprint.agents.config import Config +from blueprint.agents.io.telemetry.providers import reset_providers +from blueprint.agents.services.service_base import ServiceBase + + +class QuietService(ServiceBase): + """A service that starts without complaint.""" + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +class BrokenService(ServiceBase): + """A service whose ``on_startup`` raises, which is what spec sec. 9.1 is about.""" + + async def on_startup(self) -> None: + raise RuntimeError("its database is unreachable") + + async def on_shutdown(self) -> None: + pass + + +@pytest.fixture(autouse=True) +def _forget_providers() -> Iterator[None]: + reset_providers() + yield + reset_providers() + + +@pytest.fixture +def config(tmp_path: Path) -> Config: + """A group's configuration with no event bus, so nothing needs a broker to start.""" + settings = tmp_path / "settings.toml" + settings.write_text('[development]\napp_name = "group"\napp_port = 8000\napp_environment = "development"\n') + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + +def build(config: Config, *, critical: bool) -> tuple[FastAPI, AppBuilder]: + """One healthy agent and one whose service raises, hosted with the given flag. + + The builder comes back with the application because the supervisor is reached through the + actuator it created, and nothing mounted on a FastAPI application exposes it. + """ + builder = AppBuilder(config) + builder.host_agent("orders", critical=True) + builder.host_agent("billing", critical=critical) + with namespace_scope("orders"): + builder.with_service(QuietService) + with namespace_scope("billing"): + builder.with_service(BrokenService) + return builder.build(), builder + + +def supervisor_of(builder: AppBuilder) -> Any: + """The running supervisor, or an assertion if the actuator never started one.""" + actuator = builder._actuator_api + assert actuator is not None and actuator.supervisor is not None + return actuator.supervisor + + +class TestACriticalAgent: + async def test_its_failure_ends_the_startup(self, config: Config) -> None: + """Aborting the lifespan is what stops the port being bound, so Kubernetes crash-loops.""" + app, _ = build(config, critical=True) + with pytest.raises(RuntimeError, match="database is unreachable"): + async with app.router.lifespan_context(app): + pass + + async def test_the_root_is_critical_whatever_anyone_says(self, config: Config) -> None: + """It holds the shared infrastructure; there is no rest of the process without it.""" + builder = AppBuilder(config) + builder.with_service(BrokenService) + app = builder.build() + with pytest.raises(RuntimeError, match="database is unreachable"): + async with app.router.lifespan_context(app): + pass + + +class TestANonCriticalAgent: + async def test_the_process_starts_without_it(self, config: Config) -> None: + app, _ = build(config, critical=False) + async with app.router.lifespan_context(app): + pass + + async def test_it_is_taken_out_of_service(self, config: Config) -> None: + app, builder = build(config, critical=False) + async with app.router.lifespan_context(app): + supervisor = supervisor_of(builder) + assert supervisor.is_up("billing") is False + assert supervisor.is_up("orders") is True + + async def test_the_reason_names_the_component(self, config: Config) -> None: + app, builder = build(config, critical=False) + async with app.router.lifespan_context(app): + reason = supervisor_of(builder).forced_down_reason("billing") + assert reason is not None + assert "billing_broken_service" in reason + assert "database is unreachable" in reason + + async def test_being_down_is_latched_against_a_later_health_poll(self, config: Config) -> None: + """Its components can still answer a health check while the agent is unusable.""" + app, builder = build(config, critical=False) + async with app.router.lifespan_context(app): + supervisor = supervisor_of(builder) + await supervisor.observe({"billing": True}) + assert supervisor.is_up("billing") is False + + async def test_the_rest_of_the_group_is_untouched(self, config: Config) -> None: + app, builder = build(config, critical=False) + async with app.router.lifespan_context(app): + status = supervisor_of(builder).status + assert status["orders"] is True + assert status["billing"] is False + + +class TestTheCriticalSet: + def test_an_unflagged_agent_is_critical(self, config: Config) -> None: + builder = AppBuilder(config) + builder.host_agent("orders") + assert builder.critical_namespaces == ("orders",) + + def test_a_flag_of_false_keeps_it_out(self, config: Config) -> None: + builder = AppBuilder(config) + builder.host_agent("orders", critical=False) + assert builder.namespaces == ("orders",) + assert builder.critical_namespaces == () diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index 6d1535f3..e23d9c2d 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -1483,7 +1483,7 @@ def test_hostname_is_used_when_pod_name_is_absent(self, nats_client: NATSClient, def test_falls_back_to_the_host_name(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.delenv("POD_NAME", raising=False) monkeypatch.delenv("HOSTNAME", raising=False) - monkeypatch.setattr("blueprint.agents.clients.io.nats_client.socket.gethostname", lambda: "laptop") + monkeypatch.setattr("blueprint.agents.deployment.socket.gethostname", lambda: "laptop") assert nats_client._resolve_connection_name().endswith(".laptop") def test_unresolvable_host_still_yields_a_name(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: @@ -1493,7 +1493,7 @@ def test_unresolvable_host_still_yields_a_name(self, nats_client: NATSClient, mo def _raise() -> str: raise OSError("no host name") - monkeypatch.setattr("blueprint.agents.clients.io.nats_client.socket.gethostname", _raise) + monkeypatch.setattr("blueprint.agents.deployment.socket.gethostname", _raise) assert nats_client._resolve_connection_name().endswith(".") def test_a_dotted_group_cannot_add_a_segment(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: @@ -1542,3 +1542,87 @@ async def test_deployment_identity_never_reaches_the_consumer_identity( assert client.queue_group == "orders" assert "group-b" not in client._durable_for("orders.created") assert "pod-99" not in client._durable_for("orders.created") + + +class TestPausingADegradedAgent: + """C4: readiness gates HTTP only, so a degraded agent has to be taken off its topics.""" + + @pytest.fixture + def subscribed(self, nats_client: NATSClient, mock_nats_core: MagicMock) -> NATSClient: + """A connected client with one live subscription and one managed topic.""" + nats_client._nats_client = mock_nats_core + nats_client._client = mock_nats_core + nats_client._subscriptions_managed = True + nats_client._subscriptions_ready = True + subscription = MagicMock() + subscription.drain = AsyncMock() + nats_client._subscriptions = [subscription] + nats_client._topic_callbacks = {"orders.created": AsyncMock()} + return nats_client + + async def test_a_client_starts_unpaused(self, nats_client: NATSClient) -> None: + assert nats_client.consumption_paused is False + + async def test_pausing_drains_the_subscriptions(self, subscribed: NATSClient) -> None: + """Drained, not unsubscribed: a queued message still reaches its handler and acks.""" + subscription = subscribed._subscriptions[0] + await subscribed.pause_consumption() + subscription.drain.assert_awaited_once() + assert subscribed.consumption_paused is True + assert subscribed.subscriptions_ready is False + + async def test_pausing_leaves_the_connection_open(self, subscribed: NATSClient, mock_nats_core: MagicMock) -> None: + """A closed client reports itself unhealthy for ever, so the pause could never lift.""" + await subscribed.pause_consumption() + mock_nats_core.close.assert_not_called() + assert subscribed._nats_client is mock_nats_core + + async def test_pausing_twice_drains_once(self, subscribed: NATSClient) -> None: + subscription = subscribed._subscriptions[0] + await subscribed.pause_consumption() + await subscribed.pause_consumption() + subscription.drain.assert_awaited_once() + + async def test_the_pause_is_reported_with_its_agent(self, mock_config: MagicMock, caplog: pytest.LogCaptureFixture) -> None: + client = _namespaced_client(mock_config, "orders") + with caplog.at_level(logging.ERROR): + await client.pause_consumption() + assert "orders" in caplog.text + assert "stopped consuming" in caplog.text + + async def test_a_paused_client_reports_healthy(self, subscribed: NATSClient) -> None: + """The pause is a consequence of degradation, not a cause; latching it would be permanent.""" + await subscribed.pause_consumption() + result = await subscribed.health_check() + assert result.status == "healthy" + assert "paused" in (result.message or "") + + async def test_resuming_resubscribes(self, subscribed: NATSClient) -> None: + await subscribed.pause_consumption() + with patch.object(subscribed, "_subscribe_all", new=AsyncMock()) as subscribe_all: + await subscribed.resume_consumption() + subscribe_all.assert_awaited_once() + assert subscribed.consumption_paused is False + assert subscribed.subscriptions_ready is True + + async def test_resuming_one_that_was_not_paused_does_nothing(self, subscribed: NATSClient) -> None: + with patch.object(subscribed, "_subscribe_all", new=AsyncMock()) as subscribe_all: + await subscribed.resume_consumption() + subscribe_all.assert_not_awaited() + + async def test_a_failed_resume_stays_paused(self, subscribed: NATSClient) -> None: + """The next health poll finds the agent healthy and calls this again; that is the retry.""" + await subscribed.pause_consumption() + with patch.object(subscribed, "_subscribe_all", new=AsyncMock(side_effect=RuntimeError("no"))): + await subscribed.resume_consumption() + assert subscribed.consumption_paused is True + assert subscribed.subscriptions_ready is False + + async def test_a_reconnect_does_not_undo_a_pause(self, subscribed: NATSClient) -> None: + """Otherwise C4 would hold only until the next network blip.""" + subscribed._use_jetstream = True + await subscribed.pause_consumption() + with patch.object(subscribed, "_subscribe_all", new=AsyncMock()) as subscribe_all: + await subscribed._on_reconnected() + subscribe_all.assert_not_awaited() + assert subscribed.subscriptions_ready is False diff --git a/tests/unit/agents/component/test_component.py b/tests/unit/agents/component/test_component.py index da5d78b2..a89b0dc6 100644 --- a/tests/unit/agents/component/test_component.py +++ b/tests/unit/agents/component/test_component.py @@ -296,6 +296,23 @@ async def test_extract_stamps_named_param(self, span_exporter: InMemorySpanExpor attrs = dict(spans[0].attributes or {}) assert attrs.get("topic") == "orders" + async def test_every_span_names_its_agent(self, span_exporter: InMemorySpanExporter) -> None: + """C7: a span in flight when the process dies never reaches an exporter, so the + resource that would have named its agent is never applied -- the span itself is all a + post-mortem has.""" + with namespace_scope("orders"): + comp = _AsyncTracedComp() + await comp.my_action() + + spans = span_exporter.get_finished_spans() + assert dict(spans[0].attributes or {}).get("agent") == "orders" + + def test_a_root_component_names_the_root(self, span_exporter: InMemorySpanExporter) -> None: + _SyncTracedComp().my_sync_action() + + spans = span_exporter.get_finished_spans() + assert dict(spans[0].attributes or {}).get("agent") == "" + # --------------------------------------------------------------------------- # traced() decorator — skips arg binding/stamping when span isn't recording diff --git a/tests/unit/agents/io/api/actuators/health/test_health_cache.py b/tests/unit/agents/io/api/actuators/health/test_health_cache.py index b72a5a04..4c34b807 100644 --- a/tests/unit/agents/io/api/actuators/health/test_health_cache.py +++ b/tests/unit/agents/io/api/actuators/health/test_health_cache.py @@ -7,6 +7,7 @@ from blueprint.agents.io.api.actuators.health.health_base import HealthCheckEntry from blueprint.agents.io.api.actuators.health.health_cache import HealthCheckCache +from blueprint.agents.io.api.actuators.health.readiness_policy import ReadinessPolicy from blueprint.agents.models.api import ComponentHealth @@ -197,3 +198,83 @@ async def test_a_failure_is_logged_with_its_agent(self, caplog: pytest.LogCaptur def test_the_root_agent_is_named_where_a_value_is_required(self) -> None: assert (_entry("db", "healthy").agent, _entry("db", "healthy", namespace="orders").agent) == ("", "orders") + + +class TestTheVerdictIsPerAgent: + """C3: the overall status is no longer a fold over every check, but a policy over agents.""" + + @staticmethod + def _supervisor(namespaces: list[str], critical: set[str]) -> MagicMock: + """A stand-in supervisor: the cache reads its namespaces and its critical set.""" + supervisor = MagicMock() + supervisor.status = dict.fromkeys(namespaces, True) + supervisor.critical_namespaces = frozenset(critical) + supervisor.observe = AsyncMock() + return supervisor + + @staticmethod + def _entries() -> list[HealthCheckEntry]: + return [ + _entry("cache", "healthy", namespace="orders"), + _entry("cache", "unhealthy", "redis is gone", namespace="billing"), + ] + + async def _run(self, policy: ReadinessPolicy, critical: set[str]) -> HealthCheckCache: + supervisor = self._supervisor(["", "orders", "billing"], critical) + cache = HealthCheckCache(policy=policy, supervisor=supervisor) + cache.set_health_entries(self._entries()) + await cache._run_health_checks() + return cache + + async def test_all_takes_the_pod_out_for_one_degraded_agent(self) -> None: + cache = await self._run(ReadinessPolicy.ALL, set()) + assert (await cache.get_health_status()).status == "DOWN" + + async def test_critical_keeps_the_pod_in_for_an_agent_nobody_flagged(self) -> None: + cache = await self._run(ReadinessPolicy.CRITICAL, {"orders"}) + assert (await cache.get_health_status()).status == "UP" + + async def test_the_payload_says_which_agent_is_down(self) -> None: + """A pod answering UP with a failing check in it has to explain itself.""" + cache = await self._run(ReadinessPolicy.CRITICAL, {"orders"}) + response = await cache.get_health_status() + assert response.policy == "critical" + assert response.namespaces["billing"].status == "DOWN" + assert response.namespaces["billing"].failing == ["billing.cache"] + assert response.namespaces["billing"].critical is False + assert response.namespaces["orders"].status == "UP" + + async def test_the_root_is_always_reported_as_critical(self) -> None: + cache = await self._run(ReadinessPolicy.CRITICAL, {"orders"}) + assert (await cache.get_health_status()).namespaces[""].critical is True + + async def test_an_agent_with_no_checks_is_still_in_the_payload(self) -> None: + """Leaving it out would make 'any' and 'critical' read a shorter list than the group has.""" + supervisor = self._supervisor(["", "orders", "quiet"], set()) + cache = HealthCheckCache(policy=ReadinessPolicy.ANY, supervisor=supervisor) + cache.set_health_entries([_entry("cache", "healthy", namespace="orders")]) + await cache._run_health_checks() + assert (await cache.get_health_status()).namespaces["quiet"].status == "UP" + + async def test_the_supervisor_is_told_every_agents_verdict(self) -> None: + """It is what emits the C7 signal and stops a degraded agent consuming.""" + supervisor = self._supervisor(["", "orders", "billing"], set()) + cache = HealthCheckCache(supervisor=supervisor) + cache.set_health_entries(self._entries()) + await cache._run_health_checks() + supervisor.observe.assert_awaited_once_with({"": True, "orders": True, "billing": False}) + + async def test_the_agent_comes_from_the_entry_not_from_the_key(self) -> None: + """Splitting 'orders.cache:v2.sessions' on a dot attributes it to the wrong agent.""" + supervisor = self._supervisor(["", "orders"], set()) + cache = HealthCheckCache(supervisor=supervisor) + cache.set_health_entries([_entry("cache:v2.sessions", "unhealthy", "gone", namespace="orders")]) + await cache._run_health_checks() + supervisor.observe.assert_awaited_once_with({"": True, "orders": False}) + + async def test_a_cache_with_no_supervisor_still_answers(self) -> None: + """Nothing about the caching behaviour depends on a metrics pipeline or a registry.""" + cache = HealthCheckCache() + cache.set_health_entries(self._entries()) + await cache._run_health_checks() + assert (await cache.get_health_status()).status == "DOWN" diff --git a/tests/unit/agents/io/api/actuators/health/test_namespace_supervisor.py b/tests/unit/agents/io/api/actuators/health/test_namespace_supervisor.py new file mode 100644 index 00000000..991f7bb0 --- /dev/null +++ b/tests/unit/agents/io/api/actuators/health/test_namespace_supervisor.py @@ -0,0 +1,133 @@ +"""What happens when one agent of a group stops serving (C3, C4, C7). + +The supervisor turns one piece of state -- is this agent serving -- into three things: the +signal (gauge plus ERROR event), the consequence (it stops consuming), and the input to the +readiness verdict. These cases cover the first two; the third is +``test_readiness_policy.py``. +""" + +import logging +from collections.abc import Iterator +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from blueprint.agents.io.api.actuators.health.namespace_supervisor import NamespaceSupervisor +from blueprint.agents.io.telemetry.providers import reset_providers + + +@pytest.fixture(autouse=True) +def _forget_providers() -> Iterator[None]: + """The gauges are created on module-level providers, which are process state.""" + reset_providers() + yield + reset_providers() + + +def _client() -> MagicMock: + """A transport client that records whether it was paused.""" + client = MagicMock() + client.pause_consumption = AsyncMock() + client.resume_consumption = AsyncMock() + return client + + +@pytest.fixture +def registry() -> MagicMock: + """A registry whose IO clients are keyed by namespace, as the real one is.""" + clients: dict[str, list[MagicMock]] = {"": [], "orders": [_client()], "billing": [_client()]} + registry = MagicMock() + registry.get_io_clients.side_effect = lambda namespace=None: clients.get(namespace, []) + registry.clients = clients + return registry + + +@pytest.fixture +def supervisor(registry: MagicMock) -> NamespaceSupervisor: + return NamespaceSupervisor(registry, ["", "orders", "billing"], critical=["orders"]) + + +class TestInitialState: + def test_every_hosted_agent_starts_up(self, supervisor: NamespaceSupervisor) -> None: + """An agent with no health check of its own is present and serving, not absent.""" + assert supervisor.status == {"": True, "orders": True, "billing": True} + + def test_an_unknown_agent_counts_as_up(self, supervisor: NamespaceSupervisor) -> None: + assert supervisor.is_up("nobody") is True + + def test_the_critical_set_is_kept(self, supervisor: NamespaceSupervisor) -> None: + assert supervisor.critical_namespaces == frozenset({"orders"}) + + +class TestDegradation: + async def test_a_failing_agent_is_recorded_as_down(self, supervisor: NamespaceSupervisor) -> None: + await supervisor.observe({"": True, "orders": False, "billing": True}) + assert supervisor.is_up("orders") is False + assert supervisor.is_up("billing") is True + + async def test_a_failing_agent_stops_consuming(self, supervisor: NamespaceSupervisor, registry: MagicMock) -> None: + """C4: readiness gates HTTP only, so a degraded agent must be taken off its topics.""" + await supervisor.observe({"": True, "orders": False, "billing": True}) + registry.clients["orders"][0].pause_consumption.assert_awaited_once() + registry.clients["billing"][0].pause_consumption.assert_not_awaited() + + async def test_the_transition_is_reported_at_error_level_with_the_deployment( + self, supervisor: NamespaceSupervisor, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch + ) -> None: + """C7: grouping removed the pod restart that used to be the alert.""" + monkeypatch.setenv("BLUEPRINT_GROUP", "finance") + monkeypatch.setenv("POD_NAME", "pod-3") + supervisor = NamespaceSupervisor(supervisor._registry, ["", "orders"]) + with caplog.at_level(logging.ERROR): + await supervisor.observe({"": True, "orders": False}) + assert "orders" in caplog.text + assert "finance" in caplog.text + assert "pod-3" in caplog.text + + async def test_a_continuing_failure_is_reported_once( + self, supervisor: NamespaceSupervisor, caplog: pytest.LogCaptureFixture, registry: MagicMock + ) -> None: + """An alert repeated every poll stops being read, and the client is already paused.""" + with caplog.at_level(logging.ERROR): + await supervisor.observe({"orders": False}) + await supervisor.observe({"orders": False}) + assert caplog.text.count("has stopped serving") == 1 + registry.clients["orders"][0].pause_consumption.assert_awaited_once() + + async def test_the_root_degrading_pauses_only_the_root(self, supervisor: NamespaceSupervisor, registry: MagicMock) -> None: + """An omitted namespace on the application registry means every namespace.""" + await supervisor.observe({"": False}) + registry.get_io_clients.assert_called_with(namespace="") + registry.clients["orders"][0].pause_consumption.assert_not_awaited() + + +class TestRecovery: + async def test_an_agent_that_passes_again_resumes_consuming(self, supervisor: NamespaceSupervisor, registry: MagicMock) -> None: + await supervisor.observe({"orders": False}) + await supervisor.observe({"orders": True}) + registry.clients["orders"][0].resume_consumption.assert_awaited_once() + assert supervisor.is_up("orders") is True + + async def test_a_latched_agent_does_not_recover_on_its_own(self, supervisor: NamespaceSupervisor, registry: MagicMock) -> None: + """A component whose on_startup raised can still answer a health check.""" + await supervisor.mark_down("orders", "its service 'db' failed to start") + await supervisor.observe({"orders": True}) + assert supervisor.is_up("orders") is False + registry.clients["orders"][0].resume_consumption.assert_not_awaited() + + async def test_releasing_the_latch_lets_health_decide_again(self, supervisor: NamespaceSupervisor) -> None: + await supervisor.mark_down("orders", "boom") + await supervisor.clear_forced_down("orders") + await supervisor.observe({"orders": True}) + assert supervisor.is_up("orders") is True + + def test_the_latch_reason_is_readable(self, supervisor: NamespaceSupervisor) -> None: + assert supervisor.forced_down_reason("orders") is None + + +class TestFailureIsolation: + async def test_a_client_that_cannot_be_paused_does_not_stop_the_poll(self, registry: MagicMock) -> None: + registry.clients["orders"][0].pause_consumption.side_effect = RuntimeError("no") + supervisor = NamespaceSupervisor(registry, ["", "orders", "billing"]) + await supervisor.observe({"orders": False, "billing": False}) + registry.clients["billing"][0].pause_consumption.assert_awaited_once() diff --git a/tests/unit/agents/io/api/actuators/health/test_readiness_policy.py b/tests/unit/agents/io/api/actuators/health/test_readiness_policy.py new file mode 100644 index 00000000..81cf2847 --- /dev/null +++ b/tests/unit/agents/io/api/actuators/health/test_readiness_policy.py @@ -0,0 +1,65 @@ +"""Which degraded agents take the pod out of service rotation (C3). + +The table in ``ReadinessPolicy`` is the whole of this: three policies, and one rule -- the root +gates under all of them -- that keeps a single-agent application behaving exactly as it did +before the key existed. +""" + +import pytest + +from blueprint.agents.io.api.actuators.health.readiness_policy import CONFIG_KEY, ReadinessPolicy + + +class TestParse: + @pytest.mark.parametrize("value", ["all", "critical", "any", "ALL", " Critical "]) + def test_a_named_policy_is_returned(self, value: str) -> None: + assert ReadinessPolicy.parse(value) == value.strip().lower() + + @pytest.mark.parametrize("value", ["critcal", "none", "", None, 3]) + def test_anything_else_raises_rather_than_defaulting(self, value: object) -> None: + """A misspelt policy silently read as 'all' would remove a whole group from rotation.""" + with pytest.raises(ValueError, match=CONFIG_KEY): + ReadinessPolicy.parse(value) + + def test_the_message_names_the_three_that_exist(self) -> None: + with pytest.raises(ValueError) as exc: + ReadinessPolicy.parse("critcal") + for policy in ("all", "critical", "any"): + assert policy in str(exc.value) + + +class TestASingleAgentApplication: + """The root is the whole application, so every policy has to agree about it.""" + + @pytest.mark.parametrize("policy", list(ReadinessPolicy)) + def test_a_healthy_root_is_ready_under_every_policy(self, policy: ReadinessPolicy) -> None: + assert policy.is_ready({"": True}, set()) is True + + @pytest.mark.parametrize("policy", list(ReadinessPolicy)) + def test_a_degraded_root_is_never_ready(self, policy: ReadinessPolicy) -> None: + """The root holds the shared infrastructure; its failure is not a partial one.""" + assert policy.is_ready({"": False}, {"orders"}) is False + + +class TestAGroup: + def test_all_refuses_readiness_for_any_degraded_agent(self) -> None: + assert ReadinessPolicy.ALL.is_ready({"": True, "orders": True, "billing": False}, set()) is False + + def test_all_is_ready_when_every_agent_is_up(self) -> None: + assert ReadinessPolicy.ALL.is_ready({"": True, "orders": True, "billing": True}, set()) is True + + def test_critical_ignores_an_agent_the_deployment_can_run_without(self) -> None: + assert ReadinessPolicy.CRITICAL.is_ready({"": True, "orders": True, "billing": False}, {"orders"}) is True + + def test_critical_refuses_readiness_for_a_flagged_agent(self) -> None: + assert ReadinessPolicy.CRITICAL.is_ready({"": True, "orders": False, "billing": True}, {"orders"}) is False + + def test_critical_with_nothing_flagged_is_ready_whatever_fails(self) -> None: + """A deployment that flagged nothing said no agent is worth removing the pod for.""" + assert ReadinessPolicy.CRITICAL.is_ready({"": True, "orders": False}, set()) is True + + def test_any_is_ready_while_one_agent_is_up(self) -> None: + assert ReadinessPolicy.ANY.is_ready({"": True, "orders": False, "billing": True}, set()) is True + + def test_any_refuses_readiness_when_every_agent_is_down(self) -> None: + assert ReadinessPolicy.ANY.is_ready({"": True, "orders": False, "billing": False}, set()) is False diff --git a/tests/unit/agents/io/api/actuators/test_actuator_api.py b/tests/unit/agents/io/api/actuators/test_actuator_api.py index 44f441c8..7c96e848 100644 --- a/tests/unit/agents/io/api/actuators/test_actuator_api.py +++ b/tests/unit/agents/io/api/actuators/test_actuator_api.py @@ -11,6 +11,7 @@ from blueprint.agents.config import Config from blueprint.agents.io.api.actuators.health.health_base import HealthCheckEntry from blueprint.agents.io.api.actuators.actuator_api import ActuatorApi +from blueprint.agents.io.api.actuators.health.readiness_policy import ReadinessPolicy @pytest.fixture @@ -145,7 +146,7 @@ async def test_on_startup_uses_configured_interval(self, actuator_api: ActuatorA with patch("blueprint.agents.io.api.actuators.actuator_api.HealthCheckCache") as mock_cache_cls: mock_cache_cls.return_value.start = AsyncMock() await actuator_api.on_startup() - mock_cache_cls.assert_called_once_with(check_interval_seconds=60) + assert mock_cache_cls.call_args.kwargs["check_interval_seconds"] == 60 async def test_on_startup_registers_pending_providers(self, actuator_api: ActuatorApi, mock_config: MagicMock) -> None: entry = HealthCheckEntry(name="db", namespace="", checker=MagicMock()) @@ -383,3 +384,46 @@ def test_a_check_added_after_startup_reaches_the_live_cache(self, actuator_api: actuator_api.add_health_providers([entry]) cache.set_health_entries.assert_called_once_with([entry]) + + +class TestTheReadinessPolicy: + """C3: which agents may take the pod out of service rotation, and who knows they exist.""" + + @staticmethod + def _actuator(mock_config: MagicMock, policy: object, namespaces: tuple[str, ...], critical: tuple[str, ...]) -> ActuatorApi: + mock_config.get.side_effect = lambda key, default=None: {"readiness_policy": policy}.get(key, default) + return ActuatorApi(namespaces, critical) + + async def test_the_default_reproduces_todays_behaviour(self, mock_config: MagicMock, mock_registry: MagicMock) -> None: + mock_config.get.side_effect = lambda key, default=None: default + actuator = ActuatorApi() + with patch("blueprint.agents.io.api.actuators.actuator_api.HealthCheckCache") as cache_cls: + cache_cls.return_value.start = AsyncMock() + await actuator.on_startup() + assert cache_cls.call_args.kwargs["policy"] == ReadinessPolicy.ALL + + async def test_a_configured_policy_reaches_the_cache(self, mock_config: MagicMock, mock_registry: MagicMock) -> None: + actuator = self._actuator(mock_config, "critical", ("", "orders"), ("orders",)) + with patch("blueprint.agents.io.api.actuators.actuator_api.HealthCheckCache") as cache_cls: + cache_cls.return_value.start = AsyncMock() + await actuator.on_startup() + assert cache_cls.call_args.kwargs["policy"] == ReadinessPolicy.CRITICAL + + async def test_an_unknown_policy_refuses_to_start(self, mock_config: MagicMock, mock_registry: MagicMock) -> None: + """Defaulting would remove a whole group from rotation the first time an agent wobbled.""" + actuator = self._actuator(mock_config, "critcal", ("",), ()) + with pytest.raises(ValueError, match="readiness_policy"): + await actuator.on_startup() + + async def test_the_supervisor_knows_every_hosted_agent(self, mock_config: MagicMock, mock_registry: MagicMock) -> None: + actuator = self._actuator(mock_config, "all", ("", "orders", "billing"), ("orders",)) + with patch("blueprint.agents.io.api.actuators.actuator_api.HealthCheckCache") as cache_cls: + cache_cls.return_value.start = AsyncMock() + await actuator.on_startup() + assert actuator.supervisor is not None + assert set(actuator.supervisor.status) == {"", "orders", "billing"} + assert actuator.supervisor.critical_namespaces == frozenset({"orders"}) + + def test_there_is_no_supervisor_before_startup(self, actuator_api: ActuatorApi) -> None: + """The gauges belong to per-agent providers, which the lifespan configures first.""" + assert actuator_api.supervisor is None diff --git a/tests/unit/agents/io/api/eventing/test_dapr_fanout.py b/tests/unit/agents/io/api/eventing/test_dapr_fanout.py index cebcd455..1d20119e 100644 --- a/tests/unit/agents/io/api/eventing/test_dapr_fanout.py +++ b/tests/unit/agents/io/api/eventing/test_dapr_fanout.py @@ -288,3 +288,41 @@ def test_the_endpoint_takes_no_namespace(self, config: Config) -> None: """There is one per process, at the root, and that is structural rather than a default.""" with pytest.raises(TypeError): DaprEventing(namespace="orders") # type: ignore[call-arg] + + +class TestADegradedAgentIsNotOffered: + """C4 under a push transport: the sidecar posts whatever the application thinks.""" + + @staticmethod + def _pause(namespace: str) -> DaprClient: + """Create that agent's client and pause it, as the supervisor would.""" + with namespace_scope(namespace): + client = DaprClient() + client._consumption_paused = True + return client + + async def test_a_paused_agent_is_skipped(self, config: Config, calls: list[str]) -> None: + endpoint = build_agents(orders=OrderHandler, billing=BillingHandler) + self._pause("orders") + + await endpoint.publish("orders.created", event()) + + assert calls == ["billing"] + + async def test_the_delivery_is_retried_rather_than_acknowledged(self, config: Config) -> None: + """Acknowledging would consume the event on behalf of an agent that never saw it.""" + endpoint = build_agents(orders=OrderHandler) + self._pause("orders") + + answer = await endpoint.publish("orders.created", event()) + + assert answer["status"] == "RETRY" + assert "degraded" in answer["reason"] + + async def test_a_healthy_agent_is_unaffected(self, config: Config, calls: list[str]) -> None: + endpoint = build_agents(orders=OrderHandler) + + answer = await endpoint.publish("orders.created", event()) + + assert answer == {"status": "SUCCESS"} + assert calls == ["orders"] diff --git a/tests/unit/agents/io/api/scheduling/test_scheduler.py b/tests/unit/agents/io/api/scheduling/test_scheduler.py index 9c6b9d33..589bf273 100644 --- a/tests/unit/agents/io/api/scheduling/test_scheduler.py +++ b/tests/unit/agents/io/api/scheduling/test_scheduler.py @@ -19,6 +19,8 @@ validate_crontab, ) from blueprint.agents.component.namespace import namespace_scope +from blueprint.agents.io.telemetry.providers import reset_providers +from blueprint.agents.models.events import GenericCloudEvent from blueprint.agents.services.infrastructure.cache_service import DiskCacheService _SCHEDULER_MODULE = "blueprint.agents.io.api.scheduling.scheduler" @@ -583,3 +585,54 @@ async def test_event_mode_does_not_claim(self, scheduler: _TestScheduler, mock_r assert scheduler.tick_call_count == 1 mock_registry.cache_service.claim.assert_not_called() + + +class TestTickFreshness: + """A tick that stops arriving looks like silence, so the age since the last one is a metric.""" + + @pytest.fixture + def scheduler(self, mock_config: MagicMock, mock_registry: MagicMock) -> SchedulerBase: + reset_providers() + return _CountingScheduler("*/5 * * * *") + + def test_a_scheduler_that_has_never_ticked_reports_minus_one(self, scheduler: SchedulerBase) -> None: + """Distinct from a large age: a pod that has just started has missed nothing yet.""" + assert scheduler._last_tick is None + + async def test_a_tick_is_recorded(self, scheduler: SchedulerBase) -> None: + await scheduler.run_tick() + assert scheduler._last_tick is not None + + async def test_a_failing_tick_is_still_recorded(self, scheduler: SchedulerBase) -> None: + """The gauge answers 'is this being driven'; a failing tick is a different alert.""" + scheduler.failure = RuntimeError("boom") + with pytest.raises(RuntimeError): + await scheduler.run_tick() + assert scheduler._last_tick is not None + + async def test_the_manual_trigger_counts_as_a_tick(self, scheduler: SchedulerBase) -> None: + await scheduler._trigger_tick() + assert scheduler.ticks == 1 + assert scheduler._last_tick is not None + + async def test_the_event_path_counts_as_a_tick(self, scheduler: SchedulerBase) -> None: + """Event mode is the case that needs this: a CronJob that stopped is invisible.""" + handler = SchedulerTickHandler(scheduler, "orders.scheduler.counting_scheduler") + await handler.handle_event(GenericCloudEvent.model_construct(id="e", type="t", source="/s"), {}) + assert scheduler.ticks == 1 + assert scheduler._last_tick is not None + + +class _CountingScheduler(SchedulerBase): + """A scheduler that records its ticks and can be made to fail.""" + + failure: Exception | None = None + + def __init__(self, crontab: str) -> None: + super().__init__(crontab) + self.ticks = 0 + + async def tick(self) -> None: + self.ticks += 1 + if self.failure is not None: + raise self.failure diff --git a/tests/unit/agents/io/telemetry/test_inflight.py b/tests/unit/agents/io/telemetry/test_inflight.py new file mode 100644 index 00000000..d082c2e7 --- /dev/null +++ b/tests/unit/agents/io/telemetry/test_inflight.py @@ -0,0 +1,60 @@ +"""Per-agent in-flight accounting, which is what makes an OOM kill attributable (C7).""" + +from collections.abc import Iterator + +import pytest + +from blueprint.agents.io.telemetry.inflight import IN_FLIGHT, InFlightRegister +from blueprint.agents.io.telemetry.providers import reset_providers + + +@pytest.fixture(autouse=True) +def _clean() -> Iterator[None]: + IN_FLIGHT.reset() + reset_providers() + yield + IN_FLIGHT.reset() + reset_providers() + + +@pytest.fixture +def register() -> InFlightRegister: + return InFlightRegister() + + +class TestCounting: + def test_an_agent_starts_at_zero(self, register: InFlightRegister) -> None: + assert register.count("orders") == 0 + + def test_the_count_rises_inside_the_block(self, register: InFlightRegister) -> None: + with register.track("orders"): + assert register.count("orders") == 1 + + def test_the_count_falls_again(self, register: InFlightRegister) -> None: + with register.track("orders"): + pass + assert register.count("orders") == 0 + + def test_a_raising_dispatch_still_decrements(self, register: InFlightRegister) -> None: + """A leaked count would grow without bound and make the gauge report a stuck agent.""" + with pytest.raises(RuntimeError), register.track("orders"): + raise RuntimeError("boom") + assert register.count("orders") == 0 + + def test_concurrent_dispatches_are_counted_separately(self, register: InFlightRegister) -> None: + with register.track("orders"), register.track("orders"): + assert register.count("orders") == 2 + + def test_agents_are_counted_apart(self, register: InFlightRegister) -> None: + with register.track("orders"): + assert register.count("billing") == 0 + + def test_the_root_is_an_agent_like_any_other(self, register: InFlightRegister) -> None: + with register.track(""): + assert register.count("") == 1 + + def test_an_agent_stays_listed_after_its_work_finishes(self, register: InFlightRegister) -> None: + """The watchdog reads this list, and an agent at zero is a fact worth reporting.""" + with register.track("orders"): + pass + assert register.namespaces() == ("orders",) diff --git a/tests/unit/agents/io/telemetry/test_loop_watchdog.py b/tests/unit/agents/io/telemetry/test_loop_watchdog.py new file mode 100644 index 00000000..2e6ebaf8 --- /dev/null +++ b/tests/unit/agents/io/telemetry/test_loop_watchdog.py @@ -0,0 +1,100 @@ +"""Detecting a blocked event loop, the one group-wide failure the process can see itself.""" + +import asyncio +import logging +from collections.abc import Iterator +from unittest.mock import MagicMock + +import pytest + +from blueprint.agents.io.telemetry.inflight import IN_FLIGHT +from blueprint.agents.io.telemetry.loop_watchdog import DEBUG_KEY, LoopWatchdog, configure_loop_debug +from blueprint.agents.io.telemetry.providers import reset_providers + + +@pytest.fixture(autouse=True) +def _clean() -> Iterator[None]: + IN_FLIGHT.reset() + reset_providers() + yield + IN_FLIGHT.reset() + reset_providers() + asyncio.get_event_loop_policy() + + +def _config(**values: object) -> MagicMock: + config = MagicMock() + config.get.side_effect = lambda key, default=None: values.get(key, default) + return config + + +class TestDebugMode: + async def test_development_turns_asyncio_debug_on(self) -> None: + loop = asyncio.get_running_loop() + try: + assert configure_loop_debug(_config(), development=True) is True + assert loop.get_debug() is True + finally: + loop.set_debug(False) + + async def test_production_leaves_it_off(self) -> None: + assert configure_loop_debug(_config(), development=False) is False + assert asyncio.get_running_loop().get_debug() is False + + async def test_production_can_ask_for_it(self) -> None: + """The exact answer is available in production; it just costs enough to be a decision.""" + loop = asyncio.get_running_loop() + try: + assert configure_loop_debug(_config(**{DEBUG_KEY: True}), development=False) is True + assert loop.get_debug() is True + finally: + loop.set_debug(False) + + async def test_the_slow_callback_threshold_is_configurable(self) -> None: + loop = asyncio.get_running_loop() + try: + configure_loop_debug(_config(event_loop_slow_callback_seconds=0.5), development=True) + assert loop.slow_callback_duration == 0.5 + finally: + loop.set_debug(False) + loop.slow_callback_duration = 0.1 + + +class TestWatchdog: + async def test_it_starts_and_stops(self) -> None: + watchdog = LoopWatchdog(interval_seconds=0.01, threshold_seconds=10.0) + await watchdog.start() + assert watchdog.running is True + await watchdog.stop() + assert watchdog.running is False + + async def test_starting_twice_runs_one_task(self) -> None: + watchdog = LoopWatchdog(interval_seconds=0.01, threshold_seconds=10.0) + await watchdog.start() + first = watchdog._task + await watchdog.start() + try: + assert watchdog._task is first + finally: + await watchdog.stop() + + async def test_stopping_one_that_never_started_is_a_no_op(self) -> None: + await LoopWatchdog().stop() + + async def test_a_quiet_loop_reports_nothing(self, caplog: pytest.LogCaptureFixture) -> None: + watchdog = LoopWatchdog(interval_seconds=0.01, threshold_seconds=5.0) + with caplog.at_level(logging.ERROR): + await watchdog.start() + await asyncio.sleep(0.05) + await watchdog.stop() + assert "blocked" not in caplog.text + + async def test_a_block_is_reported_with_the_agents_that_had_work(self, caplog: pytest.LogCaptureFixture) -> None: + """It cannot name the callback -- by the time it runs again, the callback has returned.""" + watchdog = LoopWatchdog(interval_seconds=0.01, threshold_seconds=0.0) + with IN_FLIGHT.track("orders"), caplog.at_level(logging.ERROR): + await watchdog.start() + await asyncio.sleep(0.05) + await watchdog.stop() + assert "The event loop was blocked" in caplog.text + assert "orders" in caplog.text diff --git a/tests/unit/agents/io/telemetry/test_telemetry.py b/tests/unit/agents/io/telemetry/test_telemetry.py index 6c63d366..20bcdb87 100644 --- a/tests/unit/agents/io/telemetry/test_telemetry.py +++ b/tests/unit/agents/io/telemetry/test_telemetry.py @@ -1,13 +1,29 @@ """Unit tests for TelemetryManager and TracingContext.""" +from collections.abc import Iterator from unittest.mock import MagicMock, patch import pytest +from blueprint.agents.io.telemetry.providers import agent_meter, agent_tracer, configured_namespaces, reset_providers, tracer_provider from blueprint.agents.io.telemetry.telemetry import TelemetryManager, TracingContext from blueprint.agents.models.config import ObservabilityConfig +@pytest.fixture(autouse=True) +def _forget_providers() -> Iterator[None]: + """Clear the per-namespace providers around every case. + + They live in a module-level register, which is what lets a component reach its own without + holding the manager (C6). That makes them process state, so one case's providers would + otherwise satisfy the next case's assertions -- and ``configure_tracing`` skips a namespace + that already has one, so the second case would configure nothing at all. + """ + reset_providers() + yield + reset_providers() + + @pytest.fixture def telemetry_manager(mock_config: MagicMock, mock_registry: MagicMock) -> TelemetryManager: """Return a TelemetryManager with mocked config.""" @@ -68,6 +84,7 @@ def test_creates_tracer_provider_when_enabled( patch("blueprint.agents.io.telemetry.telemetry.Resource"), patch("blueprint.agents.io.telemetry.telemetry.trace"), patch.object(telemetry_manager, "_build_exporters", return_value=[MagicMock()]), + patch.object(telemetry_manager, "_build_metric_exporters", return_value=[]), patch.object(telemetry_manager, "_setup_instrumentation"), ): mock_provider = MagicMock() @@ -76,6 +93,79 @@ def test_creates_tracer_provider_when_enabled( mock_provider_cls.assert_called_once() +class TestOneIdentityPerAgent: + """C2: each agent gets its own providers, and the root keeps the one it always had.""" + + @pytest.fixture + def configure(self, telemetry_manager: TelemetryManager, mock_config: MagicMock, enabled_observability: ObservabilityConfig): + """Return a callable that configures telemetry for the given agents, exporting nothing.""" + + def _configure(*namespaces: str) -> None: + mock_config.get_observability_config.return_value = enabled_observability + with ( + patch.object(telemetry_manager, "_build_exporters", return_value=[MagicMock()]), + patch.object(telemetry_manager, "_build_metric_exporters", return_value=[]), + patch.object(telemetry_manager, "_setup_instrumentation"), + ): + telemetry_manager.configure_tracing(namespaces) + + return _configure + + @staticmethod + def _attributes(namespace: str) -> dict[str, object]: + provider = tracer_provider(namespace) + assert provider is not None + return dict(provider.resource.attributes) + + def test_the_root_is_configured_even_when_no_agent_is(self, configure) -> None: + configure() + assert configured_namespaces() == ("",) + + def test_the_root_keeps_the_configured_service_name(self, configure) -> None: + configure("orders") + assert self._attributes("")["service.name"] == "test-service" + + def test_an_agent_is_its_own_service(self, configure) -> None: + configure("orders", "billing") + assert self._attributes("orders")["service.name"] == "orders" + assert self._attributes("billing")["service.name"] == "billing" + + def test_every_resource_carries_the_deployment(self, configure, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("BLUEPRINT_GROUP", "finance") + monkeypatch.setenv("POD_NAME", "pod-7") + configure("orders") + for namespace in ("", "orders"): + assert self._attributes(namespace)["deployment.group"] == "finance" + assert self._attributes(namespace)["service.instance.id"] == "pod-7" + + def test_one_span_processor_serves_every_provider(self, configure) -> None: + """A processor per agent would be a queue and an export thread per agent.""" + configure("orders", "billing") + processors = {id(tracer_provider(namespace)._active_span_processor) for namespace in ("", "orders", "billing")} + assert len(processors) == 3, "each provider has its own multi-processor wrapper" + underlying = { + id(processor) + for namespace in ("", "orders", "billing") + for processor in tracer_provider(namespace)._active_span_processor._span_processors + } + assert len(underlying) == 1 + + def test_a_tracer_comes_from_its_own_agents_provider(self, configure) -> None: + configure("orders") + assert agent_tracer("orders", "X") is not agent_tracer("", "X") + + def test_an_unconfigured_agent_falls_back_rather_than_failing(self, configure) -> None: + configure("orders") + assert agent_tracer("nobody", "X") is not None + assert agent_meter("nobody", "X") is not None + + def test_configuring_twice_does_not_replace_a_provider(self, configure) -> None: + configure("orders") + first = tracer_provider("orders") + configure("orders") + assert tracer_provider("orders") is first + + class TestBuildExporters: def test_returns_otlp_exporter_when_endpoint_configured( self, diff --git a/tests/unit/agents/test_agent_group.py b/tests/unit/agents/test_agent_group.py index a6f1aa59..3522711d 100644 --- a/tests/unit/agents/test_agent_group.py +++ b/tests/unit/agents/test_agent_group.py @@ -398,6 +398,46 @@ def test_it_returns_a_group_ready_to_assemble(self, tmp_path: Path) -> None: assert isinstance(group, AgentGroup) +class TestTheCriticalFlagReachesReadiness: + """One flag, two consequences: whether a failed load stops the process (spec sec. 9.1), + and whether that agent may take the pod out of service rotation (C3).""" + + def test_from_config_keeps_the_flag(self, config: Config) -> None: + group = AgentGroup.from_config( + GroupConfig( + name="finance", + agents=( + spec("order", "order_declaration"), + spec("billing", "billing_declaration", critical=False), + ), + ) + ) + + assert group.critical_agents == frozenset({"order"}) + + def test_assemble_hands_it_to_the_root_builder(self, config: Config) -> None: + group = AgentGroup( + "finance", + {"order": order_declaration, "billing": billing_declaration}, + critical={"order"}, + ) + + with patch.object(AppBuilder, "host_agent", autospec=True) as host_agent: + host_agent.side_effect = lambda self, namespace, critical=True: self._namespaces.append(namespace) or self + group.assemble(config) + + assert [(call.args[1], call.kwargs["critical"]) for call in host_agent.call_args_list] == [ + ("order", True), + ("billing", False), + ] + + def test_a_group_written_by_hand_is_all_critical(self, config: Config) -> None: + """The same default GroupConfig applies, and what a single-agent application has always had.""" + group = AgentGroup("finance", {"order": order_declaration, "billing": billing_declaration}) + + assert group.critical_agents == frozenset({"order", "billing"}) + + class TestTheBuilderKnowsNothingAboutGroups: def test_app_builder_has_no_group_methods(self) -> None: """Collection is the collector's job. An AppBuilder never learns it can be collected.""" diff --git a/tests/unit/agents/test_design_rules.py b/tests/unit/agents/test_design_rules.py index e743b34a..01c6b4d4 100644 --- a/tests/unit/agents/test_design_rules.py +++ b/tests/unit/agents/test_design_rules.py @@ -736,6 +736,94 @@ def test_only_the_logging_manager_configures_logging(self, path: Path) -> None: ) +def spawns_a_task(node: ast.Call) -> str | None: + """Name ``asyncio.create_task`` / ``ensure_future`` calls, and nothing else.""" + if isinstance(node.func, ast.Attribute) and node.func.attr in {"create_task", "ensure_future"}: + return node.func.attr + return None + + +def _assigned_name(statement: ast.stmt) -> str | None: + """Return the single name a statement assigns to, or ``None``. + + Only the simple shapes a spawn is written in: ``task = create_task(...)`` and + ``self._task = create_task(...)``. Anything else is reported rather than guessed at. + """ + if not isinstance(statement, ast.Assign) or len(statement.targets) != 1: + return None + target = statement.targets[0] + if isinstance(target, ast.Name): + return target.id + if isinstance(target, ast.Attribute): + return ast.unparse(target) + return None + + +def _adds_a_done_callback(body: list[ast.stmt], index: int, name: str) -> bool: + """Whether one of the statements after ``index`` adds a done-callback to ``name``.""" + for statement in body[index + 1 :]: + for node in ast.walk(statement): + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "add_done_callback" + and ast.unparse(node.func.value) == name + ): + return True + return False + + +def unwatched_spawns(path: Path) -> list[tuple[int, str]]: + """Return ``(line, source)`` for every detached task with no done-callback beside it.""" + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + offenders: list[tuple[int, str]] = [] + watched_lines: set[int] = set() + + for holder in ast.walk(tree): + body = getattr(holder, "body", None) + if not isinstance(body, list): + continue + for index, statement in enumerate(body): + spawns = [node for node in ast.walk(statement) if isinstance(node, ast.Call) and spawns_a_task(node)] + if not spawns: + continue + name = _assigned_name(statement) + if name is not None and _adds_a_done_callback(body, index, name): + watched_lines.update(node.lineno for node in spawns) + + for node in ast.walk(tree): + if isinstance(node, ast.Call) and spawns_a_task(node) and node.lineno not in watched_lines: + offenders.append((node.lineno, ast.unparse(node))) + return offenders + + +class TestEveryDetachedTaskIsWatched: + """**Every task the framework starts carries a done-callback that logs its exception.** + + *Failure it prevents:* a detached task that raised holds its exception until it is garbage + collected, and what reaches the log is asyncio's own "Task exception was never retrieved" -- + at an unpredictable time, with no agent on it. In a process per agent that was survivable + because the pod told you; in a group it is exactly the silent per-agent failure C7 exists to + remove, because nineteen agents go on answering while the twentieth has stopped. + + The guard looks for a ``create_task`` / ``ensure_future`` whose result is assigned and then + given an ``add_done_callback`` in the same block. A spawn whose result is discarded outright + can never be watched, so it fails here too. + """ + + @pytest.mark.parametrize("path", python_files(FRAMEWORK), ids=lambda path: str(path.relative_to(REPO_ROOT))) + def test_no_task_is_started_and_forgotten(self, path: Path) -> None: + unwatched = unwatched_spawns(path) + + assert not unwatched, ( + f"{path.relative_to(REPO_ROOT)} starts a task with no done-callback: " + f"{', '.join(f'{source} on line {line}' for line, source in unwatched)}. Assign the task and call " + "add_done_callback with a handler that logs the exception and names the agent -- otherwise its failure " + "surfaces as asyncio's 'Task exception was never retrieved', at an unpredictable time and attributed to " + "nobody." + ) + + class TestNoDiagnosticsViaPrint: """**No diagnostics via print.** The framework emits through a logger. From 78642fa813857bbb40ff9ddb831fdcf03d7dacf4 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:44:58 +0200 Subject: [PATCH 014/133] feat(generator): scaffold a project that is a group of one, and validate it Phase 10 step 1-2. asbs setup writes a declaration rather than an application: src/main.py assigns an unbuilt AppBuilder, agents.toml names the agent and its module, and the Dockerfile's command is the entry point. The same project runs standalone and hosted. asbs validate reports what a project has not said about grouping. Co-Authored-By: Claude Opus 5 (1M context) --- docs/guides/cli-reference.md | 230 ++++++++---- ...26-08-28-multi-agent-grouping-changelog.md | 336 +++++++++++++++++- docs/plans/2026-08-28-multi-agent-grouping.md | 19 +- .../agent_generator/base_files/Dockerfile | 27 +- .../base_files/agents_toml.txt | 18 + .../agent_generator/base_files/src/main.txt | 22 +- .../agent_generator/cli/commands/create.py | 87 ++--- .../agent_generator/cli/commands/dev.py | 125 +++++-- .../agent_generator/cli/commands/setup.py | 14 +- .../agent_generator/cli/commands/validate.py | 335 ++++++++++++++++- src/blueprint/agent_generator/cli/main.py | 6 +- .../agent_generator/cli/utils/naming_utils.py | 81 ++++- .../agent_generator/generator/generator.py | 15 +- .../generator/part_generators/__init__.py | 2 + .../agent_map_part_generator.py | 52 +++ .../part_generators/copy_part_generator.py | 18 +- .../part_generators/main_part_generator.py | 80 +++-- src/blueprint/agents/entrypoint.py | 31 ++ .../agent_generator/cli/commands/test_dev.py | 115 +++++- .../cli/commands/test_validate_group_gates.py | 216 +++++++++++ .../cli/utils/test_component_ordering.py | 8 +- .../cli/utils/test_main_py_editing.py | 117 ++++++ .../cli/utils/test_naming_utils.py | 12 +- .../agent_generator/generator/__init__.py | 0 .../generator/test_generated_project.py | 202 +++++++++++ 25 files changed, 1930 insertions(+), 238 deletions(-) create mode 100644 src/blueprint/agent_generator/base_files/agents_toml.txt create mode 100644 src/blueprint/agent_generator/generator/part_generators/agent_map_part_generator.py create mode 100644 tests/unit/agent_generator/cli/commands/test_validate_group_gates.py create mode 100644 tests/unit/agent_generator/cli/utils/test_main_py_editing.py create mode 100644 tests/unit/agent_generator/generator/__init__.py create mode 100644 tests/unit/agent_generator/generator/test_generated_project.py diff --git a/docs/guides/cli-reference.md b/docs/guides/cli-reference.md index e54b5eaf..b27c530b 100644 --- a/docs/guides/cli-reference.md +++ b/docs/guides/cli-reference.md @@ -90,7 +90,7 @@ $ asbs create handler order_placed ✓ Created handler: src/handlers/order_placed_handler.py ✓ Auto-registered in src/main.py - Added import: from src.handlers.order_placed_handler import OrderPlacedHandler - - Added registration: .with_handler(OrderPlacedHandler()) + - Added registration: .with_handler(OrderPlacedHandler) ``` --- @@ -135,14 +135,45 @@ asbs setup asbs setup my-ai-service ``` -The generated `main.py` contains the minimal application bootstrap: +The generated `main.py` is a **declaration**, not an application. Nothing is constructed until +something calls `build()`, which is what lets the same file be served on its own and be hosted +alongside other agents in one process: ```python -from blueprint.agents import AppBuilder, Config +from blueprint.agents.agent import AgentBuilder +from blueprint.agents.app_builder import AppBuilder -app = AppBuilder(Config()).build() +from .services import MyAiServiceService + +my_ai_service_agent = ( + AgentBuilder(runtime_name="my_ai_service_agent") + .with_model_from_config() + .with_system_prompt("my_ai_service_agent_system") +) + +agent = ( + AppBuilder() + .with_service(MyAiServiceService) + .with_agent(my_ai_service_agent, name="my_ai_service_agent") +) ``` +Components are registered as **classes**, not instances: a component constructed on the `with_*` +line is constructed before any namespace exists and belongs to the root for ever, which is why a +group refuses one. + +`asbs setup` also writes `agents.toml`, which maps the agent's name to that declaration: + +```toml +[agents.my_ai_service] +module = "src.main:agent" +``` + +That name is the agent's identity everywhere outside the file -- the NATS queue group, part of the +JetStream durable name, the cache partition, the OpenTelemetry `service.name` and the `/api/` +route prefix -- so changing it after the first deploy is a consumer migration. The project is run +with `python -m blueprint.agents.entrypoint`, which reads that map and the deployment's group. + --- ## asbs create handler @@ -178,7 +209,7 @@ Handler names are converted to `Handler` format: The created handler is automatically: - Imported in `src/main.py` -- Registered with `.with_handler(OrderPlacedHandler())` +- Registered with `.with_handler(OrderPlacedHandler)` If auto-registration fails, manual registration instructions are provided. @@ -256,7 +287,7 @@ Service names are converted to `Service` format: The created service is automatically: - Imported in `src/main.py` -- Registered with `.with_service(InvoiceProcessorService())` +- Registered with `.with_service(InvoiceProcessorService)` ### Examples @@ -338,7 +369,7 @@ API names are converted to `Api` format with an accompanying models file: The created API is automatically: - Imported in `src/main.py` (both models and API) -- Registered with `.with_rest_api(OrderManagementApi())` +- Registered with `.with_rest_api(OrderManagementApi)` ### Examples @@ -447,7 +478,7 @@ Agent names are converted to `` format (no "Agent" suffix in class name, b The created agent is automatically: - Imported in `src/main.py` - Agent instance created before `app =` -- Registered with `.with_agent(_agent)` +- Registered with `.with_agent(_agent, name="_agent")` - Configuration added to `settings.toml` ### Examples @@ -543,7 +574,7 @@ Scheduler names are converted to `Scheduler` format: The created scheduler is automatically: - Imported in `src/main.py` -- Registered with `.with_scheduler(CleanupScheduler())` +- Registered with `.with_scheduler(CleanupScheduler)` ### Cron Expressions @@ -627,20 +658,50 @@ class CleanupScheduler(SchedulerBase): ## asbs validate -Validate the project structure and configuration files. Checks for required directories, valid `settings.toml` entries, correct component registrations, and import consistency. +Validate the project structure and configuration. Reads files only -- it never imports the +project -- and reports what it finds in three grades: **issues** (the project will not start, exit +status 1), **warnings** (it will start, and something is missing) and **notices** (a decision the +framework must not make for you). ```bash -asbs validate +asbs validate [] ``` ### Checks Performed -- Required project directories exist (`src/`, `tests/`) -- `settings.toml` contains required configuration keys -- `secrets.toml` is present and not committed to version control -- All referenced components can be imported -- No duplicate component names -- Port configuration is valid +Project shape: + +- Required directories (`src/`, `tests/`) and files (`settings.toml`, `pyproject.toml`) exist +- `src/main.py` exists and uses `AppBuilder` +- `secrets.toml.example` and `secrets.toml` are present +- A `Dockerfile` is present + +Group readiness -- what this project must state before it can be hosted beside another agent: + +- `agents.toml` exists; without it the project cannot be run by + `python -m blueprint.agents.entrypoint`, and the three changes that make it hostable are named +- Every `[agents.]` entry has a `module` written as `"package.module:attribute"` +- Every agent name is a legal namespace (`[a-z][a-z0-9_]*` -- no dashes), because it becomes the + queue group, the durable, the cache partition and the telemetry `service.name` +- Every declared module exists in the project and assigns the attribute the map names +- Once there is more than one agent: each ships its own `settings.toml` beside its declaration, + and declares no process-scope key (`app_port`, `event_bus`, `envvar_prefix`, ...) there, since + one process binds one port and speaks one bus + +Schedulers: + +- `scheduler_mode` is set when `src/schedulers/` holds anything, and is one of `in_process` or + `event` -- it has no default, and `build()` fails without it +- In `event` mode, `event_bus` is set; and a notice that **nothing in this project generates the + `CronJob`** that must publish the tick. A scheduler waiting for a tick nobody publishes reports + itself healthy and never runs, which nothing else reports +- In `in_process` mode, a notice when `src/main.py` declares no cache: each tick is claimed in the + agent's own cache so that one replica runs it, and with no cache every replica runs every tick + +Delivery: + +- A notice when handlers exist and `idempotency_enabled` is not declared either way. Delivery is + at-least-once, so the decision is the author's to make and the framework will not make it ### Example @@ -649,29 +710,46 @@ asbs validate ``` ``` -[OK] Project structure is valid -[OK] settings.toml configuration is valid -[OK] secrets.toml is present -[WARN] secrets.toml is not in .gitignore -[OK] All components import successfully -[OK] No duplicate component names detected +Validating Blueprint Agents project: /work/my-ai-service + +[ok] Found agents.toml (1 agent(s): my_ai_service) + +============================================================ + +Notices (1): + - 'scheduler_mode' is 'event', so no timer runs in this process: each tick + arrives as an event on '.scheduler.', published by an external + CronJob. ... ``` --- ## asbs dev -Run the application in development mode with hot reload enabled. Uses `uvicorn` under the hood. +Run this project's agents in development mode with hot reload, **under the namespaces they are +deployed under**. A development server at the root namespace would serve `/api/orders/{id}` where +production serves `/api/order/orders/{id}`, and would consume under a different queue group, so +every local URL and every local integration test would differ from the deployed one. + +With an `agents.toml`, it serves the group through +`uvicorn blueprint.agents.entrypoint:create_group_app --factory --reload`. Without one -- a project +written before the agent map, which builds its own application -- it serves `src.main:app` exactly +as it always did. ```bash -asbs dev [--port ] +asbs dev [--agents ] [--host ] [--port ] ``` ### Options -| Flag | Description | Default | -|------------------|----------------------------------|---------| -| `--port ` | Port to bind the server to | `8000` | +| Flag | Description | Default | +|--------------------|-------------------------------------------------------------|------------------| +| `--agents ` | Comma-separated agents to host | every agent in `agents.toml` | +| `--host ` | Host to bind the server to | `127.0.0.1` | +| `--port ` | Port to bind the server to | `8000` | + +`BLUEPRINT_GROUP` or `BLUEPRINT_AGENTS` already set in the environment always wins: a developer +reproducing a particular deployment is not overridden by a default read out of the agent map. ### Example @@ -723,19 +801,21 @@ Run `asbs setup ` to scaffold a complete project if needed. **Solution:** Verify `src/main.py` contains: - Import statements at the top -- `AppBuilder(config)` instantiation -- `.build()` call +- An assignment whose right-hand side opens a parenthesis, with `AppBuilder(` on the next line +- A closing `)` in the first column -- or, in a project that still builds its own application, a + `.build()` call + +That is what the CLI looks for when it rewrites the chain: it is a line-oriented editor for a file +the generator wrote in a known shape, not a parser, and it reports a file it cannot read rather +than guessing at one. Example valid structure: ```python -from blueprint.agents import AppBuilder, Config +from blueprint.agents.app_builder import AppBuilder -config = Config(...) - -app = ( - AppBuilder(config) +agent = ( + AppBuilder() # Components added here - .build() ) ``` @@ -743,16 +823,18 @@ app = ( If auto-registration fails, the CLI displays instructions. Follow this pattern for each component type: +Every registration is the **class**, not an instance of it, and the declaration ends without a +`build()` call -- the host builds it. + #### Handler ```python # In src/main.py -from src.handlers.order_placed_handler import OrderPlacedHandler +from .handlers import OrderPlacedHandler -app = ( - AppBuilder(config) - .with_handler(OrderPlacedHandler()) - .build() +agent = ( + AppBuilder() + .with_handler(OrderPlacedHandler) ) ``` @@ -760,12 +842,11 @@ app = ( ```python # In src/main.py -from src.services.invoice_processor_service import InvoiceProcessorService +from .services import InvoiceProcessorService -app = ( - AppBuilder(config) - .with_service(InvoiceProcessorService()) - .build() +agent = ( + AppBuilder() + .with_service(InvoiceProcessorService) ) ``` @@ -773,13 +854,11 @@ app = ( ```python # In src/main.py -from src.models.order_management_models import OrderManagementRequest, OrderManagementResponse -from src.api.order_management_api import OrderManagementApi +from .api import OrderManagementApi -app = ( - AppBuilder(config) - .with_rest_api(OrderManagementApi()) - .build() +agent = ( + AppBuilder() + .with_rest_api(OrderManagementApi) ) ``` @@ -787,27 +866,35 @@ app = ( ```python # In src/main.py -from src.agents.document_analyzer_agent import build_document_analyzer_agent +from blueprint.agents.agent import AgentBuilder -document_analyzer_agent: AgentRuntime = build_document_analyzer_agent(config) +document_analyzer_agent = ( + AgentBuilder(runtime_name="document_analyzer_agent") + .with_model_from_config() + .with_system_prompt("document_analyzer_agent_system") +) -app = ( - AppBuilder(config) - .with_agent(document_analyzer_agent) - .build() +agent = ( + AppBuilder() + .with_agent(document_analyzer_agent, name="document_analyzer_agent") ) ``` +The `AgentBuilder` is left **unbuilt**. `AppBuilder.build()` calls +`agent.build(config.for_namespace())`, so the model, prompt and metrics come from this +agent's own configuration view; building it here would bind it to whatever configuration happened +to be in scope at that line, which in a group is a neighbour's. The `name=` is the registry key +services resolve the runtime by. + #### Scheduler ```python # In src/main.py -from src.schedulers.cleanup_scheduler import CleanupScheduler +from .schedulers import CleanupScheduler -app = ( - AppBuilder(config) - .with_scheduler(CleanupScheduler()) - .build() +agent = ( + AppBuilder() + .with_scheduler(CleanupScheduler) ) ``` @@ -821,19 +908,18 @@ Register dependencies **before** dependents in the AppBuilder chain: 4. Schedulers last (use services) ```python -app = ( - AppBuilder(config) +agent = ( + AppBuilder() # 1. Services - .with_service(OrderService()) - .with_service(PaymentService()) + .with_service(OrderService) + .with_service(PaymentService) # 2. Handlers and APIs - .with_handler(OrderPlacedHandler()) - .with_rest_api(OrderApi()) + .with_handler(OrderPlacedHandler) + .with_rest_api(OrderApi) # 3. Agents - .with_agent(analyzer_agent) + .with_agent(analyzer_agent, name="analyzer_agent") # 4. Schedulers - .with_scheduler(CleanupScheduler()) - .build() + .with_scheduler(CleanupScheduler) ) ``` diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index c19932de..e7a8dbbd 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -5961,8 +5961,334 @@ it is about instead. --- +### Phase 10, step 1 -- a scaffolded project is a group of one, in every environment + +Phase 10 adds no framework behaviour; it makes what phases 0-9 built usable by someone who has +only ever written a single-agent service. Its first step is the one everything else documents: +**what `asbs setup` produces**. A guide written against the old scaffold would document a shape +the framework no longer hosts, so the generator goes first and the guides follow it. + +The decision behind the whole step is the plan's: *every newly scaffolded agent has a real +namespace in every environment*. A development server at the root namespace would serve +`/api/orders/{id}` where production serves `/api/order/orders/{id}`, and would consume under a +different queue group -- so every local URL and every local integration test would differ from +the deployed one, in a way nothing reports. `namespace = ""` is therefore reserved for +pre-migration agents, and a new project is a group of one from the first `asbs dev`. + +#### `src/main.py` is a declaration, and nothing else + +`base_files/src/main.txt` lost its `Config(...)` block and its `app = ...build()`; what it now +carries is `imports` and `agent_declaration`. `MainPartGenerator._generate_agent_declaration` +(replacing `_generate_agents_and_app_initialization`) writes: + +```python +invoice_processor_agent = ( + AgentBuilder(runtime_name="invoice_processor_agent") + .with_model_from_config() + .with_system_prompt("invoice_processor_agent_system") +) + +agent = ( + AppBuilder() + .with_service(InvoiceProcessorService) + .with_agent(invoice_processor_agent, name="invoice_processor_agent") + .with_handler(InvoiceProcessorHandler) + .with_rest_api(InvoiceProcessorApi) +) +``` + +Four things changed in that, and each is load-bearing: + +- **`AppBuilder()` with no configuration, and no `build()`.** The module's product is the + builder. The host -- `python -m blueprint.agents.entrypoint` -- supplies the configuration and + builds it inside the namespace the deployment gave it. +- **Classes, not instances.** `with_service(InvoiceProcessorService)` rather than + `...Service()`. A component constructed on the `with_*` line is constructed before any + namespace exists and belongs to the root for ever, which is exactly why `AgentGroup` refuses an + already-built instance (spec sec. 4.2). The class form is constructed by `build()` inside the + agent's own scope and works in both shapes. +- **An unbuilt `AgentBuilder`, with no `config` and no `.build(...)`.** `AppBuilder.build()` + calls `agent.build(config.for_namespace())`, so the model, prompt and metrics come from + this agent's own configuration view (C5). The old template built the runtime at that line + against whichever `Config` was in scope -- in a group, a neighbour's. +- **The runtime's name moved to `with_agent(..., name=...)`** from `AgentBuilder.build(name=...)`. + It is the registry key the generated service resolves the runtime by + (`registry.get_agent("invoice_processor_agent")`), and `AppBuilder` qualifies it with the + agent's namespace, so two agents' runtimes cannot collide on it. + +The runtime stays a **module-level variable** rather than being inlined into `with_agent`, and +that is not style: `asbs create` rewrites the chain line by line, so a registration spanning +several lines would lose its continuation lines on the next `asbs create`. The chain is also +emitted in `sort_components` order (services, agents, handlers, REST APIs) so the first +`asbs create` does not reorder everything and make its own diff unreadable. + +One quiet fix came with it: the system prompt was named from the agent's *class* name +(`camel_to_snake(agent_name) + "_system"`) while the prompt file is written from its +`runtime_name`. They coincide for everything `asbs setup` generates and diverge for any other +generator config. It now reads `runtime_name` on both sides. + +#### `agents.toml` -- the map the image's command reads + +New `base_files/agents_toml.txt` and `AgentMapPartGenerator`, written to the project root: + +```toml +[agents.invoice_processor] +module = "src.main:agent" +``` + +Without it `python -m blueprint.agents.entrypoint` cannot resolve an agent name to code at all -- +`GroupConfig._read_agent_map` refuses to start -- so a generated project that lacked one could +not be run by its own Dockerfile. + +The agent's name is **derived and validated, never repaired**: `AgentMapPartGenerator.agent_namespace` +is the project name in snake case, passed through the framework's own `validate_namespace`. It +becomes the queue group, part of the durable name, the cache partition, the telemetry +`service.name` and the `/api/` prefix, so a name quietly rewritten to fit would be four +different names for one agent. A project name that does not survive the derivation (a leading +digit, say) fails the generator with the reason, at the one moment the name is still free to +change. That is also why this module is the generator's first import of `blueprint.agents`: the +alphabet has one definition, and a copy of the regex here would drift from it. + +#### The Dockerfile runs the entry point, and bakes no group + +`ENTRYPOINT ["uvicorn", "src.main:app", ...]` became +`ENTRYPOINT ["python", "-m", "blueprint.agents.entrypoint"]`, `agents.toml` is copied into the +image beside `settings.toml`, and a comment block above the entry point gives the two supported +ways to say which agents a process hosts (`-e BLUEPRINT_AGENTS=...`, or a mounted group file +plus `BLUEPRINT_GROUP`). **No group file is generated and none is copied in**: one image serves +every group, so which agents run is a Deployment edit rather than a rebuild. With neither +supplied the process stops before binding the port and says which is missing, which is what the +entry point was built to do. + +The Dockerfile is therefore no longer copied verbatim -- `CopyPartGenerator` gained an optional +`template_vars`, and the Dockerfile is rendered with the agent's real name. A placeholder in a +`docker run` line is a command that looks runnable and is not. + +The **dev stage** keeps hot reload, through a new +`entrypoint.create_group_app()`: `build_group_app` returns `(app, config)` because `main()` needs +the configuration to decide host and port, and uvicorn's `--factory` wants the application alone. +Reload needs an *import string* rather than a built object (which is why `run_app` never enables +it), so `uvicorn blueprint.agents.entrypoint:create_group_app --factory --reload` is the only +shape that reloads a group. A resolution failure propagates there rather than becoming an exit +status: the caller is a developer's terminal, not Kubernetes. The dev stage also sets +`ENV BLUEPRINT_AGENTS` -- a development default, in that stage only, where the project is +bind-mounted anyway. + +#### `asbs dev` runs the group, and `asbs create` writes the new shape + +`dev.py` picks its target from what the project contains. With an `agents.toml` it runs the +group factory under the agents' real namespaces; without one, but with a `src/main.py`, it serves +`src.main:app` exactly as before, because a project written before the agent map still builds its +own application and is deployed at the root namespace too -- the two still agree. With neither it +stops and names both files. + +Which agents: `--agents` if given, otherwise every agent in the map (the map is the complete list +of what the project holds; picking one of several would be the tool deciding which agent is the +interesting one). It sets `BLUEPRINT_AGENTS` in its own environment so the child inherits it -- +but **only when the environment names no group already**. A developer who has exported +`BLUEPRINT_GROUP` or `BLUEPRINT_AGENTS` is reproducing a particular deployment, and defaulting +over that would quietly serve something else. + +`asbs create` had to follow, and would otherwise have corrupted the file it edits. +`extract_component_registrations` located the chain's end by its `.build()` line, which a +declaration-only `main.py` does not have; the fallback for "no `.build()`" appends the +registration to the end of the file, and the re-sort drops every line between the builder and the +end. New `_closing_parenthesis_index` reads the `)` in the first column as the other way a chain +ends. `add_component_registration_to_main` now emits the class rather than `Class()`, for the +same reason the generator does. And `create_agent` wrote +`{name}: AgentRuntime = (AgentBuilder(config=config, ...).build(name=...))` anchored on a literal +`app = (` line: the anchor does not exist in the new file, so the declaration went silently +missing while the registration referring to it was still added. New `insert_before_declaration` +matches the *shape* -- an assignment opening a parenthesis, with `AppBuilder(` on the next line -- +so it finds `agent = (` and `app = (` alike, and `create_agent` now writes an unbuilt +`AgentBuilder` with the import added if it is absent. + +Three of `create_agent`'s printed next steps were false and are gone: it claimed to have added +`from src.agents. import build_` and told the reader to add the same import to +`src/agents/__init__.py`, but this command writes no module -- an agent runtime is a builder in +`main.py` plus two prompt files. `module_name` went with them. + +`asbs validate` lost its "src/main.py does not appear to use Config" warning, which is now +backwards: a `main.py` that mentions `Config` is the pre-declaration shape. The rest of +`validate`'s group gates belong to a later step of this phase. + +#### Tests + +`tests/unit/agent_generator/generator/test_generated_project.py` is new (14 cases) and is the +first test of the generator's *output*. It generates the project into a temporary directory and +**imports** the declaration -- parsing is not the claim; the claim is that the framework can host +it -- then asserts the builder is unbuilt, that importing it puts nothing in the shared registry, +that every component is declared as a class, that the runtime carries the name the generated +service resolves it by, that `agents.toml` names a legal namespace and a module that really +resolves to an `AppBuilder`, and that the production stage of the Dockerfile bakes no group and +contains no placeholder. `src` is removed from `sys.modules` around each import: the repository +has a directory of that name too. + +`tests/unit/agent_generator/cli/utils/test_main_py_editing.py` is new (9 cases), covering both +chain shapes through `extract_component_registrations`, `add_component_registration_to_main` and +`insert_before_declaration`. `test_dev.py` was rewritten for the two targets and the environment +precedence. Eight assertions in `test_naming_utils.py` and `test_component_ordering.py` pinned +the instance form and now pin the class form. + +2865 unit tests pass, zero failures. + +--- + +### Phase 10, step 2 -- `asbs validate` says what a project has not said + +There is deliberately **no `asbs migrate`**: `main.py` is the developer's own declaration, and a +tool that rewrites it either guesses at intent or fails on anything hand-edited. What replaces it +is a checklist plus a `validate` that names what is missing, which is what this step builds. + +`validate` keeps its three grades and gains a fourth block feeding them. **Issues** mean the +project will not start (exit 1), **warnings** mean it will start and something is missing, +**notices** are a decision the framework must not make for the author. New `_group_findings` +returns one list of each, and `run()` extends the existing three with them -- so the summary, the +exit status and the output format are unchanged. + +#### The agent map, checked where the answer is a line in a terminal + +`_read_agent_map` checks the same shape `GroupConfig._read_agent_map` refuses to start on: + +```python + module = entry.get("module") if isinstance(entry, dict) else None + if not module or not isinstance(module, str): + issues.append(f"Agent '{name}' in {AGENT_MAP_FILE} has no 'module'. ...") + continue + if ":" not in module: + issues.append(... 'does not say which attribute to read. Write it as "package.module:attribute"') + continue + try: + validate_namespace(name) + except ValueError as exc: + issues.append(f"Agent '{name}' in {AGENT_MAP_FILE} cannot be a namespace: {exc}") +``` + +The name goes through the framework's own `validate_namespace` rather than a copy of the rule, for +the reason the rule exists: a name repaired differently by the queue group, the durable, the cache +partition and the telemetry resource is four names for one agent, and `order-eu` is refused here +rather than in a crash-looping pod. + +`_declaration_issues` then resolves the module **against the filesystem, not by importing it**: +`_module_file` tries `.py` and `/__init__.py`, and a regex asserts the module assigns +the attribute the map names. + +```python + if not re.search(rf"^{re.escape(attribute)}\s*=", text, re.MULTILINE): + return [f"Agent '{name}' points at '{module}', but ... assigns no '{attribute}'. ..."] +``` + +Importing would run the module, which needs the project's dependencies installed and is a +different failure from the one being looked for. What that costs is precision -- this reads text -- +and what it buys is a `validate` that works in a checkout. + +A project with **no** `agents.toml` gets a warning, not an issue, and the warning is the migration +checklist: the three changes (declaration, Dockerfile command, map entry) and the sentence that +the name chosen becomes the queue group and the route prefix, so changing it after the first +deploy is a consumer migration. A project deployed on its own is not broken. + +#### Settings that would not survive being grouped + +`_settings_scope_warnings` reports the two things that go wrong when an agent moves in beside +another, neither of which raises: + +- Its `settings.toml` is read from the directory its **declaration** lives in, so one written + anywhere else is merged into no scope at all -- every key it reads would come from the group's + shared file. +- A process-scope key under one agent's scope is dropped with a warning at startup, because one + process binds one port, speaks one bus and loads one environment. The list is imported + (`PROCESS_SCOPE_KEYS`) rather than restated. + +Two exemptions, and both are about the same fact -- the process's own settings file is not a +fragment. A project hosted **alone** is the process, so nothing is reported for it at all; and an +agent declared at the project root in a group (`main:agent` rather than `src.main:agent`) has its +settings file *at* the process's, which `Config.merge_agent_settings` recognises and leaves at the +root: + +```python + fragment = source.parent / SETTINGS_FILE + if fragment == project_dir / SETTINGS_FILE: + return [] +``` + +That second one was found by asking what `main:agent` -- the shape the plan's own migration bullet +writes -- would do to the check. + +#### The scheduler gap, which is the reason this step existed + +From the changelog's open points: *"a mode and a transport with nothing publishing does not +[fail]. Validate is where it should be caught."* `_scheduler_findings` covers the three states of a +project with anything under `src/schedulers/`: + +- **No `scheduler_mode`** -> issue. It has no default because neither value is safe to inherit, so + `build()` fails; reported here only to report it earlier, with both values and what each costs. +- **`"event"`** -> a notice that no timer runs, the tick must arrive on + `.scheduler.` from an external `CronJob`, and **nothing in this project + generates one**. A notice rather than an issue because nothing here can tell whether the CronJob + exists -- the deployment knows, and it is outside this project. That is exactly why it is said: + a scheduler waiting for a tick nobody publishes reports itself healthy and never runs. + `event_bus` unset in that mode *is* an issue, because wiring raises at startup. +- **`"in_process"` with no `.with_cache(` in `main.py`** -> a notice that every replica will run + every tick. Each tick is claimed in the agent's own cache so one replica runs it; with no cache + to claim in, the claim is a no-op. + +The crontab needs nothing here: P5 already validates it at startup in event mode +(`validate_crontab`, called from `wire()`), which is where the declaration is. + +Two small shared helpers replaced duplicated code rather than adding any: `_load_settings` and +`_declares` are what `_idempotency_notice` and `_declares_idempotency` were doing inline, and +`_value_of` is `_declares` returning the value. All three treat a key set in *any* Dynaconf +environment as set -- which environment is in force is a runtime decision this command cannot make, +and the checks ask whether the author has decided something, not what today's value is. + +#### `docs/guides/cli-reference.md` + +Four sections were made wrong by step 1 and are corrected here rather than left to accumulate: the +generated `main.py` (it claimed `app = AppBuilder(Config()).build()`, which was never what the +generator wrote), `asbs validate`'s checks and output, `asbs dev`'s flags and what it serves, and +every manual-registration example -- classes rather than instances, no `build()`, and the +`AgentBuilder` left unbuilt with the reason. The auto-registration troubleshooting section now +describes the shape the CLI actually looks for. + +**The rest of that file still needs reading against the code.** It documents `validate` checks that +have never existed, and it is the last of the audit's fiction documents; it belongs with the guides +in step 3. + +#### Tests + +`tests/unit/agent_generator/cli/commands/test_validate_group_gates.py` is new (21 cases) and drives +`_group_findings` against real project trees in `tmp_path`: every malformed agent map, a package +declaration as well as a module one, both settings exemptions, the fragment naming exactly the +process-scope keys it declares and not the scoped ones, and each of the scheduler states. 2886 unit +tests pass, zero failures. + +--- + ## Open points +- **`docs/guides/cli-reference.md` still documents checks that have never existed.** Four of its + sections were corrected in phase 10 step 2, because step 1 made them wrong; the rest was already + fiction before either -- `asbs validate` checks named there ("All referenced components can be + imported", "No duplicate component names", "secrets.toml is not in .gitignore") have no + implementation, and its output format is invented. It is the last of the audit's fiction + documents and belongs with the guides in step 3. +- **`asbs` crashes on a Windows console.** Every command prints check marks, warning signs and + box-drawing characters (`setup.py`, `create.py`, `validate.py`), and on a console whose encoding + is cp1252 -- the Windows default -- the first one raises `UnicodeEncodeError` mid-command, after + files have already been written. `asbs create handler` dies after writing the handler but before + registering it in `main.py`. Found while probing phase 10 step 1 against a generated project. + It is also a standing rule violation: source files are ASCII only. The fix is a sweep of the + CLI's output glyphs, which is its own step rather than a drive-by inside a step about the + generated project's shape. +- **`asbs create` writes absolute imports into a file that uses relative ones.** A generated + `main.py` imports `from .handlers import ...`; `asbs create handler` appends + `from src.handlers.order_placed_handler import OrderPlacedHandler`. Both resolve, so nothing + fails -- but the two styles in one file are how a later refactor breaks one of them. +- **The migration guide must carry the cache key layout change.** The cache key layout changed + twice (`AgentScopedCache`, then phase 8b step 5's per-agent stores), so an application upgrading + with a persistent Redis cache or a mounted disk cache sees its old entries as absent -- a cold + cache rather than an error. Recorded here again because phase 10 owns the guide and this is the + bullet most easily lost. - **Two spec amendments from phase 9, both because the spec's wording latches.** Spec C4 says a degraded namespace's transport client is *closed*. Implemented as a **pause** -- subscriptions drained, connection kept -- because a closed client reports itself unhealthy for ever, so the @@ -6034,10 +6360,12 @@ it is about instead. are simulated in one process against one `DiskCacheService` directory, which exercises the set-if-absent path but not file locking across genuinely separate processes, nor Redis under contention. Both belong on the broker/integration list below. - - **`asbs validate` says nothing about schedulers.** A project in `"event"` mode with no - generated `CronJob` is the remaining silent-failure case -- the missing `event_bus` and the - missing mode both fail at startup now, but a mode and a transport with nothing publishing - does not. Validate is where it should be caught. + - ~~**`asbs validate` says nothing about schedulers.**~~ **Done in phase 10 step 2.** A + project in `"event"` mode is now told that nothing here generates the `CronJob` that must + publish its tick, a missing mode and a missing `event_bus` are both reported before startup, + and `"in_process"` with no cache is told that every replica will run every tick. What stays + outside `validate`'s reach is whether the `CronJob` actually exists -- the deployment knows + that, and this project cannot -- which is why it is a notice rather than a gate. - ~~**The settings-fragment merge has two unanswered questions, both raised by step 3a.**~~ **Answered 2026-09-10 (D5), and by dissolving the questions rather than deciding them.** A group's settings supply *defaults only*, and each agent's own `settings.toml` merges under that diff --git a/docs/plans/2026-08-28-multi-agent-grouping.md b/docs/plans/2026-08-28-multi-agent-grouping.md index 9e751333..7d131f3a 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping.md +++ b/docs/plans/2026-08-28-multi-agent-grouping.md @@ -2,7 +2,7 @@ | | | |---|---| -| **Status** | P0-P6, phases 0-8, the whole of 8b and **phase 9** landed on `feature/multi-agent-namespaces`. Next: phase 10. | +| **Status** | P0-P6, phases 0-8, the whole of 8b, phase 9 and **phase 10 steps 1-2** landed on `feature/multi-agent-namespaces`. Next: phase 10 step 3. | | **Amendment** | `docs/plans/2026-09-10-builder-unification.md` -- decided 2026-09-10. Phase 8b below is its work breakdown; phases 0 and 3 are superseded by it. Step 9 was added on 2026-09-10 and is not in that proposal's original breakdown. | | **Deferred out** | `docs/plans/2026-09-10-config-validation-unification.md` -- configuration validation is not part of this feature and **must not** be touched during 8b. | | **Spec (normative)** | `docs/specs/2026-08-28-multi-agent-grouping.md` | @@ -1133,6 +1133,23 @@ guide will contradict it directly. deployment without reading the spec, the plan, or this changelog -- and a reviewer can verify from the guide alone that nothing broker-side changed. +**Steps, each its own commit, reported before the next begins.** The CLI comes before the guides: +a guide written against a CLI that does not behave that way yet documents an API that does not +exist, which is the same failure this phase was put last to avoid. + +1. **A scaffolded project is a group of one, in every environment.** `src/main.py` becomes a + declaration (`agent = AppBuilder()...`, classes rather than instances, an unbuilt + `AgentBuilder`), a generated `agents.toml` maps the agent name to it, the Dockerfile's command + becomes `python -m blueprint.agents.entrypoint` and bakes no group, and `asbs dev` serves the + group under the agents' real namespaces. `asbs create` follows the new shape, because it edits + the file the generator wrote. **Landed.** +2. **`asbs validate` reports what a project must state before it can be grouped**, and closes the + scheduler gap from P5's open points: a project in `"event"` mode with nothing publishing its + tick is the remaining silent-failure case. **Landed.** +3. **`docs/guides/multi-agent-setup.md`** -- the five sections listed above. +4. **`docs/guides/deployment.md`** -- rewritten here, because the setup guide contradicts it + directly. + --- ## File change summary diff --git a/src/blueprint/agent_generator/base_files/Dockerfile b/src/blueprint/agent_generator/base_files/Dockerfile index 61f09b21..18e81616 100644 --- a/src/blueprint/agent_generator/base_files/Dockerfile +++ b/src/blueprint/agent_generator/base_files/Dockerfile @@ -31,7 +31,16 @@ RUN uv pip install --system --no-cache ".[dev]" ipython debugpy pytest ENV PYTHONPATH="/app/src" ENV DYNACONF_ENVIRONMENT="development" -CMD ["python", "-m", "debugpy", "--listen", "0.0.0.0:5678", "--wait-for-client", "-m", "uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"] +# A development default, and only in this stage: the production image bakes no group, so +# which agents it runs stays a deployment decision. This stage expects the project to be +# bind-mounted at /app, which is also where agents.toml is read from. +ENV BLUEPRINT_AGENTS="agent_namespace" + +# src/main.py declares an agent; it does not build one, so there is no `src.main:app` to +# serve. The framework's factory resolves this process's group and returns the application, +# which is what lets uvicorn reload it -- reload needs an import string, not a built object. +# BLUEPRINT_AGENTS above is a development default; a deployment sets its own. +CMD ["python", "-m", "debugpy", "--listen", "0.0.0.0:5678", "--wait-for-client", "-m", "uvicorn", "blueprint.agents.entrypoint:create_group_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--reload"] # ============================================================================ # Production - Minimal runtime image @@ -60,6 +69,11 @@ COPY --from=builder /usr/local/bin /usr/local/bin COPY --chown=appuser:appuser src ./src COPY --chown=appuser:appuser settings.toml ./ +# The agent map belongs to the image -- it lists the agents this image contains and where +# their declarations live. The group file does NOT: which of those agents a process runs is +# a deployment decision, so it arrives as a mount or as BLUEPRINT_AGENTS. See the ENTRYPOINT. +COPY --chown=appuser:appuser agents.toml ./ + # The disk cache backend writes here, and it cannot create this itself: WORKDIR made /app # root-owned, so mkdir() as appuser fails with EACCES. Created and handed over at build time, # which is also the mount point to use under a read-only root filesystem -- see the @@ -87,4 +101,13 @@ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ EXPOSE 8000 -ENTRYPOINT ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"] +# One command for every deployment. Which agents this process hosts is injected at container +# start, never baked in, so regrouping is a Deployment edit rather than a rebuild: +# +# docker run -e BLUEPRINT_AGENTS=agent_namespace +# docker run -v ./deployment-groups.yaml:/app/deployment-groups.yaml:ro \n# -e BLUEPRINT_GROUP= +# +# With neither, the process stops before binding the port and says which of the two is +# missing -- a crash-loop with a readable message rather than a pod that passes its probes +# while a queue goes unconsumed. +ENTRYPOINT ["python", "-m", "blueprint.agents.entrypoint"] diff --git a/src/blueprint/agent_generator/base_files/agents_toml.txt b/src/blueprint/agent_generator/base_files/agents_toml.txt new file mode 100644 index 00000000..44812288 --- /dev/null +++ b/src/blueprint/agent_generator/base_files/agents_toml.txt @@ -0,0 +1,18 @@ +# Which agents this image contains, and where each one's declaration lives. +# +# Baked into the image on purpose: adding or removing an agent is a rebuild anyway. Which of +# these agents a given *process* runs is a separate decision, made by the deployment rather +# than by the image -- set BLUEPRINT_AGENTS to a comma-separated list, or mount a group file +# and name the group with BLUEPRINT_GROUP. Nothing here says which agents run together. +# +# The name in brackets is the agent's namespace, and it is the agent's identity everywhere +# outside this file: the registry key prefix, the NATS queue group, part of the JetStream +# durable name, the cache partition, the OpenTelemetry service.name and the REST route prefix +# (/api/). Renaming it after the first deploy is therefore a consumer migration, not a +# rename. It must match [a-z][a-z0-9_]* -- lower case, no dashes. +# +# 'module' is "package.module:attribute", naming the AppBuilder that module assigns. An agent's +# own settings.toml, if it has one, is read from the directory that module lives in. + +[agents.agent_namespace] +module = "src.main:agent" diff --git a/src/blueprint/agent_generator/base_files/src/main.txt b/src/blueprint/agent_generator/base_files/src/main.txt index a3b2bed8..73deb235 100644 --- a/src/blueprint/agent_generator/base_files/src/main.txt +++ b/src/blueprint/agent_generator/base_files/src/main.txt @@ -1,19 +1,17 @@ """ app_name app_description -""" -from pathlib import Path +This file is a *declaration*, not an application: every ``with_*`` call records what this +agent is made of, and nothing is constructed until something calls ``build()``. That is what +lets the same file be served on its own and be hosted alongside other agents in one process -- +the host decides the configuration and the namespace each component is built in, and this file +never mentions either. -imports +Run it with ``python -m blueprint.agents.entrypoint``, which reads ``agents.toml`` to find +this declaration and the deployment's group to decide which agents the process hosts. +""" -# Initialize config -config = Config( - settings_files=[ - "settings.toml", - "secrets.toml", - ], - root_path=Path(__file__).parent.parent -) +imports -agents_and_app_initialization +agent_declaration diff --git a/src/blueprint/agent_generator/cli/commands/create.py b/src/blueprint/agent_generator/cli/commands/create.py index fd9d1284..3ec6af2f 100644 --- a/src/blueprint/agent_generator/cli/commands/create.py +++ b/src/blueprint/agent_generator/cli/commands/create.py @@ -15,6 +15,7 @@ normalize_component_name, add_import_to_main, add_component_registration_to_main, + insert_before_declaration, read_main_py, write_main_py, ) @@ -150,7 +151,7 @@ def create_handler(args: Namespace) -> None: auto_registered = True print("✓ Auto-registered in src/main.py") print(f" - Added import: from src.handlers.{module_name} import {class_name}") - print(f" - Added registration: .with_handler({class_name}())") + print(f" - Added registration: .with_handler({class_name})") except (FileNotFoundError, ValueError) as e: logger.debug("Could not auto-register handler: %s", e) @@ -167,7 +168,7 @@ def create_handler(args: Namespace) -> None: print(f" from .{module_name} import {class_name}") if not auto_registered: print(" 3. Add to src/main.py:") - print(f" .with_handler({class_name}())") + print(f" .with_handler({class_name})") def create_service(args: Namespace) -> None: @@ -243,7 +244,7 @@ def create_service(args: Namespace) -> None: auto_registered = True print("✓ Auto-registered in src/main.py") print(f" - Added import: from src.services.{module_name} import {class_name}") - print(f" - Added registration: .with_service({class_name}())") + print(f" - Added registration: .with_service({class_name})") except (FileNotFoundError, ValueError) as e: logger.debug("Could not auto-register service: %s", e) @@ -260,7 +261,7 @@ def create_service(args: Namespace) -> None: print(f" from .{module_name} import {class_name}") if not auto_registered: print(" 3. Add to src/main.py:") - print(f" .with_service({class_name}())") + print(f" .with_service({class_name})") def create_api(args: Namespace) -> None: @@ -487,7 +488,7 @@ async def create_item(self, request: {request_class_name}) -> {response_class_na print("✓ Auto-registered in src/main.py") print(f" - Added import: from src.models.{models_module_name} import {request_class_name}, {response_class_name}") print(f" - Added import: from src.api.{module_name} import {class_name}") - print(f" - Added registration: .with_rest_api({class_name}())") + print(f" - Added registration: .with_rest_api({class_name})") except (FileNotFoundError, ValueError) as e: logger.debug("Could not auto-register API: %s", e) @@ -509,7 +510,7 @@ async def create_item(self, request: {request_class_name}) -> {response_class_na print(" 6. Add to src/main.py:") print(f" from src.models.{models_module_name} import {request_class_name}, {response_class_name}") print(f" from src.api.{module_name} import {class_name}") - print(f" .with_rest_api({class_name}())") + print(f" .with_rest_api({class_name})") print(" 6. View docs at http://localhost:8000/docs") @@ -526,9 +527,10 @@ def create_agent(args: Namespace) -> None: """ # Use naming utilities to normalize the agent name - class_name, snake_name, file_name = normalize_component_name(args.name, "agent") - - module_name = file_name[:-3] # Remove .py extension + # Only the names: unlike the other components, an agent runtime has no module of its own. + # It is a builder in main.py plus two prompt files, which is why nothing here writes a + # src/agents/ file and why the next steps no longer tell the reader to import one. + class_name, snake_name, _ = normalize_component_name(args.name, "agent") # Get project root and directories project_root = Path.cwd() @@ -611,28 +613,28 @@ def create_agent(args: Namespace) -> None: agent_name = snake_name if snake_name.lower().endswith("agent") else snake_name + "_agent" - # Add agent variable declaration (before AppBuilder) - agent_var_declaration = f"""{agent_name}: AgentRuntime = (\n\tAgentBuilder(config=config, runtime_name="{agent_name}") - .with_model_from_config() - .with_system_prompt("{agent_name}_system") - .build(name="{agent_name}")\n)\n""" - - # Insert the agent variable before the 'app = (' line - lines = main_content.split("\n") - app_builder_idx = -1 - for i, line in enumerate(lines): - if line.strip().startswith("app = ("): - app_builder_idx = i - break - - if app_builder_idx >= 0: - # Insert the agent variable declaration before the AppBuilder - lines.insert(app_builder_idx, agent_var_declaration) - main_content = "\n".join(lines) - - # Add component registration to AppBuilder - # For agents, pass the variable name as instantiation (e.g., document_analyzer_agent) - instantiation = f"{agent_name}" + # An unbuilt AgentBuilder, and no configuration. AppBuilder.build() calls + # agent.build(config.for_namespace()), so the model, prompt and metrics are + # read from this agent's own configuration view. Building it here instead would bind it + # to whatever configuration happened to be in scope at this line -- which, in a group, + # is a neighbour's. + agent_var_declaration = ( + f"{agent_name} = (\n" + f' AgentBuilder(runtime_name="{agent_name}")\n' + " .with_model_from_config()\n" + f' .with_system_prompt("{agent_name}_system")\n' + ")\n" + ) + + if "from blueprint.agents.agent import AgentBuilder" not in main_content: + main_content = add_import_to_main(main_content, "from blueprint.agents.agent import AgentBuilder", "agent") + + main_content = insert_before_declaration(main_content, agent_var_declaration) + + # The name is given here rather than to AgentBuilder.build(): it is the registry key the + # services look the runtime up by (registry.get_agent("")), and AppBuilder + # qualifies it with the agent's namespace so two agents' runtimes cannot collide. + instantiation = f'{agent_name}, name="{agent_name}"' main_content = add_component_registration_to_main(main_content, agent_name, "agent", instantiation=instantiation) # Write updated main.py @@ -640,9 +642,8 @@ def create_agent(args: Namespace) -> None: auto_registered = True print("✓ Auto-registered in src/main.py") - print(f" - Added import: from src.agents.{module_name} import build_{agent_name}") - print(f" - Added agent declaration: {agent_name}: AgentRuntime = build_{agent_name}(config)") - print(f" - Added registration: .with_agent({agent_name})") + print(f" - Added declaration: {agent_name} = (AgentBuilder(...))") + print(f' - Added registration: .with_agent({agent_name}, name="{agent_name}")') except (FileNotFoundError, ValueError) as e: logger.debug("Could not auto-register agent: %s", e) @@ -656,13 +657,15 @@ def create_agent(args: Namespace) -> None: print("\nNext steps:") print(f" 1. Edit {system_prompt_file} to refine the system prompt") print(f" 2. Edit {instruction_prompt_file} to add dynamic instruction templates") - print(" 3. Add to src/agents/__init__.py:") - print(f" from .{module_name} import build_{agent_name}") if not auto_registered: - print(" 4. Add to src/main.py (before app = (...)):") - print(f" {agent_name}: AgentRuntime = build_{agent_name}(config)") - print(" 5. Add to src/main.py AppBuilder chain:") - print(f" .with_agent({agent_name})") + # Only the declaration: this command writes prompts and settings, and registers the + # runtime in main.py. There is no module under src/agents/ for it to be imported from. + print(" 3. Add to src/main.py, above the AppBuilder declaration:") + print(f' {agent_name} = (AgentBuilder(runtime_name="{agent_name}")') + print(" .with_model_from_config()") + print(f' .with_system_prompt("{agent_name}_system"))') + print(" 4. Add to src/main.py AppBuilder chain:") + print(f' .with_agent({agent_name}, name="{agent_name}")') def create_scheduler(args: Namespace) -> None: @@ -762,7 +765,7 @@ async def tick(self) -> None: auto_registered = True print("✓ Auto-registered in src/main.py") print(f" - Added import: from src.schedulers.{module_name} import {class_name}") - print(f" - Added registration: .with_scheduler({class_name}())") + print(f" - Added registration: .with_scheduler({class_name})") except (FileNotFoundError, ValueError) as e: logger.debug("Could not auto-register scheduler: %s", e) @@ -779,5 +782,5 @@ async def tick(self) -> None: print(f" from .{module_name} import {class_name}") if not auto_registered: print(" 3. Add to src/main.py:") - print(f" .with_scheduler({class_name}())") + print(f" .with_scheduler({class_name})") print(f"\nCron expression: {args.cron}") diff --git a/src/blueprint/agent_generator/cli/commands/dev.py b/src/blueprint/agent_generator/cli/commands/dev.py index 0fe0dce6..0f4cab35 100644 --- a/src/blueprint/agent_generator/cli/commands/dev.py +++ b/src/blueprint/agent_generator/cli/commands/dev.py @@ -1,23 +1,48 @@ """Dev command - start development server.""" import logging -import sys +import os import subprocess +import sys +import tomllib from argparse import Namespace from pathlib import Path logger = logging.getLogger(__name__) +AGENT_MAP_FILE = "agents.toml" +LEGACY_ENTRY_POINT = "src/main.py" + +GROUP_FACTORY = "blueprint.agents.entrypoint:create_group_app" +LEGACY_APP = "src.main:app" + +AGENTS_ENV = "BLUEPRINT_AGENTS" +GROUP_ENV = "BLUEPRINT_GROUP" + def run(args: Namespace) -> None: """Execute the dev command. + Runs the project the way the deployment does, under the agents' **real** namespaces. A + development server at the root namespace would serve ``/api/orders/{id}`` where production + serves ``/api/order/orders/{id}`` and would consume under a different queue group, so every + local URL and every local integration test would differ from the deployed one in a way + nothing reports. + Args: args: Parsed command-line arguments """ - # Check if we're in a project directory - if not Path("src/main.py").exists(): - print("Error: src/main.py not found", file=sys.stderr) + agent_map = Path(AGENT_MAP_FILE) + if agent_map.is_file(): + command = _group_command(args, agent_map) + elif Path(LEGACY_ENTRY_POINT).is_file(): + # A project scaffolded before the agent map existed still builds its own application in + # src/main.py. It is served the way it always was, at the root namespace, because that + # is the namespace it is deployed under too -- the two still agree. + print(f"No {AGENT_MAP_FILE}; serving {LEGACY_APP} at the root namespace.") + command = _legacy_command(args) + else: + print(f"Error: neither {AGENT_MAP_FILE} nor {LEGACY_ENTRY_POINT} found", file=sys.stderr) print("Make sure you're in a Blueprint Agents project directory", file=sys.stderr) sys.exit(1) @@ -26,24 +51,7 @@ def run(args: Namespace) -> None: print() try: - # Run uvicorn with reload. Use sys.executable (the interpreter that launched - # asbs) rather than a literal "python": on Windows with uv-managed venvs the - # latter can resolve to the base interpreter, which can't see the venv's - # site-packages (#15). - cmd = [ - sys.executable, - "-m", - "uvicorn", - "src.main:app", - "--reload", - "--host", - args.host, - "--port", - str(args.port), - ] - - subprocess.run(cmd, check=True) - + subprocess.run(command, check=True) except FileNotFoundError: print("Error: uvicorn not found", file=sys.stderr) print("Install with: pip install uvicorn", file=sys.stderr) @@ -54,3 +62,76 @@ def run(args: Namespace) -> None: except KeyboardInterrupt: print("\nServer stopped") sys.exit(0) + + +def _group_command(args: Namespace, agent_map: Path) -> list[str]: + """Return the uvicorn command that serves this project's agents as a group. + + Sets ``BLUEPRINT_AGENTS`` in this process's environment so the child inherits it, but only + when the environment names no group of its own: a developer who has exported + ``BLUEPRINT_GROUP`` or ``BLUEPRINT_AGENTS`` is reproducing a particular deployment, and + overriding that from a default read out of the agent map would quietly serve something else. + """ + if not _group_already_chosen(): + agents = _requested_agents(args) or _agents_in_map(agent_map) + os.environ[AGENTS_ENV] = ",".join(agents) + print(f"Hosting {len(agents)} agent(s): {', '.join(agents)}") + else: + print(f"Group taken from the environment ({GROUP_ENV}/{AGENTS_ENV}); the agent map is not consulted for it.") + + return _uvicorn_command(args, GROUP_FACTORY, factory=True) + + +def _legacy_command(args: Namespace) -> list[str]: + """Return the uvicorn command for a project that still builds its own application.""" + return _uvicorn_command(args, LEGACY_APP, factory=False) + + +def _uvicorn_command(args: Namespace, target: str, *, factory: bool) -> list[str]: + """Assemble the uvicorn invocation. + + Uses ``sys.executable`` (the interpreter that launched ``asbs``) rather than a literal + "python": on Windows with uv-managed venvs the latter can resolve to the base interpreter, + which can't see the venv's site-packages (#15). + """ + command = [sys.executable, "-m", "uvicorn", target] + if factory: + command.append("--factory") + command.extend(["--reload", "--host", args.host, "--port", str(args.port)]) + return command + + +def _group_already_chosen() -> bool: + """Report whether the environment already says which agents this process runs.""" + return any(os.environ.get(name, "").strip() for name in (GROUP_ENV, AGENTS_ENV)) + + +def _requested_agents(args: Namespace) -> list[str]: + """Return the agents named on the command line, if any.""" + requested = getattr(args, "agents", None) or "" + return [name.strip() for name in requested.split(",") if name.strip()] + + +def _agents_in_map(agent_map: Path) -> list[str]: + """Return every agent the image contains, which is the default group for development. + + Every agent rather than a guess at one: the map is the complete list of what this project + holds, and a developer who wants a subset says so with ``--agents``. Choosing one of several + here would be the tool deciding which agent is the interesting one. + + Raises: + SystemExit: if the map cannot be read or declares no agents. Either way there is nothing + to serve, and the failure names the file rather than surfacing from inside the + framework's group resolution. + """ + try: + document = tomllib.loads(agent_map.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError) as exc: + print(f"Error: {agent_map} could not be read: {exc}", file=sys.stderr) + sys.exit(1) + + agents = document.get("agents") + if not isinstance(agents, dict) or not agents: + print(f"Error: {agent_map} declares no [agents.] entries, so there is nothing to serve", file=sys.stderr) + sys.exit(1) + return [str(name) for name in agents] diff --git a/src/blueprint/agent_generator/cli/commands/setup.py b/src/blueprint/agent_generator/cli/commands/setup.py index 06ec7fc9..2598fd38 100644 --- a/src/blueprint/agent_generator/cli/commands/setup.py +++ b/src/blueprint/agent_generator/cli/commands/setup.py @@ -9,6 +9,7 @@ from typing import Any from ...generator.generator import AgentGenerator +from ...generator.part_generators import AgentMapPartGenerator from ...generator.part_generators.part_generator_base import PartGeneratorBase logger = logging.getLogger(__name__) @@ -160,19 +161,28 @@ def run(args: Namespace) -> None: print(" │ ├── api/") print(" │ ├── models/") print(" │ └── prompts/") + print(" ├── agents.toml") print(" ├── settings.toml") print(" ├── secrets.toml") print(" ├── Dockerfile") print(" └── .gitignore") + namespace = AgentMapPartGenerator.agent_namespace(config) print("\nNext steps:") print(f" 1. cd {project_name}") print(" 2. Review and edit the generated files") print(" 3. Add your LLM API key to secrets.toml") print(" (A secrets.toml with a placeholder has been created for you)") print(" 4. Install dependencies: pip install -e .") - print(" 5. Run the service: uvicorn src.main:app --reload") - print(" 6. View API docs at: http://localhost:8000/docs") + print(" 5. Run the service: asbs dev") + print(f" 6. View API docs at: http://localhost:8000/docs (this agent's routes are under /api/{namespace})") + + print("\nsrc/main.py declares this agent; it does not build an application.") + print(f"agents.toml names it '{namespace}', and that name is its identity on the broker,") + print("in telemetry and in its routes -- change it now if you are going to, because") + print("changing it after the first deploy is a consumer migration.") + print("The deployment decides which agents a process hosts:") + print(f" docker run -e BLUEPRINT_AGENTS={namespace} ") finally: # Clean up temporary config file diff --git a/src/blueprint/agent_generator/cli/commands/validate.py b/src/blueprint/agent_generator/cli/commands/validate.py index 7972c88f..aa30e3f7 100644 --- a/src/blueprint/agent_generator/cli/commands/validate.py +++ b/src/blueprint/agent_generator/cli/commands/validate.py @@ -1,14 +1,22 @@ """Validate command - check project structure and configuration.""" import logging +import re import sys import tomllib from argparse import Namespace from pathlib import Path from typing import Any +from blueprint.agents.component.namespace import validate_namespace +from blueprint.agents.config import PROCESS_SCOPE_KEYS +from blueprint.agents.io.api.scheduling.scheduler import SCHEDULER_MODE_EVENT, SCHEDULER_MODE_IN_PROCESS, SCHEDULER_MODES + logger = logging.getLogger(__name__) +AGENT_MAP_FILE = "agents.toml" +SETTINGS_FILE = "settings.toml" + IDEMPOTENCY_NOTICE = "\n".join( [ "Event deduplication is off ('idempotency_enabled' is not set), so every handler in", @@ -78,12 +86,12 @@ def run(args: Namespace) -> None: else: print("✓ Found src/main.py") - # Check if main.py uses AppBuilder + # Check if main.py uses AppBuilder. Nothing is checked about Config here: main.py is a + # declaration, and the configuration belongs to whatever builds it -- a main.py that + # mentions Config at all is the pre-declaration shape, not the expected one. content = main_file.read_text() if "AppBuilder" not in content: warnings.append("src/main.py does not appear to use AppBuilder") - if "Config" not in content: - warnings.append("src/main.py does not appear to use Config") # Check for component directories component_dirs = ["handlers", "services", "api", "models"] @@ -120,6 +128,13 @@ def run(args: Namespace) -> None: if notice: notices.append(notice) + # Group readiness: what this project must state before it can be hosted beside another + # agent, and what would otherwise stay silent. + group_issues, group_warnings, group_notices = _group_findings(project_dir) + issues.extend(group_issues) + warnings.extend(group_warnings) + notices.extend(group_notices) + # Print summary print() print("=" * 60) @@ -161,27 +176,315 @@ def _idempotency_notice(project_dir: Path) -> str | None: if not handlers_dir.is_dir() or not any(handlers_dir.glob("*_handler.py")): return None - settings_file = project_dir / "settings.toml" + settings_file = project_dir / SETTINGS_FILE if not settings_file.is_file(): return IDEMPOTENCY_NOTICE - try: - with settings_file.open("rb") as handle: - settings = tomllib.load(handle) - except (OSError, tomllib.TOMLDecodeError) as exc: - # A settings file that cannot be read is reported by its own check; guessing at the - # dedup setting from an unparseable file would be worse than staying quiet. - logger.debug("Could not read settings.toml for the idempotency check: %s", exc) + settings = _load_settings(settings_file) + if settings is None: return None # Dynaconf environments are top-level tables, and the key is valid in any of them. - if _declares_idempotency(settings): + if _declares(settings, "idempotency_enabled"): return None return IDEMPOTENCY_NOTICE -def _declares_idempotency(settings: dict[str, Any]) -> bool: - """Report whether ``idempotency_enabled`` appears at the top level or in any environment.""" - if "idempotency_enabled" in settings: +# ---------------------------------------------------------------------------------------------- +# Group readiness +# +# Everything below answers one question: can this project be hosted beside another agent in one +# process, and if not, what has it failed to say? There is deliberately no `asbs migrate` -- +# main.py is the developer's own declaration, and a tool that rewrites it either guesses at +# intent or fails on anything hand-edited. A checklist plus a validate that names what is +# missing is the honest shape. +# ---------------------------------------------------------------------------------------------- + +NO_AGENT_MAP_WARNING = "\n".join( + [ + "No agents.toml, so this project cannot be hosted by 'python -m blueprint.agents.entrypoint'.", + " That is not a fault in a project deployed on its own, which is served by its own", + " src/main.py as it always was. To make it hostable, three changes and nothing else:", + " - src/main.py: 'agent = AppBuilder()...' -- drop the config argument and the", + " trailing .build(), so the file declares rather than builds;", + " - Dockerfile: the command becomes 'python -m blueprint.agents.entrypoint';", + " - agents.toml: one [agents.] entry pointing at 'src.main:agent'.", + " The name chosen there becomes the queue group, part of the durable name and the", + " /api/ prefix, so it is a consumer migration to change after the first deploy.", + ] +) + + +def _group_findings(project_dir: Path) -> tuple[list[str], list[str], list[str]]: + """Report what stops this project being hosted as one agent among several. + + Args: + project_dir: The project root. + + Returns: + Issues, warnings and notices, in that order. + """ + issues: list[str] = [] + warnings: list[str] = [] + notices: list[str] = [] + + agent_map_file = project_dir / AGENT_MAP_FILE + if not agent_map_file.is_file(): + warnings.append(NO_AGENT_MAP_WARNING) + agents: dict[str, str] = {} + else: + agents, map_issues = _read_agent_map(agent_map_file) + issues.extend(map_issues) + if agents: + print(f"[ok] Found {AGENT_MAP_FILE} ({len(agents)} agent(s): {', '.join(agents)})") + + for name, module in agents.items(): + issues.extend(_declaration_issues(project_dir, name, module)) + warnings.extend(_settings_scope_warnings(project_dir, name, module, hosted_alone=len(agents) == 1)) + + scheduler_issues, scheduler_notices = _scheduler_findings(project_dir) + issues.extend(scheduler_issues) + notices.extend(scheduler_notices) + + return issues, warnings, notices + + +def _read_agent_map(agent_map_file: Path) -> tuple[dict[str, str], list[str]]: + """Return ``{agent name: "module:attribute"}`` and whatever is wrong with the file. + + The same shape ``GroupConfig._read_agent_map`` refuses to start on, checked here instead -- + where the answer is a line in a terminal rather than a crash-looping pod. The agent name is + held to the namespace alphabet by the framework's own validator, because a name repaired + differently by the queue group, the durable, the cache partition and the telemetry resource + is four names for one agent. + """ + try: + document = tomllib.loads(agent_map_file.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError) as exc: + return {}, [f"{AGENT_MAP_FILE} could not be read: {exc}"] + + declared = document.get("agents") + if not isinstance(declared, dict) or not declared: + return {}, [f"{AGENT_MAP_FILE} declares no [agents.] entries, so this image contains no agents"] + + agents: dict[str, str] = {} + issues: list[str] = [] + for name, entry in declared.items(): + module = entry.get("module") if isinstance(entry, dict) else None + if not module or not isinstance(module, str): + issues.append(f"Agent '{name}' in {AGENT_MAP_FILE} has no 'module'. Write it as module = \"src.main:agent\"") + continue + if ":" not in module: + issues.append( + f"Agent '{name}' in {AGENT_MAP_FILE} names the module '{module}', which does not say which attribute " + 'to read. Write it as "package.module:attribute"' + ) + continue + try: + validate_namespace(name) + except ValueError as exc: + issues.append(f"Agent '{name}' in {AGENT_MAP_FILE} cannot be a namespace: {exc}") + continue + agents[str(name)] = module + + return agents, issues + + +def _declaration_issues(project_dir: Path, name: str, module: str) -> list[str]: + """Report an agent whose declaration cannot be found, or is not a declaration. + + Checked against the file rather than by importing it: importing runs the module, which needs + the project's dependencies installed and is a different failure from the one being looked for. + What that costs is precision -- this reads text -- and what it buys is a validate that works + in a checkout. + """ + module_path, _, attribute = module.partition(":") + source = _module_file(project_dir, module_path) + if source is None: + return [ + f"Agent '{name}' points at '{module_path}', which is not a module in this project. Either the agent map " + "is out of date, or the declaration moved and the map did not" + ] + + text = source.read_text(encoding="utf-8") + if not re.search(rf"^{re.escape(attribute)}\s*=", text, re.MULTILINE): + return [ + f"Agent '{name}' points at '{module}', but {source.relative_to(project_dir).as_posix()} assigns no " + f"'{attribute}'. That is the AppBuilder the host builds; without it the process stops before binding " + "its port" + ] + return [] + + +def _settings_scope_warnings(project_dir: Path, name: str, module: str, *, hosted_alone: bool) -> list[str]: + """Report settings that will not survive this agent being hosted beside another. + + Two things go wrong, and neither raises. An agent's own settings file is read from the + directory its declaration lives in, so one written anywhere else is merged into no scope at + all; and a key that describes the *process* -- the port it binds, the bus it speaks, the + environment it loads -- is dropped with a warning when it arrives under one agent's scope, + because one process has exactly one of each. + + A project hosted alone is the process, so its settings.toml is the process's own file and + neither applies: it is reported only once there is a second agent to share with. The same + exemption covers an agent declared at the project root in a group -- ``main:agent`` rather + than ``src.main:agent`` -- whose settings file *is* the process's, which the merge recognises + and leaves at the root rather than scoping. + """ + if hosted_alone: + return [] + + module_path = module.partition(":")[0] + source = _module_file(project_dir, module_path) + if source is None: + return [] + + fragment = source.parent / SETTINGS_FILE + if fragment == project_dir / SETTINGS_FILE: + return [] + + if not fragment.is_file(): + return [ + f"Agent '{name}' ships no settings of its own: its declaration is in " + f"{source.parent.relative_to(project_dir).as_posix()}/ and an agent's settings.toml is read from there. " + "Every key it reads will come from the group's own settings file, where it is shared with the other agents" + ] + + settings = _load_settings(fragment) + if settings is None: + return [] + + scoped = sorted(key for key in PROCESS_SCOPE_KEYS if _declares(settings, key)) + if not scoped: + return [] + return [ + f"Agent '{name}' declares the process-scope key(s) {', '.join(scoped)} in " + f"{fragment.relative_to(project_dir).as_posix()}. One process binds one port, speaks one event bus and loads " + "one environment, so these are dropped with a warning when this agent's settings are merged under its own " + "scope. Move them to the group's settings file" + ] + + +def _scheduler_findings(project_dir: Path) -> tuple[list[str], list[str]]: + """Report a scheduler that has not said how it is fired, or that nothing fires. + + ``scheduler_mode`` has no default and fails at ``build()`` when a scheduler is registered + without it, so that half is only reported earlier here. The half that fails *nowhere* is the + reason this check exists: ``"event"`` mode starts no timer and waits for a tick that an + external ``CronJob`` must publish, and nothing in this repository generates one -- so a + project can be correct in every mechanical respect and simply never run. + """ + schedulers = _scheduler_modules(project_dir) + if not schedulers: + return [], [] + + settings = _load_settings(project_dir / SETTINGS_FILE) + mode = _value_of(settings, "scheduler_mode") if settings is not None else None + + if mode is None: + return [ + f"{len(schedulers)} scheduler(s) under src/schedulers/ and no 'scheduler_mode' in {SETTINGS_FILE}. It has " + f"no default, because neither value is safe to inherit, so build() fails: set '{SCHEDULER_MODE_IN_PROCESS}' " + f"to run a timer in the process (needs .with_cache(), or every replica runs every tick) or " + f"'{SCHEDULER_MODE_EVENT}' to take the tick as an event (needs 'event_bus', and something publishing it)" + ], [] + + if mode not in SCHEDULER_MODES: + return [f"'scheduler_mode' is {mode!r} in {SETTINGS_FILE}; it must be one of {', '.join(SCHEDULER_MODES)}"], [] + + issues: list[str] = [] + notices: list[str] = [] + if mode == SCHEDULER_MODE_EVENT: + # A notice, not an issue: nothing here can tell whether a CronJob exists, and the thing + # that would know -- the deployment -- is outside this project. The framework cannot + # report it either, which is exactly why it is said here. + notices.append( + "\n".join( + [ + f"'scheduler_mode' is '{SCHEDULER_MODE_EVENT}', so no timer runs in this process: each tick", + " arrives as an event on '.scheduler.', published by an external", + " CronJob. Nothing in this project generates that CronJob, and a scheduler waiting for a", + " tick nobody publishes reports itself healthy and never runs. Confirm one exists, on the", + " schedule the scheduler declares, for every scheduler under src/schedulers/.", + ] + ) + ) + if not _declares(settings or {}, "event_bus"): + # This one *does* fail at startup -- the tick is an ordinary event, so without a + # transport there is nothing to subscribe to -- so it is an issue rather than advice. + issues.append( + f"'scheduler_mode' is '{SCHEDULER_MODE_EVENT}' and no 'event_bus' is set. The tick arrives as an event, " + "so there is nothing to subscribe to and wiring the scheduler fails at startup" + ) + elif not _main_declares_a_cache(project_dir): + notices.append( + "\n".join( + [ + f"'scheduler_mode' is '{SCHEDULER_MODE_IN_PROCESS}' and src/main.py declares no cache. Each tick is", + " claimed in the agent's own cache so that one replica runs it; with no cache to claim in,", + " every replica runs every tick. Add .with_cache() unless this runs as a single replica.", + ] + ) + ) + return issues, notices + + +def _scheduler_modules(project_dir: Path) -> list[Path]: + """Return the scheduler modules this project defines.""" + schedulers_dir = project_dir / "src" / "schedulers" + if not schedulers_dir.is_dir(): + return [] + return [path for path in sorted(schedulers_dir.glob("*.py")) if path.name != "__init__.py"] + + +def _main_declares_a_cache(project_dir: Path) -> bool: + """Report whether the declaration registers a cache for the tick claim to use.""" + main_file = project_dir / "src" / "main.py" + return main_file.is_file() and ".with_cache(" in main_file.read_text(encoding="utf-8") + + +def _module_file(project_dir: Path, module_path: str) -> Path | None: + """Resolve a dotted module path to the file that defines it, or ``None``.""" + relative = Path(*module_path.split(".")) + for candidate in (project_dir / relative.with_suffix(".py"), project_dir / relative / "__init__.py"): + if candidate.is_file(): + return candidate + return None + + +def _load_settings(settings_file: Path) -> dict[str, Any] | None: + """Parse a settings file, or ``None`` when there is nothing readable to parse. + + A file that cannot be read is reported by its own check; guessing at a key from an + unparseable file would be worse than staying quiet. + """ + if not settings_file.is_file(): + return None + try: + with settings_file.open("rb") as handle: + return tomllib.load(handle) + except (OSError, tomllib.TOMLDecodeError) as exc: + logger.debug("Could not read %s: %s", settings_file, exc) + return None + + +def _declares(settings: dict[str, Any], key: str) -> bool: + """Report whether ``key`` appears at the top level or in any Dynaconf environment.""" + if key in settings: return True - return any(isinstance(value, dict) and "idempotency_enabled" in value for value in settings.values()) + return any(isinstance(value, dict) and key in value for value in settings.values()) + + +def _value_of(settings: dict[str, Any], key: str) -> Any | None: + """Return ``key``'s value from the top level, or from the first environment that sets it. + + Which environment is in force is a runtime decision this command cannot make, so a key set + in any of them counts as set. That is the right answer for the checks here, which ask whether + the author has *decided* something, not what today's value is. + """ + if key in settings: + return settings[key] + for value in settings.values(): + if isinstance(value, dict) and key in value: + return value[key] + return None diff --git a/src/blueprint/agent_generator/cli/main.py b/src/blueprint/agent_generator/cli/main.py index f129261b..021718b8 100644 --- a/src/blueprint/agent_generator/cli/main.py +++ b/src/blueprint/agent_generator/cli/main.py @@ -144,7 +144,11 @@ def main() -> None: dev_parser = subparsers.add_parser( "dev", help="Start development server", - description="Run the application with hot reload", + description="Run this project's agents with hot reload, under the namespaces they deploy under", + ) + dev_parser.add_argument( + "--agents", + help="Comma-separated agents to host (default: every agent in agents.toml)", ) dev_parser.add_argument( "--port", diff --git a/src/blueprint/agent_generator/cli/utils/naming_utils.py b/src/blueprint/agent_generator/cli/utils/naming_utils.py index 31621402..d52376ef 100644 --- a/src/blueprint/agent_generator/cli/utils/naming_utils.py +++ b/src/blueprint/agent_generator/cli/utils/naming_utils.py @@ -195,12 +195,46 @@ def add_import_to_main(main_content: str, import_statement: str, component_type: return "\n".join(lines) +def insert_before_declaration(main_content: str, block: str) -> str: + """Insert ``block`` immediately above the statement that opens the AppBuilder chain. + + The chain is written as an assignment whose right-hand side opens a parenthesis -- + ``agent = (`` in a scaffolded project, ``app = (`` in one that still builds itself -- so + the anchor is the assignment line, found by matching that shape and confirming the builder + appears on the next line. Matching on the variable's *name* is what this replaces: it hard + coded ``app = (``, which the declaration-only shape does not contain, so a new agent's + declaration was silently not inserted and the registration referred to a name that did not + exist. + + Args: + main_content: Current content of main.py + block: The source to insert, ending in a newline. + + Returns: + The updated content, unchanged if no AppBuilder assignment could be found. + """ + lines = main_content.split("\n") + for index, line in enumerate(lines): + if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]* = \(", line.strip()): + continue + if index + 1 < len(lines) and "AppBuilder(" in lines[index + 1]: + lines.insert(index, block) + return "\n".join(lines) + return main_content + + def extract_component_registrations(main_content: str) -> tuple[list[tuple[str, str]], int, int]: """ Extract all component registrations from the AppBuilder chain. Finds and returns all .with_* method calls along with their line indices. + A declaration ends in one of two ways, and both have to be recognised. A scaffolded + ``main.py`` assigns the builder and stops -- ``agent = (AppBuilder()...)`` with no + ``build()`` call, because the host builds it -- so the chain closes at the ``)`` in the + first column. A project written before that shape, or one that still serves itself, ends + the chain with ``.build()``. Finding neither is what the caller treats as malformed. + Args: main_content: Content of main.py file @@ -208,7 +242,8 @@ def extract_component_registrations(main_content: str) -> tuple[list[tuple[str, Tuple of: - List of (component_type, full_line) tuples - Index of line with "AppBuilder(" - - Index of line with ".build()" + - Index of the line that closes the chain: the ``.build()`` call, or the ``)`` that + ends the assignment, whichever the file uses. ``-1`` if neither is present. """ lines = main_content.split("\n") components = [] @@ -238,9 +273,29 @@ def extract_component_registrations(main_content: str) -> tuple[list[tuple[str, components.append((comp_type, line)) break + if build_idx < 0 <= app_builder_idx: + build_idx = _closing_parenthesis_index(lines, app_builder_idx) + return components, app_builder_idx, build_idx +def _closing_parenthesis_index(lines: list[str], app_builder_idx: int) -> int: + """Return the index of the ``)`` that closes a declaration-only AppBuilder chain. + + The first line after the builder that begins a statement of its own -- unindented, and + opening with ``)``. Searching for that rather than counting brackets keeps this honest + about what it is: a line-oriented editor for a file the generator wrote in a known shape, + not a parser. A hand-edited file it cannot read is reported, never guessed at. + + Returns: + The line index, or ``-1`` if the chain is never closed in the first column. + """ + for index in range(app_builder_idx + 1, len(lines)): + if lines[index].startswith(")"): + return index + return -1 + + def sort_components(components: list[tuple[str, str]]) -> list[tuple[str, str]]: """ Sort components according to Framework dependency order. @@ -292,11 +347,16 @@ def add_component_registration_to_main( previously out of order. Modifies the AppBuilder chain to include the new component: - - For services: adds .with_service(ServiceClass()) - - For handlers: adds .with_handler(HandlerClass()) - - For APIs: adds .with_rest_api(ApiClass()) - - For schedulers: adds .with_scheduler(SchedulerClass()) - - For agents: adds .with_agent(agent_name) + - For services: adds .with_service(ServiceClass) + - For handlers: adds .with_handler(HandlerClass) + - For APIs: adds .with_rest_api(ApiClass) + - For schedulers: adds .with_scheduler(SchedulerClass) + - For agents: adds .with_agent(agent_name, name="agent_name") + + The class, not an instance of it. A component constructed on the ``with_*`` line is + constructed before any namespace exists and belongs to the root for ever, which is why a + group refuses an already-built instance; the class is constructed by ``build()`` inside the + agent's own scope and works in both shapes. Args: main_content: Current content of main.py @@ -318,12 +378,9 @@ def add_component_registration_to_main( method_name = methods.get(component_type, "with_service") - # Build the instantiation if not provided - if not instantiation: - if component_type == "agent": - instantiation = class_name - else: - instantiation = f"{class_name}()" + # Build the instantiation if not provided. The class itself, never a call: see the + # docstring -- an instance is refused when the agent is hosted in a group. + instantiation = instantiation or class_name # Build the registration line for the new component new_registration_line = f" .{method_name}({instantiation})" diff --git a/src/blueprint/agent_generator/generator/generator.py b/src/blueprint/agent_generator/generator/generator.py index 78060f7d..f952a0db 100644 --- a/src/blueprint/agent_generator/generator/generator.py +++ b/src/blueprint/agent_generator/generator/generator.py @@ -8,6 +8,7 @@ from typing import Any from .part_generators import ( + AgentMapPartGenerator, APIPartGenerator, CopyPartGenerator, DomainModelPartGenerator, @@ -335,8 +336,20 @@ def _create_files_from_templates(self) -> None: f"{self.config['agent_layer'][agent_name]['runtime_name']}_instruction.prompt", ).create_file(out) + # Create the agent map. Without it nothing can resolve this project's agent name to + # its declaration, so `python -m blueprint.agents.entrypoint` -- the image's command -- + # would refuse to start. + AgentMapPartGenerator(self.config, self.template_dir, "").create_file(out) + # Create Dockerfile - CopyPartGenerator(self.config, self.template_dir, "", "Dockerfile", "Dockerfile").create_file(out) + CopyPartGenerator( + self.config, + self.template_dir, + "", + "Dockerfile", + "Dockerfile", + template_vars={"agent_namespace": AgentMapPartGenerator.agent_namespace(self.config)}, + ).create_file(out) # Create .gitignore CopyPartGenerator(self.config, self.template_dir, "", "template_for_git_ignore.txt", ".gitignore").create_file(out) diff --git a/src/blueprint/agent_generator/generator/part_generators/__init__.py b/src/blueprint/agent_generator/generator/part_generators/__init__.py index efd07e35..7c8910d0 100644 --- a/src/blueprint/agent_generator/generator/part_generators/__init__.py +++ b/src/blueprint/agent_generator/generator/part_generators/__init__.py @@ -1,4 +1,5 @@ from .main_part_generator import MainPartGenerator +from .agent_map_part_generator import AgentMapPartGenerator from .api_part_generator import APIPartGenerator from .service_part_generator import ServicePartGenerator from .init_part_generator import InitPartGenerator @@ -10,6 +11,7 @@ __all__ = [ "MainPartGenerator", + "AgentMapPartGenerator", "APIPartGenerator", "ServicePartGenerator", "InitPartGenerator", diff --git a/src/blueprint/agent_generator/generator/part_generators/agent_map_part_generator.py b/src/blueprint/agent_generator/generator/part_generators/agent_map_part_generator.py new file mode 100644 index 00000000..46c1519d --- /dev/null +++ b/src/blueprint/agent_generator/generator/part_generators/agent_map_part_generator.py @@ -0,0 +1,52 @@ +from pathlib import Path +from typing import Any + +from blueprint.agents.component.namespace import validate_namespace + +from .part_generator_base import PartGeneratorBase + + +class AgentMapPartGenerator(PartGeneratorBase): + """Generate ``agents.toml``, the map from agent name to declaration. + + The framework resolves an agent name to code through this file and through nothing else -- + there is no discovery by convention, because a set of agents that depends on what happens + to be importable makes a renamed directory a silently removed agent. So a project that + does not ship one cannot be hosted by ``python -m blueprint.agents.entrypoint`` at all. + + The name is validated here rather than repaired. It becomes a namespace, and from there a + queue group, a durable name, a cache partition and a telemetry ``service.name``; a name + quietly rewritten to fit would be four different names for one agent. Refusing it at + scaffolding time is the one moment it is still free to change. + """ + + def __init__(self, config: dict[str, Any], template_dir: str | Path, src_path: str) -> None: + super().__init__(config, template_dir, src_path) + self.template_file_name = "agents_toml.txt" + self.template_vars["agent_namespace"] = self.agent_namespace(config) + + @classmethod + def agent_namespace(cls, config: dict[str, Any]) -> str: + """Return the namespace this project's agent is deployed under. + + The project name in snake case. Derived rather than asked for, because a project that + has exactly one agent has no second name to give it -- and the derivation is visible in + the generated file, which is where it can be changed before the first deploy. + + Raises: + ValueError: if the project name does not survive the derivation as a legal + namespace -- a leading digit, for instance. The generator fails rather than + writing a project that cannot start. + """ + namespace = cls.camel_to_snake(config["name"]) + try: + return validate_namespace(namespace) + except ValueError as exc: + raise ValueError( + f"Project name '{config['name']}' gives the agent namespace '{namespace}', which cannot be used: " + f"{exc} Choose a project name whose snake_case form matches [a-z][a-z0-9_]*." + ) from exc + + def to_py_file_name(self) -> str: + """The agent map is TOML, and lives at the project root.""" + return "agents.toml" diff --git a/src/blueprint/agent_generator/generator/part_generators/copy_part_generator.py b/src/blueprint/agent_generator/generator/part_generators/copy_part_generator.py index aa9a12a7..192fd1d6 100644 --- a/src/blueprint/agent_generator/generator/part_generators/copy_part_generator.py +++ b/src/blueprint/agent_generator/generator/part_generators/copy_part_generator.py @@ -5,12 +5,28 @@ class CopyPartGenerator(PartGeneratorBase): + """Copy one template file out under a chosen name, substituting any variables given. + + Substitution is the base class's, so a template copied with no ``template_vars`` is copied + byte for byte -- which is what most callers want. The Dockerfile is the exception: it names + the agent in the environment variable a developer runs the image with, and a literal + placeholder there would be a command that looks runnable and is not. + """ + def __init__( - self, config: dict[str, Any], template_dir: str | Path, src_path: str, template_file_name: str, output_file_name: str + self, + config: dict[str, Any], + template_dir: str | Path, + src_path: str, + template_file_name: str, + output_file_name: str, + template_vars: dict[str, str] | None = None, ) -> None: super().__init__(config, template_dir, src_path) self.template_file_name = template_file_name self.output_file_name = output_file_name + if template_vars: + self.template_vars.update(template_vars) def to_py_file_name(self) -> str: """Converts a file name to a corresponding Python file name.""" diff --git a/src/blueprint/agent_generator/generator/part_generators/main_part_generator.py b/src/blueprint/agent_generator/generator/part_generators/main_part_generator.py index 17bc4fa0..ee8bb398 100644 --- a/src/blueprint/agent_generator/generator/part_generators/main_part_generator.py +++ b/src/blueprint/agent_generator/generator/part_generators/main_part_generator.py @@ -5,7 +5,26 @@ class MainPartGenerator(PartGeneratorBase): - """Generate main.py for the agents blueprint.""" + """Generate main.py for the agents blueprint. + + What it writes is a declaration and nothing else: ``agent = AppBuilder()...`` with no + configuration, no ``build()`` and no module-level ``app``. The declaration is the unit the + framework hosts -- ``agents.toml`` points at this module's ``agent`` attribute, and + ``python -m blueprint.agents.entrypoint`` builds it under the namespace the deployment's + group gives it. + + Two consequences are deliberate and are why this generator changed shape: + + - **Classes, not instances.** ``with_service(OrderService)`` rather than + ``with_service(OrderService())``. A component constructed on the ``with_*`` line is + constructed before any namespace exists, so it belongs to the root for ever; a group + refuses an already-built instance for that reason. The class form is built by ``build()`` + inside the agent's own scope and works in both shapes. + - **An unbuilt ``AgentBuilder``.** ``with_agent`` hands it ``config.for_namespace()`` + at build time, so the model and prompt come from this agent's own configuration view + rather than from whatever configuration happened to be in scope where the chain was + written. + """ def __init__(self, config: dict[str, Any], template_dir: str | Path, src_path: str) -> None: super().__init__(config, template_dir, src_path) @@ -13,7 +32,7 @@ def __init__(self, config: dict[str, Any], template_dir: str | Path, src_path: s self.template_vars["app_name"] = self.config["name"] self.template_vars["app_description"] = self.config["description"] self.template_vars["imports"] = self._generate_main_imports() - self.template_vars["agents_and_app_initialization"] = self._generate_agents_and_app_initialization() + self.template_vars["agent_declaration"] = self._generate_agent_declaration() def _generate_main_imports(self) -> str: """Generate import statements for main.py.""" @@ -22,10 +41,8 @@ def _generate_main_imports(self) -> str: if self.config["agent_layer"]: lines.append("from blueprint.agents.agent import AgentBuilder") lines.append("from blueprint.agents.app_builder import AppBuilder") - if self.config["agent_layer"]: - lines.append("from blueprint.agents.agent import AgentRuntime") - lines.extend(["from blueprint.agents.config import Config", ""]) + lines.append("") if self.config["communication_layer"].get("rest_api", {}).get("add_rest_api", False): lines.append(f"from .api import {self.config['communication_layer']['rest_api']['name']}") @@ -44,47 +61,54 @@ def _generate_main_imports(self) -> str: return "\n".join(lines) - def _generate_agents_and_app_initialization(self) -> str: - """Generate app initialization code for main.py.""" + def _generate_agent_declaration(self) -> str: + """Generate the agent runtimes and the ``agent = AppBuilder()...`` declaration. - lines = [] - if self.config["agent_layer"]: - lines.append("# Initialize agents") + Each runtime is declared as a module-level ``AgentBuilder`` rather than inline, so that + every line of the chain is one registration. That is what ``asbs create`` needs: it + rewrites the chain line by line to keep it in dependency order, and a registration + spanning several lines would lose its continuation lines on the next ``asbs create``. + The same shape is what ``asbs create agent`` writes, so a generated project and one + grown with the CLI stay identical. + + The chain is emitted in ``sort_components`` order -- services, agents, handlers, REST + APIs -- for the same reason: the first ``asbs create`` would otherwise reorder + everything and make its diff unreadable. + """ - for agent_name, agent in self.config["agent_layer"].items(): + lines: list[str] = [] + + for agent in self.config["agent_layer"].values(): + runtime_name = agent["runtime_name"] lines.extend( [ - f"{agent['runtime_name']}: AgentRuntime = (", - f' AgentBuilder(config, runtime_name="{agent["runtime_name"]}")', + f"{runtime_name} = (", + f' AgentBuilder(runtime_name="{runtime_name}")', " .with_model_from_config()", - f' .with_system_prompt("{self.camel_to_snake(agent_name)}_system")', - f' .build(name="{self.camel_to_snake(agent_name)}")', + f' .with_system_prompt("{runtime_name}_system")', ")", "", ] ) - # Build the application - lines.extend(["# Build the application", "app = (", " AppBuilder(config=config)"]) - - # Add agents - for agent in self.config["agent_layer"]: - lines.append(f" .with_agent({self.config['agent_layer'][agent]['runtime_name']})") + lines.extend(["agent = (", " AppBuilder()"]) - # Add services for service_name in self.config["service_layer"]: - lines.append(f" .with_service({service_name}())") + lines.append(f" .with_service({service_name})") + + for agent in self.config["agent_layer"].values(): + # The name is given to with_agent rather than to AgentBuilder.build(): it is the + # registry key the services resolve the runtime by, and AppBuilder qualifies it with + # the agent's namespace so two agents' runtimes cannot collide on it. + lines.append(f' .with_agent({agent["runtime_name"]}, name="{agent["runtime_name"]}")') - # Add handlers if "handlers" in self.config["communication_layer"]: for handler_name in self.config["communication_layer"]["handlers"]: - lines.append(f" .with_handler({handler_name}())") + lines.append(f" .with_handler({handler_name})") - # Add REST API if needed if self.config["communication_layer"].get("rest_api", {}).get("add_rest_api", False): - lines.append(f" .with_rest_api({self.config['communication_layer']['rest_api']['name']}())") + lines.append(f" .with_rest_api({self.config['communication_layer']['rest_api']['name']})") - lines.append(" .build()") lines.append(")") return "\n".join(lines) diff --git a/src/blueprint/agents/entrypoint.py b/src/blueprint/agents/entrypoint.py index 41c08495..009a3ecc 100644 --- a/src/blueprint/agents/entrypoint.py +++ b/src/blueprint/agents/entrypoint.py @@ -58,6 +58,37 @@ def build_group_app(*, environ: dict[str, str] | None = None) -> tuple[FastAPI, return app, config +def create_group_app(*, environ: dict[str, str] | None = None) -> FastAPI: + """Return this process's group as an application, for a server that imports it. + + ``build_group_app`` returns the configuration as well, because :func:`main` needs it to + decide the host, port and worker count it serves on. A reloading server has no use for + that half and cannot accept it: uvicorn's ``--factory`` calls the named object and expects + the application back, so ``uvicorn blueprint.agents.entrypoint:create_group_app --factory + --reload`` is what this exists for, and it is what ``asbs dev`` runs. + + Auto-reload needs an *import string* rather than a built object, which is why this cannot + be done by calling :func:`build_group_app` from a project's own module: uvicorn imports the + target itself in each worker, after every edit (see ``run_app``, which for that reason never + enables reload). + + A resolution failure is left to propagate here rather than being turned into an exit status. + The caller is a developer's terminal, not Kubernetes, and a traceback naming the file and the + line is more use there than the one-line message a crash-looping pod needs. + + Args: + environ: The environment to resolve the group from, for tests. + + Returns: + The application this process's group assembles to. + + Raises: + GroupConfigError: if the group cannot be resolved or a critical agent cannot be loaded. + """ + app, _ = build_group_app(environ=environ) + return app + + def main(*, environ: dict[str, str] | None = None) -> int: """Serve this process's group, or fail with a message and a non-zero status. diff --git a/tests/unit/agent_generator/cli/commands/test_dev.py b/tests/unit/agent_generator/cli/commands/test_dev.py index 157b913e..53500dfb 100644 --- a/tests/unit/agent_generator/cli/commands/test_dev.py +++ b/tests/unit/agent_generator/cli/commands/test_dev.py @@ -1,27 +1,118 @@ -"""Unit tests for the `asbs dev` command (issue #15).""" +"""Unit tests for the `asbs dev` command (issue #15, and phase 10's group-of-one dev server).""" +import os import sys from argparse import Namespace +from pathlib import Path from unittest.mock import patch +import pytest + from blueprint.agent_generator.cli.commands import dev +AGENT_MAP = '[agents.orders]\nmodule = "src.main:agent"\n\n[agents.billing]\nmodule = "src.main:agent"\n' + + +@pytest.fixture(autouse=True) +def _no_inherited_group(monkeypatch: pytest.MonkeyPatch): + """Isolate the group variables in both directions. + + The command reads the environment before it defaults, so a developer's own must not leak + in; and it *sets* BLUEPRINT_AGENTS in this process so the server it spawns inherits it, so + what it sets must not leak out into the rest of the suite. + """ + monkeypatch.delenv(dev.AGENTS_ENV, raising=False) + monkeypatch.delenv(dev.GROUP_ENV, raising=False) + yield + os.environ.pop(dev.AGENTS_ENV, None) + + +def _run(tmp_path: Path, **overrides: object) -> list[str]: + """Run the command in ``tmp_path`` with the server mocked, and return the command it spawned.""" + args = Namespace(host="127.0.0.1", port=8000, agents=None) + for key, value in overrides.items(): + setattr(args, key, value) + + with patch("blueprint.agent_generator.cli.commands.dev.subprocess.run") as mock_run: + cwd = os.getcwd() + os.chdir(tmp_path) + try: + dev.run(args) + finally: + os.chdir(cwd) + + return list(mock_run.call_args.args[0]) + class TestRunInterpreter: - def test_spawns_uvicorn_with_sys_executable_not_literal_python(self) -> None: + def test_spawns_uvicorn_with_sys_executable_not_literal_python(self, tmp_path: Path) -> None: """The subprocess must use the launching interpreter (venv-correct on Windows), not the literal "python" which can resolve to uv's base interpreter.""" - args = Namespace(host="127.0.0.1", port=8000) - with ( - patch("blueprint.agent_generator.cli.commands.dev.Path") as mock_path, - patch("blueprint.agent_generator.cli.commands.dev.subprocess.run") as mock_run, - ): - mock_path.return_value.exists.return_value = True - dev.run(args) + (tmp_path / "agents.toml").write_text(AGENT_MAP, encoding="utf-8") + + cmd = _run(tmp_path) - cmd = mock_run.call_args.args[0] assert cmd[0] == sys.executable assert cmd[0] != "python" + + +class TestAProjectWithAnAgentMap: + """It is served as a group, under the agents' real namespaces.""" + + def test_it_serves_the_frameworks_group_factory(self, tmp_path: Path) -> None: + (tmp_path / "agents.toml").write_text(AGENT_MAP, encoding="utf-8") + + cmd = _run(tmp_path) + + assert cmd[1:5] == ["-m", "uvicorn", "blueprint.agents.entrypoint:create_group_app", "--factory"] + assert cmd[-5:] == ["--reload", "--host", "127.0.0.1", "--port", "8000"] + + def test_every_agent_in_the_map_is_hosted_by_default(self, tmp_path: Path) -> None: + (tmp_path / "agents.toml").write_text(AGENT_MAP, encoding="utf-8") + + _run(tmp_path) + + assert os.environ[dev.AGENTS_ENV] == "orders,billing" + + def test_a_subset_can_be_named(self, tmp_path: Path) -> None: + (tmp_path / "agents.toml").write_text(AGENT_MAP, encoding="utf-8") + + _run(tmp_path, agents="billing") + + assert os.environ[dev.AGENTS_ENV] == "billing" + + def test_an_environment_that_already_names_a_group_wins(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """A developer reproducing a deployment must not have it overwritten from the agent map.""" + (tmp_path / "agents.toml").write_text(AGENT_MAP, encoding="utf-8") + monkeypatch.setenv(dev.GROUP_ENV, "checkout") + + _run(tmp_path) + + assert dev.AGENTS_ENV not in os.environ + + def test_an_empty_map_stops_rather_than_serving_nothing(self, tmp_path: Path) -> None: + (tmp_path / "agents.toml").write_text("# nothing here\n", encoding="utf-8") + + with pytest.raises(SystemExit) as exit_info: + _run(tmp_path) + + assert exit_info.value.code == 1 + + +class TestAProjectWithoutAnAgentMap: + """A project written before the agent map still builds its own application.""" + + def test_it_is_served_as_it_always_was(self, tmp_path: Path) -> None: + (tmp_path / "src").mkdir() + (tmp_path / "src" / "main.py").write_text("app = None\n", encoding="utf-8") + + cmd = _run(tmp_path) + assert cmd[1:4] == ["-m", "uvicorn", "src.main:app"] - assert "--reload" in cmd - assert cmd[-4:] == ["--host", "127.0.0.1", "--port", "8000"] + assert "--factory" not in cmd + + def test_neither_file_is_an_error(self, tmp_path: Path) -> None: + with pytest.raises(SystemExit) as exit_info: + _run(tmp_path) + + assert exit_info.value.code == 1 diff --git a/tests/unit/agent_generator/cli/commands/test_validate_group_gates.py b/tests/unit/agent_generator/cli/commands/test_validate_group_gates.py new file mode 100644 index 00000000..c80a34ba --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_validate_group_gates.py @@ -0,0 +1,216 @@ +"""`asbs validate`'s group gates -- what a project must state before it can be grouped. + +The gates exist because there is no `asbs migrate`: `main.py` is the developer's own declaration, +and a tool that rewrites it either guesses at intent or fails on anything hand-edited. A checklist +plus a validate that names what is missing is the honest shape, so what these tests hold is that +each thing it can name, it does. +""" + +from pathlib import Path + +from blueprint.agent_generator.cli.commands.validate import _group_findings + +DECLARATION = "from blueprint.agents.app_builder import AppBuilder\n\nagent = AppBuilder()\n" + + +def _project(tmp_path: Path, *, agent_map: str | None = None, settings: str | None = None, main: str | None = DECLARATION) -> Path: + """Build the smallest project shape the group gates look at.""" + if main is not None: + (tmp_path / "src").mkdir(exist_ok=True) + (tmp_path / "src" / "main.py").write_text(main, encoding="utf-8") + if agent_map is not None: + (tmp_path / "agents.toml").write_text(agent_map, encoding="utf-8") + if settings is not None: + (tmp_path / "settings.toml").write_text(settings, encoding="utf-8") + return tmp_path + + +def _agent(name: str = "orders", module: str = "src.main:agent") -> str: + return f'[agents.{name}]\nmodule = "{module}"\n' + + +class TestTheAgentMap: + """The map is how a name reaches code; the gate is everything that stops it.""" + + def test_a_project_without_one_is_told_the_three_changes(self, tmp_path: Path) -> None: + issues, warnings, _ = _group_findings(_project(tmp_path)) + + assert not issues, "A project deployed on its own is not broken, so this is never an issue." + assert len(warnings) == 1 + assert "src/main.py" in warnings[0] + assert "Dockerfile" in warnings[0] + assert "agents.toml" in warnings[0] + + def test_a_well_formed_map_passes_silently(self, tmp_path: Path) -> None: + issues, warnings, _ = _group_findings(_project(tmp_path, agent_map=_agent())) + + assert (issues, warnings) == ([], []) + + def test_an_unparseable_map_is_reported(self, tmp_path: Path) -> None: + issues, _, _ = _group_findings(_project(tmp_path, agent_map="[agents.orders\nbroken\n")) + + assert len(issues) == 1 + assert "could not be read" in issues[0] + + def test_a_map_with_no_agents_is_reported(self, tmp_path: Path) -> None: + issues, _, _ = _group_findings(_project(tmp_path, agent_map="# nothing\n")) + + assert "declares no [agents.] entries" in issues[0] + + def test_an_entry_without_a_module_is_reported(self, tmp_path: Path) -> None: + issues, _, _ = _group_findings(_project(tmp_path, agent_map="[agents.orders]\ncritical = true\n")) + + assert "has no 'module'" in issues[0] + + def test_a_module_that_names_no_attribute_is_reported(self, tmp_path: Path) -> None: + issues, _, _ = _group_findings(_project(tmp_path, agent_map=_agent(module="src.main"))) + + assert "does not say which attribute" in issues[0] + + def test_a_name_that_cannot_be_a_namespace_is_reported(self, tmp_path: Path) -> None: + """It becomes a queue group, a durable, a cache partition and a service.name.""" + issues, _, _ = _group_findings(_project(tmp_path, agent_map=_agent(name="order-eu"))) + + assert "cannot be a namespace" in issues[0] + + def test_a_module_that_is_not_in_the_project_is_reported(self, tmp_path: Path) -> None: + issues, _, _ = _group_findings(_project(tmp_path, agent_map=_agent(module="src.nowhere:agent"))) + + assert "is not a module in this project" in issues[0] + + def test_a_module_that_declares_no_such_attribute_is_reported(self, tmp_path: Path) -> None: + """The attribute is the AppBuilder the host builds; without it the process never starts.""" + issues, _, _ = _group_findings(_project(tmp_path, agent_map=_agent(module="src.main:registration"))) + + assert "assigns no 'registration'" in issues[0] + + def test_a_package_declaration_resolves_too(self, tmp_path: Path) -> None: + package = tmp_path / "src" / "orders" + package.mkdir(parents=True) + (package / "__init__.py").write_text(DECLARATION, encoding="utf-8") + + issues, _, _ = _group_findings(_project(tmp_path, agent_map=_agent(module="src.orders:agent"))) + + assert issues == [] + + +class TestSettingsThatWillNotSurviveGrouping: + """An agent's settings are read from its declaration's directory, and scoped to it.""" + + def test_a_project_hosted_alone_is_not_told_about_scoping(self, tmp_path: Path) -> None: + """Its settings.toml *is* the process's own file, so neither rule applies to it yet.""" + project = _project(tmp_path, agent_map=_agent(), settings="[default]\napp_port = 8000\n") + + _, warnings, _ = _group_findings(project) + + assert warnings == [] + + def test_an_agent_shipping_no_settings_of_its_own_is_told_where_they_go(self, tmp_path: Path) -> None: + project = _project(tmp_path, agent_map=_agent() + _agent(name="billing", module="src.billing:agent")) + (tmp_path / "src" / "billing").mkdir() + (tmp_path / "src" / "billing" / "__init__.py").write_text(DECLARATION, encoding="utf-8") + + _, warnings, _ = _group_findings(project) + + assert len(warnings) == 2 + assert all("ships no settings of its own" in warning for warning in warnings) + + def test_a_declaration_at_the_project_root_keeps_the_process_settings_file(self, tmp_path: Path) -> None: + """`main:agent` puts the agent's settings file where the process's own already is.""" + project = _project(tmp_path, agent_map=_agent(module="main:agent") + _agent(name="billing", module="src.billing:agent")) + (tmp_path / "main.py").write_text(DECLARATION, encoding="utf-8") + (tmp_path / "settings.toml").write_text("[default]\napp_port = 8000\n", encoding="utf-8") + billing = tmp_path / "src" / "billing" + billing.mkdir(parents=True) + (billing / "__init__.py").write_text(DECLARATION, encoding="utf-8") + (billing / "settings.toml").write_text('[default]\nmodel_name = "y"\n', encoding="utf-8") + + _, warnings, _ = _group_findings(project) + + assert warnings == [], "The merge leaves the process's own settings file at the root rather than scoping it." + + def test_a_process_scope_key_in_a_fragment_is_named(self, tmp_path: Path) -> None: + """One process binds one port and speaks one bus, so these are dropped at startup.""" + project = _project(tmp_path, agent_map=_agent() + _agent(name="billing", module="src.billing:agent")) + (tmp_path / "src" / "settings.toml").write_text( + '[default]\napp_port = 8000\nevent_bus = "nats"\nmodel_name = "x"\n', encoding="utf-8" + ) + billing = tmp_path / "src" / "billing" + billing.mkdir() + (billing / "__init__.py").write_text(DECLARATION, encoding="utf-8") + (billing / "settings.toml").write_text('[default]\nmodel_name = "y"\n', encoding="utf-8") + + _, warnings, _ = _group_findings(project) + + orders = next(warning for warning in warnings if "'orders'" in warning) + assert "app_port, event_bus" in orders + assert "model_name" not in orders, "A scoped model name is the point of scoping, not a fault." + assert not [warning for warning in warnings if "'billing'" in warning] + + +class TestSchedulers: + """The mode has no default, and one of the two modes fails nowhere at all.""" + + def _with_scheduler(self, project: Path) -> Path: + schedulers = project / "src" / "schedulers" + schedulers.mkdir(parents=True, exist_ok=True) + (schedulers / "__init__.py").write_text("", encoding="utf-8") + (schedulers / "cleanup_scheduler.py").write_text("# scheduler", encoding="utf-8") + return project + + def test_a_project_with_no_schedulers_is_asked_nothing(self, tmp_path: Path) -> None: + issues, _, notices = _group_findings(_project(tmp_path, agent_map=_agent())) + + assert (issues, notices) == ([], []) + + def test_a_scheduler_without_a_mode_is_an_issue(self, tmp_path: Path) -> None: + """It has no default because neither value is safe to inherit, so build() fails.""" + project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings='[default]\napp_name = "demo"\n')) + + issues, _, _ = _group_findings(project) + + assert "no 'scheduler_mode'" in issues[0] + + def test_an_unknown_mode_is_an_issue(self, tmp_path: Path) -> None: + project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings='[default]\nscheduler_mode = "cron"\n')) + + issues, _, _ = _group_findings(project) + + assert "must be one of" in issues[0] + + def test_event_mode_says_that_nothing_here_publishes_the_tick(self, tmp_path: Path) -> None: + """The silent-failure case: a scheduler waiting for a tick nobody publishes is healthy.""" + settings = '[default]\nscheduler_mode = "event"\nevent_bus = "nats"\n' + project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings=settings)) + + issues, _, notices = _group_findings(project) + + assert issues == [] + assert len(notices) == 1 + assert "CronJob" in notices[0] + + def test_event_mode_without_a_bus_is_an_issue(self, tmp_path: Path) -> None: + """The tick is an ordinary event, so with no transport there is nothing to subscribe to.""" + project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings='[default]\nscheduler_mode = "event"\n')) + + issues, _, _ = _group_findings(project) + + assert any("no 'event_bus' is set" in issue for issue in issues) + + def test_in_process_mode_without_a_cache_says_every_replica_runs_every_tick(self, tmp_path: Path) -> None: + settings = '[default]\nscheduler_mode = "in_process"\n' + project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings=settings)) + + _, _, notices = _group_findings(project) + + assert len(notices) == 1 + assert "every replica runs every tick" in notices[0] + + def test_in_process_mode_with_a_cache_is_quiet(self, tmp_path: Path) -> None: + settings = '[default]\nscheduler_mode = "in_process"\n' + main = "agent = AppBuilder().with_cache()\n" + project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings=settings, main=main)) + + _, _, notices = _group_findings(project) + + assert notices == [] diff --git a/tests/unit/agent_generator/cli/utils/test_component_ordering.py b/tests/unit/agent_generator/cli/utils/test_component_ordering.py index 63040f1e..46e7cd71 100644 --- a/tests/unit/agent_generator/cli/utils/test_component_ordering.py +++ b/tests/unit/agent_generator/cli/utils/test_component_ordering.py @@ -132,7 +132,7 @@ def test_add_service_to_empty(self): """Test adding service to empty AppBuilder.""" content = "app = (\n AppBuilder(config)\n .build()\n)" result = add_component_registration_to_main(content, "MyService", "service") - assert ".with_service(MyService())" in result + assert ".with_service(MyService)" in result lines = result.split("\n") build_line = next(index for index, line in enumerate(lines) if ".build()" in line) service_line = next(index for index, line in enumerate(lines) if "with_service" in line) @@ -142,7 +142,7 @@ def test_add_handler_reorders_before_api(self): """Test adding handler re-orders the entire chain before API.""" content = "app = (\n AppBuilder(config)\n .with_rest_api(MyApi())\n .build()\n)" result = add_component_registration_to_main(content, "MyHandler", "handler") - assert ".with_handler(MyHandler())" in result + assert ".with_handler(MyHandler)" in result lines = result.split("\n") handler_line = next(index for index, line in enumerate(lines) if "with_handler" in line) api_line = next(index for index, line in enumerate(lines) if "with_rest_api" in line) @@ -228,8 +228,8 @@ def test_multiple_handlers_preserved_and_reordered(self): content = add_component_registration_to_main(content, "SecondHandler", "handler") # Both should exist - assert "with_handler(FirstHandler())" in content - assert "with_handler(SecondHandler())" in content + assert "with_handler(FirstHandler)" in content + assert "with_handler(SecondHandler)" in content # Handlers should come before API lines = content.split("\n") diff --git a/tests/unit/agent_generator/cli/utils/test_main_py_editing.py b/tests/unit/agent_generator/cli/utils/test_main_py_editing.py new file mode 100644 index 00000000..1f7f08f8 --- /dev/null +++ b/tests/unit/agent_generator/cli/utils/test_main_py_editing.py @@ -0,0 +1,117 @@ +"""``asbs create`` rewrites main.py, and main.py changed shape. + +A scaffolded ``main.py`` now assigns an unbuilt builder -- ``agent = (AppBuilder()...)`` with no +``build()`` call -- while a project written before that still ends its chain with ``.build()``. +The editor has to handle both, and the failure mode if it does not is silent: the registration +is appended to the end of the file, or the chain's lines are dropped while being re-sorted. +""" + +from blueprint.agent_generator.cli.utils.naming_utils import ( + add_component_registration_to_main, + extract_component_registrations, + insert_before_declaration, +) + +DECLARATION = '''"""A declaration.""" + +from blueprint.agents.app_builder import AppBuilder + +from .services import OrderService + +agent = ( + AppBuilder() + .with_service(OrderService) +) +''' + +LEGACY = '''"""An application that serves itself.""" + +from blueprint.agents.app_builder import AppBuilder +from blueprint.agents.config import Config + +from .services import OrderService + +config = Config(settings_files=["settings.toml"]) + +app = ( + AppBuilder(config=config) + .with_service(OrderService()) + .build() +) +''' + + +class TestFindingTheChain: + def test_a_declaration_closes_at_the_unindented_parenthesis(self) -> None: + components, start, end = extract_component_registrations(DECLARATION) + + lines = DECLARATION.split("\n") + assert components == [("service", " .with_service(OrderService)")] + assert lines[start].strip() == "AppBuilder()" + assert lines[end] == ")" + + def test_an_application_still_closes_at_build(self) -> None: + _, start, end = extract_component_registrations(LEGACY) + + lines = LEGACY.split("\n") + assert lines[start].strip() == "AppBuilder(config=config)" + assert lines[end].strip() == ".build()" + + def test_a_file_with_no_builder_reports_that_rather_than_guessing(self) -> None: + components, start, end = extract_component_registrations("x = 1\n") + + assert (components, start, end) == ([], -1, -1) + + +class TestAddingARegistration: + def test_it_lands_inside_the_declaration_chain(self) -> None: + updated = add_component_registration_to_main(DECLARATION, "OrderPlacedHandler", "handler") + + assert updated.split("\n")[6:10] == [ + "agent = (", + " AppBuilder()", + " .with_service(OrderService)", + " .with_handler(OrderPlacedHandler)", + ] + assert updated.endswith(")\n") + + def test_it_registers_the_class_not_an_instance(self) -> None: + """An already-built instance is refused when the agent is hosted in a group.""" + updated = add_component_registration_to_main(DECLARATION, "OrderApi", "api") + + assert " .with_rest_api(OrderApi)" in updated + assert "OrderApi()" not in updated + + def test_the_chain_is_ordered_by_dependency(self) -> None: + updated = add_component_registration_to_main(DECLARATION, "OrderApi", "api") + updated = add_component_registration_to_main(updated, "OrderPlacedHandler", "handler") + + chain = [line for line in updated.split("\n") if line.startswith(" .with_")] + assert chain == [ + " .with_service(OrderService)", + " .with_handler(OrderPlacedHandler)", + " .with_rest_api(OrderApi)", + ] + + def test_an_application_that_serves_itself_keeps_its_build_call(self) -> None: + updated = add_component_registration_to_main(LEGACY, "OrderPlacedHandler", "handler") + + assert " .with_handler(OrderPlacedHandler)" in updated + assert updated.index(".with_handler") < updated.index(".build()") + + +class TestInsertingADeclarationAbove: + def test_it_goes_above_the_builder_whatever_the_variable_is_called(self) -> None: + block = 'auditor_agent = (\n AgentBuilder(runtime_name="auditor_agent")\n)\n' + + for source, variable in ((DECLARATION, "agent = ("), (LEGACY, "app = (")): + updated = insert_before_declaration(source, block) + + assert updated.index(block) < updated.index(variable), ( + f"The declaration was not inserted above `{variable}`. Anchoring on the variable's name is what this " + "replaces: it hard coded `app = (`, so a new agent's declaration silently went missing and the " + "registration referred to a name that did not exist." + ) + + def test_a_file_with_no_builder_is_returned_unchanged(self) -> None: + assert insert_before_declaration("x = 1\n", "block\n") == "x = 1\n" diff --git a/tests/unit/agent_generator/cli/utils/test_naming_utils.py b/tests/unit/agent_generator/cli/utils/test_naming_utils.py index 466ccd76..3b67ee3b 100644 --- a/tests/unit/agent_generator/cli/utils/test_naming_utils.py +++ b/tests/unit/agent_generator/cli/utils/test_naming_utils.py @@ -210,7 +210,7 @@ def test_add_service_registration(self) -> None: service_idx = None build_idx = None for i, line in enumerate(lines): - if ".with_service(OrderService())" in line: + if ".with_service(OrderService)" in line: service_idx = i if ".build()" in line: build_idx = i @@ -225,8 +225,8 @@ def test_add_handler_registration(self) -> None: result = add_component_registration_to_main(main_content, "OrderHandler", "handler") - assert ".with_handler(OrderHandler())" in result - assert result.index(".with_handler(OrderHandler())") < result.rindex(".build()") + assert ".with_handler(OrderHandler)" in result + assert result.index(".with_handler(OrderHandler)") < result.rindex(".build()") def test_add_agent_registration_no_instantiation(self) -> None: """Should add agent registration without () for agents.""" @@ -243,7 +243,7 @@ def test_add_api_registration(self) -> None: result = add_component_registration_to_main(main_content, "OrderApi", "api") - assert ".with_rest_api(OrderApi())" in result + assert ".with_rest_api(OrderApi)" in result def test_add_scheduler_registration(self) -> None: """Should add scheduler registration before .build().""" @@ -251,7 +251,7 @@ def test_add_scheduler_registration(self) -> None: result = add_component_registration_to_main(main_content, "CleanupScheduler", "scheduler") - assert ".with_scheduler(CleanupScheduler())" in result + assert ".with_scheduler(CleanupScheduler)" in result def test_build_in_comment_does_not_break_insertion(self) -> None: """Should use last .build() call and ignore earlier ones in comments.""" @@ -301,7 +301,7 @@ def test_no_build_found_appends_at_end(self) -> None: lines = result.split("\n") # Last non-empty line should be the registration last_line = lines[-1] if lines[-1].strip() else lines[-2] - assert ".with_service(OrderService())" in last_line + assert ".with_service(OrderService)" in last_line def test_multiple_registrations_maintain_order(self) -> None: """Should add multiple registrations in the correct order.""" diff --git a/tests/unit/agent_generator/generator/__init__.py b/tests/unit/agent_generator/generator/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/unit/agent_generator/generator/test_generated_project.py b/tests/unit/agent_generator/generator/test_generated_project.py new file mode 100644 index 00000000..56c248be --- /dev/null +++ b/tests/unit/agent_generator/generator/test_generated_project.py @@ -0,0 +1,202 @@ +"""What ``asbs setup`` produces, asserted against the framework that has to host it. + +The generator's output is invisible from the framework's own tests, so a project that no longer +matches the framework it generates against is a defect nothing reports. These tests close that: +the project is generated into a temporary directory, its declaration is **imported**, and what +comes back is checked against the same rules the framework holds itself to -- a declaration +records and constructs nothing, a name that leaves the process is a legal namespace, and the +image's command can find the declaration it is asked to run. +""" + +import importlib +import json +import sys +import tomllib +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path + +import pytest + +from blueprint.agent_generator.cli.commands.setup import create_basic_config +from blueprint.agent_generator.generator.generator import AgentGenerator +from blueprint.agents.app_builder import AppBuilder +from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import validate_namespace + +PROJECT_NAME = "InvoiceProcessor" +AGENT_NAMESPACE = "invoice_processor" + + +@pytest.fixture(scope="module") +def project(tmp_path_factory: pytest.TempPathFactory) -> Path: + """Generate the project ``asbs setup InvoiceProcessor`` produces, once for the module.""" + output = tmp_path_factory.mktemp("generated") + config_file = output / "generator-config.json" + config_file.write_text(json.dumps(create_basic_config(PROJECT_NAME)), encoding="utf-8") + + generator = AgentGenerator(str(config_file), str(output)) + generator.load_config() + generator.generate() + return output + + +@contextmanager +def declaration_of(project: Path) -> Iterator[AppBuilder]: + """Import the generated ``src.main`` and yield the ``agent`` it declares. + + Imported rather than read as text, because the claim under test is that the framework can + host this file -- and a file that parses is not the same as one whose imports resolve and + whose builder calls exist. ``src`` is put back exactly as it was afterwards: the repository + has a directory of that name too, and leaving the generated one in ``sys.modules`` would + decide what a later test imports. + """ + saved_path = list(sys.path) + saved_modules = {name: module for name, module in sys.modules.items() if name == "src" or name.startswith("src.")} + for name in saved_modules: + del sys.modules[name] + + sys.path.insert(0, str(project)) + try: + yield importlib.import_module("src.main").agent + finally: + for name in [name for name in sys.modules if name == "src" or name.startswith("src.")]: + del sys.modules[name] + sys.modules.update(saved_modules) + sys.path[:] = saved_path + + +class TestTheGeneratedDeclaration: + """``src/main.py`` declares an agent and builds nothing.""" + + def test_main_assigns_an_unbuilt_app_builder(self, project: Path) -> None: + with declaration_of(project) as agent: + assert isinstance(agent, AppBuilder) + assert not agent.is_built, ( + "The generated main.py built its application on import. It must only declare one: the host decides " + "the configuration and the namespace, and a builder that has already run has taken both itself." + ) + + def test_importing_it_constructs_nothing(self, project: Path) -> None: + """Collect, then wire -- asserted where it is easiest to break, in generated code.""" + before = dict(Component.shared_registry._components) if Component.shared_registry is not None else {} + + with declaration_of(project): + after = dict(Component.shared_registry._components) if Component.shared_registry is not None else {} + + assert after == before, ( + "Importing the generated main.py put components in the registry. A component constructed while a " + "declaration is still being collected exists before any namespace does, so it belongs to the root for " + "ever -- which is exactly what a grouped deployment must not do." + ) + + def test_every_component_is_declared_once(self, project: Path) -> None: + with declaration_of(project) as agent: + declared = [(entry.kind, getattr(entry.target, "__name__", type(entry.target).__name__)) for entry in agent.declarations] + + assert declared == [ + ("service", "InvoiceProcessorService"), + ("agent", "AgentBuilder"), + ("handler", "InvoiceProcessorHandler"), + ("rest_api", "InvoiceProcessorApi"), + ] + + def test_the_agent_runtime_is_named_so_services_can_resolve_it(self, project: Path) -> None: + """The generated service does ``registry.get_agent("")``, so the name must be set.""" + with declaration_of(project) as agent: + runtimes = [entry for entry in agent.declarations if entry.kind == "agent"] + + assert [entry.name for entry in runtimes] == [f"{AGENT_NAMESPACE}_agent"] + + def test_components_are_declared_as_classes_not_instances(self, project: Path) -> None: + """An instance is refused when the agent is hosted in a group, so the generator emits classes.""" + with declaration_of(project) as agent: + constructed = [entry.kind for entry in agent.declarations if entry.is_built] + + assert not constructed, ( + f"The generated main.py passes already-built {constructed} to the builder. A component constructed on " + "the with_* line belongs to the root namespace for ever, which is why a group refuses it." + ) + + def test_it_neither_loads_configuration_nor_serves_itself(self, project: Path) -> None: + source = (project / "src" / "main.py").read_text(encoding="utf-8") + + assert "Config(" not in source, "main.py loads configuration; the host supplies it, scoped to this agent." + assert ".build()" not in source, "main.py builds its application; the host builds it, inside this agent's namespace." + + +class TestTheAgentMap: + """``agents.toml`` is how the image's command finds the declaration.""" + + def test_it_names_the_agent_and_its_declaration(self, project: Path) -> None: + document = tomllib.loads((project / "agents.toml").read_text(encoding="utf-8")) + + assert document["agents"] == {AGENT_NAMESPACE: {"module": "src.main:agent"}} + + def test_the_agent_name_is_a_legal_namespace(self, project: Path) -> None: + """It becomes a queue group, a durable, a cache partition and a service.name.""" + document = tomllib.loads((project / "agents.toml").read_text(encoding="utf-8")) + + for name in document["agents"]: + assert validate_namespace(name) == name + + def test_the_module_it_names_is_the_one_that_declares_the_agent(self, project: Path) -> None: + """The map is only useful if it resolves, and it is written by hand from here on.""" + document = tomllib.loads((project / "agents.toml").read_text(encoding="utf-8")) + module_path, _, attribute = document["agents"][AGENT_NAMESPACE]["module"].partition(":") + + saved_path = list(sys.path) + saved_modules = {name: module for name, module in sys.modules.items() if name == "src" or name.startswith("src.")} + for name in saved_modules: + del sys.modules[name] + sys.path.insert(0, str(project)) + try: + module = importlib.import_module(module_path) + assert isinstance(getattr(module, attribute), AppBuilder) + finally: + for name in [name for name in sys.modules if name == "src" or name.startswith("src.")]: + del sys.modules[name] + sys.modules.update(saved_modules) + sys.path[:] = saved_path + + +class TestTheImage: + """The Dockerfile runs the framework's entry point, and bakes no group.""" + + def test_the_command_is_the_framework_entry_point(self, project: Path) -> None: + dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") + + assert 'ENTRYPOINT ["python", "-m", "blueprint.agents.entrypoint"]' in dockerfile + assert "uvicorn" not in dockerfile.split("FROM python:3.13-slim-bookworm AS final")[1], ( + "The production stage still serves an application object. Which agents the process hosts is resolved at " + "container start, which uvicorn cannot do on its own." + ) + + def test_the_agent_map_is_in_the_image(self, project: Path) -> None: + dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") + + assert "COPY --chown=appuser:appuser agents.toml ./" in dockerfile + + def test_no_group_is_baked_into_the_production_image(self, project: Path) -> None: + """One image serves every group; the group arrives at container start.""" + final_stage = (project / "Dockerfile").read_text(encoding="utf-8").split("FROM python:3.13-slim-bookworm AS final")[1] + + assert "ENV BLUEPRINT_AGENTS" not in final_stage + assert "BLUEPRINT_GROUP" not in final_stage.replace("BLUEPRINT_GROUP=", "") + + def test_the_documented_run_command_names_the_real_agent(self, project: Path) -> None: + """A placeholder here is a command that looks runnable and is not.""" + dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") + + assert f"docker run -e BLUEPRINT_AGENTS={AGENT_NAMESPACE} " in dockerfile + assert "agent_namespace" not in dockerfile + + +class TestAnUnusableProjectNameIsRefused: + """A name that cannot be a namespace fails the generator rather than the deployment.""" + + def test_a_leading_digit_is_refused_with_the_reason(self) -> None: + from blueprint.agent_generator.generator.part_generators import AgentMapPartGenerator + + with pytest.raises(ValueError, match="cannot be used"): + AgentMapPartGenerator.agent_namespace({"name": "2ndAgent"}) From e95b5021056d107544f847425261f7a87c359af2 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:44:59 +0200 Subject: [PATCH 015/133] docs(guides): multi-agent setup, migration, and a deployment guide that matches Phase 10 step 3-4. The setup guide covers both paths -- a new project and migrating an existing single-agent one -- the identity decision to get right first, what changes and what does not, and the cold cache after the move. Writing them found defects, fixed in the same changes. The deployment guide is rewritten against what the feature actually ships. Co-Authored-By: Claude Opus 5 (1M context) --- docs/README.md | 1 + docs/guides/cli-reference.md | 290 +++--- docs/guides/deployment.md | 873 +++++++++++------- docs/guides/multi-agent-setup.md | 428 +++++++++ ...26-08-28-multi-agent-grouping-changelog.md | 197 +++- docs/plans/2026-08-28-multi-agent-grouping.md | 7 +- .../agent_generator/cli/commands/create.py | 4 +- src/blueprint/agent_generator/cli/main.py | 24 - .../agent_generator/generator/generator.py | 8 +- .../part_generators/secrets_part_generator.py | 13 +- .../generator/test_generated_project.py | 16 + 11 files changed, 1364 insertions(+), 497 deletions(-) create mode 100644 docs/guides/multi-agent-setup.md diff --git a/docs/README.md b/docs/README.md index 1ba438f8..df17d8b3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -41,6 +41,7 @@ Blueprint Agents is a Python 3.13+ framework for building AI-powered microservic | Guide | Description | |-------|-------------| | [CLI Reference](guides/cli-reference.md) | Full reference for the `asbs` command-line tool | +| [Multi-Agent Setup](guides/multi-agent-setup.md) | Running several agents in one process, and migrating an existing one into a group | | [Testing](guides/testing.md) | Unit testing, integration testing, and test fixtures | | [Deployment](guides/deployment.md) | Docker builds, environment configuration, and production setup | | [Troubleshooting](guides/troubleshooting.md) | Common issues, debugging tips, and FAQ | diff --git a/docs/guides/cli-reference.md b/docs/guides/cli-reference.md index b27c530b..2fa6f988 100644 --- a/docs/guides/cli-reference.md +++ b/docs/guides/cli-reference.md @@ -31,7 +31,7 @@ Each component type follows a consistent suffix pattern: | **Handler** | `order_placed` | `OrderPlacedHandler` | `order_placed_handler.py` | Handles events | | **Service** | `invoice_processor` | `InvoiceProcessorService` | `invoice_processor_service.py` | Contains business logic | | **API** | `order_management` | `OrderManagementApi` | `order_management_api.py` | REST endpoints + models file | -| **Agent** | `document_analyzer` | `DocumentAnalyzer` | `document_analyzer_agent.py` | No "Agent" suffix in class name | +| **Agent** | `document_analyzer` | -- | -- | No module of its own: a builder in `main.py` plus two prompt files | | **Scheduler** | `cleanup` | `CleanupScheduler` | `cleanup_scheduler.py` | Background tasks | ### Name Normalization Examples @@ -60,7 +60,7 @@ asbs create api product_catalog asbs create api ProductCatalog asbs create api product-catalog # All produce: ProductCatalogApi in product_catalog_api.py -# And: product_catalog_models.py (without the "_api" suffix) +# And the models package src/models/product_catalog/ (dto, domain_models, mapper) ``` #### Agent Examples @@ -68,9 +68,8 @@ asbs create api product-catalog asbs create agent document_analyzer asbs create agent DocumentAnalyzer asbs create agent document-analyzer -# All produce: DocumentAnalyzer (agent class, not DocumentAnalyzerAgent) -# File: document_analyzer_agent.py -# Builder function: build_document_analyzer_agent() +# All produce the runtime name: document_analyzer_agent +# Declared in src/main.py as an AgentBuilder; prompts in src/prompts/ ``` ### Auto-Registration @@ -100,7 +99,7 @@ $ asbs create handler order_placed Scaffold a complete Blueprint Agents project with all required directories and configuration files. ```bash -asbs setup +asbs setup [--output-dir ] [--overwrite] [--verbose] ``` ### Arguments @@ -109,26 +108,40 @@ asbs setup |----------------|------------------------------------|----------| | `project-name` | Name of the project to create | Yes | +### Options + +| Flag | Description | Default | +|-----------------------|--------------------------------------------------------|---------| +| `--output-dir ` | Parent directory the project is created in | `.` | +| `--overwrite` | Overwrite existing files instead of refusing | off | +| `--verbose`, `-v` | Debug-level logging from the generator | off | + +The project name is normalised to a class name (`order-processor` gives `OrderProcessor/`), and the +agent's namespace is that name in snake case (`order_processor`). + ### Generated Project Structure ``` -/ +/ src/ - main.py - handlers/ - services/ + main.py # the declaration: agent = AppBuilder()... api/ - models/ + handlers/ + models// # dto.py, domain_models.py, mapper.py prompts/ - tests/ - unit/ - integration/ + services/ + agents.toml # agent name -> declaration; baked into the image settings.toml - secrets.toml - pyproject.toml + secrets.toml # git-ignored + secrets.toml.example # committed, so the keys to fill in are known Dockerfile + .gitignore ``` +There is no `tests/` directory and no `pyproject.toml`: the scaffolder writes source, settings and +the image, and the packaging and test layout are the project's own. `asbs validate` reports both as +missing, which is a reminder rather than a defect in the scaffold. + ### Example ```bash @@ -181,7 +194,7 @@ with `python -m blueprint.agents.entrypoint`, which reads that map and the deplo Generate a new event handler component by creating a subclass of `EventHandlerBase`. ```bash -asbs create handler [--event-type ] [--priority ] +asbs create handler [--event-type ] [--priority ] [--output-dir ] ``` ### Arguments @@ -192,10 +205,14 @@ asbs create handler [--event-type ] [--priority ] ### Options -| Flag | Description | Default | -|-------------------------|----------------------------------------------------|-----------| -| `--event-type ` | The event type this handler will respond to | (prompt) | -| `--priority ` | Handler priority (lower numbers execute first) | `0` | +| Flag | Description | Default | +|-------------------------|----------------------------------------------------|------------------| +| `--event-type ` | The event type this handler will respond to | (prompt) | +| `--priority ` | Handler priority (lower numbers execute first) | `10` | +| `--output-dir ` | Where the handler module is written | `src/handlers` | + +Ties at equal priority are resolved by registration order, which is the order the `with_*` calls +appear in `main.py`. ### Naming @@ -240,7 +257,7 @@ from blueprint.agents.handler import EventHandlerBase class OrderPlacedHandler(EventHandlerBase): def __init__(self) -> None: - super().__init__(priority=0) + super().__init__(priority=10) async def on_startup(self) -> None: # Initialize resources from registry @@ -266,7 +283,7 @@ class OrderPlacedHandler(EventHandlerBase): Generate a new service component by creating a subclass of `ServiceBase`. ```bash -asbs create service +asbs create service [--output-dir ] ``` ### Arguments @@ -275,6 +292,12 @@ asbs create service |----------|---------------------------------|----------| | `name` | Name of the service to create | Yes | +### Options + +| Flag | Description | Default | +|-----------------------|-------------------------------------|------------------| +| `--output-dir ` | Where the service module is written | `src/services` | + ### Naming Service names are converted to `Service` format: @@ -337,7 +360,7 @@ class InvoiceProcessorService(ServiceBase): Generate a new REST API component by creating a subclass of `RestApiBase`, plus a models file with Request/Response classes. ```bash -asbs create api +asbs create api [--output-dir ] ``` ### Arguments @@ -346,24 +369,32 @@ asbs create api |----------|------------------------------|----------| | `name` | Name of the API to create | Yes | +### Options + +| Flag | Description | Default | +|-----------------------|---------------------------------|-------------| +| `--output-dir ` | Where the API module is written | `src/api` | + ### Naming -API names are converted to `Api` format with an accompanying models file: +API names are converted to `Api`, with a models package named after the component: - Input: `order_management` - Class: `OrderManagementApi` - - API File: `order_management_api.py` - - Models File: `order_management_models.py` + - API file: `src/api/order_management_api.py` + - Models package: `src/models/order_management/` ### Files Generated -1. **API File** (`src/api/_api.py`) - - REST API class with `.get()`, `.post()`, `.put()`, `.delete()` endpoints - - Dependency injection via `self.registry.get_service(...)` +1. **API module** (`src/api/_api.py`) + - `RestApiBase` subclass with a `GET /{item_id}` and a `POST /` placeholder, both raising + `501 Not Implemented` until you write them + - Dependency injection via `self.registry.get_service(...)` in `on_startup` -2. **Models File** (`src/models/_models.py`) - - Request and Response Pydantic models - - Example: `OrderManagementRequest` and `OrderManagementResponse` +2. **A models package** (`src/models//`), three files: + - `dto.py` -- `Request` and `Response`, the API's wire contract + - `domain_models.py` -- `Model`, what the service works with + - `mapper.py` -- `Mapper`, converting between the two ### Auto-Registration @@ -380,8 +411,10 @@ asbs create api order_management ``` Creates: -- `src/api/order_management_api.py` with `OrderManagementApi` class -- `src/models/order_management_models.py` with `OrderManagementRequest` and `OrderManagementResponse` classes +- `src/api/order_management_api.py` with the `OrderManagementApi` class +- `src/models/order_management/dto.py` with `OrderManagementRequest` and `OrderManagementResponse` +- `src/models/order_management/domain_models.py` with `OrderManagementModel` +- `src/models/order_management/mapper.py` with `OrderManagementMapper` #### API Generated Code @@ -392,7 +425,7 @@ The generated API includes: from fastapi import HTTPException, status from blueprint.agents.io.api.rest_api_base import RestApiBase -from src.models.order_management_models import OrderManagementRequest, OrderManagementResponse +from src.models.order_management.dto import OrderManagementRequest, OrderManagementResponse class OrderManagementApi(RestApiBase): async def on_startup(self) -> None: @@ -436,7 +469,8 @@ class OrderManagementResponse(BaseModel): ## asbs create agent -Generate an AI agent component with `AgentRuntime`, `AgentBuilder` boilerplate, system prompt, instruction prompt, and settings configuration. +Declare an AI agent runtime: two prompt files, a settings section, and an `AgentBuilder` in +`src/main.py`. ```bash asbs create agent @@ -450,36 +484,29 @@ asbs create agent ### Naming -Agent names are converted to `` format (no "Agent" suffix in class name, but used in builder function): - -- Input: `document_analyzer` → Function: `build_document_analyzer_agent()` → File: `document_analyzer_agent.py` -- Input: `DocumentAnalyzer` → Function: `build_document_analyzer_agent()` → File: `document_analyzer_agent.py` +The runtime name is the input in snake case with `_agent` appended, unless it already ends that way: -### Files Generated +- Input: `document_analyzer` -> runtime `document_analyzer_agent` +- Input: `DocumentAnalyzer` -> runtime `document_analyzer_agent` +- Input: `analyzer_agent` -> runtime `analyzer_agent` -1. **Agent Module** (`src/agents/_agent.py`) - - `build__agent(config)` function that creates and configures the agent - - Uses `AgentBuilder` with model config, prompts, and tools +**This command writes no module of its own.** There is no `src/agents/` file and no builder +function: an agent runtime is a declaration in `main.py` plus its prompts, so there is nothing for a +separate module to hold. -2. **System Prompt** (`src/prompts/_system.prompt`) - - Static context for the agent - - Example content already provided - -3. **Instruction Prompt** (`src/prompts/_instruction.prompt`) - - Dynamic template with `{placeholders}` for runtime input - - Example content already provided +### Files Generated -4. **Settings Configuration** (`settings.toml`) - - `[default.runtimes.]` section with model configuration - - Model provider, name, temperature, and token limits +1. **System prompt** (`src/prompts/_system.prompt`) -- static context, with example content +2. **Instruction prompt** (`src/prompts/_instruction.prompt`) -- a template with + `{placeholders}` for runtime input, with example content +3. **Settings** (`settings.toml`) -- a `[default.runtimes.]` section and a + `[default.runtimes..models]` section beneath it ### Auto-Registration -The created agent is automatically: -- Imported in `src/main.py` -- Agent instance created before `app =` -- Registered with `.with_agent(_agent, name="_agent")` -- Configuration added to `settings.toml` +- The `AgentBuilder` import is added to `src/main.py` if it is not already there +- The runtime declaration is inserted above the `AppBuilder` chain +- `.with_agent(, name="")` is added to the chain ### Examples @@ -490,55 +517,49 @@ asbs create agent document_analyzer ``` Creates: -- `src/agents/document_analyzer_agent.py` with `build_document_analyzer_agent()` function -- `src/prompts/document_analyzer_system.prompt` with system context -- `src/prompts/document_analyzer_instruction.prompt` with instruction template -- `[default.runtimes.document_analyzer]` section in `settings.toml` +- `src/prompts/document_analyzer_agent_system.prompt` +- `src/prompts/document_analyzer_agent_instruction.prompt` +- `[default.runtimes.document_analyzer_agent]` in `settings.toml` +- the declaration and the registration in `src/main.py` -#### Agent Generated Code - -The generated agent builder includes: +#### What is added to `src/main.py` ```python -"""AgentRuntime for document_analyzer operations.""" - -from blueprint.agents import AgentBuilder -from blueprint.agents.base import AgentRuntime -from blueprint.agents.config import Config - - -def build_document_analyzer_agent(config: Config) -> AgentRuntime: - """Build the document_analyzer agent. - - Args: - config: Application configuration - - Returns: - Configured AgentRuntime instance - """ - agent = ( - AgentBuilder(config, runtime_name="document_analyzer") - .with_model_from_config() - .with_system_prompt("document_analyzer_system") - .build(name="document_analyzer") - ) +document_analyzer_agent = ( + AgentBuilder(runtime_name="document_analyzer_agent") + .with_model_from_config() + .with_system_prompt("document_analyzer_agent_system") +) - return agent +agent = ( + AppBuilder() + .with_agent(document_analyzer_agent, name="document_analyzer_agent") +) ``` +The builder is left **unbuilt**, and takes no `Config`. `AppBuilder.build()` calls +`agent.build(config.for_namespace())`, so the model, prompt and metrics are read from +this agent's own configuration view; building it at this line would bind it to whatever +configuration happened to be in scope, which in a group is a neighbour's. + #### Settings Configuration Auto-generated in `settings.toml`: ```toml -[default.runtimes.document_analyzer] +[default.runtimes.document_analyzer_agent] model_provider = "openai" -model_name = "gpt-4o-mini" +model_name = "gpt-5-mini" model_temperature = 0.7 model_max_tokens = 2000 + +[default.runtimes.document_analyzer_agent.models] +openai_reasoning_effort = "low" +openai_reasoning_summary = "detailed" ``` -Override any defaults in your `settings.toml` after creation. +Override any defaults in your `settings.toml` after creation. In a group, these are read through +this agent's own configuration view, so two agents may run different models under the same key. --- @@ -547,7 +568,7 @@ Override any defaults in your `settings.toml` after creation. Generate a scheduled task component by creating a subclass of `SchedulerBase`. ```bash -asbs create scheduler [--cron ] +asbs create scheduler [--cron ] [--output-dir ] ``` ### Arguments @@ -558,9 +579,18 @@ asbs create scheduler [--cron ] ### Options -| Flag | Description | Default | -|------------------|--------------------------------------|---------------| -| `--cron ` | Cron expression for the schedule | `0 * * * *` | +| Flag | Description | Default | +|-----------------------|-----------------------------------------|--------------------| +| `--cron ` | Cron expression for the schedule | `0 * * * *` | +| `--output-dir ` | Where the scheduler module is written | `src/schedulers` | + +### `scheduler_mode` is required + +A registered scheduler with no `scheduler_mode` in `settings.toml` fails at `build()`. The key has +no default because neither value is safe to inherit: `in_process` runs a timer in every replica and +claims each tick in the agent's own cache, so it needs `.with_cache()`; `event` starts no timer at +all and waits for a tick published by an external `CronJob`, so it needs `event_bus` -- and nothing +in this project generates that `CronJob`. `asbs validate` reports both. ### Naming @@ -927,65 +957,47 @@ agent = ( ## asbs claude -Generate or update Claude Code context files for AI integration. The CLI creates framework and project-specific CLAUDE.md files automatically. +Copy the framework's Claude Code resources into a project, so that Claude Code picks up the +Blueprint patterns when working in it. ```bash -asbs claude [create|update] +asbs claude [] [--overwrite] [--verbose] ``` -### Subcommands - -| Subcommand | Description | -|------------|----------------------------------------------------------| -| `create` | Generate new Claude Code context files | -| `update` | Update existing Claude Code context files | +### Arguments -### CLAUDE.md Placement +| Argument | Description | Default | +|-----------------|--------------------------------------|---------| +| `project-dir` | Project root to write into | `.` | -The CLI creates and manages files in a consistent structure: +### Options -| Path | Purpose | Updated By | -|------|---------|-----------| -| `src/CLAUDE.md` | Framework reference for Blueprint patterns | `asbs claude` | -| `.claude/agents/` | CLI-generated agent documentation | `asbs create agent` | -| `.claude/skills/` | CLI-generated skill definitions | `asbs` commands | -| `CLAUDE.md` (optional) | Project-specific context (root) | User (manual) | +| Flag | Description | Default | +|-------------------|-----------------------------------------------------|---------| +| `--overwrite` | Replace files that already exist | off | +| `--verbose`, `-v` | Debug-level logging | off | -### Framework CLAUDE.md +There are no `create` / `update` subcommands: the command is idempotent, and `--overwrite` is the +difference between leaving existing files alone and replacing them. -Running `asbs claude create` generates: +### What it copies -1. **`src/CLAUDE.md`** - Framework documentation containing: - - Component base classes and imports - - Critical rules (registry, lifecycle, wiring) - - Component patterns with examples - - Registry lookup patterns - - Configuration structure - - CLI command reference +| From the framework | To the project | Contents | +|---|---|---| +| `claude_docs/CLAUDE.md` | `src/CLAUDE.md` | Framework reference: base classes, the registry and lifecycle rules, component patterns, configuration | +| `claude_docs/agents/` | `.claude/agents/` | Architecture agents | +| `claude_docs/skills/` | `.claude/skills/` | CLI skills | -2. **`.claude/` directory** - Generated context for Claude Code: - - Agent documentation in `.claude/agents/` - - Skill definitions in `.claude/skills/` - - Automatically updated when components are created +Nothing here is generated from *your* project: the files are the framework's own documentation, +copied. They are not updated when you run `asbs create`. ### Example ```bash -# Generate initial Claude Code context files -asbs claude create - -# Update after adding new components -asbs claude update +asbs claude +asbs claude --overwrite # after upgrading the framework ``` -The generated files include information about: - -- Project structure and component locations -- Registered handlers, services, APIs, and agents -- Configuration settings and environment variables -- Testing patterns and commands -- Build and deployment instructions - ### Project-Specific CLAUDE.md You can optionally create a `CLAUDE.md` file in your project root for project-specific context: diff --git a/docs/guides/deployment.md b/docs/guides/deployment.md index e74bcb48..34560254 100644 --- a/docs/guides/deployment.md +++ b/docs/guides/deployment.md @@ -1,168 +1,124 @@ # Deployment Guide -This guide covers packaging, deploying, and operating Blueprint Agents applications in production environments using Docker, Kubernetes, and Helm. - -> **Running more than one replica is not safe in the current release.** Message distribution is -> now correct on both NATS paths -- Core NATS subscriptions join a queue group (`nats_queue_group`, -> default `app_name`), JetStream consumers are durable and share a deliver group, and every -> delivery is acknowledged, redelivered or dead-lettered explicitly. Two problems remain: -> -> - **Every replica runs its own scheduler.** `SchedulerBase` starts an `AsyncIOScheduler` per -> process with no leader election, so each cron tick fires once per replica. -> - **Duplicate delivery is not handled.** Competing consumers make at-least-once permanent, and a -> handler that finishes its work and then fails to acknowledge -- a connection blip, a pod killed -> mid-handler -- has already committed its side effects when the message is redelivered. The -> framework offers no deduplication yet, so a handler that is not naturally idempotent will repeat -> itself. -> -> The delivery behaviour above is covered by unit tests against mocked transports, and has not yet -> been exercised against a real broker. -> -> Until these are addressed, deploy one replica with `autoscaling.enabled: false`. The HPA example -> below shows the chart's shape; it is not a recommendation. Required behaviour is specified in -> `docs/specs/2026-08-28-multi-agent-grouping.md`, sec. 7.4 and 7.5; the remaining fixes are P4 and -> P5 in `docs/plans/2026-08-28-multi-agent-grouping.md`. This guide also assumes one Deployment -> per agent, and will be rewritten when group-based deployment lands. +Packaging, deploying and operating Blueprint Agents applications with Docker, Kubernetes and Helm. + +Two things shape everything below, and both are recent: + +- **A Deployment runs a *group*, not an agent.** One image contains every agent the platform has; + which of them a given process hosts is injected at container start. Regrouping is an edit to a + Deployment, not a rebuild. See [Multi-Agent Setup](multi-agent-setup.md) for the model; this guide + is about running it. +- **More than one replica is now safe**, under conditions this guide states. Core NATS + subscriptions join a queue group, JetStream consumers are durable and share a deliver group, every + delivery is acknowledged, naked or terminated explicitly, a cron tick fires once across replicas + in both scheduler modes, and event deduplication is available. What you have to decide is listed + under [Running more than one replica](#running-more-than-one-replica). + +> **The delivery behaviour is covered by unit tests against mocked transports and has not been +> exercised against a real broker.** Queue-group distribution across replicas, redelivery after +> `nats_ack_wait`, durable survival across reconnect and the shutdown drain are all specified and +> implemented; none of them has been watched happening on a live NATS server. Treat the first +> multi-replica deployment as the experiment it is. --- -## Docker +## The image -### Dockerfile - -Blueprint Agents projects ship with a multi-stage Dockerfile. The following template provides a production-ready build: +A scaffolded project ships a multi-stage Dockerfile whose production stage is: ```dockerfile -# Stage 1: Base image -FROM python:3.13-slim AS base - -ENV PYTHONDONTWRITEBYTECODE=1 -ENV PYTHONUNBUFFERED=1 +FROM python:3.13-slim-bookworm AS final WORKDIR /app -# Stage 2: Builder -FROM base AS builder - -RUN pip install --no-cache-dir uv - -COPY pyproject.toml ./ -RUN uv pip install --system --no-cache -r pyproject.toml - -COPY src/ ./src/ - -# Stage 3: Production -FROM base AS production - COPY --from=builder /usr/local/lib/python3.13/site-packages /usr/local/lib/python3.13/site-packages COPY --from=builder /usr/local/bin /usr/local/bin -COPY --from=builder /app /app +COPY --chown=appuser:appuser src ./src +COPY --chown=appuser:appuser settings.toml ./ +COPY --chown=appuser:appuser agents.toml ./ -COPY settings.toml ./ -COPY prompts/ ./prompts/ +# The disk cache backend writes here and cannot create it itself: WORKDIR made /app root-owned. +RUN mkdir -p /app/.cache && chown -R appuser:appuser /app/.cache -EXPOSE 8000 - -HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \ - CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health/live')"] - -CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"] -``` - -### Building and Running - -```bash -# Build the image -docker build -t my-ai-service:latest . - -# Run the container -docker run -d \ - --name my-ai-service \ - -p 8000:8000 \ - -e DYNACONF_LLM__API_KEY="sk-..." \ - my-ai-service:latest -``` +ENV PYTHONPATH="/app/src" \ + DYNACONF_ENVIRONMENT="production" \ + PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 -### Environment Variable Overrides +USER appuser -Blueprint Agents uses Dynaconf for configuration. Any setting in `settings.toml` can be overridden at runtime using environment variables prefixed with `DYNACONF_`: +HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ + CMD curl -f http://localhost:8000/health/live || exit 1 -```bash -docker run -d \ - -p 8000:8000 \ - -e DYNACONF_APP__PORT=9000 \ - -e DYNACONF_LLM__PROVIDER="openai" \ - -e DYNACONF_LLM__MODEL="gpt-4" \ - -e DYNACONF_LLM__API_KEY="sk-..." \ - -e DYNACONF_CACHE__TTL=3600 \ - my-ai-service:latest -``` - -Nested settings use double underscores as separators. For example, `DYNACONF_LLM__API_KEY` maps to `settings.toml` entry: +EXPOSE 8000 -```toml -[llm] -api_key = "sk-..." +ENTRYPOINT ["python", "-m", "blueprint.agents.entrypoint"] ``` -#### Choosing Your Own Prefix - -`DYNACONF_` is the default, not the only option. Declare `envvar_prefix` as a **top-level** key -- -above every section, because the prefix is resolved before any environment section is selected: - -```toml -envvar_prefix = "ORDERS" - -[default] -app_name = "orders" -``` +Three things about it are load-bearing: -```bash -docker run -e ORDERS_MODEL_NAME="gpt-4" my-ai-service:latest -``` +- **`agents.toml` is copied in; the group file is not.** The map says what the image *contains*, and + changes only when an agent is added or removed -- which is a rebuild anyway. Which agents a + *process* runs is a deployment decision and arrives separately, so baking it would defeat the one + property the whole model exists for. +- **The command is `python -m blueprint.agents.entrypoint`**, not `uvicorn src.main:app`. A + scaffolded `src/main.py` declares an agent and builds nothing; the entry point resolves this + process's group, builds it and serves it. A project that has not migrated keeps `uvicorn + src.main:app` and keeps working. +- **`secrets.toml` is never copied in.** Mount it, or supply the values as environment variables. -An operator can override the declared prefix without rebuilding the image, using the framework's -own bootstrap variable: +### Building and running ```bash -docker run -e BLUEPRINT_ENVVAR_PREFIX="ORDERS" -e ORDERS_MODEL_NAME="gpt-4" my-ai-service:latest +docker build -t my-agents:latest . + +# One agent, no group file +docker run -d -p 8000:8000 \ + -e BLUEPRINT_AGENTS=order \ + -e DYNACONF_MODEL_API_KEY="sk-..." \ + my-agents:latest + +# A group from a mounted file +docker run -d -p 8000:8000 \ + -v ./deployment-groups.yaml:/app/deployment-groups.yaml:ro \ + -e BLUEPRINT_GROUP=checkout \ + my-agents:latest ``` -Three rules the service enforces at startup, each failing loudly rather than being ignored: +With neither, the process **stops before binding its port** and prints which of the two is missing. +That is deliberate: a pod that passes its probes while one agent's queue silently backs up is a +worse failure than a pod that will not start. -| Declaration | Result | -|---|---| -| `envvar_prefix = "orders"` | **Rejected.** Dynaconf upper-cases the prefix before matching, so the `orders_*` you export would never be read. Declare it in the case you will export it in. | -| `envvar_prefix = "BLUEPRINT"` or `"POD"` | **Rejected.** Stripping the prefix would turn `BLUEPRINT_GROUP` into the key `group` and expose deployment identity to agent code. | -| `envvar_prefix` inside `[default]` | **Rejected.** The prefix decides how the environment section is chosen, so it cannot live inside one. | +--- -`DYNACONF_*` keeps working whatever prefix you declare -- Dynaconf always loads it and cannot be -told not to -- so an existing deployment can migrate one variable at a time. Where both spellings -set the same key, the declared prefix wins. +## Choosing what a process runs -#### Turning the Prefix Off +| Variable | Default | Meaning | +|---|---|---| +| `BLUEPRINT_GROUP` | -- | Which group in the file to run. Optional when the file declares exactly one | +| `BLUEPRINT_AGENTS` | -- | Comma-separated agent names, supplying the group with no file at all | +| `BLUEPRINT_CRITICAL_AGENTS` | -- | Comma-separated subset whose failure stops the process and gates readiness | +| `BLUEPRINT_GROUP_CONFIG` | `./deployment-groups.yaml` | Where the group file is | +| `BLUEPRINT_AGENT_MAP` | `./agents.toml` | Where the agent map is | -`envvar_prefix = false` (or `BLUEPRINT_ENVVAR_PREFIX=false`) makes every environment variable a -setting, with no prefix at all: +The environment **overrides the file key by key**, so one Deployment can change the agent list +without editing or duplicating a mounted file. Every resolved value is logged with the source it +came from, because "which agents did this pod actually start" is the first question asked of a group +that misbehaves. -```bash -docker run -e BLUEPRINT_ENVVAR_PREFIX=false -e MODEL_NAME="gpt-4" my-ai-service:latest -``` +These five are read before any `Config` exists -- group composition decides which agents get a +configuration view at all -- so they are plain environment variables with an explicit `BLUEPRINT_` +prefix, not Dynaconf settings. They are not readable from agent code. -**This absorbs the whole process environment into your configuration** -- `PATH`, `HOSTNAME`, the -service-discovery variables Kubernetes injects for every Service in the namespace, and any -credential that happens to be exported. Measured on a development machine: 88 settings keys from a -5-key settings file. Anything colliding with one of your key names silently replaces it. - -Prefer a short project prefix. Use `false` only for a container whose environment you fully control -and deliberately want to pass through -- and read the startup log line, which states which prefix -the process resolved. +**One Deployment per group.** A group file with three groups is three Deployments over one image, +each setting its own `BLUEPRINT_GROUP`. Splitting an agent out into its own pod is a fourth +Deployment and an edit to the file; nothing is rebuilt, and nothing on the broker changes. --- ## Kubernetes with Helm -### Helm Chart Structure +### Chart structure ``` helm/ @@ -172,17 +128,20 @@ helm/ deployment.yaml service.yaml configmap.yaml + groups-configmap.yaml + cronjob.yaml # only if an agent runs a scheduler in "event" mode hpa.yaml ``` ### values.yaml ```yaml -replicaCount: 1 # multi-replica is unsafe in this release; see the warning at the top +group: checkout # which group this Deployment runs +replicaCount: 2 # safe; see "Running more than one replica" image: - repository: myregistry.azurecr.io/my-ai-service - tag: "latest" + repository: myregistry.azurecr.io/my-agents + tag: "1.2.3" pullPolicy: IfNotPresent service: @@ -191,8 +150,8 @@ service: targetPort: 8000 dapr: - enabled: true - appId: "my-ai-service" + enabled: false # a group has one Dapr endpoint; see the note under scaling + appId: "checkout" appPort: 8000 logLevel: "info" @@ -206,7 +165,7 @@ resources: memory: 512Mi limits: cpu: "1" - memory: 1Gi + memory: 1Gi # a group's memory is the sum of its agents; see "Sizing a group" probes: liveness: @@ -220,7 +179,7 @@ probes: initialDelaySeconds: 10 periodSeconds: 10 timeoutSeconds: 5 - failureThreshold: 3 + failureThreshold: 12 # the broker's own startup; see "Health probes" autoscaling: enabled: false @@ -229,25 +188,28 @@ autoscaling: targetCPUUtilizationPercentage: 70 ``` -### Deployment Template +### Deployment template ```yaml # templates/deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: - name: {{ .Release.Name }} + name: {{ .Release.Name }}-{{ .Values.group }} labels: app: {{ .Release.Name }} + group: {{ .Values.group }} spec: replicas: {{ .Values.replicaCount }} selector: matchLabels: app: {{ .Release.Name }} + group: {{ .Values.group }} template: metadata: labels: app: {{ .Release.Name }} + group: {{ .Values.group }} annotations: {{- if .Values.dapr.enabled }} dapr.io/enabled: "true" @@ -257,24 +219,35 @@ spec: {{- end }} spec: containers: - - name: {{ .Release.Name }} + - name: agents image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" imagePullPolicy: {{ .Values.image.pullPolicy }} ports: - containerPort: {{ .Values.app.port }} + env: + - name: BLUEPRINT_GROUP + value: {{ .Values.group | quote }} + - name: POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name envFrom: - configMapRef: name: {{ .Release.Name }}-config - secretRef: name: {{ .Release.Name }}-secrets optional: true + volumeMounts: + - name: groups + mountPath: /app/deployment-groups.yaml + subPath: deployment-groups.yaml + readOnly: true livenessProbe: httpGet: path: {{ .Values.probes.liveness.path }} port: {{ .Values.app.port }} initialDelaySeconds: {{ .Values.probes.liveness.initialDelaySeconds }} periodSeconds: {{ .Values.probes.liveness.periodSeconds }} - timeoutSeconds: {{ .Values.probes.liveness.timeoutSeconds }} failureThreshold: {{ .Values.probes.liveness.failureThreshold }} readinessProbe: httpGet: @@ -282,80 +255,320 @@ spec: port: {{ .Values.app.port }} initialDelaySeconds: {{ .Values.probes.readiness.initialDelaySeconds }} periodSeconds: {{ .Values.probes.readiness.periodSeconds }} - timeoutSeconds: {{ .Values.probes.readiness.timeoutSeconds }} failureThreshold: {{ .Values.probes.readiness.failureThreshold }} resources: {{- toYaml .Values.resources | nindent 12 }} + volumes: + - name: groups + configMap: + name: {{ .Release.Name }}-groups ``` -### Service Template +`POD_NAME` is worth injecting: the framework reads it for the telemetry `service.instance.id` and +for the NATS connection name (`..`), which is what makes "which replica did +that" answerable from the broker's own connection list. + +### The group file as a ConfigMap ```yaml -# templates/service.yaml +# templates/groups-configmap.yaml apiVersion: v1 -kind: Service +kind: ConfigMap metadata: - name: {{ .Release.Name }} + name: {{ .Release.Name }}-groups +data: + deployment-groups.yaml: | + groups: + - name: checkout + agents: [order, billing] + critical_agents: [order] + - name: reporting + agents: [reports] +``` + +One ConfigMap, mounted into every Deployment; each picks its slice with `BLUEPRINT_GROUP`. The +alternative -- `BLUEPRINT_AGENTS` per Deployment and no file at all -- works and is simpler for two +or three agents; the file earns its keep once the composition is something you want to review as a +diff. + +`critical_agents` decides two things at once: whether the process starts at all when that agent +cannot be loaded, and whether that agent can take the pod out of service rotation. The default is +**critical** for every agent in the group. Naming a subset is the deliberate choice to run the rest +without the others. + +### Deploying + +```bash +helm install checkout ./helm --namespace agents --create-namespace \ + --set group=checkout --set image.tag=1.2.3 + +helm upgrade checkout ./helm --namespace agents --set image.tag=1.3.0 + +# Split an agent out of the group: edit the group file, deploy a second release +helm install reporting ./helm --namespace agents --set group=reporting +``` + +--- + +## Running more than one replica + +Three mechanisms make this safe, and each has a setting you should look at. + +### 1. Every replica joins one queue group + +Core NATS subscriptions carry a queue group and JetStream consumers are durable with a shared +deliver group, so **one message goes to one replica**. The name is the agent's namespace in a group, +and `nats_queue_group` (falling back to `app_name`) at the root -- never the deployment group, so +scaling out and regrouping are independent of each other. + +### 2. Every delivery is acknowledged, naked or terminated + +| Outcome | Disposition | +|---|---| +| Handled, or no handler matched it | **ack** -- an unmatched event is not a failure | +| A retryable failure | **nak**, redelivered after `nats_ack_wait` | +| A poison payload, or a `CriticalHandlerError` | **term**, and dead-lettered | +| `nats_max_deliver` attempts exhausted | dead-lettered | + +Two keys to set deliberately: + +- **`nats_ack_wait`** (default `300.0` seconds) must exceed your p99 handler duration. Set it below + that and the broker redelivers work that is still in progress, to a second replica. +- **`nats_max_ack_pending`** (default `16`) is the in-flight limit **across every replica sharing + the consumer**, not per replica. Scaling to eight replicas with the default gives you sixteen + concurrent messages in total, which is usually the reason throughput does not improve with pod + count. + +### 3. Deduplication, if your handlers need it + +Delivery is at-least-once, permanently: a lost acknowledgement, a pod killed mid-handler or a +rolling deploy each produce a redelivery *after* the first attempt has committed its side effects. +Two honest answers, and the framework will not choose for you: + +- make the handlers safe to repeat (upsert rather than insert, key the outbound call on + `event.id`), or +- set `idempotency_enabled = true` and `idempotency_ttl`. + +**The TTL must outlast the broker's redelivery window**, which is +`nats_ack_wait * nats_max_deliver`: + +``` +300 s x 5 = 1500 s # the defaults +idempotency_ttl = 1800 # with headroom for clock skew and a slow restart +``` + +Too short and a redelivery arrives after the marker has expired, which is the case dedup exists to +prevent. Too long only costs cache entries. If you raise `nats_ack_wait` or `nats_max_deliver`, +raise this with them. + +Two limits to know: dedup needs the agent to declare `with_cache()` -- the marker lives in that +agent's own cache -- and `exists`-then-`set` is not atomic on either backend, so two replicas handed +the same event in the same instant can both dispatch. It closes the ordinary window, not every +window. + +**Grouped Dapr is the exception that wants dedup on.** A group has one Dapr endpoint: it publishes +the union of every agent's topics and fans each delivery out to the agents that declared it, and the +single acknowledgement Dapr gets is their combination. So a retry asked for by one agent redelivers +to *every* agent in the group. NATS has no such coupling -- each agent holds its own subscription. + +### Dead letters accumulate, and nothing drains them + +A message that exhausts `nats_max_deliver`, or that a handler terminates, is published to +`nats_dead_letter_subject` -- by default `.dead-letter`. The framework does not read +that subject. Messages sit there subject to the stream's retention, so **a deployment that never +drains it loses dead letters silently when the stream ages them out.** + +Before going multi-replica, decide who reads it. `blueprint.events.dead_lettered` (labelled with +`reason` and whether the payload was `kept`) is the metric to alert on; the subject itself needs a +consumer -- an operational tool, a second agent, or a person with `nats sub`. + +### Autoscaling + +```yaml +# templates/hpa.yaml +{{- if .Values.autoscaling.enabled }} +apiVersion: autoscaling/v2 +kind: HorizontalPodAutoscaler +metadata: + name: {{ .Release.Name }}-{{ .Values.group }} spec: - type: {{ .Values.service.type }} - ports: - - port: {{ .Values.service.port }} - targetPort: {{ .Values.service.targetPort }} - protocol: TCP - selector: - app: {{ .Release.Name }} + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: {{ .Release.Name }}-{{ .Values.group }} + minReplicas: {{ .Values.autoscaling.minReplicas }} + maxReplicas: {{ .Values.autoscaling.maxReplicas }} + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }} +{{- end }} ``` -### ConfigMap Template +CPU is a poor signal for an event-driven agent that spends its time waiting on an LLM. Consumer lag +or in-flight count is the metric you actually want to scale on, and reaching it needs a metrics +adapter. Raise `nats_max_ack_pending` before adding replicas: with the default, more pods share the +same sixteen in-flight messages. + +--- + +## Schedulers + +`scheduler_mode` has no default and is required as soon as a scheduler is registered, because +neither value is safe to inherit. It resolves **per agent**, so one agent may run an in-process +timer beside a neighbour driven by external ticks. + +### `scheduler_mode = "in_process"` + +An APScheduler timer runs in every replica, and each tick is **claimed** in the agent's own cache -- +a marker keyed on `(scheduler, minute)` -- so the replica that stores it runs the tick and the rest +do not. Nothing is elected and nothing is held, so there is no lease to renew and none to be left +behind by a replica that dies. + +It needs `.with_cache()` on that agent. Without one the claim has nowhere to go and **every replica +runs every tick**; the framework logs this at startup and `asbs validate` reports it. Right for local +development, plain Docker, and a single-replica deployment. + +### `scheduler_mode = "event"` + +No timer runs in the process at all. The tick arrives as an ordinary event on + +``` +.scheduler. +``` + +-- the agent's namespace, or `app_name` for a scheduler at the root. It is the queue group that +delivers it, so exactly one replica runs it however many there are. It needs `event_bus` set. + +**Nothing in this repository generates the `CronJob`.** The schedule stays declared in agent code, +the `CronJob` must publish on the schedule that code declares, and keeping them in step is currently +manual: ```yaml -# templates/configmap.yaml -apiVersion: v1 -kind: ConfigMap +apiVersion: batch/v1 +kind: CronJob metadata: - name: {{ .Release.Name }}-config -data: - DYNACONF_APP__PORT: {{ .Values.app.port | quote }} - DYNACONF_APP__LOG_LEVEL: {{ .Values.app.logLevel | quote }} + name: order-nightly-tick +spec: + schedule: "0 2 * * *" # must match the scheduler's declared crontab + concurrencyPolicy: Forbid + jobTemplate: + spec: + template: + spec: + restartPolicy: OnFailure + containers: + - name: tick + image: natsio/nats-box:latest + args: + - /bin/sh + - -c + - | + nats --server "$NATS_URL" pub order.scheduler.nightly \ + '{"specversion":"1.0","type":"scheduler.tick","source":"cronjob","id":"'"$(date +%s)"'"}' + env: + - name: NATS_URL + value: nats://nats:4222 ``` -### Deploying with Helm +The tick handler matches on the **topic**, not the event type, so any CloudEvent published to that +subject fires the scheduler. A `CronJob` is at-least-once too -- a restart or a missed +`startingDeadlineSeconds` can produce a second tick -- so an event-mode scheduler whose tick is not +safe to repeat wants `idempotency_enabled`. -```bash -# Install the chart -helm install my-ai-service ./helm \ - --namespace ai-services \ - --create-namespace - -# Install with custom values -helm install my-ai-service ./helm \ - --namespace ai-services \ - --set image.tag="v1.2.3" \ - --set replicaCount=1 # see the warning at the top: more than one is unsafe in this release - -# Upgrade an existing release -helm upgrade my-ai-service ./helm \ - --namespace ai-services \ - --set image.tag="v1.3.0" - -# Uninstall -helm uninstall my-ai-service --namespace ai-services +Both modes are alerted on the same way: `blueprint.scheduler.tick_age_seconds` reports how long ago +the last tick ran, `-1` before the first. "Two intervals late" is an expression you write against +that gauge; the framework does not interpret your crontab. + +--- + +## Health probes + +Two endpoints, and they answer different questions: + +| Endpoint | Question | Never depends on | +|---|---|---| +| `GET /health/live` | Is this process running? | any agent's state | +| `GET /health/ready` | Should this pod receive traffic? | -- | + +**Liveness is never agent-dependent, deliberately.** If one degraded agent failed the pod's liveness +probe, Kubernetes would restart every agent in the group, reintroducing exactly the blast radius +grouping was paid to remove. + +Also served, and useful when debugging rather than as probes: `GET /info`, `/status/env`, +`/status/llm`, `/status/build`. There is no `/health/detailed`. + +### `readiness_policy` + +A process-scope key -- one pod has one readiness probe: + +| Value | `/health/ready` is `200` when | +|---|---| +| `all` (default) | every agent is up | +| `critical` | every agent the group flagged critical is up | +| `any` | at least one agent is up | + +The root namespace gates readiness under all three: it holds the shared infrastructure, and a +single-agent application is entirely root. + +### The payload + +```json +{ + "status": "UP", + "policy": "critical", + "components": { + "orders.nats_client": {"status": "healthy", "message": "Connected to NATS server at ..."}, + "billing.cache": {"status": "unhealthy", "message": "redis is unreachable"} + }, + "namespaces": { + "": {"status": "UP", "critical": true, "failing": []}, + "orders": {"status": "UP", "critical": true, "failing": []}, + "billing": {"status": "DOWN", "critical": false, "failing": ["billing.cache"]} + } +} ``` +`components` is keyed by entry name -- bare at the root, `.` for an agent -- so a +single-agent payload's keys are unchanged. `namespaces` exists because the policy makes `status` no +longer derivable from `components`: the pod above answers `UP` with a failing check in it. + +### Broker startup + +The broker connection is established asynchronously after startup, and `/health/ready` answers `503` +until every topic subscription is active. Set `failureThreshold` high enough to outlast the broker's +own startup -- `periodSeconds: 10` with `failureThreshold: 12` gives two minutes. See +[Broker Startup Resilience](../concepts/event-processing.md#broker-startup-resilience). + +### Alerting on an agent, not on the pod + +Grouping removes the pod restart that used to serve as the alert, so the alert is emitted +deliberately instead. Every path that stops an agent serving emits an ERROR-level event carrying +that agent's own telemetry identity and drives `blueprint.namespace.up{agent} = 0` -- including the +case the probe cannot see, an agent whose subscriptions have gone while the process stays healthy. +Alert on that gauge. The probe decides where traffic goes; alerting decides who is woken. + +A degraded agent's transports are **paused**, not closed: it stops consuming, and can be seen to +recover. A closed client would report itself unhealthy for ever, so a transient fault would take the +agent off its topics permanently. + --- -### Writable Cache Directory +## Writable cache directory The disk cache backend (`cache.backend = "disk"`, the default) writes to `cache.cache_dir`, which -defaults to the **relative** path `.cache/blueprint` -- resolved against the working directory, -so `/app/.cache/blueprint` in the generated image. It is created at startup, and a container can -only create it where the process user may write. +defaults to the **relative** path `.cache/blueprint` -- resolved against the working directory, so +`/app/.cache/blueprint` in the generated image. It is created at startup, and a container can only +create it where the process user may write. Two things have to be true, and neither is automatic: -1. **The directory belongs to the user the process runs as.** `WORKDIR /app` creates `/app` owned - by root, and the image runs as `appuser`, so `mkdir /app/.cache` fails with EACCES. The - generated Dockerfile therefore creates and hands it over at build time: +1. **The directory belongs to the user the process runs as.** `WORKDIR /app` creates `/app` owned by + root, and the image runs as `appuser`, so `mkdir /app/.cache` fails with EACCES. The generated + Dockerfile therefore creates and hands it over at build time: ```dockerfile RUN mkdir -p /app/.cache && chown -R appuser:appuser /app/.cache @@ -363,15 +576,14 @@ Two things have to be true, and neither is automatic: A project scaffolded before this was added needs the same two lines. -2. **A read-only root filesystem needs a volume mounted there.** With - `readOnlyRootFilesystem: true` the ownership above is irrelevant -- nothing may be written - anywhere except a mounted volume, and the mount is declared in the pod spec rather than - discovered at runtime: +2. **A read-only root filesystem needs a volume mounted there.** With `readOnlyRootFilesystem: true` + the ownership above is irrelevant -- nothing may be written anywhere except a mounted volume, and + the mount is declared in the pod spec rather than discovered at runtime: ```yaml spec: containers: - - name: agent + - name: agents securityContext: readOnlyRootFilesystem: true runAsNonRoot: true @@ -384,183 +596,214 @@ Two things have to be true, and neither is automatic: sizeLimit: 1Gi ``` - Keep `sizeLimit` at or above `cache.size_limit` (default 1 GB): an `emptyDir` is backed by - node disk, and a pod that exceeds its limit is evicted. + Keep `sizeLimit` at or above `cache.size_limit` (default 1 GB): an `emptyDir` is backed by node + disk, and a pod that exceeds its limit is evicted. + +If the directory cannot be created the service fails at startup with a message naming the path and +these options, rather than an errno from inside a constructor. -If the directory cannot be created the service fails at startup with a message naming the path -and these options, rather than an errno from inside a constructor. +**Grouped agents still need only one mount.** Each agent's cache is a *subdirectory* of +`cache.cache_dir` -- `/orders.default` for agent `orders`, and +`/orders.sessions` for a cache it named `sessions` -- so a group of five agents mounts the +one volume a single agent does. One `size_limit` budget covers all of them, which is worth +remembering when the group grows. -**Grouped agents need no additional paths.** Agents hosted in one process share one cache backend -and are isolated by key prefix, not by directory, so a group of five agents mounts the same single -volume a single agent does and keeps one `size_limit` budget over it. +**Or avoid the filesystem entirely.** `cache.backend = "redis"` needs no writable path, which makes +it the simpler choice for a hardened pod, and the only choice if the cache has to survive a restart +or be shared across replicas -- an `emptyDir` is per pod and is deleted with it. On Redis the +per-agent separation is a key prefix (`:orders.default`) rather than a directory. -**Or avoid the filesystem entirely.** `cache.backend = "redis"` needs no writable path, which -makes it the simpler choice for a hardened pod, and the only choice if the cache has to survive a -restart or be shared across replicas -- an `emptyDir` is per pod and is deleted with it. +> **Upgrading an existing deployment starts with a cold cache.** The key layout changed during the +> multi-agent work, so a persistent Redis cache or a mounted disk cache will not find its old +> entries. Nothing errors; the first requests after the deploy are slow. If any cache entry is +> load-bearing rather than an optimisation, migrate it before cutting over. --- -## Health Probes +## Configuration + +### Environment variable overrides -Blueprint Agents provides three built-in health endpoints: +Any setting can be overridden at runtime with an environment variable. The default prefix is +`DYNACONF_`, and **`__` denotes nesting** -- so a top-level key takes a single underscore and a +sectioned one takes two: -### /health/live +```toml +[default] +app_port = 8000 +log_level = "INFO" +model_provider = "openai" -Returns a simple liveness check indicating the application process is running. +[default.cache] +backend = "redis" -```json -{ - "status": "alive" -} +[default.runtimes.order_agent] +model_name = "gpt-4.1-nano" ``` -Use this for the Kubernetes liveness probe. If this endpoint fails, the container should be restarted. +```bash +docker run \ + -e DYNACONF_APP_PORT=9000 \ + -e DYNACONF_LOG_LEVEL="DEBUG" \ + -e DYNACONF_MODEL_PROVIDER="openai" \ + -e DYNACONF_MODEL_API_KEY="sk-..." \ + -e DYNACONF_CACHE__BACKEND="redis" \ + -e DYNACONF_RUNTIMES__ORDER_AGENT__MODEL_NAME="gpt-4.1-mini" \ + my-agents:latest +``` -### /health/ready +Getting this wrong is quiet: `DYNACONF_APP__PORT` creates a nested `app.port` that nothing reads, +and the process keeps its default. Most of the framework's own keys are **flat** -- `app_port`, +`log_level`, `log_format`, `event_bus`, `nats_url`, `model_provider`, `idempotency_enabled`, +`scheduler_mode`, `readiness_policy`. The sectioned ones are `cache.*` and `runtimes..*`. -Returns a readiness check indicating the application and its dependencies are ready to serve traffic. +#### Choosing your own prefix -```json -{ - "status": "ready" -} -``` +`DYNACONF_` is the default, not the only option. Declare `envvar_prefix` as a **top-level** key -- +above every section, because the prefix is resolved before any environment section is selected: -Use this for the Kubernetes readiness probe. If this endpoint fails, the pod is removed from the service load balancer until it recovers. +```toml +envvar_prefix = "ORDERS" -> **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). +[default] +app_name = "orders" +``` -### /health/detailed +```bash +docker run -e ORDERS_MODEL_NAME="gpt-4" my-agents:latest +``` -Returns component-level health status for debugging and monitoring. +An operator can override the declared prefix without rebuilding the image, using the framework's own +bootstrap variable: -```json -{ - "status": "healthy", - "components": { - "cache": {"status": "healthy", "latency_ms": 2}, - "llm_provider": {"status": "healthy", "latency_ms": 150}, - "event_bus": {"status": "healthy", "latency_ms": 5} - } -} +```bash +docker run -e BLUEPRINT_ENVVAR_PREFIX="ORDERS" -e ORDERS_MODEL_NAME="gpt-4" my-agents:latest ``` -### Kubernetes Probe Configuration +Three rules the service enforces at startup, each failing loudly rather than being ignored: -```yaml -livenessProbe: - httpGet: - path: /health/live - port: 8000 - initialDelaySeconds: 15 - periodSeconds: 20 - timeoutSeconds: 5 - failureThreshold: 3 - -readinessProbe: - httpGet: - path: /health/ready - port: 8000 - initialDelaySeconds: 10 - periodSeconds: 10 - timeoutSeconds: 5 - failureThreshold: 3 -``` +| Declaration | Result | +|---|---| +| `envvar_prefix = "orders"` | **Rejected.** Dynaconf upper-cases the prefix before matching, so the `orders_*` you export would never be read. Declare it in the case you will export it in. | +| `envvar_prefix = "BLUEPRINT"` or `"POD"` | **Rejected.** Stripping the prefix would turn `BLUEPRINT_GROUP` into the key `group` and expose deployment identity to agent code. | +| `envvar_prefix` inside `[default]` | **Rejected.** The prefix decides how the environment section is chosen, so it cannot live inside one. | ---- +`DYNACONF_*` keeps working whatever prefix you declare -- Dynaconf always loads it and cannot be told +not to -- so an existing deployment can migrate one variable at a time. Where both spellings set the +same key, the declared prefix wins. -## Environment Configuration +`envvar_prefix` is **process scope**: one process reads its environment through one prefix, so an +agent's own settings file cannot set it. The same is true of `app_port`, `app_host`, `app_workers`, +`app_environment`, `event_bus`, `log_level`, `log_format`, `readiness_policy` and +`nats_stream_name` -- they belong to the group's settings file, and a copy under one agent's scope +is dropped with a warning at startup. -### Settings via ConfigMap +#### Turning the prefix off -Non-sensitive configuration values belong in a Kubernetes ConfigMap: +`envvar_prefix = false` (or `BLUEPRINT_ENVVAR_PREFIX=false`) makes every environment variable a +setting, with no prefix at all: + +```bash +docker run -e BLUEPRINT_ENVVAR_PREFIX=false -e MODEL_NAME="gpt-4" my-agents:latest +``` + +**This absorbs the whole process environment into your configuration** -- `PATH`, `HOSTNAME`, the +service-discovery variables Kubernetes injects for every Service in the namespace, and any credential +that happens to be exported. Measured on a development machine: 88 settings keys from a 5-key +settings file. Anything colliding with one of your key names silently replaces it. + +Prefer a short project prefix. Use `false` only for a container whose environment you fully control +and deliberately want to pass through -- and read the startup log line, which states which prefix the +process resolved. + +### ConfigMap and Secret ```yaml apiVersion: v1 kind: ConfigMap metadata: - name: my-ai-service-config + name: checkout-config data: - DYNACONF_APP__PORT: "8000" - DYNACONF_APP__LOG_LEVEL: "info" - DYNACONF_CACHE__TTL: "3600" - DYNACONF_LLM__PROVIDER: "openai" - DYNACONF_LLM__MODEL: "gpt-4" + DYNACONF_APP_PORT: "8000" + DYNACONF_LOG_LEVEL: "info" + DYNACONF_EVENT_BUS: "nats" + DYNACONF_NATS_URL: "nats://nats:4222" + DYNACONF_CACHE__BACKEND: "redis" + DYNACONF_CACHE__REDIS_URL: "redis://redis:6379" + DYNACONF_IDEMPOTENCY_ENABLED: "true" + DYNACONF_IDEMPOTENCY_TTL: "1800" + DYNACONF_READINESS_POLICY: "critical" ``` -### Secrets via Kubernetes Secrets - -Sensitive values such as API keys and credentials belong in Kubernetes Secrets: - ```yaml apiVersion: v1 kind: Secret metadata: - name: my-ai-service-secrets + name: checkout-secrets type: Opaque stringData: - DYNACONF_LLM__API_KEY: "sk-..." - DYNACONF_DATABASE__PASSWORD: "secret-password" + DYNACONF_MODEL_API_KEY: "sk-..." + DYNACONF_CACHE__REDIS_PASSWORD: "..." ``` -### Dynaconf Override Hierarchy +### Resolution order -Dynaconf resolves configuration in the following order (later sources override earlier ones): +Later sources override earlier ones: -1. `settings.toml` -- base configuration baked into the image -2. `secrets.toml` -- local secrets (not used in production) -3. Environment variables -- ConfigMap and Secret values injected into the pod - -This means environment variables always take precedence over file-based configuration. +1. `settings.toml` -- base configuration, baked into the image +2. each agent's own `settings.toml`, merged under that agent's scope -- filling gaps only, so the + group's file and any `DYNACONF___KEY` win over it +3. `secrets.toml` -- local development only; never copied into the image +4. environment variables -- the ConfigMap and Secret above --- -## Scaling Considerations - -### Horizontal Pod Autoscaling - -Leave autoscaling disabled in the current release — see the warning at the top of this guide. -Scaling past one replica multiplies event processing, acknowledgement loss and cron ticks -rather than throughput. +## Sizing a group + +Group size is a dial, not an architecture. A group of one gives per-agent process isolation; a +group of twenty shares one runtime, one port, one health endpoint and one broker connection. + +What to watch when you turn it up: + +- **Memory is the sum of the agents.** Each agent has its own thread pool, its own AI client and + its own transport subscriptions. Set the pod's memory limit against the group, not against one + agent, and remember that a memory-limit kill takes the whole group with it. +- **Three failure classes take a whole group down and raise no catchable exception**: the memory + limit, a native crash, and a blocked event loop. Careful error handling lowers how often a group + dies; it does not change which failures kill it. That is why attribution is emitted deliberately + (see *Alerting on an agent*) -- and why the blast radius, not the happy path, is what should + decide group size. +- **Blocking the event loop is the mistake that only hurts in a group.** In development, + `app_environment = "development"` puts asyncio in debug mode and names the slow callback itself + (`event_loop_slow_callback_seconds`, default `0.2`). In production a lower-overhead watchdog + measures the loop's lag and reports which agents had work in flight when it stalled + (`event_loop_block_threshold_seconds`, default `1.0`) -- candidates, not a culprit, because by + the time it runs the blocking call has returned. Debug mode is available in production behind + `event_loop_debug` at the cost of wrapping every coroutine creation, and the two are never both + on: with debug mode enabled the watchdog stands down. +- **One agent's failure should not remove the pod.** Use `critical_agents` plus + `readiness_policy = "critical"` so that a non-critical agent going down is an alert rather than a + pod out of rotation. -Enable automatic scaling based on CPU utilization: - -```yaml -# templates/hpa.yaml -{{- if .Values.autoscaling.enabled }} -apiVersion: autoscaling/v2 -kind: HorizontalPodAutoscaler -metadata: - name: {{ .Release.Name }} -spec: - scaleTargetRef: - apiVersion: apps/v1 - kind: Deployment - name: {{ .Release.Name }} - minReplicas: {{ .Values.autoscaling.minReplicas }} - maxReplicas: {{ .Values.autoscaling.maxReplicas }} - metrics: - - type: Resource - resource: - name: cpu - target: - type: Utilization - averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }} -{{- end }} -``` +--- -### Cache Considerations +## Stateless design -When running multiple replicas, be aware of cache behavior: +Handlers and services should be designed as stateless components: -- **File-based cache**: Uses file-based locking to prevent corruption. If replicas share a volume, locking ensures consistency. If each replica has its own volume, caches are independent and may diverge. -- **Recommendation**: For multi-replica deployments, prefer an external cache (Redis, Memcached) over file-based caching to ensure consistency across all replicas. +- Do not store request-specific state in instance variables. In a group your component is one of + several in a shared process; across replicas there is no shared memory at all. +- Use the cache service for data that must persist across requests, and Redis rather than the disk + backend when it must be shared across replicas. +- Use the event bus for inter-service communication rather than in-memory shared state. +- Any initialisation that must happen once belongs in `on_startup()` and must be idempotent: it runs + once per process, which is once per replica. -### Stateless Design +--- -Handlers and services should be designed as stateless components: +## See also -- Do not store request-specific state in instance variables. -- Use the cache service for data that must persist across requests. -- Use the event bus for inter-service communication rather than in-memory shared state. -- Any initialization that must happen once should be performed in `on_startup()` and should be idempotent. +- [Multi-Agent Setup](multi-agent-setup.md) -- the model, and migrating an existing agent into a group +- [Caching](../concepts/caching.md) -- backends, named caches, per-agent stores +- [Observability](../concepts/observability.md) -- metrics, traces and what each agent reports +- [Event Processing](../concepts/event-processing.md) -- the ack contract and broker startup diff --git a/docs/guides/multi-agent-setup.md b/docs/guides/multi-agent-setup.md new file mode 100644 index 00000000..0b74caad --- /dev/null +++ b/docs/guides/multi-agent-setup.md @@ -0,0 +1,428 @@ +# Multi-Agent Setup + +How to run several agents in one process, and how to move an agent you already have into one. + +The model in one sentence: **an agent's code says nothing about which other agents it runs beside.** +A project declares what it is made of; a deployment decides which of those declarations a given +process hosts. Changing that decision is an edit to a Deployment, not a rebuild, and -- after the +first grouped deploy -- it is invisible to the broker, to your dashboards and to the agent's own +code. + +Why you would want it: one process per agent is the safest shape and the most expensive one. A +group of ten agents shares one port, one health endpoint, one NATS connection and one Python +runtime. The dial runs from a group of one (full process isolation) to a group of twenty, and it is +a runtime setting rather than an architectural commitment. + +--- + +## Read this first: which of the two are you doing? + +Everything below splits along one question, and the answers differ in ways that matter: + +| | You are here if | What changes | +|---|---|---| +| **A. A new project** | You are running `asbs setup` today | Nothing to migrate. Your agent has a real namespace from the first run | +| **B. An existing single-agent project** | You have a `main.py` that builds and serves an application | Three files change, and your **broker-side identity changes once** -- see [What changes](#what-changes-and-what-does-not) | + +A third answer is legitimate and costs nothing: **do nothing.** An existing project that is +deployed on its own keeps working, unchanged, indefinitely. There is no deprecation here. + +--- + +## A. A new project + +```bash +asbs setup order-processor +cd OrderProcessor +``` + +Two of the files it writes are what make the project hostable: + +**`src/main.py` is a declaration, not an application.** + +```python +order_processor_agent = ( + AgentBuilder(runtime_name="order_processor_agent") + .with_model_from_config() + .with_system_prompt("order_processor_agent_system") +) + +agent = ( + AppBuilder() + .with_service(OrderProcessorService) + .with_agent(order_processor_agent, name="order_processor_agent") + .with_handler(OrderProcessorHandler) + .with_rest_api(OrderProcessorApi) +) +``` + +There is no `Config` and no `build()`. Every `with_*` call *records* what the agent is made of; +nothing is constructed until whoever hosts this file calls `build()`, which is what lets the same +file be served alone and be hosted beside other agents. Note that components are registered as +**classes**, not instances: a component constructed on the `with_*` line is constructed before any +namespace exists and belongs to the root for ever, which is why a group refuses one. + +**`agents.toml` maps the agent's name to that declaration.** + +```toml +[agents.order_processor] +module = "src.main:agent" +``` + +This file is **baked into the image**: it says what the image contains. It does not say which of +those agents any particular process runs -- that is the deployment's decision, and it arrives +separately. + +The `Dockerfile` runs `python -m blueprint.agents.entrypoint`, which reads `agents.toml`, works out +this process's group, and serves it. + +### Running it + +```bash +asbs dev # every agent in agents.toml, with hot reload +asbs dev --agents order_processor +asbs validate # what this project has not said yet +``` + +`asbs dev` runs your agents under their **real** namespaces, so a local route is +`/api/order_processor/orders/{id}` -- byte-identical to production -- and the local consumer +identity is the production queue group. A development server at the root namespace would give every +developer URLs and integration tests that differ from the deployed ones, in a way nothing reports. + +```bash +docker build -t order-processor . +docker run -e BLUEPRINT_AGENTS=order_processor -p 8000:8000 order-processor +``` + +### Adding a second agent to the same image + +Put the second agent's code in its own package, give it its own declaration module and its own +`settings.toml` **beside that module**, and add it to the map: + +```toml +[agents.order_processor] +module = "src.order_processor.main:agent" + +[agents.billing] +module = "src.billing.main:agent" +``` + +Each agent's `settings.toml` is read from the directory its declaration lives in and merged under +that agent's own scope, so both may write plain top-level keys and neither sees the other's. Keys +that describe the *process* -- `app_port`, `app_host`, `app_workers`, `app_environment`, +`envvar_prefix`, `event_bus`, `log_level`, `log_format`, `readiness_policy`, `nats_stream_name` and +the rest -- belong in the group's own settings file: one process binds one port, speaks one bus and +answers one readiness probe, so a copy under one agent's scope is read by nothing. `asbs validate` +names them if you leave them there. + +--- + +## B. Migrating an existing single-agent project + +Three files change, and nothing else. Read +[the one decision to get right first](#the-one-decision-to-get-right-first) before you start: one +of the three is a name you cannot cheaply change afterwards. + +### 1. `src/main.py` -- remove two things, add nothing + +Before: + +```python +config = Config(settings_files=["settings.toml", "secrets.toml"]) + +app = ( + AppBuilder(config) + .with_service(OrderService) + .with_handler(OrderValidationHandler) + .with_rest_api(OrderApi) + .with_cache() + .build() +) +``` + +After -- **the same builder**, minus its `config` argument and minus the `.build()`: + +```python +agent = ( + AppBuilder() + .with_service(OrderService) + .with_handler(OrderValidationHandler) + .with_rest_api(OrderApi) + .with_cache() +) +``` + +Every `with_*` call stays exactly where it was. `with_cache()` included. That is the point of there +being one builder class: migration removes two things and adds none, because the declaration and +the application builder are the same object. + +If the agent is **also** still to be served on its own, add a factory -- optional, and it repeats no +component: + +```python +def create_app(): + return agent.build(Config(settings_files=["settings.toml", "secrets.toml"])) +``` + +Two things the module must not do, because it is imported into a shared runtime: construct clients +or other components at import time, and call `logging.basicConfig()`. Configuration and logging +belong to the process that hosts the declaration. + +If you are passing **instances** anywhere -- `with_rest_api(OrderApi())` -- change them to classes. +An instance is constructed at that line, before any namespace exists, so it belongs to the root for +ever; a group refuses one at assembly and names the agent and the fix. + +### 2. `Dockerfile` -- one command + +```diff +-CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"] ++CMD ["python", "-m", "blueprint.agents.entrypoint"] +``` + +and copy the map into the image beside your settings: + +```dockerfile +COPY --chown=appuser:appuser agents.toml ./ +``` + +### 3. `agents.toml` -- a new file + +```toml +[agents.order] +module = "src.main:agent" +``` + +Required even for a group of one: it is the only thing that turns an agent's name into code. There +is discovery by convention nowhere in this, deliberately -- a set of agents that depends on what +happens to be importable makes a renamed directory a silently removed agent. + +### 4. Check it + +```bash +asbs validate +``` + +It reads the map, holds the name to the namespace alphabet, confirms the module exists and assigns +the attribute you named, and reports anything about schedulers or settings that would not survive +the move. It never imports your project. + +### One declaration, three ways to run it + +| Shape | Command | +|---|---| +| Standalone, unmigrated | `uvicorn src.main:app` | +| Standalone, migrated (with `create_app`) | `uvicorn src.main:create_app --factory` | +| Grouped, including a group of one | `python -m blueprint.agents.entrypoint` | + +--- + +## The one decision to get right first + +**The agent's name in `agents.toml` is its identity everywhere outside that file.** It becomes: + +- the NATS **queue group** it consumes under; +- part of every **JetStream durable** name (`--durable`); +- its **cache** directory and Redis key prefix; +- its OpenTelemetry **`service.name`**; +- its **route prefix**, `/api/`; +- the prefix on every **registry key** its components take. + +So renaming it after the first grouped deploy is a consumer migration -- new durables, messages +still pending on the old ones -- not a rename. Choose it once, before you deploy. + +It must satisfy the namespace alphabet: **`[a-z][a-z0-9_]*`**. Lower case, starting with a letter, +underscores allowed, and **no dashes**. The dash is excluded because it is the separator inside a +durable name: `orders-eu` on topic `created` and `orders` on topic `eu-created` would otherwise +produce the same durable, and two agents would bind one consumer and eat each other's events. The +alphabet is the intersection of what a registry key, a queue group, a consumer name and a telemetry +resource all accept, and a name outside it is **refused, never repaired** -- a name quietly rewritten +by four subsystems is four names for one agent. + +--- + +## What changes, and what does not + +Say which of the two you are doing before reading the table: an agent **left standalone** and an +agent **moved into a group** are affected differently, and only one of them changes anything. + +### An agent left standalone: nothing changes + +A project you do not migrate, or one you migrate and still deploy on its own, runs at the **root +namespace**. Every identity below is byte-identical to what it was, and that is enforced by tests +rather than asserted in prose: + +| | Root namespace (standalone) | +|---|---| +| Registry keys | `nats_client`, `order_service`, ... -- unqualified | +| NATS queue group | `nats_queue_group`, else `app_name` | +| JetStream durable | `-durable` | +| REST routes | `/api/orders/{id}` | +| OpenAPI tag | `Orders` | +| Telemetry `service.name` | `otel_service_name` | +| Disk cache directory | `cache.cache_dir` | +| Redis key prefix | `cache.key_prefix` | + +This is why a migration is a no-op on the broker for anything you keep standalone, and it is a claim +you can check: none of the above reads a namespace when there is none. + +### An agent moved into a group: its identity changes once + +On the **first grouped deploy**, the agent stops taking its identity from `app_name` and takes it +from its own name. That is one consumer migration, and then it is over: + +| | Agent `order` in a group | +|---|---| +| Registry keys | `order_nats_client`, `order_order_service`, ... | +| NATS queue group | `order` | +| JetStream durable | `order--durable` | +| REST routes | `/api/order/orders/{id}` | +| OpenAPI tag | `order.Orders` | +| Telemetry `service.name` | `order` | +| Disk cache directory | `/order.default` | +| Redis key prefix | `:order.default` | + +**Regrouping afterwards changes none of these.** Moving `order` from a group of three to a group of +ten, or out to a group of one, changes which process hosts it and nothing else -- the group's name +reaches the NATS connection name and the telemetry `deployment.group` attribute, and no broker-side +identifier derives from it. That property is the whole point of the feature, and it is what makes +group size a dial you can turn in response to a real failure. + +What does **not** move even in a group: the process-level endpoints. `/health/live`, +`/health/ready`, `/info`, `/status/*` and the OpenAPI document are served by the process, once, +wherever the agents are. `/cache/*` does move -- it becomes `/api//cache/*`, one endpoint set +per agent that declared a cache, because a cache belongs to the agent that declared it and to no +other. + +### The cache is cold after the move + +The cache key layout has changed twice during this work, so an application upgrading with a +**persistent Redis cache or a mounted disk cache will not find its old entries.** Nothing errors; the +cache is simply cold and refills. Plan for the first request after the deploy being slow rather than +for a failure, and if any cache entry is load-bearing rather than an optimisation, migrate it +yourself before cutting over. + +One deployment constraint survives: an agent's disk cache is a **subdirectory** of +`cache.cache_dir`, not a sibling, so a group still needs exactly one writable mount. + +--- + +## Group configuration and the entry point + +Two files, with different lifetimes, and the difference is the reason there are two. + +**`agents.toml` -- what the image contains.** Baked in; it changes only when an agent is added or +removed, which is a rebuild anyway. + +```toml +[agents.order] +module = "src.order.main:agent" + +[agents.billing] +module = "src.billing.main:agent" +``` + +**`deployment-groups.yaml` -- what this process runs.** Never baked in: one image serves every +group, so it arrives as a mount, or is replaced entirely by environment variables. + +```yaml +groups: + - name: checkout + agents: [order, billing] + critical_agents: [order] + - name: order-only + agents: [order] +``` + +`critical_agents` decides what happens when an agent cannot be loaded, and what it can do to the +pod's readiness. The default is **critical**: an agent that fails to load stops the process, because +a pod that passes its probes while one agent's queue silently backs up is a worse failure than no +pod at all. Naming an agent non-critical is the deliberate choice to run the rest without it. + +### Environment + +Every value can come from the environment, and the environment **overrides the file key by key** -- +so one Deployment can change the agent list without editing or duplicating a mounted file. + +| Variable | Default | Meaning | +|---|---|---| +| `BLUEPRINT_GROUP` | -- | Which group in the file to run. Optional when the file declares exactly one | +| `BLUEPRINT_AGENTS` | -- | Comma-separated agent names, supplying the group with no file at all | +| `BLUEPRINT_CRITICAL_AGENTS` | -- | Comma-separated subset to mark critical | +| `BLUEPRINT_GROUP_CONFIG` | `./deployment-groups.yaml` | Where the group file is | +| `BLUEPRINT_AGENT_MAP` | `./agents.toml` | Where the agent map is | + +Setting `BLUEPRINT_AGENTS` supplies the whole group and the file is not consulted for it at all, +which is the `docker run` and CI shape: + +```bash +docker run -e BLUEPRINT_AGENTS=order,billing -e BLUEPRINT_CRITICAL_AGENTS=order my-image +``` + +Every resolved value is logged with the source it came from, because "which agents did this pod +actually start" is the first question asked of a group that misbehaves. + +If the group cannot be resolved -- no agents named, a group that is not in the file, an agent the +image does not contain -- the process **stops before binding its port** and prints one line saying +which. Kubernetes then crash-loops the pod with something an operator can act on, rather than +reporting a healthy replica that is quietly short one consumer. + +### What agent code can see of all this + +Nothing. There is no supported API that exposes the group's name, its membership or its size, and +that is what makes regrouping incapable of breaking agent code: an agent that could read its +neighbours could be written to depend on them. `deployment.group` is set by the framework on +telemetry resources and is not readable through any public API. + +### A group assembled in code + +If you would rather write the composition yourself than use the entry point -- a test, or a process +that wants its own `main.py` -- `AgentGroup` is the class that does it: + +```python +from blueprint.agents import AgentGroup, Config + +from src.order.main import agent as order +from src.billing.main import agent as billing + +config = Config(settings_files=["settings.toml"]) +app = AgentGroup("checkout", {"order": order, "billing": billing}).assemble(config) +``` + +`AgentGroup` is a different class from `AppBuilder` on purpose: an `AppBuilder` never absorbs +another builder and never learns it can be collected, so every refusal a group has to make lives in +the class that imposes it, and the single-agent case is not punished for the group's constraints. + +--- + +## Once it is running + +**Readiness.** `readiness_policy` decides how a degraded agent affects the pod: `all` (the default +-- any degraded agent makes the pod not ready), `critical` (only agents flagged critical in the +group gate it) or `any` (ready while at least one agent is up). Liveness is never agent-dependent: +if one degraded agent failed the pod's liveness probe, Kubernetes would restart every agent in the +group, reintroducing exactly the blast radius grouping was paid to remove. + +**Attribution.** Grouping removes the pod restart that used to serve as the alert, so the alert is +emitted deliberately instead. Every path that stops an agent serving emits an ERROR-level event +carrying that agent's own telemetry identity, and drives `blueprint.namespace.up{agent} = 0`. A +degraded agent's transports are **paused**, not closed -- a closed client is unhealthy for ever, so +the pause would latch and a transient fault would take the agent off its topics permanently. + +**Schedulers.** `scheduler_mode` resolves per agent, so one agent may run an in-process timer beside +a neighbour driven by external ticks. Both modes need something of the agent's own: `in_process` +claims each tick in a cache **that agent declared**, and `event` needs `event_bus`, which is the +group's to set. + +**Dapr.** A group has one Dapr endpoint, which publishes the union of every agent's topics and fans +each delivery out to the agents that declared it; the single acknowledgement is their combination. +So a retry asked for by one agent redelivers to every agent in the group, and grouped Dapr therefore +wants `idempotency_enabled`. NATS has no such coupling -- each agent has its own subscription. + +--- + +## See also + +- [CLI Reference](cli-reference.md) -- `asbs setup`, `asbs dev`, `asbs validate` in full +- [Deployment](deployment.md) -- images, Helm, probes, scaling +- [Caching](../concepts/caching.md) -- named caches, per-agent stores, the management endpoints +- [Observability](../concepts/observability.md) -- what each agent reports, and under which identity diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index e7a8dbbd..65945ddc 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -6264,14 +6264,190 @@ tests pass, zero failures. --- +### Phase 10, step 3 -- the guide, and three defects that writing it found + +`docs/guides/multi-agent-setup.md` is new: how to run several agents in one process, and how to +move an agent you already have into one. It is written to be followed without reading the spec, the +plan or this changelog, and everything it claims about identity was read out of the code rather +than out of the plan -- which is what turned up the defects below. + +**Its shape is the one the plan asked for**, and the split it insists on is the first thing in the +document: an agent **left standalone** and an agent **moved into a group** are affected differently, +and only one of them changes anything. Two tables, side by side, each with the eight identities that +matter -- registry keys, queue group, JetStream durable, routes, OpenAPI tag, telemetry +`service.name`, disk cache directory, Redis key prefix -- one column for the root namespace and one +for an agent named `order`. Every value in them was read from the code that derives it +(`NATSClient._resolve_queue_group`, `_durable_for`, `RestApiBase.route_prefix`, +`qualified_component_name`, `qualified_entry_name`, `CacheBackendFactory.storage_name` and +`TelemetryManager._configure_namespace`), because a migration guide nobody can check is worse than +none. + +The other sections: what `asbs setup` writes and why one image serves every group; the three-file +migration with the before/after `main.py` that removes two things and adds none; **the one decision +to get right first** -- the agent name, what it becomes in six places, and why `-` is excluded from +the alphabet (the durable separator, where `orders-eu`/`created` and `orders`/`eu-created` would +name one consumer); the two configuration files and their different lifetimes, with the five +`BLUEPRINT_*` variables; what regrouping does and does not change, and that agent code can observe +none of it (C6); and a closing section on readiness policy, C7 attribution, per-agent schedulers and +grouped Dapr's shared acknowledgement. + +**The cache is cold after the move**, and the guide says so plainly: the key layout changed twice +during this work, so an application upgrading with a persistent Redis cache or a mounted disk cache +does not find its old entries. Nothing errors. That was an open point asking to be written down +here. + +#### Three defects the writing found + +- **`asbs setup` wrote `secrets.toml` into the working directory, not the project.** + `SecretsPartGenerator(...).create_file()` was called with no argument, and `create_file`'s + `output_path` defaults to `""` -- so the file landed wherever `asbs setup` happened to be run + from, while the command's own next-steps text said one had been created for you. Fixed by passing + `out`, and `secrets.toml.example` is now written beside it: the first is git-ignored and the + second is committed, so a scaffold that writes only the ignored one leaves nothing in the + repository for the next person to fill in. `SecretsPartGenerator` gained an `example=True` + keyword, which is the whole of the difference. +- **`asbs create agent` wrote an effort level that was a model name.** + `openai_reasoning_effort = "gpt-5-mini"` in the generated `[default.runtimes..models]` + section -- a copy of `model_name` one line above. The scaffolder's own settings writer + (`settings_part_generator.py`) has always written `"low"`, so the two disagreed; now they do not. +- **`asbs windsurf` was an advertised command with no implementation.** The subparser was declared + in `cli/main.py`, `run()` had no branch for it, and there are no Windsurf resources to copy -- + `assistant_integrations/` holds one `CLAUDE.md`. So the command printed the top-level help and + exited 1, which is what "Generate Windsurf IDE integration files" in `--help` promised. The + subparser is deleted; git history keeps it if it is ever written. + +#### `docs/guides/cli-reference.md`, read against the code + +Step 2 corrected the four sections step 1 had invalidated. This is the rest of it, and most of it +was fiction before either step: + +- **`asbs setup`** listed `tests/`, `tests/unit/`, `tests/integration/` and `pyproject.toml` in the + generated structure. None of them is written. The real tree is listed instead -- including + `agents.toml`, `secrets.toml.example` and `.gitignore`, none of which appeared -- with a sentence + saying the packaging and test layout are the project's own. The three options + (`--output-dir`, `--overwrite`, `--verbose`) were undocumented. +- **`asbs create agent`** was the worst of it: it described a module `src/agents/_agent.py` + holding a `build__agent(config)` function, showed that function's source, and named the + prompt files and the settings section after the wrong string. The command writes **no module at + all** -- two prompt files, a settings section and a declaration in `main.py` -- and the runtime + name has `_agent` appended, so the files are `document_analyzer_agent_system.prompt` and the + section is `[default.runtimes.document_analyzer_agent]`. Verified by running the command. +- **`asbs create api`** claimed one models file, `src/models/_models.py`. It writes a models + *package*, `src/models//` with `dto.py`, `domain_models.py` and `mapper.py`, and the + generated API imports from `src.models..dto`. +- **`asbs create handler`** documented `--priority` as defaulting to `0`; it is `10`, and the code + sample said `priority=0` as well. +- **`--output-dir`** was undocumented on all four `create` commands. +- **`asbs claude`** documented `create` and `update` subcommands that do not exist. It takes an + optional project directory plus `--overwrite` and `--verbose`, and it *copies* the framework's own + resources -- it generates nothing from the project, and does not update when `asbs create` runs. + +What remains in that file is now either true or an example, and the two claims that were structural +rather than incidental -- that `asbs` generates project-specific Claude context, and that it +scaffolds a test layout -- are gone rather than softened. + +#### Tests + +Two cases in `test_generated_project.py`: the secrets file and its template land in the project, and +the ignore file covers the first without covering the second. 2890 unit tests pass, zero failures. + +--- + +### Phase 10, step 4 -- the deployment guide, rewritten against what now ships + +The plan's instruction was "rewritten here or removed", and the reason was that the guide shipped +while contradicting the feature: it opened with a banner saying **more than one replica is not +safe**, recommended `replicaCount: 1` and `autoscaling.enabled: false`, assumed one Deployment per +agent, documented `CMD uvicorn src.main:app`, and said nothing about schedulers or duplicate +consumption. Every one of those is now either false or superseded. + +**What the rewrite says instead**, and each of them is a thing P0-P5 or a phase actually built: + +- **A Deployment runs a group, not an agent.** One image, `agents.toml` baked in, the group injected + at container start; a group file as a ConfigMap mounted into every Deployment, each picking its + slice with `BLUEPRINT_GROUP`. Splitting an agent out is a second Deployment and an edit to the + file -- nothing is rebuilt and nothing broker-side changes. +- **More than one replica is safe**, and the guide says *why* rather than asserting it: one queue + group so a message reaches one replica; every delivery acked, naked or termed, with the outcome + table; and deduplication for handlers that are not naturally repeatable. The two keys that decide + whether scaling helps are named -- `nats_ack_wait` must exceed p99 handler duration, and + `nats_max_ack_pending` (default 16) is the in-flight limit **across every replica sharing the + consumer**, which is usually why pod count does not buy throughput. +- **The dedup TTL question is answered, not delegated.** Spec sec. 13 left the number to the + deployment; the guide gives the working: the redelivery window is + `nats_ack_wait * nats_max_deliver`, the defaults make that 1500 s, so `idempotency_ttl = 1800` + with headroom, and it rises whenever either factor does. Too short is the case dedup exists to + prevent; too long only costs cache entries. That closes an open point that had been waiting for + this document. +- **Dead letters accumulate and nothing drains them.** Also an open point, also written here: the + default subject is `.dead-letter`, the framework never reads it, and messages age out + with the stream's retention -- so a deployment that never drains it loses them silently. Decide who + reads it before going multi-replica; alert on `blueprint.events.dead_lettered`. +- **Schedulers**, which the old guide listed only as a reason not to scale. Both modes, with what + each needs: `in_process` claims each tick in the agent's own cache, so it needs `.with_cache()` or + every replica runs every tick; `event` starts no timer and takes the tick as an event on + `.scheduler.`, delivered through the queue group to exactly one replica. A worked + `CronJob` is included, with the warning that **nothing here generates it**, that its schedule must + be kept in step with the declared crontab by hand, and that a `CronJob` is at-least-once too. +- **Probes, corrected.** The old guide documented three endpoints including `/health/detailed`, + which has never existed; it also showed `{"status": "ready"}` for a payload that is + `status`/`components`/`policy`/`namespaces`. Both fixed, with the `readiness_policy` table, the + reason liveness is never agent-dependent, and the `failureThreshold` that outlasts the broker's + own startup. +- **Alerting on an agent rather than on the pod.** Grouping removes the pod restart that used to be + the alert, so `blueprint.namespace.up{agent}` is what to alert on -- including the case a probe + cannot see, an agent whose subscriptions have gone while the process stays healthy. +- **Sizing a group.** Memory is the sum of the agents; three failure classes take a whole group down + and raise no catchable exception, so the blast radius rather than the happy path should decide + group size; and the blocked-event-loop detection, with both key names and why the two mechanisms + are never both on. + +**Corrected rather than dropped.** *Writable cache directory* stays -- `cache_backend_factory.py` +and the generated Dockerfile both point at it by name -- but its closing claim was false: grouped +agents were said to be "isolated by key prefix, not by directory", which phase 8b step 5 reversed. +Each agent's cache is now a subdirectory (`/orders.default`), the mount count is still +one, and the section says so. It also gained the cold-cache warning for an upgrade. + +The `envvar_prefix` sections were accurate and are kept whole. What was wrong around them is the +**key shapes**: the old examples used `DYNACONF_APP__PORT`, `DYNACONF_LLM__PROVIDER` and +`DYNACONF_CACHE__TTL`, and only the last of those is nested. `app_port`, `log_level`, `event_bus`, +`nats_url`, `model_provider`, `idempotency_enabled`, `scheduler_mode` and `readiness_policy` are +flat; `cache.*` and `runtimes..*` are the sectioned ones. Getting it wrong is silent -- a +nested `app.port` that nothing reads -- so the rule is stated next to the example. + +**One thing is deliberately still a warning.** Everything above is covered by unit tests against +mocked transports and has not been exercised against a real broker. The guide says so at the top, +in place of the banner it replaces: queue-group distribution, redelivery after `nats_ack_wait`, +durable survival across reconnect and the shutdown drain are specified, implemented and unwatched. + +566 lines became 809. + +--- + ## Open points -- **`docs/guides/cli-reference.md` still documents checks that have never existed.** Four of its - sections were corrected in phase 10 step 2, because step 1 made them wrong; the rest was already - fiction before either -- `asbs validate` checks named there ("All referenced components can be - imported", "No duplicate component names", "secrets.toml is not in .gitignore") have no - implementation, and its output format is invented. It is the last of the audit's fiction - documents and belongs with the guides in step 3. +- **The generated `settings.toml` writes two sections nothing reads.** `[default.logging]` + (`level`, `format`) and `[default.observability]` (`otel_enabled`, `token_metrics_enabled`) are + sectioned, and the framework reads all four as **flat** keys -- `log_level`, `log_format`, + `otel_enabled`, `token_metrics_enabled`. Probed against a real `Config`: a settings file with + `[default.observability] otel_enabled = true` yields `get_observability_config().otel_enabled == + False`, so a developer who turns telemetry on in the file scaffolded for them gets nothing and no + message. `base_files/settings.txt` is where it is written. +- **`asbs create agent` writes `[default.runtimes..models]`; the framework reads + `runtimes..model_settings`.** The generator's own settings writer + (`settings_part_generator.py`) writes `.model_settings` correctly, so the two halves of the + scaffolder disagree and the block `asbs create agent` adds is inert. Found beside the + `openai_reasoning_effort` value fixed in step 3, in the same statement. +- **`asbs` crashes on a Windows console** -- still open from step 1, and now the only thing standing + between the CLI and the ASCII rule. Every command prints check marks and box drawing; on a cp1252 + console the first one raises `UnicodeEncodeError` mid-command, after files have been written. +- ~~**`docs/guides/cli-reference.md` still documents checks that have never existed.**~~ **Done in + phase 10 step 3.** Every command was read against the code: the generated project structure (it + listed a `tests/` tree and a `pyproject.toml` that are not written), `asbs create agent` (an + entire module and builder function that do not exist), `asbs create api`'s models file (it is a + package of three), `--priority`'s default, `--output-dir` on all four `create` commands, and + `asbs claude`'s `create`/`update` subcommands. Writing it found three defects, listed in that + step. - **`asbs` crashes on a Windows console.** Every command prints check marks, warning signs and box-drawing characters (`setup.py`, `create.py`, `validate.py`), and on a console whose encoding is cp1252 -- the Windows default -- the first one raises `UnicodeEncodeError` mid-command, after @@ -6284,11 +6460,10 @@ tests pass, zero failures. `main.py` imports `from .handlers import ...`; `asbs create handler` appends `from src.handlers.order_placed_handler import OrderPlacedHandler`. Both resolve, so nothing fails -- but the two styles in one file are how a later refactor breaks one of them. -- **The migration guide must carry the cache key layout change.** The cache key layout changed - twice (`AgentScopedCache`, then phase 8b step 5's per-agent stores), so an application upgrading - with a persistent Redis cache or a mounted disk cache sees its old entries as absent -- a cold - cache rather than an error. Recorded here again because phase 10 owns the guide and this is the - bullet most easily lost. +- ~~**The migration guide must carry the cache key layout change.**~~ **Done in phase 10 step 3.** + `docs/guides/multi-agent-setup.md` says it under *The cache is cold after the move*, for both + hops, together with the surviving deployment constraint that an agent's disk cache is a + subdirectory of `cache.cache_dir` so a group still needs exactly one writable mount. - **Two spec amendments from phase 9, both because the spec's wording latches.** Spec C4 says a degraded namespace's transport client is *closed*. Implemented as a **pause** -- subscriptions drained, connection kept -- because a closed client reports itself unhealthy for ever, so the diff --git a/docs/plans/2026-08-28-multi-agent-grouping.md b/docs/plans/2026-08-28-multi-agent-grouping.md index 7d131f3a..c90415f2 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping.md +++ b/docs/plans/2026-08-28-multi-agent-grouping.md @@ -2,7 +2,7 @@ | | | |---|---| -| **Status** | P0-P6, phases 0-8, the whole of 8b, phase 9 and **phase 10 steps 1-2** landed on `feature/multi-agent-namespaces`. Next: phase 10 step 3. | +| **Status** | **Complete.** P0-P6, phases 0-10 landed on `feature/multi-agent-namespaces`. No PR opened yet; the changelog is its description. | | **Amendment** | `docs/plans/2026-09-10-builder-unification.md` -- decided 2026-09-10. Phase 8b below is its work breakdown; phases 0 and 3 are superseded by it. Step 9 was added on 2026-09-10 and is not in that proposal's original breakdown. | | **Deferred out** | `docs/plans/2026-09-10-config-validation-unification.md` -- configuration validation is not part of this feature and **must not** be touched during 8b. | | **Spec (normative)** | `docs/specs/2026-08-28-multi-agent-grouping.md` | @@ -1146,9 +1146,10 @@ exist, which is the same failure this phase was put last to avoid. 2. **`asbs validate` reports what a project must state before it can be grouped**, and closes the scheduler gap from P5's open points: a project in `"event"` mode with nothing publishing its tick is the remaining silent-failure case. **Landed.** -3. **`docs/guides/multi-agent-setup.md`** -- the five sections listed above. +3. **`docs/guides/multi-agent-setup.md`** -- the five sections listed above, plus the rest of + `docs/guides/cli-reference.md` read against the code. **Landed.** 4. **`docs/guides/deployment.md`** -- rewritten here, because the setup guide contradicts it - directly. + directly. **Landed.** --- diff --git a/src/blueprint/agent_generator/cli/commands/create.py b/src/blueprint/agent_generator/cli/commands/create.py index 3ec6af2f..e4dbd72f 100644 --- a/src/blueprint/agent_generator/cli/commands/create.py +++ b/src/blueprint/agent_generator/cli/commands/create.py @@ -594,7 +594,9 @@ def create_agent(args: Namespace) -> None: settings_models_section = f"[default.runtimes.{snake_name}.models]" if settings_models_section not in settings_content: settings_content += f"\n{settings_models_section}\n" - settings_content += 'openai_reasoning_effort = "gpt-5-mini"\n' + # An effort level, not a model: the value was a copy of model_name, and the + # scaffolder's own settings writer has always written "low" here. + settings_content += 'openai_reasoning_effort = "low"\n' settings_content += 'openai_reasoning_summary = "detailed"\n' settings_file.write_text(settings_content, encoding="utf-8") diff --git a/src/blueprint/agent_generator/cli/main.py b/src/blueprint/agent_generator/cli/main.py index 021718b8..cfc49187 100644 --- a/src/blueprint/agent_generator/cli/main.py +++ b/src/blueprint/agent_generator/cli/main.py @@ -103,30 +103,6 @@ def main() -> None: help="Enable verbose logging", ) - # Windsurf command - windsurf_parser = subparsers.add_parser( - "windsurf", - help="Generate Windsurf IDE integration files", - description="Create .windsurf/ directory with rules and workflows", - ) - windsurf_parser.add_argument( - "output_dir", - nargs="?", - default=".", - help="Project root directory (default: current directory)", - ) - windsurf_parser.add_argument( - "--overwrite", - action="store_true", - help="Overwrite existing files", - ) - windsurf_parser.add_argument( - "--verbose", - "-v", - action="store_true", - help="Enable verbose logging", - ) - # Validate command validate_parser = subparsers.add_parser( "validate", diff --git a/src/blueprint/agent_generator/generator/generator.py b/src/blueprint/agent_generator/generator/generator.py index f952a0db..f3316391 100644 --- a/src/blueprint/agent_generator/generator/generator.py +++ b/src/blueprint/agent_generator/generator/generator.py @@ -357,8 +357,12 @@ def _create_files_from_templates(self) -> None: # Create settings.toml SettingsPartGenerator(self.config, self.template_dir, "").create_file(out) - # Create secrets.toml with API key placeholder - SecretsPartGenerator(self.config, self.template_dir, "").create_file() + # Create secrets.toml with API key placeholder, and the template it is copied from. + # Both into the project: create_file() with no argument writes relative to the current + # working directory, so `asbs setup` left the secrets file wherever it was run from and + # the project it scaffolded had none. + SecretsPartGenerator(self.config, self.template_dir, "").create_file(out) + SecretsPartGenerator(self.config, self.template_dir, "", example=True).create_file(out) # Create __init__ files with imports InitPartGenerator(self.config, self.template_dir, "src", out).create_file(out) diff --git a/src/blueprint/agent_generator/generator/part_generators/secrets_part_generator.py b/src/blueprint/agent_generator/generator/part_generators/secrets_part_generator.py index be0bd473..8877418a 100644 --- a/src/blueprint/agent_generator/generator/part_generators/secrets_part_generator.py +++ b/src/blueprint/agent_generator/generator/part_generators/secrets_part_generator.py @@ -6,13 +6,22 @@ class SecretsPartGenerator(PartGeneratorBase): - def __init__(self, config: dict[str, Any], template_dir: str | Path, src_path: str) -> None: + """Write ``secrets.toml``, or the ``secrets.toml.example`` it is copied from. + + Two files with the same content and different fates: ``secrets.toml`` is what the project + runs against and is git-ignored, and ``secrets.toml.example`` is what is committed so that + the next person cloning the repository knows which keys to fill in. A scaffold that writes + only the ignored one leaves nothing behind in the repository at all. + """ + + def __init__(self, config: dict[str, Any], template_dir: str | Path, src_path: str, *, example: bool = False) -> None: super().__init__(config, template_dir, src_path) self.template_file_name = None + self._example = example self.template_vars["content"] = self._create_secrets_content() def to_py_file_name(self) -> str: - return "secrets.toml" + return "secrets.toml.example" if self._example else "secrets.toml" def _create_secrets_content(self) -> str: return '[default]\nmodel_api_key = "Your-API-Key"\n' diff --git a/tests/unit/agent_generator/generator/test_generated_project.py b/tests/unit/agent_generator/generator/test_generated_project.py index 56c248be..e44b7a1a 100644 --- a/tests/unit/agent_generator/generator/test_generated_project.py +++ b/tests/unit/agent_generator/generator/test_generated_project.py @@ -160,6 +160,22 @@ def test_the_module_it_names_is_the_one_that_declares_the_agent(self, project: P sys.path[:] = saved_path +class TestWhatTheProjectShips: + """Files the project needs that are not code.""" + + def test_the_secrets_file_and_its_template_land_in_the_project(self, project: Path) -> None: + """create_file() with no argument writes relative to the working directory, so the + secrets file used to be left wherever `asbs setup` was run from.""" + assert (project / "secrets.toml").is_file() + assert (project / "secrets.toml.example").is_file() + + def test_the_secrets_file_is_git_ignored_and_the_template_is_not(self, project: Path) -> None: + ignored = (project / ".gitignore").read_text(encoding="utf-8") + + assert "secrets.toml" in ignored + assert "secrets.toml.example" not in ignored + + class TestTheImage: """The Dockerfile runs the framework's entry point, and bakes no group.""" From 8bf18a6be6c1f9780af0045bdc746cf6fe7d6e25 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:45:00 +0200 Subject: [PATCH 016/133] test(split): settle the unit/integration split so broker tests have somewhere to go (#80) tests/integration/ was not run by CI and sat at 28 failures asserting on examples that had been removed, so nothing added there would have meant anything. The split is now enforced by location, and the example assertions that still mean something moved to tests/unit/examples/. Co-Authored-By: Claude Opus 5 (1M context) --- AGENTS.md | 18 +- CLAUDE.md | 14 +- ...26-08-28-multi-agent-grouping-changelog.md | 7 +- .../2026-09-11-broker-integration-tests.md | 200 ++++++++++++++++++ tests/integration/conftest.py | 25 +++ tests/integration/examples/__init__.py | 4 - .../examples/test_example_startup.py | 1 - tests/integration/examples/test_examples.py | 130 ------------ .../integration/test_blueprint_integration.py | 1 - tests/unit/agents/io/TESTS.md | 2 + .../test_sessions_startup_resilience.py | 11 +- .../scheduling}/test_scheduler_event_mode.py | 20 +- tests/unit/examples/__init__.py | 0 tests/unit/examples/test_example_structure.py | 104 +++++++++ 14 files changed, 381 insertions(+), 156 deletions(-) create mode 100644 docs/plans/2026-09-11-broker-integration-tests.md create mode 100644 tests/integration/conftest.py delete mode 100644 tests/integration/examples/__init__.py delete mode 100644 tests/integration/examples/test_example_startup.py delete mode 100644 tests/integration/examples/test_examples.py delete mode 100644 tests/integration/test_blueprint_integration.py rename tests/{integration => unit/agents/io/api/eventing}/test_sessions_startup_resilience.py (92%) rename tests/{integration => unit/agents/io/api/scheduling}/test_scheduler_event_mode.py (86%) create mode 100644 tests/unit/examples/__init__.py create mode 100644 tests/unit/examples/test_example_structure.py diff --git a/AGENTS.md b/AGENTS.md index 854939b2..9480130b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -215,12 +215,22 @@ cannot be traced back to a commit. ## Testing conventions -- **`tests/unit` needs nothing running.** `tests/integration` may, and anything requiring an - external service is marked `@pytest.mark.integration` (`pytest.ini`, `--strict-markers`). +- **`tests/unit` needs nothing running, and a test that needs something running lives in + `tests/integration`.** The `integration` marker is applied **by location**, from + `tests/integration/conftest.py`, so the directory and the marker cannot drift apart and nobody + has to remember a decorator. What that cannot enforce, and a review must, is the other half: + a test needing nothing is in the wrong directory even though the marker will be attached to it. + *Failure:* the split was enforced three ways at once and agreed with itself in none of them -- + CI selected by directory, three tests carried the marker by hand, and `tests/integration` sat + red and unread for a year (#80). +- **A test that reaches for a service it does not need is not offline, it is lucky.** Its result + then depends on what happens to be listening on the developer's machine. Turn the reach off + explicitly -- `health_check_dapr = false` is there for exactly this -- rather than relying on + the connection being refused. - **Every package under `tests/unit/agents/` has a `TESTS.md`** listing each file, the class under test, and what is covered; the one at the top level covers the files that sit directly in - it. It is updated with the tests, not after them. (`tests/unit/agent_generator/` and - `tests/integration/` have none yet.) + it. It is updated with the tests, not after them. (`tests/unit/agent_generator/`, + `tests/unit/examples/` and `tests/integration/` have none yet.) - **Probe against real objects.** Every real defect this framework's grouping work surfaced was found by testing against a real `Registry`, a real `Config` and a real cache rather than a mock. *Failure:* a mock registry answers every lookup and hides resolution bugs by diff --git a/CLAUDE.md b/CLAUDE.md index fad0de68..32a2c36b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,17 +11,25 @@ each with the failure it prevents -- shared across all AI assistants and every h # Install in editable mode with dev deps uv pip install -e ".[dev]" -# Run all tests (bare pytest not in PATH — always use uv run) +# Run everything CI runs: tests/unit needs nothing running (bare pytest is not in PATH) +uv run pytest tests/unit + +# Everything, including tests/integration, which needs the services it names uv run pytest tests/ -# Skip integration tests (no external services needed) +# Everything that needs no external service. tests/integration is marked by location +# (tests/integration/conftest.py), so this deselects the whole directory rather than the +# three tests that happened to carry the decorator. uv run pytest tests/ -m "not integration" +# Only the tests that need services running +uv run pytest tests/ -m integration + # Run a single test uv run pytest tests/unit/agents/app_builder/test_app_builder.py::TestClass::test_name -v # Run tests with coverage -uv run pytest tests/ --cov=blueprint.agents --cov-report=html +uv run pytest tests/unit --cov=blueprint.agents --cov-report=html # Lint / format / type-check ruff check src/ tests/ diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 65945ddc..be2b3d65 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -6666,7 +6666,12 @@ durable survival across reconnect and the shutdown drain are specified, implemen in `test_agent_registration.py` rather than in the tree, and the examples keep passing instances (`with_rest_api(MonitorApi())`), which `AgentRegistration` refuses -- converting them is part of that later work, not a prerequisite for it. -- **Local NATS and Dapr integration environment.** Everything above is covered by unit tests with +- **Local NATS and Dapr integration environment.** **Now tracked in its own document:** + `docs/plans/2026-09-11-broker-integration-tests.md` holds the plan, the running record and + the chores, and its step 0 settled #80 -- `tests/integration/` was not run by CI and sat at + 29 failures, so nothing added there would have meant anything. The original text follows, + because it is the list of what only a real broker can settle. + Everything above is covered by unit tests with mocked transports. Once the feature is implemented, stand both brokers up locally (compose file plus a CI job) and cover the behaviour that only a real broker exhibits: queue-group distribution across replicas, ack/nak/term and redelivery after `ack_wait`, JetStream durable survival across diff --git a/docs/plans/2026-09-11-broker-integration-tests.md b/docs/plans/2026-09-11-broker-integration-tests.md new file mode 100644 index 00000000..7b91cc73 --- /dev/null +++ b/docs/plans/2026-09-11-broker-integration-tests.md @@ -0,0 +1,200 @@ +# Broker integration tests + +| | | +|---|---| +| **Status** | Step 0 landed. Steps 1-3 next. | +| **Why** | Everything the multi-agent work claims about delivery is unit-tested against **mocked transports**. Nobody has watched any of it happen against a real broker. | +| **Scope** | NATS. Dapr needs a sidecar rather than a broker and is a chore below. | +| **Depends on** | #80, the unit/integration split -- settled in step 0, because `tests/integration/` was not run by CI and sat at 29 failures. | +| **Related** | `docs/plans/2026-08-28-multi-agent-grouping-changelog.md`, whose *Open points* names what only a real broker can settle. | + +This document is both the plan and its running record, the way the grouping plan and its changelog +are. It is **not** a phase of that plan: the grouping feature is complete and pushed. This is the +list of things that feature asserts and nobody has yet verified. + +## The constraint that shapes how this is written + +There is no Docker on the machine this is authored on. The tests are written here and **run by the +developer**, who pastes failures back. That makes every step smaller than it would otherwise be and +makes the harness's first job to fail loudly and readably when the broker is absent. + +The second constraint follows from it: **a broker test must skip, not fail, when the broker is not +there.** An offline run of the whole suite stays green, and `-m integration` is how you ask for the +tests that need something running. + +## Plan + +- **Step 0 -- the unit/integration split (#80).** Landed. See below. +- **Step 1 -- the harness.** A `docker-compose.yml` standing up NATS with JetStream, and the + fixtures: a connection that skips the test when the server is unreachable, a stream created and + torn down per test, and an application built against the real URL. +- **Step 2 -- the path, end to end.** A real `AppBuilder` application on real NATS: publish a + CloudEvent, the handler runs, its `HandlerResult` is published to the outbound subject, and the + inbound message is acknowledged exactly once. This is the test the whole exercise is for. +- **Step 3 -- the acknowledgement lifecycle.** Against the real broker, not a mock of it: a + retryable failure naks and is redelivered after `nats_ack_wait`; a `CriticalHandlerError` terms + and is dead-lettered without redelivery; an event no handler matches is **acked**, not naked; a + payload that fails CloudEvent parsing terms without dispatching; and `nats_max_deliver` + exhaustion dead-letters. + +## Chores + +Recorded rather than built, so they are not rediscovered. Each is something only a real broker or a +real cluster can answer. + +### Broker behaviour still unwatched + +- **Queue-group distribution across replicas.** Two application instances sharing one queue group: + one delivery per message, not two. This is the claim that makes `replicaCount > 1` safe, and it + is the one P1 rests on. +- **A durable surviving reconnect.** Kill the connection mid-stream and assert nothing is + redelivered that was already acked, and everything unacked is. +- **The shutdown drain.** In-flight handlers finish and their acknowledgements arrive *before* the + connection closes -- the ordering P0 fixed, and the one that makes duplicates certain on every + deploy when it is wrong. +- **Overlapping subjects in one queue group.** A wildcard and a literal it covers, both subscribed + by one agent, one message matching both. `nats-server` is expected to merge the subscriptions and + deliver once; if it does not, the agent sees the event twice and P2 acks both copies as ordinary + work, which changes what P2 has to handle. +- **`filter_subjects` on a durable that already exists**, and what the server does with an + `add_consumer` whose configuration differs from the durable already there. +- **Whether `msg.metadata.num_delivered` lines up with `max_deliver`** the way the dead-letter + trigger assumes. + +### Grouping, against a real broker + +- **C1 by observation.** Two agents in one `AgentGroup` on one NATS: each sees only its own topics, + and the durable and queue-group names are byte-identical to the same agent deployed alone. The + unit tests assert the names; this would assert the consequence. +- **The scheduler tick claim across real processes.** Three replicas in separate processes sharing + one `DiskCacheService` directory -- whether `diskcache-rs` file locking actually makes `add` + atomic across processes -- and Redis `SET NX` under real contention. +- **A `CronJob` tick delivered to exactly one replica** through the queue group, and what a + `CronJob` restart or a missed `startingDeadlineSeconds` actually produces. + +### Infrastructure + +- **A CI job.** NATS as a GitHub Actions service container, running `-m integration`. Until it + exists these tests are local-only, which is a smaller version of the problem #80 describes. +- **Dapr.** Needs the sidecar, not just a broker: the discovery document actually fetched, and + deliveries arriving at `/events/{topic}`. Roughly doubles the harness, and is why it is not in + the plan above. +- **Redis under contention**, for the dedup `exists`-then-`set` window and the tick claim. + +### Found on the way, not fixed + +- **`examples/webhook_relay` cannot start against a real NATS.** It sets `event_bus = "nats"` and + `app_name = "Webhook Relay"`; `app_name` is the root namespace's queue group since P1, and + `validate_subject_segment` rejects whitespace -- so `_resolve_queue_group` raises at subscribe + time. Confirmed by calling the validator directly. Four other examples carry a spaced `app_name` + and are latent rather than broken, because they use Dapr or no bus at all. The examples are + deliberately untouched by this work; this is exactly the kind of thing step 2's harness would + catch if it were pointed at them. + +--- + +## Changelog + +### Step 0 -- the unit/integration split, settled (#80) + +**The prerequisite, and the reason it is one.** `tests/integration/` was **not run by CI at all** +(`ci.yml` and `publish.yml` both run `tests/unit`), so a broker test added there would have been +invisible; and the directory sat at **29 failures**, so a new red line in it would have meant +nothing. Neither is a thing to build on. + +The split was enforced three ways at once and agreed with itself in none of them: CI selected by +**directory**, the `integration` marker was applied **by hand** to three tests out of roughly sixty, +and everything else in `tests/integration/` was unmarked -- so `pytest -m "not integration"` +deselected three tests and then failed 28. Two tests in there carried comments explaining that they +were deliberately *not* marked because they were offline, which is a contributor documenting the +confusion in place rather than fixing the category. + +**One rule now: a test in `tests/integration/` requires an external service.** New +`tests/integration/conftest.py` applies the marker by location: + +```python +def pytest_collection_modifyitems(items: list[pytest.Item]) -> None: + for item in items: + if INTEGRATION_ROOT in Path(str(item.fspath)).parents: + item.add_marker(pytest.mark.integration) +``` + +Directory and marker can no longer drift apart, and nobody has to remember a decorator. The half +that cannot be enforced -- that a test needing nothing does not belong there -- is stated in the +module docstring and in `AGENTS.md`, and the two tests that were in the wrong place were **moved +out rather than marked**. + +#### What moved, and what was deleted + +`tests/integration/examples/test_examples.py` asserted on seven example projects, **four of which +were deleted from `examples/` over a year ago**. It imports only `pytest`, `pathlib` and `tomllib`: +it never starts a process or opens a socket, so it is a repository-consistency check that had been +filed as an integration test and therefore never run. Rewritten as +`tests/unit/examples/test_example_structure.py`, where CI runs it. + +**The list is derived from the directory now, never hardcoded** -- that is the whole lesson of #80. +The two directories that are not projects are listed with the reason, in the `KNOWN_GAPS` style this +repository already uses, and a case asserts each listed one is *still* not a project so the +allowlist cannot outlive its entries: + +- `shared_cache_demo` -- standalone demo scripts plus a README, illustrating the cache API. No + declaration and no settings, because it is not an application. +- `customer_support_qa` -- a skeleton left by an earlier refactor: `src/api`, `src/handlers`, + `src/models` and `src/services`, but no `main.py`, no `settings.toml` and no `README.md`. + +Per project it checks what a reader needs before they can run it: a `main.py` (at the root or under +`src/`, both shapes are in use), a `settings.toml` that parses and names the application, and a +`README.md`. The five real projects pass. + +Two 1-line files were deleted rather than carried: `tests/integration/test_blueprint_integration.py` +and `tests/integration/examples/test_example_startup.py`, both reading +`# Tests removed -- to be recreated after architecture refactor`. The refactor happened. + +Two genuinely offline tests moved into `tests/unit/`, where their own comments said they belonged: + +- `test_sessions_startup_resilience.py` -> `tests/unit/agents/io/api/eventing/`. It binds and + releases a loopback port to guarantee ECONNREFUSED, which is offline by construction. +- `test_scheduler_event_mode.py` -> `tests/unit/agents/io/api/scheduling/`. + +`test_shared_redis_cache.py` stays: it genuinely needs Redis, and skips cleanly without it. + +#### The 29th failure was a phase 9 regression nobody had recorded + +The changelog carried "the 28 pre-existing failures in `tests/integration/examples/`". There were +**29**, and the extra one was not in `examples/`: +`test_scheduler_event_mode.py::test_event_mode_tick_arrives_as_an_event` answered `RETRY` where it +asserted `SUCCESS`. + +The chain: the test builds a Dapr application; the Dapr client's health check probes +`localhost:3500` for a sidecar that is not there; the check fails; phase 9's namespace supervisor +degrades the root agent and **pauses its transports** (C4); and the paused fan-out declines the +tick. Every link is working as designed -- and the test's own docstring, "nothing here reaches the +network", had quietly become false when phase 9 gave that health check a consequence. + +Worse than failing: it was **environment-dependent**. The result turned on whether anything happened +to be listening on port 3500, so it would have passed for a developer with a sidecar running. + +Fixed in the test, with the framework's own switch rather than a patch: + +```toml +health_check_dapr = false +``` + +The delivery path needs no sidecar; only the health check reaches for one. Turning that probe off +is what makes the test offline again, and deterministic. A new rule in `AGENTS.md` states the +general form: *a test that reaches for a service it does not need is not offline, it is lucky.* + +#### Result + +| | Before | After | +|---|---|---| +| `pytest tests/ -m "not integration"` | 28 failed, 990 passed | **passes**, 2924 collected | +| `pytest tests/` | 29 failed | **passes** (3 Redis tests skip) | +| `tests/integration/` contents | 6 files, 2 of them 1-line stubs, 1 asserting on deleted examples | 1 file, which needs Redis | + +`CLAUDE.md`'s test commands were corrected -- it documented +`uv run pytest tests/ -m "not integration"` as "skip integration tests", which was not what that +command did -- and `AGENTS.md` gained the two rules above. + +**Not done here, deliberately:** no CI job runs `-m integration`. That belongs with the harness +that gives it something to run, and is listed under *Chores* below. diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py new file mode 100644 index 00000000..b5d0a1ff --- /dev/null +++ b/tests/integration/conftest.py @@ -0,0 +1,25 @@ +"""Everything in this directory needs something running, and is marked so automatically. + +The split used to be enforced three ways at once and agreed with itself in none of them (#80): +CI selected by *directory* (`tests/unit`), the `integration` marker was applied by *hand* to three +tests out of roughly sixty, and the rest of this directory was unmarked -- so `-m "not integration"` +deselected almost nothing, and `tests/integration/` was simultaneously red and invisible. + +One rule now: **a test here requires an external service.** The marker is applied by location, so +the directory and the marker cannot drift apart and no contributor has to remember the decorator. +The other half of the rule is what this file cannot enforce and a review must -- a test that needs +nothing running does not belong here. Two that did were moved out rather than marked. +""" + +from pathlib import Path + +import pytest + +INTEGRATION_ROOT = Path(__file__).parent + + +def pytest_collection_modifyitems(items: list[pytest.Item]) -> None: + """Mark every test collected from this directory as ``integration``.""" + for item in items: + if INTEGRATION_ROOT in Path(str(item.fspath)).parents: + item.add_marker(pytest.mark.integration) diff --git a/tests/integration/examples/__init__.py b/tests/integration/examples/__init__.py deleted file mode 100644 index 03abc746..00000000 --- a/tests/integration/examples/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -"""Integration tests for all examples. - -These tests verify that each example has the correct structure and configuration. -""" diff --git a/tests/integration/examples/test_example_startup.py b/tests/integration/examples/test_example_startup.py deleted file mode 100644 index 1c4c356e..00000000 --- a/tests/integration/examples/test_example_startup.py +++ /dev/null @@ -1 +0,0 @@ -# Tests removed — to be recreated after architecture refactor diff --git a/tests/integration/examples/test_examples.py b/tests/integration/examples/test_examples.py deleted file mode 100644 index 8cc08b14..00000000 --- a/tests/integration/examples/test_examples.py +++ /dev/null @@ -1,130 +0,0 @@ -"""Integration tests for all examples. - -These tests verify that each example: -1. Has the required file structure -2. Has valid configuration files -3. Can be imported and instantiated -""" - -import pytest -from pathlib import Path -import tomllib - -EXAMPLES_DIR = Path(__file__).parent.parent.parent.parent / "examples" - -# List of all examples to test -EXAMPLES = [ - "rest_microservice", - "simple_event_processor", - "complex_agent", - "customer_support_qa", - "scheduler_example", - "trivia_game", - "sessions_job_processor", -] - - -@pytest.mark.parametrize("example_name", EXAMPLES) -def test_example_has_main_file(example_name): - """Test that each example has a main.py file.""" - example_path = EXAMPLES_DIR / example_name - - # Check for main.py in either root or src/ - has_main = (example_path / "main.py").exists() or (example_path / "src" / "main.py").exists() - - assert has_main, f"Example {example_name} missing main.py" - - -@pytest.mark.parametrize("example_name", EXAMPLES) -def test_example_has_settings(example_name): - """Test that each example has a settings.toml file.""" - example_path = EXAMPLES_DIR / example_name - settings_file = example_path / "settings.toml" - - assert settings_file.exists(), f"Example {example_name} missing settings.toml" - - -@pytest.mark.parametrize("example_name", EXAMPLES) -def test_example_settings_valid(example_name): - """Test that each example's settings.toml is valid TOML.""" - example_path = EXAMPLES_DIR / example_name - settings_file = example_path / "settings.toml" - - if settings_file.exists(): - with open(settings_file, "rb") as f: - settings = tomllib.load(f) - assert isinstance(settings, dict), f"Example {example_name} settings.toml is not valid" - # Check for app_name in root or default section - has_app_name = "app_name" in settings or ("default" in settings and "app_name" in settings["default"]) - assert has_app_name, f"Example {example_name} missing app_name in settings" - - -@pytest.mark.parametrize("example_name", EXAMPLES) -def test_example_has_readme(example_name): - """Test that each example has a README.md file.""" - example_path = EXAMPLES_DIR / example_name - readme_file = example_path / "README.md" - - assert readme_file.exists(), f"Example {example_name} missing README.md" - - -# Specific tests for examples with REST APIs -REST_API_EXAMPLES = ["rest_microservice", "scheduler_example"] - - -@pytest.mark.parametrize("example_name", REST_API_EXAMPLES) -def test_rest_api_example_structure(example_name): - """Test that REST API examples have the required structure.""" - example_path = EXAMPLES_DIR / example_name - - assert (example_path / "src" / "api").exists(), f"Example {example_name} missing src/api directory" - assert (example_path / "src" / "services").exists(), f"Example {example_name} missing src/services directory" - - -# Specific tests for event handler examples -EVENT_HANDLER_EXAMPLES = [ - "simple_event_processor", - "complex_agent", - "customer_support_qa", - "sessions_job_processor", -] - - -@pytest.mark.parametrize("example_name", EVENT_HANDLER_EXAMPLES) -def test_event_handler_example_structure(example_name): - """Test that event handler examples have the required structure.""" - example_path = EXAMPLES_DIR / example_name - - # Check for handlers directory in either root or src/ - has_handlers = (example_path / "handlers").exists() or (example_path / "src" / "handlers").exists() - - assert has_handlers, f"Example {example_name} missing handlers directory" - - -def test_sessions_job_processor_specific(): - """Test sessions_job_processor specific requirements.""" - example_path = EXAMPLES_DIR / "sessions_job_processor" - - # Check for handlers - assert (example_path / "handlers").exists() - assert (example_path / "handlers" / "text_extraction_handler.py").exists() - - # Check settings has sessions_service config - with open(example_path / "settings.toml", "rb") as f: - settings = tomllib.load(f) - assert "sessions_service" in settings, "sessions_job_processor missing sessions_service config" - - -def test_scheduler_example_specific(): - """Test scheduler_example specific requirements.""" - example_path = EXAMPLES_DIR / "scheduler_example" - - # Check for schedulers directory - assert (example_path / "src" / "schedulers").exists() - - # Check that scheduler files exist (at least one) - schedulers_dir = example_path / "src" / "schedulers" - scheduler_files = list(schedulers_dir.glob("*.py")) - # Filter out __init__.py - scheduler_files = [f for f in scheduler_files if f.name != "__init__.py"] - assert len(scheduler_files) > 0, "No scheduler files found" diff --git a/tests/integration/test_blueprint_integration.py b/tests/integration/test_blueprint_integration.py deleted file mode 100644 index 1c4c356e..00000000 --- a/tests/integration/test_blueprint_integration.py +++ /dev/null @@ -1 +0,0 @@ -# Tests removed — to be recreated after architecture refactor diff --git a/tests/unit/agents/io/TESTS.md b/tests/unit/agents/io/TESTS.md index 1f3a7719..e135f528 100644 --- a/tests/unit/agents/io/TESTS.md +++ b/tests/unit/agents/io/TESTS.md @@ -17,7 +17,9 @@ Test coverage for `src/blueprint/agents/io/`. | `api/eventing/test_dapr.py` | `DaprEventing` | `publish` PROCESSED→SUCCESS, no-handler→RETRY, `RetryableHandlerError`→RETRY, `InvalidEventError`→DROP, `CriticalHandlerError`→RETRY; `subscribe` returns empty dict | | `api/eventing/test_nats.py` | `NatsEventing` | `subscribe`/`publish` delegate to `_client`, RuntimeError when client is None; `on_startup` fetches client, subscribes to handler-declared and config-declared topics, deduplicates, preserves handler-first order, skips when no topics; `_subscribe_to_topic` RuntimeError when client None, calls `_client.subscribe` with topic and callback | | `api/eventing/test_sessions_bus.py` | `SessionsBus` | `on_startup` validation (no config/base_url/agent_id/api_key, already started, task created); `on_shutdown` (no task, running task cancelled); `_convert_to_cloud_event` (type/id/subject/source/data); `_process_job_notification` (no handler logged, `InvalidEventError`→cancel job, cancel failure swallowed, `RetryableHandlerError`→log, 403→invalidate+retry, 403 retry failure propagates `InvalidEventError`, non-403 propagates) | +| `api/eventing/test_sessions_startup_resilience.py` | `AppBuilder.build()` with `event_bus = "sessions"` | The lifespan completes and the root REST endpoints answer when the sessions service URL points at a closed port -- a background SSE consumer that cannot connect must not stop the application starting. Offline: the refused port is bound and released on loopback, so the failure is ECONNREFUSED rather than a timeout on every platform. Moved here from `tests/integration/` (#80), where nothing ran it | `api/scheduling/test_scheduler.py` | `SchedulerBase`, `SchedulerTickHandler` | `_trigger_tick` calls `tick()` and returns `{"status": "triggered"}`; `scheduler_mode` reads both values case-insensitively, has no default so an absent, empty or missing key raises with both values named, rejects an unrecognised value and resolves once; `tick_topic` derives from `app_name` and the (possibly renamed) scheduler name, honours the `topic=` override, rejects a missing identity and a wildcard, rejects whitespace in an explicit topic and rewrites it in a derived one; `wire()` creates the tick handler in event mode only, is idempotent, registers the trigger route once in both modes, refuses event mode without a topic-carrying `event_bus` and accepts both broker transports; `on_startup` starts no timer in event mode, creates and starts `AsyncIOScheduler` on the declared crontab in in-process mode, and starts no second timer or route when called twice (#43); `on_shutdown` calls `shutdown(wait=True)` only when running and allows a later restart; the in-process tick claim -- the winner ticks and a loser does not, the key carries the scheduler and the minute, the claim carries the tick TTL and its own namespace, three replicas sharing a real `DiskCacheService` run one tick between them, a later slot is claimable again, no cache means every replica ticks and startup warns, the timer is wired to the claimed wrapper rather than to `tick`, and event mode claims nothing; `validate_crontab` accepting the five standard fields, stripping whitespace and rejecting empty, nonsense and six-field (apscheduler) expressions, with event-mode wiring failing on a bad crontab and in-process wiring not reaching the check; the tick handler declares its topic, outranks the default handler priority, claims a delivery under `nats_topic`/`dapr_topic`/`topic`, declines other or absent topics, ticks its scheduler without publishing an event, lets a failing tick reach the transport edge, and two schedulers register under distinct names in a real `Registry` | +| `api/scheduling/test_scheduler_event_mode.py` | `SchedulerBase` through `AppBuilder.build()` | What only a built application can show: the tick topic reaches the Dapr subscription document and a CloudEvent posted to `/events/` runs `tick()` exactly once; event mode starts no in-process timer; `POST /api//trigger` is actually served (it used to be added to the router after `include_router` had copied it); in-process mode declares no tick topic and registers no eventing endpoint; a registered scheduler with no `scheduler_mode`, and event mode with no `event_bus`, each fail the build naming both values; and the pure-scheduler shapes -- publishing opted into, and nothing at all by default. Offline, and deterministic because `health_check_dapr = false` stops the Dapr health check probing for a sidecar: without it the namespace supervisor degrades the root agent and its paused transports refuse the tick. Moved here from `tests/integration/` (#80) | `api/utilities/test_cache.py` | `CacheManagementApi` | Which cache each endpoint reaches (`?name=` selecting a named cache, the default when none is given, evict clearing only the one it names) and how it fails (503 with no cache registered at all, 404 for an unknown name, the 404 listing the registered names); and the statistics payload **against real backends** -- a real `DiskCacheService` reporting its four fields, a real `RedisCacheService` over `fakeredis` reporting a different seven, and a backend whose own stats call fails answering an empty payload rather than a 500 | | `api/utilities/test_root.py` | `RootApi` | Service name/version/description from config (and defaults when `None`); both/one/neither doc links rendered; non-`APIRoute` routes skipped; `GET` route → direct link; non-`GET` route with `docs_url` → Swagger anchor link, without `docs_url` → plain path; route summary and sorted methods in row; cache hit skips config on second call | | `telemetry/test_telemetry.py` | `TelemetryManager`, `TracingContext` | `configure_tracing` raises when config None, no-op when disabled, creates TracerProvider when enabled; `_build_exporters` OTLP/empty; `TracingContext` span lifecycle + attribute filtering | diff --git a/tests/integration/test_sessions_startup_resilience.py b/tests/unit/agents/io/api/eventing/test_sessions_startup_resilience.py similarity index 92% rename from tests/integration/test_sessions_startup_resilience.py rename to tests/unit/agents/io/api/eventing/test_sessions_startup_resilience.py index 736495af..8580beb0 100644 --- a/tests/integration/test_sessions_startup_resilience.py +++ b/tests/unit/agents/io/api/eventing/test_sessions_startup_resilience.py @@ -1,6 +1,9 @@ -"""Integration test: AppBuilder.build() with event_bus='sessions' yields a -FastAPI app whose lifespan completes even when the sessions service URL is -unreachable. Standard REST endpoints (the framework root API) must respond. +"""AppBuilder.build() with event_bus='sessions' yields a FastAPI app whose lifespan +completes even when the sessions service URL is unreachable. Standard REST endpoints +(the framework root API) must respond. + +Offline -- it targets a closed loopback port deliberately -- which is why it lives here +rather than under tests/integration (#80). """ import logging @@ -59,8 +62,6 @@ def _reset_component_state(): Component.reset_shared_state() -# Not marked @pytest.mark.integration — this test is fully offline (it deliberately -# targets a closed local port) and must run in the offline CI matrix. def test_app_starts_when_sessions_service_unreachable(tmp_path, monkeypatch, caplog): """With sessions URL pointed at a closed port, build() returns and TestClient can hit the root endpoint.""" diff --git a/tests/integration/test_scheduler_event_mode.py b/tests/unit/agents/io/api/scheduling/test_scheduler_event_mode.py similarity index 86% rename from tests/integration/test_scheduler_event_mode.py rename to tests/unit/agents/io/api/scheduling/test_scheduler_event_mode.py index dda0c6b3..7c49b52f 100644 --- a/tests/integration/test_scheduler_event_mode.py +++ b/tests/unit/agents/io/api/scheduling/test_scheduler_event_mode.py @@ -1,9 +1,10 @@ -"""Integration test: an event-mode scheduler is ticked through the ordinary event path. +"""An event-mode scheduler is ticked through the ordinary event path. -Offline by design. Under Dapr the application holds no broker connection -- the sidecar -pushes to ``POST /events/{topic}`` -- so the whole of ``scheduler_mode = "event"`` can be -exercised with nothing listening anywhere: build the app, post a CloudEvent to the -scheduler's tick topic, and the scheduler's ``tick()`` runs. +Offline, which is why it lives here rather than under tests/integration (#80). Under Dapr the +application holds no broker connection -- the sidecar pushes to ``POST /events/{topic}`` -- so +the whole of ``scheduler_mode = "event"`` can be exercised with nothing listening anywhere: +build the app, post a CloudEvent to the scheduler's tick topic, and the scheduler's ``tick()`` +runs. The one thing that did reach for the network was the Dapr health check; see ``_config``. Two claims that unit tests cannot make are pinned here, because both are about what ``build()`` hands to FastAPI: @@ -52,14 +53,19 @@ def _config(tmp_path, mode: str) -> Config: 'app_name = "cron-test"', 'event_bus = "dapr"', f'scheduler_mode = "{mode}"', + # Without this the Dapr health check probes localhost:3500 for a sidecar that is + # not there, the namespace supervisor degrades the root agent for the failing + # check, and its paused transports refuse the tick with RETRY (phase 9, C4). The + # delivery path below needs no sidecar; only the health check reaches for one, so + # turning that probe off is what makes this test offline -- and deterministic. + # Left on, its result depends on whether anything happens to be listening on 3500. + "health_check_dapr = false", ] ) ) return Config(settings_files=[str(settings)]) -# Not marked @pytest.mark.integration -- nothing here reaches the network, so these must run -# in the offline CI matrix alongside test_sessions_startup_resilience.py. def test_event_mode_tick_arrives_as_an_event(tmp_path): scheduler = NightlyScheduler() app = AppBuilder(_config(tmp_path, "event")).with_scheduler(scheduler).build() diff --git a/tests/unit/examples/__init__.py b/tests/unit/examples/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/unit/examples/test_example_structure.py b/tests/unit/examples/test_example_structure.py new file mode 100644 index 00000000..f10cb485 --- /dev/null +++ b/tests/unit/examples/test_example_structure.py @@ -0,0 +1,104 @@ +"""Every example under ``examples/`` is a project somebody can actually run. + +These are repository-consistency checks, not integration tests: nothing here imports the +framework, starts a process or opens a socket. They lived under ``tests/integration/`` and were +therefore never run by CI, which is how they came to assert on four examples that had been deleted +and stayed red for a year (#80). They live here so that CI runs them. + +**The list is derived from the directory, never hardcoded.** That is the whole lesson of #80: a +hardcoded list goes stale silently, and the failure surfaces years later as a wall of red about +projects nobody remembers. Derived, a reorganisation of ``examples/`` fails here, immediately, with +a message naming what moved. +""" + +import tomllib +from pathlib import Path + +import pytest + +EXAMPLES_DIR = Path(__file__).resolve().parents[3] / "examples" + +NOT_PROJECTS: dict[str, str] = { + "shared_cache_demo": ( + "Standalone demo scripts (demo.py, demo_multiprocess.py, demo_redis.py, walkthrough.py) " + "plus a README, illustrating the cache API. It has no declaration and no settings because " + "it is not an application." + ), + "customer_support_qa": ( + "A skeleton left behind by an earlier refactor: it has src/api, src/handlers, src/models " + "and src/services but no main.py, no settings.toml and no README.md, so there is nothing " + "to run. Finishing or removing it is a decision about the examples, which are deliberately " + "untouched by the multi-agent work." + ), +} +"""Directories under ``examples/`` that are not Blueprint projects, each with why. + +Listed rather than silently skipped, and held to being genuinely not-a-project by +:func:`test_no_listed_directory_has_quietly_become_a_project` -- an allowlist that outlives its +entries is how a guard stops guarding. +""" + + +def example_directories() -> list[Path]: + """Every directory under ``examples/``, derived rather than declared.""" + return sorted(path for path in EXAMPLES_DIR.iterdir() if path.is_dir() and not path.name.startswith((".", "__"))) + + +def project_examples() -> list[Path]: + """The example directories that are meant to be runnable projects.""" + return [path for path in example_directories() if path.name not in NOT_PROJECTS] + + +def example_id(path: Path) -> str: + return path.name + + +class TestTheListIsDerived: + """The check #80 asks for: a reorganisation of ``examples/`` fails here, not years later.""" + + def test_there_are_examples_to_check(self) -> None: + assert example_directories(), f"No example directories under {EXAMPLES_DIR}. Either examples/ moved, or this test did." + + def test_every_directory_is_a_project_or_is_listed(self) -> None: + """A new directory is checked as a project unless somebody says why it is not.""" + assert [path.name for path in example_directories() if path.name in NOT_PROJECTS] == sorted(NOT_PROJECTS) + + @pytest.mark.parametrize("name", sorted(NOT_PROJECTS)) + def test_no_listed_directory_has_quietly_become_a_project(self, name: str) -> None: + directory = EXAMPLES_DIR / name + + if not directory.is_dir(): + pytest.fail(f"examples/{name} no longer exists, so remove it from NOT_PROJECTS. It was listed because: {NOT_PROJECTS[name]}") + + assert not (directory / "settings.toml").is_file(), ( + f"examples/{name} now has a settings.toml, so it is a project and should be checked as one. " + f"Remove it from NOT_PROJECTS. It was listed because: {NOT_PROJECTS[name]}" + ) + + +class TestEveryProjectIsRunnable: + """What a reader needs to find in an example before they can run it.""" + + @pytest.mark.parametrize("example", project_examples(), ids=example_id) + def test_it_has_a_declaration(self, example: Path) -> None: + """``main.py``, at the root or under ``src/`` -- both shapes are in use.""" + assert (example / "main.py").is_file() or (example / "src" / "main.py").is_file(), f"examples/{example.name} has no main.py" + + @pytest.mark.parametrize("example", project_examples(), ids=example_id) + def test_it_has_settings(self, example: Path) -> None: + assert (example / "settings.toml").is_file(), f"examples/{example.name} has no settings.toml" + + @pytest.mark.parametrize("example", project_examples(), ids=example_id) + def test_its_settings_parse_and_name_the_application(self, example: Path) -> None: + settings_file = example / "settings.toml" + settings = tomllib.loads(settings_file.read_text(encoding="utf-8")) + + declared = "app_name" in settings or any(isinstance(value, dict) and "app_name" in value for value in settings.values()) + assert declared, ( + f"examples/{example.name} declares no app_name. It is the fallback identity for a root-namespace " + "application -- the NATS queue group among other things -- so an example without one is not runnable." + ) + + @pytest.mark.parametrize("example", project_examples(), ids=example_id) + def test_it_has_a_readme(self, example: Path) -> None: + assert (example / "README.md").is_file(), f"examples/{example.name} has no README.md" From 81fee2b5ee864bd3d9cd9e5f5fb9d4f442bc58aa Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:45:02 +0200 Subject: [PATCH 017/133] feat(grouping): close the isolation routes and make a scaffolded project start An agent can no longer read a neighbour's data by any route the framework offers, and asbs setup produces a project that starts, tests and validates. Isolation 1: the registry's bare-name fallback checks ownership, so it reaches the root and the asking agent and never a neighbour's key. Isolation 2: _effective_namespace and _cache_owner refuse a view that names another agent. Isolation 3: AgentGroup refuses a declaration shared by several agents that carries mutable state; a zero-argument factory is the way out. Isolation 4: a scoped get() resolves a dotted key only under the framework's own prefixes, an allowlist that fails closed. AgentRuntime is constructed with its name and registered under the qualified key like every other component, so two agents may share a runtime name. nats_publish_mode splits publishing from durable consumption, publishable subjects are declared, and a wildcard publish subject is refused at startup. env_status on a scoped actuator reports its own scope, not the tree. token_metrics_enabled reaches ObservabilityConfig; it was read by nothing. Generator: the scaffolded settings file writes the flat keys the framework reads, .secrets.toml is the name DEFAULT_SETTINGS_FILES loads, a pyproject.toml and two tests are generated so setup -> pytest -> validate closes, use_utf8 at the CLI entry point, and asbs create writes relative imports. Five example app_name values the broker refuses are renamed. Co-Authored-By: Claude Opus 5 (1M context) --- docs/README.md | 4 +- docs/components/agents.md | 4 +- docs/components/event-handlers.md | 4 +- docs/concepts/architecture.md | 4 +- docs/concepts/caching.md | 2 +- docs/concepts/configuration.md | 4 +- docs/getting-started.md | 10 +- docs/guides/cli-reference.md | 6 +- docs/guides/deployment.md | 4 +- docs/guides/multi-agent-setup.md | 4 +- docs/guides/troubleshooting.md | 6 +- ...26-08-28-multi-agent-grouping-changelog.md | 647 +++++++++++++++++- .../2026-09-11-broker-integration-tests.md | 281 +++++++- examples/document_summarizer/settings.toml | 2 +- examples/health_monitor/settings.toml | 2 +- examples/inventory_api/settings.toml | 2 +- examples/order_event_pipeline/settings.toml | 2 +- examples/webhook_relay/settings.toml | 2 +- pytest.ini | 2 +- .../assistant_integrations/CLAUDE.md | 2 +- .../agent_generator/base_files/Dockerfile | 17 +- .../agent_generator/base_files/settings.txt | 18 +- .../base_files/template_for_git_ignore.txt | 4 +- .../agent_generator/claude_docs/CLAUDE.md | 8 +- .../claude_docs/agents/blueprint-builder.md | 2 +- .../claude_docs/skills/add-component/SKILL.md | 2 +- .../skills/new-agent-service/SKILL.md | 4 +- .../agent_generator/cli/commands/create.py | 44 +- .../agent_generator/cli/commands/setup.py | 44 +- .../agent_generator/cli/commands/validate.py | 21 +- src/blueprint/agent_generator/cli/main.py | 38 +- .../agent_generator/generator/generator.py | 22 +- .../generator/part_generators/__init__.py | 4 + .../pyproject_part_generator.py | 61 ++ .../part_generators/secrets_part_generator.py | 15 +- .../part_generators/tests_part_generator.py | 157 +++++ src/blueprint/agents/agent/agent_builder.py | 10 + src/blueprint/agents/agent/agent_runtime.py | 25 +- src/blueprint/agents/agent_group.py | 97 +++ .../agents/clients/io/io_client_base.py | 69 ++ .../agents/clients/io/nats_client.py | 102 ++- src/blueprint/agents/component/component.py | 5 +- src/blueprint/agents/component/registry.py | 65 +- src/blueprint/agents/config/config.py | 104 ++- .../agents/io/api/actuators/actuator_api.py | 29 +- tests/integration/__init__.py | 3 + tests/integration/conftest.py | 329 +++++++++ tests/integration/docker-compose.yml | 45 ++ tests/integration/helpers.py | 65 ++ .../test_acknowledgement_lifecycle.py | 282 ++++++++ tests/integration/test_delivery_once.py | 185 +++++ tests/integration/test_event_path.py | 222 ++++++ tests/integration/test_grouped_agents.py | 200 ++++++ tests/integration/test_harness.py | 213 ++++++ tests/integration/test_shared_redis_cache.py | 46 +- .../cli/commands/test_create_agent.py | 78 +++ .../cli/test_created_imports.py | 78 +++ tests/unit/agent_generator/cli/test_main.py | 69 ++ .../generator/test_generated_project.py | 213 +++++- tests/unit/agents/agent/test_agent_builder.py | 42 +- .../agents/clients/io/test_nats_client.py | 158 ++++- .../agents/component/test_name_uniqueness.py | 53 ++ tests/unit/agents/component/test_registry.py | 17 +- .../config/test_config_specialized_configs.py | 18 + .../agents/config/test_namespace_views.py | 30 + .../io/api/actuators/test_actuator_api.py | 6 +- tests/unit/agents/test_agent_isolation.py | 392 +++++++++++ tests/unit/examples/test_example_structure.py | 20 + 68 files changed, 4527 insertions(+), 198 deletions(-) create mode 100644 src/blueprint/agent_generator/generator/part_generators/pyproject_part_generator.py create mode 100644 src/blueprint/agent_generator/generator/part_generators/tests_part_generator.py create mode 100644 tests/integration/__init__.py create mode 100644 tests/integration/docker-compose.yml create mode 100644 tests/integration/helpers.py create mode 100644 tests/integration/test_acknowledgement_lifecycle.py create mode 100644 tests/integration/test_delivery_once.py create mode 100644 tests/integration/test_event_path.py create mode 100644 tests/integration/test_grouped_agents.py create mode 100644 tests/integration/test_harness.py create mode 100644 tests/unit/agent_generator/cli/commands/test_create_agent.py create mode 100644 tests/unit/agent_generator/cli/test_created_imports.py create mode 100644 tests/unit/agent_generator/cli/test_main.py create mode 100644 tests/unit/agents/test_agent_isolation.py diff --git a/docs/README.md b/docs/README.md index df17d8b3..b004c486 100644 --- a/docs/README.md +++ b/docs/README.md @@ -18,7 +18,7 @@ Blueprint Agents is a Python 3.13+ framework for building AI-powered microservic |-------|-------------| | [Architecture](concepts/architecture.md) | AppBuilder pattern, component lifecycle, and dependency injection | | [Event Processing](concepts/event-processing.md) | Event handler pipeline, message routing, and processing model | -| [Configuration](concepts/configuration.md) | Dynaconf-based config with `settings.toml` and `secrets.toml` | +| [Configuration](concepts/configuration.md) | Dynaconf-based config with `settings.toml` and `.secrets.toml` | | [Caching](concepts/caching.md) | Declaring caches, the disk and Redis backends, TTL, namespaces, readiness and the management API | | [Observability](concepts/observability.md) | Logging, metrics, tracing, and health checks | @@ -53,5 +53,5 @@ Blueprint Agents is a Python 3.13+ framework for building AI-powered microservic | Reference | Description | |-----------|-------------| | [API Reference](reference/api.md) | Public API surface for all framework modules | -| [Configuration Keys](reference/configuration-keys.md) | Complete list of `settings.toml` and `secrets.toml` keys | +| [Configuration Keys](reference/configuration-keys.md) | Complete list of `settings.toml` and `.secrets.toml` keys | | [Models](reference/models.md) | Built-in Pydantic models and base classes | diff --git a/docs/components/agents.md b/docs/components/agents.md index ed7a5454..17ecef71 100644 --- a/docs/components/agents.md +++ b/docs/components/agents.md @@ -250,9 +250,9 @@ model_max_tokens = 500 model_temperature = 0.0 ``` -### secrets.toml +### .secrets.toml -Store API keys in `secrets.toml` (never commit this file): +Store API keys in `.secrets.toml` (never commit this file): ```toml [default.runtimes.summarizer] diff --git a/docs/components/event-handlers.md b/docs/components/event-handlers.md index 49e1d512..4f7464b6 100644 --- a/docs/components/event-handlers.md +++ b/docs/components/event-handlers.md @@ -187,7 +187,7 @@ Register handlers with `AppBuilder` by passing the **class** or an instance of t ```python from blueprint.agents import AppBuilder, Config -config = Config(settings_files=["settings.toml", "secrets.toml"]) +config = Config(settings_files=["settings.toml", ".secrets.toml"]) app = ( AppBuilder(config) .with_service(OrderService) @@ -263,7 +263,7 @@ class InvoiceHandler(EventHandlerBase): ## Testing -Use a mock registry to unit test handlers in isolation. +Use a mock registry to unit test handlers in isolation. ```python import pytest diff --git a/docs/concepts/architecture.md b/docs/concepts/architecture.md index c8b35462..96d46074 100644 --- a/docs/concepts/architecture.md +++ b/docs/concepts/architecture.md @@ -29,7 +29,7 @@ from my_app.agents import ResearchAgent from my_app.apis import QueryApi from my_app.schedulers import CleanupScheduler -config = Config(settings_files=["settings.toml", "secrets.toml"]) +config = Config(settings_files=["settings.toml", ".secrets.toml"]) app = ( AppBuilder(config) @@ -206,7 +206,7 @@ class PurgeScheduler(SchedulerBase): # -- Application assembly -- -config = Config(settings_files=["settings.toml", "secrets.toml"]) +config = Config(settings_files=["settings.toml", ".secrets.toml"]) app = ( AppBuilder(config) diff --git a/docs/concepts/caching.md b/docs/concepts/caching.md index 2c4469e0..523f2d9a 100644 --- a/docs/concepts/caching.md +++ b/docs/concepts/caching.md @@ -18,7 +18,7 @@ this file; see the git history for those. ```python from blueprint.agents import AppBuilder, Config -config = Config(settings_files=["settings.toml", "secrets.toml"]) +config = Config(settings_files=["settings.toml", ".secrets.toml"]) app = ( AppBuilder(config) diff --git a/docs/concepts/configuration.md b/docs/concepts/configuration.md index 326c849a..94591ec3 100644 --- a/docs/concepts/configuration.md +++ b/docs/concepts/configuration.md @@ -9,7 +9,7 @@ The `Config` class is the entry point for all configuration. It accepts a list o ```python from blueprint.agents import Config -config = Config(settings_files=["settings.toml", "secrets.toml"]) +config = Config(settings_files=["settings.toml", ".secrets.toml"]) ``` The `Config` instance is passed to `AppBuilder` and automatically made available to all components via `self.config`. @@ -27,7 +27,7 @@ log_level = "INFO" event_bus = "dapr" ``` -### secrets.toml +### .secrets.toml A separate file for sensitive values such as API keys, connection strings, and credentials. This file should be listed in `.gitignore` and never committed to version control. diff --git a/docs/getting-started.md b/docs/getting-started.md index e932fd26..a12f706c 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -84,7 +84,7 @@ my-first-agent/ │ └── prompts/ # LLM prompt files ├── tests/ ├── settings.toml # Configuration -├── secrets.toml # Secrets (gitignored) +├── .secrets.toml # Secrets (gitignored) ├── pyproject.toml └── Dockerfile ``` @@ -98,7 +98,7 @@ my-first-agent/ | `src/models/` | Pydantic models for request/response schemas and domain objects. | | `src/prompts/` | Prompt template files used by LLM-powered agents. | | `settings.toml` | Application configuration managed by Dynaconf. | -| `secrets.toml` | Sensitive values (API keys, connection strings). Gitignored by default. | +| `.secrets.toml` | Sensitive values (API keys, connection strings). Gitignored by default. | --- @@ -112,7 +112,7 @@ asbs dev This will: -1. Load configuration from `settings.toml` and `secrets.toml` +1. Load configuration from `settings.toml` and `.secrets.toml` 2. Register all handlers, services, and API endpoints 3. Start the FastAPI server with hot-reload enabled @@ -180,7 +180,7 @@ app = ( ### Key points - **`AppBuilder`** is the central assembly point. It uses a fluent (method-chaining) API to register each component. -- **`Config`** loads values from `settings.toml` and `secrets.toml` via Dynaconf. Environment variables can override any setting. +- **`Config`** loads values from `settings.toml` and `.secrets.toml` via Dynaconf. Environment variables can override any setting. - **Handlers** (`EventHandlerBase` subclasses) process incoming events from message queues or other sources. - **Services** (`ServiceBase` subclasses) encapsulate reusable business logic and are injected into handlers and APIs. - **APIs** (`RestApiBase` subclasses) define REST endpoints that are automatically mounted on the FastAPI server. @@ -202,7 +202,7 @@ log_level = "INFO" server_port = 8000 ``` -**secrets.toml** -- Sensitive values (API keys, credentials): +**.secrets.toml** -- Sensitive values (API keys, credentials): ```toml [default] diff --git a/docs/guides/cli-reference.md b/docs/guides/cli-reference.md index 2fa6f988..e22ad9de 100644 --- a/docs/guides/cli-reference.md +++ b/docs/guides/cli-reference.md @@ -132,8 +132,8 @@ agent's namespace is that name in snake case (`order_processor`). services/ agents.toml # agent name -> declaration; baked into the image settings.toml - secrets.toml # git-ignored - secrets.toml.example # committed, so the keys to fill in are known + .secrets.toml # git-ignored + .secrets.toml.example # committed, so the keys to fill in are known Dockerfile .gitignore ``` @@ -703,7 +703,7 @@ Project shape: - Required directories (`src/`, `tests/`) and files (`settings.toml`, `pyproject.toml`) exist - `src/main.py` exists and uses `AppBuilder` -- `secrets.toml.example` and `secrets.toml` are present +- `.secrets.toml.example` and `.secrets.toml` are present - A `Dockerfile` is present Group readiness -- what this project must state before it can be hosted beside another agent: diff --git a/docs/guides/deployment.md b/docs/guides/deployment.md index 34560254..30292ea7 100644 --- a/docs/guides/deployment.md +++ b/docs/guides/deployment.md @@ -65,7 +65,7 @@ Three things about it are load-bearing: scaffolded `src/main.py` declares an agent and builds nothing; the entry point resolves this process's group, builds it and serves it. A project that has not migrated keeps `uvicorn src.main:app` and keeps working. -- **`secrets.toml` is never copied in.** Mount it, or supply the values as environment variables. +- **`.secrets.toml` is never copied in.** Mount it, or supply the values as environment variables. ### Building and running @@ -753,7 +753,7 @@ Later sources override earlier ones: 1. `settings.toml` -- base configuration, baked into the image 2. each agent's own `settings.toml`, merged under that agent's scope -- filling gaps only, so the group's file and any `DYNACONF___KEY` win over it -3. `secrets.toml` -- local development only; never copied into the image +3. `.secrets.toml` -- local development only; never copied into the image 4. environment variables -- the ConfigMap and Secret above --- diff --git a/docs/guides/multi-agent-setup.md b/docs/guides/multi-agent-setup.md index 0b74caad..14ce654d 100644 --- a/docs/guides/multi-agent-setup.md +++ b/docs/guides/multi-agent-setup.md @@ -128,7 +128,7 @@ of the three is a name you cannot cheaply change afterwards. Before: ```python -config = Config(settings_files=["settings.toml", "secrets.toml"]) +config = Config(settings_files=["settings.toml", ".secrets.toml"]) app = ( AppBuilder(config) @@ -161,7 +161,7 @@ component: ```python def create_app(): - return agent.build(Config(settings_files=["settings.toml", "secrets.toml"])) + return agent.build(Config(settings_files=["settings.toml", ".secrets.toml"])) ``` Two things the module must not do, because it is imported into a shared runtime: construct clients diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md index 71e8f13e..82211c15 100644 --- a/docs/guides/troubleshooting.md +++ b/docs/guides/troubleshooting.md @@ -207,15 +207,15 @@ Check the Dapr subscription configuration to ensure topic mappings are correct. **Symptom:** Agent calls fail with an authentication error. ``` -AuthenticationError: No API key provided. Set DYNACONF_LLM__API_KEY or add it to secrets.toml. +AuthenticationError: No API key provided. Set DYNACONF_LLM__API_KEY or add it to .secrets.toml. ``` **Cause:** The LLM provider API key is not configured. -**Solution:** Set the API key in `secrets.toml` (for local development) or via an environment variable (for production): +**Solution:** Set the API key in `.secrets.toml` (for local development) or via an environment variable (for production): ```toml -# secrets.toml (local only -- do not commit) +# .secrets.toml (local only -- do not commit) [llm] api_key = "sk-..." ``` diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index be2b3d65..4f5e4ba2 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -6422,23 +6422,659 @@ durable survival across reconnect and the shutdown drain are specified, implemen 566 lines became 809. +### The scaffolded settings file writes keys the framework reads + +Three open points, all the same defect wearing different names: the scaffolder writes a key in a +shape nothing looks up. Nothing fails -- the file says one thing, the process does another, and +there is no message in between. Each was probed against a real `Config` before and after. + +**`base_files/settings.txt`: two tables become four flat keys.** The template wrote + +```toml +[default.logging] +level = "DEBUG" +format = "json" + +[default.observability] +otel_enabled = false +token_metrics_enabled = true +``` + +and the framework reads `log_level`, `log_format`, `otel_enabled` and `token_metrics_enabled` from +the top level of the environment table. Probed: that file yields +`get_observability_config().otel_enabled == False` and `log_level == "INFO"` -- every value in both +tables inert, including the one a developer would edit first. They are now written flat, inside +`[default]` and above the `[default.runtimes.*]` tables the generator appends, with the reason in +the file: *these are flat keys, not sections*. + +Two values changed as a consequence, because making a key effective is choosing what it does: + +- **`log_format` is now `"text"`, not `"json"`.** A scaffolded project is run locally first, where + a JSON line per log record is unreadable. Nothing had ever run with `"json"`, so this is not a + behaviour change to anything that exists. +- **`log_level` stays `"DEBUG"`**, which is what the `debug = true` two lines above it already says. + +The comment also states what these two become in a group: `log_level` and `log_format` are in +`PROCESS_SCOPE_KEYS`, so if this project is later hosted as one agent, its own copies are reported +and ignored and the group's file decides. That is a warning the author will see, and it is better +read next to the keys than in a log line. + +**`config.py`: `token_metrics_enabled` was read by nothing at all.** Flattening the key exposed +that the getter never passed it -- `get_observability_config()` built an `ObservabilityConfig` +from four keys and left the fifth to the model's default of `True`: + +```python +return ObservabilityConfig( + otel_enabled=self.get("otel_enabled", False), + otel_endpoint=self.get("otel_endpoint"), + otel_service_name=self._resolve_service_name(), + token_metrics_enabled=self.get("token_metrics_enabled", True), + log_level=self.get("log_level", "INFO"), +) +``` + +The line in the middle is new. `MetricsRecorder` gates the per-call token and latency metrics on +`observability.otel_enabled and observability.token_metrics_enabled`, so until now the key could +be written in any shape, anywhere, and the metrics stayed on. + +**`create.py`: `[default.runtimes..models]` becomes `.model_settings`.** `Config.get_ai_config` +reads `runtimes..model_settings` and hands the dictionary to the provider client verbatim; +`OpenAIClient` builds `OpenAIResponsesModelSettings(**ai_config.model_settings)` out of it. A +`.models` table is read by nothing, so the reasoning-effort block `asbs create agent` adds was +inert -- while the generator's own settings writer (`settings_part_generator.py`) has always +written the right name, so the two halves of the scaffolder disagreed. + +**A fourth defect, found by the test written for the third.** `create_agent` derived the runtime +name *inside* the try block that reads `src/main.py`: + +```python +agent_name = snake_name if snake_name.lower().endswith("agent") else snake_name + "_agent" +``` + +`read_main_py` raises when there is no `src/main.py` -- which is exactly the project that then +needs the "register it by hand" instructions printed at the end, and those name `agent_name`. So +the fallback path ended in `UnboundLocalError`, after the prompts and the settings block had +already been written. The assignment moved above the `try`. + +Tests: `TestTheGeneratedSettingsAreRead` in `test_generated_project.py` loads the generated +`settings.toml` through a real `Config`, **flipping each value first** so that what is asserted is +that the key is live rather than that its value matches the framework's default, and checks that no +`logging` or `observability` table is written at all; new +`tests/unit/agent_generator/cli/commands/test_create_agent.py` asserts the runtime block through +`get_ai_config` rather than through the file text, and takes the no-`main.py` path; two cases added +to `TestGetObservabilityConfig`. + +**Found while writing them, not fixed here:** a scaffolded project cannot start. The generator +writes `secrets.toml`, and `DEFAULT_SETTINGS_FILES` -- what `entrypoint.py` loads -- names +`.secrets.toml`. With the scaffolded `model_provider = "vllm"`, `Config.validate()` then raises +`Missing API key for vLLM provider` on a project nobody has edited. Raised rather than fixed +because which of the two names is right is a decision: the generator says `secrets.toml` in three +places (the file, `secrets.toml.example`, `.gitignore` and `asbs validate`), Dynaconf's convention +says `.secrets.toml`, and changing the framework's list moves the ground under every existing +deployment. + +### The scaffolded project's secrets file is the one the framework loads + +`asbs setup` wrote **`secrets.toml`**; `DEFAULT_SETTINGS_FILES` -- the list `entrypoint.py` hands +to `Config`, and the image's contract with the project -- is `["settings.toml", ".secrets.toml"]`. +So the file was loaded by nothing, and since the scaffolded `model_provider = "vllm"` makes the +API key a *validated* requirement, `Config.validate()` raised on a project nobody had edited: + +``` +FAILED: ConfigError Missing API key for vLLM provider +``` + +**This is fallout from phase 10 step 1**, not an old defect. Before `5740195` the generated +`main.py` built its own configuration and named the file itself: + +```python +config = Config(settings_files=["settings.toml", "secrets.toml"], root_path=...) +``` + +Step 1 made `main.py` a pure declaration and moved the construction into the entry point, which +reads `DEFAULT_SETTINGS_FILES` -- and the undotted name was left behind in the generator. + +**The dot wins, and the generator moves.** The alternative is adding `secrets.toml` to +`DEFAULT_SETTINGS_FILES`, which changes what every existing deployment loads -- a project with a +stray `secrets.toml` on disk would start reading it -- to fix a file only the scaffolder writes. +`.secrets.toml` is also Dynaconf's own convention and the same shape as `.env`, and keeping the +framework's list untouched means no consumer of this package sees a change at all. + +- `secrets_part_generator.py` writes `.secrets.toml` and `.secrets.toml.example`. The example + keeps the real name plus a suffix, so there is one rule rather than two names to remember. +- The generated `.gitignore` ignores `**/.secrets.toml` -- named exactly, **not** `.secrets.*`, + which would also ignore the committed example. +- `asbs validate` reports an undotted file as the **rename it needs**, not as a file that is + missing: `Found secrets.toml, which nothing loads: the framework reads '.secrets.toml'`. That + is the only message an already-scaffolded project will get, and "missing" would send its author + to create a second file beside the one they already have. +- The generated `Dockerfile`'s mount example named the wrong path on both sides, so following it + produced a container whose secrets were invisible. It now mounts `/app/.secrets.toml`, and the + stale `DYNACONF_SETTINGS=/run/secrets/...` example -- which does nothing, because the entry + point passes `settings_files` explicitly -- is replaced by a Docker secret with a `target=` and + by the environment-variable form. +- `asbs setup`'s printed tree and next steps name the file it actually wrote. + +Documentation: every `secrets.toml` in `docs/` and in the docs shipped into a generated project +(`claude_docs/`, `assistant_integrations/`) is now `.secrets.toml` -- 33 occurrences across 16 +files. The `Config(settings_files=["settings.toml", "secrets.toml"])` snippets worked as written, +because they name the file explicitly, but they taught the name that the scaffolder no longer +writes. + +Tests: `test_the_project_configures_itself_from_the_files_the_image_reads` is the one that would +have caught this -- it builds a `Config` over the generated project using `DEFAULT_SETTINGS_FILES` +itself, so the project and the framework have to agree on the name or the test fails the way the +container did. The `.gitignore` assertion now reads the file as *patterns* rather than as text, +since a comment naming the example would otherwise pass for a rule about it. + +**Still not startable, for a second and unrelated reason.** With the secrets file found, the +scaffolded project gets as far as building its agent and fails: + +``` +TypeError: AgentRuntime.__init__() missing 1 required positional argument: 'name' +``` + +`AgentBuilder.build()` constructs `AgentRuntime(system_prompt=..., tools=..., **kwargs)` and never +passes a name, while `AppBuilder.with_agent(agent, name=...)` keeps `name` as the *declaration's* +name and applies it after construction. Every test that builds an `AgentBuilder` through +`AppBuilder` replaces `agent.build` with a lambda returning a `MagicMock`, so the real path has +never run. Its own change. + +### An agent runtime is constructed with a name, and registered like every other component + +The last thing standing between `asbs setup` and a process that serves. With the secrets file +found, a scaffolded project got as far as building its agent and stopped: + +``` +TypeError: AgentRuntime.__init__() missing 1 required positional argument: 'name' +``` + +**Nothing passed the name.** `AgentRuntime.__init__(self, name: str, **kwargs)` requires it -- +it is the registry key -- and `AgentBuilder.build()` constructed the runtime without one, while +`AppBuilder.with_agent(agent, name=...)` keeps that name on the *declaration* and assigns it +after construction (`_construct`: `instance.name = declaration.name`). So the call raised before +the assignment that would have supplied it. The builder has held the answer all along: + +```python +kwargs.setdefault("name", self._runtime_name) +runtime = AgentRuntime( + system_prompt=self._system_prompt, + tools=self._tools if self._tools else [], + **kwargs, +) +``` + +`runtime_name` is the key the runtime's own configuration is read under, so it is the right +default, and a differing declaration name still renames it afterwards. `setdefault` rather than a +positional argument, because `build(config, name=...)` is a legal call and a positional would +have turned it into a duplicate-argument `TypeError`. + +**The half that only becomes visible once the path runs: the runtime was the one component that +registered itself.** + +```python +Agent.__init__(self, name=name, **kwargs) +Component.__init__(self, should_register=False) +self._name = name +self.registry.add_component(name, self) +``` + +Every other component is registered by `Component.__init__` under +`qualified_component_name(namespace, base_name)`; this one opted out and registered under the +**bare** name. Two agents in a group whose runtimes shared a name therefore collided on one +registry key -- `Registry.add_component` raising "name is already taken" -- instead of becoming +`orders_assistant` and `billing_assistant`. `_base_name` was never set either, so it kept the +class-derived `agent_runtime` for every agent, which is what the readiness entry and the OpenAPI +tag render from. The four lines are now two: + +```python +Agent.__init__(self, name=name, **kwargs) +Component.__init__(self, name=name) +``` + +Nothing is lost at the root, where `qualified_component_name("", name) == name`, so a +single-agent application's registry key and every lookup of it are unchanged. Inside an agent +the bare name still resolves, because `Registry._lookup` qualifies on the way in -- a service +written as `self.registry.get_agent("assistant")` finds `orders_assistant`. + +**The rename had to be fixed with it, and this is the subtle one.** pydantic-ai's `Agent.name` is +backed by `self._name` -- the *same field* `Component` uses -- and its setter does nothing else +(read from `pydantic_ai`'s source: `name_ = self._override_name.get(); return name_.value if +name_ else self._name`). The combined setter called both: + +```python +Agent.name.fset(self, value) # self._name = value, unqualified +Component.name.fset(self, value) # update_component_name(self._name, qualified) +``` + +With the runtime registered under the bare name, the first line happened to write the value the +second line then found. Registered under a *qualified* name it no longer does: `Agent`'s setter +overwrites the field with the unqualified value, and `Component`'s setter then asks the registry +to rename a key that was never there -- `Component with name assistant does not exist`. The +setter is now `Component.name.fset` alone, which qualifies, moves the key, and writes the field +both getters read. + +**A docstring that said the opposite of the code.** `Component.name`'s setter claimed +`qualified_component_name` "is idempotent, so a caller that has already qualified the name is not +punished for it". That function's own docstring spends a paragraph on being **deliberately not** +idempotent. Corrected to say what it does: pass the bare name. + +Tests: + +- `TestAnAgentRuntimeIsNamedLikeEveryOtherComponent` in `test_name_uniqueness.py`, against a real + registry: qualification, two agents with one runtime name, the root's bare name, lookup by the + bare name from inside the agent, `base_name`, and the rename. +- Two cases in `TestBuild`, which had **no successful build at all** -- every existing case was an + error path, which is the other half of why this survived. +- `TestTheProjectTheEntryPointBuilds` in `test_generated_project.py`: the scaffolded project is + built through `entrypoint.build_group_app`, the function the container's command calls. It + assembles only -- the lifespan is where an agent reaches for its model -- and asserts the + agent's components all carry its namespace. + +**One existing test was passing because of the defect.** +`test_a_model_name_override_is_applied_at_build` asserted that `build()` raised *something* +(`pytest.raises(Exception)`, with a `# noqa: B017`) and then read the override out of the +wreckage. What it raised was this `TypeError`. It now stubs the rest of the build and asserts the +override alone. + +Every test that builds an `AgentBuilder` through `AppBuilder` replaces `agent.build` with a lambda +returning a `MagicMock` (`test_deferred_wiring.py`), which is the reason a defect on the path +every grouped agent takes left a green suite. + +**A scaffolded project now starts.** Probed end to end: generate, `create_group_app`, and the +lifespan runs to `Application startup completed`. `/health/ready` answers 503 until a real +`model_api_key` replaces the scaffolded placeholder -- the AI client's health check is what fails, +which is the intended behaviour rather than a remaining defect. + +### Isolation, step 1 -- the registry's root fallback stops reaching a neighbour + +The first of the four routes out of an agent, and the one that needed no argument at all: the +asking agent already knows its neighbours' names, because they are in the group, and the +qualifier is a documented `_`. + +```python +billing.registry.get_component("orders_ledger").record_id # -> "ORDERS-RECORD-4242" +``` + +`Registry._lookup` tries `_` and then the bare name. That fallback exists to +reach the **root** -- the shared transport client, the shared health cache -- but a neighbour's +registry key *is* a bare name in the same dictionary, so the fallback resolved it. The fix is to +check who owns what the fallback found: + +```python +found = self._components.get(name) +if found is not None and namespace and namespace_of(found) not in (ROOT_NAMESPACE, namespace): + return None +return found +``` + +Two owners pass. `ROOT_NAMESPACE` is the fallback's whole purpose. The asking namespace itself is +the documented already-qualified case -- a caller holding `orders_ledger` inside `orders` misses +on `orders_orders_ledger` and then finds it bare -- and a test now pins that, because it is what +the ownership check could most easily have cost. + +**It reads as absent, not refused.** `get_component` raises its ordinary +`Component with name orders_ledger does not exist in namespace 'billing' or at the root`. A +refusal naming the agent would confirm the neighbour exists, which is the same class of +disclosure in a smaller size -- so the neighbour is simply not there. + +`namespace` is falsy on the application registry and on a root component's view, so nothing the +root does changes: `build()`, the lifespan and the fan-out services all resolve exactly what they +resolved before. + +The `xfail(strict=True)` marker came off +`test_a_neighbours_qualified_name_is_not_a_key_this_agent_can_use`, which is what strict xfail is +for -- the fix turned the test red until the marker went. + +### Isolation, step 2 -- a view may name its own agent or the root, and no other + +The second route, and the one that took two tests to state because it opens two surfaces from one +line of code. An explicit ``namespace`` argument won unconditionally: + +```python +billing.registry.get_component("ledger", namespace="orders") # -> orders' instance +billing.registry.get_cache("default", namespace="orders").get("record") # -> orders' stored record +``` + +Every agent was one keyword away from its neighbours, and the second call is the one that +matters more: a component instance holds what is in flight, a cache holds what was *kept*. + +Both resolvers now refuse a view that names another agent. `_effective_namespace`: + +```python +if namespace is None: + return self._default_namespace +if self._default_namespace and namespace not in (self._default_namespace, ROOT_NAMESPACE): + raise RuntimeError(...) +return namespace +``` + +and `_cache_owner` carries the same check rather than sharing one -- **the two cannot be merged**, +because they mean different things by an omitted argument. For components it means *every* +namespace on the application registry, which is what `build()` and the lifespan iterate over; for +a cache it means *this agent*, never every agent, since no cache belongs to all of them. That is +why they were written as separate functions in the first place, and the duplicated check is the +price of keeping it that way. + +**Refused, not answered absent** -- the opposite of step 1, deliberately. There, a bare name that +happened to be a neighbour's key is a near miss, so the neighbour is reported as not existing. +Here the caller *named* another agent, which is a decision rather than a slip, and a silent +`None` would read as "that agent has nothing registered" -- itself a claim about the neighbour. + +**One existing test asserted the hole as intended behaviour.** +`test_an_explicit_namespace_overrides_the_view` did exactly what its name says, and it was the +only casualty of the whole isolation change. It is now +`test_an_explicit_namespace_naming_a_neighbour_is_refused`, with a second case for the two names +a view may still give -- its own and the root's. + +**Nothing else in the framework is caught by it**, which is what made the change safe to make. Every +component that passes a namespace passes `self.namespace` -- its own (`handler_chain.py:419,432`, +`nats.py:55,87`) -- and the three places that pass an arbitrary one are constructed **at the +root**: `EventProcessingService` and `DaprEventing` in `build()` outside the per-agent loop +(`app_builder.py:917,1127`), and `NamespaceSupervisor`, which is handed the application registry. +A root component's `registry` property returns the registry itself, not a view, so the guard +never fires for them. Two tests pin the calls that must keep working: a view naming its own +namespace, and a view naming the root. + +**Probed while here, and sound:** class-based resolution cannot reach a neighbour even though +`_all_of_type` deliberately ignores the namespace when gathering candidates. +`resolve_for_namespace` then filters strictly to `namespace` and then `ROOT_NAMESPACE`, so a +neighbour's instance is never a candidate it can return -- only an ambiguity *within* one level +raises. + +Two `xfail(strict=True)` markers came off. + +### Isolation, step 3 -- one declaration stops handing two agents the same object + +The only one of the four routes that needs no lookup at all: the object arrives in both +constructors. + +```python +declaration = AppBuilder().with_service(Ledger, holdings=[]) +AgentGroup("finance", {"orders": declaration, "billing": declaration}).assemble(config) +orders.holdings.append("ORDER-7") +billing.holdings # -> ['ORDER-7'] +``` + +One declaration serving several agents is the property the whole design rests on -- the same +`AppBuilder` named twice in the map, replayed once per namespace. Replay re-issues the recorded +call and `_construct` spreads the recorded `kwargs` into the constructor, and `**` copies the +*mapping* and not its values. Both agents therefore hold the same list. + +**Refused rather than copied.** `deepcopy` would close the hole silently and change what the +author wrote: a client or a connection pool passed deliberately would be duplicated per agent, +and an object holding a lock or a socket cannot be copied at all -- so the failure would arrive +later, somewhere else, and look like something different. `AgentGroup._refuse_state_shared_between_agents` +runs with the other refusals, at assembly, and names the agents, the call, the argument, its type +and the way out. + +**The line is code versus data**, in a new `SHARED_NESTED_PREFIXES`-style allowlist, +`SHAREABLE_TYPES`: `None`, `bool`, `int`, `float`, `complex`, `str`, `bytes`, `frozenset`, +`range`, `Enum`, and `type`, function, method and module -- tuples checked recursively. Two agents +built from one declaration *already* share the component class, and a class, a function or a +module is behaviour rather than something an agent can write into. A list, a dict, a set or an +ordinary instance is state. Arbitrary instances are refused even when their author considers them +frozen, because "frozen" is not decidable from the object and the cost of being wrong is silent +cross-agent sharing. + +**The fix needs no new API.** A declaration's target may be a zero-argument factory, called once +per agent, so `with_service(lambda: Ledger(holdings=[]))` gives each its own -- and a test pins +that. **Only a declaration used by more than one agent is checked**: a single-agent declaration +may carry anything, because there is nobody to share it with, which is *standalone is permissive, +the group has rules* applied to the one case that is genuinely about the group. + +### Isolation, step 4 -- a dotted configuration key stays inside its own agent + +The last route, and the one with compatibility consequences, which is why it went last. + +```python +config.for_namespace("billing").get("orders.record_id") # -> "ORDERS-RECORD-4242" +``` + +An agent's section is written `[default.]`, so its keys *are* `.` to anyone +who can resolve a dotted name -- and `_scoped_get` tries `.` and then falls back to +the raw key against the whole tree. The scope prefixes a key; it never confined it. + +The fallback is now restricted to the dotted prefixes the framework itself owns, by an +**allowlist** rather than a list of agent names: + +```python +SHARED_NESTED_PREFIXES = frozenset({"cache", "event_publishing", "runtimes", "runtime"}) +``` + +Those are the only four the framework reads a dotted key under -- `cache.*` (11 keys), +`event_publishing.*` (2), and `runtimes..*` with its legacy singular. Flat is the norm for +everything else. An allowlist fails closed: a new agent needs no entry, and a prefix this list has +never heard of is refused rather than resolved, which is the opposite of the default that created +the hole. + +**It raises, and does not quietly miss**, for the reason the deployment-identity check raises: a +`None` reads as "not configured" and sends the caller hunting for a setting, when what actually +happened is that the key names somewhere they cannot read. + +**Only a view is confined.** The loader is untouched -- the application owns its whole tree, and +`build()`, `resolved_settings` and the environment endpoint read across agents by design. A test +pins that too. + +**The compatibility note:** a project reading its own *custom* nested key through a scoped view +now gets an error naming the rule. Nothing in the framework or the examples does, and +`Config.settings` remains the escape hatch, but it is a behaviour change rather than a pure +tightening -- the only one of the four. + +### Publishing is its own decision, and its subjects are declared + +Closes the defect broker step 2 found. `_stream_subjects` covered what the client *subscribed* +to and nothing it published to, so a JetStream publish to a handler-result subject waited for a +`PubAck` no stream would send, timed out, and was swallowed by `publish_handler_event` as a +WARNING -- while a Core NATS subscriber still saw the message, because the publish did go out. +A live listener looked healthy; nothing was stored. + +**The root cause was one key doing two jobs.** `nats_use_jetstream` exists so *consumers* can be +durable, and `publish()` read the same flag: + +```python +if self._use_jetstream and client.jetstream(): + ack = await client.jetstream().publish(topic, event_data) +``` + +Nobody decided that publishing should be durable -- it followed from a key about something else. +Three changes, in that order: + +**`nats_publish_mode` splits the decision.** `"core"` or `"jetstream"`; unset, it follows +`nats_use_jetstream`, so no existing deployment changes. The shape this makes reachable is +durable consumption beside fire-and-forget publishing -- a status notification nothing needs to +persist, which under the old coupling paid for a stream round trip it had no use for. A test pins +that a client with `_use_jetstream` set no longer publishes through JetStream on that basis alone. + +**`_resolve_publish_subjects` declares what may be published.** Two sources, because there are two +ways an outbound subject is chosen: `event_publishing.topic_mapping`, which is how a +`HandlerResult` is routed and therefore where nearly every outbound subject is already written +down, and `nats_publish_subjects` for a caller that passes `topic=` to `publish_event` directly +and so never appears in the mapping. + +**A wildcard is refused**, by a new `validate_publish_subject` beside the existing +`validate_subject_segment` -- same rule, whole subject rather than one segment, so dots are legal +and `*`, `>` and whitespace are not. `orders.*` is a good thing to subscribe to and a meaningless +thing to publish to: NATS takes it literally, so the message lands on a subject spelled with an +asterisk and every subscriber to the pattern misses it. Nothing fails and nothing arrives, which +is why it is worth refusing at startup. + +`_stream_subjects` then adds the publishable subjects **when publishing is durable** -- and not +otherwise, because a Core publish stores nothing and widening the stream for it would claim +subjects the deployment has no reason to own. + +One existing test had set the old coupling by hand (`nats_client._use_jetstream = True` before +calling `publish`); it now sets the publish mode, and has a companion asserting the separation. + +### The scaffolded project ships tests, and a pyproject that makes its own next step possible + +`asbs setup` printed *"Install dependencies: pip install -e ."* and wrote no `pyproject.toml`, so +that command could not work; `asbs validate` then reported `tests/` and `pyproject.toml` missing +on a project the same tool had just produced. Both are now generated, and the loop closes: +`asbs setup` -> `pytest` (7 passed) -> `asbs validate` (passes). + +**Two tests, deliberately not more.** The scaffolded handler and service `raise +NotImplementedError` in the methods that matter -- that is where the author's logic goes -- so a +generated test of `handle_event` could only assert the stub is still a stub, and would fail the +moment it stopped being one. A test that must be deleted before the project can work teaches that +the suite is noise. What is generated is what is true on day one and stays true: + +- `tests/test_declaration.py` -- `src/main.py` declares an unbuilt `AppBuilder`, constructs + nothing on import, and passes classes rather than instances. Both mistakes it guards against + work fine standalone, which is why they are easy to make: `.build()` here takes the + configuration and namespace the host is supposed to decide, and `with_service(MyService())` + creates a component before any namespace exists, so it belongs to the root for ever. +- `tests/test_mapper.py` -- the generated mapper is the one piece of scaffolded code with real + logic in it, so a DTO round trip is a real assertion, and it is what says so when a field is + added to one side and forgotten on the other. + +`pyproject.toml` declares the framework and pytest, and carries `pythonpath = ["."]` -- without +it the first `pytest` in a new project fails on importing `src.main`, which is the same import +`agents.toml` names and the entry point performs. + +### `asbs` prints UTF-8 and writes ASCII + +Every command prints check marks, warning signs and box drawing; Python encodes stdout with the +locale encoding, which on Windows is cp1252, which has none of them. The first line of output +raised `UnicodeEncodeError` -- *mid-command*: `asbs create handler` died after writing the handler +and before registering it in `main.py`, leaving the project half-edited. + +`use_utf8`, called on `sys.stdout` and `sys.stderr` at the top of `main()`, reconfigures to UTF-8 +and falls back to `errors="replace"` for a stream that refuses an encoding change -- where a lost +glyph is a `?` in a log rather than an abandoned command. Reproduced before and after with +`PYTHONIOENCODING=cp1252`, and `setup`, `create handler` and `validate` all run clean on one now. + +The other half of the rule is held by a test rather than a docstring: +`TestEverythingWrittenIsAscii` generates a **pristine** project -- the module's shared one has +`__pycache__` written into it by the tests that import `src.main`, and a `.pyc` is binary -- and +asserts every file decodes as ASCII. + +### `asbs create` writes the imports the file it edits already uses + +The generator emits relative imports throughout (`from .handlers import OrderHandler` in +`main.py`, `from ..services import OrderService` in a component); `asbs create` appended absolute +ones (`from src.handlers.order_placed_handler import ...`). Both resolve, which is why nothing +failed and why it survived -- and two styles in one file is how a later move breaks exactly one of +them. Twelve occurrences, across the handler, service, API, models and scheduler paths, plus the +"add this by hand" messages that print them. The one inside a generated API module needed `..` +rather than `.`, being a package deeper. + +### The environment endpoint reports what it claims to report + +`env_status` had a branch whose comment said *"An agent-scoped actuator reports its own scope and +nothing else"* and whose code handed `_as_dict(settings)` -- the **unscoped** tree. A scoped +actuator would have served every agent's configuration over HTTP. Latent rather than live, since +`ActuatorApi` is constructed at the root, and wrong as written either way. + +The fix needed `Config.resolved_settings` to work on a view, which it refused outright. It now +**resolves a view's own scope and nothing else**: asked for another namespace it still raises, and +the flattening is delegated to the object that owns the tree, because stripping the other agents' +subsections needs the list of namespaces and a view deliberately has none (C6). `for_namespace` +gives each view a `_loader` reference for exactly that. + +**A second defect surfaced while testing it.** The flattening derived "the other agents" from +`self._views` -- the namespaces that had *asked* for a view. An agent whose components had not yet +read their configuration was therefore left in a neighbour's resolved settings, so whether it +leaked depended on construction order. It is now derived from the tree itself: every top-level +table that is not one of `SHARED_NESTED_PREFIXES` is an agent's section. + +`_as_dict` was that branch's only caller and is gone. The existing test +`test_an_agent_scoped_actuator_reports_only_its_own_scope` asserted `APP_NAME == "root-app"` while +`orders` overrides it -- the second test in this session found asserting the bug its name +disclaims. + +### Five examples declared an app_name the framework refuses + +Since P1 a root-namespace application's `app_name` *is* its NATS queue group, and the dead-letter +subject derives from it -- so a space in it is a subject the broker rejects and the application +raises at subscribe time. `examples/webhook_relay` was broken outright, being the only example on +`event_bus = "nats"`; the other four were the same illegal value waiting for somebody to switch +bus. All five renamed to hyphenated forms, and `tests/unit/examples` now holds every example's +`app_name` to `validate_subject_segment`, so the next one cannot ship. The prose and docstrings +keep the readable names -- nothing reads those. + --- ## Open points -- **The generated `settings.toml` writes two sections nothing reads.** `[default.logging]` +- ~~**The generated `settings.toml` writes two sections nothing reads.**~~ **Done.** `[default.logging]` (`level`, `format`) and `[default.observability]` (`otel_enabled`, `token_metrics_enabled`) are sectioned, and the framework reads all four as **flat** keys -- `log_level`, `log_format`, `otel_enabled`, `token_metrics_enabled`. Probed against a real `Config`: a settings file with `[default.observability] otel_enabled = true` yields `get_observability_config().otel_enabled == False`, so a developer who turns telemetry on in the file scaffolded for them gets nothing and no message. `base_files/settings.txt` is where it is written. -- **`asbs create agent` writes `[default.runtimes..models]`; the framework reads - `runtimes..model_settings`.** The generator's own settings writer +- ~~**`asbs create agent` writes `[default.runtimes..models]`; the framework reads + `runtimes..model_settings`.**~~ **Done.** The generator's own settings writer (`settings_part_generator.py`) writes `.model_settings` correctly, so the two halves of the scaffolder disagree and the block `asbs create agent` adds is inert. Found beside the `openai_reasoning_effort` value fixed in step 3, in the same statement. -- **`asbs` crashes on a Windows console** -- still open from step 1, and now the only thing standing +- ~~**A scaffolded project cannot start: its secrets file is never loaded.**~~ **Done** -- the + generator moved to `.secrets.toml`. `asbs setup` used to write + `secrets.toml`, and `DEFAULT_SETTINGS_FILES` -- the list `entrypoint.py` hands to `Config` -- + names `.secrets.toml`. The scaffolded `model_provider = "vllm"` makes the API key a validated + requirement, so `Config.validate()` raises `Missing API key for vLLM provider` on a project + nobody has edited. Probed by generating a project and loading it with the framework's own + defaults. Which name is right is the decision: the generator says `secrets.toml` in four places + (the file it writes, `secrets.toml.example`, the `.gitignore` entry and `asbs validate`'s two + checks), Dynaconf's own convention is `.secrets.toml`, and adding a name to the framework's list + changes what every existing deployment loads. +- ~~**A scaffolded project still cannot start: `AgentRuntime` is constructed without a name.**~~ + **Done.** + `AgentBuilder.build()` calls `AgentRuntime(system_prompt=..., tools=..., **kwargs)`, and + `AgentRuntime.__init__` takes `name` as a required positional argument; + `AppBuilder.with_agent(agent, name=...)` records `name` on the declaration and assigns it after + construction, so nothing supplies it. Every unit test of that path stubs `agent.build`, which is + why it is green. Reproduced by generating a project and calling `create_group_app`. + +- ~~**An agent can read a neighbour's data by four routes.**~~ **All four closed** in isolation + steps 1-4; what follows is the record of what each was. The barrier is now enforced rather + than conventional, with one deliberate exception (`Config.settings`, below). Grouping's whole premise is that co-hosted agents are isolated; each of these was + reached with nothing but the framework's public API and a neighbour's *name*, which an agent + knows because it is in the group. Stated as tests in + `tests/unit/agents/test_agent_isolation.py`, marked `xfail(strict=True)` so that closing one + turns the test red until the marker goes. + - ~~**`Registry._lookup` falls back from `_` to the bare name**~~ **Closed in + isolation step 1.** A neighbour's key *is* a bare name in the same dictionary, so + `get_component("orders_ledger")` from `billing` returned orders' instance. The fallback now + checks that what it found belongs to the root or to the asking agent. + - ~~**`_effective_namespace` lets an explicit `namespace=` win on a view**~~ **Closed in + isolation step 2**, together with the same hole in `_cache_owner` -- both now refuse a view + that names an agent other than itself or the root. + - ~~**A scoped `get()` resolves a dotted key against the whole tree**~~ **Closed in + isolation step 4.** The root fallback now accepts only the framework's own dotted prefixes + (`SHARED_NESTED_PREFIXES`), an allowlist that fails closed. + - ~~**One declaration serving two agents constructs both with the same mutable argument.**~~ + **Closed in isolation step 3.** A declaration used by more than one agent is refused at + assembly if it carries anything but code or an immutable value; a zero-argument factory is + the way out and needs no new API. + + `Config.settings` is a fifth route and is **deliberate** -- the documented escape hatch, which + returns the unscoped tree and logs a WARNING naming the agent. It is covered by a passing test + rather than an xfail, because what it does is what it is for; whether an escape hatch belongs in + the barrier at all is the question to settle with the other four. + + What holds, and is now pinned: two agents get separate instances of one declared class; a + lookup by bare name, by class, or by enumeration sees only the asking agent's own; the root + remains resolvable; two agents declaring one cache name get separate stores and cannot read each + other's keys; `cache_entries()` refuses on a view (C6); `Config.for_namespace` refuses to hand + out another agent's view; and each agent gets its own thread pool. + +- ~~**A handler's published result is lost under JetStream unless something else provisions the + stream.**~~ **Closed.** The client declares its publishable subjects and the stream carries + them; publishing is now its own mode. Originally: `NATSClient._stream_subjects` covers the subscribed topics and the dead-letter + subject; a subject a `HandlerResult` is published *to* is not among them, so `js.publish` waits + for a stream acknowledgement that never comes, times out, and + `EventPublishingService.publish_handler_event` swallows it as a WARNING. A Core NATS listener + still sees the event, so a live subscriber looks healthy while a downstream JetStream consumer + gets nothing. Found and reproduced against a real broker in broker step 2; stated as an + `xfail(strict=True)` in `tests/integration/test_event_path.py`, and written up in + `docs/plans/2026-09-11-broker-integration-tests.md`. The fix is a design question rather than a + line: the client would have to learn its publishable subjects, and `topic_mapping` is read by + the publishing service rather than by the client. + +- ~~**`asbs` crashes on a Windows console**~~ **Closed** -- `use_utf8` at the CLI entry point. + Originally: still open from step 1, and the only thing standing between the CLI and the ASCII rule. Every command prints check marks and box drawing; on a cp1252 console the first one raises `UnicodeEncodeError` mid-command, after files have been written. - ~~**`docs/guides/cli-reference.md` still documents checks that have never existed.**~~ **Done in @@ -6456,7 +7092,8 @@ durable survival across reconnect and the shutdown drain are specified, implemen It is also a standing rule violation: source files are ASCII only. The fix is a sweep of the CLI's output glyphs, which is its own step rather than a drive-by inside a step about the generated project's shape. -- **`asbs create` writes absolute imports into a file that uses relative ones.** A generated +- ~~**`asbs create` writes absolute imports into a file that uses relative ones.**~~ **Closed** -- + twelve occurrences rewritten. Originally: a generated `main.py` imports `from .handlers import ...`; `asbs create handler` appends `from src.handlers.order_placed_handler import OrderPlacedHandler`. Both resolve, so nothing fails -- but the two styles in one file are how a later refactor breaks one of them. diff --git a/docs/plans/2026-09-11-broker-integration-tests.md b/docs/plans/2026-09-11-broker-integration-tests.md index 7b91cc73..a7b72e38 100644 --- a/docs/plans/2026-09-11-broker-integration-tests.md +++ b/docs/plans/2026-09-11-broker-integration-tests.md @@ -2,8 +2,8 @@ | | | |---|---| -| **Status** | Step 0 landed. Steps 1-3 next. | -| **Why** | Everything the multi-agent work claims about delivery is unit-tested against **mocked transports**. Nobody has watched any of it happen against a real broker. | +| **Status** | Steps 0-3 verified against a real broker, plus chores 1-3. | +| **Why** | Everything the multi-agent work claims about delivery was unit-tested against **mocked transports** and had never been watched against a real broker. Steps 0-3 and chores 1-3 now have been; the rest of *Chores* has not. | | **Scope** | NATS. Dapr needs a sidecar rather than a broker and is a chore below. | | **Depends on** | #80, the unit/integration split -- settled in step 0, because `tests/integration/` was not run by CI and sat at 29 failures. | | **Related** | `docs/plans/2026-08-28-multi-agent-grouping-changelog.md`, whose *Open points* names what only a real broker can settle. | @@ -14,28 +14,22 @@ list of things that feature asserts and nobody has yet verified. ## The constraint that shapes how this is written -There is no Docker on the machine this is authored on. The tests are written here and **run by the -developer**, who pastes failures back. That makes every step smaller than it would otherwise be and -makes the harness's first job to fail loudly and readably when the broker is absent. +Docker is on this machine, but **only the developer can reach it**. The tests are written here and +**run by the developer**, who pastes failures back. That makes every step smaller than it would +otherwise be, and makes the harness's first job to fail loudly and readably when the broker is +absent -- every round trip costs a message, so a test that fails obscurely costs two. The second constraint follows from it: **a broker test must skip, not fail, when the broker is not there.** An offline run of the whole suite stays green, and `-m integration` is how you ask for the -tests that need something running. +tests that need something running. This is not a formality: writing it the obvious way produced a +suite that *hung* offline rather than skipping, which is recorded in step 1 below. ## Plan - **Step 0 -- the unit/integration split (#80).** Landed. See below. -- **Step 1 -- the harness.** A `docker-compose.yml` standing up NATS with JetStream, and the - fixtures: a connection that skips the test when the server is unreachable, a stream created and - torn down per test, and an application built against the real URL. -- **Step 2 -- the path, end to end.** A real `AppBuilder` application on real NATS: publish a - CloudEvent, the handler runs, its `HandlerResult` is published to the outbound subject, and the - inbound message is acknowledged exactly once. This is the test the whole exercise is for. -- **Step 3 -- the acknowledgement lifecycle.** Against the real broker, not a mock of it: a - retryable failure naks and is redelivered after `nats_ack_wait`; a `CriticalHandlerError` terms - and is dead-lettered without redelivery; an event no handler matches is **acked**, not naked; a - payload that fails CloudEvent parsing terms without dispatching; and `nats_max_deliver` - exhaustion dead-letters. +- **Step 1 -- the harness.** Landed and green against NATS. See below. +- **Step 2 -- the path, end to end.** Landed and green. See below. +- **Step 3 -- the acknowledgement lifecycle.** Landed and green. See below. ## Chores @@ -44,12 +38,12 @@ real cluster can answer. ### Broker behaviour still unwatched -- **Queue-group distribution across replicas.** Two application instances sharing one queue group: +- ~~**Queue-group distribution across replicas.**~~ **Done.** Two application instances sharing one queue group: one delivery per message, not two. This is the claim that makes `replicaCount > 1` safe, and it is the one P1 rests on. - **A durable surviving reconnect.** Kill the connection mid-stream and assert nothing is redelivered that was already acked, and everything unacked is. -- **The shutdown drain.** In-flight handlers finish and their acknowledgements arrive *before* the +- ~~**The shutdown drain.**~~ **Done.** In-flight handlers finish and their acknowledgements arrive *before* the connection closes -- the ordering P0 fixed, and the one that makes duplicates certain on every deploy when it is wrong. - **Overlapping subjects in one queue group.** A wildcard and a literal it covers, both subscribed @@ -63,7 +57,7 @@ real cluster can answer. ### Grouping, against a real broker -- **C1 by observation.** Two agents in one `AgentGroup` on one NATS: each sees only its own topics, +- ~~**C1 by observation.**~~ **Done.** Two agents in one `AgentGroup` on one NATS: each sees only its own topics, and the durable and queue-group names are byte-identical to the same agent deployed alone. The unit tests assert the names; this would assert the consequence. - **The scheduler tick claim across real processes.** Three replicas in separate processes sharing @@ -95,6 +89,253 @@ real cluster can answer. ## Changelog +### Chores 1-3 -- grouping observed, replicas, and the shutdown drain + +Three of the *Chores* below, done as tests rather than left as notes. + +#### C1 by observation (`test_grouped_agents.py`) + +Two agents in one process on one broker and one stream. The unit tests assert the *names* the +framework derives; these assert the consequence: + +- an event on one agent's topic reaches that agent and not its neighbour, with both subscribed at + the same time -- and in both directions at once, so the test cannot pass by one agent being idle; +- the queue group is the **agent's name**, not the group's: `AgentGroup("integration", ...)` is the + deployment, and nothing broker-side carries it, or moving an agent to another group would move + its queue group with it; +- two agents subscribing to **the same subject** get a durable each, and both receive the event. + Sharing a durable would make them one consumer splitting the messages, so each agent would see + half its own events -- the failure P1 and P6 exist to prevent; +- the same agent, hosted alone and hosted beside a neighbour, presents byte-identical names. If + they differed, regrouping would strand an agent's backlog on a consumer nothing binds to any + more: a migration rather than a deployment change. + +#### Replicas and the shutdown drain (`test_delivery_once.py`) + +The second replica is a raw nats-py subscription bound to **the names the framework derived** -- +its deliver subject, its queue group -- rather than a second interpreter. That is the sharper +test: a real replica is identical to the first, so what makes distribution work is that both bind +the *same* names. Six messages, two binders, six deliveries in total rather than twelve. + +The drain is three tests, because "it works" is three claims: an in-flight handler **finishes** +when shutdown begins; its acknowledgement **reaches the broker before the connection closes** +(`num_ack_pending == 0`, read after the lifespan has ended); and a second process started on the +same durable is **not** given the message again. Any one of them false makes a rolling deploy +produce duplicates. + +#### A false alarm, found by the harness itself + +Every run logged: + +``` +ERROR JetStream stream '...' does not carry subject(s) [...] and could not be updated + (subject "it....>" overlaps with "it....orders.created"); + consumers filtering those subjects will fail to bind +``` + +and the consumers bound perfectly well. `_provision_stream` computed the subjects to add with a +**set difference**, so a stream an operator provisioned as `orders.>` looked as though it were +missing every literal underneath it. The client asked the server to add them, the server refused +the overlap, and the client then predicted a failure that does not happen -- on every connect, to +any deployment whose stream uses a wildcard. + +New `subject_is_covered_by` in `io_client_base.py` does the NATS match instead (`*` is one token, +`>` is one or more and only last), and `missing` is computed with it. Nine parametrised cases pin +the matcher, including the two easy ones to get wrong: `orders` is **not** covered by `orders.>`, +and `orders.created.eu` is not covered by `orders.*`. + +#### One fixture bug, worth recording because it looked like a framework hang + +`nats_app` and `nats_group` reset the process-global registry so a test can start a second +process. Put *inside* the lifespan, that cleared the components while shutdown was still running +-- and a shutdown draining an in-flight handler then never returned. It read as the framework +hanging; a standalone probe showed the real drain completing in 1.5s. The reset is now in a +`finally` around the whole `async with`. + +### Step 3 -- the acknowledgement lifecycle + +`tests/integration/test_acknowledgement_lifecycle.py`. Spec sec. 7.2 fixes one outcome table for +every transport; the unit tests assert the framework *decides* the right disposition, and these +assert the broker then *does* it. Five groups, one per row of the table: + +- a `RetryableHandlerError` naks and the same event id reaches the handler again after + `nats_ack_wait`, with `num_redelivered` confirming it from the broker's side; +- `CriticalHandlerError` and `InvalidEventError` term -- delivered once, and still once after the + ack-wait window has passed, which is the only way to tell a term from a slow nak; +- an event **no handler matches is acknowledged**, not naked. Finding no work in an event is a + normal outcome, and naking it would put a message nobody wants back on the queue for ever; +- a payload that is not a CloudEvent is termed **without being dispatched**, and dead-lettered + with its bytes unchanged -- there is no event id for the header, because nothing parsed; +- `nats_max_deliver` exhaustion stops the handler being called and dead-letters with + `deliveries-exhausted` rather than `terminal-failure`, because a broken handler and a rejected + event are different operational problems. + +`nats_ack_wait` is 2s in `integration_config`, which is what makes the redelivery assertions +affordable; the two "it did *not* come back" tests each wait two windows. + +**Green on the first run against a broker**, having been written entirely from the client's +source with no broker available. All five rows of the disposition table hold as specified. + +### Step 2 -- the path, end to end + +`tests/integration/test_event_path.py`. Four claims, each read off the **server** rather than off +the framework's account of itself: the handler receives what was published; its `HandlerResult` +reaches the subject `event_publishing.topic_mapping` names, as a new CloudEvent with its own id +and `app_name` as its source; the inbound message is acknowledged, with `num_ack_pending == 0` and +the ack floor advanced; and **it is not redelivered once `nats_ack_wait` has passed**. + +That last one is the test a mock cannot write. An unacknowledged JetStream message comes back +after `ack_wait` -- 2 seconds here -- so waiting the window out and finding the handler called once +is the acknowledgement working. `num_ack_pending == 0` alone would pass against a consumer that +had acked and then been redelivered for some other reason, so both are asserted. + +The test watches the outbound subject over **Core NATS**, not with a JetStream consumer of its +own: a durable would be broker-side state to tear down, and would bind to the same stream the +application's consumer is on. + +#### The framework's stream did not cover the subjects it publishes to -- now fixed + +The finding, and it is a live defect rather than a test-shaping detail. `_stream_subjects` returns +the subscribed topics, their `.>` forms, and the dead-letter subject. **A subject a handler result +is published *to* is not among them.** Probed against the broker, with the framework left to +provision its own stream: + +``` +stream subjects: ['blueprint-it.dead-letter', 'itdfbb736c0a.in', 'itdfbb736c0a.in.>'] +outbound covered: False +ERROR Failed to publish event to topic 'itdfbb736c0a.out': nats: timeout +WARNING Failed to publish handler event: nats: timeout +``` + +Three consequences, in order of how long they would take to find: + +- **The publish stalls.** `js.publish` waits for a stream acknowledgement that no stream will + send, so every outbound event costs the JetStream publish timeout before it gives up. +- **The event is not persisted.** A Core NATS subscriber *does* see it -- a JetStream publish + still puts the message on the subject -- so a live listener looks fine while a downstream + JetStream consumer receives nothing, which is the worst version of this to debug. +- **The failure is a WARNING.** `EventPublishingService.publish_handler_event` catches every + exception and logs; the handler has already returned, so its inbound message is acked and the + result is simply gone. + +Was stated as `test_the_outbound_subject_is_covered_too`, `xfail(strict=True)`. **Closed**: the +client now declares its publishable subjects and the stream carries them -- see the grouping +changelog's *Publishing is its own decision, and its subjects are declared*. The marker is gone +and the test is an ordinary one. The rest of step 2 still requests the `jetstream` fixture, which +is what a deployment with an operator-provisioned stream looks like. + +#### The harness had a collision of its own + +Every test used one `app_name`, so every test's client derived the same queue group and therefore +the same default dead-letter subject, `blueprint-it.dead-letter` -- which the client puts into the +stream it provisions. Two tests' streams then claim one subject and the second is refused: + +``` +BadRequestError: code=400 err_code=10065 description='subjects overlap with an existing stream' +``` + +Found by leaving a stream behind when a probe crashed and starting the next one. `nats_queue_group` +is now per test, so the dead-letter subject falls inside that test's own prefix. `nats_ack_wait` +dropped from 5s to 2s at the same time, so a test that waits the redelivery window out costs three +seconds rather than six. + +### Step 1 -- the harness + +Four files: `tests/integration/docker-compose.yml`, the fixtures in `conftest.py`, `helpers.py`, +and `test_harness.py`, which tests the harness itself before anything is tested with it. + +**The services.** NATS with JetStream and Redis, both published on localhost because the tests run +on the host: + +```yaml +command: ["--jetstream", "--store_dir=/tmp/nats", "--http_port=8222"] +``` + +`--jetstream` is not optional: without it the server accepts the connection and refuses the stream, +every subscription falls back to Core NATS, and steps 2 and 3 would be asserting redelivery and +`max_deliver` against a transport that has neither. **No volumes, deliberately** -- JetStream state +lives in the container and dies with it, so `down` then `up -d` is a clean broker. A durable +remembers its filter subject and its delivery count, so a leftover one can make a redelivery test +pass against last week's consumer. + +**Isolation per test.** `subject_prefix` is a fresh `it` per test and every subject goes +under it; `jetstream_stream` yields `IT_` and **deletes the stream afterwards** -- which +deletes its consumers with it. The fixture deliberately does *not* create the stream: the framework +creates its own in `_ensure_stream`, and a test of that behaviour has to watch it happen. + +**The application fixture waits for the subscriptions.** `NATSClient.subscribe()` returns +immediately and connects in a background retry task, so at the moment the lifespan returns the +agent is typically not yet on its topics. A test that published there would be asserting on a +race -- JetStream would hold the message and it would usually pass, Core NATS would drop it and it +would usually fail, and neither outcome would be about the thing under test. So `nats_app` enters +the lifespan directly (not through `TestClient`, which would run it on a second event loop in a +background thread) and then blocks on `subscriptions_ready`. + +**The offline path had to be fixed before it worked at all, and this is the useful finding.** The +obvious probe -- `nats.connect(...)`, catch, skip -- **hangs**. Two behaviours combine: +`localhost` resolves to `::1` first on Windows, an unreachable IPv6 port drops the SYN rather than +refusing it (`netstat` shows the connection sitting in `SYN_SENT`), so the attempt stalls for the +whole `connect_timeout`; and nats-py then retries the initial connect **indefinitely**, because +`max_reconnect_attempts` governs re-connection and not the first one. An offline `pytest +tests/integration` sat there until it was killed. The probe is now a bare TCP `open_connection` +under `asyncio.wait_for` -- no protocol handshake, no retry loop, a deadline the fixture owns -- +and the default URL is `nats://127.0.0.1:4222` rather than `localhost`. `nats_connection` also +passes `allow_reconnect=False`, so a broker that disappears mid-run fails the test that noticed +instead of parking it in the reconnect loop. + +Offline, the whole directory now skips in about a second, and every skip names the command: + +``` +SKIPPED [1] tests/integration/test_harness.py:59: No NATS server at nats://127.0.0.1:4222. + Start one with: docker compose -f tests/integration/docker-compose.yml up -d +``` + +**What `test_harness.py` asserts.** The broker (a Core NATS round trip, and that JetStream is +enabled); the isolation (a stream is this test's own, and no `IT_` stream from an earlier test +survived its teardown); and the application -- it connects and reaches `subscriptions_ready`, its +client reports healthy, its queue group is the agent's identity, the framework creates the stream +it was told to use and covers the subscribed subject, and an event published from outside the +process reaches a handler inside it with no handler left in flight. That last one is step 2 minus +the acknowledgement and the outbound result, and it is here so that a step-2 failure reads as being +about those rather than about whether anything arrives at all. + +Also fixed in passing: `test_shared_redis_cache.py` pointed at a `docker run` command instead of +the compose file, and its skip message carried a non-ASCII em-dash that rendered as a replacement +character in the terminal. + +**Verified.** `nats:2.10-alpine` accepted the compose file, and all ten harness tests passed on +the first run against it -- including the three that were most likely to be wrong, since they were +written from the client's source rather than from a run: JetStream's reported subject list matching +what the stream was created with, `_ensure_stream` creating the stream and covering the subscribed +subject, and an event published from outside the process reaching a handler inside it. The whole +directory runs in **29 seconds**. + +#### The one failure was a pre-existing test, and not about Redis + +`test_shared_redis_cache.py::test_two_processes_share_cache` failed the moment Redis was actually +running -- it had skipped for its whole life, so its first real run was this one: + +``` +subprocess.TimeoutExpired: Command '[...python.exe, -c, "...RedisCacheService..."]' + timed out after 10 seconds +``` + +The subprocess spends its budget **importing the framework**, not talking to Redis: measured at +**11.5s cold** for `from blueprint.agents.services.infrastructure.redis_cache_service import +RedisCacheService`, which pydantic-ai dominates. Ten seconds was below the floor. Three fixes in +`_run_reader`: + +- `IMPORT_BUDGET_SECONDS = 60`, named for what it actually pays for, with the measurement recorded + next to it. +- `TimeoutExpired` becomes an `AssertionError` that says it is an import-speed problem. The failure + was a `subprocess.py` traceback pointing at nothing in this repository. +- **A non-zero exit carrying stderr now fails with that stderr.** The child exits 1 for a genuine + cache miss, and every other error was being swallowed into the same `return None` -- so a broken + reader was indistinguishable from an empty cache, and reported as `read None, expected {...}`. + +It is the same lesson as the 29th failure in step 0: a test that has only ever skipped is a test +whose first real run is a first draft. + ### Step 0 -- the unit/integration split, settled (#80) **The prerequisite, and the reason it is one.** `tests/integration/` was **not run by CI at all** diff --git a/examples/document_summarizer/settings.toml b/examples/document_summarizer/settings.toml index a055ea15..e1065ef7 100644 --- a/examples/document_summarizer/settings.toml +++ b/examples/document_summarizer/settings.toml @@ -1,5 +1,5 @@ [default] -app_name = "Document Summarizer" +app_name = "document-summarizer" app_port = 8000 app_environment = "development" log_level = "INFO" diff --git a/examples/health_monitor/settings.toml b/examples/health_monitor/settings.toml index 5e3997b3..5de9cf5f 100644 --- a/examples/health_monitor/settings.toml +++ b/examples/health_monitor/settings.toml @@ -1,5 +1,5 @@ [default] -app_name = "Health Monitor" +app_name = "health-monitor" app_port = 8000 app_environment = "development" log_level = "INFO" diff --git a/examples/inventory_api/settings.toml b/examples/inventory_api/settings.toml index c5fc6c35..148a3aec 100644 --- a/examples/inventory_api/settings.toml +++ b/examples/inventory_api/settings.toml @@ -1,5 +1,5 @@ [default] -app_name = "Inventory API" +app_name = "inventory-api" app_port = 8000 app_environment = "development" log_level = "INFO" diff --git a/examples/order_event_pipeline/settings.toml b/examples/order_event_pipeline/settings.toml index 2660e883..e522c347 100644 --- a/examples/order_event_pipeline/settings.toml +++ b/examples/order_event_pipeline/settings.toml @@ -1,5 +1,5 @@ [default] -app_name = "Order Event Pipeline" +app_name = "order-event-pipeline" app_port = 8000 app_environment = "development" log_level = "INFO" diff --git a/examples/webhook_relay/settings.toml b/examples/webhook_relay/settings.toml index ef087372..42dfe157 100644 --- a/examples/webhook_relay/settings.toml +++ b/examples/webhook_relay/settings.toml @@ -1,5 +1,5 @@ [default] -app_name = "Webhook Relay" +app_name = "webhook-relay" app_port = 8000 app_environment = "development" log_level = "INFO" diff --git a/pytest.ini b/pytest.ini index c3256b69..4bbb4ece 100644 --- a/pytest.ini +++ b/pytest.ini @@ -10,4 +10,4 @@ pythonpath = examples/simple_event_processor examples/complex_agent markers = - integration: requires external services (e.g. Redis) — skipped in offline CI + integration: requires external services (NATS, Redis) — skipped in offline CI diff --git a/src/blueprint/agent_generator/assistant_integrations/CLAUDE.md b/src/blueprint/agent_generator/assistant_integrations/CLAUDE.md index 1da40eb3..b3258c65 100644 --- a/src/blueprint/agent_generator/assistant_integrations/CLAUDE.md +++ b/src/blueprint/agent_generator/assistant_integrations/CLAUDE.md @@ -41,7 +41,7 @@ class MyHandler(EventHandlerBase): - Every public method needs a docstring (one-liner is fine for simple methods) - Use `%s`-style args in log calls, not f-strings (deferred formatting) - Validate all external input with Pydantic at system boundaries -- Never hardcode secrets — use environment variables via `secrets.toml` +- Never hardcode secrets — use environment variables via `.secrets.toml` - **No `assert` statements in production code** — `assert` is only permitted in test files (`tests/`) - **All imports at the top of the file** — never inside methods, functions, or classes diff --git a/src/blueprint/agent_generator/base_files/Dockerfile b/src/blueprint/agent_generator/base_files/Dockerfile index 18e81616..03d807fd 100644 --- a/src/blueprint/agent_generator/base_files/Dockerfile +++ b/src/blueprint/agent_generator/base_files/Dockerfile @@ -80,14 +80,15 @@ COPY --chown=appuser:appuser agents.toml ./ # "Writable cache directory" section of docs/guides/deployment.md. RUN mkdir -p /app/.cache && chown -R appuser:appuser /app/.cache -# Note: secrets.toml is NOT copied into the image. -# Mount it at runtime via Docker secrets or volume mount. -# Example (Docker Swarm): -# docker run --secret secrets_file_id \ -# -e DYNACONF_SETTINGS=/run/secrets/secrets_file_id \ -# pir-agent:latest -# Example (Volume mount): -# docker run -v ./secrets.toml:/app/secrets.toml:ro pir-agent:latest +# Note: .secrets.toml is NOT copied into the image. Mount it at runtime, at that exact path -- +# the entry point loads ["settings.toml", ".secrets.toml"] relative to the working directory, so +# a file mounted under any other name is loaded by nothing and reports nothing. +# Example (volume mount): +# docker run -v ./.secrets.toml:/app/.secrets.toml:ro +# Example (Docker secret, which lands under /run/secrets): +# docker run --secret source=agent_secrets,target=/app/.secrets.toml +# An individual key can also be supplied as an environment variable instead, with no file at +# all: -e DYNACONF_MODEL_API_KEY=... ENV PYTHONPATH="/app/src" \ DYNACONF_ENVIRONMENT="production" \ diff --git a/src/blueprint/agent_generator/base_files/settings.txt b/src/blueprint/agent_generator/base_files/settings.txt index 8cd52b71..216a4f63 100644 --- a/src/blueprint/agent_generator/base_files/settings.txt +++ b/src/blueprint/agent_generator/base_files/settings.txt @@ -28,12 +28,22 @@ scheduler_mode = "in_process" # applications need it. Needs event_bus, and subscribes to nothing. # event_publishing_enabled = true -[default.logging] -level = "DEBUG" -format = "json" +# Logging and telemetry. These are flat keys, not sections: the framework reads +# log_level, log_format, otel_enabled and token_metrics_enabled from the top level +# of the environment table, so a [default.logging] or [default.observability] +# section would be read by nothing at all. +# +# log_level and log_format describe the process. If this project is later hosted as +# one agent of a group, the group's own settings file decides both and these two are +# reported and ignored -- one process configures logging once. +log_level = "DEBUG" +log_format = "text" -[default.observability] +# otel_enabled turns OpenTelemetry on and needs otel_endpoint to have somewhere to +# send to. token_metrics_enabled adds per-call token and latency metrics on top, and +# is read only when otel_enabled is true. otel_enabled = false +# otel_endpoint = "http://localhost:4317" token_metrics_enabled = true agent_runtime_configs diff --git a/src/blueprint/agent_generator/base_files/template_for_git_ignore.txt b/src/blueprint/agent_generator/base_files/template_for_git_ignore.txt index c3562ad4..af6a36c3 100644 --- a/src/blueprint/agent_generator/base_files/template_for_git_ignore.txt +++ b/src/blueprint/agent_generator/base_files/template_for_git_ignore.txt @@ -142,8 +142,8 @@ cython_debug/ # Generated Dapr components (from templates) custom/dapr/components/rabbitmq-pubsub.yaml -# Secrets -**/secrets.toml +# Secrets. Named exactly, not as a glob: the committed example template shares the prefix. +**/.secrets.toml .env.rabbitmq uv.lock diff --git a/src/blueprint/agent_generator/claude_docs/CLAUDE.md b/src/blueprint/agent_generator/claude_docs/CLAUDE.md index d37d12d7..b4a5e1b9 100644 --- a/src/blueprint/agent_generator/claude_docs/CLAUDE.md +++ b/src/blueprint/agent_generator/claude_docs/CLAUDE.md @@ -39,7 +39,7 @@ from pathlib import Path from blueprint.agents import AppBuilder, Config, AgentBuilder config = Config( - settings_files=["settings.toml", "secrets.toml"], + settings_files=["settings.toml", ".secrets.toml"], root_path=Path(__file__).parent.parent, ) @@ -156,7 +156,7 @@ class CleanupScheduler(SchedulerBase): async def on_startup(self) -> None: self._service = self.registry.get_service(CleanupService) - await super().on_startup() # required: without it the scheduler never runs + await super().on_startup() # required: without it the scheduler never runs async def on_shutdown(self) -> None: await super().on_shutdown() @@ -241,7 +241,7 @@ model_name = "gpt-4-turbo" model_temperature = 0.5 ``` -**secrets.toml** (never commit): `model_api_key = "sk-..."` +**.secrets.toml** (never commit): `model_api_key = "sk-..."` ## CLI (`asbs`) @@ -264,7 +264,7 @@ asbs dev [--port 8000] # Run dev server - All I/O must be `async`/`await` - `%s`-style args in log calls, not f-strings - Pydantic validation at system boundaries -- Secrets via `secrets.toml` — never hardcoded +- Secrets via `.secrets.toml` — never hardcoded - Context managers (`async with`) for external resources - **No `assert` statements in production code** — `assert` is only permitted in test files (`tests/`) - **All imports at the top of the file** — never inside methods, functions, or classes diff --git a/src/blueprint/agent_generator/claude_docs/agents/blueprint-builder.md b/src/blueprint/agent_generator/claude_docs/agents/blueprint-builder.md index 3acbfd53..4cd05e76 100644 --- a/src/blueprint/agent_generator/claude_docs/agents/blueprint-builder.md +++ b/src/blueprint/agent_generator/claude_docs/agents/blueprint-builder.md @@ -240,5 +240,5 @@ Add to `settings.toml`: 8. **Services contain ALL business logic** — one method per responsibility, not one giant method 9. **Handlers and APIs are thin delegation layers** — they call service methods 10. **Context managers for HTTP clients, files, DB connections** -11. **Secrets in `secrets.toml`** — never hardcoded +11. **Secrets in `.secrets.toml`** — never hardcoded 12. **System prompt is static** (no dynamic inputs) — **instruction prompt has dynamic inputs** 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 e37a5590..16b4ceb7 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 @@ -81,7 +81,7 @@ Add the component to the `AppBuilder` chain in `src/main.py`: If the component needs configuration: - Add runtime config to `settings.toml` under `[default.runtimes.]` for agents - Add topic mappings under `[default.event_publishing]` for handlers that publish events -- Add API key placeholders to `secrets.toml` for new AI providers +- Add API key placeholders to `.secrets.toml` for new AI providers ## Rules diff --git a/src/blueprint/agent_generator/claude_docs/skills/new-agent-service/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/new-agent-service/SKILL.md index 9ec98a79..9d00463e 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/new-agent-service/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/new-agent-service/SKILL.md @@ -32,7 +32,7 @@ Use the `blueprint-architect` agent to produce an architecture plan based on the - Which components are needed (handlers, services, agents, APIs, schedulers) - The dependency graph between components - The wiring order in `main.py` -- Configuration structure (settings.toml, secrets.toml) +- Configuration structure (settings.toml, .secrets.toml) ## Step 4: Implementation @@ -52,7 +52,7 @@ Ensure `settings.toml` has: - Event publishing topic mappings (if handlers publish events) - Cache settings (if caching is used) -Ensure `secrets.toml` has placeholder keys for any required API keys. +Ensure `.secrets.toml` has placeholder keys for any required API keys. ## Step 6: Verification diff --git a/src/blueprint/agent_generator/cli/commands/create.py b/src/blueprint/agent_generator/cli/commands/create.py index e4dbd72f..841c0fd7 100644 --- a/src/blueprint/agent_generator/cli/commands/create.py +++ b/src/blueprint/agent_generator/cli/commands/create.py @@ -139,7 +139,7 @@ def create_handler(args: Namespace) -> None: main_content = read_main_py(project_root) # Add import statement (use snake_case module name) - import_statement = f"from src.handlers.{module_name} import {class_name}" + import_statement = f"from .handlers.{module_name} import {class_name}" main_content = add_import_to_main(main_content, import_statement, "handler") # Add component registration @@ -150,7 +150,7 @@ def create_handler(args: Namespace) -> None: auto_registered = True print("✓ Auto-registered in src/main.py") - print(f" - Added import: from src.handlers.{module_name} import {class_name}") + print(f" - Added import: from .handlers.{module_name} import {class_name}") print(f" - Added registration: .with_handler({class_name})") except (FileNotFoundError, ValueError) as e: @@ -232,7 +232,7 @@ def create_service(args: Namespace) -> None: main_content = read_main_py(project_root) # Add import statement (use snake_case module name) - import_statement = f"from src.services.{module_name} import {class_name}" + import_statement = f"from .services.{module_name} import {class_name}" main_content = add_import_to_main(main_content, import_statement, "service") # Add component registration @@ -243,7 +243,7 @@ def create_service(args: Namespace) -> None: auto_registered = True print("✓ Auto-registered in src/main.py") - print(f" - Added import: from src.services.{module_name} import {class_name}") + print(f" - Added import: from .services.{module_name} import {class_name}") print(f" - Added registration: .with_service({class_name})") except (FileNotFoundError, ValueError) as e: @@ -389,7 +389,7 @@ def to_{_to_snake_case(response_class_name)}({_to_snake_case(domain_model_class_ from blueprint.agents.io.api.rest_api_base import RestApiBase -from src.models.{models_module_name} import {request_class_name}, {response_class_name} +from ..models.{models_module_name} import {request_class_name}, {response_class_name} logger = logging.getLogger(__name__) @@ -471,11 +471,11 @@ async def create_item(self, request: {request_class_name}) -> {response_class_na main_content = read_main_py(project_root) # Add models import (use snake_case module name) - models_import_statement = f"from src.models.{models_module_name} import {request_class_name}, {response_class_name}" + models_import_statement = f"from .models.{models_module_name} import {request_class_name}, {response_class_name}" main_content = add_import_to_main(main_content, models_import_statement, "api") # Add API import (use snake_case module name) - api_import_statement = f"from src.api.{module_name} import {class_name}" + api_import_statement = f"from .api.{module_name} import {class_name}" main_content = add_import_to_main(main_content, api_import_statement, "api") # Add component registration @@ -486,8 +486,8 @@ async def create_item(self, request: {request_class_name}) -> {response_class_na auto_registered = True print("✓ Auto-registered in src/main.py") - print(f" - Added import: from src.models.{models_module_name} import {request_class_name}, {response_class_name}") - print(f" - Added import: from src.api.{module_name} import {class_name}") + print(f" - Added import: from .models.{models_module_name} import {request_class_name}, {response_class_name}") + print(f" - Added import: from .api.{module_name} import {class_name}") print(f" - Added registration: .with_rest_api({class_name})") except (FileNotFoundError, ValueError) as e: @@ -508,8 +508,8 @@ async def create_item(self, request: {request_class_name}) -> {response_class_na print(f" from .{module_name} import {class_name}") if not auto_registered: print(" 6. Add to src/main.py:") - print(f" from src.models.{models_module_name} import {request_class_name}, {response_class_name}") - print(f" from src.api.{module_name} import {class_name}") + print(f" from .models.{models_module_name} import {request_class_name}, {response_class_name}") + print(f" from .api.{module_name} import {class_name}") print(f" .with_rest_api({class_name})") print(" 6. View docs at http://localhost:8000/docs") @@ -591,9 +591,13 @@ def create_agent(args: Namespace) -> None: settings_content += "model_temperature = 0.7\n" settings_content += "model_max_tokens = 2000\n" - settings_models_section = f"[default.runtimes.{snake_name}.models]" - if settings_models_section not in settings_content: - settings_content += f"\n{settings_models_section}\n" + # model_settings, not models: Config.get_ai_config reads + # runtimes..model_settings and hands it to the provider client verbatim. + # A [.models] table is read by nothing, so the block would look configured and + # be inert -- which is what it was. + model_settings_section = f"[default.runtimes.{snake_name}.model_settings]" + if model_settings_section not in settings_content: + settings_content += f"\n{model_settings_section}\n" # An effort level, not a model: the value was a copy of model_name, and the # scaffolder's own settings writer has always written "low" here. settings_content += 'openai_reasoning_effort = "low"\n' @@ -608,13 +612,17 @@ def create_agent(args: Namespace) -> None: logger.debug("Could not update settings.toml: %s", e) print(f"⚠ Could not update settings.toml: {e}") + # The registry key, derived before the attempt rather than inside it: the manual-registration + # instructions printed when auto-registration fails name it, and read_main_py raises for + # exactly the project that needs those instructions -- so deriving it inside the try left the + # fallback path printing an unbound local and ending in a traceback. + agent_name = snake_name if snake_name.lower().endswith("agent") else snake_name + "_agent" + # Attempt to auto-register in main.py auto_registered = False try: main_content = read_main_py(project_root) - agent_name = snake_name if snake_name.lower().endswith("agent") else snake_name + "_agent" - # An unbuilt AgentBuilder, and no configuration. AppBuilder.build() calls # agent.build(config.for_namespace()), so the model, prompt and metrics are # read from this agent's own configuration view. Building it here instead would bind it @@ -755,7 +763,7 @@ async def tick(self) -> None: main_content = read_main_py(project_root) # Add import statement (use snake_case module name) - import_statement = f"from src.schedulers.{module_name} import {class_name}" + import_statement = f"from .schedulers.{module_name} import {class_name}" main_content = add_import_to_main(main_content, import_statement, "scheduler") # Add component registration @@ -766,7 +774,7 @@ async def tick(self) -> None: auto_registered = True print("✓ Auto-registered in src/main.py") - print(f" - Added import: from src.schedulers.{module_name} import {class_name}") + print(f" - Added import: from .schedulers.{module_name} import {class_name}") print(f" - Added registration: .with_scheduler({class_name})") except (FileNotFoundError, ValueError) as e: diff --git a/src/blueprint/agent_generator/cli/commands/setup.py b/src/blueprint/agent_generator/cli/commands/setup.py index 2598fd38..ce18fb4a 100644 --- a/src/blueprint/agent_generator/cli/commands/setup.py +++ b/src/blueprint/agent_generator/cli/commands/setup.py @@ -117,24 +117,32 @@ def run(args: Namespace) -> None: print("=== Blueprint Agents Project Setup ===") print("This will create a complete project structure with handlers, services, APIs, and agents.") - # Get project name, sanitizing it to a valid Python class name + # The name is this agent's *identity*, not a directory to create. + # + # `asbs` is installed into the project's own virtual environment, so by the time it can be + # run at all the project directory exists and somebody is standing in it. Scaffolding into a + # `/` subdirectory would put the source one level below the environment that has to + # import it. The name is what `create_basic_config` derives everything else from: `app_name`, + # the agent namespace in `agents.toml`, the class names and the prompt filenames. + # + # This used to compute a `project_path = output_dir / project_name`, guard `--overwrite` + # with it and print it as the location -- while handing the generator `output_dir`. So the + # directory it protected was never created, and the location it printed was never written to. project_name = PartGeneratorBase.to_class_name(args.project_name) output_dir = Path(args.output_dir).absolute() - project_path = output_dir / project_name - # Check if output directory exists if not output_dir.exists(): print(f"Error: Output directory does not exist: {output_dir}", file=sys.stderr) sys.exit(1) - # Check if project already exists - if project_path.exists() and not args.overwrite: - print(f"Error: Project directory already exists: {project_path}", file=sys.stderr) - print("Use --overwrite to overwrite existing files", file=sys.stderr) + existing = [path.name for path in (output_dir / "src", output_dir / "agents.toml", output_dir / "settings.toml") if path.exists()] + if existing and not args.overwrite: + print(f"Error: {output_dir} already contains a scaffolded project ({', '.join(existing)})", file=sys.stderr) + print("Use --overwrite to write over it", file=sys.stderr) sys.exit(1) - print(f"\nCreating project: {project_name}") - print(f"Location: {project_path}") + print(f"\nScaffolding agent: {project_name}") + print(f"Location: {output_dir}") try: # Create basic configuration @@ -153,7 +161,7 @@ def run(args: Namespace) -> None: print("\n✓ Project created successfully!") print("\nProject structure:") - print(f" {project_name}/") + print(f" {output_dir.name}/ (this directory)") print(" ├── src/") print(" │ ├── main.py") print(" │ ├── handlers/") @@ -161,21 +169,21 @@ def run(args: Namespace) -> None: print(" │ ├── api/") print(" │ ├── models/") print(" │ └── prompts/") + print(" ├── tests/") print(" ├── agents.toml") print(" ├── settings.toml") - print(" ├── secrets.toml") + print(" ├── .secrets.toml") print(" ├── Dockerfile") print(" └── .gitignore") namespace = AgentMapPartGenerator.agent_namespace(config) print("\nNext steps:") - print(f" 1. cd {project_name}") - print(" 2. Review and edit the generated files") - print(" 3. Add your LLM API key to secrets.toml") - print(" (A secrets.toml with a placeholder has been created for you)") - print(" 4. Install dependencies: pip install -e .") - print(" 5. Run the service: asbs dev") - print(f" 6. View API docs at: http://localhost:8000/docs (this agent's routes are under /api/{namespace})") + print(" 1. Review and edit the generated files") + print(" 2. Add your LLM API key to .secrets.toml") + print(" (A .secrets.toml with a placeholder has been created for you)") + print(" 3. Run the generated tests: pytest") + print(" 4. Run the service: asbs dev") + print(f" 5. View API docs at: http://localhost:8000/docs (this agent's routes are under /api/{namespace})") print("\nsrc/main.py declares this agent; it does not build an application.") print(f"agents.toml names it '{namespace}', and that name is its identity on the broker,") diff --git a/src/blueprint/agent_generator/cli/commands/validate.py b/src/blueprint/agent_generator/cli/commands/validate.py index aa30e3f7..b14e1067 100644 --- a/src/blueprint/agent_generator/cli/commands/validate.py +++ b/src/blueprint/agent_generator/cli/commands/validate.py @@ -68,16 +68,25 @@ def run(args: Namespace) -> None: else: print(f"✓ Found {file_name}") - # Check for secrets template - secrets_example = project_dir / "secrets.toml.example" - secrets_file = project_dir / "secrets.toml" + # Check for secrets template. The leading dot is what DEFAULT_SETTINGS_FILES names, so a + # file without it is loaded by nothing -- which is why an undotted one is reported as the + # rename it needs rather than as a file that is simply missing. + secrets_example = project_dir / ".secrets.toml.example" + secrets_file = project_dir / ".secrets.toml" + undotted = project_dir / "secrets.toml" if not secrets_example.is_file(): - warnings.append("Missing secrets.toml.example template") + warnings.append("Missing .secrets.toml.example template") else: - print("✓ Found secrets.toml.example") + print("✓ Found .secrets.toml.example") if not secrets_file.is_file(): - warnings.append("Missing secrets.toml (copy from secrets.toml.example)") + if undotted.is_file(): + warnings.append( + "Found secrets.toml, which nothing loads: the framework reads '.secrets.toml'. " + "Rename it (git mv secrets.toml .secrets.toml) or its keys are invisible at startup." + ) + else: + warnings.append("Missing .secrets.toml (copy from .secrets.toml.example)") # Check for main.py main_file = project_dir / "src" / "main.py" diff --git a/src/blueprint/agent_generator/cli/main.py b/src/blueprint/agent_generator/cli/main.py index cfc49187..a3fa369c 100644 --- a/src/blueprint/agent_generator/cli/main.py +++ b/src/blueprint/agent_generator/cli/main.py @@ -2,12 +2,46 @@ import argparse import sys +from typing import TextIO from .commands import claude, create, dev, setup, validate +def use_utf8(stream: TextIO) -> None: + """Make ``stream`` able to carry the glyphs this CLI prints, or degrade instead of dying. + + Every command prints check marks, warning signs and box drawing. Python encodes stdout with + the locale encoding, which on Windows is cp1252, and cp1252 has none of those characters -- + so the first line of output raised ``UnicodeEncodeError``. Mid-command: ``asbs create + handler`` died after writing the handler file and before registering it in ``main.py``, + leaving the project half-edited. + + Two steps, because they fail for different reasons. UTF-8 is the fix and works wherever the + stream can be reconfigured at all. ``errors="replace"`` is the fallback for a stream that + refuses -- a redirected handle Python has already committed to an encoding, say -- where a + lost glyph is a ``?`` in a log rather than an abandoned command. + + This changes only what the CLI *prints*. Everything it *writes* stays ASCII, which is the + repository's rule for source, and ``tests/unit/agent_generator`` asserts it of the generated + project rather than leaving it to this docstring. + """ + reconfigure = getattr(stream, "reconfigure", None) + if reconfigure is None: # pragma: no cover - a stream replaced by something simpler + return + try: + reconfigure(encoding="utf-8", errors="replace") + except (ValueError, OSError, AttributeError): + try: + reconfigure(errors="replace") + except (ValueError, OSError, AttributeError): # pragma: no cover - nothing left to try + pass + + def main() -> None: """Entry point for the asbc CLI command.""" + use_utf8(sys.stdout) + use_utf8(sys.stderr) + parser = argparse.ArgumentParser( prog="asbs", description="Agentic Service Blueprint Shell - CLI for Blueprint Agents framework", @@ -24,12 +58,12 @@ def main() -> None: ) setup_parser.add_argument( "project_name", - help="Name of the project to create (e.g., 'invoice-processor')", + help="This agent's name: its app_name, its namespace in agents.toml and its class prefix (e.g. 'invoice-processor')", ) setup_parser.add_argument( "--output-dir", default=".", - help="Parent directory where project will be created (default: current directory)", + help="Directory to scaffold into, which is the project itself (default: current directory)", ) setup_parser.add_argument( "--overwrite", diff --git a/src/blueprint/agent_generator/generator/generator.py b/src/blueprint/agent_generator/generator/generator.py index f3316391..f99d1f9a 100644 --- a/src/blueprint/agent_generator/generator/generator.py +++ b/src/blueprint/agent_generator/generator/generator.py @@ -17,9 +17,11 @@ InitPartGenerator, MainPartGenerator, MapperPartGenerator, + PyprojectPartGenerator, + SecretsPartGenerator, ServicePartGenerator, SettingsPartGenerator, - SecretsPartGenerator, + TestsPartGenerator, ) logger = logging.getLogger(__name__) @@ -357,13 +359,29 @@ def _create_files_from_templates(self) -> None: # Create settings.toml SettingsPartGenerator(self.config, self.template_dir, "").create_file(out) - # Create secrets.toml with API key placeholder, and the template it is copied from. + # Create .secrets.toml with API key placeholder, and the template it is copied from. # Both into the project: create_file() with no argument writes relative to the current # working directory, so `asbs setup` left the secrets file wherever it was run from and # the project it scaffolded had none. SecretsPartGenerator(self.config, self.template_dir, "").create_file(out) SecretsPartGenerator(self.config, self.template_dir, "", example=True).create_file(out) + # pyproject.toml, and ONLY if the project has none. `asbs` is installed into the + # project's own environment, so by the time it can run there is usually a pyproject + # already -- somebody's, with their dependencies in it. Writing over that would be + # this tool destroying the file that made it runnable. The generated tests do not + # need it either: tests/conftest.py puts the project root on the path itself. + if not (Path(out) / "pyproject.toml").exists(): + PyprojectPartGenerator(self.config, self.template_dir, "").create_file(out) + else: + logger.info("pyproject.toml already exists; leaving it alone") + + # A tests/ directory: `asbs validate` requires one, so a scaffolded project used to + # fail the validation of the tool that made it. + TestsPartGenerator(self.config, self.template_dir, "tests", part="conftest").create_file(out) + TestsPartGenerator(self.config, self.template_dir, "tests", part="declaration").create_file(out) + TestsPartGenerator(self.config, self.template_dir, "tests", part="mapper").create_file(out) + # Create __init__ files with imports InitPartGenerator(self.config, self.template_dir, "src", out).create_file(out) InitPartGenerator(self.config, self.template_dir, "src/api", out).create_file(out) diff --git a/src/blueprint/agent_generator/generator/part_generators/__init__.py b/src/blueprint/agent_generator/generator/part_generators/__init__.py index 7c8910d0..f01d9a93 100644 --- a/src/blueprint/agent_generator/generator/part_generators/__init__.py +++ b/src/blueprint/agent_generator/generator/part_generators/__init__.py @@ -7,7 +7,9 @@ from .handler_part_generator import HandlerPartGenerator from .copy_part_generator import CopyPartGenerator from .settings_part_generator import SettingsPartGenerator +from .pyproject_part_generator import PyprojectPartGenerator from .secrets_part_generator import SecretsPartGenerator +from .tests_part_generator import TestsPartGenerator __all__ = [ "MainPartGenerator", @@ -21,5 +23,7 @@ "HandlerPartGenerator", "CopyPartGenerator", "SettingsPartGenerator", + "PyprojectPartGenerator", "SecretsPartGenerator", + "TestsPartGenerator", ] diff --git a/src/blueprint/agent_generator/generator/part_generators/pyproject_part_generator.py b/src/blueprint/agent_generator/generator/part_generators/pyproject_part_generator.py new file mode 100644 index 00000000..3c96a667 --- /dev/null +++ b/src/blueprint/agent_generator/generator/part_generators/pyproject_part_generator.py @@ -0,0 +1,61 @@ +from pathlib import Path +from typing import Any + +from .part_generator_base import PartGeneratorBase + + +class PyprojectPartGenerator(PartGeneratorBase): + """Write the ``pyproject.toml`` that makes a scaffolded project installable and testable. + + ``asbs setup`` printed *"Install dependencies: pip install -e ."* as its next step and wrote + no ``pyproject.toml``, so that command could not work; ``asbs validate`` then reported the + file as missing on a project the same tool had just produced. Both were true, and the missing + file is the one thing that fixes them together. + + It declares the framework as the only dependency and ``pytest`` as the only development one, + because everything else a project needs is a decision its author has not made yet. The pytest + configuration is the part worth having by default: ``pythonpath = ["."]`` is what lets the + generated tests import ``src.main`` the way the entry point does, and without it the first + ``pytest`` run in a new project fails on an import rather than on anything real. + """ + + def __init__(self, config: dict[str, Any], template_dir: str | Path, src_path: str) -> None: + super().__init__(config, template_dir, src_path) + self.template_file_name = None + self.template_vars["content"] = self._pyproject() + + def to_py_file_name(self) -> str: + return "pyproject.toml" + + def _pyproject(self) -> str: + distribution = self.camel_to_snake(self.config["name"]).replace("_", "-") + return f'''[project] +name = "{distribution}" +version = "0.1.0" +description = "{self.config["description"]}" +requires-python = ">=3.13" +dependencies = [ + "avs-blueprint-agents", +] + +[project.optional-dependencies] +dev = [ + "pytest", + "pytest-asyncio", +] + +[build-system] +requires = ["setuptools>=68"] +build-backend = "setuptools.build_meta" + +[tool.setuptools.packages.find] +include = ["src*"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +# The generated tests import `src.main`, which is how agents.toml names the declaration and how +# the container's entry point imports it. Without the project root on the path, the first pytest +# run in a new project fails on the import rather than on anything the author wrote. +pythonpath = ["."] +asyncio_mode = "auto" +''' diff --git a/src/blueprint/agent_generator/generator/part_generators/secrets_part_generator.py b/src/blueprint/agent_generator/generator/part_generators/secrets_part_generator.py index 8877418a..219cb881 100644 --- a/src/blueprint/agent_generator/generator/part_generators/secrets_part_generator.py +++ b/src/blueprint/agent_generator/generator/part_generators/secrets_part_generator.py @@ -6,12 +6,19 @@ class SecretsPartGenerator(PartGeneratorBase): - """Write ``secrets.toml``, or the ``secrets.toml.example`` it is copied from. + """Write ``.secrets.toml``, or the ``.secrets.toml.example`` it is copied from. - Two files with the same content and different fates: ``secrets.toml`` is what the project - runs against and is git-ignored, and ``secrets.toml.example`` is what is committed so that + Two files with the same content and different fates: ``.secrets.toml`` is what the project + runs against and is git-ignored, and ``.secrets.toml.example`` is what is committed so that the next person cloning the repository knows which keys to fill in. A scaffold that writes only the ignored one leaves nothing behind in the repository at all. + + **The leading dot is load-bearing.** ``DEFAULT_SETTINGS_FILES`` -- what ``entrypoint.py`` + hands to ``Config``, and the image's contract with the project -- is + ``["settings.toml", ".secrets.toml"]``. Written without the dot the file was never loaded by + anything, so a scaffolded project with the vLLM provider it is given failed + ``Config.validate()`` with ``Missing API key for vLLM provider`` before it could serve a + request. It is also Dynaconf's own convention, and the same shape as ``.env``. """ def __init__(self, config: dict[str, Any], template_dir: str | Path, src_path: str, *, example: bool = False) -> None: @@ -21,7 +28,7 @@ def __init__(self, config: dict[str, Any], template_dir: str | Path, src_path: s self.template_vars["content"] = self._create_secrets_content() def to_py_file_name(self) -> str: - return "secrets.toml.example" if self._example else "secrets.toml" + return ".secrets.toml.example" if self._example else ".secrets.toml" def _create_secrets_content(self) -> str: return '[default]\nmodel_api_key = "Your-API-Key"\n' diff --git a/src/blueprint/agent_generator/generator/part_generators/tests_part_generator.py b/src/blueprint/agent_generator/generator/part_generators/tests_part_generator.py new file mode 100644 index 00000000..db4a4bd9 --- /dev/null +++ b/src/blueprint/agent_generator/generator/part_generators/tests_part_generator.py @@ -0,0 +1,157 @@ +from pathlib import Path +from typing import Any + +from .part_generator_base import PartGeneratorBase + + +class TestsPartGenerator(PartGeneratorBase): + """Write the tests a scaffolded project starts with. + + **Two, and deliberately not more.** The scaffolded handler and service raise + ``NotImplementedError`` in the methods that matter -- they are where the author's business + logic goes -- so a generated test of ``handle_event`` could only assert that the stub is + still a stub, and would fail the moment it stopped being one. A test that has to be deleted + before the project can work is worse than no test: it teaches that the suite is noise. + + What is generated is the part that is true on day one and stays true: + + - **the declaration** -- ``src/main.py`` declares an unbuilt ``AppBuilder``, constructs + nothing when imported, and passes classes rather than instances. This is the file an author + edits most and the one whose mistakes are least visible: building it, or passing an + instance, both work standalone and both make the project impossible to host in a group. + - **the mapper** -- the one piece of generated code with real logic in it, so a round trip + through it is a real assertion. + + ``asbs validate`` requires a ``tests/`` directory, and until now ``asbs setup`` did not write + one, so a freshly scaffolded project failed its own validation. + """ + + def __init__(self, config: dict[str, Any], template_dir: str | Path, src_path: str, *, part: str) -> None: + super().__init__(config, template_dir, src_path) + self.template_file_name = None + self._part = part + builders = {"declaration": self._declaration_test, "mapper": self._mapper_test, "conftest": self._conftest} + self.template_vars["content"] = builders[part]() + + def to_py_file_name(self) -> str: + return "conftest.py" if self._part == "conftest" else f"test_{self._part}.py" + + def _conftest(self) -> str: + """Put the project root on the path, so the tests need no pytest configuration at all. + + ``test_declaration.py`` imports ``src.main`` -- the same import ``agents.toml`` names and + the container entry point performs -- which needs the project root importable. That can + come from ``pythonpath`` in ``pyproject.toml``, but a scaffolded project is scaffolded + *into* a project that already exists and already has a ``pyproject.toml`` of its own, and + editing somebody's build configuration to make generated tests run is not this tool's + business. Doing it here costs four lines and depends on nothing. + """ + return '''"""Make the project root importable, so `from src.main import agent` resolves. + +`src.main` is what `agents.toml` names and what `python -m blueprint.agents.entrypoint` imports, +so the tests import it the same way the runtime does rather than a way of their own. +""" + +import sys +from pathlib import Path + +PROJECT_ROOT = Path(__file__).resolve().parent.parent + +if str(PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(PROJECT_ROOT)) +''' + + def _declaration_test(self) -> str: + """A test of what ``src/main.py`` declares, and of what it must not do on import.""" + name = self.config["name"] + # service_layer is keyed by class name; the value describes it. + components = [f'"{service}"' for service in self.config["service_layer"]] + return f'''"""What ``src/main.py`` declares. + +``main.py`` is a *declaration*: every ``with_*`` call records what this agent is made of, and +nothing is constructed until the host calls ``build()``. That is what lets this project run on +its own and be hosted alongside other agents in one process. + +Both mistakes this guards against work fine standalone, which is why they are easy to make and +hard to notice: calling ``.build()`` in this file takes the configuration and the namespace that +the host is supposed to decide, and passing an already-constructed component +(``.with_service(MyService())`` instead of ``.with_service(MyService)``) creates it before any +namespace exists, so it belongs to the root for ever. +""" + +from blueprint.agents.app_builder import AppBuilder + +from src.main import agent + + +def test_main_declares_an_unbuilt_builder() -> None: + assert isinstance(agent, AppBuilder) + assert not agent.is_built, "main.py built the application on import; the host builds it" + + +def test_nothing_is_constructed_on_import() -> None: + """A declaration records; it does not create. Instances here would carry the root namespace.""" + constructed = [declaration.kind for declaration in agent.declarations if declaration.is_built] + + assert not constructed, f"main.py passes already-built {{constructed}} to the builder; pass the class instead" + + +def test_every_component_is_declared() -> None: + """Rename or remove a component and this is what tells you main.py was not updated.""" + kinds = [declaration.kind for declaration in agent.declarations] + + assert "service" in kinds + assert "handler" in kinds + + +def test_the_services_this_project_ships_are_declared() -> None: + declared = {{ + getattr(declaration.target, "__name__", type(declaration.target).__name__) + for declaration in agent.declarations + if declaration.kind == "service" + }} + + assert declared == {{{", ".join(components)}}}, f"{name} declares {{declared}}" +''' + + def _mapper_test(self) -> str: + """A round trip through the generated mapper, which is real code rather than a stub.""" + name = self.config["name"] + snake = self.camel_to_snake(name) + return f'''"""The mapper, which is the one piece of generated code with logic in it. + +DTOs are what the REST API speaks; domain models are what the service works on. The mapper is +the boundary, and a round trip through it is the cheapest statement that the boundary is intact +-- if a field is added to one side and not the other, this is what says so. +""" + +from src.models.{snake}.dto import {name}RequestDTO, {name}ResponseDTO +from src.models.{snake}.mapper import {name}Mapper + + +def test_a_request_becomes_a_domain_model() -> None: + request = {name}RequestDTO(id="abc", data={{"key": "value"}}) + + model = {name}Mapper.from_{snake}_request_dto(request) + + assert model.id == "abc" + assert model.data == {{"key": "value"}} + + +def test_a_domain_model_becomes_a_response() -> None: + model = {name}Mapper.from_{snake}_request_dto({name}RequestDTO(id="abc", data={{"key": "value"}})) + + response = {name}Mapper.to_{snake}_response_dto(model) + + assert isinstance(response, {name}ResponseDTO) + assert (response.id, response.data) == ("abc", {{"key": "value"}}) + + +def test_the_round_trip_changes_nothing() -> None: + """What the test is really for: a field added on one side and forgotten on the other.""" + request = {name}RequestDTO(id="abc", data={{"key": "value"}}) + + response = {name}Mapper.to_{snake}_response_dto({name}Mapper.from_{snake}_request_dto(request)) + + assert response.model_dump() == request.model_dump() +''' diff --git a/src/blueprint/agents/agent/agent_builder.py b/src/blueprint/agents/agent/agent_builder.py index b6e1aaba..9eea8bdf 100644 --- a/src/blueprint/agents/agent/agent_builder.py +++ b/src/blueprint/agents/agent/agent_builder.py @@ -375,6 +375,16 @@ def build(self, config: Config | None = None, **kwargs: Any) -> AgentRuntime: if kwarg not in allowed: raise ValueError(f"Unexpected keyword argument for Agent: {kwarg}") + # AgentRuntime takes its registry name as a required argument and nothing was passing + # one: AppBuilder.with_agent(agent, name=...) keeps that name on the *declaration* and + # assigns it after construction, so this call raised TypeError before it could get + # there. The builder already knows what the runtime is called -- runtime_name is the + # key its configuration is read under -- so that is the name it is built with, and a + # differing declaration name still renames it afterwards. + # + # setdefault rather than a positional argument: build(config, name=...) may legitimately + # carry one, and a positional would make that a duplicate-argument TypeError. + kwargs.setdefault("name", self._runtime_name) runtime = AgentRuntime( system_prompt=self._system_prompt, tools=self._tools if self._tools else [], diff --git a/src/blueprint/agents/agent/agent_runtime.py b/src/blueprint/agents/agent/agent_runtime.py index 8b2057c8..a0807a86 100644 --- a/src/blueprint/agents/agent/agent_runtime.py +++ b/src/blueprint/agents/agent/agent_runtime.py @@ -38,8 +38,15 @@ def name(self) -> str | None: @name.setter def name(self, value: str | None) -> None: - """Update name in both the pydantic_ai Agent and the Component registry.""" - Agent.name.fset(self, value) # type: ignore[attr-defined] # pydantic_ai side-effects (future-proof) + """Rename through ``Component``, which renames the pydantic_ai side with it. + + Both classes keep the name in ``self._name`` -- ``Agent.name`` reads that field and its + setter writes nothing else -- so ``Component``'s setter is the whole rename: it qualifies + the value with this agent's namespace, moves the registry key, and writes the field both + getters read. Calling ``Agent.name.fset`` first, as this used to, put the *unqualified* + value into that field before ``Component``'s setter read it as "the name I am registered + under", so the rename went looking for a key that had never existed. + """ Component.name.fset(self, value) # type: ignore[attr-defined] # registry update + self._name def __init__( @@ -49,14 +56,22 @@ def __init__( ) -> None: """Initialize the agent runtime. + Registration is ``Component``'s, not this class's. It used to be done here by hand -- + ``Component.__init__(should_register=False)`` followed by + ``self.registry.add_component(name, self)`` -- which registered the runtime under the + **bare** name while every other component in the process carries its namespace. Two + agents in one group whose runtimes shared a name therefore collided on one key instead + of becoming ``orders_assistant`` and ``billing_assistant``, and ``base_name`` was left + saying ``agent_runtime``. ``Component.__init__`` qualifies, registers and sets both + halves; ``Registry._lookup`` qualifies on the way in too, so ``get_agent("assistant")`` + still resolves within the calling agent. + Args: name: Name used for registry lookup and logging **kwargs: Keyword arguments forwarded to pydantic_ai.Agent """ Agent.__init__(self, name=name, **kwargs) - Component.__init__(self, should_register=False) - self._name = name - self.registry.add_component(name, self) + Component.__init__(self, name=name) self._ai_client: AIClientBase | None = None self._prompt_cache: dict[str, str] = {} diff --git a/src/blueprint/agents/agent_group.py b/src/blueprint/agents/agent_group.py index 3733259d..b39035b1 100644 --- a/src/blueprint/agents/agent_group.py +++ b/src/blueprint/agents/agent_group.py @@ -26,7 +26,9 @@ import logging import sys from collections.abc import Collection, Mapping +from enum import Enum from pathlib import Path +from types import BuiltinFunctionType, FunctionType, MethodType, ModuleType from fastapi import FastAPI @@ -38,6 +40,44 @@ logger = logging.getLogger(__name__) +SHAREABLE_TYPES: tuple[type, ...] = ( + type(None), + bool, + int, + float, + complex, + str, + bytes, + frozenset, + range, + Enum, + type, + FunctionType, + BuiltinFunctionType, + MethodType, + ModuleType, +) +"""What one declaration may hand to two agents at once: code, and values that cannot change. + +The distinction is **code versus data**. Two agents built from one declaration already share the +component *class* -- that is what a declaration is -- and a class, a function or a module is +behaviour rather than something an agent can write into. A list, a dict, a set or an ordinary +instance is state, and a shared one is a channel between two agents that nothing else in the +framework would let them open. + +Arbitrary instances are refused even when their author considers them immutable: "frozen" is not +decidable from the object, and the cost of being wrong is silent cross-agent sharing while the +cost of being conservative is one keyword in a declaration. +""" + + +def is_shareable(value: object) -> bool: + """Whether ``value`` may be handed to more than one agent. See :data:`SHAREABLE_TYPES`.""" + if isinstance(value, tuple): + return all(is_shareable(item) for item in value) + return isinstance(value, SHAREABLE_TYPES) + + class AgentGroup: """The agents one process hosts, and the single application they become. @@ -311,6 +351,7 @@ def assemble(self, config: Config) -> FastAPI: for namespace, builder in self._agents.items(): self._refuse_what_a_group_cannot_honour(namespace, builder) + self._refuse_state_shared_between_agents() # Before anything is constructed, and before the root builder adopts the configuration: # every component reads its keys through its agent's scoped view during build(), so a @@ -333,6 +374,62 @@ def assemble(self, config: Config) -> FastAPI: return root.build() + def _refuse_state_shared_between_agents(self) -> None: + """Refuse one declaration handing the same mutable object to two agents. + + A group's central property is that one declaration can serve several agents -- the same + ``AppBuilder`` named twice in the map, replayed once per namespace. Replay re-issues the + recorded call, and ``_construct`` spreads the recorded ``kwargs`` into the constructor; + ``**`` copies the *mapping* and not its values, so both agents are constructed with the + very same object:: + + declaration = AppBuilder().with_service(Ledger, holdings=[]) + AgentGroup("finance", {"orders": declaration, "billing": declaration}) + # orders' ledger and billing's ledger hold one list + + Whatever one agent puts in it, the other reads. That is a channel between two agents that + nothing else in the framework would let them open, and it needs no lookup at all. + + **Refused rather than copied.** ``deepcopy`` would close the hole silently and change what + the author wrote -- a connection pool or a client passed deliberately would be duplicated + per agent, and objects holding a lock or a socket cannot be copied at all, so the failure + would arrive later and somewhere else. A refusal arrives at assembly, names the argument, + and leaves the decision where it belongs. + + The fix needs no new API: a declaration's target may be a **zero-argument factory**, which + is called once per agent, so ``with_service(lambda: Ledger(holdings=[]))`` gives each agent + its own. Declaring the component separately per agent works too. + + Only a declaration used by **more than one agent** is checked. A single-agent declaration + may carry whatever its author likes, because there is nobody to share it with -- which is + *standalone is permissive, the group has rules* applied to the one case that is genuinely + about the group. + + Raises: + ValueError: naming the agents, the call, the argument and the way out. + """ + by_identity: dict[int, list[str]] = {} + builders: dict[int, AppBuilder] = {} + for namespace, builder in self._agents.items(): + by_identity.setdefault(id(builder), []).append(namespace) + builders[id(builder)] = builder + + for identity, namespaces in by_identity.items(): + if len(namespaces) < 2: + continue + for declaration in builders[identity].declarations: + for argument, value in declaration.kwargs.items(): + if is_shareable(value): + continue + raise ValueError( + f"One declaration serves agents {', '.join(repr(name) for name in namespaces)}, and its " + f"{declaration.kind} call passes '{argument}' as a {type(value).__name__}, which every one " + "of them would then hold the same object of -- so a value written by one agent is read by " + "the others. Pass a zero-argument factory instead, which is called once per agent " + f"(with_{declaration.kind}(lambda: ...)), or declare this component separately for each " + "agent. Immutable values and classes, functions and modules are shared as they are." + ) + @staticmethod def _refuse_what_a_group_cannot_honour(namespace: str, builder: AppBuilder) -> None: """Refuse a declaration a group cannot place, naming the agent and the fix. diff --git a/src/blueprint/agents/clients/io/io_client_base.py b/src/blueprint/agents/clients/io/io_client_base.py index 1a795ce5..9f08586a 100644 --- a/src/blueprint/agents/clients/io/io_client_base.py +++ b/src/blueprint/agents/clients/io/io_client_base.py @@ -99,6 +99,75 @@ async def resume_consumption(self) -> None: """What a subject a component publishes to or subscribes to cannot contain.""" +def subject_is_covered_by(subject: str, pattern: str) -> bool: + """Whether ``pattern`` -- a NATS subject, possibly with wildcards -- already matches ``subject``. + + NATS has two wildcards: ``*`` stands for exactly one token, and ``>`` for one or more and only + as the last token. A stream configured with ``orders.>`` therefore already captures + ``orders.created``, even though the two strings are not equal. + + This exists because comparing them as strings says otherwise. A stream provisioned by an + operator with a wildcard looks, to a set difference, as though it is missing every literal + subject the client wants -- so the client asks the server to add them, and the server refuses + the update with *subject "orders.>" overlaps with "orders.created"*. What the client then logs + is that consumers filtering those subjects will fail to bind, which is false: the wildcard + covers them and they bind perfectly well. The message is the defect, not the stream. + + Args: + subject: A concrete subject, with no wildcards of its own. + pattern: A stream subject, which may have them. + + Returns: + Whether a message on ``subject`` would be captured by ``pattern``. + """ + if pattern == subject: + return True + + pattern_tokens = pattern.split(".") + subject_tokens = subject.split(".") + + for index, token in enumerate(pattern_tokens): + if token == ">": + # Matches the rest, and there has to be a rest: 'a.>' does not match 'a'. + return index < len(subject_tokens) + if index >= len(subject_tokens): + return False + if token != "*" and token != subject_tokens[index]: + return False + + return len(pattern_tokens) == len(subject_tokens) + + +def validate_publish_subject(subject: str, *, source: str) -> str: + """Return ``subject`` unchanged, or raise if it cannot be published to. + + The sibling of :func:`validate_subject_segment`, for a whole subject rather than one of its + segments -- so dots are legal here and only whitespace, ``*`` and ``>`` are not. + + **A wildcard is the one worth naming.** ``orders.*`` is a perfectly good thing to *subscribe* + to and a meaningless thing to publish to: NATS treats it as a literal subject, so the message + goes to a subject spelled with an asterisk and every subscriber to the pattern misses it. + Nothing fails, and nothing arrives. Refusing it at startup is the only place that is cheap. + + Args: + subject: The subject something would publish to. + source: Where it came from, named in the error so the fix is obvious. + + Raises: + ValueError: if the subject is empty or contains whitespace, ``*`` or ``>``. + """ + if not subject: + raise ValueError(f"{source} is empty, so there is nothing to publish to.") + if _SUBJECT_UNUSABLE.search(subject): + raise ValueError( + f"{source} is '{subject}', which cannot be published to: whitespace, '*' and '>' are not usable in a " + "subject a message is sent to. A wildcard is only meaningful when subscribing -- published, it is " + "taken literally, so the message lands on a subject with an asterisk in it and no subscriber to the " + "pattern receives it." + ) + return subject + + def validate_subject_segment(segment: str, *, source: str, subject: str) -> str: """Return ``segment`` unchanged, or raise if it cannot appear in a subject. diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 63ada1fd..b37e9ec7 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -23,7 +23,7 @@ from ...models.api import ComponentHealth from ...models.errors import DeliveryDisposition, disposition_for from ...models.events import CloudEvent -from .io_client_base import IOClientBase, validate_subject_segment +from .io_client_base import IOClientBase, subject_is_covered_by, validate_publish_subject, validate_subject_segment logger = logging.getLogger(__name__) @@ -139,6 +139,8 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: self._nats_client: NatsClient | None = None self._js: JetStreamContext | None = None self._use_jetstream: bool = False + self._publish_via_jetstream: bool = False + self._publish_subjects: set[str] = set() self._subscriptions: list[Any] = [] self._topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = {} self._queue_group: str = "" @@ -260,6 +262,89 @@ def _resolve_queue_group(self) -> str: "Without one every replica processes every message." ) + # ------------------------------------------------------------------ + # Publishing (mode and subjects) + # ------------------------------------------------------------------ + + def _resolve_publish_mode(self) -> bool: + """Whether this client publishes through JetStream. ``False`` means Core NATS. + + **Publishing and consuming are two decisions, and now have two keys.** They used to share + ``nats_use_jetstream``: that key exists so *consumers* can be durable, and ``publish()`` + read the same flag -- so turning durability on for consumption silently made every + outbound event a JetStream publish as well. Nobody chose that, and it is the wrong + default for an event nothing needs to persist, where a Core publish is cheaper and + cannot stall. + + ``nats_publish_mode`` is ``"core"`` or ``"jetstream"``. Unset, it follows + ``nats_use_jetstream``, so no existing deployment changes. + + Raises: + ValueError: for any other value, naming what each one means. + """ + raw = self.config.get("nats_publish_mode", None) + mode = str(raw or "").strip().lower() + if not mode: + return bool(self._use_jetstream) + if mode not in ("core", "jetstream"): + raise ValueError( + f"Config key 'nats_publish_mode' must be 'core' or 'jetstream', got {raw!r}. 'core' is " + "fire-and-forget: the message reaches whoever is subscribed at that moment and is not stored. " + "'jetstream' stores it in the stream, so a consumer that was not running still receives it -- and " + "it requires the subject to be one this client declares, see 'nats_publish_subjects'." + ) + return mode == "jetstream" + + def _resolve_publish_subjects(self) -> set[str]: + """The subjects this client may publish to, declared rather than discovered. + + A JetStream publish is a request/reply: the server stores the message and answers with a + ``PubAck``. **If no stream captures the subject, no answer ever comes** -- the publish + waits and times out, and ``EventPublishingService.publish_handler_event`` logs it and + moves on. A Core NATS subscriber still sees the message, because the publish did go out, + so a live listener looks healthy while nothing is stored and a JetStream consumer + downstream receives nothing at all. That was the behaviour before this existed: + ``_stream_subjects`` covered what the client *subscribed* to and nothing it published to. + + Two sources, because there are two ways an outbound subject is chosen: + + - ``event_publishing.topic_mapping`` -- the configured event-type-to-topic map, which is + how a ``HandlerResult`` is routed and so where nearly every outbound subject is already + written down; + - ``nats_publish_subjects`` -- an explicit list, for a caller that passes ``topic=`` to + ``publish_event`` directly and therefore never appears in the mapping. + + Every one is validated, because a wildcard published to is taken literally by NATS: the + message lands on a subject with an asterisk in it and no subscriber to the pattern gets + it. + """ + subjects: set[str] = set() + + mapping = self.config.get("event_publishing.topic_mapping", {}) or {} + if hasattr(mapping, "items"): + for event_type, routing in mapping.items(): + topic = routing.get("topic") if hasattr(routing, "get") else None + if topic: + source = f"The topic mapped from event type '{event_type}'" + subjects.add(validate_publish_subject(str(topic), source=source)) + + declared = self.config.get("nats_publish_subjects", []) or [] + if isinstance(declared, list): + for subject in declared: + subjects.add(validate_publish_subject(str(subject), source="A subject in 'nats_publish_subjects'")) + + return subjects + + @property + def publish_subjects(self) -> tuple[str, ...]: + """The subjects this client declares it may publish to, sorted.""" + return tuple(sorted(self._publish_subjects)) + + @property + def publishes_via_jetstream(self) -> bool: + """Whether an outbound event is stored in the stream or sent fire-and-forget.""" + return self._publish_via_jetstream + # ------------------------------------------------------------------ # Consumer settings (P3) # ------------------------------------------------------------------ @@ -478,6 +563,8 @@ async def connect(self) -> None: ) self._client = self._nats_client self._use_jetstream = self.config.get("nats_use_jetstream", False) + self._publish_via_jetstream = self._resolve_publish_mode() + self._publish_subjects = self._resolve_publish_subjects() if self._use_jetstream: try: self._js = self._nats_client.jetstream() @@ -485,6 +572,7 @@ async def connect(self) -> None: except Exception as e: logger.warning("JetStream initialization failed, falling back to Core NATS: %s", str(e)) self._use_jetstream = False + self._publish_via_jetstream = False if not self._use_jetstream: logger.info("Connected to NATS server (Core NATS) at %s as '%s'", nats_url, self._connection_name) @@ -651,7 +739,7 @@ async def publish(self, topic: str, event: CloudEvent[Any], routing_key: str | N try: event_data = json.dumps(dict(event)).encode() - if self._use_jetstream and client.jetstream(): + if self._publish_via_jetstream and client.jetstream(): ack = await client.jetstream().publish(topic, event_data) logger.debug("Published event to JetStream topic '%s' (seq: %d): %s", topic, ack.seq, event.id) else: @@ -766,6 +854,11 @@ def _stream_subjects(self) -> set[str]: subjects.add(f"{topic}.>") if self._tuning and self._tuning.dead_letter_subject: subjects.add(self._tuning.dead_letter_subject) + # What this client publishes, when it publishes durably. Without these the stream has + # no subject matching the outbound message, so the publish waits for an acknowledgement + # that never comes -- see _resolve_publish_subjects. + if self._publish_via_jetstream: + subjects |= self._publish_subjects return subjects async def _provision_stream(self) -> None: @@ -792,8 +885,11 @@ async def _provision_stream(self) -> None: logger.info("Created JetStream stream '%s' with subjects %s", stream, sorted(wanted)) return + # Not a set difference: a stream an operator provisioned as 'orders.>' already captures + # 'orders.created', and asking the server to add the literal is refused as an overlap -- + # which used to be reported as "consumers will fail to bind" when they bind fine. existing = set(info.config.subjects or []) - missing = wanted - existing + missing = {subject for subject in wanted if not any(subject_is_covered_by(subject, pattern) for pattern in existing)} if not missing: return diff --git a/src/blueprint/agents/component/component.py b/src/blueprint/agents/component/component.py index 71df5d43..5d113dca 100644 --- a/src/blueprint/agents/component/component.py +++ b/src/blueprint/agents/component/component.py @@ -166,8 +166,9 @@ def name(self, value: str) -> None: The new name is qualified with this component's namespace, for the same reason the constructor qualifies one: a name that does not carry its agent is a name that cannot be - told apart from a neighbour's in a log. ``qualified_component_name`` is idempotent, so a - caller that has already qualified the name is not punished for it. + told apart from a neighbour's in a log. Pass the **bare** name: + ``qualified_component_name`` is deliberately *not* idempotent -- see its own docstring + for why -- so an already-qualified value is qualified a second time. Raises: ValueError: if the component is not registered under its current name, or if the new diff --git a/src/blueprint/agents/component/registry.py b/src/blueprint/agents/component/registry.py index c2201c99..9a5249b3 100644 --- a/src/blueprint/agents/component/registry.py +++ b/src/blueprint/agents/component/registry.py @@ -175,14 +175,35 @@ def _all_of_type(self, component_type: Any) -> list[Any]: return [component for component in self._components.values() if isinstance(component, component_type)] def _effective_namespace(self, namespace: str | None) -> str | None: - """Resolve an omitted ``namespace`` argument. + """Resolve an omitted ``namespace`` argument, and refuse one that names a neighbour. On the application's own registry an omitted namespace means *every* namespace, which is what ``build()`` and the lifespan need when they iterate. On a view it means *that view's* - namespace, which is what a component needs when it looks up a collaborator. An explicit - argument always wins, on either. - """ - return self._default_namespace if namespace is None else namespace + namespace, which is what a component needs when it looks up a collaborator. + + **A view may name its own namespace or the root, and no other.** An explicit argument + used to win unconditionally, which made every agent one keyword away from its + neighbours: ``self.registry.get_component("ledger", namespace="orders")`` resolved + orders' instance from inside billing. Unlike the fallback in :meth:`_lookup`, this is + refused rather than answered with an absence -- the caller named another agent, so it is + a decision rather than a near miss, and a silent ``None`` would leave it looking like the + neighbour had nothing registered. + + Nothing in the framework is caught by this. Every component that passes a namespace + passes ``self.namespace`` -- its own -- and the three places that pass an arbitrary one + (``EventProcessingService``, ``DaprEventing``, ``NamespaceSupervisor``) are constructed + at the root, so they hold the application registry rather than a view. + """ + if namespace is None: + return self._default_namespace + if self._default_namespace and namespace not in (self._default_namespace, ROOT_NAMESPACE): + raise RuntimeError( + f"The registry view for namespace '{self._default_namespace}' was asked for namespace " + f"'{namespace}'. An agent resolves its own components and the root's shared ones; a " + "neighbour's belong to that agent alone. Drop the 'namespace' argument to resolve within " + "this agent." + ) + return namespace def _lookup(self, name: str, namespace: str | None) -> Any | None: """Return the component registered under ``name`` for ``namespace``, or ``None``. @@ -195,13 +216,29 @@ def _lookup(self, name: str, namespace: str | None) -> Any | None: A caller that already holds the qualified name is unaffected: qualifying it a second time simply misses, and the bare lookup then finds it. + + **The fallback reaches the root, and only the root.** A neighbour's registry key is a + bare name in the same dictionary -- ``orders_ledger`` is what orders' component is + registered under -- so the fallback used to resolve it: asking billing's view for + ``"orders_ledger"`` returned orders' instance, with nothing but a name the asking agent + already knows from the group. What the fallback found is therefore checked for ownership, + and a neighbour's component is reported **absent** rather than refused. Absence is the + stronger answer: a refusal naming the agent would confirm that the neighbour exists, + which is the same class of disclosure in a smaller size. + + The two owners that pass are the root (``""``), which holds what the process genuinely + shares, and the asking namespace itself, which is the already-qualified case above. """ namespace = self._effective_namespace(namespace) if namespace: qualified = qualified_component_name(namespace, name) if qualified in self._components: return self._components[qualified] - return self._components.get(name) + + found = self._components.get(name) + if found is not None and namespace and namespace_of(found) not in (ROOT_NAMESPACE, namespace): + return None + return found @property def correlation_context(self) -> CorrelationContext: @@ -272,11 +309,27 @@ def _cache_owner(self, namespace: str | None) -> str: a lookup that ranged over the process would be the cross-agent sharing spec sec. 8 exists to prevent. + **A view may name its own agent or the root, and no other**, for the reason + :meth:`_effective_namespace` gives -- and it matters more here, because a cache is where + an agent's data accumulates rather than merely passes through. ``get_cache("default", + namespace="orders")`` from inside billing used to return orders' live store, keys and + all. The check is repeated rather than shared because the two resolvers mean different + things by an omitted argument, which is the whole reason they are separate functions. + Args: namespace: The agent named at the call site, or ``None`` to take it from this object. + + Raises: + RuntimeError: if a view names an agent that is neither itself nor the root. """ if namespace is not None: + if self._default_namespace and namespace not in (self._default_namespace, ROOT_NAMESPACE): + raise RuntimeError( + f"The registry view for namespace '{self._default_namespace}' was asked for the caches of " + f"namespace '{namespace}'. A cache belongs to the agent that declared it (spec sec. 8), and " + "no agent reads another's. Drop the 'namespace' argument to reach this agent's own." + ) return namespace return self._default_namespace or ROOT_NAMESPACE diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index 19645309..7533f049 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -37,6 +37,22 @@ class ConfigError(Exception): """ +SHARED_NESTED_PREFIXES = frozenset({"cache", "event_publishing", "runtimes", "runtime"}) +"""The dotted sections that belong to the process rather than to an agent. + +Flat is the norm in this tree -- ``app_port``, ``log_level``, ``nats_url`` and the rest are +top-level keys -- and these four are the only prefixes the framework itself reads a dotted key +under: ``cache.*`` (the cache backend's settings), ``event_publishing.*`` (the pubsub name and +topic mapping), and ``runtimes..*`` with its legacy singular ``runtime..*``. + +Everything else at the top of the tree that is a table is somebody's *scope*: an agent's section +is written ``[default.]``, so its keys are reachable as ``.`` by anyone who +can resolve a dotted name. That is why this is an allowlist of what may be shared rather than a +denylist of agent names -- a new agent needs no entry here, and a key this list has never heard +of is refused rather than resolved. +""" + + PROCESS_SCOPE_KEYS = frozenset( { "app_port", @@ -164,6 +180,10 @@ def __init__( self._agent_scope = agent_scope self._is_view = False self._views: dict[str, Config] = {} + # Set on a view by for_namespace, so a view can ask the object that owns the tree to + # flatten *its own* scope. Stripping the other agents' subsections needs the list of + # namespaces, and a view deliberately does not have one (C6). + self._loader: Config | None = None # Kept so that :meth:`merge_agent_settings` can recognise a file the process has already # loaded as its own. An agent whose declaration module sits beside the group's settings # file would otherwise have every root key merged under its scope a second time. @@ -428,6 +448,7 @@ def for_namespace(self, namespace: str) -> "Config": view._agent_scope = namespace view._is_view = True view._views = {} + view._loader = self self._views[namespace] = view return view @@ -649,31 +670,46 @@ def resolved_settings(self, namespace: str = "") -> dict[str, Any]: A key whose scoped value is ``None`` is left at its root value, matching :meth:`_scoped_get` -- ``None`` there means "not set", not "set to nothing". - Args: - namespace: The agent to resolve for. ``""`` returns the whole tree, which is what the - root namespace resolves. - Returns: A plain dictionary, keys as the settings tree spells them. + **A view may resolve itself, and nothing else.** Asked for an arbitrary namespace this + would be a window on a neighbour, which is what it used to refuse outright -- but a view + asking for its *own* scope is the agent describing itself, and the operator-facing + environment endpoint needs exactly that when it is scoped to one agent. The work is + delegated to the object that owns the tree, because flattening means stripping the other + agents' subsections and a view deliberately does not know what they are (C6). + + Args: + namespace: The agent to resolve for. ``""`` returns the whole tree on the + application's own configuration, and this view's own scope on a view. + Raises: - RuntimeError: if called on a view, for the reason given on :attr:`namespaces` -- this - answers for an arbitrary namespace, so on a view it would be a route to a - neighbour's configuration. + RuntimeError: if a view is asked for a namespace other than its own. """ if self._is_view: - raise RuntimeError( - f"Namespace '{self._agent_scope}' asked its own view to resolve configuration for namespace " - f"'{namespace}'. Views resolve their own keys through get(); they are not a window on another " - "agent's configuration." - ) + if namespace and namespace != self._agent_scope: + raise RuntimeError( + f"Namespace '{self._agent_scope}' asked its own view to resolve configuration for namespace " + f"'{namespace}'. A view resolves itself; it is not a window on another agent's configuration." + ) + assert self._loader is not None, "a view without the loader that made it cannot resolve itself" + return self._loader.resolved_settings(self._agent_scope or "") tree: dict[str, Any] = dict(self._settings.as_dict()) if not namespace: return tree logger.debug("Resolving the flattened configuration of namespace '%s'", namespace) - others = {name.lower() for name in self._views} - {namespace.lower()} + # Every top-level table that is not one of the framework's own is an agent's section, so + # that is what gets stripped. Derived from the tree rather than from `self._views`, which + # holds only the namespaces that have *asked* for a view: an agent whose components had + # not yet read their configuration was therefore left in a neighbour's resolved settings, + # and whether it leaked depended on construction order. + sections = { + str(key).lower() for key, value in tree.items() if hasattr(value, "items") and str(key).lower() not in SHARED_NESTED_PREFIXES + } + others = (sections | {name.lower() for name in self._views}) - {namespace.lower()} own: Any = None resolved: dict[str, Any] = {} for key, value in tree.items(): @@ -805,13 +841,46 @@ def _scoped_get(self, key: str, default: Any = None) -> Any: ``None`` from a scoped lookup is treated as "not set" so the root fallback fires. Empty containers (``[]``, ``{}``, ``""``) at the scoped key are returned as-is — only ``None`` triggers fallback. + + **The root fallback does not walk into another agent's section.** An agent's keys live + under its own name at the top of the tree, so a dotted key resolves them: + ``for_namespace("billing").get("orders.record_id")`` used to return orders' value, + because the scope *prefixes* a key without confining it. The fallback is therefore + restricted to the dotted prefixes the framework itself owns -- see + :data:`SHARED_NESTED_PREFIXES`, an allowlist rather than a list of agent names, so it + fails closed for anything it has not been told about. """ if self._agent_scope: scoped = self._settings.get(f"{self._agent_scope}.{key}") if scoped is not None: return scoped + self._refuse_a_foreign_section(key) return self._settings.get(key, default) + def _refuse_a_foreign_section(self, key: str) -> None: + """Refuse a dotted key that a scoped view would resolve outside its own agent. + + Raised rather than answered with the default, for the reason the deployment-identity + check raises: a quiet miss reads as "not configured" and sends the caller looking for a + setting, while what actually happened is that the key names somewhere they cannot read. + + Args: + key: The key being resolved, before the root fallback runs. + + Raises: + ValueError: if ``key`` is dotted and its first segment is not one of the framework's + own nested sections. + """ + head = key.split(".", 1)[0] + if "." not in key or head in SHARED_NESTED_PREFIXES: + return + raise ValueError( + f"Agent '{self._agent_scope}' cannot read '{key}': its first segment names a section of the " + f"configuration tree outside this agent, and an agent reads its own keys and the process's shared " + f"ones. The nested sections the framework shares are {', '.join(sorted(SHARED_NESTED_PREFIXES))}; " + "anything else dotted is somebody's scope. Write the key flat to read this agent's own value." + ) + def get(self, key: str, default: Any = None) -> Any: """Get a configuration value, scope-aware when ``agent_scope`` is set. @@ -989,11 +1058,18 @@ def get_prompt_config(self, runtime_name: str | None = None) -> PromptConfig: ) def get_observability_config(self) -> ObservabilityConfig: - """Get observability-related configuration.""" + """Get observability-related configuration. + + ``token_metrics_enabled`` is read here like every other key. It was previously left to + the model's default, so the one thing it gates -- the per-call token and latency metrics + in :mod:`blueprint.agents.agent.metrics` -- could not be turned off from a settings file + at all. + """ return ObservabilityConfig( otel_enabled=self.get("otel_enabled", False), otel_endpoint=self.get("otel_endpoint"), otel_service_name=self._resolve_service_name(), + token_metrics_enabled=self.get("token_metrics_enabled", True), log_level=self.get("log_level", "INFO"), ) diff --git a/src/blueprint/agents/io/api/actuators/actuator_api.py b/src/blueprint/agents/io/api/actuators/actuator_api.py index 52182e90..979196c8 100644 --- a/src/blueprint/agents/io/api/actuators/actuator_api.py +++ b/src/blueprint/agents/io/api/actuators/actuator_api.py @@ -275,14 +275,17 @@ async def env_status(self) -> EnvironmentStatus: settings = config.settings environment = getattr(settings, "current_env", "unknown") + # One call, both shapes: on the application's own configuration this is the whole tree, + # and on a view it is that agent's own resolved keys. The branch used to hand a view + # `settings.as_dict()` -- the *unscoped* tree -- while its comment claimed the opposite, + # so a scoped actuator would have served every agent's configuration over HTTP. + raw_config = config.resolved_settings() + + # The per-agent breakdown is the operator's view of the whole process, so it exists only + # on the application's own configuration. Listing neighbours from inside an agent is the + # thing C6 exists to prevent, and `config.namespaces` refuses on a view for that reason. namespaces: dict[str, dict[str, Any]] = {} - if config.is_view: - # An agent-scoped actuator reports its own scope and nothing else: resolving for - # another namespace is refused on a view (C6), and listing neighbours is the thing - # C6 exists to prevent. - raw_config = self._as_dict(settings) - else: - raw_config = config.resolved_settings() + if not config.is_view: namespaces = {name: self._sanitize_config(config.resolved_settings(name)) for name in config.namespaces} logger.info( @@ -299,14 +302,6 @@ async def env_status(self) -> EnvironmentStatus: namespaces=namespaces, ) - @staticmethod - def _as_dict(settings: Any) -> dict[str, Any]: - """Return the settings tree as a plain dictionary, or ``{}`` if it cannot be read.""" - try: - return dict(settings.as_dict()) - except AttributeError: # pragma: no cover - defensive - return {} - @RestApiBase.get("/status/llm", response_model=LLMStatus, tags=["Status"], summary="Returns AI provider configuration and diagnostics.") async def llm_status(self) -> LLMStatus: """Expose AI configuration and provider diagnostics.""" @@ -316,7 +311,9 @@ async def llm_status(self) -> LLMStatus: ai_config_dict = ( ai_config_model.model_dump() if hasattr(ai_config_model, "model_dump") - else ai_config_model.dict() if hasattr(ai_config_model, "dict") else {} + else ai_config_model.dict() + if hasattr(ai_config_model, "dict") + else {} ) ai_config = self._sanitize_config(ai_config_dict) diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py new file mode 100644 index 00000000..376f37c3 --- /dev/null +++ b/tests/integration/__init__.py @@ -0,0 +1,3 @@ +"""Broker integration tests. A package for the same reason ``tests/unit`` is one: the modules +here import shared helpers from each other, and pytest resolves that through the package. +""" diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index b5d0a1ff..a2b2876b 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -9,17 +9,346 @@ the directory and the marker cannot drift apart and no contributor has to remember the decorator. The other half of the rule is what this file cannot enforce and a review must -- a test that needs nothing running does not belong here. Two that did were moved out rather than marked. + +**A missing broker skips; it never fails.** An offline run of the whole suite has to stay green, +because `-m integration` is how you *ask* for the tests that need something running -- so the +absence of a server is not a result. The skip messages name the command that starts it, since the +reader of a skip is usually someone who did not know these needed anything. + +The services: + + docker compose -f tests/integration/docker-compose.yml up -d + pytest tests/ -m integration """ +import asyncio +import os +import uuid +from urllib.parse import urlparse +from collections.abc import AsyncIterator, Callable, Iterator +from contextlib import asynccontextmanager from pathlib import Path +from typing import Any +import nats import pytest +from fastapi import FastAPI +from nats.aio.client import Client as NatsClient +from nats.js import JetStreamContext + +from blueprint.agents.agent_group import AgentGroup +from blueprint.agents.app_builder import AppBuilder +from blueprint.agents.clients.io.nats_client import NATSClient +from blueprint.agents.component.component import Component +from blueprint.agents.config import Config + +from .helpers import wait_until INTEGRATION_ROOT = Path(__file__).parent +NATS_URL = os.environ.get("BLUEPRINT_TEST_NATS_URL", "nats://127.0.0.1:4222") +"""Where the broker is. + +Overridable, because a CI service container is not on localhost. The literal address rather than +``localhost`` is deliberate: ``localhost`` resolves to ``::1`` first here, and see +:func:`server_is_listening` for why that costs a minute per run when nothing is there. +""" + +COMPOSE_HINT = "docker compose -f tests/integration/docker-compose.yml up -d" + def pytest_collection_modifyitems(items: list[pytest.Item]) -> None: """Mark every test collected from this directory as ``integration``.""" for item in items: if INTEGRATION_ROOT in Path(str(item.fspath)).parents: item.add_marker(pytest.mark.integration) + + +# --------------------------------------------------------------------------- +# The broker +# --------------------------------------------------------------------------- + + +def server_is_listening(url: str, timeout: float = 2.0) -> bool: + """Is anything accepting TCP connections at ``url``? A plain socket, and a hard deadline. + + **Not** ``nats.connect``, which is the obvious way to write this and does not work offline. + Two behaviours combine badly: an unreachable ``::1`` port on Windows silently drops the SYN + rather than refusing it, so the attempt stalls for the whole ``connect_timeout``; and nats-py + then retries the initial connect indefinitely -- ``max_reconnect_attempts`` governs + *re*-connection, not the first one. An offline run of this directory therefore hung rather + than skipping, which is the one thing these fixtures exist to prevent. + + A bare ``open_connection`` under ``wait_for`` has neither problem: no protocol handshake, no + retry loop, and a deadline this function owns. + """ + parsed = urlparse(url) + host, port = parsed.hostname or "127.0.0.1", parsed.port or 4222 + + async def probe() -> None: + _, writer = await asyncio.wait_for(asyncio.open_connection(host, port), timeout=timeout) + writer.close() + await writer.wait_closed() + + try: + asyncio.run(probe()) + except Exception: + return False + return True + + +@pytest.fixture(scope="session") +def nats_url() -> str: + """The broker's URL, or skip the test because there is no broker. + + Probed once per session, and by socket rather than by client: a session-scoped fixture must + not hold a connection either way, because pytest-asyncio gives each test its own event loop + and a connection made on a loop that has since closed is unusable on the next. + """ + if not server_is_listening(NATS_URL): + pytest.skip(f"No NATS server at {NATS_URL}. Start one with: {COMPOSE_HINT}") + return NATS_URL + + +@pytest.fixture +async def nats_connection(nats_url: str) -> AsyncIterator[NatsClient]: + """A raw nats-py connection for the test to publish and assert with. + + Deliberately *not* the framework's client: a test that observes the broker through the same + object it is testing can only confirm that object agrees with itself. + """ + # allow_reconnect=False so that a broker disappearing mid-run fails the test that noticed + # rather than parking it in nats-py's reconnect loop. + connection = await nats.connect(nats_url, connect_timeout=2, allow_reconnect=False) + try: + yield connection + finally: + await connection.close() + + +@pytest.fixture +def subject_prefix() -> str: + """A subject namespace unique to this test, so no two tests can see each other's messages. + + Every subject a test uses goes under here. Without it, a leftover durable from a previous + run -- or a test running beside this one -- delivers into the assertion. + """ + return f"it{uuid.uuid4().hex[:12]}" + + +@pytest.fixture +async def jetstream_stream(nats_connection: NatsClient, subject_prefix: str) -> AsyncIterator[str]: + """Yield a stream name reserved for this test, and delete the stream afterwards. + + The stream is **not** created here. The framework creates its own (`_ensure_stream`), and a + test of that behaviour has to watch it happen; a test that needs one up front creates it + itself from this name. What the fixture guarantees is the teardown, which is the half that + cannot be left to the test: deleting a stream deletes its consumers with it, and a durable + that outlives its test carries a delivery count and a filter subject into the next one. + """ + name = f"IT_{subject_prefix.upper()}" + try: + yield name + finally: + try: + await nats_connection.jetstream().delete_stream(name) + except Exception: + # Never created, or already gone. Either is a legitimate end for a test that did + # not get that far, and a teardown that raises would mask the real failure. + pass + + +@pytest.fixture +async def jetstream(nats_connection: NatsClient, jetstream_stream: str, subject_prefix: str) -> JetStreamContext: + """A JetStream context with this test's stream already created over its subject prefix.""" + js = nats_connection.jetstream() + await js.add_stream(name=jetstream_stream, subjects=[f"{subject_prefix}.>"]) + return js + + +# --------------------------------------------------------------------------- +# An application built against the real broker +# --------------------------------------------------------------------------- + + +OUTBOUND_EVENT_TYPE = "order.validated" +"""The event type a test handler returns, mapped to ``.out`` by the config below.""" + + +@pytest.fixture +def outbound_subject(subject_prefix: str) -> str: + """Where a handler's ``HandlerResult`` is published, inside this test's own namespace.""" + return f"{subject_prefix}.out" + + +@pytest.fixture +def integration_config( + tmp_path: Path, + nats_url: str, + jetstream_stream: str, + subject_prefix: str, + outbound_subject: str, +) -> Iterator[Config]: + """A ``Config`` written to disk and loaded the way a deployed process loads one. + + Written as a file rather than mocked, because the keys under test -- ``nats_url``, + ``nats_stream_name``, the consumer tuning -- are read through the same resolution a + deployment uses, and a mock cannot be wrong about it in the way a settings file can. + + ``app_name`` has no whitespace on purpose: since P1 it is the root namespace's queue group, + and ``validate_subject_segment`` rejects a space. That is not a fixture detail -- it is the + defect `examples/webhook_relay` is sitting on. + + **``nats_queue_group`` is per test, and that is not cosmetic.** The dead-letter subject + defaults to ``.dead-letter`` and the client puts it into the stream it + provisions, so with one shared queue group every test's stream claims + ``blueprint-it.dead-letter`` -- and the second stream to be created is refused with + *subjects overlap with an existing stream*. Found by leaving one stream behind and starting + the next test. + """ + settings = tmp_path / "settings.toml" + settings.write_text( + "[default]\n" + 'app_name = "blueprint-it"\n' + 'app_environment = "development"\n' + "app_port = 8000\n" + 'model_provider = "openai"\n' + 'model_api_key = "not-a-real-key"\n' + 'event_bus = "nats"\n' + f'nats_url = "{nats_url}"\n' + f'nats_stream_name = "{jetstream_stream}"\n' + f'nats_queue_group = "{subject_prefix}"\n' + "nats_use_jetstream = true\n" + # Well above any handler here, and short enough that a test asserting *no* redelivery can + # afford to wait the whole window out. The framework default is 300. + "nats_ack_wait = 2.0\n" + "nats_max_deliver = 3\n" + # The client retries the initial connect forever by default, which turns "the broker + # refused this subscription" into a test that hangs instead of one that fails. + "event_client_max_retries = 2\n" + "event_client_retry_delay = 0.5\n\n" + # Where a handler's HandlerResult goes. Without a mapping for the event type, + # EventPublishingService logs "no topic mapping found" and publishes nothing at all. + f'[default.event_publishing.topic_mapping."{OUTBOUND_EVENT_TYPE}"]\n' + f'topic = "{outbound_subject}"\n', + encoding="utf-8", + ) + config = Config(settings_files=["settings.toml"], root_path=str(tmp_path)) + try: + yield config + finally: + Component.reset_shared_state() + + +NatsAppFactory = Callable[..., Any] + + +@pytest.fixture +def nats_app(integration_config: Config) -> NatsAppFactory: + """Return a context manager yielding a started, subscribed application on the real broker. + + Used as:: + + async with nats_app(MyHandler) as (app, client): + ... + + Two things it does that a test should not have to repeat: + + **The lifespan is entered directly**, not through ``TestClient``. Startup is where the client + connects and subscribes; the test is already async, and ``TestClient`` would run that + lifespan on a second event loop in a background thread. + + **It waits for the subscriptions.** ``NATSClient.subscribe()`` returns immediately and does + the connecting in a background retry task, so the moment the lifespan returns, the agent is + typically not yet on its topics. A test that published there would be asserting on a race: + JetStream would hold the message and the test would usually pass, Core NATS would drop it + and the test would usually fail, and neither outcome would be about the thing under test. + + At least one handler is required. With none, the agent neither consumes nor publishes, so + ``build()`` deliberately gives it no transport client at all and there would be nothing to + hand back. + """ + + @asynccontextmanager + async def factory(*handlers: type, ready_timeout: float = 15.0) -> AsyncIterator[tuple[FastAPI, NATSClient]]: + assert handlers, "nats_app needs at least one handler; without one the agent is given no transport client" + + builder = AppBuilder(integration_config) + for handler in handlers: + builder = builder.with_handler(handler) + app = builder.build() + + try: + async with app.router.lifespan_context(app): + registry = Component.shared_registry + assert registry is not None + client: NATSClient = registry.get_component(NATSClient) + + await wait_until( + lambda: client.subscriptions_ready, + timeout=ready_timeout, + description=f"the NATS subscriptions of queue group '{client.queue_group}' to become ready", + ) + yield app, client + finally: + # After the lifespan, never inside it. `Component.configure` refuses a second call and + # the registry is process-global, so both have to go before a test can start a second + # process -- but clearing them while shutdown is still running takes the components + # out from under it, and a shutdown draining an in-flight handler then never returns. + Component.reset_shared_state() + + return factory + + +@pytest.fixture +def agent_names(subject_prefix: str) -> tuple[str, str]: + """Two agent names unique to this test. + + Unique because a namespaced client derives its queue group from the namespace, and the + dead-letter subject from the queue group -- so two tests sharing an agent name would claim + one dead-letter subject and their streams would overlap. The alphabet is ``[a-z][a-z0-9_]*``, + which the ``it`` prefix already satisfies. + """ + return f"orders_{subject_prefix}", f"billing_{subject_prefix}" + + +@pytest.fixture +def nats_group(integration_config: Config) -> NatsAppFactory: + """Return a context manager yielding a *group* of agents started on the real broker. + + The single-agent ``nats_app`` cannot express what a group asserts. Each agent gets its own + ``NATSClient``, its own queue group and its own durable, and the claim under test is that + those stay separate while sharing one process, one connection pool and one stream. + + Used as:: + + async with nats_group({"orders": OrdersHandler, "billing": BillingHandler}) as clients: + ... + + and yields the clients by agent name, because every assertion here is about one agent's + transport rather than about the application object they share. + """ + + @asynccontextmanager + async def factory(agents: dict[str, type], *, ready_timeout: float = 20.0) -> AsyncIterator[dict[str, NATSClient]]: + group = AgentGroup("integration", {name: AppBuilder().with_handler(handler) for name, handler in agents.items()}) + app = group.assemble(integration_config) + + try: + async with app.router.lifespan_context(app): + registry = Component.shared_registry + assert registry is not None + clients = {name: registry.get_component(NATSClient, namespace=name) for name in agents} + + for name, client in clients.items(): + await wait_until( + lambda client=client: client.subscriptions_ready, # type: ignore[misc] + timeout=ready_timeout, + description=f"agent '{name}' to subscribe", + ) + yield clients + finally: + # After the lifespan, for the reason given on `nats_app`. + Component.reset_shared_state() + + return factory diff --git a/tests/integration/docker-compose.yml b/tests/integration/docker-compose.yml new file mode 100644 index 00000000..454f5cba --- /dev/null +++ b/tests/integration/docker-compose.yml @@ -0,0 +1,45 @@ +# The services the tests in this directory need, and nothing else. +# +# docker compose -f tests/integration/docker-compose.yml up -d +# pytest tests/ -m integration +# docker compose -f tests/integration/docker-compose.yml down +# +# Ports are published on localhost because the tests run on the host, not in a container. +# Nothing here is a deployment example -- see docs/guides/deployment.md for that. +# +# **No volumes, deliberately.** JetStream state lives inside the container and is gone with it, +# so `down` followed by `up -d` is a clean broker. A stream or a durable left over from an +# earlier run is exactly the kind of state that makes a green test meaningless: a durable +# remembers its filter subject and its delivery count, so a test that asserts a redelivery can +# pass against last week's consumer. The fixtures tear down what they create as well, per test; +# this is the coarser guarantee underneath that. + +services: + nats: + image: nats:2.10-alpine + container_name: blueprint-test-nats + # --jetstream is what the framework needs for durables, dead letters and max_deliver; + # without it every subscription silently falls back to Core NATS and the acknowledgement + # tests assert nothing. --http_port exposes /healthz and /connz, which is also where the + # connection names the client sets (namespace.group.pod) can be read back. + command: ["--jetstream", "--store_dir=/tmp/nats", "--http_port=8222"] + ports: + - "4222:4222" + - "8222:8222" + healthcheck: + test: ["CMD", "wget", "--spider", "-q", "http://localhost:8222/healthz"] + interval: 5s + timeout: 3s + retries: 5 + start_period: 5s + + redis: + image: redis:7-alpine + container_name: blueprint-test-redis + ports: + - "6379:6379" + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 5 diff --git a/tests/integration/helpers.py b/tests/integration/helpers.py new file mode 100644 index 00000000..80864d3d --- /dev/null +++ b/tests/integration/helpers.py @@ -0,0 +1,65 @@ +"""Waiting, done once so that no broker test has to invent it. + +A broker is asynchronous in the sense that matters here: nothing a test asks for is true at the +moment it asks. The connection is established by a background task, a subscription is registered +on the server a round trip later, and a handler runs when the delivery arrives. Every assertion +against a real broker is therefore preceded by a wait, and the shape of that wait decides what a +failure tells you. +""" + +import asyncio +from collections.abc import Awaitable, Callable + + +async def wait_until(predicate: Callable[[], bool], *, timeout: float, description: str) -> None: + """Poll ``predicate`` until it is true, or fail saying what never happened. + + The alternative -- a fixed ``asyncio.sleep`` -- is either too short on a loaded machine or + wasted on every run, and when it is too short the failure blames the assertion that follows + rather than the wait. ``description`` is what makes the timeout readable: it is the only + thing the reader of a CI log has. + + Args: + predicate: Checked repeatedly; must not block. + timeout: Seconds to wait before failing. + description: What is being waited for, phrased to follow "waiting for". + + Raises: + AssertionError: if the timeout passes with the predicate still false. + """ + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while loop.time() < deadline: + if predicate(): + return + await asyncio.sleep(0.05) + raise AssertionError(f"Timed out after {timeout}s waiting for {description}") + + +async def poll_until( + predicate: Callable[[], Awaitable[bool]], + *, + timeout: float, + description: str, +) -> None: + """Like :func:`wait_until`, for a condition that has to be asked of the broker. + + Separate rather than a flag on one function, because the two take different things: a + synchronous predicate reads state the process already holds, and this one makes a request per + attempt -- so the interval is longer, and a caller has to know which it is using. + + Args: + predicate: Awaited repeatedly until it returns true. + timeout: Seconds to wait before failing. + description: What is being waited for, phrased to follow "waiting for". + + Raises: + AssertionError: if the timeout passes with the predicate still false. + """ + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while loop.time() < deadline: + if await predicate(): + return + await asyncio.sleep(0.2) + raise AssertionError(f"Timed out after {timeout}s waiting for {description}") diff --git a/tests/integration/test_acknowledgement_lifecycle.py b/tests/integration/test_acknowledgement_lifecycle.py new file mode 100644 index 00000000..bc94dff1 --- /dev/null +++ b/tests/integration/test_acknowledgement_lifecycle.py @@ -0,0 +1,282 @@ +"""What the broker does with a delivery the framework could not complete. + +Step 3 of `docs/plans/2026-09-11-broker-integration-tests.md`. Spec sec. 7.2 fixes one outcome +table for every transport, and the unit tests assert that the framework *decides* the right one. +These assert that the broker then *does* it -- which is a different claim, and the only one that +matters to a deployment: + +| what the handler does | disposition | what the broker does | +|----------------------------------|-------------|---------------------------------| +| returns normally | ack | nothing more | +| raises `RetryableHandlerError` | nak | redelivers after `nats_ack_wait`| +| raises `CriticalHandlerError` | term | never redelivers | +| raises `InvalidEventError` | term | never redelivers | +| no handler matches | **ack** | nothing more | +| payload is not a CloudEvent | term | never dispatched at all | +| `nats_max_deliver` spent | - | dead-lettered, then termed | + +The two easiest to get backwards are the ones worth naming. **An event no handler matches is +acknowledged**: finding no work in an event is a normal outcome, and naking it would put it back +on the queue for ever. **A payload that does not parse is termed without being dispatched**: it +cannot become valid on a retry, so redelivering it is a loop with no exit. + +`nats_ack_wait` is 2 seconds here (`integration_config`), which is what makes the redelivery +tests affordable. +""" + +import asyncio +import uuid +from dataclasses import dataclass, field +from typing import Any + +import pytest +from nats.aio.client import Client as NatsClient +from nats.js import JetStreamContext + +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.errors import CriticalHandlerError, InvalidEventError, RetryableHandlerError +from blueprint.agents.models.events import GenericCloudEvent + +from .helpers import poll_until, wait_until + + +@dataclass +class Attempts: + """A handler that fails in a chosen way, and the record of every time it was called.""" + + handler: type[EventHandlerBase] + topic: str + seen: list[str] = field(default_factory=list) + + +@pytest.fixture +def failing(subject_prefix: str) -> Any: + """Return a factory making a handler that raises what a test asks it to. + + The exception is what the framework classifies, so it is the only thing that varies between + the cases below -- everything else about the handler is identical on purpose. + """ + + def make(error: BaseException | None, *, matches: bool = True) -> Attempts: + topic = f"{subject_prefix}.orders.created" + seen: list[str] = [] + + class FailingHandler(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return [topic] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return matches + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> None: + seen.append(event.id) + if error is not None: + raise error + return None + + return Attempts(handler=FailingHandler, topic=topic, seen=seen) + + return make + + +def an_order() -> GenericCloudEvent: + return GenericCloudEvent(id=str(uuid.uuid4()), source="integration-test", type="orders.created", data={"order_id": "1"}) + + +async def only_consumer(jetstream: JetStreamContext, stream: str) -> Any: + consumers = await jetstream.consumers_info(stream) + assert len(consumers) == 1, f"expected one consumer, found {[consumer.name for consumer in consumers]}" + return consumers[0] + + +class TestARetryableFailureComesBack: + """`nak` means "not now": the broker holds the message and redelivers it.""" + + async def test_it_is_redelivered_after_the_ack_wait(self, nats_app: Any, failing: Any, jetstream: JetStreamContext) -> None: + """The claim no mock can make. A nak returns the message to the consumer, and the + handler runs again on the same event id -- which is also why a handler has to be safe + to repeat, or dedup has to be switched on.""" + attempts = failing(RetryableHandlerError(status="failed", reason="not yet")) + event = an_order() + + async with nats_app(attempts.handler): + await jetstream.publish(attempts.topic, event.model_dump_json().encode()) + + await wait_until( + lambda: len(attempts.seen) >= 2, + timeout=15, + description="the nak'd event to be redelivered", + ) + + assert attempts.seen[0] == event.id + assert attempts.seen[1] == event.id, "a different event came back, so this is not a redelivery" + + async def test_the_broker_counts_it_as_a_redelivery( + self, nats_app: Any, failing: Any, jetstream: JetStreamContext, jetstream_stream: str + ) -> None: + attempts = failing(RetryableHandlerError(status="failed", reason="not yet")) + + async with nats_app(attempts.handler): + await jetstream.publish(attempts.topic, an_order().model_dump_json().encode()) + await wait_until(lambda: len(attempts.seen) >= 2, timeout=15, description="a redelivery") + + consumer = await only_consumer(jetstream, jetstream_stream) + + assert consumer.num_redelivered >= 1 + + +class TestATerminalFailureDoesNotComeBack: + """`term` means "never again": the message is removed from the consumer.""" + + @pytest.mark.parametrize( + "error", + [ + CriticalHandlerError(status="failed", reason="cannot continue"), + InvalidEventError(status="failed", reason="not something this handler can read"), + ], + ids=["critical", "invalid"], + ) + async def test_it_is_delivered_once(self, nats_app: Any, failing: Any, jetstream: JetStreamContext, error: BaseException) -> None: + """Waiting past `nats_ack_wait` is the whole test: a nak would show up as a second call.""" + attempts = failing(error) + + async with nats_app(attempts.handler): + await jetstream.publish(attempts.topic, an_order().model_dump_json().encode()) + await wait_until(lambda: bool(attempts.seen), timeout=10, description="the handler to be called") + + await asyncio.sleep(3.0) # nats_ack_wait is 2.0 + + assert len(attempts.seen) == 1, f"a termed delivery came back {len(attempts.seen)} times" + + async def test_it_is_dead_lettered_with_the_reason_in_the_headers( + self, nats_app: Any, failing: Any, jetstream: JetStreamContext, nats_connection: NatsClient, subject_prefix: str + ) -> None: + """The payload is republished unchanged and what went wrong travels in headers, so a + dead-letter consumer reading the body is not handed a corrupted one.""" + attempts = failing(CriticalHandlerError(status="failed", reason="cannot continue")) + event = an_order() + dead_letters: asyncio.Queue[Any] = asyncio.Queue() + + async def collect(msg: Any) -> None: + await dead_letters.put(msg) + + async with nats_app(attempts.handler): + await nats_connection.subscribe(f"{subject_prefix}.dead-letter", cb=collect) + await nats_connection.flush() + await jetstream.publish(attempts.topic, event.model_dump_json().encode()) + + dead = await asyncio.wait_for(dead_letters.get(), timeout=15) + + assert GenericCloudEvent.model_validate_json(dead.data).id == event.id + assert dead.headers["Blueprint-Dead-Letter-Reason"] == "terminal-failure" + assert dead.headers["Blueprint-Original-Subject"] == attempts.topic + assert dead.headers["Blueprint-Event-Id"] == event.id + + +class TestAnEventNobodyWantsIsAcknowledged: + """Finding no work in an event is a normal outcome, not a failure.""" + + async def test_it_is_not_redelivered(self, nats_app: Any, failing: Any, jetstream: JetStreamContext) -> None: + """`can_handle_event` returning False for every handler must ack. Naking it would put a + message nobody wants back on the queue for ever, at `ack_wait` intervals.""" + attempts = failing(None, matches=False) + + async with nats_app(attempts.handler): + await jetstream.publish(attempts.topic, an_order().model_dump_json().encode()) + await asyncio.sleep(4.0) # two ack_wait windows + + assert attempts.seen == [], "a handler that declined the event was called anyway" + + async def test_the_broker_has_nothing_left_pending( + self, nats_app: Any, failing: Any, jetstream: JetStreamContext, jetstream_stream: str + ) -> None: + attempts = failing(None, matches=False) + + async with nats_app(attempts.handler): + await jetstream.publish(attempts.topic, an_order().model_dump_json().encode()) + + async def settled() -> bool: + consumer = await only_consumer(jetstream, jetstream_stream) + return bool(consumer.num_ack_pending == 0 and consumer.ack_floor.stream_seq == 1) + + await poll_until(settled, timeout=15, description="the unmatched event to be acknowledged") + + +class TestAPayloadThatIsNotACloudEventIsNeverDispatched: + """It cannot become valid on a retry, so redelivering it is a loop with no exit.""" + + async def test_the_handler_is_not_called(self, nats_app: Any, failing: Any, jetstream: JetStreamContext) -> None: + attempts = failing(None) + + async with nats_app(attempts.handler): + await jetstream.publish(attempts.topic, b"this is not a cloud event") + await asyncio.sleep(4.0) # two ack_wait windows + + assert attempts.seen == [], "an undecodable payload reached a handler" + + async def test_it_is_dead_lettered_with_its_bytes_unchanged( + self, nats_app: Any, failing: Any, jetstream: JetStreamContext, nats_connection: NatsClient, subject_prefix: str + ) -> None: + """The message boundary P0 drew: an undecodable payload is distinguished from a failed + dispatch, and the original bytes are what is kept -- there is no event id to put in a + header, because nothing parsed.""" + attempts = failing(None) + dead_letters: asyncio.Queue[Any] = asyncio.Queue() + + async def collect(msg: Any) -> None: + await dead_letters.put(msg) + + async with nats_app(attempts.handler): + await nats_connection.subscribe(f"{subject_prefix}.dead-letter", cb=collect) + await nats_connection.flush() + await jetstream.publish(attempts.topic, b"this is not a cloud event") + + dead = await asyncio.wait_for(dead_letters.get(), timeout=15) + + assert dead.data == b"this is not a cloud event" + assert dead.headers["Blueprint-Dead-Letter-Reason"] == "terminal-failure" + + +class TestRedeliveriesRunOut: + """`nats_max_deliver` is 3 here, so the third failure is the last.""" + + async def test_the_handler_stops_being_called(self, nats_app: Any, failing: Any, jetstream: JetStreamContext) -> None: + attempts = failing(RetryableHandlerError(status="failed", reason="never works")) + + async with nats_app(attempts.handler): + await jetstream.publish(attempts.topic, an_order().model_dump_json().encode()) + await wait_until( + lambda: len(attempts.seen) >= 3, + timeout=20, + description="the delivery attempts to be spent", + ) + await asyncio.sleep(4.0) # two more ack_wait windows + + assert len(attempts.seen) == 3, f"max_deliver is 3 and the handler ran {len(attempts.seen)} times" + + async def test_the_exhausted_message_is_dead_lettered( + self, nats_app: Any, failing: Any, jetstream: JetStreamContext, nats_connection: NatsClient, subject_prefix: str + ) -> None: + """A different reason from a terminal failure, because the two are different operational + problems: one handler is broken, the other rejected this particular event.""" + attempts = failing(RetryableHandlerError(status="failed", reason="never works")) + dead_letters: asyncio.Queue[Any] = asyncio.Queue() + + async def collect(msg: Any) -> None: + await dead_letters.put(msg) + + async with nats_app(attempts.handler): + await nats_connection.subscribe(f"{subject_prefix}.dead-letter", cb=collect) + await nats_connection.flush() + await jetstream.publish(attempts.topic, an_order().model_dump_json().encode()) + + dead = await asyncio.wait_for(dead_letters.get(), timeout=25) + + assert dead.headers["Blueprint-Dead-Letter-Reason"] == "deliveries-exhausted" + assert dead.headers["Blueprint-Delivery-Count"] == "3" diff --git a/tests/integration/test_delivery_once.py b/tests/integration/test_delivery_once.py new file mode 100644 index 00000000..8b0e94f3 --- /dev/null +++ b/tests/integration/test_delivery_once.py @@ -0,0 +1,185 @@ +"""A message is handled once -- across replicas, and across a shutdown. + +Chores 2 and 3 from `docs/plans/2026-09-11-broker-integration-tests.md`. Both are the same claim +seen from two sides, and both are what make a rolling deploy safe: + +- **Across replicas.** Two processes of one agent share a queue group, so the broker delivers each + message to one of them. This is the claim `replicaCount > 1` rests on, and before P1 it was + false -- every replica processed everything. +- **Across a shutdown.** A handler already running when the process is told to stop finishes, and + its acknowledgement reaches the broker *before* the connection closes. Wrong, and every deploy + produces a duplicate: the handler's work is done, the ack is lost, and the message is redelivered + to whichever replica is still up. + +The second replica here is a raw nats-py subscription bound to **the names the framework derived** +-- its queue group, its durable, its deliver subject -- rather than a second process. That is the +part worth stating: a real replica is identical to the first, so what makes distribution work is +that both bind the *same* names, and binding them by hand is a sharper test of that than starting +another interpreter. A second process would additionally test process startup, which step 1 +already covers. +""" + +import asyncio +import uuid +from typing import Any + +import pytest +from nats.aio.client import Client as NatsClient +from nats.aio.msg import Msg +from nats.js import JetStreamContext + +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.events import GenericCloudEvent + +from .helpers import poll_until, wait_until + + +def an_event() -> GenericCloudEvent: + return GenericCloudEvent(id=str(uuid.uuid4()), source="integration-test", type="thing.happened", data={}) + + +@pytest.fixture +def slow_handler(subject_prefix: str) -> Any: + """A handler that takes a measurable amount of time, and records when it started and ended. + + The shutdown test needs a handler it can be *inside* when the process is asked to stop, which + a handler that returns immediately cannot provide. + """ + + def make(duration: float) -> dict[str, Any]: + topic = f"{subject_prefix}.orders.created" + started: list[str] = [] + finished: list[str] = [] + + class SlowHandler(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return [topic] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> None: + started.append(event.id) + await asyncio.sleep(duration) + finished.append(event.id) + return None + + return {"handler": SlowHandler, "topic": topic, "started": started, "finished": finished} + + return make + + +class TestTwoReplicasShareTheWork: + """One queue group, one delivery per message.""" + + async def test_a_second_binder_does_not_double_the_deliveries( + self, nats_app: Any, slow_handler: Any, jetstream: JetStreamContext, nats_connection: NatsClient + ) -> None: + """The claim `replicaCount > 1` rests on, and the one P1 fixed. + + The second subscriber joins the deliver subject and queue group the framework chose, which + is exactly what a second replica of the same image does. Every message must arrive once + in total across the two -- not once each. + """ + work = slow_handler(0.0) + second_replica: list[bytes] = [] + + async def take(msg: Msg) -> None: + second_replica.append(msg.data) + await msg.ack() + + async with nats_app(work["handler"]) as (_, client): + consumers = await jetstream.consumers_info(await_stream(client)) + deliver_subject = consumers[0].config.deliver_subject + assert deliver_subject, "a push consumer without a deliver subject cannot have a replica" + + await nats_connection.subscribe(deliver_subject, queue=client.queue_group, cb=take) + await nats_connection.flush() + + published = [an_event() for _ in range(6)] + for event in published: + await jetstream.publish(work["topic"], event.model_dump_json().encode()) + + await wait_until( + lambda: len(work["finished"]) + len(second_replica) >= len(published), + timeout=20, + description="every message to reach one of the two replicas", + ) + await asyncio.sleep(1.5) # a duplicate would arrive in this window + + total = len(work["finished"]) + len(second_replica) + assert total == len(published), f"{len(published)} messages produced {total} deliveries across two replicas" + + +def await_stream(client: Any) -> str: + """The stream name the client was configured with.""" + return str(client.config.get("nats_stream_name", "EVENTS")) + + +class TestShutdownDrainsBeforeItCloses: + """A handler already running finishes, and its acknowledgement lands first.""" + + async def test_an_in_flight_handler_finishes(self, nats_app: Any, slow_handler: Any, jetstream: JetStreamContext) -> None: + """Leaving the lifespan is the shutdown. The handler is mid-`asyncio.sleep` when it + begins, and must still be allowed to reach its end.""" + work = slow_handler(1.5) + event = an_event() + + async with nats_app(work["handler"]): + await jetstream.publish(work["topic"], event.model_dump_json().encode()) + await wait_until(lambda: bool(work["started"]), timeout=15, description="the handler to start") + assert work["finished"] == [], "the handler finished before the shutdown began, so this proves nothing" + + assert work["finished"] == [event.id], "shutdown closed the connection with a handler still running" + + async def test_the_acknowledgement_arrives_before_the_connection_closes( + self, nats_app: Any, slow_handler: Any, jetstream: JetStreamContext, jetstream_stream: str + ) -> None: + """The half that makes a deploy safe. The handler finishing is not enough -- if its ack + is lost with the connection, the broker redelivers work that was already done, and every + rolling deploy produces a duplicate. + """ + work = slow_handler(1.0) + + async with nats_app(work["handler"]): + await jetstream.publish(work["topic"], an_event().model_dump_json().encode()) + await wait_until(lambda: bool(work["started"]), timeout=15, description="the handler to start") + + # Read after the lifespan: the question is what the broker was told before it ended. + consumers = await jetstream.consumers_info(jetstream_stream) + consumer = consumers[0] + + assert consumer.num_ack_pending == 0, "the connection closed with an acknowledgement still outstanding" + assert consumer.ack_floor.stream_seq == 1 + + async def test_nothing_is_redelivered_to_the_next_process( + self, nats_app: Any, slow_handler: Any, jetstream: JetStreamContext, jetstream_stream: str + ) -> None: + """The consequence, stated as a deploy: stop one process mid-handler, start another on + the same durable, and the message must not come back.""" + first = slow_handler(1.0) + event = an_event() + + async with nats_app(first["handler"]): + await jetstream.publish(first["topic"], event.model_dump_json().encode()) + await wait_until(lambda: bool(first["started"]), timeout=15, description="the first process to start work") + + assert first["finished"] == [event.id] + + second = slow_handler(0.0) + async with nats_app(second["handler"]): + await asyncio.sleep(4.0) # two ack_wait windows: a redelivery would land in here + + async def settled() -> bool: + info = await jetstream.consumers_info(jetstream_stream) + return bool(info and info[0].num_ack_pending == 0) + + await poll_until(settled, timeout=10, description="the consumer to be idle") + + assert second["started"] == [], "the message was redelivered to the next process after being acknowledged" diff --git a/tests/integration/test_event_path.py b/tests/integration/test_event_path.py new file mode 100644 index 00000000..5a99ac10 --- /dev/null +++ b/tests/integration/test_event_path.py @@ -0,0 +1,222 @@ +"""The whole path, on a real broker: in, handled, out, acknowledged once. + +Step 2 of `docs/plans/2026-09-11-broker-integration-tests.md`, and the test the exercise is for. +Everything the multi-agent work claims about delivery has until now been asserted against mocked +transports, which cannot tell you whether the broker agrees. + +Four claims, each stated against the server rather than against the framework's own account of +itself: + +1. an event published from outside the process reaches a handler inside it; +2. the handler's `HandlerResult` is published to the subject the configuration maps it to; +3. the inbound message is acknowledged **exactly once** -- read off the consumer, not inferred; +4. and it is not redelivered once `nats_ack_wait` has passed, which is the same claim from the + other side and the one a mock can never make. + +**The stream is pre-created over the whole test prefix**, by requesting the `jetstream` fixture. +That is not a convenience: the framework provisions a stream covering the subjects it +*subscribes*, and an outbound subject is not one of them -- see `TestWhatTheFrameworkProvisions` +at the bottom, where that is stated as its own failing test rather than hidden in a fixture. +""" + +import asyncio +import uuid +from dataclasses import dataclass, field +from typing import Any + +import pytest +from nats.aio.client import Client as NatsClient +from nats.aio.msg import Msg +from nats.js import JetStreamContext + +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.events import GenericCloudEvent, HandlerResult + +from .conftest import OUTBOUND_EVENT_TYPE +from .helpers import poll_until, wait_until + + +@dataclass +class Validator: + """A handler that records what it was given and returns a result to be published.""" + + handler: type[EventHandlerBase] + topic: str + received: list[GenericCloudEvent] = field(default_factory=list) + + +@pytest.fixture +def validator(subject_prefix: str) -> Validator: + """A handler on this test's inbound subject, returning a result for the mapped event type.""" + topic = f"{subject_prefix}.orders.created" + received: list[GenericCloudEvent] = [] + + class ValidatingHandler(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return [topic] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult: + received.append(event) + return HandlerResult(event_type=OUTBOUND_EVENT_TYPE, data={"order_id": event.data["order_id"]}) + + return Validator(handler=ValidatingHandler, topic=topic, received=received) + + +def an_order(order_id: str = "order-1") -> GenericCloudEvent: + return GenericCloudEvent(id=str(uuid.uuid4()), source="integration-test", type="orders.created", data={"order_id": order_id}) + + +async def collect_from(connection: NatsClient, subject: str) -> asyncio.Queue[bytes]: + """Subscribe to ``subject`` on Core NATS and queue what arrives. + + Core rather than a JetStream consumer on purpose: this is the test *watching* the process, + and a durable of its own would be broker-side state the test then has to tear down -- and + would consume from the same stream the application's own consumer is bound to. + """ + received: asyncio.Queue[bytes] = asyncio.Queue() + + async def collect(msg: Msg) -> None: + await received.put(msg.data) + + await connection.subscribe(subject, cb=collect) + await connection.flush() + return received + + +async def only_consumer(jetstream: JetStreamContext, stream: str) -> Any: + """The one consumer the application created on this test's stream.""" + consumers = await jetstream.consumers_info(stream) + assert len(consumers) == 1, f"expected one consumer, found {[consumer.name for consumer in consumers]}" + return consumers[0] + + +class TestThePathEndToEnd: + """Published from outside, handled inside, published back out.""" + + async def test_the_handler_receives_what_was_published(self, nats_app: Any, validator: Validator, jetstream: JetStreamContext) -> None: + event = an_order() + + async with nats_app(validator.handler): + await jetstream.publish(validator.topic, event.model_dump_json().encode()) + await wait_until( + lambda: bool(validator.received), + timeout=10, + description=f"the handler on '{validator.topic}' to be called", + ) + + assert [received.id for received in validator.received] == [event.id] + assert validator.received[0].data == {"order_id": "order-1"} + + async def test_the_result_is_published_to_the_mapped_subject( + self, nats_app: Any, validator: Validator, jetstream: JetStreamContext, nats_connection: NatsClient, outbound_subject: str + ) -> None: + """``HandlerResult(event_type=...)`` is resolved through ``event_publishing.topic_mapping``. + + The outbound event is a CloudEvent of its own -- new id, the configured ``app_name`` as + its source -- carrying the handler's data. It is not the inbound event forwarded. + """ + outbound = None + + async with nats_app(validator.handler): + received = await collect_from(nats_connection, outbound_subject) + await jetstream.publish(validator.topic, an_order("order-2").model_dump_json().encode()) + outbound = await asyncio.wait_for(received.get(), timeout=10) + + published = GenericCloudEvent.model_validate_json(outbound) + assert published.type == OUTBOUND_EVENT_TYPE + assert published.data == {"order_id": "order-2"} + assert published.source == "blueprint-it" + assert published.id != validator.received[0].id, "the outbound event reuses the inbound id" + + +class TestTheAcknowledgement: + """A normal return acks, and acks once. Read off the consumer, not off the framework.""" + + async def test_the_message_is_acknowledged( + self, nats_app: Any, validator: Validator, jetstream: JetStreamContext, jetstream_stream: str + ) -> None: + """``num_ack_pending`` is the broker's own count of what it is still waiting to be told + about. Zero, with the ack floor advanced, is the acknowledgement having actually landed + rather than the handler merely having returned.""" + async with nats_app(validator.handler): + await jetstream.publish(validator.topic, an_order().model_dump_json().encode()) + await wait_until( + lambda: bool(validator.received), + timeout=10, + description="the handler to be called", + ) + + async def acknowledged() -> bool: + consumer = await only_consumer(jetstream, jetstream_stream) + return bool(consumer.num_ack_pending == 0 and consumer.ack_floor.stream_seq == 1) + + await poll_until(acknowledged, timeout=10, description="the broker to record the acknowledgement") + consumer = await only_consumer(jetstream, jetstream_stream) + + assert consumer.num_ack_pending == 0, "the broker is still waiting for an acknowledgement" + assert consumer.ack_floor.stream_seq == 1, "the acknowledgement did not advance the ack floor" + assert consumer.num_pending == 0, "the stream still holds an undelivered message" + + async def test_it_is_delivered_once_and_not_redelivered( + self, nats_app: Any, validator: Validator, jetstream: JetStreamContext, jetstream_stream: str + ) -> None: + """The same claim from the broker's side, and the one no mock can make. + + An unacknowledged message comes back after ``nats_ack_wait`` -- 2 seconds here -- so + waiting the window out and finding the handler called once is the acknowledgement + working. A test that only asserted ``num_ack_pending == 0`` would pass against a + consumer that had acked and then been redelivered for another reason. + """ + async with nats_app(validator.handler): + await jetstream.publish(validator.topic, an_order().model_dump_json().encode()) + await wait_until( + lambda: bool(validator.received), + timeout=10, + description="the handler to be called", + ) + + await asyncio.sleep(3.0) # nats_ack_wait is 2.0 + + consumer = await only_consumer(jetstream, jetstream_stream) + + assert len(validator.received) == 1, f"the handler ran {len(validator.received)} times" + assert consumer.delivered.stream_seq == 1 + assert consumer.num_redelivered == 0, "the broker redelivered a message it had been told about" + + +class TestWhatTheFrameworkProvisions: + """What the client puts in the stream when nothing else has created one.""" + + async def test_the_subscribed_subject_is_covered( + self, nats_app: Any, validator: Validator, jetstream_stream: str, nats_connection: NatsClient + ) -> None: + """The `jetstream` fixture is deliberately not requested, so the stream below is the + framework's own work.""" + async with nats_app(validator.handler): + info = await nats_connection.jetstream().stream_info(jetstream_stream) + + assert validator.topic in (info.config.subjects or []) + + async def test_the_outbound_subject_is_covered_too( + self, nats_app, validator, jetstream_stream: str, nats_connection, outbound_subject: str + ) -> None: + """The client declares what it publishes, so the stream carries it. + + Before, `_stream_subjects` covered only what was subscribed: a JetStream publish to the + outbound subject waited for an acknowledgement no stream would send, timed out, and was + swallowed as a WARNING -- while a Core NATS subscriber still saw the message, so a live + listener looked healthy and nothing was stored. + """ + async with nats_app(validator.handler): + info = await nats_connection.jetstream().stream_info(jetstream_stream) + + assert outbound_subject in (info.config.subjects or []) diff --git a/tests/integration/test_grouped_agents.py b/tests/integration/test_grouped_agents.py new file mode 100644 index 00000000..dc7af05c --- /dev/null +++ b/tests/integration/test_grouped_agents.py @@ -0,0 +1,200 @@ +"""Two agents in one process, on one broker: C1 by observation. + +The first *chore* from `docs/plans/2026-09-11-broker-integration-tests.md`, and the one the whole +grouping feature rests on. C1 says an agent's broker-side identity derives from **the agent**, not +from the deployment it happens to be in -- so moving an agent between groups, or hosting it beside +a neighbour, must not change what it subscribes to, what queue group it joins, or what durable it +binds. + +The unit tests assert the *names* the framework derives. These assert the *consequence*, which is +a different claim and the one a deployment actually depends on: + +- each agent receives only what is published to its own topics, with a neighbour subscribed to the + broker at the same time; +- the queue group and the durable are the agent's, not the group's -- and are byte-identical to + what the same agent produces deployed alone, which is what makes a regrouping safe; +- the two agents' consumers are separate objects on the server, so neither can consume the + other's backlog. + +Everything here runs against one NATS and one stream, because that is the deployment being +described: one process, one connection per agent, one stream shared by the group. +""" + +import asyncio +import uuid +from typing import Any + +import pytest +from nats.js import JetStreamContext + +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.events import GenericCloudEvent + +from .helpers import wait_until + + +def handler_for(topic: str, seen: list[str]) -> type[EventHandlerBase]: + """A handler subscribed to one topic, recording the ids it is given.""" + + class ScopedHandler(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return [topic] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> None: + seen.append(event.id) + return None + + return ScopedHandler + + +def an_event() -> GenericCloudEvent: + return GenericCloudEvent(id=str(uuid.uuid4()), source="integration-test", type="thing.happened", data={}) + + +class TestEachAgentReceivesOnlyItsOwn: + """A neighbour is on the same broker, the same stream and the same process.""" + + @pytest.fixture + def two_agents(self, agent_names: tuple[str, str], subject_prefix: str) -> dict[str, Any]: + """Two agents, each on a topic of its own, sharing everything else.""" + orders, billing = agent_names + seen: dict[str, list[str]] = {orders: [], billing: []} + topics = {orders: f"{subject_prefix}.orders.created", billing: f"{subject_prefix}.billing.raised"} + handlers = {name: handler_for(topics[name], seen[name]) for name in (orders, billing)} + return {"handlers": handlers, "topics": topics, "seen": seen, "orders": orders, "billing": billing} + + async def test_an_event_reaches_one_agent_and_not_the_other( + self, nats_group: Any, two_agents: dict[str, Any], jetstream: JetStreamContext + ) -> None: + """The claim in its plainest form. Both agents are subscribed, on one connection each, to + one stream -- and a message on one topic is delivered to exactly one of them.""" + orders, billing = two_agents["orders"], two_agents["billing"] + event = an_event() + + async with nats_group(two_agents["handlers"]): + await jetstream.publish(two_agents["topics"][orders], event.model_dump_json().encode()) + await wait_until( + lambda: bool(two_agents["seen"][orders]), + timeout=15, + description=f"agent '{orders}' to receive its own event", + ) + await asyncio.sleep(1.0) # long enough for a misrouted delivery to have arrived + + assert two_agents["seen"][orders] == [event.id] + assert two_agents["seen"][billing] == [], "the neighbour received an event addressed to another agent" + + async def test_each_agent_receives_its_own_when_both_are_published( + self, nats_group: Any, two_agents: dict[str, Any], jetstream: JetStreamContext + ) -> None: + """Both directions at once, so a test cannot pass by one agent simply being idle.""" + orders, billing = two_agents["orders"], two_agents["billing"] + to_orders, to_billing = an_event(), an_event() + + async with nats_group(two_agents["handlers"]): + await jetstream.publish(two_agents["topics"][orders], to_orders.model_dump_json().encode()) + await jetstream.publish(two_agents["topics"][billing], to_billing.model_dump_json().encode()) + + await wait_until( + lambda: bool(two_agents["seen"][orders]) and bool(two_agents["seen"][billing]), + timeout=15, + description="both agents to receive their own event", + ) + await asyncio.sleep(1.0) + + assert two_agents["seen"][orders] == [to_orders.id] + assert two_agents["seen"][billing] == [to_billing.id] + + +class TestTheBrokerSideIdentityIsTheAgents: + """What a regrouping must not change.""" + + @pytest.fixture + def one_topic_each(self, agent_names: tuple[str, str], subject_prefix: str) -> dict[str, Any]: + orders, billing = agent_names + seen: dict[str, list[str]] = {orders: [], billing: []} + topic = f"{subject_prefix}.shared.topic" + return { + "handlers": {name: handler_for(topic, seen[name]) for name in (orders, billing)}, + "topic": topic, + "seen": seen, + "orders": orders, + "billing": billing, + } + + async def test_the_queue_group_is_the_agent_not_the_group(self, nats_group: Any, one_topic_each: dict[str, Any]) -> None: + """`AgentGroup("integration", ...)` is the deployment. Nothing broker-side may carry it, + or moving an agent to another group would move its queue group with it.""" + orders, billing = one_topic_each["orders"], one_topic_each["billing"] + + async with nats_group(one_topic_each["handlers"]) as clients: + assert clients[orders].queue_group == orders + assert clients[billing].queue_group == billing + assert "integration" not in clients[orders].queue_group + + async def test_two_agents_on_one_topic_get_a_durable_each( + self, nats_group: Any, one_topic_each: dict[str, Any], jetstream: JetStreamContext, jetstream_stream: str + ) -> None: + """The sharpest case: both agents subscribe to the *same* subject. Sharing a durable + would make them one consumer splitting the messages between them -- each agent seeing + half its own events, which is the failure P1 and P6 exist to prevent.""" + async with nats_group(one_topic_each["handlers"]): + consumers = await jetstream.consumers_info(jetstream_stream) + + names = sorted(consumer.name for consumer in consumers) + assert len(names) == 2, f"two agents on one subject produced {names}" + assert names[0] != names[1] + + async def test_both_agents_receive_an_event_on_a_subject_they_share( + self, nats_group: Any, one_topic_each: dict[str, Any], jetstream: JetStreamContext + ) -> None: + """The consequence of the durable each: a subject two agents both care about is + delivered to both, rather than being split between them.""" + orders, billing = one_topic_each["orders"], one_topic_each["billing"] + event = an_event() + + async with nats_group(one_topic_each["handlers"]): + await jetstream.publish(one_topic_each["topic"], event.model_dump_json().encode()) + await wait_until( + lambda: bool(one_topic_each["seen"][orders]) and bool(one_topic_each["seen"][billing]), + timeout=15, + description="both agents to receive the shared subject", + ) + + assert one_topic_each["seen"][orders] == [event.id] + assert one_topic_each["seen"][billing] == [event.id] + + +class TestAnAgentIsUnchangedByBeingGrouped: + """The migration claim: the same agent, hosted alone and hosted beside a neighbour, presents + the same names to the broker. Asserted by running it both ways in one test.""" + + async def test_the_queue_group_and_durable_are_byte_identical( + self, nats_group: Any, agent_names: tuple[str, str], subject_prefix: str, jetstream: JetStreamContext, jetstream_stream: str + ) -> None: + """If these differed, regrouping would strand an agent's in-flight backlog on a consumer + nothing binds to any more -- a migration rather than a deployment change.""" + orders, billing = agent_names + topic = f"{subject_prefix}.orders.created" + + async with nats_group({orders: handler_for(topic, [])}) as alone: + alone_group = alone[orders].queue_group + alone_durables = sorted(consumer.name for consumer in await jetstream.consumers_info(jetstream_stream)) + + async with nats_group({orders: handler_for(topic, []), billing: handler_for(f"{subject_prefix}.billing.raised", [])}) as grouped: + grouped_group = grouped[orders].queue_group + grouped_durables = sorted(consumer.name for consumer in await jetstream.consumers_info(jetstream_stream)) + + assert grouped_group == alone_group + assert set(alone_durables) <= set(grouped_durables), ( + f"the durable this agent bound alone ({alone_durables}) is not among the ones it binds " + f"in a group ({grouped_durables}), so its backlog would be stranded by the move" + ) diff --git a/tests/integration/test_harness.py b/tests/integration/test_harness.py new file mode 100644 index 00000000..44db84ae --- /dev/null +++ b/tests/integration/test_harness.py @@ -0,0 +1,213 @@ +"""The harness, tested before anything is tested with it. + +Step 1 of `docs/plans/2026-09-11-broker-integration-tests.md`. Every later broker test rests on +three claims made by `conftest.py`, and a failure in any of them would otherwise surface as a +confusing failure inside the test that used it: + +1. there is a reachable NATS server with JetStream, and a test can publish and receive on it; +2. a test's stream is its own and is gone afterwards, so no two tests -- and no two runs -- + share broker-side state; +3. a real `AppBuilder` application starts against that server and gets as far as *subscribed*. + +The third is the one worth having for its own sake. It is the first time in this repository that +the framework's NATS path runs against a broker rather than a mock, and it stops where step 2 +begins: the application is connected, on its topics and receiving, and nothing here asserts what +it does with an acknowledgement. +""" + +import asyncio +import uuid +from collections.abc import AsyncIterator +from dataclasses import dataclass, field +from typing import Any + +import pytest +from nats.aio.client import Client as NatsClient +from nats.aio.msg import Msg +from nats.js import JetStreamContext +from nats.js.errors import NotFoundError + +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.events import GenericCloudEvent + +from .helpers import wait_until + + +@dataclass +class Recorder: + """The three things a test needs about its handler, kept together rather than unpacked.""" + + handler: type[EventHandlerBase] + topic: str + received: list[GenericCloudEvent] = field(default_factory=list) + + +def subject_prefix_of(stream_name: str) -> str: + """The subject prefix a stream name was derived from -- see the ``jetstream_stream`` fixture.""" + return stream_name.removeprefix("IT_").lower() + + +async def stream_names(js: JetStreamContext) -> AsyncIterator[str]: + """Every stream currently on the server.""" + for stream in await js.streams_info(): + yield stream.config.name + + +class TestTheBroker: + """There is a server, and this directory's fixtures can talk to it.""" + + async def test_a_message_published_is_a_message_received(self, nats_connection: NatsClient, subject_prefix: str) -> None: + """Core NATS, no framework involved: the plainest statement that the harness works. + + If this fails, nothing else in this directory means anything -- which is why it is the + first test in the file. + """ + subject = f"{subject_prefix}.ping" + received: asyncio.Queue[bytes] = asyncio.Queue() + + async def collect(msg: Msg) -> None: + await received.put(msg.data) + + subscription = await nats_connection.subscribe(subject, cb=collect) + await nats_connection.flush() + await nats_connection.publish(subject, b"hello") + + assert await asyncio.wait_for(received.get(), timeout=5) == b"hello" + await subscription.unsubscribe() + + async def test_jetstream_is_enabled(self, jetstream: JetStreamContext, jetstream_stream: str) -> None: + """Without ``--jetstream`` the server accepts the connection and refuses the stream. + + Every subscription then falls back to Core NATS, where there are no durables, no + redelivery and no ``max_deliver`` -- so steps 2 and 3 would be asserting against a + transport that cannot exhibit what they test. + """ + info = await jetstream.stream_info(jetstream_stream) + + assert info.config.name == jetstream_stream + assert info.config.subjects == [f"{subject_prefix_of(jetstream_stream)}.>"] + + +class TestTheStreamIsThisTestsOwn: + """A durable outliving its test carries a delivery count and a filter subject into the next. + + The first two run in file order, which is what makes the pair meaningful: tests above this + class create streams through the fixture, and the second test here asserts that no ``IT_`` + stream from any of them is still on the server. A teardown that stopped working fails it. + """ + + async def test_a_stream_is_created_for_this_test(self, jetstream: JetStreamContext, jetstream_stream: str) -> None: + info = await jetstream.stream_info(jetstream_stream) + + assert info.state.messages == 0, "a stream named for this test already had messages in it" + + async def test_no_stream_from_an_earlier_test_survived_it(self, nats_connection: NatsClient, jetstream_stream: str) -> None: + js = nats_connection.jetstream() + + surviving = [name async for name in stream_names(js) if name.startswith("IT_") and name != jetstream_stream] + + assert surviving == [], f"streams from earlier tests are still on the server: {surviving}" + + async def test_a_name_that_was_never_created_is_simply_absent(self, nats_connection: NatsClient) -> None: + """The teardown swallows an exception for a test that failed before creating its stream. + This pins what that swallowed exception actually is.""" + with pytest.raises(NotFoundError): + await nats_connection.jetstream().stream_info(f"IT_{uuid.uuid4().hex[:12].upper()}") + + +class TestAnApplicationOnTheRealBroker: + """The framework's own NATS path, against a server rather than a mock.""" + + @pytest.fixture + def recorder(self, subject_prefix: str) -> Recorder: + """A handler class subscribed to a subject belonging to this test alone. + + Defined per test rather than at module level because ``with_handler`` is given the + *class* -- the framework constructs it -- so the subject and the list it records into + have to be closed over rather than passed in. A module-level class would carry both + from one test into the next. + """ + topic = f"{subject_prefix}.orders.created" + received: list[GenericCloudEvent] = [] + + class HarnessHandler(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return [topic] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> None: + received.append(event) + return None + + return Recorder(handler=HarnessHandler, topic=topic, received=received) + + async def test_it_connects_and_subscribes(self, nats_app: Any, recorder: Recorder) -> None: + """``subscriptions_ready`` is what the readiness probe gates on, and it is set by the + background retry task rather than by ``subscribe()`` -- so this asserts that the task got + all the way through connect, stream creation and consumer creation.""" + async with nats_app(recorder.handler) as (_, client): + assert client.subscriptions_ready + + async def test_the_client_reports_healthy(self, nats_app: Any, recorder: Recorder) -> None: + async with nats_app(recorder.handler) as (_, client): + health = await client.health_check() + + assert health.status == "healthy", health.message + + async def test_the_queue_group_is_the_agents_identity(self, nats_app: Any, recorder: Recorder, subject_prefix: str) -> None: + """C1: the name derives from the agent, not from the deployment. + + The agent here is the root namespace, so ``_resolve_queue_group`` falls through to + ``nats_queue_group`` -- which the fixture sets per test, because the dead-letter subject + derives from it and a shared one makes two tests' streams overlap. + """ + async with nats_app(recorder.handler) as (_, client): + assert client.queue_group == subject_prefix + + async def test_the_framework_creates_the_stream_it_was_told_to_use( + self, nats_app: Any, recorder: Recorder, jetstream_stream: str, nats_connection: NatsClient + ) -> None: + """``_ensure_stream`` creates the stream named by ``nats_stream_name`` when it is missing + and widens it to cover every subscribed subject. Nothing here creates it -- the + ``jetstream`` fixture is deliberately not requested -- so its existence afterwards is the + framework's doing, and ``jetstream_stream`` still removes it.""" + async with nats_app(recorder.handler): + info = await nats_connection.jetstream().stream_info(jetstream_stream) + + assert recorder.topic in (info.config.subjects or []) + + async def test_a_subscribed_agent_receives_what_is_published_to_its_topic( + self, nats_app: Any, recorder: Recorder, nats_connection: NatsClient + ) -> None: + """The harness's purpose in its smallest form: published from outside the process, + dispatched to a handler inside it. + + Step 2 is this plus the acknowledgement and the outbound result. It is here so that a + step-2 failure reads as being about those, rather than about whether anything arrives. + """ + event = GenericCloudEvent( + id=str(uuid.uuid4()), + source="integration-test", + type="orders.created", + data={"order_id": "1"}, + ) + + async with nats_app(recorder.handler) as (_, client): + await nats_connection.jetstream().publish(recorder.topic, event.model_dump_json().encode()) + + await wait_until( + lambda: bool(recorder.received), + timeout=10, + description=f"the handler subscribed to '{recorder.topic}' to be called", + ) + assert client.inflight_handlers == 0 + + assert [received.id for received in recorder.received] == [event.id] diff --git a/tests/integration/test_shared_redis_cache.py b/tests/integration/test_shared_redis_cache.py index 6be95e2c..527879cf 100644 --- a/tests/integration/test_shared_redis_cache.py +++ b/tests/integration/test_shared_redis_cache.py @@ -4,11 +4,12 @@ when Redis is not reachable, so CI does not need a Redis sidecar unless you explicitly want to run them. -Run with a local Redis: - docker run -d -p 6379:6379 redis:alpine +Run with the services this directory's compose file stands up: + docker compose -f tests/integration/docker-compose.yml up -d pytest tests/integration/test_shared_redis_cache.py -v """ +import json import subprocess import sys import textwrap @@ -16,9 +17,14 @@ import pytest import redis +from .conftest import COMPOSE_HINT + REDIS_URL = "redis://localhost:6379/0" KEY_PREFIX = "pytest_shared_cache" +IMPORT_BUDGET_SECONDS = 60 +"""What the reader subprocess is allowed, almost all of it spent importing. See ``_run_reader``.""" + # --------------------------------------------------------------------------- # Fixture: skip the whole module when Redis is unavailable @@ -32,7 +38,7 @@ def redis_url() -> str: client.ping() client.close() except Exception: - pytest.skip("Redis is not available at localhost:6379 — skipping integration tests") + pytest.skip("Redis is not available at localhost:6379. Start it with: " + COMPOSE_HINT) return REDIS_URL @@ -65,6 +71,13 @@ def _run_reader(redis_url: str, key: str, namespace: str, key_prefix: str) -> di """Spawn a subprocess that creates its own RedisCacheService and reads one key. Returns the cached value (dict) if the key is found, otherwise None. + + **The timeout is an import budget, not a Redis one.** The child imports + ``blueprint.agents`` -- and through it pydantic-ai -- before it touches the cache at all, + which measures 11.5s cold on a Windows developer machine. The original 10s therefore failed + this test on the first run where Redis was actually up, with a ``TimeoutExpired`` traceback + pointing at ``subprocess.py`` rather than at anything in this repository. The read itself is + a single round trip to localhost. """ script = textwrap.dedent(f""" import json, sys @@ -76,17 +89,28 @@ def _run_reader(redis_url: str, key: str, namespace: str, key_prefix: str) -> di sys.exit(1) print(json.dumps(value)) """) - result = subprocess.run( - [sys.executable, "-c", script], - capture_output=True, - text=True, - timeout=10, - ) + try: + result = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + timeout=IMPORT_BUDGET_SECONDS, + ) + except subprocess.TimeoutExpired as expired: + raise AssertionError( + f"The reader subprocess did not finish within {IMPORT_BUDGET_SECONDS}s. It spends most of that " + "importing the framework, so this is a slow machine or a slow import rather than a slow cache." + ) from expired + if result.returncode != 0: + # The child exits 1 for a cache miss, which is a legitimate answer, and non-zero for + # anything else -- which is not, and used to be reported as a miss. Its stderr is the + # only account of what went wrong, so it travels with the None. + if result.stderr.strip(): + raise AssertionError("The reader subprocess failed:\n" + result.stderr.strip()) return None - try: - import json + try: return json.loads(result.stdout.strip()) except Exception: return None diff --git a/tests/unit/agent_generator/cli/commands/test_create_agent.py b/tests/unit/agent_generator/cli/commands/test_create_agent.py new file mode 100644 index 00000000..0fd43894 --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_create_agent.py @@ -0,0 +1,78 @@ +"""What ``asbs create agent`` writes into ``settings.toml``, read back by the framework. + +The command's whole output is a pair of prompt files, a block of configuration and a +registration in ``main.py``. The configuration block is the half nothing would report if it were +wrong: a table whose name the framework does not look up is not an error, it is simply never +read, and the project runs with the defaults while the file says otherwise. So the assertion +here is not that the text was written -- it is that ``Config`` hands the written values back. +""" + +from argparse import Namespace +from pathlib import Path + +import pytest + +from blueprint.agent_generator.cli.commands.create import create_agent +from blueprint.agents.config import Config + +AGENT = "pricing" +RUNTIME = "pricing_agent" + + +@pytest.fixture +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> Path: + """Run ``asbs create agent pricing`` in an otherwise empty project and return its root. + + ``create_agent`` reads the working directory rather than an output path, so the directory is + what has to be moved into. + """ + (tmp_path / "settings.toml").write_text( + '[default]\napp_name = "the-project"\napp_environment = "development"\n' + 'model_provider = "openai"\nmodel_api_key = "not-a-real-key"\n', + encoding="utf-8", + ) + monkeypatch.chdir(tmp_path) + create_agent(Namespace(name=AGENT)) + capsys.readouterr() + return tmp_path + + +def load(project: Path) -> Config: + return Config(settings_files=["settings.toml"], root_path=str(project)) + + +class TestTheRuntimeItConfigures: + def test_the_model_is_the_one_written(self, project: Path) -> None: + ai_config = load(project).get_ai_config(RUNTIME) + + assert ai_config.provider == "openai" + assert ai_config.model_name == "gpt-5-mini" + + def test_the_model_settings_reach_the_provider_client(self, project: Path) -> None: + """Written as ``[.models]`` these were read by nothing: ``get_ai_config`` looks up + ``runtimes..model_settings``, and hands exactly that to the client.""" + assert load(project).get_ai_config(RUNTIME).model_settings == { + "openai_reasoning_effort": "low", + "openai_reasoning_summary": "detailed", + } + + def test_no_table_is_written_that_nothing_reads(self, project: Path) -> None: + assert ".models]" not in (project / "settings.toml").read_text(encoding="utf-8") + + +class TestWhenThereIsNoMainPyToRegisterIn: + """The fallback path has to survive being taken.""" + + def test_it_prints_the_registration_to_add_by_hand( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] + ) -> None: + """The runtime name was derived inside the try block that needs ``src/main.py``, so the + instructions printed when that file is missing raised ``UnboundLocalError`` instead -- + after the prompts and the settings block had already been written.""" + monkeypatch.chdir(tmp_path) + + create_agent(Namespace(name=AGENT)) + + printed = capsys.readouterr().out + assert f'.with_agent({RUNTIME}, name="{RUNTIME}")' in printed + assert f'AgentBuilder(runtime_name="{RUNTIME}")' in printed diff --git a/tests/unit/agent_generator/cli/test_created_imports.py b/tests/unit/agent_generator/cli/test_created_imports.py new file mode 100644 index 00000000..ad9690a0 --- /dev/null +++ b/tests/unit/agent_generator/cli/test_created_imports.py @@ -0,0 +1,78 @@ +"""What ``asbs create`` adds to ``src/main.py`` is written the way that file already writes. + +The generator emits relative imports throughout -- `from .handlers import OrderHandler` in +`main.py`, `from ..services import OrderService` in a component -- and `asbs create` used to +append absolute ones: `from src.handlers.order_placed_handler import OrderPlacedHandler`. Both +resolve, which is why nothing failed and why it survived; two styles in one file is how a later +move breaks exactly one of them. +""" + +import json +from argparse import Namespace +from pathlib import Path + +import pytest + +from blueprint.agent_generator.cli.commands.create import create_api, create_handler, create_service +from blueprint.agent_generator.cli.commands.setup import create_basic_config +from blueprint.agent_generator.generator.generator import AgentGenerator + +PROJECT_NAME = "ImportDemo" + + +@pytest.fixture +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> Path: + """A scaffolded project, with the working directory inside it. + + The create commands read `Path.cwd()` for the project root and write their component file + into `--output-dir`, so both have to be arranged for them. + """ + config_file = tmp_path / "generator-config.json" + config_file.write_text(json.dumps(create_basic_config(PROJECT_NAME)), encoding="utf-8") + generator = AgentGenerator(str(config_file), str(tmp_path)) + generator.load_config() + generator.generate() + + monkeypatch.chdir(tmp_path) + capsys.readouterr() + return tmp_path + + +def main_py(project: Path) -> str: + return (project / "src" / "main.py").read_text(encoding="utf-8") + + +class TestEveryImportAddedIsRelative: + """``from src.`` in a file whose own imports start with ``.`` is the mismatch under test.""" + + def test_the_scaffolded_file_starts_out_relative(self, project: Path) -> None: + """The premise: the style being matched is the generator's, not one invented here.""" + assert "from .handlers import" in main_py(project) + assert "from src." not in main_py(project) + + def test_a_created_handler_is_imported_relatively(self, project: Path, capsys: pytest.CaptureFixture[str]) -> None: + create_handler(Namespace(name="OrderPlaced", event_type="order.placed", output_dir=str(project / "src" / "handlers"), priority=10)) + capsys.readouterr() + + assert "from .handlers.order_placed_handler import OrderPlacedHandler" in main_py(project) + assert "from src." not in main_py(project) + + def test_a_created_service_is_imported_relatively(self, project: Path, capsys: pytest.CaptureFixture[str]) -> None: + create_service(Namespace(name="Pricing", output_dir=str(project / "src" / "services"))) + capsys.readouterr() + + assert "from .services.pricing_service import PricingService" in main_py(project) + assert "from src." not in main_py(project) + + def test_a_created_api_imports_its_models_relatively_too(self, project: Path, capsys: pytest.CaptureFixture[str]) -> None: + """Two files at once: the import added to `main.py`, and the one inside the API module + the command writes -- which is a package deeper, so it needs `..` rather than `.`.""" + create_api(Namespace(name="Pricing", output_dir=str(project / "src" / "api"))) + capsys.readouterr() + + assert "from .api.pricing_api import PricingApi" in main_py(project) + assert "from src." not in main_py(project) + + api_source = (project / "src" / "api" / "pricing_api.py").read_text(encoding="utf-8") + assert "from ..models." in api_source + assert "from src." not in api_source diff --git a/tests/unit/agent_generator/cli/test_main.py b/tests/unit/agent_generator/cli/test_main.py new file mode 100644 index 00000000..b2833b8d --- /dev/null +++ b/tests/unit/agent_generator/cli/test_main.py @@ -0,0 +1,69 @@ +"""The CLI's own output encoding. + +`asbs` prints check marks, warning signs and box drawing. Python encodes stdout with the locale +encoding, and on Windows that is cp1252, which has none of those characters -- so the first line +of output raised `UnicodeEncodeError`, and it did so *mid-command*: `asbs create handler` died +after writing the handler file and before registering it in `main.py`. + +The rule the fix keeps: what the CLI **prints** may be UTF-8, and what it **writes** stays ASCII. +The second half is asserted in `tests/unit/agent_generator/generator/test_generated_project.py`. +""" + +import io + +import pytest + +from blueprint.agent_generator.cli.main import use_utf8 + + +class RefusesEncoding(io.StringIO): + """A stream that will not change encoding but will change error handling. + + Stands in for a handle Python has already committed to an encoding -- the case the fallback + exists for, and one that cannot be produced reliably in a test by redirecting anything. + """ + + def __init__(self) -> None: + super().__init__() + self.errors_set: str | None = None + + def reconfigure(self, *, encoding: str | None = None, errors: str | None = None) -> None: # type: ignore[override] + if encoding is not None: + raise ValueError("cannot change encoding on this stream") + self.errors_set = errors + + +class TakesNothing(io.StringIO): + """A stream with no ``reconfigure`` at all, which must not be an error.""" + + reconfigure = None # type: ignore[assignment] + + +class TestTheOutputEncoding: + def test_a_stream_is_reconfigured_to_utf8(self) -> None: + stream = io.StringIO() + stream.reconfigure = lambda **kwargs: setattr(stream, "seen", kwargs) # type: ignore[attr-defined,method-assign] + + use_utf8(stream) + + assert stream.seen == {"encoding": "utf-8", "errors": "replace"} # type: ignore[attr-defined] + + def test_a_stream_that_refuses_utf8_still_stops_raising(self) -> None: + """The fallback: a lost glyph becomes '?' in a log rather than an abandoned command.""" + stream = RefusesEncoding() + + use_utf8(stream) + + assert stream.errors_set == "replace" + + def test_a_stream_without_reconfigure_is_left_alone(self) -> None: + use_utf8(TakesNothing()) # must not raise + + @pytest.mark.parametrize("glyph", ["\u2713", "\u26a0", "\u251c", "\u2500"]) + def test_the_glyphs_the_cli_prints_survive_the_round_trip(self, glyph: str) -> None: + """cp1252 has none of these: the check mark, the warning sign and two box-drawing + characters, which between them are every non-ASCII character the commands print.""" + with pytest.raises(UnicodeEncodeError): + glyph.encode("cp1252") + + assert glyph.encode("utf-8").decode("utf-8") == glyph diff --git a/tests/unit/agent_generator/generator/test_generated_project.py b/tests/unit/agent_generator/generator/test_generated_project.py index e44b7a1a..617b8c14 100644 --- a/tests/unit/agent_generator/generator/test_generated_project.py +++ b/tests/unit/agent_generator/generator/test_generated_project.py @@ -10,6 +10,7 @@ import importlib import json +import re import sys import tomllib from collections.abc import Iterator @@ -17,12 +18,16 @@ from pathlib import Path import pytest +from fastapi import FastAPI from blueprint.agent_generator.cli.commands.setup import create_basic_config from blueprint.agent_generator.generator.generator import AgentGenerator from blueprint.agents.app_builder import AppBuilder from blueprint.agents.component.component import Component from blueprint.agents.component.namespace import validate_namespace +from blueprint.agents.config import Config +from blueprint.agents.config.config import DEFAULT_SETTINGS_FILES +from blueprint.agents.entrypoint import build_group_app PROJECT_NAME = "InvoiceProcessor" AGENT_NAMESPACE = "invoice_processor" @@ -166,14 +171,212 @@ class TestWhatTheProjectShips: def test_the_secrets_file_and_its_template_land_in_the_project(self, project: Path) -> None: """create_file() with no argument writes relative to the working directory, so the secrets file used to be left wherever `asbs setup` was run from.""" - assert (project / "secrets.toml").is_file() - assert (project / "secrets.toml.example").is_file() + assert (project / ".secrets.toml").is_file() + assert (project / ".secrets.toml.example").is_file() + + def test_the_secrets_file_is_the_one_the_framework_loads(self, project: Path) -> None: + """The name is the whole of it. `DEFAULT_SETTINGS_FILES` is what `entrypoint.py` hands to + `Config`, so a file called anything else is loaded by nothing and reports nothing.""" + assert ".secrets.toml" in DEFAULT_SETTINGS_FILES + assert not (project / "secrets.toml").exists() + + def test_the_project_configures_itself_from_the_files_the_image_reads(self, project: Path) -> None: + """The regression this closes: `asbs setup` produced a project that could not start. + Its `model_provider = "vllm"` makes the API key a validated requirement, and the key is + in the secrets file, so an unloaded secrets file was a `ConfigError` on an unedited + project rather than a missing value somewhere later.""" + config = Config(settings_files=DEFAULT_SETTINGS_FILES, root_path=str(project)) + + assert config.get_ai_config().api_key + + def test_it_ships_the_tests_directory_its_own_validator_requires(self, project: Path) -> None: + """`asbs validate` requires `tests/`, so a scaffolded project used to fail the validation + of the tool that made it.""" + assert (project / "tests" / "test_declaration.py").is_file() + assert (project / "tests" / "test_mapper.py").is_file() + + def test_a_pyproject_is_written_when_the_directory_has_none(self, project: Path) -> None: + """`asbs validate` requires one, and a directory with no pyproject has nothing to lose.""" + document = tomllib.loads((project / "pyproject.toml").read_text(encoding="utf-8")) + + assert document["project"]["name"] + assert "avs-blueprint-agents" in document["project"]["dependencies"] + + def test_an_existing_pyproject_is_left_alone(self, tmp_path: Path) -> None: + """`asbs` is installed into the project's own environment, so by the time it can run + there is usually a pyproject already -- somebody's, with their dependencies in it. + Writing over it would be this tool destroying the file that made it runnable.""" + theirs = '[project]\nname = "already-here"\nversion = "9.9.9"\n' + (tmp_path / "pyproject.toml").write_text(theirs, encoding="utf-8") + config_file = tmp_path / "generator-config.json" + config_file.write_text(json.dumps(create_basic_config(PROJECT_NAME)), encoding="utf-8") + + generator = AgentGenerator(str(config_file), str(tmp_path)) + generator.load_config() + generator.generate() + + assert (tmp_path / "pyproject.toml").read_text(encoding="utf-8") == theirs + + def test_the_tests_import_the_declaration_without_any_pytest_configuration(self, project: Path) -> None: + """`test_declaration.py` imports `src.main` -- what `agents.toml` names and what the + entry point imports -- so the project root has to be importable. `tests/conftest.py` does + that itself rather than relying on a `pythonpath` setting in somebody else's pyproject. + """ + conftest = (project / "tests" / "conftest.py").read_text(encoding="utf-8") + + assert "sys.path.insert" in conftest + assert "PROJECT_ROOT" in conftest def test_the_secrets_file_is_git_ignored_and_the_template_is_not(self, project: Path) -> None: - ignored = (project / ".gitignore").read_text(encoding="utf-8") + """Read as patterns rather than as text: a comment naming the example file would + otherwise pass for a rule ignoring it, in either direction.""" + patterns = [line.strip() for line in (project / ".gitignore").read_text(encoding="utf-8").splitlines() if line.strip()] + patterns = [line for line in patterns if not line.startswith("#")] - assert "secrets.toml" in ignored - assert "secrets.toml.example" not in ignored + assert "**/.secrets.toml" in patterns + assert not [line for line in patterns if line.endswith(".example") or line.endswith(".secrets.*")] + + +class TestTheGeneratedSettingsAreRead: + """Every key the scaffolded ``settings.toml`` writes is a key the framework looks up. + + A settings file is the one place a developer expects to be believed, and a key in the wrong + shape fails silently in both directions: nothing reads it, and nothing says so. These tests + load the generated file through a real ``Config`` and assert the value in the file is the + value that comes back -- flipping each one first, so what is asserted is that the key is + live rather than that its value happens to match the framework's default. + """ + + @staticmethod + def _loaded(project: Path, tmp_path: Path, **overrides: str) -> Config: + """Load the generated settings file, with the named keys rewritten to new values. + + The generated ``secrets.toml`` is loaded alongside it and named explicitly, because the + scaffolded ``model_provider = "vllm"`` makes the API key a validated requirement. + """ + body = (project / "settings.toml").read_text(encoding="utf-8") + for key, value in overrides.items(): + replaced = re.subn(rf"^{key} = .*$", f"{key} = {value}", body, count=1, flags=re.MULTILINE) + assert replaced[1] == 1, f"the generated settings.toml no longer writes a top-level '{key}'" + body = replaced[0] + + (tmp_path / "settings.toml").write_text(body, encoding="utf-8") + (tmp_path / ".secrets.toml").write_text((project / ".secrets.toml").read_text(encoding="utf-8"), encoding="utf-8") + return Config(settings_files=DEFAULT_SETTINGS_FILES, root_path=str(tmp_path)) + + def test_telemetry_turns_on_from_the_file(self, project: Path, tmp_path: Path) -> None: + """Under ``[default.observability]`` this was inert: the file said true and read False.""" + config = self._loaded(project, tmp_path, otel_enabled="true") + + assert config.get_observability_config().otel_enabled is True + + def test_token_metrics_turn_off_from_the_file(self, project: Path, tmp_path: Path) -> None: + config = self._loaded(project, tmp_path, token_metrics_enabled="false") + + assert config.get_observability_config().token_metrics_enabled is False + + def test_the_log_level_is_the_one_the_file_states(self, project: Path, tmp_path: Path) -> None: + config = self._loaded(project, tmp_path, log_level='"WARNING"') + + assert config.get_observability_config().log_level == "WARNING" + assert config.get("log_format") == "text" + + def test_no_table_is_written_that_nothing_reads(self, project: Path) -> None: + """The framework reads these four flat. A section of the same name is dead weight that + reads as configuration.""" + default = tomllib.loads((project / "settings.toml").read_text(encoding="utf-8"))["default"] + + assert "logging" not in default + assert "observability" not in default + + +class TestTheProjectTheEntryPointBuilds: + """`asbs setup` produces a project that `python -m blueprint.agents.entrypoint` can run. + + Every other test here reads the declaration; this one builds it, through the same function + the container's command calls. That is the only way this class of defect surfaces: the + declaration was always well-formed, and what failed was the construction of what it + declared. Nothing is started -- the lifespan is where an agent reaches for its model -- so + this asserts assembly, not a working LLM. + """ + + @pytest.fixture + def built(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[FastAPI]: + """Build the group the entry point would, with the project as the working directory. + + `Config` resolves `settings.toml` and `.secrets.toml` relative to the working directory + and the agent's prompts relative to `prompt_directory`, so the chdir is what the + container does by having WORKDIR /app. The registry is process-global, hence the reset. + """ + saved_path = list(sys.path) + saved_modules = {name: module for name, module in sys.modules.items() if name == "src" or name.startswith("src.")} + for name in saved_modules: + del sys.modules[name] + + monkeypatch.chdir(project) + sys.path.insert(0, str(project)) + try: + app, _ = build_group_app(environ={"BLUEPRINT_AGENTS": AGENT_NAMESPACE, "BLUEPRINT_GROUP": "test"}) + yield app + finally: + Component.reset_shared_state() + for name in [name for name in sys.modules if name == "src" or name.startswith("src.")]: + del sys.modules[name] + sys.modules.update(saved_modules) + sys.path[:] = saved_path + + def test_the_group_assembles(self, built: FastAPI) -> None: + """`AgentBuilder.build()` constructed `AgentRuntime` without the name it requires, so + this raised `TypeError` -- for every scaffolded project, and for any group at all.""" + assert isinstance(built, FastAPI) + + def test_the_agents_components_are_registered_under_its_namespace(self, built: FastAPI) -> None: + registry = Component.shared_registry + assert registry is not None + names = registry.get_component_names_by_type(Component, AGENT_NAMESPACE) + + assert names, "the agent was assembled with no components of its own" + assert all(name.startswith(f"{AGENT_NAMESPACE}_") for name in names), names + + +class TestEverythingWrittenIsAscii: + """What the CLI prints may be UTF-8; what it writes may not. + + The repository's rule is ASCII in source, and a scaffolded project is source somebody else + then owns -- so an em-dash or a check mark the generator emitted would be a rule violation + the recipient inherits and did not choose. This is also the half of the console fix that has + to be held in place: `use_utf8` makes the CLI's *output* UTF-8, and nothing about that should + reach a file. + """ + + @pytest.fixture + def untouched(self, tmp_path: Path) -> Path: + """A project generated for this test alone, and never run. + + Not the module's shared ``project``: other tests import ``src.main`` and build the group + inside it, which leaves ``__pycache__`` behind -- and a ``.pyc`` is binary, so the check + would fail on an artefact the generator never wrote. What is under test is what the + generator emits, so it has to be looked at before anything else has been there. + """ + config_file = tmp_path / "generator-config.json" + config_file.write_text(json.dumps(create_basic_config(PROJECT_NAME)), encoding="utf-8") + + generator = AgentGenerator(str(config_file), str(tmp_path)) + generator.load_config() + generator.generate() + return tmp_path + + def test_no_generated_file_contains_a_non_ascii_byte(self, untouched: Path) -> None: + offenders: list[str] = [] + for path in sorted(untouched.rglob("*")): + if not path.is_file() or path.name == "generator-config.json": + continue + try: + path.read_text(encoding="ascii") + except UnicodeDecodeError as decoded: + offenders.append(f"{path.relative_to(untouched).as_posix()}: {decoded.reason} at byte {decoded.start}") + + assert offenders == [], "the generator wrote non-ASCII into: " + "; ".join(offenders) class TestTheImage: diff --git a/tests/unit/agents/agent/test_agent_builder.py b/tests/unit/agents/agent/test_agent_builder.py index ed96d5f4..35c324af 100644 --- a/tests/unit/agents/agent/test_agent_builder.py +++ b/tests/unit/agents/agent/test_agent_builder.py @@ -63,11 +63,24 @@ def test_build_resolves_the_ai_config(self, builder: AgentBuilder, mock_ai_confi assert builder._ai_config is mock_ai_config def test_a_model_name_override_is_applied_at_build(self, builder: AgentBuilder, mock_ai_config: MagicMock) -> None: + """The rest of the build is stubbed rather than allowed to fail. + + This used to assert that ``build()`` raised *something* and then read the override out + of the wreckage. What it raised was ``AgentRuntime.__init__() missing 1 required + positional argument: 'name'`` -- so the test passed because of a defect, and started + failing when that was fixed. It asserts the override and nothing else now. + """ builder.with_model_from_config(model_name="override-model") assert mock_ai_config.model_name == "gpt-4o" - with pytest.raises(Exception): # noqa: B017 -- the build path beyond the override is not under test - builder.build() + with patch.dict( + "blueprint.agents.agent.agent_builder._CLIENT_MAP", + {"openai": MagicMock(return_value=MagicMock())}, + ): + with patch("blueprint.agents.agent.agent_builder.PromptLoader.load_prompt", return_value="prompt"): + with patch("blueprint.agents.agent.agent_builder.AgentRuntime"): + builder.build() + assert mock_ai_config.model_name == "override-model" def test_deprecated_runtime_name_logs_warning(self, builder: AgentBuilder, caplog: pytest.LogCaptureFixture) -> None: @@ -252,6 +265,31 @@ def test_build_requires_system_prompt(self, builder_with_model: AgentBuilder) -> with pytest.raises(ValueError, match="System prompt must be configured"): builder_with_model.build() + def test_the_runtime_is_named_after_the_builders_runtime_name(self, builder_with_model: AgentBuilder) -> None: + """AgentRuntime takes its name as a required argument and nothing passed one, so every + build through AppBuilder raised TypeError. The name is the key the runtime's own + configuration is read under, which is the one the builder already holds.""" + builder_with_model._system_prompt = "system" + with patch.dict( + "blueprint.agents.agent.agent_builder._CLIENT_MAP", + {"openai": MagicMock(return_value=MagicMock())}, + ): + runtime = builder_with_model.build() + + assert runtime.name == "test-agent" + + def test_an_explicit_name_wins_over_the_runtime_name(self, builder_with_model: AgentBuilder) -> None: + """setdefault, not a positional argument: build(config, name=...) is a legal call and a + positional would have made it a duplicate-argument TypeError.""" + builder_with_model._system_prompt = "system" + with patch.dict( + "blueprint.agents.agent.agent_builder._CLIENT_MAP", + {"openai": MagicMock(return_value=MagicMock())}, + ): + runtime = builder_with_model.build(name="given-here") + + assert runtime.name == "given-here" + def test_build_raises_for_conflicting_kwarg(self, builder_with_model: AgentBuilder) -> None: builder_with_model._system_prompt = "system" with patch.dict( diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index e23d9c2d..fbcf0a91 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -8,6 +8,7 @@ import pytest from nats.js import api as js_api +from blueprint.agents.clients.io.io_client_base import subject_is_covered_by from blueprint.agents.clients.io.nats_client import ConsumerTuning, NATSClient from blueprint.agents.models.errors import CriticalHandlerError, InvalidEventError, RetryableHandlerError from blueprint.agents.models.events import CloudEvent @@ -474,7 +475,9 @@ async def test_publish_uses_jetstream_when_enabled( mock_nc, mock_js = mock_nats_jetstream nats_client._nats_client = mock_nc nats_client._client = mock_nc - nats_client._use_jetstream = True + # The publish mode, not the consumption flag: this used to set _use_jetstream, which is + # the coupling the two keys now separate. + nats_client._publish_via_jetstream = True await nats_client.publish("js-topic", cloud_event) @@ -482,6 +485,26 @@ async def test_publish_uses_jetstream_when_enabled( topic_arg = mock_js.publish.call_args[0][0] assert topic_arg == "js-topic" + async def test_durable_consumption_alone_does_not_make_publishing_durable( + self, + nats_client: NATSClient, + mock_nats_jetstream: tuple, + cloud_event: CloudEvent, + ) -> None: + """The separation, stated: `nats_use_jetstream` is about consumers. A client consuming + durably and publishing fire-and-forget is a legitimate shape, and used to be unreachable. + """ + mock_nc, mock_js = mock_nats_jetstream + nats_client._nats_client = mock_nc + nats_client._client = mock_nc + nats_client._use_jetstream = True + nats_client._publish_via_jetstream = False + + await nats_client.publish("core-topic", cloud_event) + + mock_js.publish.assert_not_awaited() + mock_nc.publish.assert_awaited_once() + async def test_publish_raises_on_nats_error( self, connected_nats_client: NATSClient, @@ -1626,3 +1649,136 @@ async def test_a_reconnect_does_not_undo_a_pause(self, subscribed: NATSClient) - await subscribed._on_reconnected() subscribe_all.assert_not_awaited() assert subscribed.subscriptions_ready is False + + +class TestNATSClientPublishMode: + """Publishing and consuming are two decisions, and used to share one key. + + ``nats_use_jetstream`` exists so *consumers* can be durable. ``publish()`` read the same + flag, so turning durability on for consumption silently made every outbound event a + JetStream publish -- which stalls and is dropped when the subject is not in the stream. + """ + + def test_it_follows_the_consumption_flag_when_unset(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """No existing deployment changes: unset, the behaviour is exactly what it was.""" + mock_config.get.side_effect = lambda key, default=None: {"nats_publish_mode": None}.get(key, default) + nats_client._use_jetstream = True + + assert nats_client._resolve_publish_mode() is True + + def test_core_can_be_chosen_while_consuming_durably(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """The case the split exists for: durable consumption, fire-and-forget notifications.""" + mock_config.get.side_effect = lambda key, default=None: {"nats_publish_mode": "core"}.get(key, default) + nats_client._use_jetstream = True + + assert nats_client._resolve_publish_mode() is False + + def test_jetstream_can_be_chosen_while_consuming_from_core(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda key, default=None: {"nats_publish_mode": "JetStream "}.get(key, default) + nats_client._use_jetstream = False + + assert nats_client._resolve_publish_mode() is True + + def test_an_unknown_mode_is_refused_with_both_meanings(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + mock_config.get.side_effect = lambda key, default=None: {"nats_publish_mode": "durable"}.get(key, default) + + with pytest.raises(ValueError, match="must be 'core' or 'jetstream'"): + nats_client._resolve_publish_mode() + + +class TestNATSClientPublishSubjects: + """What the client declares it may publish to, and what the stream therefore carries.""" + + @staticmethod + def _config(mock_config: MagicMock, **values: object) -> None: + mock_config.get.side_effect = lambda key, default=None: values.get(key, default) + + def test_the_configured_topic_mapping_is_the_source(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """Where an outbound subject is already written down: a HandlerResult is routed by it.""" + self._config( + mock_config, + **{"event_publishing.topic_mapping": {"order.validated": {"topic": "orders.validated"}}}, + ) + + assert nats_client._resolve_publish_subjects() == {"orders.validated"} + + def test_an_explicit_list_covers_what_the_mapping_cannot(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """``publish_event(topic=...)`` bypasses the mapping, so it needs somewhere to be said.""" + self._config(mock_config, nats_publish_subjects=["audit.trail"]) + + assert nats_client._resolve_publish_subjects() == {"audit.trail"} + + def test_a_wildcard_topic_is_refused(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """Published, a wildcard is taken literally: the message lands on a subject with an + asterisk in it and no subscriber to the pattern receives it.""" + self._config(mock_config, **{"event_publishing.topic_mapping": {"order.validated": {"topic": "orders.*"}}}) + + with pytest.raises(ValueError, match="only meaningful when subscribing"): + nats_client._resolve_publish_subjects() + + def test_a_greater_than_wildcard_is_refused_too(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._config(mock_config, nats_publish_subjects=["orders.>"]) + + with pytest.raises(ValueError, match="cannot be published to"): + nats_client._resolve_publish_subjects() + + def test_whitespace_is_refused(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._config(mock_config, nats_publish_subjects=["orders validated"]) + + with pytest.raises(ValueError, match="cannot be published to"): + nats_client._resolve_publish_subjects() + + def test_the_stream_carries_what_is_published_durably(self, nats_client: NATSClient) -> None: + """The defect this closes: the stream covered what was subscribed and nothing else, so a + JetStream publish waited for an acknowledgement no stream would send.""" + nats_client._topic_callbacks = {"orders.created": AsyncMock()} + nats_client._publish_subjects = {"orders.validated"} + nats_client._publish_via_jetstream = True + + assert "orders.validated" in nats_client._stream_subjects() + + def test_the_stream_does_not_carry_them_when_publishing_is_fire_and_forget(self, nats_client: NATSClient) -> None: + """Core publishing stores nothing, so widening the stream for it would claim subjects + this deployment has no reason to own.""" + nats_client._topic_callbacks = {"orders.created": AsyncMock()} + nats_client._publish_subjects = {"orders.validated"} + nats_client._publish_via_jetstream = False + + assert "orders.validated" not in nats_client._stream_subjects() + + +class TestStreamSubjectCoverage: + """A wildcard on the stream already carries the literals underneath it. + + Compared as strings they look absent, so the client asked the server to add them and the + server refused the update as an overlap -- and the client then logged that consumers would + fail to bind, when the wildcard means they bind fine. The message was the defect. + """ + + @pytest.mark.parametrize( + ("subject", "pattern", "covered"), + [ + ("orders.created", "orders.created", True), + ("orders.created", "orders.>", True), + ("orders.created", "orders.*", True), + ("orders.created.eu", "orders.>", True), + ("orders.created.eu", "orders.*", False), + ("orders.created", "billing.>", False), + ("orders", "orders.>", False), + ("orders.created", "*.created", True), + ("orders.created", "orders.created.>", False), + ], + ) + def test_coverage(self, subject: str, pattern: str, covered: bool) -> None: + assert subject_is_covered_by(subject, pattern) is covered + + def test_a_wildcard_stream_needs_no_widening(self, nats_client: NATSClient) -> None: + """The case the harness hits every run: an operator-provisioned `orders.>` stream, and a + client subscribing a literal beneath it. Every subject it wants is already carried.""" + nats_client._topic_callbacks = {"orders.created": AsyncMock()} + nats_client._tuning = None + + wanted = {subject for subject in nats_client._stream_subjects() if subject.startswith("orders.")} + + assert wanted, "the client wanted no subjects at all, so this asserts nothing" + assert all(subject_is_covered_by(subject, "orders.>") for subject in wanted) diff --git a/tests/unit/agents/component/test_name_uniqueness.py b/tests/unit/agents/component/test_name_uniqueness.py index 9ebe3099..c55ce3d2 100644 --- a/tests/unit/agents/component/test_name_uniqueness.py +++ b/tests/unit/agents/component/test_name_uniqueness.py @@ -10,6 +10,7 @@ import pytest +from blueprint.agents.agent.agent_runtime import AgentRuntime from blueprint.agents.component.component import Component from blueprint.agents.component.namespace import namespace_scope, qualified_component_name from blueprint.agents.config import Config @@ -99,6 +100,58 @@ def test_a_rename_at_the_root_is_unchanged(self, config: Config) -> None: assert planner.name == "db" +class TestAnAgentRuntimeIsNamedLikeEveryOtherComponent: + """It used to register itself by hand, under the bare name, and was the only one that did.""" + + def test_it_carries_its_agent(self, config: Config) -> None: + with namespace_scope("orders"): + runtime = AgentRuntime(name="assistant") + + assert (runtime.name, registry_names()) == ("orders_assistant", ["orders_assistant"]) + + def test_two_agents_can_each_have_one_of_the_same_name(self, config: Config) -> None: + """Registered bare, the second of these raised 'name is already taken' -- so a group + could not host two agents whose runtimes happened to share a name.""" + with namespace_scope("orders"): + AgentRuntime(name="assistant") + with namespace_scope("billing"): + AgentRuntime(name="assistant") + + assert registry_names() == ["billing_assistant", "orders_assistant"] + + def test_the_root_keeps_the_bare_name(self, config: Config) -> None: + """A single-agent application's registry key, and every lookup of it, is unchanged.""" + runtime = AgentRuntime(name="assistant") + + assert (runtime.name, registry_names()) == ("assistant", ["assistant"]) + + def test_it_is_found_by_the_bare_name_from_inside_its_own_agent(self, config: Config) -> None: + """What qualification must not cost: user code asks for the name it declared.""" + with namespace_scope("orders"): + runtime = AgentRuntime(name="assistant") + + assert Component.shared_registry.get_agent("assistant", "orders") is runtime + + def test_base_name_is_the_name_it_was_given(self, config: Config) -> None: + """Left unset by the hand-rolled registration, it said 'agent_runtime' for every agent -- + and it is what the readiness entry and the OpenAPI tag are rendered from.""" + with namespace_scope("orders"): + runtime = AgentRuntime(name="assistant") + + assert runtime.base_name == "assistant" + + def test_a_rename_moves_the_registry_key(self, config: Config) -> None: + """Assigning the declaration's name is what AppBuilder._construct does to every + component. Agent.name.fset used to run first and overwrite the field Component's setter + reads as the current key, so this raised 'does not exist'.""" + with namespace_scope("orders"): + runtime = AgentRuntime(name="assistant") + + runtime.name = "planner" + + assert (runtime.name, registry_names()) == ("orders_planner", ["orders_planner"]) + + class TestTheQualifierDoesNotGuess: def test_a_base_name_starting_with_the_namespace_is_still_qualified(self, config: Config) -> None: """Skipping the prefix when it looks present would silently unqualify this component. diff --git a/tests/unit/agents/component/test_registry.py b/tests/unit/agents/component/test_registry.py index 1637d665..d7465912 100644 --- a/tests/unit/agents/component/test_registry.py +++ b/tests/unit/agents/component/test_registry.py @@ -563,9 +563,22 @@ def test_a_plural_lookup_on_a_view_returns_only_this_agent(self, grouped_registr found = grouped_registry.for_namespace("orders").get_components_by_type(_Namespaced) assert [component.namespace for component in found] == ["orders"] - def test_an_explicit_namespace_overrides_the_view(self, grouped_registry: Registry) -> None: + def test_an_explicit_namespace_naming_a_neighbour_is_refused(self, grouped_registry: Registry) -> None: + """This asserted the opposite until the isolation work: an explicit namespace overrode + the view, so every component was one keyword away from its neighbours. A view resolves + its own agent and the root, and naming another is refused rather than answered. + """ + view = grouped_registry.for_namespace("orders") + with pytest.raises(RuntimeError, match="neighbour's belong to that agent alone"): + view.get_component("order_service", "billing") + + def test_an_explicit_namespace_may_name_this_view_or_the_root(self, grouped_registry: Registry) -> None: + """What the refusal must not cost: every framework component that passes a namespace + passes its own, and the root is shared infrastructure.""" view = grouped_registry.for_namespace("orders") - assert view.get_component("order_service", "billing").namespace == "billing" + + assert view.get_component("order_service", "orders").namespace == "orders" + assert view.get_component("shared_audit", "").namespace == "" def test_the_application_registry_still_sees_everything(self, grouped_registry: Registry) -> None: """build() and the lifespan hold the unscoped registry and must keep iterating all of it.""" diff --git a/tests/unit/agents/config/test_config_specialized_configs.py b/tests/unit/agents/config/test_config_specialized_configs.py index 400576bf..68f993db 100644 --- a/tests/unit/agents/config/test_config_specialized_configs.py +++ b/tests/unit/agents/config/test_config_specialized_configs.py @@ -46,6 +46,24 @@ def test_custom_otel_settings_are_reflected(self, write_settings) -> None: assert result.otel_endpoint == "http://collector:4317" assert result.otel_service_name == "my-service" + def test_token_metrics_can_be_turned_off(self, write_settings) -> None: + """The key gates the per-call token metrics, and was not read at all until now.""" + settings_file = write_settings(""" + [development] + app_name = "test" + app_port = 8000 + app_environment = "development" + model_provider = "openai" + model_api_key = "key" + otel_enabled = true + token_metrics_enabled = false + """) + config = Config(settings_files=[str(settings_file)], root_path=str(settings_file.parent)) + assert config.get_observability_config().token_metrics_enabled is False + + def test_token_metrics_are_on_when_nothing_says_otherwise(self, base_config: Config) -> None: + assert base_config.get_observability_config().token_metrics_enabled is True + def test_service_name_falls_back_to_app_name(self, write_settings) -> None: settings_file = write_settings(""" [development] diff --git a/tests/unit/agents/config/test_namespace_views.py b/tests/unit/agents/config/test_namespace_views.py index d67a4168..7e849d6e 100644 --- a/tests/unit/agents/config/test_namespace_views.py +++ b/tests/unit/agents/config/test_namespace_views.py @@ -210,3 +210,33 @@ def test_a_view_cannot_resolve_another_namespace(self, two_agent_config: Config) view = two_agent_config.for_namespace("orders") with pytest.raises(RuntimeError, match="not a window on another"): view.resolved_settings("billing") + + +class TestAViewResolvesItself: + """`resolved_settings` used to refuse on a view outright, which left the one legitimate + caller -- an agent-scoped actuator describing its own agent -- with the raw tree instead.""" + + def test_a_view_resolves_its_own_scope(self, two_agent_config: Config) -> None: + view = two_agent_config.for_namespace("orders") + + resolved = view.resolved_settings() + + assert resolved == two_agent_config.resolved_settings("orders") + + def test_a_view_naming_its_own_scope_is_the_same_answer(self, two_agent_config: Config) -> None: + view = two_agent_config.for_namespace("orders") + + assert view.resolved_settings("orders") == view.resolved_settings() + + def test_a_view_cannot_resolve_a_neighbour(self, two_agent_config: Config) -> None: + view = two_agent_config.for_namespace("orders") + + with pytest.raises(RuntimeError, match="not a window on another agent"): + view.resolved_settings("billing") + + def test_what_a_view_resolves_carries_no_neighbour(self, two_agent_config: Config) -> None: + """The property the actuator depends on: the flattening strips the other agents' + subsections, which is why it has to be done by the object that knows what they are.""" + resolved = two_agent_config.for_namespace("orders").resolved_settings() + + assert "billing" not in {str(key).lower() for key in resolved} diff --git a/tests/unit/agents/io/api/actuators/test_actuator_api.py b/tests/unit/agents/io/api/actuators/test_actuator_api.py index 7c96e848..1f440a20 100644 --- a/tests/unit/agents/io/api/actuators/test_actuator_api.py +++ b/tests/unit/agents/io/api/actuators/test_actuator_api.py @@ -339,7 +339,11 @@ async def test_an_agent_scoped_actuator_reports_only_its_own_scope(self, grouped result = await ActuatorApi().env_status() assert result.namespaces == {} - assert result.settings["APP_NAME"] == "root-app" + # Its own scope: 'orders' overrides app_name, and this asserted the root's value until + # the endpoint actually did what its comment claimed. + assert result.settings["APP_NAME"] == "orders" + assert result.settings["MODEL_NAME"] == "orders-model" + assert "billing" not in {str(key).lower() for key in result.settings} class TestRegisteringChecks: diff --git a/tests/unit/agents/test_agent_isolation.py b/tests/unit/agents/test_agent_isolation.py new file mode 100644 index 00000000..9237ceea --- /dev/null +++ b/tests/unit/agents/test_agent_isolation.py @@ -0,0 +1,392 @@ +"""The barrier between two agents sharing one process. + +Grouping puts several agents in one operating-system process, one Python interpreter and one +component registry. The promise that makes that acceptable is that **an agent can reach its own +data and nothing else** -- not a neighbour's component, not a neighbour's cache entry, not a +neighbour's configuration value, not a neighbour's events. The unit of concern is a *value*: an +identifier held by one agent must not be readable from another by any route the framework offers. + +Every test here is written the same way, because the property only means something when it is +stated in data rather than in structure: a distinctive value is planted in one agent, and the +other agent is asked for it through every API a component actually has. `namespace_of` and +`agent_scope` say what something *is*; these say what can be *read*, which is the claim. + +**Five of these tests fail, on four distinct mechanisms.** They are marked `xfail(strict=True)` +rather than deleted or softened, each naming the mechanism that lets the value through. Strict, so +that closing a hole turns the test red until the marker is removed -- a silently-passing xfail is +how a fix gets made and never noticed. All four are in the changelog's *Open points*: + +1. the registry's fallback from a qualified name to a bare one reaches a *neighbour's* key, not + only the root's; +2. an explicit ``namespace=`` argument wins on a view as well as on the application registry, so + an agent can address any other by naming it -- which costs two tests, because it opens both + the component lookup and the cache; +3. a scoped ``get()`` resolves a dotted key against the whole configuration tree; +4. one declaration serving two agents constructs both with the *same* mutable argument object. + +None of them is reachable by accident, and none of them requires anything but the framework's own +public API and a neighbour's name -- which an agent knows, because it is in the group. + +The root namespace is not a neighbour. It holds what the process genuinely shares -- one transport +connection, one health cache -- so an agent resolving a root component is the design working, and +the tests below distinguish that case rather than forbidding it. +""" + +from collections.abc import Generator +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest + +from blueprint.agents.agent_group import AgentGroup +from blueprint.agents.app_builder import AppBuilder +from blueprint.agents.component.component import Component +from blueprint.agents.component.namespace import namespace_scope +from blueprint.agents.config import Config +from blueprint.agents.services.service_base import ServiceBase + +ORDERS_RECORD = "ORDERS-RECORD-4242" +"""Planted in ``orders``. Every assertion below is some form of "billing cannot read this".""" + +BILLING_RECORD = "BILLING-RECORD-9999" + + +class Ledger(ServiceBase): + """One class, declared by both agents -- the shape a shared library component takes. + + ``holdings`` defaults to ``None`` and is filled per instance, so that any sharing observed + between two agents comes from the framework rather than from a mutable default argument. + """ + + def __init__(self, holdings: list[str] | None = None) -> None: + super().__init__() + self.holdings = holdings + self.record_id: str | None = None + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +@pytest.fixture(autouse=True) +def reset_component_state() -> Generator[None]: + with patch( + "blueprint.agents.component.registry.CorrelationContextProvider.get_correlation_context", + return_value=MagicMock(), + ): + yield + Component.reset_shared_state() + + +@pytest.fixture +def config(tmp_path: Path) -> Config: + """A process with shared infrastructure and one private value per agent.""" + settings = tmp_path / "settings.toml" + settings.write_text( + "[default]\n" + 'app_name = "the-process"\n' + 'app_environment = "development"\n' + "app_port = 8000\n" + 'model_provider = "openai"\n' + 'model_api_key = "not-a-real-key"\n' + 'nats_url = "nats://shared:4222"\n\n' + f'[default.orders]\nrecord_id = "{ORDERS_RECORD}"\n\n' + f'[default.billing]\nrecord_id = "{BILLING_RECORD}"\n\n' + f'[default.cache]\ncache_dir = "{(tmp_path / "cache").as_posix()}"\n', + encoding="utf-8", + ) + # Deliberately not Component.configure()'d here: AppBuilder.build() does that during + # assembly, and it refuses a second call. + return Config(settings_files=["settings.toml"], root_path=str(tmp_path)) + + +@pytest.fixture +def two_agents(config: Config) -> dict[str, Ledger]: + """Two agents in one process, each with a ledger carrying its own record. + + Assembled through ``AgentGroup`` rather than constructed by hand, because the barrier under + test is the one a real group produces -- the ambient namespace, the qualified registry keys + and the scoped configuration views all come from assembly. + """ + AgentGroup( + "finance", + { + "orders": AppBuilder().with_service(Ledger).with_cache(), + "billing": AppBuilder().with_service(Ledger).with_cache(), + }, + ).assemble(config) + + registry = Component.shared_registry + assert registry is not None + ledgers = {"orders": registry.get_component("orders_ledger"), "billing": registry.get_component("billing_ledger")} + ledgers["orders"].record_id = ORDERS_RECORD + ledgers["billing"].record_id = BILLING_RECORD + return ledgers + + +class TestAnAgentSeesItsOwnComponents: + """The barrier holds for every lookup a component makes without naming a namespace.""" + + def test_the_two_agents_are_separate_instances(self, two_agents: dict[str, Ledger]) -> None: + """One declared class, two agents: two objects. A singleton here would share everything + at once, so it is the first thing to rule out.""" + assert two_agents["orders"] is not two_agents["billing"] + + def test_a_lookup_by_bare_name_finds_this_agents_own(self, two_agents: dict[str, Ledger]) -> None: + """How a component actually resolves a collaborator: the name it declared, no namespace. + + Both agents ask for ``ledger`` and each gets its own -- which is the whole ambient + mechanism, seen from the inside. + """ + assert two_agents["billing"].registry.get_component("ledger").record_id == BILLING_RECORD + assert two_agents["orders"].registry.get_component("ledger").record_id == ORDERS_RECORD + + def test_a_lookup_by_class_finds_only_this_agents_own(self, two_agents: dict[str, Ledger]) -> None: + """The other resolution style, and the one where a neighbour would be easiest to reach: + both agents' ledgers are instances of the same class, in one registry.""" + found = two_agents["billing"].registry.get_components_by_type(Ledger) + + assert [ledger.record_id for ledger in found] == [BILLING_RECORD] + + def test_listing_names_does_not_name_the_neighbour(self, two_agents: dict[str, Ledger]) -> None: + """Enumeration is a read too. A component that can list its neighbour's registry keys can + then ask for them by name, and the key itself may say what the neighbour is for.""" + names = two_agents["billing"].registry.get_component_names_by_type(Ledger) + + assert names == ["billing_ledger"] + + def test_the_shared_root_is_not_a_neighbour(self, config: Config, two_agents: dict[str, Ledger]) -> None: + """The fallback that must keep working: what the process genuinely shares is resolvable + from inside an agent, and that is not a hole -- it is what the root namespace is.""" + with namespace_scope(""): + shared = Ledger() + shared.name = "shared_ledger" + + assert two_agents["billing"].registry.get_component("shared_ledger") is shared + + +class TestAnAgentCannotReachANeighboursComponents: + """Named routes to another agent's objects.""" + + def test_a_neighbours_qualified_name_is_not_a_key_this_agent_can_use(self, two_agents: dict[str, Ledger]) -> None: + """The registry keys are derivable: an agent knows its neighbours' names from the group, + and the qualifier is a documented ``_``. So this was not a guess. + + It reads as *absent*, not refused. A refusal naming the agent would confirm the + neighbour exists, which is the same disclosure in a smaller size. + """ + with pytest.raises(ValueError, match="does not exist in namespace 'billing' or at the root"): + two_agents["billing"].registry.get_component("orders_ledger") + + def test_an_agent_can_still_use_its_own_qualified_name(self, two_agents: dict[str, Ledger]) -> None: + """The documented behaviour the ownership check must not cost: a caller already holding + the qualified name resolves it, because qualifying it twice misses and the bare lookup + then finds a component this agent owns.""" + assert two_agents["orders"].registry.get_component("orders_ledger").record_id == ORDERS_RECORD + + def test_naming_a_neighbours_namespace_is_refused(self, two_agents: dict[str, Ledger]) -> None: + """Refused rather than answered absent, unlike the fallback above: naming another agent + is a decision, not a near miss, and a silent ``None`` would read as "that agent has + nothing registered" -- which is itself a claim about the neighbour.""" + with pytest.raises(RuntimeError, match="neighbour's belong to that agent alone"): + two_agents["billing"].registry.get_component("ledger", namespace="orders") + + def test_an_agent_may_still_name_its_own_namespace(self, two_agents: dict[str, Ledger]) -> None: + """What the refusal must not cost: every framework component that passes a namespace + passes ``self.namespace``, so this is the call the framework itself makes.""" + found = two_agents["billing"].registry.get_component("ledger", namespace="billing") + + assert found.record_id == BILLING_RECORD + + def test_an_agent_may_still_name_the_root(self, two_agents: dict[str, Ledger]) -> None: + """The root is shared infrastructure, and reaching it explicitly is not a cross-agent + read -- a view can already reach it by omitting the argument entirely.""" + with namespace_scope(""): + shared = Ledger() + shared.name = "shared_ledger" + + assert two_agents["billing"].registry.get_component("shared_ledger", namespace="") is shared + + +class TestAnAgentCannotReadANeighboursCache: + """The cache is where an agent's data actually accumulates, so it is the barrier that matters + most: a component instance holds what is in flight, the cache holds what was kept.""" + + @pytest.fixture + def stored(self, two_agents: dict[str, Ledger]) -> str: + """A record written into the orders cache, under a key billing also uses.""" + registry = Component.shared_registry + assert registry is not None + registry.get_cache("default", namespace="orders").set("record", {"id": ORDERS_RECORD}, namespace="data") + return "record" + + def test_the_same_key_in_this_agents_cache_is_empty(self, two_agents: dict[str, Ledger], stored: str) -> None: + """Two agents declaring one cache name get separate stores, so the shared key is the + sharpest form of the question: same name, same key, different data.""" + billing_cache = two_agents["billing"].registry.get_cache("default") + + assert billing_cache.get(stored, namespace="data") is None + + def test_every_cache_in_the_process_cannot_be_listed_from_inside_an_agent(self, two_agents: dict[str, Ledger]) -> None: + """C6: ``cache_entries()`` is the one cross-agent view, and a view refuses it outright.""" + with pytest.raises(RuntimeError, match="every cache"): + two_agents["billing"].registry.cache_entries() + + def test_naming_a_neighbours_namespace_does_not_open_its_cache(self, two_agents: dict[str, Ledger], stored: str) -> None: + """The same refusal as for components, on the store that actually holds the records. + + ``_cache_owner`` carries its own copy of the check rather than sharing one, because the + two resolvers mean different things by an omitted argument -- for a cache it means *this + agent*, never *every agent*, since no cache belongs to all of them. + """ + with pytest.raises(RuntimeError, match="no agent reads another's"): + two_agents["billing"].registry.get_cache("default", namespace="orders") + + +class TestAnAgentCannotReadANeighboursConfiguration: + """Configuration is one loaded tree with a view per agent, so the tree is the shared surface.""" + + def test_a_plain_key_resolves_to_this_agents_value(self, config: Config) -> None: + assert config.for_namespace("billing").get("record_id") == BILLING_RECORD + + def test_shared_infrastructure_still_resolves(self, config: Config) -> None: + """The barrier is around an agent's own keys, not around the process's.""" + assert config.for_namespace("billing").get("nats_url") == "nats://shared:4222" + + def test_a_view_cannot_hand_out_a_neighbours_view(self, config: Config) -> None: + """The obvious route, and the one that is closed: a view is not a loader.""" + with pytest.raises(RuntimeError, match="not from another"): + config.for_namespace("billing").for_namespace("orders") + + def test_a_dotted_key_cannot_walk_into_a_neighbours_section(self, config: Config) -> None: + """An agent's section is ``[default.]``, so its keys are ``.`` to + anyone who can resolve a dotted name. The scope used to prefix a key without confining + it.""" + with pytest.raises(ValueError, match="outside this agent"): + config.for_namespace("billing").get("orders.record_id") + + def test_the_frameworks_own_nested_sections_still_resolve(self, config: Config) -> None: + """An allowlist, so what the process genuinely shares keeps working -- and this is the + case that would have been broken by a denylist of agent names.""" + assert config.for_namespace("billing").get("cache.cache_dir") is not None + + def test_the_loader_is_unrestricted(self, config: Config) -> None: + """Only a *view* is confined. The application owns its whole tree, and `build()` and the + environment endpoint read across agents by design.""" + assert config.get("orders.record_id") == ORDERS_RECORD + + def test_the_escape_hatch_is_the_one_way_through_and_it_announces_itself( + self, config: Config, caplog: pytest.LogCaptureFixture + ) -> None: + """``settings`` deliberately returns the unscoped tree; it is audited, not forbidden. + + Recorded here rather than only in the config tests because it belongs in the account of + what the barrier does *not* stop: an agent that reaches for it can read anything, and all + that stands in the way is a WARNING naming the agent. + """ + with caplog.at_level("WARNING"): + reached = config.for_namespace("billing").settings.get("orders.record_id") + + assert reached == ORDERS_RECORD + assert "billing" in caplog.text and "not scoped to it" in caplog.text + + +class TestOneDeclarationDoesNotBecomeASharedObject: + """The property a group rests on -- one declaration, replayed per agent -- was also the way an + object could end up belonging to two agents at once. + + ``**`` copies the recorded mapping and not its values, so both agents were constructed with + the very same list. It is the only one of the four routes that needs no lookup: the object + arrives in both constructors. + """ + + def test_a_mutable_argument_shared_by_two_agents_is_refused(self, config: Config) -> None: + declaration = AppBuilder().with_service(Ledger, holdings=[]) + + with pytest.raises(ValueError, match="written by one agent is read by the others"): + AgentGroup("finance", {"orders": declaration, "billing": declaration}).assemble(config) + + def test_the_refusal_names_the_agents_the_argument_and_the_way_out(self, config: Config) -> None: + """It arrives at assembly, so the message is the only thing the author has to work from.""" + declaration = AppBuilder().with_service(Ledger, holdings=[]) + + with pytest.raises(ValueError) as refusal: + AgentGroup("finance", {"orders": declaration, "billing": declaration}).assemble(config) + + message = str(refusal.value) + assert "'orders'" in message and "'billing'" in message + assert "'holdings'" in message and "list" in message + assert "factory" in message + + def test_a_factory_gives_each_agent_its_own(self, config: Config) -> None: + """The way out, and the reason no new API was needed: a declaration's target may be a + zero-argument factory, which is called once per agent.""" + declaration = AppBuilder().with_service(lambda: Ledger(holdings=[])) + AgentGroup("finance", {"orders": declaration, "billing": declaration}).assemble(config) + + registry = Component.shared_registry + assert registry is not None + orders = registry.get_component("orders_ledger") + billing = registry.get_component("billing_ledger") + + orders.holdings.append(ORDERS_RECORD) + assert billing.holdings == [] + + def test_an_immutable_argument_is_shared_as_it_is(self, config: Config) -> None: + """Code and unchangeable values are not a channel: two agents already share the declared + *class*, which is what a declaration is.""" + declaration = AppBuilder().with_service(Ledger, holdings=("read-only",)) + AgentGroup("finance", {"orders": declaration, "billing": declaration}).assemble(config) + + registry = Component.shared_registry + assert registry is not None + assert registry.get_component("orders_ledger").holdings == ("read-only",) + + def test_one_agent_may_carry_whatever_it_likes(self, config: Config) -> None: + """Only a declaration used by more than one agent is checked -- there is nobody to share + it with otherwise, and a standalone project must not be punished for the group's rule.""" + AgentGroup("finance", {"orders": AppBuilder().with_service(Ledger, holdings=[])}).assemble(config) + + registry = Component.shared_registry + assert registry is not None + assert registry.get_component("orders_ledger").holdings == [] + + +class TestTheProcessLevelResourcesAreStillPerAgent: + """Not data, but channels through which data would flow.""" + + def test_each_agent_gets_its_own_thread_pool(self, two_agents: dict[str, Ledger]) -> None: + """A shared pool is a shared queue: one agent's work would be observable in another's + latency, and a task submitted by one would run beside a task submitted by the other.""" + registry = Component.shared_registry + assert registry is not None + + assert registry.get_or_create_executor("orders") is not registry.get_or_create_executor("billing") + + def test_each_agent_gets_its_own_cache_store(self, two_agents: dict[str, Ledger]) -> None: + """Separate objects, which is what makes the key-level isolation above true rather than + incidental.""" + registry = Component.shared_registry + assert registry is not None + + assert registry.get_cache("default", namespace="orders") is not registry.get_cache("default", namespace="billing") + + +class TestAnEventReachesOnlyItsOwnAgent: + """The live path: a delivery into one agent must not be offered to another agent's handlers.""" + + def test_a_handler_chain_answers_for_one_agent(self, two_agents: dict[str, Ledger]) -> None: + """Each agent's chain is built for its namespace, so the handler set is the agent's own. + + Asserted through the registry rather than by dispatching, because the selection that + matters happens when the chain is assembled: a handler that is never in the chain can + never be offered the event. + """ + registry = Component.shared_registry + assert registry is not None + + for agent in ("orders", "billing"): + handlers = registry.get_event_handler(namespace=agent) + assert all(handler.namespace == agent for handler in handlers), (agent, handlers) diff --git a/tests/unit/examples/test_example_structure.py b/tests/unit/examples/test_example_structure.py index f10cb485..507afe3b 100644 --- a/tests/unit/examples/test_example_structure.py +++ b/tests/unit/examples/test_example_structure.py @@ -16,6 +16,8 @@ import pytest +from blueprint.agents.clients.io.io_client_base import validate_subject_segment + EXAMPLES_DIR = Path(__file__).resolve().parents[3] / "examples" NOT_PROJECTS: dict[str, str] = { @@ -99,6 +101,24 @@ def test_its_settings_parse_and_name_the_application(self, example: Path) -> Non "application -- the NATS queue group among other things -- so an example without one is not runnable." ) + @pytest.mark.parametrize("example", project_examples(), ids=example_id) + def test_its_app_name_can_be_a_queue_group(self, example: Path) -> None: + """Since P1, a root-namespace application's ``app_name`` *is* its NATS queue group, and + the dead-letter subject is derived from it -- so a space in it is a subject the broker + rejects, and the application raises at subscribe time. + + Every example carried one. Only ``webhook_relay`` was actually broken, because it is the + only one on ``event_bus = "nats"``; the other four were an illegal value waiting for + somebody to switch bus. An example that demonstrates a value the framework refuses is + worse than no example, so this holds all five to what the client will accept. + """ + settings = tomllib.loads((example / "settings.toml").read_text(encoding="utf-8")) + names = [settings["app_name"]] if "app_name" in settings else [] + names += [value["app_name"] for value in settings.values() if isinstance(value, dict) and "app_name" in value] + + for name in names: + validate_subject_segment(name, source=f"examples/{example.name} app_name", subject=f"{name}.dead-letter") + @pytest.mark.parametrize("example", project_examples(), ids=example_id) def test_it_has_a_readme(self, example: Path) -> None: assert (example / "README.md").is_file(), f"examples/{example.name} has no README.md" From 2aabb57d613b8b8d3760cd37254b5dc58f5ad011 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:45:02 +0200 Subject: [PATCH 018/133] chore(gitignore): ignore .secrets.toml, the name the framework loads `DEFAULT_SETTINGS_FILES` is `["settings.toml", ".secrets.toml"]` and `asbs setup` now scaffolds that name, but this repository only ignored the undotted `secrets.toml` -- so a `.secrets.toml` created here was stageable. Both names are ignored now, each spelled out rather than `.secrets.*`, which would also hide the committed `.secrets.toml.example`. Co-Authored-By: Claude Opus 5 (1M context) --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index 6b349575..042ba2cd 100644 --- a/.gitignore +++ b/.gitignore @@ -146,7 +146,11 @@ cython_debug/ custom/dapr/components/rabbitmq-pubsub.yaml # Secrets +# Both names: the framework loads '.secrets.toml' (DEFAULT_SETTINGS_FILES) and asbs +# scaffolds that name, while 'secrets.toml' is the older name still found in the wild. +# Named exactly rather than '.secrets.*', which would also hide the committed example. **/secrets.toml +**/.secrets.toml .env.rabbitmq uv.lock From cecbf9ce16d8e60cea7093218826df842125dbd2 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:45:03 +0200 Subject: [PATCH 019/133] docs(readme): document the group path beside the standalone one The README never mentioned grouping, and its `AppBuilder` example taught three things the scaffolder no longer writes: `build()` inside `main.py`, a component instance on the `with_*` line, and the undotted `secrets.toml`. Standalone is unchanged and says so -- a built module-level `app`, a factory, or `agent.build(config)`, all still at the root namespace with the same registry names, routes, queue group, durable and `service.name`. Added beside it: what `agents.toml` declares, that `BLUEPRINT_AGENTS` decides which agents a process runs, what each hosted agent owns and what stays shared, that agents in one process are isolated, and that the name in `agents.toml` is the agent's identity everywhere else and renaming it later is a consumer migration. Co-Authored-By: Claude Opus 5 (1M context) --- README.md | 97 +++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 88 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 69927b26..ed68514b 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ Blueprint Agents gives you a component-based toolkit for building intelligent mi - **Event-Driven Processing** -- CloudEvents v1.0 with chain-of-responsibility handlers, Dapr and NATS pub/sub support - **LLM Integration** -- AI agents powered by [Pydantic AI](https://ai.pydantic.dev/) with structured outputs, tool calling, and multi-model support (OpenAI, vLLM) - **Built-in Observability** -- OpenTelemetry tracing, metrics, and structured logging out of the box +- **Multi-Agent Grouping** -- Run one agent per process, or host several in one process, as a *deployment* choice: the agent's code is identical either way - **CLI Scaffolding** -- Generate complete project structures and individual components with the `asbs` CLI - **Deployment Ready** -- Docker, Kubernetes with Helm charts, health checks, and CI/CD patterns included @@ -37,7 +38,13 @@ pip install -e . asbs dev ``` -Your service is now running at `http://localhost:8000` with interactive API docs at `/docs`. +Your service is now running at `http://localhost:8000` with interactive API docs at `/docs`, +and this agent's routes under `/api/my-agent`. + +`asbs setup` writes your project's `main.py` as a **declaration** -- an `AppBuilder` that is never built -- +plus an `agents.toml` naming it. That is what lets the same project run on its own and be hosted +alongside other agents without changing a line. See +[Running one agent, or several](#running-one-agent-or-several). --- @@ -93,24 +100,30 @@ pip install -e ".[dev]" Blueprint Agents uses five composable component types, wired together with the `AppBuilder`: ```python -from blueprint.agents import AppBuilder, AgentBuilder, Config +from blueprint.agents import AppBuilder from src.handlers.order_handler import OrderHandler from src.services.order_service import OrderService from src.api.routes import OrderApi -config = Config(settings_files=["settings.toml", "secrets.toml"]) - -app = ( - AppBuilder(config) +agent = ( + AppBuilder() .with_handler(OrderHandler) .with_service(OrderService) - .with_rest_api(OrderApi()) + .with_rest_api(OrderApi) .with_cache() - .build() ) ``` +Two things about that chain are worth knowing up front: + +- **Nothing is constructed yet.** Every `with_*` call records a declaration; `build()` constructs + it. Leaving `build()` out is what lets the deployment decide the configuration and the namespace + each component is built in. +- **Pass classes, not instances.** `with_rest_api(OrderApi)` rather than `with_rest_api(OrderApi())`. + An instance created on the `with_*` line exists before any namespace does, so it belongs to the + process root for ever. Instances still work for a single standalone agent; a group refuses them. + ### The Five Components | Component | Base Class | Purpose | @@ -134,6 +147,71 @@ on_shutdown() --> Clean up resources, close connections --- +## Running one agent, or several + +**How many agents share a process is a deployment parameter, not an architectural commitment.** +The declaration in your project's `main.py` is the same either way; only what starts the +process differs. + +| Shape | What starts it | +|---|---| +| Standalone, a module-level `app` you built yourself | `uvicorn src.main:app` | +| Standalone, a declaration built by a factory | `uvicorn src.main:create_app --factory` | +| Hosted -- one agent, or twenty | `python -m blueprint.agents.entrypoint` | + +### Standalone + +Unchanged, and still fully supported. Build the declaration yourself and serve it: + +```python +config = Config(settings_files=["settings.toml", ".secrets.toml"]) +app = agent.build(config) # the declaration from "How It Works" +``` + +A standalone agent runs at the **root namespace**: its registry names, REST paths (`/api/...`), +NATS queue group, JetStream durable and OpenTelemetry `service.name` are exactly what they were +before this existed. Nothing reads `agents.toml` unless you run the entry point. + +### Hosted in a group + +Name each agent and the module its declaration lives in, in `agents.toml`: + +```toml +[agents.orders] +module = "src.main:agent" + +[agents.billing] +module = "billing.main:agent" +``` + +The image contains those agents; the **deployment** decides which of them a given process runs: + +```bash +docker run -e BLUEPRINT_AGENTS=orders,billing my-image # both in one process +docker run -e BLUEPRINT_AGENTS=orders my-image # a group of one +``` + +Each hosted agent gets its own handlers, agent runtime, REST routes, AI client, thread pool, +caches and broker connection. The port, the health endpoint and the process are shared. Agents in +one process are **isolated**: an agent resolves its own components, caches and configuration and +the root's shared ones, and the framework refuses any attempt to reach a neighbour's. + +A group of one gives today's process isolation; a group of twenty gives the shared-interpreter +memory profile. Moving an agent between groups changes neither its broker-side consumer identity +nor its telemetry identity. + +> **The agent's name in `agents.toml` is its identity everywhere else** -- registry prefix, NATS +> queue group, part of the JetStream durable, cache partition, OpenTelemetry `service.name` and +> the REST prefix `/api/`. Renaming it after the first deploy is a consumer migration, not a +> rename. Choose it before you ship. + +Other group settings: `BLUEPRINT_GROUP_CONFIG` and `BLUEPRINT_GROUP` select a named group from a +mounted file, and `BLUEPRINT_CRITICAL_AGENTS` says which agents failing should fail the process. +See the [Multi-Agent Setup guide](docs/guides/multi-agent-setup.md) for the full reference and the +migration path for an existing single-agent project. + +--- + ## Examples Explore complete, runnable examples in the [`examples/`](examples/) directory: @@ -172,7 +250,7 @@ cache_dir = ".cache/my-agent" default_ttl = 3600 ``` -**secrets.toml** (never commit this file): +**.secrets.toml** (never commit this file): ```toml [default.runtimes.my_agent] @@ -236,6 +314,7 @@ See the [Deployment Guide](docs/guides/deployment.md) for detailed instructions. ### Getting Started - [Getting Started Guide](docs/getting-started.md) -- Installation, first project, and walkthrough +- [Multi-Agent Setup](docs/guides/multi-agent-setup.md) -- Running several agents in one process, and migrating an existing one into a group ### Core Concepts - [Architecture](docs/concepts/architecture.md) -- Component model, registry, and lifecycle From 3322f4e25b0688ab0bbc999fa9204291ec288f2d Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 11:45:04 +0200 Subject: [PATCH 020/133] docs(spec): record where each acceptance criterion actually stands Section 12 had 3 of 27 boxes ticked while most of the work behind them had landed, so the normative document read as though nothing was done. Each criterion is now verified against the suite and sorted: 18 met, each naming the test that holds it; 3 built and unit-tested but written to ask for something only a real broker shows, pointing at tests/integration/; 5 genuinely not done, each saying why (no CI gate, no CronJob renderer, no fan-out gauge, no exhaustive detached-task test, no RSS benchmark); and 1 superseded, because per-namespace filter_subjects became unnecessary when each agent got its own durable. All 27 are still present. Nothing was ticked that a test does not hold. Co-Authored-By: Claude Opus 5 (1M context) --- docs/specs/2026-08-28-multi-agent-grouping.md | 125 ++++++++++++------ 1 file changed, 88 insertions(+), 37 deletions(-) diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md index 07eeefbf..079c3ffc 100644 --- a/docs/specs/2026-08-28-multi-agent-grouping.md +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -883,57 +883,108 @@ Two things an author still needs to know: their agent's name, and that handlers ## 12. Acceptance criteria -- [ ] Two agents in one process; an event on a topic both subscribe to reaches both, once each. -- [ ] Two replicas of a two-agent group: each event processed exactly once per agent. -- [ ] Durable and queue names byte-identical across two builds where the same agent sits in - different groups (C1). +Status on `feature/multi-agent-namespaces`, 2026-09-14. A ticked box names what holds it. `[~]` +means the behaviour is built and covered by unit tests against a mocked transport, while the +criterion as written asks for something only a real broker shows -- those have tests waiting in +`tests/integration/` and are tracked in `docs/plans/2026-09-11-broker-integration-tests.md`. An +unticked box is not done, and says why. + +### Met + +- [x] Durable and queue names byte-identical across two builds where the same agent sits in + different groups (C1) -- `TestConsumerIdentityIgnoresTheDeployment`, + `tests/unit/agents/clients/io/test_nats_client.py`. - [x] Spans from namespace `invoice` carry `service.name = "invoice"`; a `namespace=""` app keeps `otel_service_name` (C2). - [x] A degraded namespace: liveness `UP`, readiness per policy, `blueprint_namespace_up = 0`, that namespace's consumers stopped (C3, C4). -- [ ] `.model_name` overrides root `model_name` for that namespace only (C5). -- [ ] No supported API exposes group membership to agent code (C6). +- [x] `.model_name` overrides root `model_name` for that namespace only (C5) -- + `tests/unit/agents/config/test_namespace_views.py`: `orders` reads its own, `billing` falls + back to the root, and the two differ. +- [x] No supported API exposes group membership to agent code (C6) -- + `tests/unit/agents/test_agent_isolation.py` and `test_a_view_cannot_list_its_neighbours`. - [x] Every path that stops a namespace serving emits an ERROR event and `blueprint_namespace_up{agent} = 0` carrying that namespace's identity; a namespace whose subscriptions vanish while the process stays healthy is reported within one scrape interval (C7). +- [x] File-only, env-only and combined resolution produce identical groups; env overrides the file + key by key -- `tests/unit/agents/test_group_config.py`: `TestFromTheGroupFile`, + `TestFromTheEnvironmentAlone`, `TestPrecedence`. +- [x] `CacheService.claim` is set-if-absent on both backends: of N concurrent callers on one key + exactly one is told it stored the value (sec. 7.5) -- `TestClaim` in both + `test_disk_cache_service.py` and `test_redis_cache_service.py`. +- [x] An `"in_process"` scheduler with no cache still ticks, and warns at startup that its ticks + are uncoordinated (sec. 7.5) -- `test_without_a_cache_every_replica_ticks` and + `test_in_process_mode_without_a_cache_says_every_replica_runs_every_tick`. +- [x] A registered scheduler with no `scheduler_mode` fails before the port is bound, and so does + `"event"` with no topic-carrying `event_bus` (sec. 7.5). +- [x] Two namespaces in one group resolve different `scheduler_mode` values, and only the + `"in_process"` one starts a timer (sec. 7.5, C5). +- [x] A pure-scheduler namespace that neither subscribes nor publishes is given no transport client + (sec. 6), and one that opts into publishing is given a client and no subscription (sec. 7.5) + -- `test_an_agent_that_neither_consumes_nor_publishes_gets_no_client` and + `test_a_publish_only_agent_gets_a_client_and_no_endpoint`. +- [x] A scheduler's `on_startup` and `on_shutdown` each run exactly once per lifespan, asserted + against both lifespan loops a `SchedulerBase` appears in (#43) -- + `test_repeated_startup_starts_no_second_timer`. +- [x] An event that matches no handler is acknowledged, not redelivered: the transport edge + behaves identically for `PROCESSED` and `NO_HANDLER_FOUND` (sec. 7.2) -- + `test_no_handler_found_still_acks`. +- [x] The same outcome yields the same disposition on both transports -- `CriticalHandlerError` + drops on Dapr and terms on NATS, and a payload that fails to parse never naks (sec. 7.2) -- + `test_critical_error_returns_drop`, `test_critical_error_terms`, + `test_invalid_event_error_terms`. +- [x] A handler declaring no topics and no event types is still evaluated for every event its + namespace receives (sec. 7.7) -- + `test_a_handler_that_declares_nothing_is_a_candidate_for_everything`. +- [x] Frozen compat suite and generated-project smoke test both green (sec. 10.2) -- + `tests/unit/agents/test_frozen_compatibility.py` and + `tests/unit/agent_generator/generator/test_generated_project.py`. +- [x] Idempotency off by default, with the requirement surfaced at scaffold time and in + `asbs validate` -- `test_dedup_is_off_by_default`, plus the `DECIDE:` comment in the + scaffolded handler and the notice `asbs validate` prints. + +### Built, awaiting a real broker + +- [~] Two agents in one process; an event on a topic both subscribe to reaches both, once each. + Per-agent subscription and the Dapr in-process fan-out are unit-tested; + `tests/integration/test_grouped_agents.py` is the version that settles it. +- [~] Two replicas of a two-agent group: each event processed exactly once per agent. Whether a + queue group merges overlapping subscriptions is the broker's behaviour, not ours. +- [~] Cron fires once across three replicas in both `scheduler_mode` values (#73). The claim is + atomic on both cache backends by unit test; three real replicas contending is not. + +### Not done + - [ ] No framework-created task is detached without a done-callback that logs exceptions with the namespace attached; asserted by a test that fails a task in each background path (C7). -- [ ] File-only, env-only and combined resolution produce identical groups; env overrides the file - key by key. + Done-callbacks are on the NATS, Dapr and sessions paths and individually tested; the + *exhaustive* test the criterion asks for -- one that fails a task in every background path + -- does not exist, so nothing stops the next path being added without one. - [ ] The CI gate fails when an environment's group declaration omits an agent present in the - in-image agent map (sec. 13). -- [ ] Cron fires once across three replicas in both `scheduler_mode` values (#73). -- [ ] `CacheService.claim` is set-if-absent on both backends: of N concurrent callers on one key - exactly one is told it stored the value (sec. 7.5). -- [ ] An `"in_process"` scheduler with no cache still ticks, and warns at startup that its ticks - are uncoordinated (sec. 7.5). + in-image agent map (sec. 13). `asbs validate` reports it locally; no CI gate enforces it. - [ ] `scheduler_mode = "event"` starts no timer, and the generated `CronJob` matches the schedule - declared in agent code. -- [ ] A registered scheduler with no `scheduler_mode` fails before the port is bound, and so does - `"event"` with no topic-carrying `event_bus` (sec. 7.5). -- [ ] Two namespaces in one group resolve different `scheduler_mode` values, and only the - `"in_process"` one starts a timer (sec. 7.5, C5). -- [ ] A pure-scheduler namespace that neither subscribes nor publishes is given no transport client - (sec. 6), and one that opts into publishing is given a client and no subscription (sec. 7.5). -- [ ] A scheduler's `on_startup` and `on_shutdown` each run exactly once per lifespan, asserted - against both lifespan loops a `SchedulerBase` appears in (#43). -- [ ] An event that matches no handler is acknowledged, not redelivered: the transport edge - behaves identically for `PROCESSED` and `NO_HANDLER_FOUND` (sec. 7.2). -- [ ] The same outcome yields the same disposition on both transports -- `CriticalHandlerError` - drops on Dapr and terms on NATS, and a payload that fails to parse never naks (sec. 7.2). -- [ ] A handler declaring no topics and no event types is still evaluated for every event its - namespace receives (sec. 7.7). -- [ ] A namespace's derived `filter_subjects` is never narrower than its declared topics unioned - with `nats_subscriptions` (sec. 7.7). + declared in agent code. The first half holds (`test_event_mode_starts_no_timer`); manifest + generation was deliberately deferred and the renderer written for it was removed rather than + carried as dead code, so the second half has nothing to check yet. - [ ] Unhandled events per (namespace, topic) and namespaces-per-subject fan-out are both exposed, neither reported as a fault and neither keeping per-topic state (sec. 7.2, sec. 7.7). -- [ ] Frozen compat suite and generated-project smoke test both green (sec. 10.2). -- [ ] Idempotency off by default, with the requirement surfaced at scaffold time and in - `asbs validate`. -- [ ] Marginal RSS per additional idle namespace measured and published, reusing #36's benchmark - harness. #32 measures ~6 MB per forked child with shared libraries; a namespace should be - materially below that, and this number is what retires the lazy-agent idea for good. + `blueprint.events.unhandled` carries (namespace, topic); the namespaces-per-subject fan-out + gauge is not implemented. +- [ ] Marginal RSS per additional idle namespace measured and published, reusing #36's + benchmark harness. #32 measures ~6 MB per forked child with shared libraries; a + namespace should be materially below that, and this number is what retires the + lazy-agent idea for good. No benchmark harness exists yet, so the number this feature + exists to produce has not been measured. + +### Superseded + +- A namespace's derived `filter_subjects` is never narrower than its declared topics unioned with + `nats_subscriptions`. The design moved: each agent owns its own durable filtering on its own + subjects, which is what makes a per-namespace `filter_subjects` set unnecessary + (`nats_client.py`). Recorded rather than deleted, because this spec is normative and a change + of approach belongs on it. + --- From 66aa9adfa7c5b28f9a78daf2520720d2787b66e4 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 12:03:54 +0200 Subject: [PATCH 021/133] chore(release): write the release changelog and bump the version CHANGELOG.md carried one entry for #76 and nothing about grouping, which is the document a consuming service opens to answer "what breaks". The 0.7.0 entry now states it: what was added, eleven breaking changes in the order a consumer is likely to hit them, what was fixed with the issue it closes, and what is knowingly still open. Assessed against the open issues rather than the commit log. Closed here: #91 (/status/env in clear), #81 (Dapr declared topics never subscribed), #28 (resilient broker startup and subscription readiness -- P0 meets its acceptance criteria, including event_client_max_retries and event_client_retry_delay), #73 (duplicate cron ticks under replicas), #43 (schedulers starting twice, both causes), #4 (AgentBuilder building a model during __init__), #80 (the test split), and #76 ships with it. Listed as still open rather than claimed: #89 -- Config passes current_env= to Dynaconf where the selector is env=, so the resolved environment is never loaded. The configuration layer was reworked substantially here and that defect survived it, which is worth saying out loud next to a release that rewrites config. #75 is materially answered by the spec but its ADR is outstanding, and #32/#35/#36 are enabled but unmeasured. One claim was checked and dropped before it shipped: an earlier draft said a group of two or more consuming agents on Dapr fails at build(). It did in phase 6, and phase 7 replaced it with in-process fan-out (test_dapr_fanout.py). The real caveat is what the entry says instead -- one acknowledgement is shared, so a retry asked for by one agent redelivers to all. Version bumped to 0.7.0. The publish workflow overwrites this from the tag, so it is the tree being honest rather than the source of truth. The version this commit sets is 0.7.0, and that is wrong: 0.7.0 and 0.8.0 were already published to PyPI from develop on 2026-09-04 and 2026-09-07. The number was chosen against a stale `origin/main` and a tag list that had not been fetched. The merge with develop that follows corrects it to 0.9.0 and restores the two released entries this changelog was missing. The subject no longer carries a version so that the log does not advertise a number that was never this branch's to claim. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 185 ++++++++++++++++++++++++++++++++++++++++++++++++- pyproject.toml | 2 +- 2 files changed, 185 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df840254..c00a8596 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,191 @@ # Changelog ## [Unreleased] +## [0.7.0] - 2026-09-14 + +**Multi-agent grouping.** How many agents share a process becomes a *deployment* parameter rather +than an architectural commitment. An agent's code is identical whether it runs alone or beside +nineteen others; only what starts the process differs. A standalone agent is unaffected by almost +all of this — see **Breaking** for the exceptions, which are listed in the order you are likely to +hit them. + +Full migration path, including the one decision to get right before the first deploy: +[`docs/guides/multi-agent-setup.md`](docs/guides/multi-agent-setup.md). The normative spec is +`docs/specs/2026-08-28-multi-agent-grouping.md`. + ### Added -- **`SessionKeyProvider` gains a `"job"` source** (#76). `env`/`config` only ever supported one static key for every session, which cannot work for consumers whose session keys are generated fresh per session and actually validated (encryption enforced) — the gap live-reproduced as `ValueError: Environment variable SESSION_KEY not set` immediately after a job dispatch. `source = "job"` fetches the key via `GET {session_key_remote_url}/internal/jobs/{job_id}/session-key?agent_id=` (bechtleav360/avs.ai.idac.service-sessions#194 Finding 2 / #196), threading a new optional `job_id` parameter through `get_session_key` from `SessionsBus`'s three call sites. A 409 (job already claimed by a different `agent_id`) raises the new `SessionKeyClaimConflictError`, distinct from the 404/`httpx.HTTPStatusError` case. `env`/`config`/`vault`/`remote` sources are unaffected. + +- **Agent grouping.** `agents.toml` names the agents an image contains and the module each + declaration lives in; `BLUEPRINT_AGENTS`, or `BLUEPRINT_GROUP` plus a mounted + `BLUEPRINT_GROUP_CONFIG` file, decides which of them a given process runs; + `python -m blueprint.agents.entrypoint` resolves, builds and serves them. Each hosted agent owns + its handlers, agent runtime, REST routes (`/api/`), AI client, thread pool, caches and + broker connection; the port, the health endpoint and the process are shared. + `BLUEPRINT_CRITICAL_AGENTS` says which agents failing should fail the process. +- **Agents in one process are isolated, and the barrier is enforced rather than conventional.** An + agent resolves its own components, caches and configuration plus the root's shared ones. Reaching + a neighbour by its registry key, by an explicit `namespace=` on a view, by a dotted configuration + key, or by sharing one declaration's mutable argument between two agents is refused or reported + absent. `Config.settings` remains the documented escape hatch and logs a WARNING naming the agent. +- **An agent's identity is stable across regrouping** (spec C1): its NATS queue group, JetStream + durable, cache partition, OpenTelemetry `service.name`, registry prefix and REST prefix all derive + from the agent's own name and never from the group or the pod. +- **Per-agent observability.** `service.name` per agent, `blueprint_namespace_up{agent}`, a + readiness entry and health checks attributed per agent, `blueprint.scheduler.tick_age_seconds`, + `blueprint.events.dead_lettered`, `blueprint.events.unhandled` and `blueprint.events.duplicate`. +- **`SessionKeyProvider` gains a `"job"` source** (#76). `env`/`config` only ever supported one + static key for every session, which cannot work for consumers whose session keys are generated + fresh per session and actually validated (encryption enforced) — the gap live-reproduced as + `ValueError: Environment variable SESSION_KEY not set` immediately after a job dispatch. + `source = "job"` fetches the key via + `GET {session_key_remote_url}/internal/jobs/{job_id}/session-key?agent_id=` + (bechtleav360/avs.ai.idac.service-sessions#194 Finding 2 / #196), threading a new optional + `job_id` parameter through `get_session_key` from `SessionsBus`'s three call sites. A 409 (job + already claimed by a different `agent_id`) raises the new `SessionKeyClaimConflictError`, distinct + from the 404/`httpx.HTTPStatusError` case. `env`/`config`/`vault`/`remote` sources are unaffected. +- **`CacheService.claim`** — set-if-absent, atomic on both backends (`add` on disk, `SET NX EX` on + Redis). This is the compare-and-set primitive the deduplication work flagged as missing. +- **Named caches.** `with_cache(name=...)`, `/cache/*` endpoints take `?name=`, and `/readiness` + gains a `cache:` entry per named cache. +- **Opt-in event deduplication** — `idempotency_enabled` and a required `idempotency_ttl`. Off by + default; a failed dispatch releases its claim so the nak's redelivery still runs. +- **`nats_publish_mode`** (`"core"` / `"jetstream"`) separates publishing from durable consumption, + with `nats_publish_subjects` for subjects not already in `event_publishing.topic_mapping`. Unset, + it follows `nats_use_jetstream`, so nothing existing changes. +- **`run_app`**, so a project can serve itself from its own settings. +- **Scaffolding**: `asbs setup` now writes `agents.toml`, a `pyproject.toml` and two tests, so + `asbs setup` → `pytest` → `asbs validate` closes; `asbs validate` reports what a project has not + said about grouping and about idempotency; the CLI no longer crashes on a Windows console. +- New config keys: `event_client_drain_timeout`, `dapr_pubsub_name`, + `dapr_declarative_subscriptions`, `idempotency_enabled`, `idempotency_ttl`, `scheduler_mode`, + `event_publishing_enabled`, `nats_publish_mode`, `nats_publish_subjects`. All default to current + behaviour except `scheduler_mode`, which is required — see below. +- `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. + +### Breaking + +1. **`scheduler_mode` is required.** A project that registers a scheduler and does not set it fails + at `build()`, with an error naming both values and what each costs. `"in_process"` reproduces + today's behaviour exactly and is the no-op migration; `"event"` is the one that fixes #73. + Defaulting the key would either keep firing a timer per replica or silently stop ticking a + service with no broker, and neither is safe to inherit. +2. **A subject-unsafe `app_name` or `nats_queue_group` now fails at startup** instead of being + rewritten or reaching the broker. `app_name = "Health Monitor"` with an event-mode scheduler used + to derive `Health_Monitor.scheduler.`; the rewrite was invisible to whoever wrote the + `CronJob`, so the symptom was a tick that never arrived. Rename to a subject-safe value, or pass + `topic=` explicitly. +3. **A scoped `Config`'s dotted key no longer resolves against the whole tree.** `_scoped_get` used + to fall back from `.` to the raw key, and since an agent's section is + `[default.]`, that let one agent read another's settings. The fallback is now an allowlist + of the four prefixes the framework itself owns (`cache`, `event_publishing`, `runtimes`, + `runtime`). A project reading its *own custom* nested key through a scoped view now gets an error + naming the rule; flat keys and `Config.settings` are unaffected. +4. **A registry view that names another agent is refused.** `get_component(..., namespace="other")` + and `get_cache(..., namespace="other")` raise on a scoped view. Every in-framework caller passes + its own namespace or holds the application registry, so nothing internal is affected. +5. **A scoped `Config`'s telemetry `service.name` is the agent's name.** Affects a project using + `Config(agent_scope=...)`, which has shipped since April. A repo with `foo.app_name = "Foo + Service"` and no `foo.otel_service_name` sees `service.name` change from `Foo Service` to `foo`. + Migration is one line: set `.otel_service_name` to whatever the dashboards key on. A + project that passes no `agent_scope` is unaffected. +6. **Cache keys moved, twice.** A cache is now private to the agent that declared it, keyed on + `(namespace, name)` with its own subdirectory and Redis prefix. An application upgrading with a + persistent Redis cache or a mounted disk cache sees its old entries as **absent** — a cold cache, + not an error. A group still needs exactly one writable mount, since an agent's store is a + subdirectory of `cache.cache_dir`. If any cache entry is load-bearing rather than an + optimisation, migrate it deliberately. +7. **Four declaration surfaces are deleted**: `AgentRegistration`, `RegisteredComponent`, + `NamespaceBuilder`, and `AppBuilder.with_namespace` / `with_registration`. `AppBuilder` is the one + declaration surface; `AgentGroup` collects named declarations into a process. Passing an + already-built component instance (`with_service(MyService())`) still works for a single standalone + agent and is refused in a group — pass the class, or a zero-argument factory. +8. **`ClientBase.subscribe` changed from `(topic, callback)` to `(topic_callbacks)`**, and + `EventHandlingBase.subscribe` and `POST /nats/subscribe/{topic}` are removed. This affects + third-party transport implementations; both in-repo clients are updated. +9. **On grouped Dapr, one delivery is fanned out in-process to every agent that declared the + topic, and the single acknowledgement the sidecar receives is their combination** — so a retry + asked for by one agent redelivers to all of them. The sidecar fetches the subscription document + from one fixed path, which is why there is one endpoint at the root that routes rather than one + document per agent. Set `idempotency_enabled` for grouped Dapr, or keep handlers + repeat-tolerant. Single-agent Dapr and NATS are both unaffected. +10. **`Registry.update_component_name` refuses a name that is already taken** instead of overwriting + it. Anything relying on the overwrite was losing a component silently. +11. **`asbs setup` now scaffolds `.secrets.toml`**, the name `DEFAULT_SETTINGS_FILES` actually loads; + it used to write `secrets.toml`, which nothing read. This is a change to the *scaffolder* only — + the framework's file list is untouched, so no existing deployment changes. `asbs validate` + reports an undotted file as the rename it needs. An already-scaffolded project should rename its + file. + +### Fixed + +- **`/status/env` no longer returns credentials in clear** (#91). Config masking matched whole keys + only, so anything with a prefix or suffix around the secret word came back readable. Present since + `4e6421b`, unrelated to grouping. An agent-scoped actuator also now reports its own scope rather + than the whole tree. +- **Dapr declared topics actually subscribe** (#81). `GET /dapr/subscribe` served nothing usable and + answered 422 to the sidecar. A project that overrides `get_subscribed_topics()` will see Dapr + behaviour change by design — declared topics went from subscribing to nothing to subscribing. +- **Resilient broker startup and subscription readiness** (#28). Connection and subscription setup + run asynchronously with background retry, `/health/live` succeeds while retrying, + `/health/ready` stays unhealthy until subscriptions are established, and NATS and Dapr behave + consistently. Configurable via `event_client_max_retries` and `event_client_retry_delay`. +- **Schedulers no longer fire duplicate cron ticks under multiple replicas or workers** (#73). + `scheduler_mode = "event"` delivers the tick as an ordinary event, so the queue group picks one + replica; `"in_process"` claims each tick in the shared cache so one replica runs it. +- **Schedulers no longer start twice** (#43), on both causes: a second `build()` pass no longer + starts a second timer, and `SchedulerBase` sitting in the REST-API lifespan loop as well as the + scheduler loop no longer creates two `AsyncIOScheduler` instances per scheduler. The manual + trigger route is now registered before `include_router` copies it, so it is actually served. +- **`AgentBuilder` no longer needs a `Config` at construction and builds no model during `__init__`** + (#4). The AI client and model are resolved in `build()`, against the agent's own configuration view. +- **The unit/integration test split is enforced** (#80). `tests/integration/` was not run by CI and + sat at 28 failures asserting on examples that had been removed. +- **A handler's published result is no longer silently lost under JetStream.** The client declared + no publishable subjects, so `js.publish` waited for an acknowledgement no stream would send, timed + out, and was swallowed as a WARNING while a Core NATS listener still saw the message. Found + against a real broker. +- **`AgentRuntime` is constructed with its name and registered like every other component.** It + registered itself under the bare name, so two agents in a group sharing a runtime name collided on + one registry key. This also made a freshly scaffolded project fail to start with + `TypeError: AgentRuntime.__init__() missing 1 required positional argument: 'name'`. +- **A scaffolded project starts, tests and validates.** Its settings file wrote `[default.logging]` + and `[default.observability]` tables the framework never reads; `asbs create agent` wrote + `[default.runtimes..models]` where the framework reads `model_settings`; `asbs create` wrote + absolute imports into files using relative ones; `asbs create handler` could die mid-command on a + Windows console leaving the project half-edited; and `asbs setup` printed + `pip install -e .` without writing a `pyproject.toml`. +- **`token_metrics_enabled` is actually read.** `get_observability_config()` never passed it, so the + per-call token and latency metrics stayed on however the key was set. +- **`GET /cache/stats` no longer returns 500**, and the four overlapping cache documents are one, + rewritten against the code. +- **Five bundled examples declared an `app_name` the broker refuses**; `webhook_relay` was broken + outright. All renamed, and a test now holds every example's `app_name` to the subject alphabet. +- Events that match no handler are counted rather than flagged, acknowledged rather than redelivered + to `max_deliver`; a critical error drops on Dapr and terms on NATS; an unparseable body drops + instead of answering 422; in-flight handlers drain before the connection closes; JetStream + consumers share load via a deliver group; and what the framework gives up on is republished to + `.dead-letter` before being termed. + +### Known issues + +- **#89 is still open and this release does not fix it.** `Config` passes `current_env=` to Dynaconf + where the environment selector is `env=`, so the resolved environment is never actually loaded and + the log line reports a name that was never applied. The configuration layer was substantially + reworked here and this defect survived it. +- Generating the `CronJob` for `scheduler_mode = "event"` is deliberately deferred, so the publisher + must be written by hand. +- No CI gate enforces that an environment's group declaration covers the in-image agent map; + `asbs validate` reports it locally. +- The memory number this feature exists to produce — marginal RSS per additional hosted agent — has + not been measured (#32, #35, #36). +- **#75** (supervisord multi-agent-per-host vs. Kubernetes per-agent Pod) is materially answered by + the spec: grouping makes the choice a deployment parameter and Kubernetes runs one Deployment per + group. The ADR the issue asks for is still outstanding. +- Dead letters accumulate on `.dead-letter` with no consumer; draining it is an + operational task the framework does not perform. +- `size` in the cache statistics counts TTL metadata entries, so a cache holding two values reports + `4`. Documented as-is rather than changed, because a reported metric is somebody's dashboard. ## [0.6.4] - 2026-07-29 diff --git a/pyproject.toml b/pyproject.toml index 905b6cda..7b5d18cd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta" [project] name = "avs-blueprint-agents" -version = "0.6.4" +version = "0.7.0" description = "Microservice blueprint for creating agents" authors = [ { name = "Blueprint Team", email = "patrick.maue@bechtle.com" }, From 3dc88f074e0373f606526f41ca6a40db6870deea Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 12:03:55 +0200 Subject: [PATCH 022/133] fix(test): drop an example directory that exists only as bytecode CI failed on `test_every_directory_is_a_project_or_is_listed` and `test_no_listed_directory_has_quietly_become_a_project[customer_support_qa]`: `NOT_PROJECTS` listed `customer_support_qa`, and on a clean checkout there is no such directory. `examples/customer_support_qa` was deleted in `ef6cd03`, long before this branch. Git removes tracked files and nothing else, so its `__pycache__` directories stayed in the working copy -- nine `.pyc` files and not one tracked file -- and because `.pyc` is gitignored, `git status` stayed clean and the husk looked like a real example. The entry's description was written off that husk, which is why it reads "src/api, src/handlers, src/models and src/services but no main.py": those are the directories `__pycache__` leaves behind, and `main.py` was gone because only `main.cpython-314.pyc` remained. The guard was right and the entry was fiction, so the entry is removed. `example_directories()` now also requires a directory to hold a file that is not a `.pyc`. Without that, this test answers one way on a working copy carrying a husk and another on CI, which is how a green local run shipped a red remote one. The helper's docstring records the incident and the hash. Verified against CI's condition rather than assumed: the tree was exported with `git archive HEAD`, confirmed to contain no `customer_support_qa`, and the tests run there -- 28 passed. Full unit suite green, ruff and black both clean on the file. Co-Authored-By: Claude Opus 5 (1M context) --- tests/unit/examples/test_example_structure.py | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/tests/unit/examples/test_example_structure.py b/tests/unit/examples/test_example_structure.py index 507afe3b..c716a75d 100644 --- a/tests/unit/examples/test_example_structure.py +++ b/tests/unit/examples/test_example_structure.py @@ -26,12 +26,6 @@ "plus a README, illustrating the cache API. It has no declaration and no settings because " "it is not an application." ), - "customer_support_qa": ( - "A skeleton left behind by an earlier refactor: it has src/api, src/handlers, src/models " - "and src/services but no main.py, no settings.toml and no README.md, so there is nothing " - "to run. Finishing or removing it is a decision about the examples, which are deliberately " - "untouched by the multi-agent work." - ), } """Directories under ``examples/`` that are not Blueprint projects, each with why. @@ -41,9 +35,22 @@ """ +def _has_content(directory: Path) -> bool: + """True if anything but compiled bytecode lives under ``directory``. + + A directory deleted from the repository leaves its ``__pycache__`` behind in a working copy + -- git removes tracked files and nothing else -- and ``.pyc`` is gitignored, so the husk is + invisible to ``git status`` and looks like a real example forever. That is not a hypothetical: + ``customer_support_qa`` was deleted in ``ef6cd03`` and sat in ``NOT_PROJECTS`` describing a + layout read off exactly such a husk, which passed locally and failed on CI's clean checkout. + Deriving from files rather than from directories makes this test answer the same on both. + """ + return any(path.is_file() and path.suffix != ".pyc" for path in directory.rglob("*")) + + def example_directories() -> list[Path]: - """Every directory under ``examples/``, derived rather than declared.""" - return sorted(path for path in EXAMPLES_DIR.iterdir() if path.is_dir() and not path.name.startswith((".", "__"))) + """Every directory under ``examples/`` that has content, derived rather than declared.""" + return sorted(path for path in EXAMPLES_DIR.iterdir() if path.is_dir() and not path.name.startswith((".", "__")) and _has_content(path)) def project_examples() -> list[Path]: From 3a305c36ba26869b0e8c2059bde87b5cad37f9c6 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 12:25:58 +0200 Subject: [PATCH 023/133] fix(config): load the environment the project actually resolved (#89) `Config` resolved `app_environment`, logged the name it had resolved, and then loaded a different environment. The value went to Dynaconf as `current_env=`, which is a *derived* property reporting which environment is active rather than the parameter that selects one. The selector is `env=`. Nothing failed and nothing disagreed: a deployment could read `Loading configuration properties for environment: production` in its own logs while every value came from the default section. Probed against dynaconf 3.3.5 with two sections that differ -- `current_env=` returns the default's value, `env=` returns production's. Found while writing the tests, and documented rather than changed: `app_environment` is consumed by the first configuration pass, which loads with `environments=False` and therefore sees top-level keys only -- the same shape `envvar_prefix` requires. Declared inside a section it is invisible to that pass and selects nothing, before this fix or after. The first version of these tests put it in `[default]` and failed for that reason. Behavioural change, not opt-in: a project with a non-default `app_environment` and a matching section has been silently running the default section, and now gets the section it always asked for. If that section is stale -- written once, never exercised, never corrected because it never took effect -- those values go live on upgrade. Written up under Fixed in CHANGELOG.md with that warning, and moved out of Known issues. Tests: `TestTheResolvedEnvironmentIsTheOneLoaded` -- a non-default section applies, the default still loads its own, `[default]` keys are still inherited rather than replaced, the environment variable selects too, and a sectioned declaration does not. Checked they are load-bearing by reinstating the old keyword: three of the five fail. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 26 +++- src/blueprint/agents/config/config.py | 13 +- tests/unit/agents/config/test_config_init.py | 126 +++++++++++++++++++ 3 files changed, 159 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ebcbf66..6127dad6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -112,6 +112,28 @@ Full migration path, including the one decision to get right before the first de ### Fixed +- **⚠️ The environment a project selects is now actually the one that loads** (#89). `Config` + passed the resolved `app_environment` to Dynaconf as `current_env=`, which is a *derived* + property reporting the active environment, not the parameter that selects one. That parameter + is `env=`. The resolved environment was therefore never applied: a deployment could log + `Loading configuration properties for environment: production` and read every value from the + default section, with nothing anywhere disagreeing. Verified against dynaconf 3.3.5 — with two + sections that differ, `current_env=` returns the default's value and `env=` returns + production's. + + **This is a behavioural change, and it is not opt-in.** A project that declares a non-default + `app_environment` *and* has a matching `[]` section has been silently running the + default section; on upgrade it starts getting the section it always asked for. If that section + is stale — written once, never exercised, never corrected because it never took effect — the + values in it go live on upgrade. **Check your non-default sections before upgrading.** A + project with no `app_environment`, or with no section for it, is unaffected. + + Note `app_environment` is read by the first configuration pass, which loads with + `environments=False` and so sees **top-level keys only** — the same shape `envvar_prefix` + requires. Declared inside a section it is invisible to that pass and selects nothing, before + this fix or after; set it at the top level of `settings.toml`, or as `_APP_ENVIRONMENT` + in the environment. Pinned by `TestTheResolvedEnvironmentIsTheOneLoaded`, whose cases fail + against the old keyword. - **`/status/env` no longer returns credentials in clear** (#91). Config masking matched whole keys only, so anything with a prefix or suffix around the secret word came back readable. Present since `4e6421b`, unrelated to grouping. An agent-scoped actuator also now reports its own scope rather @@ -162,10 +184,6 @@ Full migration path, including the one decision to get right before the first de ### Known issues -- **#89 is still open and this release does not fix it.** `Config` passes `current_env=` to Dynaconf - where the environment selector is `env=`, so the resolved environment is never actually loaded and - the log line reports a name that was never applied. The configuration layer was substantially - reworked here and this defect survived it. - Generating the `CronJob` for `scheduler_mode = "event"` is deliberately deferred, so the publisher must be written by hand. - No CI gate enforces that an environment's group declaration covers the in-image agent map; diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index c1954ac7..c7f3ae5a 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -258,11 +258,20 @@ def __init__( Validator("app_environment", must_exist=True, default="development"), ] - # Second pass: load with the correct environment + # Second pass: load with the correct environment. + # + # The selector is ``env``, not ``current_env`` (#89). ``current_env`` is a *derived* + # property on Dynaconf -- it reports which environment is active -- and passing it as a + # keyword stores the value and then ignores it for layer selection, so the resolved + # environment was never actually loaded. Nothing failed: the log line above named the + # resolved environment while ``[development]`` stayed in force, so a deployment could + # read "Loading configuration properties for environment: production" and be running + # the default section. Verified against dynaconf 3.3.5: with two sections that disagree, + # ``current_env=`` returns the default's value and ``env=`` returns production's. self._settings = Dynaconf( settings_files=settings_files, environments=True, - current_env=app_env, + env=app_env, load_dotenv=False, merge_enabled=True, root_path=root_path, diff --git a/tests/unit/agents/config/test_config_init.py b/tests/unit/agents/config/test_config_init.py index c4dc498f..4727efc1 100644 --- a/tests/unit/agents/config/test_config_init.py +++ b/tests/unit/agents/config/test_config_init.py @@ -1,6 +1,8 @@ """Unit tests for Config initialisation and low-level accessors.""" from pathlib import Path + +import pytest from unittest.mock import MagicMock @@ -135,3 +137,127 @@ def test_recurses_into_nested_dicts(self, base_config: Config) -> None: def test_returns_non_dict_input_unchanged(self, base_config: Config) -> None: assert base_config._process_dynabox("just a string", "DOT", ".") == "just a string" assert base_config._process_dynabox(42, "DOT", ".") == 42 + + +class TestTheResolvedEnvironmentIsTheOneLoaded: + """**The environment named in the configuration is the section that takes effect** (#89). + + *Failure it prevents:* the quietest kind there is. ``Config`` resolved ``app_environment`` + correctly, logged the name it had resolved, and then loaded a different environment -- the + value went to Dynaconf as ``current_env``, which is a *derived* property reporting which + environment is active rather than the parameter that selects one. The selector is ``env``. + So a deployment could read ``Loading configuration properties for environment: production`` + in its own logs while every value came from the default section, and nothing disagreed. + + Each test asserts on a **marker that differs between the two sections**, never on the + reported environment name: the name was always right, and that is precisely what kept the + defect invisible for so long. + + ``app_environment`` is consumed by the first pass, which loads with ``environments=False`` + and therefore sees **top-level keys only** -- the same shape ``envvar_prefix`` requires, for + the same reason. A declaration inside a section is invisible to it; the last test pins that + so nobody reads this class as promising otherwise. + """ + + def _written(self, tmp_path: Path, body: str) -> Path: + path = tmp_path / "settings.toml" + path.write_text(body, encoding="utf-8") + return path + + def test_a_non_default_environments_section_is_the_one_that_applies(self, tmp_path: Path) -> None: + path = self._written( + tmp_path, + """ +app_environment = "production" + +[default] +app_name = "from-default" +app_port = 8000 + +[production] +app_name = "from-production" +app_port = 9999 +""", + ) + config = Config(settings_files=[str(path)], root_path=str(tmp_path)) + + assert config.get("app_name") == "from-production" + assert config.get("app_port") == 9999 + + def test_the_default_environment_still_loads_its_own_section(self, tmp_path: Path) -> None: + path = self._written( + tmp_path, + """ +app_environment = "development" + +[default] +app_name = "from-default" +app_port = 8000 + +[production] +app_name = "from-production" +app_port = 9999 +""", + ) + config = Config(settings_files=[str(path)], root_path=str(tmp_path)) + + assert config.get("app_name") == "from-default" + assert config.get("app_port") == 8000 + + def test_keys_only_the_default_section_declares_are_still_inherited(self, tmp_path: Path) -> None: + """Selecting an environment layers it over ``[default]``; it does not replace it.""" + path = self._written( + tmp_path, + """ +app_environment = "production" + +[default] +app_name = "from-default" +app_port = 8000 +shared_key = "only-in-default" + +[production] +app_name = "from-production" +""", + ) + config = Config(settings_files=[str(path)], root_path=str(tmp_path)) + + assert config.get("app_name") == "from-production" + assert config.get("shared_key") == "only-in-default" + + def test_the_environment_variable_selects_too(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """The realistic deployment route: one image, the section chosen per environment.""" + path = self._written( + tmp_path, + """ +[default] +app_name = "from-default" +app_port = 8000 + +[production] +app_name = "from-production" +app_port = 9999 +""", + ) + monkeypatch.setenv("DYNACONF_APP_ENVIRONMENT", "production") + config = Config(settings_files=[str(path)], root_path=str(tmp_path)) + + assert config.get("app_name") == "from-production" + + def test_a_sectioned_declaration_is_not_seen_by_the_first_pass(self, tmp_path: Path) -> None: + """Documents the trap rather than promising it works: the first pass reads top level only.""" + path = self._written( + tmp_path, + """ +[default] +app_environment = "production" +app_name = "from-default" +app_port = 8000 + +[production] +app_name = "from-production" +""", + ) + config = Config(settings_files=[str(path)], root_path=str(tmp_path)) + + assert config.get("app_name") == "from-default" From c027d66ef045d9c30fcf6d21794803ba3445f0b0 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 14 Sep 2026 12:52:34 +0200 Subject: [PATCH 024/133] docs(readme): install instructions for TestPyPI that actually work Both documented commands fail, and they fail in a way that looks like a defect in this package rather than in the instruction. Found by installing 0.9.0a1 from TestPyPI as a consumer would. TestPyPI carries stale copies of common dependencies -- a decade-old `fastapi` sdist that cannot even be built, and an `apscheduler` older than this package requires. Any setup that leaves TestPyPI reachable for *dependencies* hits them: - `--index-url` TestPyPI `--extra-index-url` PyPI (the documented pip command) dies on `FileNotFoundError: DESCRIPTION.txt` building `fastapi`. - Swapping the two flags fails identically. pip has no index priority: `--extra-index-url` merges the candidate lists and picks by version, so the broken copies stay reachable whichever order they are in. - `priority = "supplemental"` (the documented uv config) is not what confines an index in uv 0.8.3 either. uv's default `first-index` strategy pins each package to the first index containing it, so resolution fails on TestPyPI's `apscheduler` 3.11.0 against a `>=3.11.2` requirement. The fix is to name the index for this one package and nothing else, which uv supports directly: `explicit = true` plus a `[tool.uv.sources]` entry. Verified -- `uv lock` resolves 139 packages with `avs-blueprint-agents` from test.pypi.org and `apscheduler` 3.11.3 from pypi.org, `uv sync` installs, and the public API imports. pip has no equivalent, so its instructions are now two steps: fetch the package alone with `--no-deps`, then install that file with dependencies from PyPI. Verified end to end -- the installed package scaffolds a project with `asbs setup` and passes `asbs validate`. Both forms now pin the exact alpha, because PyPI carries the newer stable and an unpinned install silently resolves to that instead. Co-Authored-By: Claude Opus 5 (1M context) --- README.md | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index ed68514b..b4f74609 100644 --- a/README.md +++ b/README.md @@ -64,27 +64,43 @@ uv add avs-blueprint-agents ### Alpha Release (TestPyPI) -To install the latest alpha version for testing, add the TestPyPI index to your `pyproject.toml`: +Alpha builds are published to TestPyPI. **TestPyPI must be used for this package only** -- it also +carries stale copies of common dependencies (an ancient `fastapi`, an `apscheduler` too old for +this package), and any setup that lets the resolver reach them for *dependencies* fails. + +With uv, name the index for this one package and nothing else: ```toml [[tool.uv.index]] name = "test-pypi" url = "https://test.pypi.org/simple/" -priority = "supplemental" -``` +explicit = true # only for packages that name it below -Then install: +[tool.uv.sources] +avs-blueprint-agents = { index = "test-pypi" } +``` ```bash -uv add avs-blueprint-agents +uv add "avs-blueprint-agents==0.9.0a1" ``` -Or with pip: +`explicit = true` is the load-bearing part: without it uv applies its default `first-index` +strategy, pins every dependency to the first index that happens to contain it, and the resolution +fails on TestPyPI's old `apscheduler`. That is deliberate protection against dependency confusion, +not something to work around with `--index-strategy unsafe-best-match`. + +**pip has no equivalent** -- no index priority and no per-package source, so `--extra-index-url` +merges both indexes and the broken copies stay reachable whichever order the flags are in. Fetch +the package alone, then install it with dependencies resolved from PyPI: ```bash -pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ avs-blueprint-agents +pip download --no-deps --index-url https://test.pypi.org/simple/ "avs-blueprint-agents==0.9.0a1" -d ./dl +pip install --index-url https://pypi.org/simple/ ./dl/avs_blueprint_agents-0.9.0a1-py3-none-any.whl ``` +Pin the exact alpha version in both cases: PyPI carries the newer stable release, and an unpinned +install resolves to that instead. + ### From Source ```bash From 424d9dcc3ce82bd400716cbacd660dcf83ae5e05 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Tue, 15 Sep 2026 12:04:13 +0200 Subject: [PATCH 025/133] feat(docs): ship the documentation inside the package README.md becomes the wheel's METADATA, and the 21 documentation pages it links to stayed behind in the repository -- so every one of those links resolved to nothing once installed, and an assistant working in a consuming project could not read the guide it was pointed at. The user-facing guides move to src/blueprint/agent_generator/docs/ and ship with the wheel; `asbs docs` locates them wherever site-packages happens to be. Seven Claude Code skills reference those pages rather than restating them, so the docs stay the single source of truth, and a test parses the skills and fails if a slug one of them cites stops resolving. - docs move into the package; 28 pages now ship - asbs docs [] [--cat] [--root] locates them - skills: blueprint-cli, -config, -events, -multi-agent, -testing, -deployment, -troubleshooting; new-agent-service and add-component extended - cli-reference.md split into an index plus one page per command - multi-agent migration split out of multi-agent-setup - README links absolute: relative ones resolve nowhere on PyPI - LICENSE added; the MIT claim had no file behind it - pytest/pytest-asyncio out of runtime dependencies Co-Authored-By: Claude Opus 5 (1M context) --- AGENTS.md | 4 +- CHANGELOG.md | 36 +- CONTRIBUTE.md | 2 +- LICENSE | 21 + README.md | 79 +- docs/guides/cli-reference.md | 1023 ----------------- pyproject.toml | 11 +- .../agent_generator/claude_docs/CLAUDE.md | 17 + .../claude_docs/skills/add-component/SKILL.md | 22 + .../claude_docs/skills/blueprint-cli/SKILL.md | 50 + .../skills/blueprint-config/SKILL.md | 57 + .../skills/blueprint-deployment/SKILL.md | 48 + .../skills/blueprint-events/SKILL.md | 73 ++ .../skills/blueprint-multi-agent/SKILL.md | 52 + .../skills/blueprint-testing/SKILL.md | 49 + .../skills/blueprint-troubleshooting/SKILL.md | 45 + .../skills/new-agent-service/SKILL.md | 20 +- .../agent_generator/cli/commands/docs.py | 120 ++ src/blueprint/agent_generator/cli/main.py | 26 +- .../blueprint/agent_generator/docs}/README.md | 20 +- .../docs}/components/agents.md | 0 .../docs}/components/event-handlers.md | 0 .../docs}/components/rest-apis.md | 0 .../docs}/components/schedulers.md | 0 .../docs}/components/services.md | 0 .../docs}/concepts/architecture.md | 0 .../agent_generator/docs}/concepts/caching.md | 0 .../docs}/concepts/configuration.md | 0 .../docs}/concepts/event-processing.md | 0 .../docs}/concepts/observability.md | 0 .../agent_generator/docs}/getting-started.md | 0 .../docs/guides/cli-reference.md | 47 + .../docs/guides/cli/auto-registration.md | 155 +++ .../agent_generator/docs/guides/cli/claude.md | 66 ++ .../agent_generator/docs/guides/cli/create.md | 496 ++++++++ .../agent_generator/docs/guides/cli/dev.md | 40 + .../agent_generator/docs/guides/cli/naming.md | 83 ++ .../agent_generator/docs/guides/cli/setup.md | 92 ++ .../docs/guides/cli/validate.md | 65 ++ .../docs}/guides/deployment.md | 0 .../docs/guides/multi-agent-migration.md | 123 ++ .../docs}/guides/multi-agent-setup.md | 104 +- .../agent_generator/docs}/guides/testing.md | 0 .../docs}/guides/troubleshooting.md | 0 .../agent_generator/docs}/reference/api.md | 0 .../docs}/reference/configuration-keys.md | 0 .../agent_generator/docs}/reference/models.md | 0 .../generator/claude_generator.py | 7 +- .../agent_generator/cli/commands/test_docs.py | 126 ++ tests/unit/agents/test_design_rules.py | 7 +- 50 files changed, 2009 insertions(+), 1177 deletions(-) create mode 100644 LICENSE delete mode 100644 docs/guides/cli-reference.md create mode 100644 src/blueprint/agent_generator/claude_docs/skills/blueprint-cli/SKILL.md create mode 100644 src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md create mode 100644 src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md create mode 100644 src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md create mode 100644 src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md create mode 100644 src/blueprint/agent_generator/claude_docs/skills/blueprint-testing/SKILL.md create mode 100644 src/blueprint/agent_generator/claude_docs/skills/blueprint-troubleshooting/SKILL.md create mode 100644 src/blueprint/agent_generator/cli/commands/docs.py rename {docs => src/blueprint/agent_generator/docs}/README.md (76%) rename {docs => src/blueprint/agent_generator/docs}/components/agents.md (100%) rename {docs => src/blueprint/agent_generator/docs}/components/event-handlers.md (100%) rename {docs => src/blueprint/agent_generator/docs}/components/rest-apis.md (100%) rename {docs => src/blueprint/agent_generator/docs}/components/schedulers.md (100%) rename {docs => src/blueprint/agent_generator/docs}/components/services.md (100%) rename {docs => src/blueprint/agent_generator/docs}/concepts/architecture.md (100%) rename {docs => src/blueprint/agent_generator/docs}/concepts/caching.md (100%) rename {docs => src/blueprint/agent_generator/docs}/concepts/configuration.md (100%) rename {docs => src/blueprint/agent_generator/docs}/concepts/event-processing.md (100%) rename {docs => src/blueprint/agent_generator/docs}/concepts/observability.md (100%) rename {docs => src/blueprint/agent_generator/docs}/getting-started.md (100%) create mode 100644 src/blueprint/agent_generator/docs/guides/cli-reference.md create mode 100644 src/blueprint/agent_generator/docs/guides/cli/auto-registration.md create mode 100644 src/blueprint/agent_generator/docs/guides/cli/claude.md create mode 100644 src/blueprint/agent_generator/docs/guides/cli/create.md create mode 100644 src/blueprint/agent_generator/docs/guides/cli/dev.md create mode 100644 src/blueprint/agent_generator/docs/guides/cli/naming.md create mode 100644 src/blueprint/agent_generator/docs/guides/cli/setup.md create mode 100644 src/blueprint/agent_generator/docs/guides/cli/validate.md rename {docs => src/blueprint/agent_generator/docs}/guides/deployment.md (100%) create mode 100644 src/blueprint/agent_generator/docs/guides/multi-agent-migration.md rename {docs => src/blueprint/agent_generator/docs}/guides/multi-agent-setup.md (82%) rename {docs => src/blueprint/agent_generator/docs}/guides/testing.md (100%) rename {docs => src/blueprint/agent_generator/docs}/guides/troubleshooting.md (100%) rename {docs => src/blueprint/agent_generator/docs}/reference/api.md (100%) rename {docs => src/blueprint/agent_generator/docs}/reference/configuration-keys.md (100%) rename {docs => src/blueprint/agent_generator/docs}/reference/models.md (100%) create mode 100644 tests/unit/agent_generator/cli/commands/test_docs.py diff --git a/AGENTS.md b/AGENTS.md index 9480130b..7293ac78 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,8 +35,8 @@ scaffolder that generates projects against it. Inside the framework: | `config/` | `Config` (Dynaconf), the logging manager | | `models/` | Pydantic models: events, configuration, API payloads, status | -Prose for users lives in `docs/`: `docs/concepts/architecture.md` for the assembly model, -`docs/concepts/event-processing.md` for the dispatch pipeline, `docs/concepts/configuration.md` +Prose for users lives in `docs/`: `src/blueprint/agent_generator/docs/concepts/architecture.md` for the assembly model, +`src/blueprint/agent_generator/docs/concepts/event-processing.md` for the dispatch pipeline, `src/blueprint/agent_generator/docs/concepts/configuration.md` for settings, `docs/guides/` for deployment, testing and the CLI. Specifications and plans are in `docs/specs/` and `docs/plans/`; a feature's changelog beside its plan is the running record of what was done and why. diff --git a/CHANGELOG.md b/CHANGELOG.md index 6127dad6..8c2935fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,40 @@ # Changelog ## [Unreleased] +### Added + +- **The documentation ships inside the package.** The user-facing guides moved from the repository + root to `src/blueprint/agent_generator/docs/` and are now installed with the wheel, so a + developer or an AI assistant working in a consuming project can read them with no network access. + Previously `README.md` became the wheel's `METADATA` while the 21 documentation pages it links to + stayed behind in the repository, and every one of those links resolved to nothing once installed. +- **`asbs docs`** locates the packaged documentation: `asbs docs` lists every page, `asbs docs + ` prints the path to one, `asbs docs --cat` prints its contents, and `--root` + prints the directory. A bare page name is accepted when it is unambiguous. +- **Seven Claude Code skills**, installed by `asbs claude` alongside the two that already existed: + `blueprint-cli`, `blueprint-config`, `blueprint-events`, `blueprint-multi-agent`, + `blueprint-testing`, `blueprint-deployment` and `blueprint-troubleshooting`. Each carries the + rules that are expensive to get wrong and points at the packaged page for the rest, rather than + restating it -- the docs stay the single source of truth. +- **`LICENSE`** (MIT). The repository claimed MIT in its classifiers and linked a `LICENSE` file + that did not exist; the license is now declared as an SPDX expression and ships in the wheel. + +### Changed + +- **`docs/guides/cli-reference.md` is an index**, with one page per command under `guides/cli/` + (`setup`, `create`, `validate`, `dev`, `claude`, plus `naming` and `auto-registration`). It was a + single 1,023-line page, which meant reading about one flag cost the whole file. +- **Migrating an existing agent into a group is its own page**, + `guides/multi-agent-migration.md`, split out of `guides/multi-agent-setup.md`. +- **`README.md` links are absolute.** Relative links do not resolve on the PyPI project page or in + the installed `METADATA`. The CI badge pointed at an unrelated repository. + +### Fixed + +- **`pytest` and `pytest-asyncio` are no longer runtime dependencies.** They were listed in + `[project.dependencies]`, so every consumer installed the test suite's tooling in production. + They remain in the `ci` extra. + ### Added - **`AppBuilder.build()` now sources `docs_url`/`redoc_url`/`openapi_url` from config** (#191, defaults unchanged: `/docs`, `/redoc`, `/openapi.json`). Previously these were hardcoded at `FastAPI()` construction, so a consumer could not disable the built-in `/docs` route without mutating `app.router.routes` after the fact — fragile because it depends on FastAPI's internal route-registration shape (bechtleav360/avs.ai.idac.service-sessions#191). Set `docs_url = "@none"` (Dynaconf's `None` cast) in `settings.toml` to opt out before the route is ever registered. Set at the root of `settings.toml`, not under an `agent_scope` block (`Config._scoped_get()` falls back to the root value when a scoped lookup is `None`). Note FastAPI only registers `docs_url`/`redoc_url` when `openapi_url` is also set, so disabling `openapi_url` disables all three. @@ -13,7 +47,7 @@ all of this — see **Breaking** for the exceptions, which are listed in the ord hit them. Full migration path, including the one decision to get right before the first deploy: -[`docs/guides/multi-agent-setup.md`](docs/guides/multi-agent-setup.md). The normative spec is +[`guides/multi-agent-setup.md`](src/blueprint/agent_generator/docs/guides/multi-agent-setup.md). The normative spec is `docs/specs/2026-08-28-multi-agent-grouping.md`. ### Added diff --git a/CONTRIBUTE.md b/CONTRIBUTE.md index 9986574b..d8c204e2 100644 --- a/CONTRIBUTE.md +++ b/CONTRIBUTE.md @@ -288,7 +288,7 @@ Publishing is handled by the CI/CD pipeline. See `.github/workflows/publish.yml` If you encounter issues, please: -1. Check the [Troubleshooting Guide](docs/guides/troubleshooting.md) for known issues +1. Check the [Troubleshooting Guide](src/blueprint/agent_generator/docs/guides/troubleshooting.md) for known issues 2. Review the test output carefully for error messages 3. Open an issue on GitHub with details about your environment and the error diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..df54ac4f --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Bechtle AG + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index b4f74609..4dbd1e74 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ [![PyPI version](https://img.shields.io/pypi/v/avs-blueprint-agents)](https://pypi.org/project/avs-blueprint-agents/) [![Python 3.13+](https://img.shields.io/badge/python-3.13%2B-blue)](https://www.python.org/downloads/) -[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE) -[![CI](https://github.com/2SpeakAI/blueprint-agents/actions/workflows/ci.yml/badge.svg)](https://github.com/2SpeakAI/blueprint-agents/actions) +[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/LICENSE) +[![CI](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/actions/workflows/ci.yml/badge.svg)](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/actions) **A Python framework for building production-ready AI agent microservices with event-driven architecture.** @@ -223,22 +223,22 @@ nor its telemetry identity. Other group settings: `BLUEPRINT_GROUP_CONFIG` and `BLUEPRINT_GROUP` select a named group from a mounted file, and `BLUEPRINT_CRITICAL_AGENTS` says which agents failing should fail the process. -See the [Multi-Agent Setup guide](docs/guides/multi-agent-setup.md) for the full reference and the +See the [Multi-Agent Setup guide](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md) for the full reference and the migration path for an existing single-agent project. --- ## Examples -Explore complete, runnable examples in the [`examples/`](examples/) directory: +Explore complete, runnable examples in the [`examples/`](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/examples/) directory: | Example | Description | Components Used | |---------|-------------|-----------------| -| [**inventory_api**](examples/inventory_api/) | Product inventory CRUD REST API | RestApiBase, ServiceBase, Cache | -| [**order_event_pipeline**](examples/order_event_pipeline/) | E-commerce order processing with Dapr pub/sub | EventHandlerBase, ServiceBase, Dapr | -| [**document_summarizer**](examples/document_summarizer/) | LLM-powered document summarization with structured output | AgentRuntime, AgentBuilder, Tools | -| [**webhook_relay**](examples/webhook_relay/) | Webhook ingestion and normalization pipeline with NATS | EventHandlerBase, NATS, Cache | -| [**health_monitor**](examples/health_monitor/) | System health monitoring with scheduled checks | SchedulerBase, ServiceBase, Cache | +| [**inventory_api**](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/examples/inventory_api/) | Product inventory CRUD REST API | RestApiBase, ServiceBase, Cache | +| [**order_event_pipeline**](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/examples/order_event_pipeline/) | E-commerce order processing with Dapr pub/sub | EventHandlerBase, ServiceBase, Dapr | +| [**document_summarizer**](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/examples/document_summarizer/) | LLM-powered document summarization with structured output | AgentRuntime, AgentBuilder, Tools | +| [**webhook_relay**](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/examples/webhook_relay/) | Webhook ingestion and normalization pipeline with NATS | EventHandlerBase, NATS, Cache | +| [**health_monitor**](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/examples/health_monitor/) | System health monitoring with scheduled checks | SchedulerBase, ServiceBase, Cache | --- @@ -291,7 +291,7 @@ job_timeout_seconds = 300 No `SessionsBus`, `SessionsApiClient`, or `SessionKeyProvider` references in service `main.py` — `AppBuilder.build()` wires them automatically. -See the [Configuration Reference](docs/concepts/configuration.md) for all available settings. +See the [Configuration Reference](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/concepts/configuration.md) for all available settings. --- @@ -310,7 +310,7 @@ asbs validate # Validate project structure asbs dev [--port ] # Run development server ``` -See the full [CLI Reference](docs/guides/cli-reference.md). +See the full [CLI Reference](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/cli-reference.md). --- @@ -322,40 +322,53 @@ Blueprint Agents services deploy as standard Python containers: - **Kubernetes** -- Helm charts with Dapr sidecar injection, health probes, and ConfigMap/Secret management - **CI/CD** -- GitHub Actions workflows for linting, testing, and publishing -See the [Deployment Guide](docs/guides/deployment.md) for detailed instructions. +See the [Deployment Guide](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/deployment.md) for detailed instructions. --- ## Documentation +**The documentation ships with the package.** Every page below is installed alongside the code, so +a developer -- or an AI assistant working in your project -- can read it without network access: + +```bash +asbs docs # list every page +asbs docs guides/multi-agent-setup # print the path to one page +asbs docs reference/configuration-keys --cat # print its contents +``` + +`asbs claude` additionally installs Claude Code skills that route to the right page for the task at +hand. The links below are the same pages on GitHub, for browsing. + ### Getting Started -- [Getting Started Guide](docs/getting-started.md) -- Installation, first project, and walkthrough -- [Multi-Agent Setup](docs/guides/multi-agent-setup.md) -- Running several agents in one process, and migrating an existing one into a group +- [Getting Started Guide](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/getting-started.md) -- Installation, first project, and walkthrough +- [Multi-Agent Setup](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md) -- Running several agents in one process +- [Multi-Agent Migration](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md) -- Moving an existing agent into a group ### Core Concepts -- [Architecture](docs/concepts/architecture.md) -- Component model, registry, and lifecycle -- [Event Processing](docs/concepts/event-processing.md) -- CloudEvents, handler chain, Dapr/NATS -- [Configuration](docs/concepts/configuration.md) -- Settings, secrets, and environment variables -- [Caching](docs/concepts/caching.md) -- Disk and Redis caches, TTL, namespaces, and per-agent isolation -- [Observability](docs/concepts/observability.md) -- OpenTelemetry tracing, metrics, and logging +- [Architecture](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/concepts/architecture.md) -- Component model, registry, and lifecycle +- [Event Processing](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/concepts/event-processing.md) -- CloudEvents, handler chain, Dapr/NATS +- [Configuration](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/concepts/configuration.md) -- Settings, secrets, and environment variables +- [Caching](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/concepts/caching.md) -- Disk and Redis caches, TTL, namespaces, and per-agent isolation +- [Observability](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/concepts/observability.md) -- OpenTelemetry tracing, metrics, and logging ### Component Guides -- [Event Handlers](docs/components/event-handlers.md) -- [Services](docs/components/services.md) -- [REST APIs](docs/components/rest-apis.md) -- [Agents](docs/components/agents.md) -- [Schedulers](docs/components/schedulers.md) +- [Event Handlers](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/components/event-handlers.md) +- [Services](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/components/services.md) +- [REST APIs](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/components/rest-apis.md) +- [Agents](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/components/agents.md) +- [Schedulers](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/components/schedulers.md) ### Operations -- [CLI Reference](docs/guides/cli-reference.md) -- [Testing Guide](docs/guides/testing.md) -- [Deployment Guide](docs/guides/deployment.md) -- [Troubleshooting](docs/guides/troubleshooting.md) +- [CLI Reference](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/cli-reference.md) +- [Testing Guide](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/testing.md) +- [Deployment Guide](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/deployment.md) +- [Troubleshooting](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/troubleshooting.md) ### Reference -- [API Reference](docs/reference/api.md) -- [Configuration Keys](docs/reference/configuration-keys.md) -- [Data Models](docs/reference/models.md) +- [API Reference](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/reference/api.md) +- [Configuration Keys](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/reference/configuration-keys.md) +- [Data Models](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/reference/models.md) --- @@ -371,7 +384,7 @@ See the [Deployment Guide](docs/guides/deployment.md) for detailed instructions. ## Contributing -We welcome contributions! See [CONTRIBUTE.md](CONTRIBUTE.md) for guidelines on: +We welcome contributions! See [CONTRIBUTE.md](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/CONTRIBUTE.md) for guidelines on: - Setting up the development environment - Running tests and linting @@ -381,4 +394,4 @@ We welcome contributions! See [CONTRIBUTE.md](CONTRIBUTE.md) for guidelines on: ## License -This project is licensed under the MIT License. See [LICENSE](LICENSE) for details. +This project is licensed under the MIT License. See [LICENSE](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/LICENSE) for details. diff --git a/docs/guides/cli-reference.md b/docs/guides/cli-reference.md deleted file mode 100644 index e22ad9de..00000000 --- a/docs/guides/cli-reference.md +++ /dev/null @@ -1,1023 +0,0 @@ -# CLI Reference - -The `asbs` command-line tool is the primary interface for scaffolding, developing, and managing Blueprint Agents projects. It is installed automatically with the `avs-blueprint-agents` package. - -```bash -pip install avs-blueprint-agents -``` - ---- - -## Naming Conventions and Auto-Registration - -All `asbs create` commands follow consistent naming conventions and automatically register components in `src/main.py`. - -### Input Flexibility - -The CLI accepts component names in multiple formats and normalizes them to proper class and file names: - -- **snake_case**: `order_placed` → `OrderPlacedHandler` -- **CamelCase**: `OrderPlaced` → `OrderPlacedHandler` -- **kebab-case**: `order-placed` → `OrderPlacedHandler` - -All formats are converted to proper class names without double suffixes (e.g., never `OrderPlacedHandlerHandler`). - -### Component Naming - -Each component type follows a consistent suffix pattern: - -| Component Type | Input | Class Name | File Name | Notes | -|---|---|---|---|---| -| **Handler** | `order_placed` | `OrderPlacedHandler` | `order_placed_handler.py` | Handles events | -| **Service** | `invoice_processor` | `InvoiceProcessorService` | `invoice_processor_service.py` | Contains business logic | -| **API** | `order_management` | `OrderManagementApi` | `order_management_api.py` | REST endpoints + models file | -| **Agent** | `document_analyzer` | -- | -- | No module of its own: a builder in `main.py` plus two prompt files | -| **Scheduler** | `cleanup` | `CleanupScheduler` | `cleanup_scheduler.py` | Background tasks | - -### Name Normalization Examples - -The CLI handles various input formats correctly: - -#### Handler Examples -```bash -asbs create handler order_placed # Snake case input -asbs create handler OrderPlaced # CamelCase input -asbs create handler order-placed # Kebab-case input -# All produce: OrderPlacedHandler in order_placed_handler.py -``` - -#### Service Examples -```bash -asbs create service user_manager -asbs create service UserManager -asbs create service user-manager -# All produce: UserManagerService in user_manager_service.py -``` - -#### API Examples -```bash -asbs create api product_catalog -asbs create api ProductCatalog -asbs create api product-catalog -# All produce: ProductCatalogApi in product_catalog_api.py -# And the models package src/models/product_catalog/ (dto, domain_models, mapper) -``` - -#### Agent Examples -```bash -asbs create agent document_analyzer -asbs create agent DocumentAnalyzer -asbs create agent document-analyzer -# All produce the runtime name: document_analyzer_agent -# Declared in src/main.py as an AgentBuilder; prompts in src/prompts/ -``` - -### Auto-Registration - -When you create a component, the CLI automatically: - -1. **Creates the component file** in the appropriate directory -2. **Adds imports** to `src/main.py` -3. **Registers with AppBuilder** in the chain - -If auto-registration fails (e.g., `src/main.py` not found), the CLI displays a clear error message with manual registration instructions. - -#### Example Auto-Registration Output - -```bash -$ asbs create handler order_placed -✓ Created handler: src/handlers/order_placed_handler.py -✓ Auto-registered in src/main.py - - Added import: from src.handlers.order_placed_handler import OrderPlacedHandler - - Added registration: .with_handler(OrderPlacedHandler) -``` - ---- - -## asbs setup - -Scaffold a complete Blueprint Agents project with all required directories and configuration files. - -```bash -asbs setup [--output-dir ] [--overwrite] [--verbose] -``` - -### Arguments - -| Argument | Description | Required | -|----------------|------------------------------------|----------| -| `project-name` | Name of the project to create | Yes | - -### Options - -| Flag | Description | Default | -|-----------------------|--------------------------------------------------------|---------| -| `--output-dir ` | Parent directory the project is created in | `.` | -| `--overwrite` | Overwrite existing files instead of refusing | off | -| `--verbose`, `-v` | Debug-level logging from the generator | off | - -The project name is normalised to a class name (`order-processor` gives `OrderProcessor/`), and the -agent's namespace is that name in snake case (`order_processor`). - -### Generated Project Structure - -``` -/ - src/ - main.py # the declaration: agent = AppBuilder()... - api/ - handlers/ - models// # dto.py, domain_models.py, mapper.py - prompts/ - services/ - agents.toml # agent name -> declaration; baked into the image - settings.toml - .secrets.toml # git-ignored - .secrets.toml.example # committed, so the keys to fill in are known - Dockerfile - .gitignore -``` - -There is no `tests/` directory and no `pyproject.toml`: the scaffolder writes source, settings and -the image, and the packaging and test layout are the project's own. `asbs validate` reports both as -missing, which is a reminder rather than a defect in the scaffold. - -### Example - -```bash -asbs setup my-ai-service -``` - -The generated `main.py` is a **declaration**, not an application. Nothing is constructed until -something calls `build()`, which is what lets the same file be served on its own and be hosted -alongside other agents in one process: - -```python -from blueprint.agents.agent import AgentBuilder -from blueprint.agents.app_builder import AppBuilder - -from .services import MyAiServiceService - -my_ai_service_agent = ( - AgentBuilder(runtime_name="my_ai_service_agent") - .with_model_from_config() - .with_system_prompt("my_ai_service_agent_system") -) - -agent = ( - AppBuilder() - .with_service(MyAiServiceService) - .with_agent(my_ai_service_agent, name="my_ai_service_agent") -) -``` - -Components are registered as **classes**, not instances: a component constructed on the `with_*` -line is constructed before any namespace exists and belongs to the root for ever, which is why a -group refuses one. - -`asbs setup` also writes `agents.toml`, which maps the agent's name to that declaration: - -```toml -[agents.my_ai_service] -module = "src.main:agent" -``` - -That name is the agent's identity everywhere outside the file -- the NATS queue group, part of the -JetStream durable name, the cache partition, the OpenTelemetry `service.name` and the `/api/` -route prefix -- so changing it after the first deploy is a consumer migration. The project is run -with `python -m blueprint.agents.entrypoint`, which reads that map and the deployment's group. - ---- - -## asbs create handler - -Generate a new event handler component by creating a subclass of `EventHandlerBase`. - -```bash -asbs create handler [--event-type ] [--priority ] [--output-dir ] -``` - -### Arguments - -| Argument | Description | Required | -|----------|---------------------------------|----------| -| `name` | Name of the handler to create | Yes | - -### Options - -| Flag | Description | Default | -|-------------------------|----------------------------------------------------|------------------| -| `--event-type ` | The event type this handler will respond to | (prompt) | -| `--priority ` | Handler priority (lower numbers execute first) | `10` | -| `--output-dir ` | Where the handler module is written | `src/handlers` | - -Ties at equal priority are resolved by registration order, which is the order the `with_*` calls -appear in `main.py`. - -### Naming - -Handler names are converted to `Handler` format: - -- Input: `order_placed` → Class: `OrderPlacedHandler` → File: `order_placed_handler.py` -- Input: `OrderPlaced` → Class: `OrderPlacedHandler` → File: `order_placed_handler.py` -- Input: `order-placed` → Class: `OrderPlacedHandler` → File: `order_placed_handler.py` - -### Auto-Registration - -The created handler is automatically: -- Imported in `src/main.py` -- Registered with `.with_handler(OrderPlacedHandler)` - -If auto-registration fails, manual registration instructions are provided. - -### Examples - -#### Basic Handler - -```bash -asbs create handler order_placed --event-type "order.placed" -``` - -Creates `src/handlers/order_placed_handler.py` with an `OrderPlacedHandler` class. - -#### Handler with Priority - -```bash -asbs create handler high_priority_event --event-type "system.alert" --priority 5 -``` - -Handlers with lower priority numbers execute first in the chain. - -#### Handler Generated Code - -The generated handler includes: - -```python -from blueprint.agents.handler import EventHandlerBase - -class OrderPlacedHandler(EventHandlerBase): - def __init__(self) -> None: - super().__init__(priority=10) - - async def on_startup(self) -> None: - # Initialize resources from registry - pass - - async def on_shutdown(self) -> None: - # Clean up resources - pass - - async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: - return event.type == "order.placed" - - async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None: - # Return None to pass to next handler - # Return HandlerResult(...) to publish and stop chain - return None -``` - ---- - -## asbs create service - -Generate a new service component by creating a subclass of `ServiceBase`. - -```bash -asbs create service [--output-dir ] -``` - -### Arguments - -| Argument | Description | Required | -|----------|---------------------------------|----------| -| `name` | Name of the service to create | Yes | - -### Options - -| Flag | Description | Default | -|-----------------------|-------------------------------------|------------------| -| `--output-dir ` | Where the service module is written | `src/services` | - -### Naming - -Service names are converted to `Service` format: - -- Input: `invoice_processor` → Class: `InvoiceProcessorService` → File: `invoice_processor_service.py` -- Input: `InvoiceProcessor` → Class: `InvoiceProcessorService` → File: `invoice_processor_service.py` -- Input: `invoice-processor` → Class: `InvoiceProcessorService` → File: `invoice_processor_service.py` - -### Auto-Registration - -The created service is automatically: -- Imported in `src/main.py` -- Registered with `.with_service(InvoiceProcessorService)` - -### Examples - -#### Basic Service - -```bash -asbs create service invoice_processor -``` - -Creates `src/services/invoice_processor_service.py` with an `InvoiceProcessorService` class. - -#### Service Generated Code - -The generated service includes: - -```python -from blueprint.agents.services import ServiceBase - -class InvoiceProcessorService(ServiceBase): - async def on_startup(self) -> None: - # Initialize resources, fetch dependencies from registry - # Example: self._cache = self.registry.cache_service - # Example: self._agent = self.registry.get_agent("analyzer") - pass - - async def on_shutdown(self) -> None: - # Clean up resources - pass - - async def process(self, data: dict) -> dict: - """Process invoice data. - - Args: - data: Invoice information - - Returns: - Processing result - """ - # TODO: Implement business logic - pass -``` - ---- - -## asbs create api - -Generate a new REST API component by creating a subclass of `RestApiBase`, plus a models file with Request/Response classes. - -```bash -asbs create api [--output-dir ] -``` - -### Arguments - -| Argument | Description | Required | -|----------|------------------------------|----------| -| `name` | Name of the API to create | Yes | - -### Options - -| Flag | Description | Default | -|-----------------------|---------------------------------|-------------| -| `--output-dir ` | Where the API module is written | `src/api` | - -### Naming - -API names are converted to `Api`, with a models package named after the component: - -- Input: `order_management` - - Class: `OrderManagementApi` - - API file: `src/api/order_management_api.py` - - Models package: `src/models/order_management/` - -### Files Generated - -1. **API module** (`src/api/_api.py`) - - `RestApiBase` subclass with a `GET /{item_id}` and a `POST /` placeholder, both raising - `501 Not Implemented` until you write them - - Dependency injection via `self.registry.get_service(...)` in `on_startup` - -2. **A models package** (`src/models//`), three files: - - `dto.py` -- `Request` and `Response`, the API's wire contract - - `domain_models.py` -- `Model`, what the service works with - - `mapper.py` -- `Mapper`, converting between the two - -### Auto-Registration - -The created API is automatically: -- Imported in `src/main.py` (both models and API) -- Registered with `.with_rest_api(OrderManagementApi)` - -### Examples - -#### Basic API - -```bash -asbs create api order_management -``` - -Creates: -- `src/api/order_management_api.py` with the `OrderManagementApi` class -- `src/models/order_management/dto.py` with `OrderManagementRequest` and `OrderManagementResponse` -- `src/models/order_management/domain_models.py` with `OrderManagementModel` -- `src/models/order_management/mapper.py` with `OrderManagementMapper` - -#### API Generated Code - -The generated API includes: - -```python -"""REST API for order_management operations.""" - -from fastapi import HTTPException, status -from blueprint.agents.io.api.rest_api_base import RestApiBase -from src.models.order_management.dto import OrderManagementRequest, OrderManagementResponse - -class OrderManagementApi(RestApiBase): - async def on_startup(self) -> None: - # Initialize dependencies from registry - # Example: self._service = self.registry.get_service(OrderService) - pass - - async def on_shutdown(self) -> None: - pass - - @RestApiBase.get("/{item_id}", response_model=OrderManagementResponse) - async def get_item(self, item_id: str) -> OrderManagementResponse: - """Get item by ID.""" - # TODO: Implement get logic - pass - - @RestApiBase.post("/", response_model=OrderManagementResponse) - async def create_item(self, request: OrderManagementRequest) -> OrderManagementResponse: - """Create new item.""" - # TODO: Implement create logic - pass -``` - -The accompanying models file includes: - -```python -from pydantic import BaseModel - -class OrderManagementRequest(BaseModel): - """Request model for order_management operations.""" - # TODO: Add your request fields - pass - -class OrderManagementResponse(BaseModel): - """Response model for order_management operations.""" - # TODO: Add your response fields - pass -``` - ---- - -## asbs create agent - -Declare an AI agent runtime: two prompt files, a settings section, and an `AgentBuilder` in -`src/main.py`. - -```bash -asbs create agent -``` - -### Arguments - -| Argument | Description | Required | -|----------|--------------------------------|----------| -| `name` | Name of the agent to create | Yes | - -### Naming - -The runtime name is the input in snake case with `_agent` appended, unless it already ends that way: - -- Input: `document_analyzer` -> runtime `document_analyzer_agent` -- Input: `DocumentAnalyzer` -> runtime `document_analyzer_agent` -- Input: `analyzer_agent` -> runtime `analyzer_agent` - -**This command writes no module of its own.** There is no `src/agents/` file and no builder -function: an agent runtime is a declaration in `main.py` plus its prompts, so there is nothing for a -separate module to hold. - -### Files Generated - -1. **System prompt** (`src/prompts/_system.prompt`) -- static context, with example content -2. **Instruction prompt** (`src/prompts/_instruction.prompt`) -- a template with - `{placeholders}` for runtime input, with example content -3. **Settings** (`settings.toml`) -- a `[default.runtimes.]` section and a - `[default.runtimes..models]` section beneath it - -### Auto-Registration - -- The `AgentBuilder` import is added to `src/main.py` if it is not already there -- The runtime declaration is inserted above the `AppBuilder` chain -- `.with_agent(, name="")` is added to the chain - -### Examples - -#### Basic Agent - -```bash -asbs create agent document_analyzer -``` - -Creates: -- `src/prompts/document_analyzer_agent_system.prompt` -- `src/prompts/document_analyzer_agent_instruction.prompt` -- `[default.runtimes.document_analyzer_agent]` in `settings.toml` -- the declaration and the registration in `src/main.py` - -#### What is added to `src/main.py` - -```python -document_analyzer_agent = ( - AgentBuilder(runtime_name="document_analyzer_agent") - .with_model_from_config() - .with_system_prompt("document_analyzer_agent_system") -) - -agent = ( - AppBuilder() - .with_agent(document_analyzer_agent, name="document_analyzer_agent") -) -``` - -The builder is left **unbuilt**, and takes no `Config`. `AppBuilder.build()` calls -`agent.build(config.for_namespace())`, so the model, prompt and metrics are read from -this agent's own configuration view; building it at this line would bind it to whatever -configuration happened to be in scope, which in a group is a neighbour's. - -#### Settings Configuration - -Auto-generated in `settings.toml`: - -```toml -[default.runtimes.document_analyzer_agent] -model_provider = "openai" -model_name = "gpt-5-mini" -model_temperature = 0.7 -model_max_tokens = 2000 - -[default.runtimes.document_analyzer_agent.models] -openai_reasoning_effort = "low" -openai_reasoning_summary = "detailed" -``` - -Override any defaults in your `settings.toml` after creation. In a group, these are read through -this agent's own configuration view, so two agents may run different models under the same key. - ---- - -## asbs create scheduler - -Generate a scheduled task component by creating a subclass of `SchedulerBase`. - -```bash -asbs create scheduler [--cron ] [--output-dir ] -``` - -### Arguments - -| Argument | Description | Required | -|----------|------------------------------------|----------| -| `name` | Name of the scheduler to create | Yes | - -### Options - -| Flag | Description | Default | -|-----------------------|-----------------------------------------|--------------------| -| `--cron ` | Cron expression for the schedule | `0 * * * *` | -| `--output-dir ` | Where the scheduler module is written | `src/schedulers` | - -### `scheduler_mode` is required - -A registered scheduler with no `scheduler_mode` in `settings.toml` fails at `build()`. The key has -no default because neither value is safe to inherit: `in_process` runs a timer in every replica and -claims each tick in the agent's own cache, so it needs `.with_cache()`; `event` starts no timer at -all and waits for a tick published by an external `CronJob`, so it needs `event_bus` -- and nothing -in this project generates that `CronJob`. `asbs validate` reports both. - -### Naming - -Scheduler names are converted to `Scheduler` format: - -- Input: `cleanup` → Class: `CleanupScheduler` → File: `cleanup_scheduler.py` -- Input: `Cleanup` → Class: `CleanupScheduler` → File: `cleanup_scheduler.py` -- Input: `cleanup-task` → Class: `CleanupTaskScheduler` → File: `cleanup_task_scheduler.py` - -### Auto-Registration - -The created scheduler is automatically: -- Imported in `src/main.py` -- Registered with `.with_scheduler(CleanupScheduler)` - -### Cron Expressions - -Use standard 5-field cron syntax: - -``` -┌───────────── minute (0-59) -│ ┌───────────── hour (0-23) -│ │ ┌───────────── day of month (1-31) -│ │ │ ┌───────────── month (1-12) -│ │ │ │ ┌───────────── day of week (0-7, 0=Sunday) -│ │ │ │ │ -│ │ │ │ │ -* * * * * -``` - -Common patterns: -- `*/5 * * * *` - Every 5 minutes -- `0 * * * *` - Every hour at minute 0 -- `0 2 * * *` - Daily at 2:00 AM -- `0 8 * * 1-5` - Weekdays at 8:00 AM -- `0 0 1 * *` - Monthly at midnight on the 1st - -### Examples - -#### Hourly Scheduler - -```bash -asbs create scheduler metrics_collector -``` - -Creates `src/schedulers/metrics_collector_scheduler.py` with default hourly schedule. - -#### Custom Cron Schedule - -```bash -asbs create scheduler daily_cleanup --cron "0 2 * * *" -``` - -Creates a scheduler that runs daily at 2:00 AM. - -#### Scheduler Generated Code - -The generated scheduler includes: - -```python -"""Scheduler for cleanup operations.""" - -import logging -from blueprint.agents.io.api.scheduling.scheduler import SchedulerBase - -logger = logging.getLogger(__name__) - - -class CleanupScheduler(SchedulerBase): - """Scheduler for cleanup operations.""" - - def __init__(self) -> None: - """Initialize the scheduler.""" - super().__init__(crontab="0 2 * * *") - - async def on_startup(self) -> None: - """Initialize the scheduler.""" - # TODO: Get services from registry - # Example: self._service = self.registry.get_service(CleanupService) - - async def on_shutdown(self) -> None: - """Cleanup when shutting down.""" - - async def tick(self) -> None: - """Execute scheduled task.""" - try: - # TODO: Implement your scheduled task here - # Example: await self._service.cleanup() - except Exception as e: - logger.exception("Error during %s scheduler tick: %s", __name__, e) - raise -``` - ---- - -## asbs validate - -Validate the project structure and configuration. Reads files only -- it never imports the -project -- and reports what it finds in three grades: **issues** (the project will not start, exit -status 1), **warnings** (it will start, and something is missing) and **notices** (a decision the -framework must not make for you). - -```bash -asbs validate [] -``` - -### Checks Performed - -Project shape: - -- Required directories (`src/`, `tests/`) and files (`settings.toml`, `pyproject.toml`) exist -- `src/main.py` exists and uses `AppBuilder` -- `.secrets.toml.example` and `.secrets.toml` are present -- A `Dockerfile` is present - -Group readiness -- what this project must state before it can be hosted beside another agent: - -- `agents.toml` exists; without it the project cannot be run by - `python -m blueprint.agents.entrypoint`, and the three changes that make it hostable are named -- Every `[agents.]` entry has a `module` written as `"package.module:attribute"` -- Every agent name is a legal namespace (`[a-z][a-z0-9_]*` -- no dashes), because it becomes the - queue group, the durable, the cache partition and the telemetry `service.name` -- Every declared module exists in the project and assigns the attribute the map names -- Once there is more than one agent: each ships its own `settings.toml` beside its declaration, - and declares no process-scope key (`app_port`, `event_bus`, `envvar_prefix`, ...) there, since - one process binds one port and speaks one bus - -Schedulers: - -- `scheduler_mode` is set when `src/schedulers/` holds anything, and is one of `in_process` or - `event` -- it has no default, and `build()` fails without it -- In `event` mode, `event_bus` is set; and a notice that **nothing in this project generates the - `CronJob`** that must publish the tick. A scheduler waiting for a tick nobody publishes reports - itself healthy and never runs, which nothing else reports -- In `in_process` mode, a notice when `src/main.py` declares no cache: each tick is claimed in the - agent's own cache so that one replica runs it, and with no cache every replica runs every tick - -Delivery: - -- A notice when handlers exist and `idempotency_enabled` is not declared either way. Delivery is - at-least-once, so the decision is the author's to make and the framework will not make it - -### Example - -```bash -asbs validate -``` - -``` -Validating Blueprint Agents project: /work/my-ai-service - -[ok] Found agents.toml (1 agent(s): my_ai_service) - -============================================================ - -Notices (1): - - 'scheduler_mode' is 'event', so no timer runs in this process: each tick - arrives as an event on '.scheduler.', published by an external - CronJob. ... -``` - ---- - -## asbs dev - -Run this project's agents in development mode with hot reload, **under the namespaces they are -deployed under**. A development server at the root namespace would serve `/api/orders/{id}` where -production serves `/api/order/orders/{id}`, and would consume under a different queue group, so -every local URL and every local integration test would differ from the deployed one. - -With an `agents.toml`, it serves the group through -`uvicorn blueprint.agents.entrypoint:create_group_app --factory --reload`. Without one -- a project -written before the agent map, which builds its own application -- it serves `src.main:app` exactly -as it always did. - -```bash -asbs dev [--agents ] [--host ] [--port ] -``` - -### Options - -| Flag | Description | Default | -|--------------------|-------------------------------------------------------------|------------------| -| `--agents ` | Comma-separated agents to host | every agent in `agents.toml` | -| `--host ` | Host to bind the server to | `127.0.0.1` | -| `--port ` | Port to bind the server to | `8000` | - -`BLUEPRINT_GROUP` or `BLUEPRINT_AGENTS` already set in the environment always wins: a developer -reproducing a particular deployment is not overridden by a default read out of the agent map. - -### Example - -```bash -asbs dev --port 9000 -``` - -``` -INFO: Blueprint Agents dev server starting... -INFO: Uvicorn running on http://0.0.0.0:9000 (Press CTRL+C to quit) -INFO: Started reloader process -``` - -The development server watches for file changes in the `src/` directory and automatically restarts when modifications are detected. - ---- - -## Auto-Registration Troubleshooting - -When `asbs create` commands run, they attempt to automatically register components in `src/main.py`. If this fails, the CLI provides clear guidance on manual registration. - -### Common Issues - -#### `src/main.py` Not Found - -**Error:** -``` -⚠ Could not auto-register (src/main.py not found or invalid) -``` - -**Solution:** -Ensure your project has the correct structure: -``` -my_service/ -├── src/ -│ └── main.py -└── pyproject.toml -``` - -Run `asbs setup ` to scaffold a complete project if needed. - -#### Invalid main.py Structure - -**Error:** -``` -⚠ Could not auto-register (src/main.py not found or invalid) -``` - -**Solution:** -Verify `src/main.py` contains: -- Import statements at the top -- An assignment whose right-hand side opens a parenthesis, with `AppBuilder(` on the next line -- A closing `)` in the first column -- or, in a project that still builds its own application, a - `.build()` call - -That is what the CLI looks for when it rewrites the chain: it is a line-oriented editor for a file -the generator wrote in a known shape, not a parser, and it reports a file it cannot read rather -than guessing at one. - -Example valid structure: -```python -from blueprint.agents.app_builder import AppBuilder - -agent = ( - AppBuilder() - # Components added here -) -``` - -### Manual Registration - -If auto-registration fails, the CLI displays instructions. Follow this pattern for each component type: - -Every registration is the **class**, not an instance of it, and the declaration ends without a -`build()` call -- the host builds it. - -#### Handler -```python -# In src/main.py - -from .handlers import OrderPlacedHandler - -agent = ( - AppBuilder() - .with_handler(OrderPlacedHandler) -) -``` - -#### Service -```python -# In src/main.py - -from .services import InvoiceProcessorService - -agent = ( - AppBuilder() - .with_service(InvoiceProcessorService) -) -``` - -#### API -```python -# In src/main.py - -from .api import OrderManagementApi - -agent = ( - AppBuilder() - .with_rest_api(OrderManagementApi) -) -``` - -#### Agent -```python -# In src/main.py - -from blueprint.agents.agent import AgentBuilder - -document_analyzer_agent = ( - AgentBuilder(runtime_name="document_analyzer_agent") - .with_model_from_config() - .with_system_prompt("document_analyzer_agent_system") -) - -agent = ( - AppBuilder() - .with_agent(document_analyzer_agent, name="document_analyzer_agent") -) -``` - -The `AgentBuilder` is left **unbuilt**. `AppBuilder.build()` calls -`agent.build(config.for_namespace())`, so the model, prompt and metrics come from this -agent's own configuration view; building it here would bind it to whatever configuration happened -to be in scope at that line, which in a group is a neighbour's. The `name=` is the registry key -services resolve the runtime by. - -#### Scheduler -```python -# In src/main.py - -from .schedulers import CleanupScheduler - -agent = ( - AppBuilder() - .with_scheduler(CleanupScheduler) -) -``` - -### Registration Order Matters - -Register dependencies **before** dependents in the AppBuilder chain: - -1. Services first (contain business logic) -2. Handlers and APIs next (use services) -3. Agents last (may use multiple services) -4. Schedulers last (use services) - -```python -agent = ( - AppBuilder() - # 1. Services - .with_service(OrderService) - .with_service(PaymentService) - # 2. Handlers and APIs - .with_handler(OrderPlacedHandler) - .with_rest_api(OrderApi) - # 3. Agents - .with_agent(analyzer_agent, name="analyzer_agent") - # 4. Schedulers - .with_scheduler(CleanupScheduler) -) -``` - ---- - -## asbs claude - -Copy the framework's Claude Code resources into a project, so that Claude Code picks up the -Blueprint patterns when working in it. - -```bash -asbs claude [] [--overwrite] [--verbose] -``` - -### Arguments - -| Argument | Description | Default | -|-----------------|--------------------------------------|---------| -| `project-dir` | Project root to write into | `.` | - -### Options - -| Flag | Description | Default | -|-------------------|-----------------------------------------------------|---------| -| `--overwrite` | Replace files that already exist | off | -| `--verbose`, `-v` | Debug-level logging | off | - -There are no `create` / `update` subcommands: the command is idempotent, and `--overwrite` is the -difference between leaving existing files alone and replacing them. - -### What it copies - -| From the framework | To the project | Contents | -|---|---|---| -| `claude_docs/CLAUDE.md` | `src/CLAUDE.md` | Framework reference: base classes, the registry and lifecycle rules, component patterns, configuration | -| `claude_docs/agents/` | `.claude/agents/` | Architecture agents | -| `claude_docs/skills/` | `.claude/skills/` | CLI skills | - -Nothing here is generated from *your* project: the files are the framework's own documentation, -copied. They are not updated when you run `asbs create`. - -### Example - -```bash -asbs claude -asbs claude --overwrite # after upgrading the framework -``` - -### Project-Specific CLAUDE.md - -You can optionally create a `CLAUDE.md` file in your project root for project-specific context: - -```markdown -# My Service - Blueprint Agents Project - -## Overview -Brief description of this service's purpose and architecture. - -## Key Components -- **OrderService**: Validates and processes orders -- **OrderHandler**: Responds to order.placed events -- **OrderApi**: REST endpoints for order management - -## Deployment -Information specific to how this service is deployed. - -## Team Guidelines -Any team-specific development guidelines or patterns. -``` - -This user-created file is not updated by `asbs` commands. diff --git a/pyproject.toml b/pyproject.toml index 1205b110..daf8d43d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,18 +6,19 @@ build-backend = "setuptools.build_meta" [project] name = "avs-blueprint-agents" -version = "0.9.0" +version = "0.9.0a3" description = "Microservice blueprint for creating agents" authors = [ { name = "Blueprint Team", email = "patrick.maue@bechtle.com" }, { name = "Blueprint Team", email = "jan.weber@bechtle.com" } ] readme = "README.md" +license = "MIT" +license-files = ["LICENSE"] requires-python = ">=3.13" classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", - "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.13", "Typing :: Typed", @@ -41,9 +42,7 @@ dependencies = [ "diskcache-rs>=0.4.4", "nats-py>=2.13.1", "croniter>=6.0.0", - "pyyaml>=6.0", - "pytest", - "pytest-asyncio" + "pyyaml>=6.0" ] [project.optional-dependencies] @@ -109,7 +108,7 @@ packages = [ [tool.setuptools.package-data] "blueprint.agents" = ["py.typed"] -"blueprint.agent_generator" = ["base_files/**/*", "assistant_integrations/**/*", "claude_docs/**/*"] +"blueprint.agent_generator" = ["base_files/**/*", "assistant_integrations/**/*", "claude_docs/**/*", "docs/**/*"] [tool.black] line-length = 140 diff --git a/src/blueprint/agent_generator/claude_docs/CLAUDE.md b/src/blueprint/agent_generator/claude_docs/CLAUDE.md index b4a5e1b9..8d1c7534 100644 --- a/src/blueprint/agent_generator/claude_docs/CLAUDE.md +++ b/src/blueprint/agent_generator/claude_docs/CLAUDE.md @@ -243,6 +243,22 @@ model_temperature = 0.5 **.secrets.toml** (never commit): `model_api_key = "sk-..."` +## Documentation + +The full framework documentation ships inside the installed package -- no network needed. Locate a +page with `asbs docs`, then read it: + +```bash +asbs docs # list every page +asbs docs guides/multi-agent-setup # print the path to one page +asbs docs reference/configuration-keys --cat # print its contents +``` + +Prefer the matching skill (`blueprint-cli`, `blueprint-config`, `blueprint-events`, +`blueprint-multi-agent`, `blueprint-testing`, `blueprint-deployment`, +`blueprint-troubleshooting`); each one carries the rules that matter and points at the page for the +detail. **Never guess a configuration key or a CLI flag** -- the reference is on disk. + ## CLI (`asbs`) ```bash @@ -254,6 +270,7 @@ asbs create agent # Add AgentRuntime asbs create scheduler [--cron CRON] # Add Scheduler asbs validate # Validate project structure asbs dev [--port 8000] # Run dev server +asbs docs [] [--cat] # Locate the framework documentation ``` **IMPORTANT:** Always use `asbs create` when adding components for consistent naming and imports. 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 16b4ceb7..2bb61883 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 @@ -38,6 +38,12 @@ asbs create agent asbs create scheduler --cron "" ``` +The full option list for each component type, with examples, is in the packaged docs: + +```bash +asbs docs guides/cli/create --cat +``` + ## Step 3: Implement After scaffolding, implement the component logic: @@ -90,3 +96,19 @@ If the component needs configuration: - **Register in correct order** in `main.py`: services → agents → handlers/APIs/schedulers - **Type hints on every method signature** - **Pydantic models for all API request/response types** + +## Reference + +Per-component guides ship with the package: + +```bash +asbs docs components/event-handlers --cat +asbs docs components/services --cat +asbs docs components/rest-apis --cat +asbs docs components/agents --cat +asbs docs components/schedulers --cat +``` + +If `asbs create` could not register the component in `src/main.py`, read +`asbs docs guides/cli/auto-registration --cat` -- registration order matters, and services must come +before the handlers, agents and APIs that resolve them. diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-cli/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-cli/SKILL.md new file mode 100644 index 00000000..9d4e14c5 --- /dev/null +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-cli/SKILL.md @@ -0,0 +1,50 @@ +--- +name: blueprint-cli +description: Reference for the `asbs` command-line tool - scaffolding a project, adding components, validating, and running the dev server. Use when running or explaining any `asbs` command, or when a component needs to be created in a Blueprint Agents project. +user-invocable: true +--- + +# Blueprint CLI (`asbs`) + +`asbs` is how components get created in this framework. **Always scaffold with `asbs create` rather +than writing component files by hand** - it applies the naming rules and registers the component in +`src/main.py`, and hand-written files miss both. + +## Commands + +```bash +asbs setup # Scaffold a complete project +asbs create handler [--event-type TYPE] # Add EventHandler +asbs create service # Add Service +asbs create api # Add RestApi +asbs create agent # Add AgentRuntime +asbs create scheduler [--cron CRON] # Add Scheduler +asbs validate # Check structure and configuration +asbs dev [--port 8000] # Dev server with reload +asbs docs [] [--cat] # Locate the framework docs +``` + +## Read the detail before acting + +Each command has its own page. Load only the one you need: + +```bash +asbs docs guides/cli/setup --cat # asbs setup, and what it generates +asbs docs guides/cli/create --cat # all five component types, with examples +asbs docs guides/cli/validate --cat # what validate checks, and the three grades +asbs docs guides/cli/dev --cat # dev server options +asbs docs guides/cli/naming --cat # how a typed name becomes a class and a file +asbs docs guides/cli/auto-registration --cat # when create could not edit main.py +``` + +For the end-to-end workflow of a first project, read `asbs docs getting-started --cat`. + +## Rules that bite + +- **Only run `asbs setup` when no project exists.** Never scaffold over an existing project. +- **`asbs create` edits `src/main.py`.** If it reports that it could not, fix the registration by + hand using `guides/cli/auto-registration`, and mind that **registration order matters**: services + before the handlers, agents and APIs that resolve them. +- **Names are normalised, not rejected.** `order-placed`, `OrderPlaced` and `order_placed` all + produce the same handler. Agent *namespaces* are the exception - see `blueprint-multi-agent`. +- After any `create`, run `asbs validate` before calling the work done. diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md new file mode 100644 index 00000000..c972d885 --- /dev/null +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md @@ -0,0 +1,57 @@ +--- +name: blueprint-config +description: Configuring a Blueprint Agents service - settings.toml, .secrets.toml, per-runtime overrides, environment interpolation, and the complete key list. Use when adding or debugging any configuration key, or when startup fails on a configuration error. +user-invocable: true +--- + +# Blueprint Configuration + +Config is Dynaconf-backed and layered: `settings.toml`, then `.secrets.toml`, then environment. + +**Never guess a key name.** The complete list ships with the package - read it: + +```bash +asbs docs reference/configuration-keys --cat # every key, grouped by subsystem +asbs docs concepts/configuration --cat # the Config class, layering, interpolation +``` + +The reference groups keys under: Application, Event Bus, Deployment Identity (environment only), +Event Deduplication, Scheduling, Event Publishing, AI / Model Runtime, Prompts, Cache, +Observability, Logging. + +## Shape + +```toml +[default] +app_name = "my-service" +event_bus = "dapr" # or "nats" +model_provider = "openai" +model_name = "gpt-4" + +[default.runtimes.my_agent] # per-agent overrides +model_name = "gpt-4-turbo" +model_temperature = 0.5 +``` + +`.secrets.toml` holds `model_api_key` and the like, and is never committed. + +## Keys with no safe default + +These fail at startup rather than guess, so they must be set deliberately: + +- **`scheduler_mode`** - required once any scheduler is registered. `"in_process"` runs an + APScheduler timer in *every* replica and claims each tick through the cache, so it needs + `.with_cache()` or every replica runs every tick. `"event"` starts no timer: the tick arrives as + an event on `.scheduler.`, so it needs `event_bus` set. +- **`idempotency_enabled` and `idempotency_ttl`** - both, or neither. Delivery is at-least-once; + deduplication is off by default because only you know whether replaying your side effects is + acceptable. The TTL must outlast the broker redelivery window. +- **`event_publishing_enabled`** - consuming and publishing are separate concerns. A handler implies + a transport client; a scheduler does not. + +## Reading config at runtime + +Resolve configuration in `on_startup()`, never in `__init__` - `self.config` is not linked until +after construction. See *Accessing Configuration at Runtime* in `concepts/configuration`. + +When startup fails on a configuration error, `blueprint-troubleshooting` carries the symptom table. diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md new file mode 100644 index 00000000..97500e9e --- /dev/null +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md @@ -0,0 +1,48 @@ +--- +name: blueprint-deployment +description: Deploying a Blueprint Agents service - Docker images, Kubernetes and Helm, health probes, replicas, schedulers under scale, and the writable cache directory. Use when building an image, writing manifests, scaling replicas, or diagnosing a probe or CronJob failure. +user-invocable: true +--- + +# Deployment + +```bash +asbs docs guides/deployment --cat # images, Helm, probes, replicas, schedulers, sizing +``` + +Sections, in order: The image, Choosing what a process runs, Kubernetes with Helm, Running more than +one replica, Schedulers, Health probes, Writable cache directory, Configuration, Sizing a group, +Stateless design. + +## What a process runs is a deployment decision + +The image is the same whether it hosts one agent or ten. What differs is the command and the agent +map - see `blueprint-multi-agent`. Changing the mix is an edit to a Deployment, not a rebuild. + +| Shape | Command | +|---|---| +| Standalone | `uvicorn src.main:app` (or `src.main:create_app --factory` once migrated) | +| Grouped, including a group of one | `python -m blueprint.agents.entrypoint` | + +## The two that break under replicas + +- **Schedulers.** `scheduler_mode = "in_process"` runs a timer in *every* replica and relies on the + cache to claim each tick, so without `.with_cache()` every replica runs every tick. + `scheduler_mode = "event"` starts no timer at all - an external `CronJob` publishes the tick and + the queue group already guarantees one consumer. Read *Schedulers* and *Running more than one + replica* together before scaling past one. +- **The cache directory must be writable.** The disk backend needs a writable volume; a read-only + root filesystem fails at startup, not at first use. See *Writable cache directory*. + +## Probes + +Health endpoints are covered under *Health probes*, and only one readiness probe is answered per +process - in a group, a copy of the probe config scoped under a single agent is read by nothing. +`asbs validate` reports that case. + +## Before shipping + +- Secrets come from the environment or a mounted `.secrets.toml` - never baked into the image. +- Keep components stateless; *Stateless design* explains what that rules out. +- Size a group deliberately: *Sizing a group* runs the dial from full process isolation to twenty + agents sharing one runtime. diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md new file mode 100644 index 00000000..7bc86b10 --- /dev/null +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md @@ -0,0 +1,73 @@ +--- +name: blueprint-events +description: CloudEvents, the event handler chain, priorities, at-least-once delivery and idempotency, and the Dapr and NATS transports. Use when writing or debugging an EventHandler, choosing an event bus, or when events are duplicated, lost, or not reaching a handler. +user-invocable: true +--- + +# Event Processing + +Handlers form a **chain of responsibility** ordered by priority (lower runs first). Each handler +decides whether the event is its business, and the chain stops at the first handler that returns a +result. + +```bash +asbs docs concepts/event-processing --cat # CloudEvent model, chain, transports +asbs docs components/event-handlers --cat # writing a handler +``` + +## The two rules that decide behaviour + +**Return value is control flow:** + +- `return None` - not mine, or nothing to publish. The event passes to the next handler. +- `return HandlerResult(...)` - publish that event and **stop the chain**. + +**Delivery is at-least-once.** The same event can reach `handle_event` more than once: a lost ack, a +pod restart, a rolling deploy. Either make the method safe to repeat, or set **both** +`idempotency_enabled = true` and `idempotency_ttl = `; the framework then skips an event +whose id and source it has already dispatched, within that window. It is off by default on purpose - +only you know whether replaying your side effects is acceptable. + +## Shape + +```python +class OrderHandler(EventHandlerBase): + def __init__(self) -> None: + super().__init__(priority=10) # lower runs first + + async def on_startup(self) -> None: + self._service = self.registry.get_service(OrderService) + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return event.type == "order.placed" + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None: + order = self.extract_payload(event, OrderModel) + result = await self._service.process(order) + return HandlerResult(event_type="order.processed", data=result) +``` + +- **`self.extract_payload(event, Model)`** validates `event.data` and returns a typed instance, + raising `InvalidEventError` that the framework handles. Do not hand-parse `event.data`. +- Handlers are a **thin delegation layer**. Business logic belongs in a service. +- Dependencies resolve in `on_startup()`, never in `__init__`. + +## Publishing from elsewhere + +From a REST endpoint, build the event rather than constructing it by hand: + +```python +from blueprint.agents.models import create_cloud_event + +cloud_event = create_cloud_event("order.created", payload, source="/api/orders") +result = await event_processing.process_event(cloud_event) +``` + +It generates the id, calls `model_dump()` on Pydantic models and sets the defaults. + +## Transport + +`event_bus` selects `"dapr"` or `"nats"`. Their sections in `concepts/event-processing` cover +subscriptions, queue groups, JetStream durables and *Broker Startup Resilience*. In a group, the +agent namespace is part of every durable name - see `blueprint-multi-agent` before renaming +anything. diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md new file mode 100644 index 00000000..fe40f54c --- /dev/null +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md @@ -0,0 +1,52 @@ +--- +name: blueprint-multi-agent +description: Running several Blueprint agents in one process, and migrating an existing single-agent project into a group. Use for agents.toml, agent namespaces, group deployment, the entrypoint module, or when an existing agent must join a group. +user-invocable: true +--- + +# Multi-Agent Groups + +An agent's code says nothing about which other agents it runs beside. A project *declares* what it +is made of; a *deployment* decides which of those declarations a process hosts. Moving between the +two is an edit to a Deployment, not a rebuild. + +## Which case is this? + +| Case | Read | +|---|---| +| New project, built as a group from the start | `asbs docs guides/multi-agent-setup --cat` | +| Existing single-agent project joining a group | `asbs docs guides/multi-agent-migration --cat` | +| Leave it standalone | Nothing changes. There is no deprecation - this is a legitimate answer | + +## The decision to get right first + +**The agent's name in `agents.toml` is its identity everywhere outside that file.** It becomes the +NATS queue group, part of every JetStream durable (`--durable`), the cache directory +and Redis key prefix, the OpenTelemetry `service.name`, the route prefix `/api/`, and the +prefix on every registry key its components take. + +Renaming it after the first grouped deploy is a **consumer migration** - new durables, messages +still pending on the old ones - not a rename. Choose it once, before deploying. + +The namespace alphabet is **`[a-z][a-z0-9_]*`**: lower case, leading letter, underscores allowed, +**no dashes**. A name outside it is refused, never repaired. The dash is excluded because it +separates the parts of a durable name, so `orders-eu` on topic `created` and `orders` on topic +`eu-created` would otherwise produce the same durable and two agents would eat each other's events. + +## Three ways to run one declaration + +| Shape | Command | +|---|---| +| Standalone, unmigrated | `uvicorn src.main:app` | +| Standalone, migrated (with `create_app`) | `uvicorn src.main:create_app --factory` | +| Grouped, including a group of one | `python -m blueprint.agents.entrypoint` | + +## Before promising the move is free + +An agent **left standalone** is unaffected by any of this. An agent **moved into a group** changes +its broker-side identity once, and its cache starts cold. Both are set out under *What changes, and +what does not* in `guides/multi-agent-setup` - read that section before telling anyone the migration +is invisible, because for a migrated agent it is not. + +Run `asbs validate` after migrating. It reads files only, never imports the project, and checks the +namespace alphabet, the agent map and the module attribute. diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-testing/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-testing/SKILL.md new file mode 100644 index 00000000..806b4d70 --- /dev/null +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-testing/SKILL.md @@ -0,0 +1,49 @@ +--- +name: blueprint-testing +description: Testing a Blueprint Agents service - mock registries, unit tests for handlers, services, APIs and agents, integration tests, and the pytest-asyncio setup. Use when writing or fixing tests for any Blueprint component. +user-invocable: true +--- + +# Testing Blueprint Components + +```bash +asbs docs guides/testing --cat # mock registry, per-component patterns, integration tests +``` + +The guide covers, in order: Test Setup, Creating a Mock Registry, Unit Testing Components, +Integration Testing, Running Tests, Tips and Best Practices. **Read *Creating a Mock Registry* +before writing the first test** - components resolve their dependencies through `self.registry`, so +a test that does not provide one tests nothing. + +## Conventions + +| Thing | Convention | +|---|---| +| File | `test_.py` | +| Class | `Test` | +| Method | `test__` | +| Shared fixtures | `conftest.py` | +| Async | `asyncio_mode = auto` - no `@pytest.mark.asyncio` needed | + +- `MagicMock(spec=...)` for synchronous dependencies, `AsyncMock()` for async ones. The `spec` is + what makes a renamed method fail the test instead of passing silently. +- **`assert` is for tests only.** It is not permitted in production code in this framework. + +## The lifecycle trap + +Components do not have `self.registry` or `self.config` until after construction, and they resolve +dependencies in `on_startup()`. So a unit test must **call `on_startup()` itself** after attaching +the mock registry - constructing the component is not enough, and a test that skips it will fail on +an attribute that production code sets correctly. + +Schedulers additionally require `await super().on_startup()` inside any overridden `on_startup`; the +base class is what starts the timer and registers the trigger route. + +## Running + +```bash +pytest tests/ # everything +pytest tests/unit -v --tb=short # what CI runs on publish +``` + +Test dependencies live in the `ci` extra: `pip install -e ".[ci]"`. diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-troubleshooting/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-troubleshooting/SKILL.md new file mode 100644 index 00000000..96fbae72 --- /dev/null +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-troubleshooting/SKILL.md @@ -0,0 +1,45 @@ +--- +name: blueprint-troubleshooting +description: Diagnosing a failing Blueprint Agents service - startup errors, configuration errors, event bus connectivity, LLM provider failures, component registration errors, health check failures, cache problems and test failures. Use whenever a Blueprint service fails to start, throws at runtime, or behaves unexpectedly. +user-invocable: true +--- + +# Troubleshooting + +**Read the symptom table before theorising.** Most failures in this framework have a known cause and +a one-line fix: + +```bash +asbs docs guides/troubleshooting --cat +``` + +Sections map to symptoms: Installation Issues, Configuration Errors, Event Bus Connectivity, LLM +Provider Issues, Component Registration Errors, Health Check Failures, Cache Issues, Testing Issues. + +## First, run the validator + +```bash +asbs validate +``` + +It reads files only - it never imports the project - and grades what it finds: **issues** (will not +start, exit 1), **warnings** (will start, something is missing), **notices** (a decision the +framework will not make for you). It catches most misconfiguration before a stack trace does. + +## The usual suspects, in order of likelihood + +| Symptom | Almost always | +|---|---| +| `AttributeError` on `self.registry` or `self.config` | Accessed in `__init__`. Resolve in `on_startup()` | +| Component not found at runtime | Registered after its dependent. Services go before handlers, agents and APIs | +| Scheduler never fires | `scheduler_mode` unset, or an overridden `on_startup` that never calls `await super().on_startup()` | +| Every replica runs every scheduled tick | `scheduler_mode = "in_process"` without `.with_cache()` | +| The same event processed twice | At-least-once delivery. Make it repeatable, or set both `idempotency_enabled` and `idempotency_ttl` | +| Handler never reached | An earlier handler in the priority chain returned a `HandlerResult` and stopped the chain | +| Events vanish after a rename | The agent namespace is part of every durable name - see `blueprint-multi-agent` | +| Cache fails at startup | The disk backend needs a writable volume; a read-only root filesystem fails immediately | + +## When the docs do not cover it + +Narrow it down before changing code: `asbs validate` first, then the relevant section above, then +`blueprint-config` for the exact key spelling. Only then read the framework source. diff --git a/src/blueprint/agent_generator/claude_docs/skills/new-agent-service/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/new-agent-service/SKILL.md index 9d00463e..14644064 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/new-agent-service/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/new-agent-service/SKILL.md @@ -16,6 +16,9 @@ If the user provided a description, extract from it: - **What LLM agents it needs** (names, purposes, expected outputs) - **What REST endpoints it exposes** (if any) - **What scheduled tasks it runs** (if any) +- **Whether it runs alone or in a group** -- one agent per process is the default and the safest + shape. If several agents should share one process, the name you choose becomes a namespace that + is expensive to change later: read the `blueprint-multi-agent` skill before running `asbs setup`. If any of these are unclear, ask the user ONE focused question before proceeding. @@ -54,7 +57,22 @@ Ensure `settings.toml` has: Ensure `.secrets.toml` has placeholder keys for any required API keys. -## Step 6: Verification +## Step 6: Reference + +The framework documentation ships with the package. Load a page only when the step needs it: + +```bash +asbs docs # list every page +asbs docs getting-started --cat # the end-to-end first-project walkthrough +asbs docs guides/cli/setup --cat # what asbs setup generates +asbs docs reference/configuration-keys --cat # exact settings.toml key names +asbs docs guides/multi-agent-setup --cat # if this project is a group +``` + +Related skills: `blueprint-cli`, `blueprint-config`, `blueprint-events`, `blueprint-multi-agent`, +`blueprint-testing`, `blueprint-troubleshooting`. + +## Step 7: Verification - Run `asbs validate` to check project structure - Verify all imports resolve correctly diff --git a/src/blueprint/agent_generator/cli/commands/docs.py b/src/blueprint/agent_generator/cli/commands/docs.py new file mode 100644 index 00000000..35e9ee7d --- /dev/null +++ b/src/blueprint/agent_generator/cli/commands/docs.py @@ -0,0 +1,120 @@ +"""Docs command - locate the framework documentation shipped inside the package. + +The guides ship with the package rather than being fetched from the web, so a developer +or an AI assistant working against the framework can read them offline. They land in +``blueprint/agent_generator/docs/``, which is somewhere under ``site-packages`` and not a +path anybody should have to type. This command resolves it. +""" + +import importlib.resources +import sys +from argparse import Namespace +from pathlib import Path + + +def locate_docs_root() -> Path: + """Return the directory holding the packaged documentation. + + Returns: + Absolute path to the packaged ``docs/`` directory. + + Raises: + FileNotFoundError: If the directory is missing, which means the package was + built without its documentation. + """ + try: + pkg_ref = importlib.resources.files("blueprint.agent_generator") + resolved = Path(str(pkg_ref)) / "docs" + if resolved.is_dir(): + return resolved.resolve() + except (TypeError, ModuleNotFoundError): + pass + + # Fallback for running from a source checkout without an editable install + fallback = Path(__file__).parent.parent.parent / "docs" + if fallback.is_dir(): + return fallback.resolve() + + raise FileNotFoundError( + "Could not locate the packaged documentation.\n" + "Expected it at: blueprint/agent_generator/docs/\n" + "This package was built without its docs; reinstall avs-blueprint-agents." + ) + + +def list_topics(root: Path) -> list[str]: + """List every documentation page, as slugs relative to the docs root. + + Args: + root: The packaged documentation directory. + + Returns: + Sorted slugs such as ``guides/multi-agent-setup`` and ``concepts/caching``. + """ + return sorted(p.relative_to(root).with_suffix("").as_posix() for p in root.rglob("*.md")) + + +def resolve_topic(root: Path, topic: str) -> Path: + """Resolve a topic slug to a page on disk. + + Accepts a full slug (``guides/multi-agent-setup``), the same with a ``.md`` + suffix, or a bare page name (``multi-agent-setup``) when it is unambiguous. + + Args: + root: The packaged documentation directory. + topic: What the caller asked for. + + Returns: + Absolute path to the page. + + Raises: + FileNotFoundError: If nothing matches, or a bare name matches several pages. + """ + slug = topic.removesuffix(".md").strip("/") + + exact = root / f"{slug}.md" + if exact.is_file(): + return exact.resolve() + + matches = [t for t in list_topics(root) if t.rsplit("/", 1)[-1] == slug] + if len(matches) == 1: + return (root / f"{matches[0]}.md").resolve() + if len(matches) > 1: + raise FileNotFoundError(f"'{topic}' is ambiguous; it matches: {', '.join(matches)}") + + raise FileNotFoundError(f"No documentation page named '{topic}'. Run 'asbs docs' to list them.") + + +def run(args: Namespace) -> None: + """Execute the docs command. + + Args: + args: Parsed command-line arguments. + """ + try: + root = locate_docs_root() + except FileNotFoundError as e: + print(f"Error: {e}", file=sys.stderr) + sys.exit(1) + + if getattr(args, "root", False): + print(root) + return + + if not args.topic: + print(f"Documentation root: {root}\n") + print("Pages (read one with 'asbs docs '):\n") + for slug in list_topics(root): + print(f" {slug}") + return + + try: + page = resolve_topic(root, args.topic) + except FileNotFoundError as e: + print(f"Error: {e}", file=sys.stderr) + sys.exit(1) + + if args.cat: + print(page.read_text(encoding="utf-8")) + else: + print(page) diff --git a/src/blueprint/agent_generator/cli/main.py b/src/blueprint/agent_generator/cli/main.py index a3fa369c..d05086de 100644 --- a/src/blueprint/agent_generator/cli/main.py +++ b/src/blueprint/agent_generator/cli/main.py @@ -4,7 +4,7 @@ import sys from typing import TextIO -from .commands import claude, create, dev, setup, validate +from .commands import claude, create, dev, docs, setup, validate def use_utf8(stream: TextIO) -> None: @@ -137,6 +137,28 @@ def main() -> None: help="Enable verbose logging", ) + # Docs command + docs_parser = subparsers.add_parser( + "docs", + help="Locate the framework documentation shipped with the package", + description="Print the path to a documentation page, or list every page", + ) + docs_parser.add_argument( + "topic", + nargs="?", + help="Page to locate, e.g. 'guides/multi-agent-setup' or 'caching' (default: list all)", + ) + docs_parser.add_argument( + "--cat", + action="store_true", + help="Print the page contents instead of its path", + ) + docs_parser.add_argument( + "--root", + action="store_true", + help="Print the documentation root directory and exit", + ) + # Validate command validate_parser = subparsers.add_parser( "validate", @@ -187,6 +209,8 @@ def main() -> None: create.run(args) elif args.command == "claude": claude.run(args) + elif args.command == "docs": + docs.run(args) elif args.command == "validate": validate.run(args) elif args.command == "dev": diff --git a/docs/README.md b/src/blueprint/agent_generator/docs/README.md similarity index 76% rename from docs/README.md rename to src/blueprint/agent_generator/docs/README.md index b004c486..93091e51 100644 --- a/docs/README.md +++ b/src/blueprint/agent_generator/docs/README.md @@ -40,8 +40,9 @@ Blueprint Agents is a Python 3.13+ framework for building AI-powered microservic | Guide | Description | |-------|-------------| -| [CLI Reference](guides/cli-reference.md) | Full reference for the `asbs` command-line tool | -| [Multi-Agent Setup](guides/multi-agent-setup.md) | Running several agents in one process, and migrating an existing one into a group | +| [CLI Reference](guides/cli-reference.md) | Index of the `asbs` command-line tool; one page per command | +| [Multi-Agent Setup](guides/multi-agent-setup.md) | Running several agents in one process | +| [Multi-Agent Migration](guides/multi-agent-migration.md) | Moving an existing single-agent project into a group | | [Testing](guides/testing.md) | Unit testing, integration testing, and test fixtures | | [Deployment](guides/deployment.md) | Docker builds, environment configuration, and production setup | | [Troubleshooting](guides/troubleshooting.md) | Common issues, debugging tips, and FAQ | @@ -55,3 +56,18 @@ Blueprint Agents is a Python 3.13+ framework for building AI-powered microservic | [API Reference](reference/api.md) | Public API surface for all framework modules | | [Configuration Keys](reference/configuration-keys.md) | Complete list of `settings.toml` and `.secrets.toml` keys | | [Models](reference/models.md) | Built-in Pydantic models and base classes | + +--- + +## Where these docs live + +These pages ship inside the installed package, at +``blueprint/agent_generator/docs/``. That is deliberate: a developer or an AI assistant working +against the framework can read them without network access. `asbs claude` installs skills that +reference them by path. + +To find them in an environment that has the package installed: + +```bash +python -c "import blueprint.agent_generator as g, pathlib; print(pathlib.Path(g.__file__).parent / 'docs')" +``` diff --git a/docs/components/agents.md b/src/blueprint/agent_generator/docs/components/agents.md similarity index 100% rename from docs/components/agents.md rename to src/blueprint/agent_generator/docs/components/agents.md diff --git a/docs/components/event-handlers.md b/src/blueprint/agent_generator/docs/components/event-handlers.md similarity index 100% rename from docs/components/event-handlers.md rename to src/blueprint/agent_generator/docs/components/event-handlers.md diff --git a/docs/components/rest-apis.md b/src/blueprint/agent_generator/docs/components/rest-apis.md similarity index 100% rename from docs/components/rest-apis.md rename to src/blueprint/agent_generator/docs/components/rest-apis.md diff --git a/docs/components/schedulers.md b/src/blueprint/agent_generator/docs/components/schedulers.md similarity index 100% rename from docs/components/schedulers.md rename to src/blueprint/agent_generator/docs/components/schedulers.md diff --git a/docs/components/services.md b/src/blueprint/agent_generator/docs/components/services.md similarity index 100% rename from docs/components/services.md rename to src/blueprint/agent_generator/docs/components/services.md diff --git a/docs/concepts/architecture.md b/src/blueprint/agent_generator/docs/concepts/architecture.md similarity index 100% rename from docs/concepts/architecture.md rename to src/blueprint/agent_generator/docs/concepts/architecture.md diff --git a/docs/concepts/caching.md b/src/blueprint/agent_generator/docs/concepts/caching.md similarity index 100% rename from docs/concepts/caching.md rename to src/blueprint/agent_generator/docs/concepts/caching.md diff --git a/docs/concepts/configuration.md b/src/blueprint/agent_generator/docs/concepts/configuration.md similarity index 100% rename from docs/concepts/configuration.md rename to src/blueprint/agent_generator/docs/concepts/configuration.md diff --git a/docs/concepts/event-processing.md b/src/blueprint/agent_generator/docs/concepts/event-processing.md similarity index 100% rename from docs/concepts/event-processing.md rename to src/blueprint/agent_generator/docs/concepts/event-processing.md diff --git a/docs/concepts/observability.md b/src/blueprint/agent_generator/docs/concepts/observability.md similarity index 100% rename from docs/concepts/observability.md rename to src/blueprint/agent_generator/docs/concepts/observability.md diff --git a/docs/getting-started.md b/src/blueprint/agent_generator/docs/getting-started.md similarity index 100% rename from docs/getting-started.md rename to src/blueprint/agent_generator/docs/getting-started.md diff --git a/src/blueprint/agent_generator/docs/guides/cli-reference.md b/src/blueprint/agent_generator/docs/guides/cli-reference.md new file mode 100644 index 00000000..802bf0d4 --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/cli-reference.md @@ -0,0 +1,47 @@ +# CLI Reference + +The `asbs` command-line tool is the primary interface for scaffolding, developing, and managing +Blueprint Agents projects. It is installed automatically with the `avs-blueprint-agents` package. + +```bash +pip install avs-blueprint-agents +``` + +This page is an index. Each command has its own page so you can read only the part you need. + +--- + +## Commands + +| Command | Page | What it does | +|---|---|---| +| `asbs setup` | [setup](cli/setup.md) | Scaffold a complete new project | +| `asbs create` | [create](cli/create.md) | Add a handler, service, api, agent or scheduler | +| `asbs validate` | [validate](cli/validate.md) | Check project structure and configuration | +| `asbs dev` | [dev](cli/dev.md) | Run the development server with reload | +| `asbs claude` | [claude](cli/claude.md) | Copy the Claude Code resources into a project | + +--- + +## Behaviour shared by every command + +| Topic | Page | Why you would read it | +|---|---|---| +| Naming conventions | [naming](cli/naming.md) | How the name you type becomes a class, a file and a runtime name | +| Auto-registration troubleshooting | [auto-registration](cli/auto-registration.md) | `asbs create` could not edit `src/main.py`, and what to do about it | + +--- + +## Quick reference + +```bash +asbs setup # Scaffold complete project +asbs create handler [--event-type TYPE] # Add EventHandler +asbs create service # Add Service +asbs create api # Add RestApi +asbs create agent # Add AgentRuntime +asbs create scheduler [--cron CRON] # Add Scheduler +asbs validate # Validate project structure +asbs dev [--port 8000] # Run dev server +asbs claude [--overwrite] # Install Claude Code resources +``` diff --git a/src/blueprint/agent_generator/docs/guides/cli/auto-registration.md b/src/blueprint/agent_generator/docs/guides/cli/auto-registration.md new file mode 100644 index 00000000..88f1533f --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/cli/auto-registration.md @@ -0,0 +1,155 @@ +# Auto-Registration Troubleshooting + +When `asbs create` commands run, they attempt to automatically register components in `src/main.py`. If this fails, the CLI provides clear guidance on manual registration. + +## Common Issues + +### `src/main.py` Not Found + +**Error:** +``` +⚠ Could not auto-register (src/main.py not found or invalid) +``` + +**Solution:** +Ensure your project has the correct structure: +``` +my_service/ +├── src/ +│ └── main.py +└── pyproject.toml +``` + +Run `asbs setup ` to scaffold a complete project if needed. + +### Invalid main.py Structure + +**Error:** +``` +⚠ Could not auto-register (src/main.py not found or invalid) +``` + +**Solution:** +Verify `src/main.py` contains: +- Import statements at the top +- An assignment whose right-hand side opens a parenthesis, with `AppBuilder(` on the next line +- A closing `)` in the first column -- or, in a project that still builds its own application, a + `.build()` call + +That is what the CLI looks for when it rewrites the chain: it is a line-oriented editor for a file +the generator wrote in a known shape, not a parser, and it reports a file it cannot read rather +than guessing at one. + +Example valid structure: +```python +from blueprint.agents.app_builder import AppBuilder + +agent = ( + AppBuilder() + # Components added here +) +``` + +## Manual Registration + +If auto-registration fails, the CLI displays instructions. Follow this pattern for each component type: + +Every registration is the **class**, not an instance of it, and the declaration ends without a +`build()` call -- the host builds it. + +### Handler +```python +# In src/main.py + +from .handlers import OrderPlacedHandler + +agent = ( + AppBuilder() + .with_handler(OrderPlacedHandler) +) +``` + +### Service +```python +# In src/main.py + +from .services import InvoiceProcessorService + +agent = ( + AppBuilder() + .with_service(InvoiceProcessorService) +) +``` + +### API +```python +# In src/main.py + +from .api import OrderManagementApi + +agent = ( + AppBuilder() + .with_rest_api(OrderManagementApi) +) +``` + +### Agent +```python +# In src/main.py + +from blueprint.agents.agent import AgentBuilder + +document_analyzer_agent = ( + AgentBuilder(runtime_name="document_analyzer_agent") + .with_model_from_config() + .with_system_prompt("document_analyzer_agent_system") +) + +agent = ( + AppBuilder() + .with_agent(document_analyzer_agent, name="document_analyzer_agent") +) +``` + +The `AgentBuilder` is left **unbuilt**. `AppBuilder.build()` calls +`agent.build(config.for_namespace())`, so the model, prompt and metrics come from this +agent's own configuration view; building it here would bind it to whatever configuration happened +to be in scope at that line, which in a group is a neighbour's. The `name=` is the registry key +services resolve the runtime by. + +### Scheduler +```python +# In src/main.py + +from .schedulers import CleanupScheduler + +agent = ( + AppBuilder() + .with_scheduler(CleanupScheduler) +) +``` + +## Registration Order Matters + +Register dependencies **before** dependents in the AppBuilder chain: + +1. Services first (contain business logic) +2. Handlers and APIs next (use services) +3. Agents last (may use multiple services) +4. Schedulers last (use services) + +```python +agent = ( + AppBuilder() + # 1. Services + .with_service(OrderService) + .with_service(PaymentService) + # 2. Handlers and APIs + .with_handler(OrderPlacedHandler) + .with_rest_api(OrderApi) + # 3. Agents + .with_agent(analyzer_agent, name="analyzer_agent") + # 4. Schedulers + .with_scheduler(CleanupScheduler) +) +``` diff --git a/src/blueprint/agent_generator/docs/guides/cli/claude.md b/src/blueprint/agent_generator/docs/guides/cli/claude.md new file mode 100644 index 00000000..440dc12a --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/cli/claude.md @@ -0,0 +1,66 @@ +# asbs claude + +Copy the framework's Claude Code resources into a project, so that Claude Code picks up the +Blueprint patterns when working in it. + +```bash +asbs claude [] [--overwrite] [--verbose] +``` + +## Arguments + +| Argument | Description | Default | +|-----------------|--------------------------------------|---------| +| `project-dir` | Project root to write into | `.` | + +## Options + +| Flag | Description | Default | +|-------------------|-----------------------------------------------------|---------| +| `--overwrite` | Replace files that already exist | off | +| `--verbose`, `-v` | Debug-level logging | off | + +There are no `create` / `update` subcommands: the command is idempotent, and `--overwrite` is the +difference between leaving existing files alone and replacing them. + +## What it copies + +| From the framework | To the project | Contents | +|---|---|---| +| `claude_docs/CLAUDE.md` | `src/CLAUDE.md` | Framework reference: base classes, the registry and lifecycle rules, component patterns, configuration | +| `claude_docs/agents/` | `.claude/agents/` | Architecture agents | +| `claude_docs/skills/` | `.claude/skills/` | CLI skills | + +Nothing here is generated from *your* project: the files are the framework's own documentation, +copied. They are not updated when you run `asbs create`. + +## Example + +```bash +asbs claude +asbs claude --overwrite # after upgrading the framework +``` + +## Project-Specific CLAUDE.md + +You can optionally create a `CLAUDE.md` file in your project root for project-specific context: + +```markdown +# My Service - Blueprint Agents Project + +## Overview +Brief description of this service's purpose and architecture. + +## Key Components +- **OrderService**: Validates and processes orders +- **OrderHandler**: Responds to order.placed events +- **OrderApi**: REST endpoints for order management + +## Deployment +Information specific to how this service is deployed. + +## Team Guidelines +Any team-specific development guidelines or patterns. +``` + +This user-created file is not updated by `asbs` commands. diff --git a/src/blueprint/agent_generator/docs/guides/cli/create.md b/src/blueprint/agent_generator/docs/guides/cli/create.md new file mode 100644 index 00000000..285c2f26 --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/cli/create.md @@ -0,0 +1,496 @@ +# asbs create + +## asbs create handler + +Generate a new event handler component by creating a subclass of `EventHandlerBase`. + +```bash +asbs create handler [--event-type ] [--priority ] [--output-dir ] +``` + +### Arguments + +| Argument | Description | Required | +|----------|---------------------------------|----------| +| `name` | Name of the handler to create | Yes | + +### Options + +| Flag | Description | Default | +|-------------------------|----------------------------------------------------|------------------| +| `--event-type ` | The event type this handler will respond to | (prompt) | +| `--priority ` | Handler priority (lower numbers execute first) | `10` | +| `--output-dir ` | Where the handler module is written | `src/handlers` | + +Ties at equal priority are resolved by registration order, which is the order the `with_*` calls +appear in `main.py`. + +### Naming + +Handler names are converted to `Handler` format: + +- Input: `order_placed` → Class: `OrderPlacedHandler` → File: `order_placed_handler.py` +- Input: `OrderPlaced` → Class: `OrderPlacedHandler` → File: `order_placed_handler.py` +- Input: `order-placed` → Class: `OrderPlacedHandler` → File: `order_placed_handler.py` + +### Auto-Registration + +The created handler is automatically: +- Imported in `src/main.py` +- Registered with `.with_handler(OrderPlacedHandler)` + +If auto-registration fails, manual registration instructions are provided. + +### Examples + +#### Basic Handler + +```bash +asbs create handler order_placed --event-type "order.placed" +``` + +Creates `src/handlers/order_placed_handler.py` with an `OrderPlacedHandler` class. + +#### Handler with Priority + +```bash +asbs create handler high_priority_event --event-type "system.alert" --priority 5 +``` + +Handlers with lower priority numbers execute first in the chain. + +#### Handler Generated Code + +The generated handler includes: + +```python +from blueprint.agents.handler import EventHandlerBase + +class OrderPlacedHandler(EventHandlerBase): + def __init__(self) -> None: + super().__init__(priority=10) + + async def on_startup(self) -> None: + # Initialize resources from registry + pass + + async def on_shutdown(self) -> None: + # Clean up resources + pass + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return event.type == "order.placed" + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None: + # Return None to pass to next handler + # Return HandlerResult(...) to publish and stop chain + return None +``` + +--- + +## asbs create service + +Generate a new service component by creating a subclass of `ServiceBase`. + +```bash +asbs create service [--output-dir ] +``` + +### Arguments + +| Argument | Description | Required | +|----------|---------------------------------|----------| +| `name` | Name of the service to create | Yes | + +### Options + +| Flag | Description | Default | +|-----------------------|-------------------------------------|------------------| +| `--output-dir ` | Where the service module is written | `src/services` | + +### Naming + +Service names are converted to `Service` format: + +- Input: `invoice_processor` → Class: `InvoiceProcessorService` → File: `invoice_processor_service.py` +- Input: `InvoiceProcessor` → Class: `InvoiceProcessorService` → File: `invoice_processor_service.py` +- Input: `invoice-processor` → Class: `InvoiceProcessorService` → File: `invoice_processor_service.py` + +### Auto-Registration + +The created service is automatically: +- Imported in `src/main.py` +- Registered with `.with_service(InvoiceProcessorService)` + +### Examples + +#### Basic Service + +```bash +asbs create service invoice_processor +``` + +Creates `src/services/invoice_processor_service.py` with an `InvoiceProcessorService` class. + +#### Service Generated Code + +The generated service includes: + +```python +from blueprint.agents.services import ServiceBase + +class InvoiceProcessorService(ServiceBase): + async def on_startup(self) -> None: + # Initialize resources, fetch dependencies from registry + # Example: self._cache = self.registry.cache_service + # Example: self._agent = self.registry.get_agent("analyzer") + pass + + async def on_shutdown(self) -> None: + # Clean up resources + pass + + async def process(self, data: dict) -> dict: + """Process invoice data. + + Args: + data: Invoice information + + Returns: + Processing result + """ + # TODO: Implement business logic + pass +``` + +--- + +## asbs create api + +Generate a new REST API component by creating a subclass of `RestApiBase`, plus a models file with Request/Response classes. + +```bash +asbs create api [--output-dir ] +``` + +### Arguments + +| Argument | Description | Required | +|----------|------------------------------|----------| +| `name` | Name of the API to create | Yes | + +### Options + +| Flag | Description | Default | +|-----------------------|---------------------------------|-------------| +| `--output-dir ` | Where the API module is written | `src/api` | + +### Naming + +API names are converted to `Api`, with a models package named after the component: + +- Input: `order_management` + - Class: `OrderManagementApi` + - API file: `src/api/order_management_api.py` + - Models package: `src/models/order_management/` + +### Files Generated + +1. **API module** (`src/api/_api.py`) + - `RestApiBase` subclass with a `GET /{item_id}` and a `POST /` placeholder, both raising + `501 Not Implemented` until you write them + - Dependency injection via `self.registry.get_service(...)` in `on_startup` + +2. **A models package** (`src/models//`), three files: + - `dto.py` -- `Request` and `Response`, the API's wire contract + - `domain_models.py` -- `Model`, what the service works with + - `mapper.py` -- `Mapper`, converting between the two + +### Auto-Registration + +The created API is automatically: +- Imported in `src/main.py` (both models and API) +- Registered with `.with_rest_api(OrderManagementApi)` + +### Examples + +#### Basic API + +```bash +asbs create api order_management +``` + +Creates: +- `src/api/order_management_api.py` with the `OrderManagementApi` class +- `src/models/order_management/dto.py` with `OrderManagementRequest` and `OrderManagementResponse` +- `src/models/order_management/domain_models.py` with `OrderManagementModel` +- `src/models/order_management/mapper.py` with `OrderManagementMapper` + +#### API Generated Code + +The generated API includes: + +```python +"""REST API for order_management operations.""" + +from fastapi import HTTPException, status +from blueprint.agents.io.api.rest_api_base import RestApiBase +from src.models.order_management.dto import OrderManagementRequest, OrderManagementResponse + +class OrderManagementApi(RestApiBase): + async def on_startup(self) -> None: + # Initialize dependencies from registry + # Example: self._service = self.registry.get_service(OrderService) + pass + + async def on_shutdown(self) -> None: + pass + + @RestApiBase.get("/{item_id}", response_model=OrderManagementResponse) + async def get_item(self, item_id: str) -> OrderManagementResponse: + """Get item by ID.""" + # TODO: Implement get logic + pass + + @RestApiBase.post("/", response_model=OrderManagementResponse) + async def create_item(self, request: OrderManagementRequest) -> OrderManagementResponse: + """Create new item.""" + # TODO: Implement create logic + pass +``` + +The accompanying models file includes: + +```python +from pydantic import BaseModel + +class OrderManagementRequest(BaseModel): + """Request model for order_management operations.""" + # TODO: Add your request fields + pass + +class OrderManagementResponse(BaseModel): + """Response model for order_management operations.""" + # TODO: Add your response fields + pass +``` + +--- + +## asbs create agent + +Declare an AI agent runtime: two prompt files, a settings section, and an `AgentBuilder` in +`src/main.py`. + +```bash +asbs create agent +``` + +### Arguments + +| Argument | Description | Required | +|----------|--------------------------------|----------| +| `name` | Name of the agent to create | Yes | + +### Naming + +The runtime name is the input in snake case with `_agent` appended, unless it already ends that way: + +- Input: `document_analyzer` -> runtime `document_analyzer_agent` +- Input: `DocumentAnalyzer` -> runtime `document_analyzer_agent` +- Input: `analyzer_agent` -> runtime `analyzer_agent` + +**This command writes no module of its own.** There is no `src/agents/` file and no builder +function: an agent runtime is a declaration in `main.py` plus its prompts, so there is nothing for a +separate module to hold. + +### Files Generated + +1. **System prompt** (`src/prompts/_system.prompt`) -- static context, with example content +2. **Instruction prompt** (`src/prompts/_instruction.prompt`) -- a template with + `{placeholders}` for runtime input, with example content +3. **Settings** (`settings.toml`) -- a `[default.runtimes.]` section and a + `[default.runtimes..models]` section beneath it + +### Auto-Registration + +- The `AgentBuilder` import is added to `src/main.py` if it is not already there +- The runtime declaration is inserted above the `AppBuilder` chain +- `.with_agent(, name="")` is added to the chain + +### Examples + +#### Basic Agent + +```bash +asbs create agent document_analyzer +``` + +Creates: +- `src/prompts/document_analyzer_agent_system.prompt` +- `src/prompts/document_analyzer_agent_instruction.prompt` +- `[default.runtimes.document_analyzer_agent]` in `settings.toml` +- the declaration and the registration in `src/main.py` + +#### What is added to `src/main.py` + +```python +document_analyzer_agent = ( + AgentBuilder(runtime_name="document_analyzer_agent") + .with_model_from_config() + .with_system_prompt("document_analyzer_agent_system") +) + +agent = ( + AppBuilder() + .with_agent(document_analyzer_agent, name="document_analyzer_agent") +) +``` + +The builder is left **unbuilt**, and takes no `Config`. `AppBuilder.build()` calls +`agent.build(config.for_namespace())`, so the model, prompt and metrics are read from +this agent's own configuration view; building it at this line would bind it to whatever +configuration happened to be in scope, which in a group is a neighbour's. + +#### Settings Configuration + +Auto-generated in `settings.toml`: + +```toml +[default.runtimes.document_analyzer_agent] +model_provider = "openai" +model_name = "gpt-5-mini" +model_temperature = 0.7 +model_max_tokens = 2000 + +[default.runtimes.document_analyzer_agent.models] +openai_reasoning_effort = "low" +openai_reasoning_summary = "detailed" +``` + +Override any defaults in your `settings.toml` after creation. In a group, these are read through +this agent's own configuration view, so two agents may run different models under the same key. + +--- + +## asbs create scheduler + +Generate a scheduled task component by creating a subclass of `SchedulerBase`. + +```bash +asbs create scheduler [--cron ] [--output-dir ] +``` + +### Arguments + +| Argument | Description | Required | +|----------|------------------------------------|----------| +| `name` | Name of the scheduler to create | Yes | + +### Options + +| Flag | Description | Default | +|-----------------------|-----------------------------------------|--------------------| +| `--cron ` | Cron expression for the schedule | `0 * * * *` | +| `--output-dir ` | Where the scheduler module is written | `src/schedulers` | + +### `scheduler_mode` is required + +A registered scheduler with no `scheduler_mode` in `settings.toml` fails at `build()`. The key has +no default because neither value is safe to inherit: `in_process` runs a timer in every replica and +claims each tick in the agent's own cache, so it needs `.with_cache()`; `event` starts no timer at +all and waits for a tick published by an external `CronJob`, so it needs `event_bus` -- and nothing +in this project generates that `CronJob`. `asbs validate` reports both. + +### Naming + +Scheduler names are converted to `Scheduler` format: + +- Input: `cleanup` → Class: `CleanupScheduler` → File: `cleanup_scheduler.py` +- Input: `Cleanup` → Class: `CleanupScheduler` → File: `cleanup_scheduler.py` +- Input: `cleanup-task` → Class: `CleanupTaskScheduler` → File: `cleanup_task_scheduler.py` + +### Auto-Registration + +The created scheduler is automatically: +- Imported in `src/main.py` +- Registered with `.with_scheduler(CleanupScheduler)` + +### Cron Expressions + +Use standard 5-field cron syntax: + +``` +┌───────────── minute (0-59) +│ ┌───────────── hour (0-23) +│ │ ┌───────────── day of month (1-31) +│ │ │ ┌───────────── month (1-12) +│ │ │ │ ┌───────────── day of week (0-7, 0=Sunday) +│ │ │ │ │ +│ │ │ │ │ +* * * * * +``` + +Common patterns: +- `*/5 * * * *` - Every 5 minutes +- `0 * * * *` - Every hour at minute 0 +- `0 2 * * *` - Daily at 2:00 AM +- `0 8 * * 1-5` - Weekdays at 8:00 AM +- `0 0 1 * *` - Monthly at midnight on the 1st + +### Examples + +#### Hourly Scheduler + +```bash +asbs create scheduler metrics_collector +``` + +Creates `src/schedulers/metrics_collector_scheduler.py` with default hourly schedule. + +#### Custom Cron Schedule + +```bash +asbs create scheduler daily_cleanup --cron "0 2 * * *" +``` + +Creates a scheduler that runs daily at 2:00 AM. + +#### Scheduler Generated Code + +The generated scheduler includes: + +```python +"""Scheduler for cleanup operations.""" + +import logging +from blueprint.agents.io.api.scheduling.scheduler import SchedulerBase + +logger = logging.getLogger(__name__) + + +class CleanupScheduler(SchedulerBase): + """Scheduler for cleanup operations.""" + + def __init__(self) -> None: + """Initialize the scheduler.""" + super().__init__(crontab="0 2 * * *") + + async def on_startup(self) -> None: + """Initialize the scheduler.""" + # TODO: Get services from registry + # Example: self._service = self.registry.get_service(CleanupService) + + async def on_shutdown(self) -> None: + """Cleanup when shutting down.""" + + async def tick(self) -> None: + """Execute scheduled task.""" + try: + # TODO: Implement your scheduled task here + # Example: await self._service.cleanup() + except Exception as e: + logger.exception("Error during %s scheduler tick: %s", __name__, e) + raise +``` diff --git a/src/blueprint/agent_generator/docs/guides/cli/dev.md b/src/blueprint/agent_generator/docs/guides/cli/dev.md new file mode 100644 index 00000000..587b0b9d --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/cli/dev.md @@ -0,0 +1,40 @@ +# asbs dev + +Run this project's agents in development mode with hot reload, **under the namespaces they are +deployed under**. A development server at the root namespace would serve `/api/orders/{id}` where +production serves `/api/order/orders/{id}`, and would consume under a different queue group, so +every local URL and every local integration test would differ from the deployed one. + +With an `agents.toml`, it serves the group through +`uvicorn blueprint.agents.entrypoint:create_group_app --factory --reload`. Without one -- a project +written before the agent map, which builds its own application -- it serves `src.main:app` exactly +as it always did. + +```bash +asbs dev [--agents ] [--host ] [--port ] +``` + +## Options + +| Flag | Description | Default | +|--------------------|-------------------------------------------------------------|------------------| +| `--agents ` | Comma-separated agents to host | every agent in `agents.toml` | +| `--host ` | Host to bind the server to | `127.0.0.1` | +| `--port ` | Port to bind the server to | `8000` | + +`BLUEPRINT_GROUP` or `BLUEPRINT_AGENTS` already set in the environment always wins: a developer +reproducing a particular deployment is not overridden by a default read out of the agent map. + +## Example + +```bash +asbs dev --port 9000 +``` + +``` +INFO: Blueprint Agents dev server starting... +INFO: Uvicorn running on http://0.0.0.0:9000 (Press CTRL+C to quit) +INFO: Started reloader process +``` + +The development server watches for file changes in the `src/` directory and automatically restarts when modifications are detected. diff --git a/src/blueprint/agent_generator/docs/guides/cli/naming.md b/src/blueprint/agent_generator/docs/guides/cli/naming.md new file mode 100644 index 00000000..312eaba9 --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/cli/naming.md @@ -0,0 +1,83 @@ +# Naming Conventions and Auto-Registration + +All `asbs create` commands follow consistent naming conventions and automatically register components in `src/main.py`. + +## Input Flexibility + +The CLI accepts component names in multiple formats and normalizes them to proper class and file names: + +- **snake_case**: `order_placed` → `OrderPlacedHandler` +- **CamelCase**: `OrderPlaced` → `OrderPlacedHandler` +- **kebab-case**: `order-placed` → `OrderPlacedHandler` + +All formats are converted to proper class names without double suffixes (e.g., never `OrderPlacedHandlerHandler`). + +## Component Naming + +Each component type follows a consistent suffix pattern: + +| Component Type | Input | Class Name | File Name | Notes | +|---|---|---|---|---| +| **Handler** | `order_placed` | `OrderPlacedHandler` | `order_placed_handler.py` | Handles events | +| **Service** | `invoice_processor` | `InvoiceProcessorService` | `invoice_processor_service.py` | Contains business logic | +| **API** | `order_management` | `OrderManagementApi` | `order_management_api.py` | REST endpoints + models file | +| **Agent** | `document_analyzer` | -- | -- | No module of its own: a builder in `main.py` plus two prompt files | +| **Scheduler** | `cleanup` | `CleanupScheduler` | `cleanup_scheduler.py` | Background tasks | + +## Name Normalization Examples + +The CLI handles various input formats correctly: + +### Handler Examples +```bash +asbs create handler order_placed # Snake case input +asbs create handler OrderPlaced # CamelCase input +asbs create handler order-placed # Kebab-case input +# All produce: OrderPlacedHandler in order_placed_handler.py +``` + +### Service Examples +```bash +asbs create service user_manager +asbs create service UserManager +asbs create service user-manager +# All produce: UserManagerService in user_manager_service.py +``` + +### API Examples +```bash +asbs create api product_catalog +asbs create api ProductCatalog +asbs create api product-catalog +# All produce: ProductCatalogApi in product_catalog_api.py +# And the models package src/models/product_catalog/ (dto, domain_models, mapper) +``` + +### Agent Examples +```bash +asbs create agent document_analyzer +asbs create agent DocumentAnalyzer +asbs create agent document-analyzer +# All produce the runtime name: document_analyzer_agent +# Declared in src/main.py as an AgentBuilder; prompts in src/prompts/ +``` + +## Auto-Registration + +When you create a component, the CLI automatically: + +1. **Creates the component file** in the appropriate directory +2. **Adds imports** to `src/main.py` +3. **Registers with AppBuilder** in the chain + +If auto-registration fails (e.g., `src/main.py` not found), the CLI displays a clear error message with manual registration instructions. + +### Example Auto-Registration Output + +```bash +$ asbs create handler order_placed +✓ Created handler: src/handlers/order_placed_handler.py +✓ Auto-registered in src/main.py + - Added import: from src.handlers.order_placed_handler import OrderPlacedHandler + - Added registration: .with_handler(OrderPlacedHandler) +``` diff --git a/src/blueprint/agent_generator/docs/guides/cli/setup.md b/src/blueprint/agent_generator/docs/guides/cli/setup.md new file mode 100644 index 00000000..f122f0e4 --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/cli/setup.md @@ -0,0 +1,92 @@ +# asbs setup + +Scaffold a complete Blueprint Agents project with all required directories and configuration files. + +```bash +asbs setup [--output-dir ] [--overwrite] [--verbose] +``` + +## Arguments + +| Argument | Description | Required | +|----------------|------------------------------------|----------| +| `project-name` | Name of the project to create | Yes | + +## Options + +| Flag | Description | Default | +|-----------------------|--------------------------------------------------------|---------| +| `--output-dir ` | Parent directory the project is created in | `.` | +| `--overwrite` | Overwrite existing files instead of refusing | off | +| `--verbose`, `-v` | Debug-level logging from the generator | off | + +The project name is normalised to a class name (`order-processor` gives `OrderProcessor/`), and the +agent's namespace is that name in snake case (`order_processor`). + +## Generated Project Structure + +``` +/ + src/ + main.py # the declaration: agent = AppBuilder()... + api/ + handlers/ + models// # dto.py, domain_models.py, mapper.py + prompts/ + services/ + agents.toml # agent name -> declaration; baked into the image + settings.toml + .secrets.toml # git-ignored + .secrets.toml.example # committed, so the keys to fill in are known + Dockerfile + .gitignore +``` + +There is no `tests/` directory and no `pyproject.toml`: the scaffolder writes source, settings and +the image, and the packaging and test layout are the project's own. `asbs validate` reports both as +missing, which is a reminder rather than a defect in the scaffold. + +## Example + +```bash +asbs setup my-ai-service +``` + +The generated `main.py` is a **declaration**, not an application. Nothing is constructed until +something calls `build()`, which is what lets the same file be served on its own and be hosted +alongside other agents in one process: + +```python +from blueprint.agents.agent import AgentBuilder +from blueprint.agents.app_builder import AppBuilder + +from .services import MyAiServiceService + +my_ai_service_agent = ( + AgentBuilder(runtime_name="my_ai_service_agent") + .with_model_from_config() + .with_system_prompt("my_ai_service_agent_system") +) + +agent = ( + AppBuilder() + .with_service(MyAiServiceService) + .with_agent(my_ai_service_agent, name="my_ai_service_agent") +) +``` + +Components are registered as **classes**, not instances: a component constructed on the `with_*` +line is constructed before any namespace exists and belongs to the root for ever, which is why a +group refuses one. + +`asbs setup` also writes `agents.toml`, which maps the agent's name to that declaration: + +```toml +[agents.my_ai_service] +module = "src.main:agent" +``` + +That name is the agent's identity everywhere outside the file -- the NATS queue group, part of the +JetStream durable name, the cache partition, the OpenTelemetry `service.name` and the `/api/` +route prefix -- so changing it after the first deploy is a consumer migration. The project is run +with `python -m blueprint.agents.entrypoint`, which reads that map and the deployment's group. diff --git a/src/blueprint/agent_generator/docs/guides/cli/validate.md b/src/blueprint/agent_generator/docs/guides/cli/validate.md new file mode 100644 index 00000000..b6061c54 --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/cli/validate.md @@ -0,0 +1,65 @@ +# asbs validate + +Validate the project structure and configuration. Reads files only -- it never imports the +project -- and reports what it finds in three grades: **issues** (the project will not start, exit +status 1), **warnings** (it will start, and something is missing) and **notices** (a decision the +framework must not make for you). + +```bash +asbs validate [] +``` + +## Checks Performed + +Project shape: + +- Required directories (`src/`, `tests/`) and files (`settings.toml`, `pyproject.toml`) exist +- `src/main.py` exists and uses `AppBuilder` +- `.secrets.toml.example` and `.secrets.toml` are present +- A `Dockerfile` is present + +Group readiness -- what this project must state before it can be hosted beside another agent: + +- `agents.toml` exists; without it the project cannot be run by + `python -m blueprint.agents.entrypoint`, and the three changes that make it hostable are named +- Every `[agents.]` entry has a `module` written as `"package.module:attribute"` +- Every agent name is a legal namespace (`[a-z][a-z0-9_]*` -- no dashes), because it becomes the + queue group, the durable, the cache partition and the telemetry `service.name` +- Every declared module exists in the project and assigns the attribute the map names +- Once there is more than one agent: each ships its own `settings.toml` beside its declaration, + and declares no process-scope key (`app_port`, `event_bus`, `envvar_prefix`, ...) there, since + one process binds one port and speaks one bus + +Schedulers: + +- `scheduler_mode` is set when `src/schedulers/` holds anything, and is one of `in_process` or + `event` -- it has no default, and `build()` fails without it +- In `event` mode, `event_bus` is set; and a notice that **nothing in this project generates the + `CronJob`** that must publish the tick. A scheduler waiting for a tick nobody publishes reports + itself healthy and never runs, which nothing else reports +- In `in_process` mode, a notice when `src/main.py` declares no cache: each tick is claimed in the + agent's own cache so that one replica runs it, and with no cache every replica runs every tick + +Delivery: + +- A notice when handlers exist and `idempotency_enabled` is not declared either way. Delivery is + at-least-once, so the decision is the author's to make and the framework will not make it + +## Example + +```bash +asbs validate +``` + +``` +Validating Blueprint Agents project: /work/my-ai-service + +[ok] Found agents.toml (1 agent(s): my_ai_service) + +============================================================ + +Notices (1): + - 'scheduler_mode' is 'event', so no timer runs in this process: each tick + arrives as an event on '.scheduler.', published by an external + CronJob. ... +``` diff --git a/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md similarity index 100% rename from docs/guides/deployment.md rename to src/blueprint/agent_generator/docs/guides/deployment.md diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md new file mode 100644 index 00000000..31c582d7 --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md @@ -0,0 +1,123 @@ +# Migrating an Existing Agent into a Group + +You have a single-agent project with a `main.py` that builds and serves an application, and you +want it to run beside other agents in one process. Three files change, and nothing else. + +Migrating is optional. A project deployed on its own keeps working, unchanged, indefinitely -- +there is no deprecation here. See [Multi-Agent Setup](multi-agent-setup.md) for the model this fits into, and +read [the one decision to get right first](multi-agent-setup.md#the-one-decision-to-get-right-first) before you +start: one of the three files carries a name you cannot cheaply change afterwards. + +--- + +Three files change, and nothing else. Read +[the one decision to get right first](multi-agent-setup.md#the-one-decision-to-get-right-first) before you start: one +of the three is a name you cannot cheaply change afterwards. + +## 1. `src/main.py` -- remove two things, add nothing + +Before: + +```python +config = Config(settings_files=["settings.toml", ".secrets.toml"]) + +app = ( + AppBuilder(config) + .with_service(OrderService) + .with_handler(OrderValidationHandler) + .with_rest_api(OrderApi) + .with_cache() + .build() +) +``` + +After -- **the same builder**, minus its `config` argument and minus the `.build()`: + +```python +agent = ( + AppBuilder() + .with_service(OrderService) + .with_handler(OrderValidationHandler) + .with_rest_api(OrderApi) + .with_cache() +) +``` + +Every `with_*` call stays exactly where it was. `with_cache()` included. That is the point of there +being one builder class: migration removes two things and adds none, because the declaration and +the application builder are the same object. + +If the agent is **also** still to be served on its own, add a factory -- optional, and it repeats no +component: + +```python +def create_app(): + return agent.build(Config(settings_files=["settings.toml", ".secrets.toml"])) +``` + +Two things the module must not do, because it is imported into a shared runtime: construct clients +or other components at import time, and call `logging.basicConfig()`. Configuration and logging +belong to the process that hosts the declaration. + +If you are passing **instances** anywhere -- `with_rest_api(OrderApi())` -- change them to classes. +An instance is constructed at that line, before any namespace exists, so it belongs to the root for +ever; a group refuses one at assembly and names the agent and the fix. + +## 2. `Dockerfile` -- one command + +```diff +-CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"] ++CMD ["python", "-m", "blueprint.agents.entrypoint"] +``` + +and copy the map into the image beside your settings: + +```dockerfile +COPY --chown=appuser:appuser agents.toml ./ +``` + +## 3. `agents.toml` -- a new file + +```toml +[agents.order] +module = "src.main:agent" +``` + +Required even for a group of one: it is the only thing that turns an agent's name into code. There +is discovery by convention nowhere in this, deliberately -- a set of agents that depends on what +happens to be importable makes a renamed directory a silently removed agent. + +## 4. Check it + +```bash +asbs validate +``` + +It reads the map, holds the name to the namespace alphabet, confirms the module exists and assigns +the attribute you named, and reports anything about schedulers or settings that would not survive +the move. It never imports your project. + +## One declaration, three ways to run it + +| Shape | Command | +|---|---| +| Standalone, unmigrated | `uvicorn src.main:app` | +| Standalone, migrated (with `create_app`) | `uvicorn src.main:create_app --factory` | +| Grouped, including a group of one | `python -m blueprint.agents.entrypoint` | + +--- + +## After the move + +Your **broker-side identity changes once**, on the first grouped deploy. What that affects -- +durables, queue groups, cache directories, telemetry -- is set out in +[What changes, and what does not](multi-agent-setup.md#what-changes-and-what-does-not), and the cold-cache +consequence in [The cache is cold after the move](multi-agent-setup.md#the-cache-is-cold-after-the-move). + +--- + +## See also + +- [Multi-Agent Setup](multi-agent-setup.md) -- the model, a new project, and group configuration +- [CLI Reference](cli-reference.md) -- `asbs validate` checks the migration for you +- [Deployment](deployment.md) -- images, Helm, probes, scaling diff --git a/docs/guides/multi-agent-setup.md b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md similarity index 82% rename from docs/guides/multi-agent-setup.md rename to src/blueprint/agent_generator/docs/guides/multi-agent-setup.md index 14ce654d..c90a892e 100644 --- a/docs/guides/multi-agent-setup.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md @@ -15,6 +15,8 @@ a runtime setting rather than an architectural commitment. --- +--- + ## Read this first: which of the two are you doing? Everything below splits along one question, and the answers differ in ways that matter: @@ -22,7 +24,7 @@ Everything below splits along one question, and the answers differ in ways that | | You are here if | What changes | |---|---|---| | **A. A new project** | You are running `asbs setup` today | Nothing to migrate. Your agent has a real namespace from the first run | -| **B. An existing single-agent project** | You have a `main.py` that builds and serves an application | Three files change, and your **broker-side identity changes once** -- see [What changes](#what-changes-and-what-does-not) | +| **B. An existing single-agent project** | You have a `main.py` that builds and serves an application | Three files change, and your **broker-side identity changes once** -- see [Migrating an Existing Agent into a Group](multi-agent-migration.md) | A third answer is legitimate and costs nothing: **do nothing.** An existing project that is deployed on its own keeps working, unchanged, indefinitely. There is no deprecation here. @@ -117,105 +119,6 @@ names them if you leave them there. --- -## B. Migrating an existing single-agent project - -Three files change, and nothing else. Read -[the one decision to get right first](#the-one-decision-to-get-right-first) before you start: one -of the three is a name you cannot cheaply change afterwards. - -### 1. `src/main.py` -- remove two things, add nothing - -Before: - -```python -config = Config(settings_files=["settings.toml", ".secrets.toml"]) - -app = ( - AppBuilder(config) - .with_service(OrderService) - .with_handler(OrderValidationHandler) - .with_rest_api(OrderApi) - .with_cache() - .build() -) -``` - -After -- **the same builder**, minus its `config` argument and minus the `.build()`: - -```python -agent = ( - AppBuilder() - .with_service(OrderService) - .with_handler(OrderValidationHandler) - .with_rest_api(OrderApi) - .with_cache() -) -``` - -Every `with_*` call stays exactly where it was. `with_cache()` included. That is the point of there -being one builder class: migration removes two things and adds none, because the declaration and -the application builder are the same object. - -If the agent is **also** still to be served on its own, add a factory -- optional, and it repeats no -component: - -```python -def create_app(): - return agent.build(Config(settings_files=["settings.toml", ".secrets.toml"])) -``` - -Two things the module must not do, because it is imported into a shared runtime: construct clients -or other components at import time, and call `logging.basicConfig()`. Configuration and logging -belong to the process that hosts the declaration. - -If you are passing **instances** anywhere -- `with_rest_api(OrderApi())` -- change them to classes. -An instance is constructed at that line, before any namespace exists, so it belongs to the root for -ever; a group refuses one at assembly and names the agent and the fix. - -### 2. `Dockerfile` -- one command - -```diff --CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"] -+CMD ["python", "-m", "blueprint.agents.entrypoint"] -``` - -and copy the map into the image beside your settings: - -```dockerfile -COPY --chown=appuser:appuser agents.toml ./ -``` - -### 3. `agents.toml` -- a new file - -```toml -[agents.order] -module = "src.main:agent" -``` - -Required even for a group of one: it is the only thing that turns an agent's name into code. There -is discovery by convention nowhere in this, deliberately -- a set of agents that depends on what -happens to be importable makes a renamed directory a silently removed agent. - -### 4. Check it - -```bash -asbs validate -``` - -It reads the map, holds the name to the namespace alphabet, confirms the module exists and assigns -the attribute you named, and reports anything about schedulers or settings that would not survive -the move. It never imports your project. - -### One declaration, three ways to run it - -| Shape | Command | -|---|---| -| Standalone, unmigrated | `uvicorn src.main:app` | -| Standalone, migrated (with `create_app`) | `uvicorn src.main:create_app --factory` | -| Grouped, including a group of one | `python -m blueprint.agents.entrypoint` | - ---- - ## The one decision to get right first **The agent's name in `agents.toml` is its identity everywhere outside that file.** It becomes: @@ -422,6 +325,7 @@ wants `idempotency_enabled`. NATS has no such coupling -- each agent has its own ## See also +- [Migrating an Existing Agent into a Group](multi-agent-migration.md) -- moving a project you already have - [CLI Reference](cli-reference.md) -- `asbs setup`, `asbs dev`, `asbs validate` in full - [Deployment](deployment.md) -- images, Helm, probes, scaling - [Caching](../concepts/caching.md) -- named caches, per-agent stores, the management endpoints diff --git a/docs/guides/testing.md b/src/blueprint/agent_generator/docs/guides/testing.md similarity index 100% rename from docs/guides/testing.md rename to src/blueprint/agent_generator/docs/guides/testing.md diff --git a/docs/guides/troubleshooting.md b/src/blueprint/agent_generator/docs/guides/troubleshooting.md similarity index 100% rename from docs/guides/troubleshooting.md rename to src/blueprint/agent_generator/docs/guides/troubleshooting.md diff --git a/docs/reference/api.md b/src/blueprint/agent_generator/docs/reference/api.md similarity index 100% rename from docs/reference/api.md rename to src/blueprint/agent_generator/docs/reference/api.md diff --git a/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md similarity index 100% rename from docs/reference/configuration-keys.md rename to src/blueprint/agent_generator/docs/reference/configuration-keys.md diff --git a/docs/reference/models.md b/src/blueprint/agent_generator/docs/reference/models.md similarity index 100% rename from docs/reference/models.md rename to src/blueprint/agent_generator/docs/reference/models.md diff --git a/src/blueprint/agent_generator/generator/claude_generator.py b/src/blueprint/agent_generator/generator/claude_generator.py index b1339ed1..f328e503 100644 --- a/src/blueprint/agent_generator/generator/claude_generator.py +++ b/src/blueprint/agent_generator/generator/claude_generator.py @@ -112,9 +112,14 @@ def generate(self, overwrite: bool = False) -> None: print("\nNext steps:") print(" 1. Open the project in Claude Code — it will pick up src/CLAUDE.md automatically.") print(" 2. Use slash commands:") - print(" /new-agent-service /add-component") + print(" /new-agent-service /add-component") + print(" /blueprint-cli /blueprint-config") + print(" /blueprint-events /blueprint-multi-agent") + print(" /blueprint-testing /blueprint-deployment") + print(" /blueprint-troubleshooting") print(" 3. Use agents:") print(" @blueprint-architect @blueprint-builder") + print(" 4. The framework docs are on disk; find them with 'asbs docs'.") # ------------------------------------------------------------------ # Private helpers diff --git a/tests/unit/agent_generator/cli/commands/test_docs.py b/tests/unit/agent_generator/cli/commands/test_docs.py new file mode 100644 index 00000000..e130b64c --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_docs.py @@ -0,0 +1,126 @@ +"""The documentation is reachable from the installed package, not just from the repository. + +``README.md`` becomes the wheel's ``METADATA``, and it linked twenty-one pages that lived at the +repository root and were never packaged -- so every one of those links resolved to nothing once +installed, and an assistant working in a consuming project could not read the guide it was told to +read. The pages now ship inside ``blueprint/agent_generator/docs`` and ``asbs docs`` is what finds +them, wherever site-packages happens to be. + +These tests hold the packaging, not the prose: that the directory is found through the package +rather than a path relative to the checkout, and that the pages the skills name by slug are the +pages that are actually there. +""" + +import re +from pathlib import Path + +import pytest + +from blueprint.agent_generator.cli.commands.docs import list_topics, locate_docs_root, resolve_topic + +CLAUDE_DOCS = Path(__file__).resolve().parents[5] / "src" / "blueprint" / "agent_generator" / "claude_docs" + +# "asbs docs " as written anywhere in a shipped skill or in the shipped CLAUDE.md. +DOCS_INVOCATION = re.compile(r"asbs docs ([A-Za-z0-9_][A-Za-z0-9_./-]*)") + +# Flags, not slugs: "asbs docs --root" names no page. +NOT_A_SLUG = {"--root", "--cat"} + + +def cited_slugs() -> list[tuple[str, str]]: + """Every (citing file, slug) pair the shipped assistant material tells a reader to open.""" + found = [] + for md in sorted(CLAUDE_DOCS.rglob("*.md")): + for slug in DOCS_INVOCATION.findall(md.read_text(encoding="utf-8")): + if slug not in NOT_A_SLUG: + found.append((md.relative_to(CLAUDE_DOCS).as_posix(), slug)) + return found + + +class TestLocateDocsRoot: + """Finding the packaged documentation.""" + + def test_root_is_found_through_the_package(self) -> None: + root = locate_docs_root() + assert root.is_dir() + # Resolved from the package, so it follows the package wherever it is installed. + assert root.parent.name == "agent_generator" + + def test_root_holds_pages(self) -> None: + assert list_topics(locate_docs_root()) + + +class TestEveryPageIsReachable: + """Every page that ships can be opened by the slug the listing gives for it.""" + + def test_every_page_is_listed_by_its_slug(self) -> None: + root = locate_docs_root() + for slug in list_topics(root): + assert resolve_topic(root, slug).is_file() + + +class TestResolveTopic: + """What the caller is allowed to type.""" + + def test_full_slug(self, tmp_path: Path) -> None: + (tmp_path / "guides").mkdir() + (tmp_path / "guides" / "testing.md").write_text("# Testing", encoding="utf-8") + assert resolve_topic(tmp_path, "guides/testing").name == "testing.md" + + def test_md_suffix_is_tolerated(self, tmp_path: Path) -> None: + (tmp_path / "testing.md").write_text("# Testing", encoding="utf-8") + assert resolve_topic(tmp_path, "testing.md").name == "testing.md" + + def test_bare_name_when_unambiguous(self, tmp_path: Path) -> None: + (tmp_path / "guides").mkdir() + (tmp_path / "guides" / "troubleshooting.md").write_text("# T", encoding="utf-8") + assert resolve_topic(tmp_path, "troubleshooting").name == "troubleshooting.md" + + def test_bare_name_matching_two_pages_is_refused(self, tmp_path: Path) -> None: + """Refused rather than guessed: picking one of two silently sends half the readers wrong.""" + for folder in ("guides", "concepts"): + (tmp_path / folder).mkdir() + (tmp_path / folder / "caching.md").write_text("# Caching", encoding="utf-8") + + with pytest.raises(FileNotFoundError, match="ambiguous"): + resolve_topic(tmp_path, "caching") + + def test_unknown_topic_names_the_way_out(self, tmp_path: Path) -> None: + with pytest.raises(FileNotFoundError, match="asbs docs"): + resolve_topic(tmp_path, "no-such-page") + + +class TestListTopics: + """Slugs are what a skill writes, so they are posix and suffix-free.""" + + def test_slugs_are_relative_posix_without_suffix(self, tmp_path: Path) -> None: + (tmp_path / "guides").mkdir() + (tmp_path / "guides" / "deployment.md").write_text("# D", encoding="utf-8") + (tmp_path / "top.md").write_text("# T", encoding="utf-8") + + assert list_topics(tmp_path) == ["guides/deployment", "top"] + + +class TestSkillsCiteRealPages: + """The skills point at the docs rather than restating them, so the pointers have to land. + + A skill is written once and the docs move afterwards; the citation is the part that rots. + Parsing the skills rather than listing their slugs here keeps this guard true of skills + written after this test. + """ + + def test_some_skill_cites_the_docs(self) -> None: + """Guards the parser: a regex that silently matches nothing would pass every case below.""" + assert cited_slugs() + + @pytest.mark.parametrize( + ("citing_file", "slug"), + cited_slugs(), + ids=lambda v: v.replace("/", "-"), + ) + def test_cited_slug_resolves(self, citing_file: str, slug: str) -> None: + root = locate_docs_root() + try: + resolve_topic(root, slug) + except FileNotFoundError as e: + pytest.fail(f"{citing_file} tells the reader to run 'asbs docs {slug}', which fails: {e}") diff --git a/tests/unit/agents/test_design_rules.py b/tests/unit/agents/test_design_rules.py index 01c6b4d4..84b09315 100644 --- a/tests/unit/agents/test_design_rules.py +++ b/tests/unit/agents/test_design_rules.py @@ -904,12 +904,7 @@ def test_every_allowed_print_still_writes_to_stderr(self, path: Path) -> None: it, and ``CLAUDE.local.md`` is one developer's machine. Neither is scanned, so that this guard gives the same answer everywhere.""" -KNOWN_GAPS: dict[tuple[str, str], str] = { - ("README.md", "LICENSE"): ( - "README states the MIT licence and pyproject.toml carries the MIT classifier, but no LICENSE file has ever " - "been committed. Adding one is a legal artefact and a human decision, not a documentation fix." - ), -} +KNOWN_GAPS: dict[tuple[str, str], str] = {} """References that are known not to resolve, each with why it has not been fixed. Listed rather than silently tolerated, and held to being genuinely broken by From ec6048c0a76ae1c748c5031735e86e755b074cb4 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 16 Sep 2026 09:08:10 +0200 Subject: [PATCH 026/133] fix(ci): keep ruff format off the packaged documentation The docs moved under src/ so they ship in the wheel, which put them in reach of "ruff format --check src tests". Ruff 0.15+ formats Python code blocks inside Markdown, and CI resolves ruff>=0.14.4 to 0.16.7, so 17 pages failed the format check: it collapses the fluent AppBuilder and AgentBuilder chains onto a single 140-column line. Those examples are wrapped one call per line on purpose -- the shape is what the reader is being shown. Excluded rather than reformatted: these are documentation that happens to live under src/ for packaging reasons, not source. Co-Authored-By: Claude Opus 5 (1M context) --- pyproject.toml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index daf8d43d..7c2e997d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -131,6 +131,15 @@ extend-exclude = ''' [tool.ruff] target-version = "py313" line-length = 140 +# The packaged documentation lives under src/ so it ships in the wheel, which puts it in reach of +# "ruff format src". Ruff formats Python code blocks inside Markdown, and the examples in these +# pages are wrapped on purpose -- a fluent AppBuilder chain is one call per line because that is +# what makes the shape readable. Formatting them collapses each chain onto a single 140-column +# line, which is worse prose and not what the reader is being shown. +extend-exclude = [ + "src/blueprint/agent_generator/docs", + "src/blueprint/agent_generator/claude_docs", +] lint.select = [ "E", # pycodestyle errors "W", # pycodestyle warnings From aba6621208a5cf485b985feab74e075757e41b5c Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 16 Sep 2026 12:25:45 +0200 Subject: [PATCH 027/133] fix(group): read each agent's files from the root its map entry states Two defects, one cause: a group never knew where an agent's own directory was, so it inferred one -- and inference was wrong for every layout but the one it was written against. An agent's settings.toml was looked for beside the declaration *module*, inside src/, while every scaffolded project writes it beside src/. The file existed, looked right, and was never opened: the agent ran on the group's defaults and said so nowhere. Prompts resolved against the process working directory, which is one directory for a whole group -- right for at most one agent, and for the rest either nothing or a neighbour's prompt of the same name. The agent map now states each agent's root, required and never derived, so nesting an agent at any depth costs nothing. A missing root, one escaping the image, one that is not a directory and two agents sharing one are each refused at startup naming the agent. That makes an agent the same directory whether it runs alone or as one of twenty, which is what lets it move between repositories untouched. Files that cannot be read from where they sit are now refused rather than ignored, because being ignored is what made the original defect invisible. - agents.toml entries take root = "", relative to that file - blueprint/agents/layout.py: one table of artefacts with a single legal location, enforced at assembly and by asbs validate --group - asbs setup --group writes the image's files; asbs setup writes an agent and no agents.toml -- the single-agent Dockerfile writes its own map - asbs dev needs no map in an agent directory; --name, else the directory name - asbs validate --group checks the map against what is on disk - the scaffolded settings.toml no longer sets process-wide keys - AgentMapPartGenerator removed; agent_namespace moved to PartGeneratorBase The src//main.py group layout is retired. Multi-agent grouping has only ever shipped in 0.9.0 alphas, so nothing stable depended on it. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 50 ++++ pyproject.toml | 2 +- .../agent_generator/base_files/Dockerfile | 19 +- .../base_files/agents_toml.txt | 18 -- .../base_files/group_Dockerfile | 69 +++++ .../base_files/group_agents_toml.txt | 40 +++ .../agent_generator/base_files/settings.txt | 14 +- .../claude_docs/skills/blueprint-cli/SKILL.md | 14 +- .../skills/blueprint-config/SKILL.md | 13 + .../skills/blueprint-multi-agent/SKILL.md | 48 ++++ .../agent_generator/cli/commands/dev.py | 74 +++++ .../cli/commands/group_setup.py | 126 ++++++++ .../agent_generator/cli/commands/setup.py | 36 ++- .../agent_generator/cli/commands/validate.py | 8 + .../cli/commands/validate_group.py | 195 +++++++++++++ src/blueprint/agent_generator/cli/main.py | 22 +- .../docs/concepts/configuration.md | 48 ++++ .../agent_generator/docs/guides/cli/dev.md | 24 ++ .../agent_generator/docs/guides/cli/setup.md | 48 +++- .../docs/guides/cli/validate.md | 27 ++ .../docs/guides/multi-agent-migration.md | 52 +++- .../docs/guides/multi-agent-setup.md | 107 +++++-- .../agent_generator/generator/generator.py | 13 +- .../generator/part_generators/__init__.py | 2 - .../agent_map_part_generator.py | 52 ---- .../part_generators/part_generator_base.py | 28 ++ src/blueprint/agents/agent_group.py | 68 ++--- src/blueprint/agents/config/config.py | 33 +++ src/blueprint/agents/group_config.py | 79 +++++- src/blueprint/agents/layout.py | 121 ++++++++ .../generator/test_generated_project.py | 64 +++-- .../agents/clients/io/test_nats_client.py | 1 - tests/unit/agents/conftest.py | 3 + tests/unit/agents/test_agent_files.py | 268 ++++++++++++++++++ tests/unit/agents/test_agent_group.py | 60 ++-- tests/unit/agents/test_design_rules.py | 3 +- tests/unit/agents/test_entrypoint.py | 8 +- tests/unit/agents/test_group_config.py | 24 +- 38 files changed, 1662 insertions(+), 219 deletions(-) delete mode 100644 src/blueprint/agent_generator/base_files/agents_toml.txt create mode 100644 src/blueprint/agent_generator/base_files/group_Dockerfile create mode 100644 src/blueprint/agent_generator/base_files/group_agents_toml.txt create mode 100644 src/blueprint/agent_generator/cli/commands/group_setup.py create mode 100644 src/blueprint/agent_generator/cli/commands/validate_group.py delete mode 100644 src/blueprint/agent_generator/generator/part_generators/agent_map_part_generator.py create mode 100644 src/blueprint/agents/layout.py create mode 100644 tests/unit/agents/test_agent_files.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c2935fe..1d12bdea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,56 @@ # Changelog ## [Unreleased] +### Fixed + +- **A grouped agent's own `settings.toml` was never read.** The group looked for it beside the + *declaration module* -- inside `src/` -- while every scaffolded project writes it beside `src/`, + so the file existed, looked right, and was never opened. Nothing failed: the agent ran on the + group's defaults and said so nowhere. It is now read from the directory the agent map states. +- **Prompts resolved against the process working directory.** One directory for a whole group, so + it was right for at most one agent; the others found nothing, or found a neighbour's prompt of + the same name. Each agent's configuration view now reports its own directory as the package + root, so `/src/prompts` resolves exactly as it does standalone. +- **A scaffolded agent no longer ships process-wide keys.** `log_level` and `log_format` were + written into every agent's `settings.toml`, so every group one joined dropped them with a + warning about a file the scaffolder itself wrote. They are now commented out, with the reason. + +### Added + +- **`root` in the agent map**, required per agent, relative to the directory `agents.toml` is in. + Stated rather than derived: a root guessed from where a declaration happens to sit is right for + one layout and silently wrong for every other, and nesting an agent at any depth now costs + nothing. A missing `root`, one that escapes the image, one that is not a directory, and two + agents sharing one are each refused at startup, naming the agent. +- **Misplaced files are refused, not ignored** (`blueprint.agents.layout`). One table of artefacts + with a single legal location, enforced at group assembly and reported by `asbs validate + --group`: `settings.toml` and `.secrets.toml` beside `src/`, `agents.toml` at the image root. + `Dockerfile` is deliberately absent from it -- an agent may own one while living in a group + repository. Adding an artefact is one tuple. +- **`asbs setup --group`** writes the image's files -- an empty agent map, the process settings + and a group Dockerfile -- and creates no agent. +- **`asbs validate --group`** validates an image: every `root`, each agent's layout, misplaced + files, process-wide keys left in an agent, and which `settings.toml` each agent actually reads. +- **`asbs dev --name`**, and `asbs dev` no longer needs an `agents.toml` in an agent's directory. + It writes the one-agent map outside the project for that run. + +### Breaking + +- **`root` is required in `agents.toml`.** Every existing entry needs one line added; a map + without it refuses to start rather than guessing. For an image that copied one agent to `/app`, + that is `root = "."`. +- **`asbs setup` no longer writes `agents.toml` into an agent.** The map says which agents an + *image* contains, which is a packaging decision -- an agent carrying one is an agent that knows + whether it is running alone. The single-agent `Dockerfile` writes a one-agent map into its own + image instead. Existing projects keep working; delete the file when the agent joins a group, + where it is refused. +- **The `src//main.py` group layout is retired.** An agent is now the same directory alone + or in a group -- `/settings.toml` beside `/src/` -- which is what lets it move + between repositories untouched. Multi-agent grouping has only ever shipped in 0.9.0 alphas, so + nothing stable depended on the old shape. +- **`AgentMapPartGenerator` is gone.** It generated a file that is no longer written; its + `agent_namespace` helper moved to `PartGeneratorBase`. + ### Added - **The documentation ships inside the package.** The user-facing guides moved from the repository diff --git a/pyproject.toml b/pyproject.toml index 7c2e997d..a9f32c48 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta" [project] name = "avs-blueprint-agents" -version = "0.9.0a3" +version = "0.9.0a4" description = "Microservice blueprint for creating agents" authors = [ { name = "Blueprint Team", email = "patrick.maue@bechtle.com" }, diff --git a/src/blueprint/agent_generator/base_files/Dockerfile b/src/blueprint/agent_generator/base_files/Dockerfile index 03d807fd..cf4eaf7a 100644 --- a/src/blueprint/agent_generator/base_files/Dockerfile +++ b/src/blueprint/agent_generator/base_files/Dockerfile @@ -69,10 +69,21 @@ COPY --from=builder /usr/local/bin /usr/local/bin COPY --chown=appuser:appuser src ./src COPY --chown=appuser:appuser settings.toml ./ -# The agent map belongs to the image -- it lists the agents this image contains and where -# their declarations live. The group file does NOT: which of those agents a process runs is -# a deployment decision, so it arrives as a mount or as BLUEPRINT_AGENTS. See the ENTRYPOINT. -COPY --chown=appuser:appuser agents.toml ./ +# The agent map belongs to the image, not to the agent -- it says which agents an image +# contains, which is a packaging decision. So it is written here rather than copied from the +# agent's directory: the agent carries no agents.toml, and is therefore the same directory +# whether it is built alone like this or dropped into a group image that maps several. +# +# root = "." because this image contains exactly one agent and it was copied to /app. In a +# group image each agent has its own subdirectory, and root names it. +# +# The group file does NOT belong here: which of an image's agents a process runs is a +# deployment decision, so it arrives as a mount or as BLUEPRINT_AGENTS. See the ENTRYPOINT. +COPY --chown=appuser:appuser <). Renaming it after the first deploy is therefore a consumer migration, not a -# rename. It must match [a-z][a-z0-9_]* -- lower case, no dashes. -# -# 'module' is "package.module:attribute", naming the AppBuilder that module assigns. An agent's -# own settings.toml, if it has one, is read from the directory that module lives in. - -[agents.agent_namespace] -module = "src.main:agent" diff --git a/src/blueprint/agent_generator/base_files/group_Dockerfile b/src/blueprint/agent_generator/base_files/group_Dockerfile new file mode 100644 index 00000000..b4d30157 --- /dev/null +++ b/src/blueprint/agent_generator/base_files/group_Dockerfile @@ -0,0 +1,69 @@ +# syntax=docker/dockerfile:1.7 + +# ============================================================================ +# Group image - hosts several agents in one process +# ============================================================================ +# +# The difference from an agent's own Dockerfile is what gets copied, not how it runs: both end +# at the same entry point, because a standalone agent is a group of one. Here the agent +# directories are copied as they are, beside the map that names them. +# +# Each agent directory is exactly what `asbs setup ` wrote -- its own settings.toml, +# .secrets.toml and src/ -- and carries no agents.toml. That is what lets the same directory be +# built by its own Dockerfile as a single-agent image without editing anything. + +FROM python:3.13-bookworm AS builder + +RUN pip install --no-cache-dir --upgrade pip uv + +WORKDIR /app + +COPY pyproject.toml ./ +RUN uv pip install --system --no-cache . + +# ============================================================================ +# Runtime +# ============================================================================ +FROM python:3.13-slim-bookworm AS runtime + +RUN useradd --create-home --shell /bin/bash appuser + +WORKDIR /app + +COPY --from=builder /usr/local/lib/python3.13/site-packages /usr/local/lib/python3.13/site-packages +COPY --from=builder /usr/local/bin /usr/local/bin + +# The agents, each in the directory its entry in agents.toml points at with `root`. Copy the +# directories this image actually contains; a blanket `COPY . .` would bake in whatever else +# the repository holds, including other images' build context. +COPY --chown=appuser:appuser agents ./agents + +# The image's own settings: the process-wide keys -- app_port, app_host, event_bus, log_level +# and the rest. One process has one of each, so an agent that sets them in its own settings +# file has them dropped before the merge, with a warning naming the value the process uses. +COPY --chown=appuser:appuser settings.toml ./ + +# The map: which agents this image contains, and where each one's files are. The group file +# does NOT belong here -- which of these agents a process runs is a deployment decision, so it +# arrives as a mount or as BLUEPRINT_AGENTS. +COPY --chown=appuser:appuser agents.toml ./ + +# The disk cache backend writes here and cannot create it itself: WORKDIR made /app +# root-owned, so mkdir() as appuser fails with EACCES. Created and handed over at build time. +RUN mkdir -p /app/.cache && chown -R appuser:appuser /app/.cache + +USER appuser + +EXPOSE 8000 + +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ + CMD curl -f http://localhost:8000/health || exit 1 + +# Which agents this process runs is the deployment's to say: +# +# docker run -e BLUEPRINT_AGENTS=order_processor,billing +# docker run -v ./deployment-groups.yaml:/app/deployment-groups.yaml:ro \ +# -e BLUEPRINT_GROUP= +# +# Nothing in the image names a group, so one image serves every one of them. +ENTRYPOINT ["python", "-m", "blueprint.agents.entrypoint"] diff --git a/src/blueprint/agent_generator/base_files/group_agents_toml.txt b/src/blueprint/agent_generator/base_files/group_agents_toml.txt new file mode 100644 index 00000000..f4f65676 --- /dev/null +++ b/src/blueprint/agent_generator/base_files/group_agents_toml.txt @@ -0,0 +1,40 @@ +# Which agents this image contains, and where each one's files and code live. +# +# Baked into the image on purpose: adding or removing an agent is a rebuild anyway. Which of +# these agents a given *process* runs is a separate decision, made by the deployment rather +# than by the image -- set BLUEPRINT_AGENTS to a comma-separated list, or mount a group file +# and name the group with BLUEPRINT_GROUP. Nothing here says which agents run together. +# +# The name in brackets is the agent's namespace, and it is the agent's identity everywhere +# outside this file: the registry key prefix, the NATS queue group, part of the JetStream +# durable name, the cache partition, the OpenTelemetry service.name and the REST route prefix +# (/api/). Renaming it after the first deploy is therefore a consumer migration, not a +# rename. It must match [a-z][a-z0-9_]* -- lower case, no dashes. +# +# Each agent needs two keys, and both are required: +# +# root Where the agent's own directory is, relative to this file. Its settings.toml and +# its src/prompts are read from there. Stated rather than guessed from the module: +# a root derived from where a declaration happens to sit is right for one layout and +# silently wrong for every other, and an agent reading the group's defaults instead +# of its own settings does not announce itself. +# module "package.module:attribute", naming the AppBuilder that module assigns. +# +# An agent directory is created by running `asbs setup ` inside it, and is the same +# directory whether it is hosted here or built as its own image -- it carries no agents.toml +# of its own, which is what lets it move between the two untouched. +# +# This file starts empty. A group with no agents cannot run: the process refuses to start +# rather than bind a port and consume nothing. Add an entry per agent, for example: +# +# [agents.order_processor] +# root = "agents/order_processor" +# module = "agents.order_processor.src.main:agent" +# +# [agents.billing] +# root = "agents/some_topic/billing" +# module = "agents.some_topic.billing.src.main:agent" +# +# Renaming or moving an agent directory means updating its entry here. That is deliberate: +# the map is the one place the change has to be made on purpose, so a moved directory fails +# loudly at startup instead of quietly removing an agent from the image. diff --git a/src/blueprint/agent_generator/base_files/settings.txt b/src/blueprint/agent_generator/base_files/settings.txt index 216a4f63..45023324 100644 --- a/src/blueprint/agent_generator/base_files/settings.txt +++ b/src/blueprint/agent_generator/base_files/settings.txt @@ -33,11 +33,15 @@ scheduler_mode = "in_process" # of the environment table, so a [default.logging] or [default.observability] # section would be read by nothing at all. # -# log_level and log_format describe the process. If this project is later hosted as -# one agent of a group, the group's own settings file decides both and these two are -# reported and ignored -- one process configures logging once. -log_level = "DEBUG" -log_format = "text" +# log_level and log_format describe the *process*, not this agent, so they are +# commented out here: one process configures logging once, and a value set under an +# agent is dropped before the merge with a warning naming the value actually used. +# +# Uncomment them only while this agent is deployed on its own, where its directory is +# also the image. In a group they belong in the image's settings.toml, beside +# agents.toml -- `asbs validate --group` reports them if they are left here. +# log_level = "DEBUG" +# log_format = "text" # otel_enabled turns OpenTelemetry on and needs otel_endpoint to have somewhere to # send to. token_metrics_enabled adds per-call token and latency metrics on top, and diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-cli/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-cli/SKILL.md index 9d4e14c5..e229abc4 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-cli/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-cli/SKILL.md @@ -13,14 +13,15 @@ than writing component files by hand** - it applies the naming rules and registe ## Commands ```bash -asbs setup # Scaffold a complete project +asbs setup # Scaffold one agent +asbs setup --group # Scaffold the image's files instead asbs create handler [--event-type TYPE] # Add EventHandler asbs create service # Add Service asbs create api # Add RestApi asbs create agent # Add AgentRuntime asbs create scheduler [--cron CRON] # Add Scheduler -asbs validate # Check structure and configuration -asbs dev [--port 8000] # Dev server with reload +asbs validate [--group] # Check one agent, or a whole image +asbs dev [--name NAME] [--port 8000] # Dev server with reload asbs docs [] [--cat] # Locate the framework docs ``` @@ -47,4 +48,9 @@ For the end-to-end workflow of a first project, read `asbs docs getting-started before the handlers, agents and APIs that resolve them. - **Names are normalised, not rejected.** `order-placed`, `OrderPlaced` and `order_placed` all produce the same handler. Agent *namespaces* are the exception - see `blueprint-multi-agent`. -- After any `create`, run `asbs validate` before calling the work done. +- After any `create`, run `asbs validate` before calling the work done. In a repository that + hosts several agents, `asbs validate --group` checks the map and every agent it points at. +- **`asbs setup` has two modes.** `--group` writes the image's files (an empty agent map, the + process settings, a group Dockerfile) and creates no agent. Without it, one agent is created + in the current directory -- the same command whether it will run alone or in a group. +- **A scaffolded agent has no `agents.toml`**, deliberately: see `blueprint-multi-agent`. diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md index c972d885..9f8d5513 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md @@ -49,6 +49,19 @@ These fail at startup rather than guess, so they must be set deliberately: - **`event_publishing_enabled`** - consuming and publishing are separate concerns. A handler implies a transport client; a scheduler does not. +## Where the file goes + +**Beside `src/`, in the agent's own directory** -- never inside `src/`, which is refused rather +than ignored. The same place alone or in a group. + +In a group the image's `agents.toml` states that directory with `root`, and process-wide keys +(`app_port`, `app_host`, `app_environment`, `envvar_prefix`, `event_bus`, `log_level`, +`log_format`, `readiness_policy`, `nats_stream_name`, ...) belong in the **image's** +`settings.toml`, beside `agents.toml`. Set in an agent's file they are dropped before the merge +with a warning naming the value actually used. + +`asbs validate --group` reports all of this without starting anything. + ## Reading config at runtime Resolve configuration in `on_startup()`, never in `__init__` - `self.config` is not linked until diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md index fe40f54c..25ee3b51 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md @@ -18,6 +18,54 @@ two is an edit to a Deployment, not a rebuild. | Existing single-agent project joining a group | `asbs docs guides/multi-agent-migration --cat` | | Leave it standalone | Nothing changes. There is no deprecation - this is a legitimate answer | +## The layout, which is not negotiable + +An agent is **the same directory** alone or in a group -- that is what lets it move between +repositories untouched: + +``` +my_agent/ + settings.toml # beside src/, never inside it + .secrets.toml + Dockerfile # optional: builds this agent alone + src/ + main.py # the declaration + prompts/ +``` + +It carries **no `agents.toml`**. The map says which agents an *image* contains; an agent holding +one would be an agent that knows whether it is running alone. Whoever hosts it supplies the name: +a group image's map, a single-agent image's Dockerfile, or `asbs dev --name`. + +The image, at the top of the repository: + +``` +agents.toml # the map +settings.toml # process-wide keys only +Dockerfile # the group image +agents/... # the agent directories, at any depth +``` + +Create them with two distinct modes -- `asbs setup --group` for the image, `asbs setup ` +inside each agent's directory. The agent command is identical to the standalone one. + +## The map states both keys + +```toml +[agents.my_agent] +root = "agents/some_topic/my_agent" +module = "agents.some_topic.my_agent.src.main:agent" +``` + +**Both are required and neither is derived from the other.** `root` is where the agent's files are +(its `settings.toml`, its `src/prompts`), relative to the directory `agents.toml` is in; `module` +is how its code imports. A root guessed from where the declaration sits is right for one layout and +silently wrong for the rest -- and an agent whose settings were looked for in the wrong place does +not fail, it runs on the group's defaults and says nothing. + +Run `asbs validate --group` after editing the map. It resolves every root, reports which +`settings.toml` each agent reads, and refuses a file that sits where nothing will read it. + ## The decision to get right first **The agent's name in `agents.toml` is its identity everywhere outside that file.** It becomes the diff --git a/src/blueprint/agent_generator/cli/commands/dev.py b/src/blueprint/agent_generator/cli/commands/dev.py index 0f4cab35..46f1b29d 100644 --- a/src/blueprint/agent_generator/cli/commands/dev.py +++ b/src/blueprint/agent_generator/cli/commands/dev.py @@ -1,17 +1,25 @@ """Dev command - start development server.""" +import ast +import atexit import logging import os +import re +import tempfile import subprocess import sys import tomllib from argparse import Namespace from pathlib import Path +from blueprint.agents.component.namespace import validate_namespace + logger = logging.getLogger(__name__) AGENT_MAP_FILE = "agents.toml" +DECLARATION_ENTRY_POINT = "src/main.py" LEGACY_ENTRY_POINT = "src/main.py" +AGENT_MAP_ENV = "BLUEPRINT_AGENT_MAP" GROUP_FACTORY = "blueprint.agents.entrypoint:create_group_app" LEGACY_APP = "src.main:app" @@ -35,6 +43,14 @@ def run(args: Namespace) -> None: agent_map = Path(AGENT_MAP_FILE) if agent_map.is_file(): command = _group_command(args, agent_map) + elif Path(DECLARATION_ENTRY_POINT).is_file() and _declares_an_agent(Path(DECLARATION_ENTRY_POINT)): + # An agent directory carries no agents.toml: the map says which agents an *image* + # contains, and an agent does not know whether it is one of several. So the map this + # run needs is written here, outside the project, rather than expected in it -- the + # framework still resolves agents through an explicit map, this one is just supplied by + # the dev server instead of committed. + agent_map = _temporary_agent_map(args) + command = _group_command(args, agent_map) elif Path(LEGACY_ENTRY_POINT).is_file(): # A project scaffolded before the agent map existed still builds its own application in # src/main.py. It is served the way it always was, at the root namespace, because that @@ -135,3 +151,61 @@ def _agents_in_map(agent_map: Path) -> list[str]: print(f"Error: {agent_map} declares no [agents.] entries, so there is nothing to serve", file=sys.stderr) sys.exit(1) return [str(name) for name in agents] + + +def _declares_an_agent(entry_point: Path) -> bool: + """Report whether ``entry_point`` assigns a module-level ``agent``. + + Read rather than imported: importing it here would construct the declaration twice, once in + this process and once in uvicorn's, and a declaration is not something to build for a + question about its shape. + """ + try: + module = ast.parse(entry_point.read_text(encoding="utf-8")) + except (OSError, SyntaxError): + return False + return any( + isinstance(node, ast.Assign) and any(isinstance(target, ast.Name) and target.id == "agent" for target in node.targets) + for node in module.body + ) + + +def _dev_agent_name(args: Namespace) -> str: + """Return the name this agent runs under while developing. + + ``--name``, or the directory's own name. The agent itself does not carry one: the name is + its identity on the broker, in telemetry and in its routes, and who supplies it depends on + who is hosting it -- a group image's map, a single-agent image's Dockerfile, or this. + + Raises: + SystemExit: if neither yields a legal namespace, because a repaired name would be a + different agent under the same directory. + """ + requested = (getattr(args, "name", "") or "").strip() or Path.cwd().name + candidate = re.sub(r"[-\s]+", "_", requested).lower() + try: + return validate_namespace(candidate) + except ValueError as exc: + print(f"Error: '{requested}' cannot be an agent name: {exc}", file=sys.stderr) + print("Pass --name with a name matching [a-z][a-z0-9_]*", file=sys.stderr) + sys.exit(1) + + +def _temporary_agent_map(args: Namespace) -> Path: + """Write a one-agent map for this run and point the framework at it. + + Written outside the project on purpose. Writing an ``agents.toml`` into the directory would + leave behind exactly the file an agent must not carry, and a developer who then committed it + would have an agent that names itself. + """ + name = _dev_agent_name(args) + handle = tempfile.NamedTemporaryFile("w", suffix="-agents.toml", delete=False, encoding="utf-8") + with handle as written: + written.write(f'[agents.{name}]\nroot = "."\nmodule = "src.main:agent"\n') + path = Path(handle.name) + os.environ[AGENT_MAP_ENV] = str(path) + atexit.register(lambda: path.unlink(missing_ok=True)) + print(f"No {AGENT_MAP_FILE} here, which is how an agent directory should look.") + print(f"Serving it as '{name}' (from {'--name' if getattr(args, 'name', '') else 'the directory name'}).") + print(f"Its routes are under /api/{name}.") + return path diff --git a/src/blueprint/agent_generator/cli/commands/group_setup.py b/src/blueprint/agent_generator/cli/commands/group_setup.py new file mode 100644 index 00000000..24742549 --- /dev/null +++ b/src/blueprint/agent_generator/cli/commands/group_setup.py @@ -0,0 +1,126 @@ +"""Scaffold the image-level files: the agent map, the process settings and the group Dockerfile. + +The other half of ``asbs setup``. These two modes write disjoint sets of files because they +describe different things: an *agent* is a directory of code, settings and prompts, and an +*image* is a container for some number of agents plus the map naming them. Conflating them is +what put an ``agents.toml`` inside every scaffolded agent -- a file that says which agents an +image contains, sitting inside one of them. + +Nothing here names an agent, and no agent is created. Which agents an image contains is decided +one ``asbs setup `` at a time, in whatever directories the author chooses, and recorded in +the map by hand. The map therefore starts empty, and a group with no agents refuses to start +rather than binding a port and consuming nothing. +""" + +import sys +from argparse import Namespace +from pathlib import Path + +BASE_FILES = Path(__file__).resolve().parent.parent.parent / "base_files" + +GROUP_SETTINGS = """# The image's own settings: the keys that describe the *process*. +# +# One process has one of each of these, so they belong here rather than in any agent's +# settings.toml. An agent that sets one has it dropped before its settings are merged, with a +# warning naming the value the process uses instead. + +[default] +app_name = "agent-group" +app_host = "0.0.0.0" +app_port = 8000 +log_level = "INFO" + +# "dapr" or "nats". One process speaks one bus. +# event_bus = "nats" + +# Required once any agent registers a scheduler. "in_process" runs a timer in every replica and +# claims each tick through the cache, so it needs a cache; "event" takes the tick as an event. +# scheduler_mode = "event" + +[development] +app_environment = "development" +log_level = "DEBUG" +""" + + +def scaffold_group(output_dir: Path, overwrite: bool) -> None: + """Write the image-level files into ``output_dir``. + + Args: + output_dir: Where the image is assembled -- the top of the repository, normally. + overwrite: Replace files that are already there. Off by default, because this command + is run in a directory that usually holds work already. + """ + sources = { + "agents.toml": BASE_FILES / "group_agents_toml.txt", + "Dockerfile": BASE_FILES / "group_Dockerfile", + ".gitignore": BASE_FILES / "template_for_git_ignore.txt", + } + + written: list[str] = [] + skipped: list[str] = [] + for name, source in sources.items(): + target = output_dir / name + if target.exists() and not overwrite: + skipped.append(name) + continue + target.write_text(source.read_text(encoding="utf-8"), encoding="utf-8") + written.append(name) + + settings = output_dir / "settings.toml" + if settings.exists() and not overwrite: + skipped.append("settings.toml") + else: + settings.write_text(GROUP_SETTINGS, encoding="utf-8") + written.append("settings.toml") + + _report(output_dir, written, skipped) + + +def _report(output_dir: Path, written: list[str], skipped: list[str]) -> None: + """Print what was written, and the one thing the author has to do next.""" + print("=== Blueprint Agents Group Setup ===") + print(f"Location: {output_dir}") + print("") + print("Written:") + for name in written: + print(f" + {name}") + if skipped: + print("") + print("Left alone (use --overwrite to replace):") + for name in skipped: + print(f" = {name}") + + print("") + print("These are the image's files, not an agent's.") + print("") + print("agents.toml is empty: this image contains no agents yet, and a group with none") + print("cannot start. Create each agent in its own directory:") + print("") + print(" mkdir -p agents/some_topic/my_agent") + print(" cd agents/some_topic/my_agent") + print(" asbs setup my_agent") + print("") + print("then add it to agents.toml, both keys required:") + print("") + print(" [agents.my_agent]") + print(' root = "agents/some_topic/my_agent"') + print(' module = "agents.some_topic.my_agent.src.main:agent"') + print("") + print("An agent directory carries no agents.toml of its own, which is what lets it be") + print("built as its own single-agent image without editing anything.") + print("") + print("Run 'asbs validate --group' here to check the map against what is on disk.") + + +def run(args: Namespace) -> None: + """Execute ``asbs setup --group``. + + Args: + args: Parsed command-line arguments. + """ + output_dir = Path(args.output_dir).absolute() + if not output_dir.is_dir(): + print(f"Error: Output directory does not exist: {output_dir}", file=sys.stderr) + sys.exit(1) + scaffold_group(output_dir, overwrite=args.overwrite) diff --git a/src/blueprint/agent_generator/cli/commands/setup.py b/src/blueprint/agent_generator/cli/commands/setup.py index ce18fb4a..1670ed0c 100644 --- a/src/blueprint/agent_generator/cli/commands/setup.py +++ b/src/blueprint/agent_generator/cli/commands/setup.py @@ -9,8 +9,8 @@ from typing import Any from ...generator.generator import AgentGenerator -from ...generator.part_generators import AgentMapPartGenerator from ...generator.part_generators.part_generator_base import PartGeneratorBase +from . import group_setup logger = logging.getLogger(__name__) @@ -114,6 +114,13 @@ def run(args: Namespace) -> None: format="%(levelname)s: %(message)s", ) + # Two modes writing disjoint sets of files, because they describe different things: an + # agent is a directory of code, settings and prompts; an image is a container for some + # number of agents plus the map naming them. + if getattr(args, "group", False): + group_setup.run(args) + return + print("=== Blueprint Agents Project Setup ===") print("This will create a complete project structure with handlers, services, APIs, and agents.") @@ -128,6 +135,10 @@ def run(args: Namespace) -> None: # This used to compute a `project_path = output_dir / project_name`, guard `--overwrite` # with it and print it as the location -- while handing the generator `output_dir`. So the # directory it protected was never created, and the location it printed was never written to. + if not args.project_name: + print("Error: asbs setup needs the agent's name, or --group to create the image's files", file=sys.stderr) + sys.exit(1) + project_name = PartGeneratorBase.to_class_name(args.project_name) output_dir = Path(args.output_dir).absolute() @@ -135,7 +146,7 @@ def run(args: Namespace) -> None: print(f"Error: Output directory does not exist: {output_dir}", file=sys.stderr) sys.exit(1) - existing = [path.name for path in (output_dir / "src", output_dir / "agents.toml", output_dir / "settings.toml") if path.exists()] + existing = [path.name for path in (output_dir / "src", output_dir / "settings.toml") if path.exists()] if existing and not args.overwrite: print(f"Error: {output_dir} already contains a scaffolded project ({', '.join(existing)})", file=sys.stderr) print("Use --overwrite to write over it", file=sys.stderr) @@ -170,13 +181,12 @@ def run(args: Namespace) -> None: print(" │ ├── models/") print(" │ └── prompts/") print(" ├── tests/") - print(" ├── agents.toml") print(" ├── settings.toml") print(" ├── .secrets.toml") print(" ├── Dockerfile") print(" └── .gitignore") - namespace = AgentMapPartGenerator.agent_namespace(config) + namespace = PartGeneratorBase.agent_namespace(config) print("\nNext steps:") print(" 1. Review and edit the generated files") print(" 2. Add your LLM API key to .secrets.toml") @@ -186,11 +196,19 @@ def run(args: Namespace) -> None: print(f" 5. View API docs at: http://localhost:8000/docs (this agent's routes are under /api/{namespace})") print("\nsrc/main.py declares this agent; it does not build an application.") - print(f"agents.toml names it '{namespace}', and that name is its identity on the broker,") - print("in telemetry and in its routes -- change it now if you are going to, because") - print("changing it after the first deploy is a consumer migration.") - print("The deployment decides which agents a process hosts:") - print(f" docker run -e BLUEPRINT_AGENTS={namespace} ") + print("\nThis directory carries no agents.toml, and that is deliberate: the agent map says") + print("which agents an *image* contains, so an agent holding one would be an agent that") + print("knows whether it is running alone. Whoever hosts it supplies the name:") + print(f" - its own Dockerfile writes a one-agent map naming it '{namespace}'") + print(" - a group image maps it in the repository's agents.toml, with root and module") + print(" - asbs dev uses this directory's name unless --name says otherwise") + print("\nThat name is the agent's identity on the broker, in telemetry and in its routes") + print("(/api/) -- change it now if you are going to, because changing it after the") + print("first deploy is a consumer migration.") + print("\nTo host it in a group, add to the repository's agents.toml:") + print(f" [agents.{namespace}]") + print(' root = ""') + print(' module = ".src.main:agent"') finally: # Clean up temporary config file diff --git a/src/blueprint/agent_generator/cli/commands/validate.py b/src/blueprint/agent_generator/cli/commands/validate.py index b14e1067..fa8a12a1 100644 --- a/src/blueprint/agent_generator/cli/commands/validate.py +++ b/src/blueprint/agent_generator/cli/commands/validate.py @@ -10,6 +10,8 @@ from blueprint.agents.component.namespace import validate_namespace from blueprint.agents.config import PROCESS_SCOPE_KEYS + +from . import validate_group from blueprint.agents.io.api.scheduling.scheduler import SCHEDULER_MODE_EVENT, SCHEDULER_MODE_IN_PROCESS, SCHEDULER_MODES logger = logging.getLogger(__name__) @@ -37,6 +39,12 @@ def run(args: Namespace) -> None: Args: args: Parsed command-line arguments """ + # An image and an agent are different things to check, so this is a mode rather than a + # guess about what the directory looks like. + if getattr(args, "group", False): + validate_group.run(args) + return + project_dir = Path(args.project_dir).resolve() if not project_dir.is_dir(): diff --git a/src/blueprint/agent_generator/cli/commands/validate_group.py b/src/blueprint/agent_generator/cli/commands/validate_group.py new file mode 100644 index 00000000..9c5ae839 --- /dev/null +++ b/src/blueprint/agent_generator/cli/commands/validate_group.py @@ -0,0 +1,195 @@ +"""Validate an image: the agent map, and every agent directory it points at. + +``asbs validate`` checks one agent. This checks the thing that contains agents -- a different +question, which is why it is a different mode rather than a heuristic about what the directory +looks like. + +What it is really for is making the quiet failures loud. Every defect this module reports was, +at some point, something the process did silently: a settings file in a directory nobody reads +from, an agent whose map entry points at a directory that has since been renamed, process-wide +keys set under an agent where nothing consults them. None of those stop a pod from starting and +passing its probes, which is exactly what makes them expensive to find later. +""" + +import sys +import tomllib +from argparse import Namespace +from pathlib import Path +from typing import Any + +from blueprint.agents.component.namespace import validate_namespace +from blueprint.agents.config import PROCESS_SCOPE_KEYS +from blueprint.agents.layout import check_agent_layout + +AGENT_MAP_FILE = "agents.toml" + + +def run(args: Namespace) -> None: + """Execute ``asbs validate --group``. + + Args: + args: Parsed command-line arguments. + """ + image_root = Path(args.project_dir).resolve() + if not image_root.is_dir(): + print(f"Error: Directory does not exist: {image_root}", file=sys.stderr) + sys.exit(1) + + print(f"Validating Blueprint Agents image: {image_root}") + print() + + issues, warnings, notices = _findings(image_root) + _report(issues, warnings, notices) + sys.exit(1 if issues else 0) + + +def _findings(image_root: Path) -> tuple[list[str], list[str], list[str]]: + """Return issues, warnings and notices for the image at ``image_root``.""" + issues: list[str] = [] + warnings: list[str] = [] + notices: list[str] = [] + + agent_map = image_root / AGENT_MAP_FILE + if not agent_map.is_file(): + issues.append( + f"No {AGENT_MAP_FILE} here, so this directory is not an image. Run 'asbs setup --group' to create one, " + "or drop --group to validate a single agent." + ) + return issues, warnings, notices + + try: + document = tomllib.loads(agent_map.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError) as exc: + return [f"{AGENT_MAP_FILE} could not be read: {exc}"], warnings, notices + + declared = document.get("agents") + if not isinstance(declared, dict) or not declared: + warnings.append( + f"{AGENT_MAP_FILE} declares no agents. That is what 'asbs setup --group' writes, and an image with no " + "agents cannot start -- add an entry per agent before deploying it." + ) + return issues, warnings, notices + + print(f"[ok] {AGENT_MAP_FILE} declares {len(declared)} agent(s): {', '.join(str(name) for name in declared)}") + print() + + claimed: dict[Path, str] = {} + for name, entry in declared.items(): + agent_issues, agent_warnings, agent_notices = _agent_findings(image_root, str(name), entry, claimed) + issues.extend(agent_issues) + warnings.extend(agent_warnings) + notices.extend(agent_notices) + + return issues, warnings, notices + + +def _agent_findings(image_root: Path, name: str, entry: Any, claimed: dict[Path, str]) -> tuple[list[str], list[str], list[str]]: + """Check one map entry and the directory it points at.""" + issues: list[str] = [] + warnings: list[str] = [] + notices: list[str] = [] + + try: + validate_namespace(name) + except ValueError as exc: + issues.append(f"Agent '{name}' in {AGENT_MAP_FILE} cannot be a namespace: {exc}") + return issues, warnings, notices + + if not isinstance(entry, dict): + issues.append(f"Agent '{name}' in {AGENT_MAP_FILE} is not a table. Write it as [agents.{name}] with root and module.") + return issues, warnings, notices + + module = entry.get("module") + if not module or not isinstance(module, str) or ":" not in module: + issues.append(f"Agent '{name}' in {AGENT_MAP_FILE} has no usable 'module'. Write it as module = \"package.module:attribute\"") + + declared_root = entry.get("root") + if not declared_root or not isinstance(declared_root, str): + issues.append( + f"Agent '{name}' in {AGENT_MAP_FILE} has no 'root', so there is nowhere to read its settings and prompts " + 'from. Write it as root = "relative/path/to/the/agent".' + ) + return issues, warnings, notices + + root = (image_root / declared_root).resolve() + if not root.is_relative_to(image_root): + issues.append(f"Agent '{name}' has root '{declared_root}', which is outside the image.") + return issues, warnings, notices + if not root.is_dir(): + issues.append( + f"Agent '{name}' has root '{declared_root}', and {root} is not a directory. Either the agent moved and " + f"{AGENT_MAP_FILE} did not, or the path is a typo." + ) + return issues, warnings, notices + if root in claimed: + issues.append(f"Agents '{claimed[root]}' and '{name}' share the root {declared_root}; they would read each other's files.") + return issues, warnings, notices + claimed[root] = name + + for misplaced in check_agent_layout(root, image_root): + issues.append(misplaced.describe(name)) + + if not (root / "src").is_dir(): + warnings.append(f"Agent '{name}' has no 'src' directory at {declared_root}. An agent is the same shape alone or in a group.") + + settings = root / "settings.toml" + if settings.is_file(): + print(f"[ok] {name}: settings from {declared_root}/settings.toml") + warnings.extend(_process_key_warnings(name, settings)) + else: + print(f"[--] {name}: no settings.toml of its own; it reads the image's") + + if root != image_root and root.name != name: + notices.append( + f"Agent '{name}' lives in a directory named '{root.name}'. Nothing breaks, but 'asbs dev' in that " + f"directory serves it as '{root.name}' unless --name says otherwise, so its routes differ between " + "development and this image." + ) + + return issues, warnings, notices + + +def _process_key_warnings(name: str, settings: Path) -> list[str]: + """Report process-wide keys set in an agent's own settings file. + + They are dropped before the merge at runtime rather than obeyed, so this is the difference + between a key that does nothing and a key somebody believes in. + """ + try: + document = tomllib.loads(settings.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError) as exc: + return [f"Agent '{name}' has a settings.toml that could not be read: {exc}"] + + found: set[str] = set() + for key, value in document.items(): + if isinstance(value, dict): + found.update(str(inner).lower() for inner in value if str(inner).lower() in PROCESS_SCOPE_KEYS) + elif str(key).lower() in PROCESS_SCOPE_KEYS: + found.add(str(key).lower()) + + if not found: + return [] + return [ + f"Agent '{name}' sets process-wide key(s) in its own settings.toml: {', '.join(sorted(found))}. One process " + "has one of each, so these are dropped before the merge and the image's settings.toml decides. Move them " + "there, or remove them." + ] + + +def _report(issues: list[str], warnings: list[str], notices: list[str]) -> None: + """Print the three grades, worst first.""" + for label, entries in (("Issues", issues), ("Warnings", warnings), ("Notices", notices)): + if not entries: + continue + print() + print(f"{label}:") + for entry in entries: + print(f" - {entry}") + + print() + if issues: + print(f"Not valid: {len(issues)} issue(s) would stop this image starting.") + elif warnings: + print(f"Valid, with {len(warnings)} warning(s).") + else: + print("Valid.") diff --git a/src/blueprint/agent_generator/cli/main.py b/src/blueprint/agent_generator/cli/main.py index d05086de..dc66c72f 100644 --- a/src/blueprint/agent_generator/cli/main.py +++ b/src/blueprint/agent_generator/cli/main.py @@ -58,7 +58,15 @@ def main() -> None: ) setup_parser.add_argument( "project_name", - help="This agent's name: its app_name, its namespace in agents.toml and its class prefix (e.g. 'invoice-processor')", + nargs="?", + help="This agent's name: its app_name, the namespace it is mapped under and its class prefix " + "(e.g. 'invoice-processor'). Omitted with --group, which creates no agent.", + ) + setup_parser.add_argument( + "--group", + action="store_true", + help="Create the image's files instead of an agent: an empty agent map, the process settings and a " + "group Dockerfile. Run it at the top of the repository, then create each agent in its own directory.", ) setup_parser.add_argument( "--output-dir", @@ -169,7 +177,12 @@ def main() -> None: "project_dir", nargs="?", default=".", - help="Project directory to validate (default: current directory)", + help="Directory to validate (default: current directory)", + ) + validate_parser.add_argument( + "--group", + action="store_true", + help="Validate an image rather than a single agent: the agent map, and every agent it points at.", ) # Dev command @@ -178,6 +191,11 @@ def main() -> None: help="Start development server", description="Run this project's agents with hot reload, under the namespaces they deploy under", ) + dev_parser.add_argument( + "--name", + help="The name to serve a single agent under (default: this directory's name). An agent " + "directory carries no agent map, so the name comes from whoever hosts it.", + ) dev_parser.add_argument( "--agents", help="Comma-separated agents to host (default: every agent in agents.toml)", diff --git a/src/blueprint/agent_generator/docs/concepts/configuration.md b/src/blueprint/agent_generator/docs/concepts/configuration.md index 94591ec3..96f4538b 100644 --- a/src/blueprint/agent_generator/docs/concepts/configuration.md +++ b/src/blueprint/agent_generator/docs/concepts/configuration.md @@ -233,3 +233,51 @@ size_limit = 1073741824 eviction_policy = "least-recently-used" default_ttl = 3600 ``` + +--- + +## Where an agent's settings file lives + +**Beside `src/`, in the agent's own directory.** The same place whether the agent runs alone or +as one of twenty -- that sameness is what lets the directory move between its own repository +and a group image untouched. + +``` +my_agent/ + settings.toml <- here + .secrets.toml + src/ + main.py + prompts/ +``` + +In a group, the image's `agents.toml` states that directory with `root`, and the file is merged +under the agent's own scope -- so the agent keeps writing plain keys and never learns that a +scope exists. It is **stated, never derived**: a root guessed from where the declaration module +happens to sit is right for one layout and silently wrong for every other, and an agent whose +settings file was looked for in the wrong place does not fail. It runs on the group's defaults +and says nothing. + +A `settings.toml` inside `src/` is **refused**, not ignored, for that reason. + +### Keys an agent cannot set + +Some keys describe the *process*, and one process has one of each: `app_port`, `app_host`, +`app_workers`, `app_environment`, `envvar_prefix`, `event_bus`, `log_level`, `log_format`, +`suppress_noisy_loggers`, `health_check_interval_seconds`, `readiness_policy`, +`nats_stream_name`. + +They belong in the image's own `settings.toml`, beside `agents.toml`. Set in an agent's file +they are dropped before the merge, with a warning naming the value the process uses instead -- +dropped rather than obeyed, because merging them under an agent's scope would file them where +nothing reads them. `asbs validate --group` reports them without starting anything. + +A standalone agent is its own image, so its directory is both and the distinction does not +arise -- which is why the scaffolded `settings.toml` carries those keys commented out rather +than absent. + +### Prompts + +Resolved under the same root: `/src/prompts` and `/prompts`. Before `root` was +stated, they resolved against the *process* working directory -- one directory for a whole +group, and therefore right for at most one agent. diff --git a/src/blueprint/agent_generator/docs/guides/cli/dev.md b/src/blueprint/agent_generator/docs/guides/cli/dev.md index 587b0b9d..c39e2b7a 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/dev.md +++ b/src/blueprint/agent_generator/docs/guides/cli/dev.md @@ -38,3 +38,27 @@ INFO: Started reloader process ``` The development server watches for file changes in the `src/` directory and automatically restarts when modifications are detected. + +--- + +## Running a single agent + +An agent directory carries no `agents.toml`, so there is nothing there to name it. `asbs dev` +supplies the name instead -- from `--name`, or the directory's own name: + +```bash +cd agents/some_topic/my_agent +asbs dev # serves it as "my_agent" +asbs dev --name orders # serves it as "orders" +``` + +The map it needs is written outside the project for that run and removed afterwards. Nothing is +created in the agent's directory: an `agents.toml` left behind there is exactly the file an +agent must not carry. + +The name decides the route prefix, so `/api/my_agent/...` here and `/api//...` in a +group image. If they differ, development and production differ -- `asbs validate --group` says +so when a map key does not match its directory name. + +Where an `agents.toml` *is* present -- an image's directory -- `asbs dev` hosts the agents it +names, as before. diff --git a/src/blueprint/agent_generator/docs/guides/cli/setup.md b/src/blueprint/agent_generator/docs/guides/cli/setup.md index f122f0e4..24be04fc 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/setup.md +++ b/src/blueprint/agent_generator/docs/guides/cli/setup.md @@ -34,7 +34,6 @@ agent's namespace is that name in snake case (`order_processor`). models// # dto.py, domain_models.py, mapper.py prompts/ services/ - agents.toml # agent name -> declaration; baked into the image settings.toml .secrets.toml # git-ignored .secrets.toml.example # committed, so the keys to fill in are known @@ -42,9 +41,14 @@ agent's namespace is that name in snake case (`order_processor`). .gitignore ``` -There is no `tests/` directory and no `pyproject.toml`: the scaffolder writes source, settings and -the image, and the packaging and test layout are the project's own. `asbs validate` reports both as -missing, which is a reminder rather than a defect in the scaffold. +There is no `agents.toml`. The agent map says which agents an *image* contains, which is a +packaging decision -- an agent that carried one would be an agent that knows whether it is running +alone. The generated `Dockerfile` writes a one-agent map into its own image; a group image maps it +in the repository's `agents.toml`; `asbs dev` supplies the name from the directory. `asbs validate +--group` refuses one found inside an agent. + +A `pyproject.toml` is written only if the directory has none: `asbs` runs from the project's own +environment, so by then there is usually one already, with somebody's dependencies in it. ## Example @@ -90,3 +94,39 @@ That name is the agent's identity everywhere outside the file -- the NATS queue JetStream durable name, the cache partition, the OpenTelemetry `service.name` and the `/api/` route prefix -- so changing it after the first deploy is a consumer migration. The project is run with `python -m blueprint.agents.entrypoint`, which reads that map and the deployment's group. + +--- + +## asbs setup --group + +The other mode. It writes the *image's* files and creates no agent: + +```bash +asbs setup --group +``` + +``` +agents.toml # empty: this image contains no agents yet +settings.toml # the process: app_port, app_host, event_bus, log_level +Dockerfile # the group image +.gitignore +``` + +No agent is created and none is named, because which agents an image contains is decided one +`asbs setup ` at a time, in whatever directories suit the repository. An image with no +agents cannot start -- the process refuses rather than binding a port and consuming nothing -- +so add an entry per agent before deploying it: + +```bash +mkdir -p agents/some_topic/my_agent +cd agents/some_topic/my_agent +asbs setup my_agent +``` + +```toml +[agents.my_agent] +root = "agents/some_topic/my_agent" +module = "agents.some_topic.my_agent.src.main:agent" +``` + +Both keys are required. See [Multi-Agent Setup](../multi-agent-setup.md). diff --git a/src/blueprint/agent_generator/docs/guides/cli/validate.md b/src/blueprint/agent_generator/docs/guides/cli/validate.md index b6061c54..a7995bad 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/validate.md +++ b/src/blueprint/agent_generator/docs/guides/cli/validate.md @@ -63,3 +63,30 @@ Notices (1): arrives as an event on '.scheduler.', published by an external CronJob. ... ``` + +--- + +## asbs validate --group + +Validates an *image* rather than a single agent: the agent map, and every agent directory it +points at. Run it where `agents.toml` is. + +```bash +asbs validate --group +``` + +It checks, per agent: + +- `root` and `module` are both present -- neither is derived from the other +- `root` resolves to a directory, inside the image, not shared with another agent +- no file sits where the framework will not read it (a `settings.toml` under `src/`, an + `agents.toml` inside an agent) +- which `settings.toml` each agent actually reads, printed, so "is it picking mine up?" is + answerable without starting the process +- process-wide keys left in an agent's settings, which are dropped before the merge +- whether the map key matches the directory name, since `asbs dev` defaults to the latter + +Exit status is 1 when anything would stop the image starting, 0 otherwise. + +Most of these were, until recently, things the process did silently: none of them stops a pod +starting and passing its probes, which is what made them expensive to find. diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md index 31c582d7..17cb4a30 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md @@ -76,26 +76,60 @@ and copy the map into the image beside your settings: COPY --chown=appuser:appuser agents.toml ./ ``` -## 3. `agents.toml` -- a new file +## 3. The image's `agents.toml` -- one entry, not a new file here + +The entry goes in the **image's** map, at the top of the repository that builds the image -- +not in the agent's directory. The map says which agents an image contains, which is a packaging +decision; an agent that carried one would be an agent that knows whether it is running alone. +`asbs validate --group` refuses one found inside an agent. + +If the repository has no image files yet, create them once: + +```bash +asbs setup --group +``` + +Then add this agent: ```toml [agents.order] -module = "src.main:agent" +root = "agents/order" +module = "agents.order.src.main:agent" ``` -Required even for a group of one: it is the only thing that turns an agent's name into code. There -is discovery by convention nowhere in this, deliberately -- a set of agents that depends on what -happens to be importable makes a renamed directory a silently removed agent. +**Both keys are required.** `root` is the agent's own directory, relative to the directory +`agents.toml` is in -- the one holding its `settings.toml` and its `src/`. `module` is how its +code imports. Neither is derived from the other: a root guessed from where the declaration sits +is right for one layout and silently wrong for the rest, and an agent whose settings were looked +for in the wrong place does not fail, it runs on the group's defaults without saying so. + +Nothing inside the agent's directory moves. Its `settings.toml` stays beside `src/`, exactly +where it was when the project ran on its own -- that sameness is what lets the directory move +back out again untouched. + +Required even for a group of one: it is the only thing that turns an agent's name into code. +There is discovery by convention nowhere in this, deliberately -- a set of agents that depends +on what happens to be importable makes a renamed directory a silently removed agent. Renaming +or moving an agent directory means updating its entry here, and until you do, the process +refuses to start rather than quietly dropping the agent. + +### Process-wide keys move up + +If the project's `settings.toml` sets `app_port`, `app_host`, `app_environment`, `event_bus`, +`log_level`, `log_format` or the other keys that describe the process, they belong in the +**image's** `settings.toml` now. One process has one of each, so a copy under an agent is +dropped before the merge with a warning naming the value actually used. ## 4. Check it ```bash -asbs validate +asbs validate # inside the agent's directory: the agent itself +asbs validate --group # at the top: the map, and every agent it points at ``` -It reads the map, holds the name to the namespace alphabet, confirms the module exists and assigns -the attribute you named, and reports anything about schedulers or settings that would not survive -the move. It never imports your project. +`--group` resolves every `root`, reports which `settings.toml` each agent actually reads, refuses a +file sitting where the framework will not look for it, and names process-wide keys left in an +agent. Neither imports your project. ## One declaration, three ways to run it diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md index c90a892e..328d8e5c 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md @@ -64,19 +64,23 @@ file be served alone and be hosted beside other agents. Note that components are **classes**, not instances: a component constructed on the `with_*` line is constructed before any namespace exists and belongs to the root for ever, which is why a group refuses one. -**`agents.toml` maps the agent's name to that declaration.** +**The agent carries no `agents.toml`, and that is the point.** -```toml -[agents.order_processor] -module = "src.main:agent" -``` +The agent map says which agents an *image* contains, which is a packaging decision. An agent that +carried one would be an agent that knows whether it is running alone -- and in a group only the +image's own map is read, so the copy would be dead weight that reads as authoritative. `asbs +validate --group` refuses one found inside an agent. + +Whoever hosts the agent supplies its name: -This file is **baked into the image**: it says what the image contains. It does not say which of -those agents any particular process runs -- that is the deployment's decision, and it arrives -separately. +| Host | Where the name comes from | +|---|---| +| Its own `Dockerfile` | a one-agent map written into the image, with `root = "."` | +| A group image | an entry in the repository's `agents.toml` | +| `asbs dev` | `--name`, defaulting to the directory's name | -The `Dockerfile` runs `python -m blueprint.agents.entrypoint`, which reads `agents.toml`, works out -this process's group, and serves it. +The `Dockerfile` runs `python -m blueprint.agents.entrypoint`, which reads that map, works out this +process's group, and serves it. ### Running it @@ -98,24 +102,85 @@ docker run -e BLUEPRINT_AGENTS=order_processor -p 8000:8000 order-processor ### Adding a second agent to the same image -Put the second agent's code in its own package, give it its own declaration module and its own -`settings.toml` **beside that module**, and add it to the map: +An agent is the same directory whether it runs alone or beside twenty others, so there is no +second way to create one: you create the *image*, then create each agent inside it exactly as +you would on its own. + +At the top of the repository: + +```bash +asbs setup --group +``` + +That writes the image's files and nothing else: an empty `agents.toml`, a `settings.toml` for +the process-wide keys, and a group `Dockerfile`. No agent is created and none is named. + +Then each agent, in its own directory, at whatever depth suits the repository: + +```bash +mkdir -p agents/some_topic/order_processor +cd agents/some_topic/order_processor +asbs setup order-processor +``` + +and one entry per agent in the image's `agents.toml`: ```toml [agents.order_processor] -module = "src.order_processor.main:agent" +root = "agents/some_topic/order_processor" +module = "agents.some_topic.order_processor.src.main:agent" [agents.billing] -module = "src.billing.main:agent" +root = "agents/billing" +module = "agents.billing.src.main:agent" +``` + +**Both keys are required, and `root` is not derived from `module`.** `root` says where the +agent's files are -- its `settings.toml` and its `src/prompts` -- relative to the directory +`agents.toml` is in. `module` says how its code imports. They answer different questions and can +legitimately differ, and a root guessed from where a declaration happens to sit is right for one +layout and silently wrong for every other. An agent whose settings file was looked for in the +wrong place does not fail: it runs on the group's defaults and says nothing. + +Nesting is free. `root` is stated, so no rule has to guess how deep an agent sits. + +The resulting repository: + +``` +agents.toml # which agents this image contains +settings.toml # the process: app_port, event_bus, log_level +Dockerfile # the group image +agents/ + billing/ + settings.toml # this agent, and only this agent + .secrets.toml + Dockerfile # optional: builds this agent alone + src/ + main.py + prompts/ + some_topic/ + order_processor/ + ... +``` + +Each agent directory is exactly what `asbs setup` writes on its own, so moving one into its own +repository means deleting its line from this map -- nothing inside the directory changes. An +agent may keep its own `Dockerfile` to be built as a single-agent image at the same time. + +**Process-wide keys belong in the image's `settings.toml`:** `app_port`, `app_host`, +`app_workers`, `app_environment`, `envvar_prefix`, `event_bus`, `log_level`, `log_format`, +`readiness_policy`, `nats_stream_name` and the rest. One process binds one port, speaks one bus +and configures logging once, so a copy under an agent is dropped before the merge with a warning +naming the value actually used. `asbs validate --group` reports them. + +Check the whole image against what is on disk: + +```bash +asbs validate --group ``` -Each agent's `settings.toml` is read from the directory its declaration lives in and merged under -that agent's own scope, so both may write plain top-level keys and neither sees the other's. Keys -that describe the *process* -- `app_port`, `app_host`, `app_workers`, `app_environment`, -`envvar_prefix`, `event_bus`, `log_level`, `log_format`, `readiness_policy`, `nats_stream_name` and -the rest -- belong in the group's own settings file: one process binds one port, speaks one bus and -answers one readiness probe, so a copy under one agent's scope is read by nothing. `asbs validate` -names them if you leave them there. +It resolves every `root`, reports which `settings.toml` each agent reads, and refuses a file +that sits where the framework will not look for it. --- diff --git a/src/blueprint/agent_generator/generator/generator.py b/src/blueprint/agent_generator/generator/generator.py index f99d1f9a..080879a1 100644 --- a/src/blueprint/agent_generator/generator/generator.py +++ b/src/blueprint/agent_generator/generator/generator.py @@ -7,8 +7,8 @@ from pathlib import Path from typing import Any +from .part_generators.part_generator_base import PartGeneratorBase from .part_generators import ( - AgentMapPartGenerator, APIPartGenerator, CopyPartGenerator, DomainModelPartGenerator, @@ -338,10 +338,11 @@ def _create_files_from_templates(self) -> None: f"{self.config['agent_layer'][agent_name]['runtime_name']}_instruction.prompt", ).create_file(out) - # Create the agent map. Without it nothing can resolve this project's agent name to - # its declaration, so `python -m blueprint.agents.entrypoint` -- the image's command -- - # would refuse to start. - AgentMapPartGenerator(self.config, self.template_dir, "").create_file(out) + # No agent map here. It says which agents an *image* contains, which is a packaging + # decision, so an agent that carried one would be an agent that knows whether it is + # running alone -- and in a group only the image's own map is read, so the copy would + # be dead weight that looks authoritative. The standalone Dockerfile writes a + # one-agent map into its image; `asbs setup --group` writes the image-level one. # Create Dockerfile CopyPartGenerator( @@ -350,7 +351,7 @@ def _create_files_from_templates(self) -> None: "", "Dockerfile", "Dockerfile", - template_vars={"agent_namespace": AgentMapPartGenerator.agent_namespace(self.config)}, + template_vars={"agent_namespace": PartGeneratorBase.agent_namespace(self.config)}, ).create_file(out) # Create .gitignore diff --git a/src/blueprint/agent_generator/generator/part_generators/__init__.py b/src/blueprint/agent_generator/generator/part_generators/__init__.py index f01d9a93..b6c96144 100644 --- a/src/blueprint/agent_generator/generator/part_generators/__init__.py +++ b/src/blueprint/agent_generator/generator/part_generators/__init__.py @@ -1,5 +1,4 @@ from .main_part_generator import MainPartGenerator -from .agent_map_part_generator import AgentMapPartGenerator from .api_part_generator import APIPartGenerator from .service_part_generator import ServicePartGenerator from .init_part_generator import InitPartGenerator @@ -13,7 +12,6 @@ __all__ = [ "MainPartGenerator", - "AgentMapPartGenerator", "APIPartGenerator", "ServicePartGenerator", "InitPartGenerator", diff --git a/src/blueprint/agent_generator/generator/part_generators/agent_map_part_generator.py b/src/blueprint/agent_generator/generator/part_generators/agent_map_part_generator.py deleted file mode 100644 index 46c1519d..00000000 --- a/src/blueprint/agent_generator/generator/part_generators/agent_map_part_generator.py +++ /dev/null @@ -1,52 +0,0 @@ -from pathlib import Path -from typing import Any - -from blueprint.agents.component.namespace import validate_namespace - -from .part_generator_base import PartGeneratorBase - - -class AgentMapPartGenerator(PartGeneratorBase): - """Generate ``agents.toml``, the map from agent name to declaration. - - The framework resolves an agent name to code through this file and through nothing else -- - there is no discovery by convention, because a set of agents that depends on what happens - to be importable makes a renamed directory a silently removed agent. So a project that - does not ship one cannot be hosted by ``python -m blueprint.agents.entrypoint`` at all. - - The name is validated here rather than repaired. It becomes a namespace, and from there a - queue group, a durable name, a cache partition and a telemetry ``service.name``; a name - quietly rewritten to fit would be four different names for one agent. Refusing it at - scaffolding time is the one moment it is still free to change. - """ - - def __init__(self, config: dict[str, Any], template_dir: str | Path, src_path: str) -> None: - super().__init__(config, template_dir, src_path) - self.template_file_name = "agents_toml.txt" - self.template_vars["agent_namespace"] = self.agent_namespace(config) - - @classmethod - def agent_namespace(cls, config: dict[str, Any]) -> str: - """Return the namespace this project's agent is deployed under. - - The project name in snake case. Derived rather than asked for, because a project that - has exactly one agent has no second name to give it -- and the derivation is visible in - the generated file, which is where it can be changed before the first deploy. - - Raises: - ValueError: if the project name does not survive the derivation as a legal - namespace -- a leading digit, for instance. The generator fails rather than - writing a project that cannot start. - """ - namespace = cls.camel_to_snake(config["name"]) - try: - return validate_namespace(namespace) - except ValueError as exc: - raise ValueError( - f"Project name '{config['name']}' gives the agent namespace '{namespace}', which cannot be used: " - f"{exc} Choose a project name whose snake_case form matches [a-z][a-z0-9_]*." - ) from exc - - def to_py_file_name(self) -> str: - """The agent map is TOML, and lives at the project root.""" - return "agents.toml" diff --git a/src/blueprint/agent_generator/generator/part_generators/part_generator_base.py b/src/blueprint/agent_generator/generator/part_generators/part_generator_base.py index ed446d52..5a8277f0 100644 --- a/src/blueprint/agent_generator/generator/part_generators/part_generator_base.py +++ b/src/blueprint/agent_generator/generator/part_generators/part_generator_base.py @@ -41,6 +41,34 @@ def to_class_name(name: str) -> str: parts = re.split(r"[^a-zA-Z0-9]", name) return "".join(part[0].upper() + part[1:] if part else "" for part in parts if part) + @classmethod + def agent_namespace(cls, config: dict[str, Any]) -> str: + """Return the namespace this project's agent is deployed under. + + The project name in snake case. Derived rather than asked for, because a project that + has exactly one agent has no second name to give it. + + The agent itself never stores this: whoever hosts it supplies the name -- a group + image's agent map, a single-agent image's Dockerfile, or ``asbs dev``. It is derived + here only to write those, and to tell the author what the name will be. + + Raises: + ValueError: if the project name does not survive the derivation as a legal + namespace -- a leading digit, for instance. Refused rather than repaired: a + name rewritten differently by the queue group, the durable, the cache + partition and the telemetry resource is four names for one agent. + """ + from blueprint.agents.component.namespace import validate_namespace + + namespace = cls.camel_to_snake(config["name"]) + try: + return validate_namespace(namespace) + except ValueError as exc: + raise ValueError( + f"Project name '{config['name']}' gives the agent namespace '{namespace}', which cannot be " + f"used: {exc} Choose a project name whose snake_case form matches [a-z][a-z0-9_]*." + ) from exc + @staticmethod def camel_to_snake(name: str) -> str: """ diff --git a/src/blueprint/agents/agent_group.py b/src/blueprint/agents/agent_group.py index b39035b1..f32b6520 100644 --- a/src/blueprint/agents/agent_group.py +++ b/src/blueprint/agents/agent_group.py @@ -24,7 +24,6 @@ import importlib import logging -import sys from collections.abc import Collection, Mapping from enum import Enum from pathlib import Path @@ -36,6 +35,7 @@ from .component.namespace import namespace_scope, validate_namespace from .config import Config from .group_config import AgentSpec, GroupConfig, GroupConfigError +from .layout import check_agent_layout logger = logging.getLogger(__name__) @@ -100,6 +100,7 @@ def __init__( agents: Mapping[str, AppBuilder], *, settings: Mapping[str, Path] | None = None, + roots: Mapping[str, Path] | None = None, critical: Collection[str] | None = None, ) -> None: """Declare a group. @@ -115,9 +116,13 @@ def __init__( settings: Each agent's own settings file, keyed by the same agent name. :meth:`assemble` merges each one under that agent's scope (spec sec. 5.3), so an agent keeps writing plain keys in its own directory and never learns that a scope - exists. :meth:`from_config` derives these from the declaration modules it - imports; a group constructed literally passes them, or passes none and every - agent's settings then come from the group's own file. + exists. :meth:`from_config` takes these from each agent's stated ``root``; a group + constructed literally passes them, or passes none and every agent's settings then + come from the group's own file. + roots: Each agent's own directory, keyed by agent name. It is what the agent's + configuration view reports as its package root, so the agent's prompts are found + under its own ``src/prompts`` rather than under the process's working directory -- + which is one place for a whole group, and therefore right for at most one agent. Raises: ValueError: if an agent's name is not a legal namespace, or is the root. @@ -134,6 +139,7 @@ def __init__( ) self._agents[namespace] = builder self._settings: dict[str, Path] = {name: Path(path) for name, path in (settings or {}).items()} + self._roots: dict[str, Path] = {name: Path(path) for name, path in (roots or {}).items()} self._critical: frozenset[str] = frozenset(self._agents) if critical is None else frozenset(critical) @property @@ -151,6 +157,11 @@ def settings(self) -> Mapping[str, Path]: """Where each agent's own settings file is, for the agents that have one.""" return dict(self._settings) + @property + def roots(self) -> Mapping[str, Path]: + """Each agent's own directory, keyed by agent name.""" + return dict(self._roots) + @property def critical_agents(self) -> frozenset[str]: """The agents this deployment cannot run without.""" @@ -211,11 +222,20 @@ def from_config(cls, group: GroupConfig) -> "AgentGroup": agents: dict[str, AppBuilder] = {} settings: dict[str, Path] = {} + roots: dict[str, Path] = {} critical: set[str] = set() for spec in group.agents: builder = cls._load_declaration(spec) if builder is None: continue + + # Before the agent is hosted, not after: an agent whose files are where they cannot + # be read from would otherwise run on the group's defaults and say nothing. + misplaced = check_agent_layout(spec.root, group.image_root) + if misplaced: + cls._skip_or_raise(spec, " ".join(item.describe(spec.name) for item in misplaced)) + continue + agents[spec.name] = builder if spec.critical: # The same flag twice, deliberately. It decided above whether a failed import @@ -224,13 +244,16 @@ def from_config(cls, group: GroupConfig) -> "AgentGroup": # can run without the agent, so a second flag would be a second answer to one # question. critical.add(spec.name) + roots[spec.name] = spec.root # Only for an agent that loaded: a skipped non-critical agent has no scope to merge # anything into. - fragment = cls._settings_path(spec.module) - if fragment is not None: + fragment = spec.root / "settings.toml" + if fragment.is_file(): settings[spec.name] = fragment + else: + logger.debug("Agent '%s' ships no settings of its own (looked at %s)", spec.name, fragment) - return cls(group.name, agents, settings=settings, critical=critical) + return cls(group.name, agents, settings=settings, roots=roots, critical=critical) @staticmethod def _load_declaration(spec: AgentSpec) -> AppBuilder | None: @@ -277,31 +300,6 @@ def _load_declaration(spec: AgentSpec) -> AppBuilder | None: logger.debug("Loaded the declaration for agent '%s' from '%s'", spec.name, spec.module) return declaration - @staticmethod - def _settings_path(module_spec: str) -> Path | None: - """Return where an agent's own settings file is: beside the module that declares it. - - One rule, and it has to be one an author can see without reading this code: the - ``settings.toml`` in the same directory as the declaration module named in the agent - map. An agent is a directory of handlers, services and a declaration, and its settings - belong to that directory the same way. - - Read from ``sys.modules`` rather than by importing again, because this runs only after - :meth:`_load_declaration` has imported the module -- so the answer is the file Python - actually loaded, not one guessed from a dotted path that may resolve differently. - - Returns: - The path, or ``None`` for a module with no file at all -- a namespace package or one - built in memory, neither of which has a directory to ship settings in. - """ - module_path = module_spec.partition(":")[0] - module = sys.modules.get(module_path) - file = getattr(module, "__file__", None) - if not file: - logger.debug("Module '%s' has no file, so the agent can ship no settings of its own", module_path) - return None - return Path(file).parent / "settings.toml" - @staticmethod def _skip_or_raise(spec: AgentSpec, reason: str, cause: BaseException | None = None) -> None: """Raise for a critical agent, or log and skip a non-critical one. @@ -357,6 +355,12 @@ def assemble(self, config: Config) -> FastAPI: # every component reads its keys through its agent's scoped view during build(), so a # fragment merged afterwards would be a file that was read too late to matter. for namespace in self._agents: + # The root first: it is what the agent's view reports as its package root, and a + # view taken before it is set would keep the process's root for the rest of the + # process's life. + agent_root = self._roots.get(namespace) + if agent_root is not None: + config.set_agent_root(namespace, agent_root) path = self._settings.get(namespace) if path is not None: config.merge_agent_settings(namespace, path) diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index c7f3ae5a..416b7cf2 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -186,6 +186,7 @@ def __init__( self._validation_errors: list[str] = [] self._root_path = Path(root_path) if root_path else Path.cwd() + self._agent_roots: dict[str, Path] = {} self._agent_scope = agent_scope self._is_view = False self._views: dict[str, Config] = {} @@ -467,9 +468,41 @@ def for_namespace(self, namespace: str) -> "Config": view._is_view = True view._views = {} view._loader = self + # An agent's files are its own. Without this the view reports the *process* root, which + # is one directory for the whole group and therefore right for at most one agent -- so + # prompts resolved under it silently found a neighbour's file, or none. + agent_root = self._agent_roots.get(namespace) + if agent_root is not None: + view._root_path = agent_root self._views[namespace] = view return view + def set_agent_root(self, namespace: str, root: Path | str) -> None: + """Record where one agent's own files live, for the view that agent reads through. + + Called by :class:`~blueprint.agents.agent_group.AgentGroup` before any view is taken, + with the ``root`` that agent's entry in the agent map states. Standalone applications + never call it: there is one agent, and the process root is already its root. + + Args: + namespace: The agent the root belongs to. + root: That agent's own directory. + + Raises: + RuntimeError: if called on a view. Which directory an agent reads from is the + process's to decide, not a neighbour's. + """ + if self._is_view: + raise RuntimeError( + f"Namespace '{self._agent_scope}' tried to set an agent root. Roots come from the agent map, and are " + "applied by the group before any agent has a view." + ) + resolved = Path(root) + self._agent_roots[namespace] = resolved + cached = self._views.get(namespace) + if cached is not None: + cached._root_path = resolved + @property def agent_scope(self) -> str | None: """The namespace whose keys this object resolves first; ``None`` at the root.""" diff --git a/src/blueprint/agents/group_config.py b/src/blueprint/agents/group_config.py index 249f062b..a7691498 100644 --- a/src/blueprint/agents/group_config.py +++ b/src/blueprint/agents/group_config.py @@ -45,7 +45,7 @@ import logging import os import tomllib -from dataclasses import dataclass +from dataclasses import dataclass, field from pathlib import Path from typing import Any @@ -76,6 +76,24 @@ class GroupConfigError(Exception): """ +@dataclass(frozen=True) +class AgentMapEntry: + """One agent as the image's agent map describes it: where its code imports from, and where + its files live. + + Two fields because they answer two different questions and can legitimately disagree: + ``module`` is an import path, ``root`` a directory. An agent installed as a distribution + imports from site-packages while its settings and prompts sit in the image. + + Attributes: + module: ``"package.module:attribute"``, naming the ``AppBuilder`` that module assigns. + root: The agent's own directory, absolute, resolved against the image root. + """ + + module: str + root: Path + + @dataclass(frozen=True) class AgentSpec: """One agent this process is asked to host. @@ -88,6 +106,13 @@ class AgentSpec: module: Where the agent's ``AppBuilder`` declaration lives, as ``"module.path:attribute"``. Comes from the agent map, never from the group file: what an agent *is* belongs to the image, and only which agents run belongs to the deployment. + root: The agent's own directory, absolute. Comes from the agent map's ``root`` key and + is where the agent's ``settings.toml`` and its ``src/prompts`` are read from. Stated + rather than derived: deriving it from the declaration module's file assumed the + declaration sits one fixed level below the agent, which silently resolved to the + wrong directory for every layout that nests differently -- and a settings file that + is looked for in the wrong place is not an error, it is an agent running on the + group's defaults without saying so. critical: Whether this agent failing to load must stop the process. Defaults to ``True``, because a partially loaded group whose missing agent's queue has no consumer is a worse failure than no pod at all (spec sec. 9.1) -- the pod would pass @@ -97,6 +122,7 @@ class AgentSpec: name: str module: str + root: Path critical: bool = True @@ -114,6 +140,9 @@ class GroupConfig: broker-side identifier may derive from it, or moving an agent between groups would be visible to the broker (C1). agents: The agents to host, in the order the group declared them. + image_root: The directory the agent map was read from, which every agent's ``root`` is + relative to. Carried because a standalone agent's root *is* this directory, and the + rules about where the image's own files may sit differ in that case. Note: A group declares **no caches**. A cache belongs to the agent that declared it with @@ -125,6 +154,7 @@ class GroupConfig: name: str agents: tuple[AgentSpec, ...] + image_root: Path = field(default_factory=Path.cwd) @property def agent_names(self) -> tuple[str, ...]: @@ -173,7 +203,7 @@ def resolve(cls, config: Config, *, environ: dict[str, str] | None = None) -> "G agent_map = cls._read_agent_map(env, root) agents = cls._resolve_agents(agent_names, critical_names, agent_map, name) - group = cls(name=name, agents=tuple(agents)) + group = cls(name=name, agents=tuple(agents), image_root=root.resolve()) logger.info( "Resolved group '%s' with %d agent(s): %s", group.name, @@ -266,8 +296,8 @@ def _parse_group_file(path: Path) -> dict[str, Any]: return document @classmethod - def _read_agent_map(cls, env: dict[str, str] | Any, root: Path) -> dict[str, str]: - """Return ``{agent name: "module:attribute"}`` from the in-image agent map. + def _read_agent_map(cls, env: dict[str, str] | Any, root: Path) -> dict[str, AgentMapEntry]: + """Return ``{agent name: AgentMapEntry}`` from the in-image agent map. An explicit map rather than scanning for modules by convention. Discovery by convention makes the set of agents in an image depend on what happens to be importable, so a @@ -298,7 +328,8 @@ def _read_agent_map(cls, env: dict[str, str] | Any, root: Path) -> dict[str, str if not isinstance(agents, dict) or not agents: raise GroupConfigError(f"Agent map {path} declares no [agents.] entries, so this image contains no agents.") - resolved: dict[str, str] = {} + resolved: dict[str, AgentMapEntry] = {} + claimed: dict[Path, str] = {} for agent_name, entry in agents.items(): module = entry.get("module") if isinstance(entry, dict) else None if not module or not isinstance(module, str): @@ -306,7 +337,33 @@ def _read_agent_map(cls, env: dict[str, str] | Any, root: Path) -> dict[str, str f"Agent '{agent_name}' in {path} has no 'module', so its declaration cannot be found. Write it as " 'module = "pkg.mod:registration".' ) - resolved[str(agent_name)] = module + declared_root = entry.get("root") if isinstance(entry, dict) else None + if not declared_root or not isinstance(declared_root, str): + raise GroupConfigError( + f"Agent '{agent_name}' in {path} has no 'root', so there is nowhere to read its settings and " + 'prompts from. Write it as root = "relative/path/to/the/agent", relative to the directory this ' + "file is in. It is required rather than derived: a root guessed from the declaration module is " + "right for one layout and silently wrong for every other, and an agent reading the group's " + "defaults instead of its own settings does not announce itself." + ) + agent_root = (root / declared_root).resolve() + if not agent_root.is_relative_to(root.resolve()): + raise GroupConfigError( + f"Agent '{agent_name}' in {path} has root '{declared_root}', which resolves to {agent_root} -- " + f"outside the image root {root}. An agent's files are part of the image." + ) + if not agent_root.is_dir(): + raise GroupConfigError( + f"Agent '{agent_name}' in {path} has root '{declared_root}', and {agent_root} is not a directory. " + "Either the agent was moved and the map was not updated, or the path is a typo." + ) + if agent_root in claimed: + raise GroupConfigError( + f"Agents '{claimed[agent_root]}' and '{agent_name}' in {path} share the root {agent_root}. Two " + "agents cannot be the same directory: they would read one another's settings and prompts." + ) + claimed[agent_root] = str(agent_name) + resolved[str(agent_name)] = AgentMapEntry(module=module, root=agent_root) logger.debug("Agent map %s contains %d agent(s): %s", path, len(resolved), ", ".join(sorted(resolved))) return resolved @@ -351,7 +408,9 @@ def _split(raw: str) -> list[str]: return name, agents, critical @staticmethod - def _resolve_agents(agent_names: list[str], critical_names: set[str], agent_map: dict[str, str], group_name: str) -> list[AgentSpec]: + def _resolve_agents( + agent_names: list[str], critical_names: set[str], agent_map: dict[str, AgentMapEntry], group_name: str + ) -> list[AgentSpec]: """Turn names into specs, refusing a name the image does not contain. A name absent from the map is refused **here**, before anything is built, which is the @@ -386,8 +445,8 @@ def _resolve_agents(agent_names: list[str], critical_names: set[str], agent_map: raise GroupConfigError(f"Group '{group_name}' names an agent that cannot be a namespace: {exc}") from exc critical = name in critical_names if critical_names else True - module = agent_map.get(name) - if module is None: + entry = agent_map.get(name) + if entry is None: if critical: raise GroupConfigError( f"Group '{group_name}' names agent '{name}', which this image does not contain (it has: " @@ -400,5 +459,5 @@ def _resolve_agents(agent_names: list[str], critical_names: set[str], agent_map: group_name, ) continue - specs.append(AgentSpec(name=name, module=module, critical=critical)) + specs.append(AgentSpec(name=name, module=entry.module, root=entry.root, critical=critical)) return specs diff --git a/src/blueprint/agents/layout.py b/src/blueprint/agents/layout.py new file mode 100644 index 00000000..09994589 --- /dev/null +++ b/src/blueprint/agents/layout.py @@ -0,0 +1,121 @@ +"""Where an agent's files belong, and what it means to find one somewhere else. + +An agent is the same directory whether it runs on its own or as one of twenty, which is what +lets it move between repositories unchanged. That only holds if every artefact has exactly one +place it can be, so this module states those places once and both the runtime and ``asbs +validate`` read them from here rather than each having an opinion. + +A file in the wrong place is **refused, not ignored**. The failure this prevents is the one that +started this module: a ``settings.toml`` the framework did not look at is not an error at +startup, it is an agent quietly running on the group's defaults -- discovered later, from +behaviour, in an environment where it matters. +""" + +from dataclasses import dataclass +from pathlib import Path + +__all__ = ["MISPLACED", "MisplacedArtifact", "ExpectedArtifact", "check_agent_layout"] + + +@dataclass(frozen=True) +class ExpectedArtifact: + """One file with a single legal location, and the places that are certainly mistakes. + + Attributes: + filename: The file's name. + expected: Where it belongs, relative to the agent's root. ``""`` is the root itself; + ``None`` means it does not belong under an agent at all. + wrong: Directories relative to the agent's root where finding it is a mistake rather + than a coincidence. + reason: What goes wrong when it sits in the wrong place, in the message the author reads. + """ + + filename: str + expected: str | None + wrong: tuple[str, ...] + reason: str + + +@dataclass(frozen=True) +class MisplacedArtifact: + """One artefact found where it cannot be read from.""" + + filename: str + found_at: Path + belongs_at: Path + reason: str + + def describe(self, agent: str) -> str: + """Return the message shown for this agent, naming both paths and the consequence.""" + return ( + f"Agent '{agent}' has '{self.filename}' at {self.found_at}, and that is not where it is read from. " + f"Move it to {self.belongs_at}. {self.reason}" + ) + + +MISPLACED: tuple[ExpectedArtifact, ...] = ( + ExpectedArtifact( + filename="settings.toml", + expected="", + wrong=("src",), + reason=( + "An agent's settings sit beside its 'src', exactly as they do when it runs standalone -- that sameness " + "is what lets the directory move between a group and its own repository untouched." + ), + ), + ExpectedArtifact( + filename=".secrets.toml", + expected="", + wrong=("src",), + reason="Secrets are read from beside 'src', alongside settings.", + ), + ExpectedArtifact( + filename="agents.toml", + expected=None, + wrong=("", "src"), + reason=( + "The agent map belongs to the image, not to an agent: it says which agents an image contains, which is " + "a packaging decision. An agent that carries one is an agent that knows whether it is running alone, " + "and it is read from the image root regardless, so this copy changes nothing." + ), + ), +) +"""Every artefact with one legal location. Seeded with the three we have been bitten by; a new +entry is one tuple, and both the runtime refusal and ``asbs validate`` pick it up.""" + + +def check_agent_layout(root: Path, image_root: Path) -> list[MisplacedArtifact]: + """Return every artefact of ``root`` that is somewhere it cannot be read from. + + Args: + root: The agent's own directory, as the agent map's ``root`` names it. + image_root: The directory the agent map itself lives in. A standalone agent *is* its own + image, so the two are the same directory and the image's own files sit beside the + agent legitimately -- which is why this is a parameter rather than an assumption. + + Returns: + One entry per misplaced file, in the order :data:`MISPLACED` declares them. Empty when + the layout is right, which is the only case that starts. + """ + found: list[MisplacedArtifact] = [] + is_own_image = root.resolve() == image_root.resolve() + for artifact in MISPLACED: + for wrong in artifact.wrong: + # An image-level file at the agent's root is only misplaced when that root is not + # also the image root. Standalone, one directory wears both hats and the file is + # exactly where it belongs. + if artifact.expected is None and not wrong and is_own_image: + continue + candidate = root / wrong / artifact.filename if wrong else root / artifact.filename + if not candidate.is_file(): + continue + belongs = root / artifact.expected / artifact.filename if artifact.expected is not None else Path("the image root") + found.append( + MisplacedArtifact( + filename=artifact.filename, + found_at=candidate, + belongs_at=belongs, + reason=artifact.reason, + ) + ) + return found diff --git a/tests/unit/agent_generator/generator/test_generated_project.py b/tests/unit/agent_generator/generator/test_generated_project.py index 617b8c14..62aa53df 100644 --- a/tests/unit/agent_generator/generator/test_generated_project.py +++ b/tests/unit/agent_generator/generator/test_generated_project.py @@ -131,24 +131,40 @@ def test_it_neither_loads_configuration_nor_serves_itself(self, project: Path) - class TestTheAgentMap: - """``agents.toml`` is how the image's command finds the declaration.""" + """The map is the *image's*, so a scaffolded agent does not carry one. - def test_it_names_the_agent_and_its_declaration(self, project: Path) -> None: - document = tomllib.loads((project / "agents.toml").read_text(encoding="utf-8")) + It says which agents an image contains, which is a packaging decision -- an agent that + shipped one would be an agent that knows whether it is running alone, and in a group only + the image's own map is read. The single-agent Dockerfile writes it instead. + """ + + def test_the_agent_does_not_carry_one(self, project: Path) -> None: + assert not (project / "agents.toml").exists() + + def test_the_dockerfile_writes_one_naming_this_agent(self, project: Path) -> None: + dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") + + assert f"[agents.{AGENT_NAMESPACE}]" in dockerfile + assert 'root = "."' in dockerfile + assert 'module = "src.main:agent"' in dockerfile + + def test_the_map_the_dockerfile_writes_parses(self, project: Path) -> None: + """It is written into the image verbatim, so a typo here is a pod that will not start.""" + dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") + body = dockerfile.split("< None: """It becomes a queue group, a durable, a cache partition and a service.name.""" - document = tomllib.loads((project / "agents.toml").read_text(encoding="utf-8")) - - for name in document["agents"]: + for name in (AGENT_NAMESPACE,): assert validate_namespace(name) == name def test_the_module_it_names_is_the_one_that_declares_the_agent(self, project: Path) -> None: """The map is only useful if it resolves, and it is written by hand from here on.""" - document = tomllib.loads((project / "agents.toml").read_text(encoding="utf-8")) - module_path, _, attribute = document["agents"][AGENT_NAMESPACE]["module"].partition(":") + module_path, _, attribute = "src.main:agent".partition(":") saved_path = list(sys.path) saved_modules = {name: module for name, module in sys.modules.items() if name == "src" or name.startswith("src.")} @@ -275,11 +291,18 @@ def test_token_metrics_turn_off_from_the_file(self, project: Path, tmp_path: Pat assert config.get_observability_config().token_metrics_enabled is False - def test_the_log_level_is_the_one_the_file_states(self, project: Path, tmp_path: Path) -> None: - config = self._loaded(project, tmp_path, log_level='"WARNING"') + def test_the_process_wide_logging_keys_are_left_commented_out(self, project: Path) -> None: + """They describe the process, not this agent. + + In a group they are dropped before the merge with a warning, so a scaffolded agent that + set them would make every group it joined complain about a file the scaffolder wrote. + Commented out rather than absent, because a single-agent deployment does want them and + the agent's directory is the image there. + """ + body = (project / "settings.toml").read_text(encoding="utf-8") - assert config.get_observability_config().log_level == "WARNING" - assert config.get("log_format") == "text" + assert "# log_level = " in body + assert "# log_format = " in body def test_no_table_is_written_that_nothing_reads(self, project: Path) -> None: """The framework reads these four flat. A section of the same name is dead weight that @@ -315,11 +338,20 @@ def built(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Fast monkeypatch.chdir(project) sys.path.insert(0, str(project)) + # The map is the image's file, written by the Dockerfile rather than shipped in the + # agent -- so the fixture writes what that Dockerfile writes, which is also what makes + # this the shape the container actually runs. + map_file = project / "agents.toml" + map_file.write_text( + f'[agents.{AGENT_NAMESPACE}]{chr(10)}root = "."{chr(10)}module = "src.main:agent"{chr(10)}', + encoding="utf-8", + ) try: app, _ = build_group_app(environ={"BLUEPRINT_AGENTS": AGENT_NAMESPACE, "BLUEPRINT_GROUP": "test"}) yield app finally: Component.reset_shared_state() + map_file.unlink(missing_ok=True) for name in [name for name in sys.modules if name == "src" or name.startswith("src.")]: del sys.modules[name] sys.modules.update(saved_modules) @@ -394,7 +426,7 @@ def test_the_command_is_the_framework_entry_point(self, project: Path) -> None: def test_the_agent_map_is_in_the_image(self, project: Path) -> None: dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") - assert "COPY --chown=appuser:appuser agents.toml ./" in dockerfile + assert "< None: """One image serves every group; the group arrives at container start.""" @@ -415,7 +447,7 @@ class TestAnUnusableProjectNameIsRefused: """A name that cannot be a namespace fails the generator rather than the deployment.""" def test_a_leading_digit_is_refused_with_the_reason(self) -> None: - from blueprint.agent_generator.generator.part_generators import AgentMapPartGenerator + from blueprint.agent_generator.generator.part_generators.part_generator_base import PartGeneratorBase with pytest.raises(ValueError, match="cannot be used"): - AgentMapPartGenerator.agent_namespace({"name": "2ndAgent"}) + PartGeneratorBase.agent_namespace({"name": "2ndAgent"}) diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index fbcf0a91..7363f02a 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -149,7 +149,6 @@ async def test_close_clears_client_references(self, connected_nats_client: NATSC assert connected_nats_client._js is None async def test_close_cancels_retry_task(self, nats_client: NATSClient) -> None: - async def _never() -> None: await asyncio.sleep(9999) diff --git a/tests/unit/agents/conftest.py b/tests/unit/agents/conftest.py index 4d0388f4..06e47d21 100644 --- a/tests/unit/agents/conftest.py +++ b/tests/unit/agents/conftest.py @@ -9,6 +9,9 @@ def mock_prompt_loader(request): """Mock PromptLoader.load_prompt to avoid file I/O in tests, except for PromptLoader tests and test_build_requires_system_prompt.""" skip_nodes = ( "test_prompt_loader", + # Whether a prompt resolves under the right agent's root is the thing under test there, + # so a loader that answers "Test prompt" from anywhere would assert nothing. + "test_agent_files", "test_build_requires_system_prompt", "test_build_resolves_prompt_from_config", "test_build_constructs_runtime_with_full_configuration", diff --git a/tests/unit/agents/test_agent_files.py b/tests/unit/agents/test_agent_files.py new file mode 100644 index 00000000..1d76de7a --- /dev/null +++ b/tests/unit/agents/test_agent_files.py @@ -0,0 +1,268 @@ +"""An agent's own files, read from the root its entry in the agent map states. + +These cases build real directories and import real modules, because both bugs they pin down were +invisible to a test that stated paths instead of creating them: + +- the group looked for an agent's ``settings.toml`` beside its *declaration module* -- inside + ``src/`` -- while every scaffolded project writes it beside ``src/``. The file was simply never + read, and an agent silently ran on the group's defaults. +- prompts resolved against the *process* working directory, which is one directory for a whole + group and therefore right for at most one agent. The others found nothing, or found a + neighbour's prompt of the same name. + +Both were failures of inference: a root derived from where the declaration happened to sit is +right for one layout and quietly wrong for the rest. The root is now stated in the map, and these +tests hold it to being stated -- including at a nesting depth no derivation rule would have +guessed. +""" + +import sys +import textwrap +from collections.abc import Generator +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest + +from blueprint.agents.agent.prompt_loader import PromptLoader +from blueprint.agents.agent_group import AgentGroup +from blueprint.agents.component.component import Component +from blueprint.agents.config import Config +from blueprint.agents.group_config import GroupConfig, GroupConfigError + +DECLARATION = "from blueprint.agents.app_builder import AppBuilder\nagent = AppBuilder()\n" + + +@pytest.fixture(autouse=True) +def reset_component_state() -> Generator[None]: + with patch( + "blueprint.agents.component.registry.CorrelationContextProvider.get_correlation_context", + return_value=MagicMock(), + ): + yield + Component.reset_shared_state() + + +@pytest.fixture +def image(tmp_path: Path) -> Generator[Path]: + """An image root on ``sys.path``, cleaned up so modules do not leak between tests.""" + sys.path.insert(0, str(tmp_path)) + before = set(sys.modules) + yield tmp_path.resolve() + sys.path.remove(str(tmp_path)) + for name in set(sys.modules) - before: + del sys.modules[name] + + +def make_agent(image: Path, relative: str, *, prompt: str | None = None, settings: str | None = None) -> Path: + """Create one agent directory in the shape ``asbs setup`` writes, and return its root.""" + root = image / relative + (root / "src" / "prompts").mkdir(parents=True) + (root / "src" / "__init__.py").write_text("", encoding="utf-8") + (root / "src" / "main.py").write_text(DECLARATION, encoding="utf-8") + if settings is not None: + (root / "settings.toml").write_text(settings, encoding="utf-8") + if prompt is not None: + (root / "src" / "prompts" / "system.prompt").write_text(prompt, encoding="utf-8") + return root + + +def write_map(image: Path, entries: str) -> None: + (image / "agents.toml").write_text(textwrap.dedent(entries), encoding="utf-8") + + +def process_config(image: Path) -> Config: + (image / "settings.toml").write_text( + '[development]\napp_environment = "development"\napp_name = "the-process"\napp_port = 8000\n', + encoding="utf-8", + ) + return Config(settings_files=[str(image / "settings.toml")], root_path=str(image)) + + +def resolve(image: Path, agents: str) -> AgentGroup: + config = process_config(image) + return AgentGroup.from_config(GroupConfig.resolve(config, environ={"BLUEPRINT_AGENTS": agents})) + + +class TestEachAgentReadsItsOwnFiles: + """Two agents at different depths, neither of which a positional rule would have found.""" + + @pytest.fixture + def two_agents(self, image: Path) -> Path: + make_agent(image, "agents/some_topic/alpha", prompt="ALPHA PROMPT", settings='model_name = "alpha-model"') + make_agent(image, "services/beta", prompt="BETA PROMPT", settings='model_name = "beta-model"') + write_map( + image, + """ + [agents.alpha] + root = "agents/some_topic/alpha" + module = "agents.some_topic.alpha.src.main:agent" + + [agents.beta] + root = "services/beta" + module = "services.beta.src.main:agent" + """, + ) + return image + + def test_settings_come_from_the_stated_root(self, two_agents: Path) -> None: + group = resolve(two_agents, "alpha,beta") + + assert group.settings["alpha"] == two_agents / "agents/some_topic/alpha/settings.toml" + assert group.settings["beta"] == two_agents / "services/beta/settings.toml" + + def test_each_agent_reads_its_own_settings(self, two_agents: Path) -> None: + config = process_config(two_agents) + group = AgentGroup.from_config(GroupConfig.resolve(config, environ={"BLUEPRINT_AGENTS": "alpha,beta"})) + group.assemble(config) + + assert config.for_namespace("alpha").get("model_name") == "alpha-model" + assert config.for_namespace("beta").get("model_name") == "beta-model" + + def test_each_agent_resolves_its_own_prompt(self, two_agents: Path) -> None: + """The failure this prevents is a prompt that resolves to the neighbour's file.""" + config = process_config(two_agents) + group = AgentGroup.from_config(GroupConfig.resolve(config, environ={"BLUEPRINT_AGENTS": "alpha,beta"})) + group.assemble(config) + + assert PromptLoader.load_prompt("system", config.for_namespace("alpha")) == "ALPHA PROMPT" + assert PromptLoader.load_prompt("system", config.for_namespace("beta")) == "BETA PROMPT" + + def test_the_package_root_each_agent_sees_is_its_own(self, two_agents: Path) -> None: + config = process_config(two_agents) + AgentGroup.from_config(GroupConfig.resolve(config, environ={"BLUEPRINT_AGENTS": "alpha,beta"})).assemble(config) + + assert config.for_namespace("alpha").get_package_root() == two_agents / "agents/some_topic/alpha" + assert config.for_namespace("beta").get_package_root() == two_agents / "services/beta" + + +class TestStandalone: + """One agent whose root is the image root: the shape ``asbs setup`` writes.""" + + @pytest.fixture + def solo(self, image: Path) -> Path: + (image / "src" / "prompts").mkdir(parents=True) + (image / "src" / "__init__.py").write_text("", encoding="utf-8") + (image / "src" / "main.py").write_text(DECLARATION, encoding="utf-8") + (image / "src" / "prompts" / "system.prompt").write_text("SOLO PROMPT", encoding="utf-8") + write_map( + image, + """ + [agents.solo] + root = "." + module = "src.main:agent" + """, + ) + return image + + def test_it_resolves(self, solo: Path) -> None: + group = resolve(solo, "solo") + + assert group.roots["solo"] == solo + + def test_its_agent_map_is_not_treated_as_misplaced(self, solo: Path) -> None: + """Standalone, one directory is both the agent and the image, so the map belongs there.""" + config = process_config(solo) + AgentGroup.from_config(GroupConfig.resolve(config, environ={"BLUEPRINT_AGENTS": "solo"})).assemble(config) + + assert PromptLoader.load_prompt("system", config.for_namespace("solo")) == "SOLO PROMPT" + + +class TestTheMapStatesTheRoot: + """``root`` is required, and wrong values are refused rather than worked around.""" + + def test_a_missing_root_is_refused(self, image: Path) -> None: + make_agent(image, "alpha") + write_map( + image, + """ + [agents.alpha] + module = "alpha.src.main:agent" + """, + ) + + with pytest.raises(GroupConfigError, match="has no 'root'"): + resolve(image, "alpha") + + def test_a_root_that_is_not_there_is_refused(self, image: Path) -> None: + write_map( + image, + """ + [agents.alpha] + root = "nowhere" + module = "alpha.src.main:agent" + """, + ) + + with pytest.raises(GroupConfigError, match="is not a directory"): + resolve(image, "alpha") + + def test_a_root_outside_the_image_is_refused(self, image: Path) -> None: + write_map( + image, + """ + [agents.alpha] + root = "../elsewhere" + module = "alpha.src.main:agent" + """, + ) + + with pytest.raises(GroupConfigError, match="outside the image root"): + resolve(image, "alpha") + + def test_two_agents_sharing_a_root_are_refused(self, image: Path) -> None: + """They would read one another's settings and prompts.""" + make_agent(image, "shared") + write_map( + image, + """ + [agents.alpha] + root = "shared" + module = "shared.src.main:agent" + + [agents.beta] + root = "shared" + module = "shared.src.main:agent" + """, + ) + + with pytest.raises(GroupConfigError, match="share the root"): + resolve(image, "alpha,beta") + + +class TestMisplacedFilesAreRefused: + """A file the framework will not read is refused, never ignored. + + Ignoring it is what the original defect did: the settings file was there, looked correct, and + was never opened -- so the agent ran on the group's defaults and nothing said so. + """ + + def test_settings_inside_src_is_refused(self, image: Path) -> None: + root = make_agent(image, "alpha", prompt="P") + (root / "src" / "settings.toml").write_text('model_name = "wrong-place"', encoding="utf-8") + write_map( + image, + """ + [agents.alpha] + root = "alpha" + module = "alpha.src.main:agent" + """, + ) + + with pytest.raises(GroupConfigError, match="settings.toml"): + resolve(image, "alpha") + + def test_an_agent_map_inside_a_grouped_agent_is_refused(self, image: Path) -> None: + root = make_agent(image, "alpha", prompt="P") + (root / "agents.toml").write_text('[agents.alpha]\nroot = "."\nmodule = "src.main:agent"\n', encoding="utf-8") + write_map( + image, + """ + [agents.alpha] + root = "alpha" + module = "alpha.src.main:agent" + """, + ) + + with pytest.raises(GroupConfigError, match="belongs to the image"): + resolve(image, "alpha") diff --git a/tests/unit/agents/test_agent_group.py b/tests/unit/agents/test_agent_group.py index 3522711d..1c91e75a 100644 --- a/tests/unit/agents/test_agent_group.py +++ b/tests/unit/agents/test_agent_group.py @@ -85,8 +85,14 @@ def config(tmp_path: Path) -> Config: return Config(settings_files=[str(settings)], root_path=str(tmp_path)) -def spec(name: str, attribute: str, *, critical: bool = True) -> AgentSpec: - return AgentSpec(name=name, module=f"{_THIS}:{attribute}", critical=critical) +def spec(name: str, attribute: str, *, critical: bool = True, root: Path | None = None) -> AgentSpec: + """A spec for a declaration in this module. + + ``root`` is where the agent's own files would be. These cases are about composition rather + than about files, so it defaults to a directory that does not exist: nothing is read from it, + and an agent that ships no settings is the ordinary case. + """ + return AgentSpec(name=name, module=f"{_THIS}:{attribute}", root=root or Path("agents") / name, critical=critical) def component_names() -> list[str]: @@ -283,13 +289,17 @@ def test_a_health_checker_is_carried_over(self, config: Config) -> None: class TestLoadingADeclaration: def test_a_missing_module_fails_a_critical_agent(self) -> None: - group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module="no.such.module:declaration"),)) + group = GroupConfig( + name="finance", agents=(AgentSpec(name="order", module="no.such.module:declaration", root=Path("agents") / "order"),) + ) with pytest.raises(GroupConfigError, match="could not be loaded and is critical"): AgentGroup.from_config(group) def test_the_failure_names_the_agent_and_the_module(self) -> None: - group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module="no.such.module:declaration"),)) + group = GroupConfig( + name="finance", agents=(AgentSpec(name="order", module="no.such.module:declaration", root=Path("agents") / "order"),) + ) with pytest.raises(GroupConfigError, match=r"'order'.*no\.such\.module"): AgentGroup.from_config(group) @@ -304,7 +314,7 @@ def test_an_attribute_that_is_not_a_builder_is_refused(self) -> None: @pytest.mark.parametrize("module", ["no_colon_at_all", ":declaration", "module.path:"]) def test_a_malformed_declaration_path_is_refused(self, module: str) -> None: - group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module=module),)) + group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module=module, root=Path("agents") / "order"),)) with pytest.raises(GroupConfigError, match="is not a valid declaration path"): AgentGroup.from_config(group) @@ -314,7 +324,7 @@ def test_a_non_critical_agent_is_skipped(self, caplog: pytest.LogCaptureFixture) group = GroupConfig( name="finance", agents=( - AgentSpec(name="order", module="no.such.module:declaration", critical=False), + AgentSpec(name="order", module="no.such.module:declaration", root=Path("agents") / "order", critical=False), spec("billing", "billing_declaration"), ), ) @@ -329,7 +339,7 @@ def test_a_skipped_agent_does_not_stop_the_ones_after_it(self, config: Config) - group = GroupConfig( name="finance", agents=( - AgentSpec(name="order", module="no.such.module:declaration", critical=False), + AgentSpec(name="order", module="no.such.module:declaration", root=Path("agents") / "order", critical=False), spec("billing", "billing_declaration"), ), ) @@ -342,7 +352,10 @@ def test_a_critical_agent_stops_resolution_before_later_ones(self, config: Confi """There is no partial build to unwind, so it fails rather than half-wiring the group.""" group = GroupConfig( name="finance", - agents=(AgentSpec(name="order", module="no.such.module:declaration"), spec("billing", "billing_declaration")), + agents=( + AgentSpec(name="order", module="no.such.module:declaration", root=Path("agents") / "order"), + spec("billing", "billing_declaration"), + ), ) with pytest.raises(GroupConfigError): @@ -369,7 +382,8 @@ def test_a_group_can_be_constructed_literally(self, config: Config) -> None: class TestResolve: def test_it_resolves_and_loads_in_one_call(self, tmp_path: Path) -> None: - (tmp_path / "agents.toml").write_text(f'[agents.order]\nmodule = "{_THIS}:order_declaration"\n') + (tmp_path / "order").mkdir(exist_ok=True) + (tmp_path / "agents.toml").write_text(f'[agents.order]\nroot = "order"\nmodule = "{_THIS}:order_declaration"\n') settings = tmp_path / "settings.toml" settings.write_text('[development]\napp_environment = "development"\napp_port = 8000\n') config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) @@ -388,7 +402,8 @@ def test_a_resolution_failure_propagates(self, tmp_path: Path) -> None: AgentGroup.resolve(config, environ={"BLUEPRINT_AGENTS": "order"}) def test_it_returns_a_group_ready_to_assemble(self, tmp_path: Path) -> None: - (tmp_path / "agents.toml").write_text(f'[agents.order]\nmodule = "{_THIS}:order_declaration"\n') + (tmp_path / "order").mkdir(exist_ok=True) + (tmp_path / "agents.toml").write_text(f'[agents.order]\nroot = "order"\nmodule = "{_THIS}:order_declaration"\n') settings = tmp_path / "settings.toml" settings.write_text('[development]\napp_environment = "development"\napp_port = 8000\n') config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) @@ -482,17 +497,30 @@ class TestEachAgentsOwnSettings: group -- where the file is looked for, and that it is merged early enough to be read. """ - def test_the_file_is_looked_for_beside_the_declaration_module(self) -> None: - """One rule an author can see: the settings.toml in the agent's own directory.""" - group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module=f"{_THIS}:order_declaration"),)) + def test_the_file_is_read_from_the_root_the_map_states(self, tmp_path: Path) -> None: + """Stated, not derived: the agent map's ``root`` is the whole rule. + + The declaration module lives in this test package; the agent's files live in a + directory that has nothing to do with it. Deriving the one from the other is what + looked in the wrong place for every layout that nests differently. + """ + agent_root = tmp_path / "agents" / "some_topic" / "order" + agent_root.mkdir(parents=True) + (agent_root / "settings.toml").write_text('model_name = "orders-own-model"') + group = GroupConfig( + name="finance", + agents=(spec("order", "order_declaration", root=agent_root),), + image_root=tmp_path, + ) resolved = AgentGroup.from_config(group) - assert resolved.settings["order"] == Path(__file__).parent / "settings.toml" + assert resolved.settings["order"] == agent_root / "settings.toml" + assert resolved.roots["order"] == agent_root def test_an_agent_that_ships_none_is_simply_an_agent_without_settings(self, config: Config) -> None: - """This test package has no settings.toml, so the path resolves to nothing to merge.""" - group = GroupConfig(name="finance", agents=(AgentSpec(name="order", module=f"{_THIS}:order_declaration"),)) + """A root with no settings.toml in it is an agent that has none, not an error.""" + group = GroupConfig(name="finance", agents=(spec("order", "order_declaration"),)) AgentGroup.from_config(group).assemble(config) diff --git a/tests/unit/agents/test_design_rules.py b/tests/unit/agents/test_design_rules.py index 84b09315..1562ea05 100644 --- a/tests/unit/agents/test_design_rules.py +++ b/tests/unit/agents/test_design_rules.py @@ -556,7 +556,8 @@ def declare() -> None: def group_config_with_agent(name: str, tmp_path: Path, config: Config) -> Callable[[], None]: """The deployment route to the same name: an agent map and a group naming it.""" - (tmp_path / "agents.toml").write_text(f'[agents."{name}"]\nmodule = "a.module:declaration"\n') + (tmp_path / "the_agent").mkdir(exist_ok=True) + (tmp_path / "agents.toml").write_text(f'[agents."{name}"]\nroot = "the_agent"\nmodule = "a.module:declaration"\n') def resolve() -> None: GroupConfig.resolve(config, environ={"BLUEPRINT_AGENTS": name}) diff --git a/tests/unit/agents/test_entrypoint.py b/tests/unit/agents/test_entrypoint.py index a1a7e91b..9efb154c 100644 --- a/tests/unit/agents/test_entrypoint.py +++ b/tests/unit/agents/test_entrypoint.py @@ -55,7 +55,9 @@ def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: what the container's ``WORKDIR`` provides. So this fixture reproduces the container's shape rather than passing paths the real entry point has no parameter for. """ - (tmp_path / "agents.toml").write_text(f'[agents.order]\nmodule = "{_THIS}:order_declaration"\n') + (tmp_path / "order").mkdir(exist_ok=True) + (tmp_path / "billing").mkdir(exist_ok=True) + (tmp_path / "agents.toml").write_text(f'[agents.order]\nroot = "order"\nmodule = "{_THIS}:order_declaration"\n') (tmp_path / "settings.toml").write_text('[development]\napp_environment = "development"\napp_name = "the-process"\napp_port = 8000\n') monkeypatch.chdir(tmp_path) return tmp_path @@ -138,7 +140,7 @@ def test_the_message_names_what_was_wrong(self, project: Path, capsys: pytest.Ca assert "not-in-this-image" in capsys.readouterr().err def test_a_critical_agent_that_cannot_be_loaded_exits_non_zero(self, project: Path) -> None: - (project / "agents.toml").write_text('[agents.order]\nmodule = "no.such.module:registration"\n') + (project / "agents.toml").write_text('[agents.order]\nroot = "order"\nmodule = "no.such.module:registration"\n') with patch.object(entrypoint, "run_app") as run: status = entrypoint.main(environ={"BLUEPRINT_AGENTS": "order"}) @@ -192,7 +194,7 @@ def test_the_same_declaration_runs_as_a_group_of_one(self, project: Path) -> Non def test_the_same_declaration_runs_beside_another_agent(self, project: Path) -> None: (project / "agents.toml").write_text( - f'[agents.order]\nmodule = "{_THIS}:order_declaration"\n\n[agents.billing]\nmodule = "{_THIS}:order_declaration"\n' + f'[agents.order]\nroot = "order"\nmodule = "{_THIS}:order_declaration"\n\n[agents.billing]\nroot = "billing"\nmodule = "{_THIS}:order_declaration"\n' ) entrypoint.build_group_app(environ={"BLUEPRINT_AGENTS": "order,billing"}) diff --git a/tests/unit/agents/test_group_config.py b/tests/unit/agents/test_group_config.py index 2affbd29..db4945e9 100644 --- a/tests/unit/agents/test_group_config.py +++ b/tests/unit/agents/test_group_config.py @@ -18,15 +18,20 @@ AGENT_MAP = """ [agents.invoice] +root = "agents/invoice" module = "agents.invoice.declaration:registration" [agents.order] +root = "agents/order" module = "agents.order.declaration:registration" [agents.dunning] +root = "agents/dunning" module = "agents.dunning.declaration:registration" """ +AGENT_ROOTS = ("agents/invoice", "agents/order", "agents/dunning") + GROUP_FILE = """ groups: - name: finance @@ -41,6 +46,8 @@ def project(tmp_path: Path) -> Config: """A project root with an agent map, a group file and a settings tree.""" (tmp_path / "agents.toml").write_text(AGENT_MAP) + for relative in AGENT_ROOTS: + (tmp_path / relative).mkdir(parents=True) (tmp_path / "deployment-groups.yaml").write_text(GROUP_FILE) settings = tmp_path / "settings.toml" settings.write_text('[development]\napp_environment = "development"\napp_name = "the-process"\n') @@ -54,11 +61,16 @@ def test_the_named_group_is_loaded(self, project: Config) -> None: assert group.name == "finance" assert group.agent_names == ("invoice", "order") - def test_the_agents_module_comes_from_the_image(self, project: Config) -> None: + def test_the_agents_module_comes_from_the_image(self, project: Config, tmp_path: Path) -> None: """What an agent *is* belongs to the image; only which agents run is the deployment's.""" group = GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "finance"}) - assert group.agents[0] == AgentSpec(name="invoice", module="agents.invoice.declaration:registration", critical=True) + assert group.agents[0] == AgentSpec( + name="invoice", + module="agents.invoice.declaration:registration", + root=(tmp_path / "agents/invoice").resolve(), + critical=True, + ) def test_a_declared_cache_list_is_read_by_nothing(self, project: Config) -> None: """A cache belongs to the agent that declared it (D3), so a group declares none. @@ -79,6 +91,8 @@ def test_another_group_in_the_same_file(self, project: Config) -> None: def test_a_single_group_file_needs_no_group_name(self, tmp_path: Path) -> None: (tmp_path / "agents.toml").write_text(AGENT_MAP) + for relative in AGENT_ROOTS: + (tmp_path / relative).mkdir(parents=True, exist_ok=True) (tmp_path / "deployment-groups.yaml").write_text("groups:\n - name: only\n agents: [invoice]\n") settings = tmp_path / "settings.toml" settings.write_text('[development]\napp_environment = "development"\n') @@ -128,6 +142,8 @@ class TestFromTheEnvironmentAlone: def test_agents_can_come_from_the_environment_with_no_file(self, tmp_path: Path) -> None: """The docker run and CI shape: no file, no mount.""" (tmp_path / "agents.toml").write_text(AGENT_MAP) + for relative in AGENT_ROOTS: + (tmp_path / relative).mkdir(parents=True, exist_ok=True) settings = tmp_path / "settings.toml" settings.write_text('[development]\napp_environment = "development"\n') config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) @@ -149,6 +165,8 @@ def test_a_group_with_no_name_is_called_ungrouped(self, project: Config) -> None def test_no_agents_anywhere_is_an_error(self, tmp_path: Path) -> None: (tmp_path / "agents.toml").write_text(AGENT_MAP) + for relative in AGENT_ROOTS: + (tmp_path / relative).mkdir(parents=True, exist_ok=True) settings = tmp_path / "settings.toml" settings.write_text('[development]\napp_environment = "development"\n') config = Config(settings_files=[str(settings)], root_path=str(tmp_path)) @@ -264,7 +282,7 @@ def test_the_same_agent_twice_is_refused(self, project: Config) -> None: class TestTheValueObject: def test_it_performs_no_io_once_constructed(self) -> None: """Constructed literally, so a test states a composition instead of arranging files.""" - group = GroupConfig(name="finance", agents=(AgentSpec(name="invoice", module="pkg:reg"),)) + group = GroupConfig(name="finance", agents=(AgentSpec(name="invoice", module="pkg:reg", root=Path("agents/invoice")),)) assert (group.name, group.agent_names) == ("finance", ("invoice",)) From 18264c99af3a92830f7cc8c632e8330094ded6b3 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 16 Sep 2026 13:14:56 +0200 Subject: [PATCH 028/133] feat(standalone): serve one agent without declaring a group of one A standalone agent had to carry an agents.toml naming itself, because the generated image ran the group entry point -- so the file that says which agents an image contains sat inside one of them, and the misplacement rule needed an exception to allow it. A group of one is still a group. asbs setup now writes a create_app() factory beside the declaration, and the single-agent Dockerfile serves it with uvicorn: no map, no group, no namespace. The same directory is still hosted by a group image without changing a line -- the generated-project test now proves that by copying it verbatim into one -- and only then do its components gain the agent's namespace and its /api/ route prefix. With standalone no longer a group, `agents.toml` inside an agent is refused unconditionally and check_agent_layout no longer needs to know the image root. The old shape keeps working: a pre-split main.py that builds its own app is still served as src.main:app, and AppBuilder(config) built in place stays permissive. What is new is that a *declaration* built by a host -- create_app or a group -- is held to the group's rules, because an agent that works standalone only because nobody checked fails the day it joins a group. Two defects found while building the group image: - COPY agents ./agents copies every agent, which is right -- the image must hold all of them because the group config decides at startup which load. But .gitignore does not apply to a build context, so every agent's .secrets.toml went into a layer. Both scaffolds now write a .dockerignore. - the group Dockerfile installs from a pyproject.toml that `asbs setup --group` never wrote, so the image could not be built. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 24 +++++ .../agent_generator/base_files/Dockerfile | 51 ++++----- .../agent_generator/base_files/src/main.txt | 28 ++++- .../base_files/template_for_docker_ignore.txt | 53 ++++++++++ .../skills/blueprint-deployment/SKILL.md | 17 ++- .../skills/blueprint-multi-agent/SKILL.md | 15 ++- .../agent_generator/cli/commands/dev.py | 53 ++++++---- .../cli/commands/group_setup.py | 31 ++++++ .../cli/commands/validate_group.py | 2 +- .../agent_generator/docs/guides/cli/setup.md | 3 +- .../docs/guides/multi-agent-migration.md | 19 ++-- .../docs/guides/multi-agent-setup.md | 5 +- .../agent_generator/generator/generator.py | 5 + .../part_generators/main_part_generator.py | 5 +- src/blueprint/agents/agent_group.py | 16 +-- src/blueprint/agents/app_builder.py | 47 ++++++++ src/blueprint/agents/layout.py | 16 +-- .../generator/test_generated_project.py | 100 +++++++++++------- tests/unit/agents/test_agent_files.py | 29 +++-- 19 files changed, 365 insertions(+), 154 deletions(-) create mode 100644 src/blueprint/agent_generator/base_files/template_for_docker_ignore.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d12bdea..e0a752bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,24 @@ ### Added +- **A standalone agent declares nothing group-related.** `asbs setup` writes a `create_app()` + factory beside the declaration, and the generated Dockerfile serves it with + `uvicorn src.main:create_app --factory` -- no agent map, no group, no namespace. A group of one + is still a group, and requiring an agent to declare itself one in order to run alone is what put + the group's own file inside the agent. The same directory is still hosted by a group image + without changing a line; its components simply gain that agent's namespace, and with it the + `/api/` route prefix. +- **`.dockerignore`**, written by both `asbs setup` and `asbs setup --group`. Not tidy-up: the + group image copies the whole `agents/` tree, because which agents a process runs is decided at + startup rather than at build time -- and Docker's build context is the filesystem, not the + repository, so `**/.secrets.toml` being in `.gitignore` did nothing to keep real keys out of a + layer. +- **`asbs setup --group` writes a `pyproject.toml`** as well. The group Dockerfile's builder stage + installs from one, so without it the image could not be built. +- **The declaration rules apply to `create_app` too.** A component registered as an already-built + instance is refused when a *host* builds a declaration -- `create_app()` or a group -- because an + agent that works standalone only because nobody checked is an agent that fails the day it joins a + group. The older shape, `AppBuilder(config)` built in place, stays permissive and keeps working. - **`root` in the agent map**, required per agent, relative to the directory `agents.toml` is in. Stated rather than derived: a root guessed from where a declaration happens to sit is right for one layout and silently wrong for every other, and nesting an agent at any depth now costs @@ -39,6 +57,12 @@ - **`root` is required in `agents.toml`.** Every existing entry needs one line added; a map without it refuses to start rather than guessing. For an image that copied one agent to `/app`, that is `root = "."`. +- **The standalone image no longer runs the group entry point.** It serves + `src.main:create_app` directly. An existing project keeps working: `uvicorn src.main:app` is + still served for a pre-split `main.py`, and a project that wants the old command can keep it. +- **`agents.toml` inside an agent is refused unconditionally**, with no exception for an agent + mapped at the image root. That shape only existed to let a standalone agent be a group of one, + which it no longer has to be. - **`asbs setup` no longer writes `agents.toml` into an agent.** The map says which agents an *image* contains, which is a packaging decision -- an agent carrying one is an agent that knows whether it is running alone. The single-agent `Dockerfile` writes a one-agent map into its own diff --git a/src/blueprint/agent_generator/base_files/Dockerfile b/src/blueprint/agent_generator/base_files/Dockerfile index cf4eaf7a..9a143c27 100644 --- a/src/blueprint/agent_generator/base_files/Dockerfile +++ b/src/blueprint/agent_generator/base_files/Dockerfile @@ -31,16 +31,13 @@ RUN uv pip install --system --no-cache ".[dev]" ipython debugpy pytest ENV PYTHONPATH="/app/src" ENV DYNACONF_ENVIRONMENT="development" -# A development default, and only in this stage: the production image bakes no group, so -# which agents it runs stays a deployment decision. This stage expects the project to be -# bind-mounted at /app, which is also where agents.toml is read from. -ENV BLUEPRINT_AGENTS="agent_namespace" - # src/main.py declares an agent; it does not build one, so there is no `src.main:app` to -# serve. The framework's factory resolves this process's group and returns the application, -# which is what lets uvicorn reload it -- reload needs an import string, not a built object. -# BLUEPRINT_AGENTS above is a development default; a deployment sets its own. -CMD ["python", "-m", "debugpy", "--listen", "0.0.0.0:5678", "--wait-for-client", "-m", "uvicorn", "blueprint.agents.entrypoint:create_group_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--reload"] +# serve. create_app() builds the declaration with this directory's settings, and uvicorn +# reloads it because a factory is an import string rather than a built object. +# +# Nothing group-related here either: this stage expects the project bind-mounted at /app and +# serves the one agent it contains. +CMD ["python", "-m", "debugpy", "--listen", "0.0.0.0:5678", "--wait-for-client", "-m", "uvicorn", "src.main:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000", "--reload"] # ============================================================================ # Production - Minimal runtime image @@ -69,21 +66,13 @@ COPY --from=builder /usr/local/bin /usr/local/bin COPY --chown=appuser:appuser src ./src COPY --chown=appuser:appuser settings.toml ./ -# The agent map belongs to the image, not to the agent -- it says which agents an image -# contains, which is a packaging decision. So it is written here rather than copied from the -# agent's directory: the agent carries no agents.toml, and is therefore the same directory -# whether it is built alone like this or dropped into a group image that maps several. -# -# root = "." because this image contains exactly one agent and it was copied to /app. In a -# group image each agent has its own subdirectory, and root names it. +# No agent map, and no group. This image contains one agent and serves it directly through +# its own create_app() factory -- a standalone agent defines nothing group-related, because +# a group of one is a group, and an agent must not have to declare itself one to run alone. # -# The group file does NOT belong here: which of an image's agents a process runs is a -# deployment decision, so it arrives as a mount or as BLUEPRINT_AGENTS. See the ENTRYPOINT. -COPY --chown=appuser:appuser < prefix. # The disk cache backend writes here, and it cannot create this itself: WORKDIR made /app # root-owned, so mkdir() as appuser fails with EACCES. Created and handed over at build time, @@ -113,13 +102,13 @@ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ EXPOSE 8000 -# One command for every deployment. Which agents this process hosts is injected at container -# start, never baked in, so regrouping is a Deployment edit rather than a rebuild: +# This image contains one agent and serves it. There is no group to choose at container +# start, no agent map to read and no BLUEPRINT_* variable to set: # -# docker run -e BLUEPRINT_AGENTS=agent_namespace -# docker run -v ./deployment-groups.yaml:/app/deployment-groups.yaml:ro \n# -e BLUEPRINT_GROUP= +# docker run -p 8000:8000 # -# With neither, the process stops before binding the port and says which of the two is -# missing -- a crash-loop with a readable message rather than a pod that passes its probes -# while a queue goes unconsumed. -ENTRYPOINT ["python", "-m", "blueprint.agents.entrypoint"] +# Its components are built at the root namespace, so the routes are the ones the API +# declares. Hosted in a group image instead, the same directory gains an /api/ +# prefix -- that identity change happens once, on the first grouped deploy, and is what +# the migration guide covers. Nothing in this directory changes to make it. +ENTRYPOINT ["python", "-m", "uvicorn", "src.main:create_app", "--factory", "--host", "0.0.0.0", "--port", "8000"] diff --git a/src/blueprint/agent_generator/base_files/src/main.txt b/src/blueprint/agent_generator/base_files/src/main.txt index 73deb235..50d5d316 100644 --- a/src/blueprint/agent_generator/base_files/src/main.txt +++ b/src/blueprint/agent_generator/base_files/src/main.txt @@ -8,10 +8,34 @@ lets the same file be served on its own and be hosted alongside other agents in the host decides the configuration and the namespace each component is built in, and this file never mentions either. -Run it with ``python -m blueprint.agents.entrypoint``, which reads ``agents.toml`` to find -this declaration and the deployment's group to decide which agents the process hosts. +Two ways to run it, and this directory is identical in both: + +- **On its own**, which is what the generated ``Dockerfile`` does:: + + uvicorn src.main:create_app --factory + + ``create_app`` below builds this declaration with this directory's own settings. Nothing + group-related is involved: no agent map, no group file, no namespace. The components are + built at the root namespace, so the routes are the ones the API declares. + +- **As one agent of a group**, where an image's ``agents.toml`` names this module and + ``python -m blueprint.agents.entrypoint`` builds the same declaration under this agent's + namespace -- which is where the routes gain their ``/api/`` prefix. Nothing in this + directory changes to make that work; the image's map points at it. """ imports agent_declaration + + +def create_app(): + """Build this agent as an application of its own. + + Only for running it standalone. A group never calls this: it builds the declaration above + itself, once per hosted agent, inside that agent's namespace. + + Returns: + The FastAPI application, with every component built at the root namespace. + """ + return agent.build(Config(settings_files=["settings.toml", ".secrets.toml"], root_path=str(Path(__file__).parent.parent))) diff --git a/src/blueprint/agent_generator/base_files/template_for_docker_ignore.txt b/src/blueprint/agent_generator/base_files/template_for_docker_ignore.txt new file mode 100644 index 00000000..7349662e --- /dev/null +++ b/src/blueprint/agent_generator/base_files/template_for_docker_ignore.txt @@ -0,0 +1,53 @@ +# What must never reach the build context. +# +# The group image copies the whole `agents/` tree, because which agents a *process* runs is +# decided at startup rather than at build time -- so the image has to contain all of them. That +# makes this file load-bearing rather than tidy-up: a wholesale copy takes whatever is on disk. +# +# .gitignore does not help here. Docker's build context is the filesystem, not the repository, +# so a file git has never seen is copied in anyway. + +# Secrets. The single most important line in this file: real API keys live in .secrets.toml +# during development, git ignores them, and a COPY would bake them into a layer that anyone +# who can pull the image can read. Secrets reach a container as environment variables or a +# mounted file, never as a layer. +**/.secrets.toml +**/*.secrets.toml +.env +**/.env + +# Per-agent Dockerfiles. An agent may own one so it can be built as a single-agent image; it is +# not part of the group image and only invalidates layers. +agents/**/Dockerfile +agents/**/.dockerignore + +# The deployment's group file. Which agents this process runs is a deployment decision, so it +# arrives as a mount or as BLUEPRINT_AGENTS -- baking one in would make the image serve one +# group only, which is the opposite of the point. +deployment-groups.yaml +deployment-groups.yml + +# Local environments and caches, which are large, machine-specific and often not even the right +# platform. +.venv/ +venv/ +**/__pycache__/ +**/*.py[cod] +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ +**/.cache/ + +# Version control and CI +.git/ +.gitignore +.github/ + +# Tests and docs do not run in the image +**/tests/ +docs/ + +# Editor and OS noise +.idea/ +.vscode/ +.DS_Store diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md index 97500e9e..0cdbfea4 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md @@ -19,10 +19,19 @@ Stateless design. The image is the same whether it hosts one agent or ten. What differs is the command and the agent map - see `blueprint-multi-agent`. Changing the mix is an edit to a Deployment, not a rebuild. -| Shape | Command | -|---|---| -| Standalone | `uvicorn src.main:app` (or `src.main:create_app --factory` once migrated) | -| Grouped, including a group of one | `python -m blueprint.agents.entrypoint` | +| Shape | Command | Needs group config? | +|---|---|---| +| Standalone | `uvicorn src.main:create_app --factory` | no | +| Standalone, from before the split | `uvicorn src.main:app` | no | +| One agent of a group | `python -m blueprint.agents.entrypoint` | yes: an agent map and a group | + +The two images differ in what they copy, not only in how they run. The group image copies the whole +`agents/` tree -- every agent it contains, since which of them a process runs is decided at startup +-- plus `agents.toml` and the process `settings.toml`. A single-agent image copies one agent and no +map at all. + +**Both need a `.dockerignore`.** `.gitignore` does not apply to a build context, so a wholesale +`COPY agents ./agents` bakes every agent's `.secrets.toml` into a layer. `asbs setup` writes one. ## The two that break under replicas diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md index 25ee3b51..de3698bb 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md @@ -83,11 +83,16 @@ separates the parts of a durable name, so `orders-eu` on topic `created` and `or ## Three ways to run one declaration -| Shape | Command | -|---|---| -| Standalone, unmigrated | `uvicorn src.main:app` | -| Standalone, migrated (with `create_app`) | `uvicorn src.main:create_app --factory` | -| Grouped, including a group of one | `python -m blueprint.agents.entrypoint` | +| Shape | Command | Needs group config? | +|---|---|---| +| Standalone, from before the split | `uvicorn src.main:app` | no | +| Standalone | `uvicorn src.main:create_app --factory` | no | +| One agent of a group | `python -m blueprint.agents.entrypoint` | yes: an agent map and a group | + +A standalone agent declares **nothing** group-related -- no agent map, no group, no namespace. A +group of one is still a group, and an agent must not have to declare itself one to run alone. +Its components are built at the root namespace, so the routes are the ones the API declares; +hosted in a group, the same directory gains an `/api/` prefix. ## Before promising the move is free diff --git a/src/blueprint/agent_generator/cli/commands/dev.py b/src/blueprint/agent_generator/cli/commands/dev.py index 46f1b29d..31a85f6e 100644 --- a/src/blueprint/agent_generator/cli/commands/dev.py +++ b/src/blueprint/agent_generator/cli/commands/dev.py @@ -23,6 +23,7 @@ GROUP_FACTORY = "blueprint.agents.entrypoint:create_group_app" LEGACY_APP = "src.main:app" +STANDALONE_FACTORY = "src.main:create_app" AGENTS_ENV = "BLUEPRINT_AGENTS" GROUP_ENV = "BLUEPRINT_GROUP" @@ -41,25 +42,31 @@ def run(args: Namespace) -> None: args: Parsed command-line arguments """ agent_map = Path(AGENT_MAP_FILE) - if agent_map.is_file(): + entry = Path(DECLARATION_ENTRY_POINT) + requested_name = (getattr(args, "name", "") or "").strip() + + if requested_name and entry.is_file(): + # Explicitly asked for the grouped shape: serve the agent under the namespace it will + # have in an image, so the routes match production. The map is written outside the + # project -- an agents.toml left in an agent directory is the one file it must not have. + command = _group_command(args, _temporary_agent_map(args)) + elif agent_map.is_file(): command = _group_command(args, agent_map) - elif Path(DECLARATION_ENTRY_POINT).is_file() and _declares_an_agent(Path(DECLARATION_ENTRY_POINT)): - # An agent directory carries no agents.toml: the map says which agents an *image* - # contains, and an agent does not know whether it is one of several. So the map this - # run needs is written here, outside the project, rather than expected in it -- the - # framework still resolves agents through an explicit map, this one is just supplied by - # the dev server instead of committed. - agent_map = _temporary_agent_map(args) - command = _group_command(args, agent_map) - elif Path(LEGACY_ENTRY_POINT).is_file(): - # A project scaffolded before the agent map existed still builds its own application in - # src/main.py. It is served the way it always was, at the root namespace, because that - # is the namespace it is deployed under too -- the two still agree. - print(f"No {AGENT_MAP_FILE}; serving {LEGACY_APP} at the root namespace.") + elif _declares(entry, "create_app"): + # A standalone agent, served through its own factory. Nothing group-related is + # involved: no map, no group, no namespace -- a group of one is still a group, and an + # agent must not have to declare itself one to run alone. + print("Serving this agent on its own (src.main:create_app), at the root namespace.") + print("Use --name to serve it under the namespace a group image would give it.") + command = _uvicorn_command(args, STANDALONE_FACTORY, factory=True) + elif entry.is_file() and _declares(entry, "app"): + # A project from before the declaration split, which builds its own application. It is + # served the way it always was, and goes on working. + print(f"No {AGENT_MAP_FILE} and no create_app(); serving {LEGACY_APP} at the root namespace.") command = _legacy_command(args) else: - print(f"Error: neither {AGENT_MAP_FILE} nor {LEGACY_ENTRY_POINT} found", file=sys.stderr) - print("Make sure you're in a Blueprint Agents project directory", file=sys.stderr) + print(f"Error: no {AGENT_MAP_FILE}, and {DECLARATION_ENTRY_POINT} defines neither create_app nor app", file=sys.stderr) + print("Make sure you are in a Blueprint Agents project directory", file=sys.stderr) sys.exit(1) print(f"Starting development server on {args.host}:{args.port}") @@ -153,8 +160,8 @@ def _agents_in_map(agent_map: Path) -> list[str]: return [str(name) for name in agents] -def _declares_an_agent(entry_point: Path) -> bool: - """Report whether ``entry_point`` assigns a module-level ``agent``. +def _declares(entry_point: Path, name: str) -> bool: + """Report whether ``entry_point`` defines ``name`` at module level. Read rather than imported: importing it here would construct the declaration twice, once in this process and once in uvicorn's, and a declaration is not something to build for a @@ -164,10 +171,12 @@ def _declares_an_agent(entry_point: Path) -> bool: module = ast.parse(entry_point.read_text(encoding="utf-8")) except (OSError, SyntaxError): return False - return any( - isinstance(node, ast.Assign) and any(isinstance(target, ast.Name) and target.id == "agent" for target in node.targets) - for node in module.body - ) + for node in module.body: + if isinstance(node, ast.FunctionDef) and node.name == name: + return True + if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == name for t in node.targets): + return True + return False def _dev_agent_name(args: Namespace) -> str: diff --git a/src/blueprint/agent_generator/cli/commands/group_setup.py b/src/blueprint/agent_generator/cli/commands/group_setup.py index 24742549..ee6e6e95 100644 --- a/src/blueprint/agent_generator/cli/commands/group_setup.py +++ b/src/blueprint/agent_generator/cli/commands/group_setup.py @@ -43,6 +43,24 @@ """ +GROUP_PYPROJECT = """[project] +name = "agent-group" +version = "0.1.0" +description = "An image hosting several Blueprint agents" +requires-python = ">=3.13" +dependencies = [ + "avs-blueprint-agents", +] + +# One dependency set for the image. The agents are imported from this directory rather than +# installed -- their module paths in agents.toml are relative to it -- so what belongs here is +# whatever third-party packages their code needs, not the agents themselves. + +[tool.setuptools] +packages = [] +""" + + def scaffold_group(output_dir: Path, overwrite: bool) -> None: """Write the image-level files into ``output_dir``. @@ -55,6 +73,10 @@ def scaffold_group(output_dir: Path, overwrite: bool) -> None: "agents.toml": BASE_FILES / "group_agents_toml.txt", "Dockerfile": BASE_FILES / "group_Dockerfile", ".gitignore": BASE_FILES / "template_for_git_ignore.txt", + # Load-bearing, not tidy-up: the group image copies the whole agents/ tree, and Docker's + # build context is the filesystem rather than the repository -- so without this every + # agent's .secrets.toml is baked into a layer. + ".dockerignore": BASE_FILES / "template_for_docker_ignore.txt", } written: list[str] = [] @@ -67,6 +89,15 @@ def scaffold_group(output_dir: Path, overwrite: bool) -> None: target.write_text(source.read_text(encoding="utf-8"), encoding="utf-8") written.append(name) + pyproject = output_dir / "pyproject.toml" + if pyproject.exists(): + # Never written over: by the time `asbs` can run, this is usually somebody's file with + # their dependencies in it, and it is what made this tool runnable. + skipped.append("pyproject.toml") + else: + pyproject.write_text(GROUP_PYPROJECT, encoding="utf-8") + written.append("pyproject.toml") + settings = output_dir / "settings.toml" if settings.exists() and not overwrite: skipped.append("settings.toml") diff --git a/src/blueprint/agent_generator/cli/commands/validate_group.py b/src/blueprint/agent_generator/cli/commands/validate_group.py index 9c5ae839..f2c841a7 100644 --- a/src/blueprint/agent_generator/cli/commands/validate_group.py +++ b/src/blueprint/agent_generator/cli/commands/validate_group.py @@ -126,7 +126,7 @@ def _agent_findings(image_root: Path, name: str, entry: Any, claimed: dict[Path, return issues, warnings, notices claimed[root] = name - for misplaced in check_agent_layout(root, image_root): + for misplaced in check_agent_layout(root): issues.append(misplaced.describe(name)) if not (root / "src").is_dir(): diff --git a/src/blueprint/agent_generator/docs/guides/cli/setup.md b/src/blueprint/agent_generator/docs/guides/cli/setup.md index 24be04fc..61d8e70d 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/setup.md +++ b/src/blueprint/agent_generator/docs/guides/cli/setup.md @@ -93,7 +93,8 @@ module = "src.main:agent" That name is the agent's identity everywhere outside the file -- the NATS queue group, part of the JetStream durable name, the cache partition, the OpenTelemetry `service.name` and the `/api/` route prefix -- so changing it after the first deploy is a consumer migration. The project is run -with `python -m blueprint.agents.entrypoint`, which reads that map and the deployment's group. +with `uvicorn src.main:create_app --factory`, which needs no map and no group. A group image runs +`python -m blueprint.agents.entrypoint` instead, and maps this directory from its own `agents.toml`. --- diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md index 17cb4a30..61503341 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md @@ -107,7 +107,9 @@ Nothing inside the agent's directory moves. Its `settings.toml` stays beside `sr where it was when the project ran on its own -- that sameness is what lets the directory move back out again untouched. -Required even for a group of one: it is the only thing that turns an agent's name into code. +Only for a group. Running this agent on its own needs no map at all -- `uvicorn +src.main:create_app --factory` builds the declaration directly. In a group the map is the only +thing that turns an agent's name into code. There is discovery by convention nowhere in this, deliberately -- a set of agents that depends on what happens to be importable makes a renamed directory a silently removed agent. Renaming or moving an agent directory means updating its entry here, and until you do, the process @@ -133,11 +135,16 @@ agent. Neither imports your project. ## One declaration, three ways to run it -| Shape | Command | -|---|---| -| Standalone, unmigrated | `uvicorn src.main:app` | -| Standalone, migrated (with `create_app`) | `uvicorn src.main:create_app --factory` | -| Grouped, including a group of one | `python -m blueprint.agents.entrypoint` | +| Shape | Command | Needs group config? | +|---|---|---| +| Standalone, from before the split | `uvicorn src.main:app` | no | +| Standalone | `uvicorn src.main:create_app --factory` | no | +| One agent of a group | `python -m blueprint.agents.entrypoint` | yes: an agent map and a group | + +A standalone agent declares **nothing** group-related -- no agent map, no group, no namespace. A +group of one is still a group, and an agent must not have to declare itself one to run alone. +Its components are built at the root namespace, so the routes are the ones the API declares; +hosted in a group, the same directory gains an `/api/` prefix. --- diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md index 328d8e5c..b19febc4 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md @@ -79,8 +79,9 @@ Whoever hosts the agent supplies its name: | A group image | an entry in the repository's `agents.toml` | | `asbs dev` | `--name`, defaulting to the directory's name | -The `Dockerfile` runs `python -m blueprint.agents.entrypoint`, which reads that map, works out this -process's group, and serves it. +The generated `Dockerfile` runs `uvicorn src.main:create_app --factory`: one agent, served directly, +with no map and no group involved. A group image runs `python -m blueprint.agents.entrypoint` +instead, which reads that image's map, works out this process's group, and serves it. ### Running it diff --git a/src/blueprint/agent_generator/generator/generator.py b/src/blueprint/agent_generator/generator/generator.py index 080879a1..7b7eaf33 100644 --- a/src/blueprint/agent_generator/generator/generator.py +++ b/src/blueprint/agent_generator/generator/generator.py @@ -357,6 +357,11 @@ def _create_files_from_templates(self) -> None: # Create .gitignore CopyPartGenerator(self.config, self.template_dir, "", "template_for_git_ignore.txt", ".gitignore").create_file(out) + # Create .dockerignore. Not tidy-up: .secrets.toml holds real keys during development + # and git ignores it, but Docker's build context is the filesystem rather than the + # repository, so without this a COPY bakes them into a layer. + CopyPartGenerator(self.config, self.template_dir, "", "template_for_docker_ignore.txt", ".dockerignore").create_file(out) + # Create settings.toml SettingsPartGenerator(self.config, self.template_dir, "").create_file(out) diff --git a/src/blueprint/agent_generator/generator/part_generators/main_part_generator.py b/src/blueprint/agent_generator/generator/part_generators/main_part_generator.py index ee8bb398..308f3372 100644 --- a/src/blueprint/agent_generator/generator/part_generators/main_part_generator.py +++ b/src/blueprint/agent_generator/generator/part_generators/main_part_generator.py @@ -37,10 +37,13 @@ def __init__(self, config: dict[str, Any], template_dir: str | Path, src_path: s def _generate_main_imports(self) -> str: """Generate import statements for main.py.""" - lines = [] + # Path and Config are for create_app(), which serves this agent on its own: it anchors + # the settings to this directory rather than to whatever the process's cwd happens to be. + lines = ["from pathlib import Path", ""] if self.config["agent_layer"]: lines.append("from blueprint.agents.agent import AgentBuilder") lines.append("from blueprint.agents.app_builder import AppBuilder") + lines.append("from blueprint.agents.config import Config") lines.append("") diff --git a/src/blueprint/agents/agent_group.py b/src/blueprint/agents/agent_group.py index f32b6520..840bfd24 100644 --- a/src/blueprint/agents/agent_group.py +++ b/src/blueprint/agents/agent_group.py @@ -31,7 +31,7 @@ from fastapi import FastAPI -from .app_builder import AppBuilder +from .app_builder import AppBuilder, refuse_constructed_components from .component.namespace import namespace_scope, validate_namespace from .config import Config from .group_config import AgentSpec, GroupConfig, GroupConfigError @@ -231,7 +231,7 @@ def from_config(cls, group: GroupConfig) -> "AgentGroup": # Before the agent is hosted, not after: an agent whose files are where they cannot # be read from would otherwise run on the group's defaults and say nothing. - misplaced = check_agent_layout(spec.root, group.image_root) + misplaced = check_agent_layout(spec.root) if misplaced: cls._skip_or_raise(spec, " ".join(item.describe(spec.name) for item in misplaced)) continue @@ -472,14 +472,4 @@ def _refuse_what_a_group_cannot_honour(namespace: str, builder: AppBuilder) -> N "the group hands each agent its own scoped view of the process's configuration when it builds it." ) - for declaration in builder.declarations: - if not declaration.is_built: - continue - raise ValueError( - f"{type(declaration.target).__name__} was passed to with_{declaration.kind}() as an instance by " - f"agent '{namespace}', and a group cannot place it: it was constructed at that line, before the " - "group existed, so its namespace and its registry key are already the root's -- and two agents " - f"declaring one would collide on that key. Pass the class -- with_{declaration.kind}(" - f"{type(declaration.target).__name__}, ...) with its constructor arguments as keyword arguments -- " - "or a callable returning it, so the group builds it inside this agent's namespace." - ) + refuse_constructed_components(builder, namespace) diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index bbe7f43b..b196ccf3 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -139,6 +139,48 @@ def replay(self, builder: "AppBuilder") -> None: getattr(builder, f"with_{self.kind}")(*arguments, name=self.name, **self.kwargs) +def refuse_constructed_components(builder: "AppBuilder", agent: str | None = None) -> None: + """Refuse a declaration that registered an already-constructed component. + + A component built on the ``with_*`` line is constructed before its host exists, so its + namespace and registry key are the root's for ever. A group cannot place it; and a + declaration served on its own through ``create_app()`` is the same shape as one a group + hosts, so it is held to the same rule -- an agent that only works standalone because it + was never checked is an agent that fails the day it joins a group. + + The old shape -- ``AppBuilder(config)`` built in place -- is deliberately **not** subject + to this. That application constructs its own components knowing it is the only one in the + process, and it goes on working indefinitely. + + Args: + builder: The declaration to check. + agent: The agent it belongs to, when a group is asking, for the message. + + Raises: + ValueError: naming the component, the call and the fix. + """ + for declaration in builder.declarations: + if not declaration.is_built: + continue + target = type(declaration.target).__name__ + whose = f"by agent '{agent}' " if agent else "" + consequence = ( + "it was constructed at that line, before the group existed, so its namespace and its registry key " + "are already the root's -- and two agents declaring one would collide on that key." + if agent + else ( + "it was constructed at that line, before this declaration had a host, so its namespace and " + "registry key are fixed. The same declaration hosted in a group would be refused, and this " + "is the same rule applied where it is still cheap to fix." + ) + ) + raise ValueError( + f"{target} was passed to with_{declaration.kind}() as an instance {whose}-- {consequence} " + f"Pass the class -- with_{declaration.kind}({target}, ...) with its constructor arguments as " + "keyword arguments -- or a callable returning it, so it is built inside its own namespace." + ) + + class AppBuilder: """Builds the FastAPI application with a fluent interface. @@ -873,6 +915,11 @@ def build(self, config: Config | None = None) -> FastAPI: "components of the first are still in the process-wide registry, so a test doing this wants " "Component.reset_shared_state() between cases." ) + # A declaration being built by a host -- create_app(), or a group -- rather than an + # application that carries its own configuration. Same shape, same rules. + if config is not None: + refuse_constructed_components(self) + self._built = True resolved_config = self._resolve_config(config) diff --git a/src/blueprint/agents/layout.py b/src/blueprint/agents/layout.py index 09994589..5b1184c6 100644 --- a/src/blueprint/agents/layout.py +++ b/src/blueprint/agents/layout.py @@ -75,8 +75,9 @@ def describe(self, agent: str) -> str: wrong=("", "src"), reason=( "The agent map belongs to the image, not to an agent: it says which agents an image contains, which is " - "a packaging decision. An agent that carries one is an agent that knows whether it is running alone, " - "and it is read from the image root regardless, so this copy changes nothing." + "a packaging decision. An agent that carries one is an agent that knows whether it is running alone. " + "An agent served on its own needs no map at all -- 'uvicorn src.main:create_app --factory' builds this " + "declaration directly, because a group of one is still a group." ), ), ) @@ -84,28 +85,19 @@ def describe(self, agent: str) -> str: entry is one tuple, and both the runtime refusal and ``asbs validate`` pick it up.""" -def check_agent_layout(root: Path, image_root: Path) -> list[MisplacedArtifact]: +def check_agent_layout(root: Path) -> list[MisplacedArtifact]: """Return every artefact of ``root`` that is somewhere it cannot be read from. Args: root: The agent's own directory, as the agent map's ``root`` names it. - image_root: The directory the agent map itself lives in. A standalone agent *is* its own - image, so the two are the same directory and the image's own files sit beside the - agent legitimately -- which is why this is a parameter rather than an assumption. Returns: One entry per misplaced file, in the order :data:`MISPLACED` declares them. Empty when the layout is right, which is the only case that starts. """ found: list[MisplacedArtifact] = [] - is_own_image = root.resolve() == image_root.resolve() for artifact in MISPLACED: for wrong in artifact.wrong: - # An image-level file at the agent's root is only misplaced when that root is not - # also the image root. Standalone, one directory wears both hats and the file is - # exactly where it belongs. - if artifact.expected is None and not wrong and is_own_image: - continue candidate = root / wrong / artifact.filename if wrong else root / artifact.filename if not candidate.is_file(): continue diff --git a/tests/unit/agent_generator/generator/test_generated_project.py b/tests/unit/agent_generator/generator/test_generated_project.py index 62aa53df..fb2c4267 100644 --- a/tests/unit/agent_generator/generator/test_generated_project.py +++ b/tests/unit/agent_generator/generator/test_generated_project.py @@ -11,6 +11,7 @@ import importlib import json import re +import shutil import sys import tomllib from collections.abc import Iterator @@ -123,42 +124,53 @@ def test_components_are_declared_as_classes_not_instances(self, project: Path) - "the with_* line belongs to the root namespace for ever, which is why a group refuses it." ) - def test_it_neither_loads_configuration_nor_serves_itself(self, project: Path) -> None: + def test_the_declaration_itself_neither_configures_nor_builds(self, project: Path) -> None: + """The chain records; only create_app() builds, and only when serving this agent alone. + + A group never calls create_app: it builds the same declaration itself, inside the agent's + namespace. So nothing above create_app may mention configuration or build anything. + """ + source = (project / "src" / "main.py").read_text(encoding="utf-8") + declaration = source.split("def create_app()")[0] + + assert "Config(" not in declaration, "the declaration loads configuration; its host supplies that" + assert ".build(" not in declaration, "the declaration builds itself; its host builds it, in its own namespace" + + def test_it_can_serve_itself_without_a_group(self, project: Path) -> None: + """create_app is the standalone path, and it is the only place configuration appears.""" source = (project / "src" / "main.py").read_text(encoding="utf-8") - assert "Config(" not in source, "main.py loads configuration; the host supplies it, scoped to this agent." - assert ".build()" not in source, "main.py builds its application; the host builds it, inside this agent's namespace." + assert "def create_app()" in source + assert "agent.build(" in source + code = source.split('"""', 2)[-1] + assert "agents.toml" not in code, "the declaration reads an agent map; a standalone agent has none" class TestTheAgentMap: - """The map is the *image's*, so a scaffolded agent does not carry one. + """A scaffolded agent has no agent map, and its own image does not write one either. - It says which agents an image contains, which is a packaging decision -- an agent that - shipped one would be an agent that knows whether it is running alone, and in a group only - the image's own map is read. The single-agent Dockerfile writes it instead. + The map says which agents an *image* contains, which is a packaging decision. An agent + served on its own contains no group at all -- a group of one is still a group, and an agent + must not have to declare itself one to run alone. """ def test_the_agent_does_not_carry_one(self, project: Path) -> None: assert not (project / "agents.toml").exists() - def test_the_dockerfile_writes_one_naming_this_agent(self, project: Path) -> None: + def test_its_own_image_does_not_write_one(self, project: Path) -> None: dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") - assert f"[agents.{AGENT_NAMESPACE}]" in dockerfile - assert 'root = "."' in dockerfile - assert 'module = "src.main:agent"' in dockerfile + assert "agents.toml" not in dockerfile.replace("# agents.toml names this module", "") + assert "BLUEPRINT_AGENTS" not in dockerfile.replace("BLUEPRINT_* variable", "") - def test_the_map_the_dockerfile_writes_parses(self, project: Path) -> None: - """It is written into the image verbatim, so a typo here is a pod that will not start.""" + def test_it_is_served_through_its_own_factory(self, project: Path) -> None: dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") - body = dockerfile.split("< None: - """It becomes a queue group, a durable, a cache partition and a service.name.""" + """Whoever hosts it uses this name; it becomes a queue group, durable and service.name.""" for name in (AGENT_NAMESPACE,): assert validate_namespace(name) == name @@ -332,27 +344,37 @@ def built(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Fast container does by having WORKDIR /app. The registry is process-global, hence the reset. """ saved_path = list(sys.path) - saved_modules = {name: module for name, module in sys.modules.items() if name == "src" or name.startswith("src.")} + saved_modules = { + name: module for name, module in sys.modules.items() if name in ("src", "agents") or name.startswith(("src.", "agents.")) + } for name in saved_modules: del sys.modules[name] - monkeypatch.chdir(project) - sys.path.insert(0, str(project)) - # The map is the image's file, written by the Dockerfile rather than shipped in the - # agent -- so the fixture writes what that Dockerfile writes, which is also what makes - # this the shape the container actually runs. - map_file = project / "agents.toml" - map_file.write_text( - f'[agents.{AGENT_NAMESPACE}]{chr(10)}root = "."{chr(10)}module = "src.main:agent"{chr(10)}', + # A real image: the agents live in subdirectories and the map sits beside them. The + # agent directory is copied verbatim, which is the claim -- nothing in it changes to + # be hosted by a group. + image = project.parent / "image" + if image.exists(): + shutil.rmtree(image) + (image / "agents").mkdir(parents=True) + shutil.copytree(project, image / "agents" / AGENT_NAMESPACE) + (image / "agents.toml").write_text( + f'[agents.{AGENT_NAMESPACE}]{chr(10)}root = "agents/{AGENT_NAMESPACE}"{chr(10)}' + f'module = "agents.{AGENT_NAMESPACE}.src.main:agent"{chr(10)}', encoding="utf-8", ) + (image / "settings.toml").write_text((project / "settings.toml").read_text(encoding="utf-8"), encoding="utf-8") + (image / ".secrets.toml").write_text((project / ".secrets.toml").read_text(encoding="utf-8"), encoding="utf-8") + + monkeypatch.chdir(image) + sys.path.insert(0, str(image)) try: app, _ = build_group_app(environ={"BLUEPRINT_AGENTS": AGENT_NAMESPACE, "BLUEPRINT_GROUP": "test"}) yield app finally: Component.reset_shared_state() - map_file.unlink(missing_ok=True) - for name in [name for name in sys.modules if name == "src" or name.startswith("src.")]: + shutil.rmtree(image, ignore_errors=True) + for name in [n for n in sys.modules if n in ("src", "agents") or n.startswith(("src.", "agents."))]: del sys.modules[name] sys.modules.update(saved_modules) sys.path[:] = saved_path @@ -417,16 +439,20 @@ class TestTheImage: def test_the_command_is_the_framework_entry_point(self, project: Path) -> None: dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") - assert 'ENTRYPOINT ["python", "-m", "blueprint.agents.entrypoint"]' in dockerfile - assert "uvicorn" not in dockerfile.split("FROM python:3.13-slim-bookworm AS final")[1], ( - "The production stage still serves an application object. Which agents the process hosts is resolved at " - "container start, which uvicorn cannot do on its own." + final = dockerfile.split("FROM python:3.13-slim-bookworm AS final")[1] + + assert "src.main:create_app" in final + assert "--factory" in final, "create_app is a factory; uvicorn needs an import string to reload it" + assert "blueprint.agents.entrypoint" not in final, ( + "The image serves one agent through the group entry point, which makes a standalone agent declare itself a group of one." ) - def test_the_agent_map_is_in_the_image(self, project: Path) -> None: + def test_no_agent_map_is_in_the_image(self, project: Path) -> None: + """This image holds one agent and serves it; there is no group for a map to describe.""" dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") - assert "< None: """One image serves every group; the group arrives at container start.""" @@ -435,11 +461,11 @@ def test_no_group_is_baked_into_the_production_image(self, project: Path) -> Non assert "ENV BLUEPRINT_AGENTS" not in final_stage assert "BLUEPRINT_GROUP" not in final_stage.replace("BLUEPRINT_GROUP=", "") - def test_the_documented_run_command_names_the_real_agent(self, project: Path) -> None: + def test_the_documented_run_command_needs_no_group(self, project: Path) -> None: """A placeholder here is a command that looks runnable and is not.""" dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") - assert f"docker run -e BLUEPRINT_AGENTS={AGENT_NAMESPACE} " in dockerfile + assert "docker run -p 8000:8000 " in dockerfile assert "agent_namespace" not in dockerfile diff --git a/tests/unit/agents/test_agent_files.py b/tests/unit/agents/test_agent_files.py index 1d76de7a..a6f55769 100644 --- a/tests/unit/agents/test_agent_files.py +++ b/tests/unit/agents/test_agent_files.py @@ -136,15 +136,20 @@ def test_the_package_root_each_agent_sees_is_its_own(self, two_agents: Path) -> assert config.for_namespace("beta").get_package_root() == two_agents / "services/beta" -class TestStandalone: - """One agent whose root is the image root: the shape ``asbs setup`` writes.""" +class TestAStandaloneAgentIsNotAGroupOfOne: + """An agent served on its own has no map, so nothing can sit at its root claiming otherwise. - @pytest.fixture - def solo(self, image: Path) -> Path: + A group of one is still a group. Requiring an agent to declare itself one in order to run + alone put the group's own file inside the agent -- which is the thing an agent must never + carry, because carrying it is knowing whether it is running alone. Standalone is served by + the declaration's own ``create_app`` factory instead, and this rule needs no exception. + """ + + def test_an_agent_mapped_at_the_image_root_is_refused(self, image: Path) -> None: + """The old group-of-one shape: the agent flattened into the image, map beside it.""" (image / "src" / "prompts").mkdir(parents=True) (image / "src" / "__init__.py").write_text("", encoding="utf-8") (image / "src" / "main.py").write_text(DECLARATION, encoding="utf-8") - (image / "src" / "prompts" / "system.prompt").write_text("SOLO PROMPT", encoding="utf-8") write_map( image, """ @@ -153,19 +158,9 @@ def solo(self, image: Path) -> Path: module = "src.main:agent" """, ) - return image - def test_it_resolves(self, solo: Path) -> None: - group = resolve(solo, "solo") - - assert group.roots["solo"] == solo - - def test_its_agent_map_is_not_treated_as_misplaced(self, solo: Path) -> None: - """Standalone, one directory is both the agent and the image, so the map belongs there.""" - config = process_config(solo) - AgentGroup.from_config(GroupConfig.resolve(config, environ={"BLUEPRINT_AGENTS": "solo"})).assemble(config) - - assert PromptLoader.load_prompt("system", config.for_namespace("solo")) == "SOLO PROMPT" + with pytest.raises(GroupConfigError, match="belongs to the image"): + resolve(image, "solo") class TestTheMapStatesTheRoot: From 57371ba767e034c6cba4c0f38aa857c2b0e564b2 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 16 Sep 2026 14:48:29 +0200 Subject: [PATCH 029/133] fix(config): refuse an agent settings file that names its own agent An agent's settings.toml *becomes* that agent's scope when the group merges it, so a [default.] section inside it nests a second time to ..* and every key under it is read by nothing. Nothing failed at the merge. The failure arrived later and somewhere else, as "No model name for runtime agent '_agent' configured" -- a message that names the agent and says nothing about the settings file that caused it. Found migrating a real project into its first group. Refused at merge now, naming the section, what it would become and the fix, and reported by asbs validate --group before anything starts. Plain [default] serves both shapes, so there is no second file to keep: standalone resolves it because a scoped lookup falls back to the root key. Other top-level tables are left alone -- [cache] is an agent's cache configuration, not a scope. The migration guide said "nothing inside the agent's directory moves", which is true of the file's location and not of its contents; it now says so. Version bumped to 0.9.0a5: 0.9.0a4 is already on TestPyPI, and a version number cannot be reused there even after a release is deleted. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 8 ++++ pyproject.toml | 2 +- .../skills/blueprint-config/SKILL.md | 5 +++ .../skills/blueprint-multi-agent/SKILL.md | 5 +++ .../cli/commands/validate_group.py | 32 +++++++++++++++ .../docs/concepts/configuration.md | 13 ++++++ .../docs/guides/multi-agent-migration.md | 24 +++++++++++ src/blueprint/agents/config/config.py | 36 ++++++++++++++++ tests/unit/agents/test_agent_files.py | 41 ++++++++++++++++++- 9 files changed, 164 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9487d5b4..2f2c4ba6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,14 @@ ### Fixed +- **An agent settings file that scoped keys under the agent's own name merged into nothing.** + `[default.]` in that agent's own `settings.toml` nested to `..*` once the + file was merged under the agent's namespace, so every key in it was unreachable -- and the + failure surfaced far from the cause, as `No model name for runtime agent '_agent' + configured`, naming the agent rather than the file. Found migrating a real project. It is now + refused at merge, naming the section and the fix, and `asbs validate --group` reports it without + starting anything. Plain `[default]` serves both shapes: standalone resolves it because a scoped + lookup falls back to the root key. - **A grouped agent's own `settings.toml` was never read.** The group looked for it beside the *declaration module* -- inside `src/` -- while every scaffolded project writes it beside `src/`, so the file existed, looked right, and was never opened. Nothing failed: the agent ran on the diff --git a/pyproject.toml b/pyproject.toml index a9f32c48..b7a563a2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta" [project] name = "avs-blueprint-agents" -version = "0.9.0a4" +version = "0.9.0a5" description = "Microservice blueprint for creating agents" authors = [ { name = "Blueprint Team", email = "patrick.maue@bechtle.com" }, diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md index 9f8d5513..a7838e45 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md @@ -60,6 +60,11 @@ In a group the image's `agents.toml` states that directory with `root`, and proc `settings.toml`, beside `agents.toml`. Set in an agent's file they are dropped before the merge with a warning naming the value actually used. +**The file must never name its own agent.** It becomes that agent's scope when merged, so +`[default.orders]` inside the orders agent's file nests to `orders.orders.*` and nothing reads it. +Refused at merge. Use plain `[default]` -- it resolves standalone too, since a scoped lookup falls +back to the root key. + `asbs validate --group` reports all of this without starting anything. ## Reading config at runtime diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md index de3698bb..86e7f45e 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md @@ -63,6 +63,11 @@ is how its code imports. A root guessed from where the declaration sits is right silently wrong for the rest -- and an agent whose settings were looked for in the wrong place does not fail, it runs on the group's defaults and says nothing. +**Migrating an existing agent: check the file's contents, not just its place.** An agent's +`settings.toml` becomes its scope when merged, so a `[default.]` section inside it nests to +`..*` and is read by nothing -- surfacing later as a missing model name that blames +the agent, not the file. Unprefix to plain `[default]`; that serves both shapes. + Run `asbs validate --group` after editing the map. It resolves every root, reports which `settings.toml` each agent reads, and refuses a file that sits where nothing will read it. diff --git a/src/blueprint/agent_generator/cli/commands/validate_group.py b/src/blueprint/agent_generator/cli/commands/validate_group.py index f2c841a7..bd9a5173 100644 --- a/src/blueprint/agent_generator/cli/commands/validate_group.py +++ b/src/blueprint/agent_generator/cli/commands/validate_group.py @@ -135,6 +135,7 @@ def _agent_findings(image_root: Path, name: str, entry: Any, claimed: dict[Path, settings = root / "settings.toml" if settings.is_file(): print(f"[ok] {name}: settings from {declared_root}/settings.toml") + issues.extend(_self_scoped_issues(name, settings)) warnings.extend(_process_key_warnings(name, settings)) else: print(f"[--] {name}: no settings.toml of its own; it reads the image's") @@ -149,6 +150,37 @@ def _agent_findings(image_root: Path, name: str, entry: Any, claimed: dict[Path, return issues, warnings, notices +def _self_scoped_issues(name: str, settings: Path) -> list[str]: + """Report an agent settings file that scopes keys under the agent's own name. + + The file becomes that agent's scope when merged, so a ``[default.]`` section in it + nests to ``..*`` and nothing reads those keys. The runtime refuses it; this + says so without starting the process, because the symptom otherwise arrives far from the + cause -- as a missing model name, naming the agent rather than the file. + """ + try: + document = tomllib.loads(settings.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError): + return [] # reported by the caller's own read + + found = [ + f"[{section}.{key}]" + for section, value in document.items() + if isinstance(value, dict) + for key in value + if str(key).lower() == name.lower() + ] + found += [f"[{key}]" for key, value in document.items() if isinstance(value, dict) and str(key).lower() == name.lower()] + if not found: + return [] + return [ + f"Agent '{name}' scopes its own settings under its own name ({', '.join(sorted(set(found)))}). That file " + f"becomes the agent's scope when it is merged, so those keys nest as '{name}.{name}.*' and nothing reads " + "them. Write them at the top level or under a plain [default] -- which also works standalone, because a " + "scoped lookup falls back to the root key." + ] + + def _process_key_warnings(name: str, settings: Path) -> list[str]: """Report process-wide keys set in an agent's own settings file. diff --git a/src/blueprint/agent_generator/docs/concepts/configuration.md b/src/blueprint/agent_generator/docs/concepts/configuration.md index 96f4538b..e9c79a47 100644 --- a/src/blueprint/agent_generator/docs/concepts/configuration.md +++ b/src/blueprint/agent_generator/docs/concepts/configuration.md @@ -260,6 +260,19 @@ and says nothing. A `settings.toml` inside `src/` is **refused**, not ignored, for that reason. +### The file must not name its own agent + +It *becomes* that agent's scope when merged, so a section named after the agent nests twice: + +```toml +[default.orders] # in the orders agent's own file -> orders.orders.*, read by nothing +``` + +Refused at merge, and reported by `asbs validate --group`. Write the keys at the top level or under +a plain `[default]`; that form resolves standalone as well, because a scoped lookup falls back to +the root key. Other top-level tables are untouched -- `[cache]` is this agent's cache +configuration, not a scope. + ### Keys an agent cannot set Some keys describe the *process*, and one process has one of each: `app_port`, `app_host`, diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md index 61503341..5b1784f5 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md @@ -107,6 +107,30 @@ Nothing inside the agent's directory moves. Its `settings.toml` stays beside `sr where it was when the project ran on its own -- that sameness is what lets the directory move back out again untouched. +### One thing inside the file may have to change + +The location does not move; the *contents* might. This file **becomes** the agent's scope when it +is merged, so it must not scope keys itself: + +```toml +# Wrong in a group: nests to risk_identifier.risk_identifier.*, and nothing reads it +[default.risk_identifier] +model_name = "..." + +# Right, and works standalone too +[default] +model_name = "..." +``` + +A standalone project may well carry the prefixed form today, because a scoped lookup falls back to +the root key and both resolve. Once the file is merged under the agent's namespace the prefix nests +a second time and every key under it becomes unreachable -- which surfaces far from the cause, as +something like `No model name for runtime agent 'risk_identifier_agent' configured`, naming the +agent rather than the file. + +The merge refuses this outright, and `asbs validate --group` reports it without starting anything. +Unprefixing to plain `[default]` serves both shapes, so there is no second file to keep. + Only for a group. Running this agent on its own needs no map at all -- `uvicorn src.main:create_app --factory` builds the declaration directly. In a group the map is the only thing that turns an agent's name into code. diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index 416b7cf2..fb7a411a 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -615,6 +615,7 @@ def merge_agent_settings(self, namespace: str, path: str | Path) -> tuple[str, . raise ConfigError(f"The settings file of agent '{namespace}' ({resolved}) could not be read: {exc}") from exc fragment = self._layer_fragment(document) + self._refuse_self_scoped_fragment(namespace, resolved, fragment) fragment = self._drop_process_scope_keys(namespace, resolved, fragment) if not fragment: logger.debug("The settings file of agent '%s' (%s) contributes nothing", namespace, resolved) @@ -663,6 +664,41 @@ def _layer_fragment(self, document: dict[str, Any]) -> dict[str, Any]: layered.setdefault(name, values) return layered + @staticmethod + def _refuse_self_scoped_fragment(namespace: str, path: Path, fragment: dict[str, Any]) -> None: + """Refuse a fragment that already scopes its keys under the agent's own name. + + This file *becomes* the agent's scope when it is merged, so a ``[default.]`` + section inside it nests to ``..*`` and every key in it is unreachable. + + Refused rather than flattened, and refused here rather than left to surface later, + because of where the symptom appears otherwise: the merge succeeds, and the failure + arrives as something like "No model name for runtime agent 'x_agent' configured" -- + which names the agent and says nothing about the settings file that caused it. + + A standalone project may legitimately carry the prefix, because the scoped view falls + back to root keys and both shapes then resolve. Plain ``[default]`` is what serves + both, which is why the fix is to unprefix rather than to keep two files. + + Args: + namespace: The agent whose scope this fragment becomes. + path: The file, for the message. + fragment: Its keys, already layered. + + Raises: + ConfigError: naming the section, what it would become, and the fix. + """ + own = [key for key in fragment if str(key).lower() == namespace.lower()] + if not own: + return + raise ConfigError( + f"The settings file of agent '{namespace}' ({path}) scopes keys under '{own[0]}' -- its own name. " + f"This file becomes that agent's scope when it is merged, so those keys would nest as " + f"'{namespace}.{own[0]}.*' and nothing would read them. Write them at the top level, or under a " + f"plain [default] section: an agent's own file never names the agent. That form serves the project " + "standalone too, because a scoped lookup falls back to the root key." + ) + def _drop_process_scope_keys(self, namespace: str, path: Path, fragment: dict[str, Any]) -> dict[str, Any]: """Return ``fragment`` without the keys an agent cannot set, warning about each. diff --git a/tests/unit/agents/test_agent_files.py b/tests/unit/agents/test_agent_files.py index a6f55769..9491589c 100644 --- a/tests/unit/agents/test_agent_files.py +++ b/tests/unit/agents/test_agent_files.py @@ -27,7 +27,7 @@ from blueprint.agents.agent.prompt_loader import PromptLoader from blueprint.agents.agent_group import AgentGroup from blueprint.agents.component.component import Component -from blueprint.agents.config import Config +from blueprint.agents.config import Config, ConfigError from blueprint.agents.group_config import GroupConfig, GroupConfigError DECLARATION = "from blueprint.agents.app_builder import AppBuilder\nagent = AppBuilder()\n" @@ -261,3 +261,42 @@ def test_an_agent_map_inside_a_grouped_agent_is_refused(self, image: Path) -> No with pytest.raises(GroupConfigError, match="belongs to the image"): resolve(image, "alpha") + + +class TestAFragmentNeverNamesItsOwnAgent: + """An agent's settings file becomes that agent's scope, so it must not scope keys itself. + + Found in a real migration: a project whose settings.toml already carried + ``[default.risk_identifier]`` merged without complaint, nested every key to + ``risk_identifier.risk_identifier.*``, and surfaced much later as "No model name for + runtime agent 'risk_identifier_agent' configured" -- a message naming the agent and not + the file that caused it. + """ + + def test_a_section_named_after_the_agent_is_refused(self, tmp_path: Path) -> None: + config = process_config(tmp_path) + fragment = tmp_path / "agent.toml" + fragment.write_text('[default.orders]\nmodel_name = "m"\n\n', encoding="utf-8") + + with pytest.raises(ConfigError, match="its own name"): + config.merge_agent_settings("orders", fragment) + + def test_the_unprefixed_form_serves_both_shapes(self, tmp_path: Path) -> None: + """Plain [default] is the fix, and it resolves standalone too.""" + config = process_config(tmp_path) + fragment = tmp_path / "agent.toml" + fragment.write_text('[default]\nmodel_name = "m"\n\n', encoding="utf-8") + + config.merge_agent_settings("orders", fragment) + + assert config.for_namespace("orders").get("model_name") == "m" + + def test_a_table_that_is_not_the_agents_name_is_left_alone(self, tmp_path: Path) -> None: + """[cache] is this agent's cache configuration, not a scope.""" + config = process_config(tmp_path) + fragment = tmp_path / "agent.toml" + fragment.write_text('[default]\nmodel_name = "m"\n\n[cache]\nbackend = "disk"\n\n', encoding="utf-8") + + config.merge_agent_settings("orders", fragment) + + assert config.for_namespace("orders").get("model_name") == "m" From 0496ce745c46bb800927c9ad8840abe5a63cf477 Mon Sep 17 00:00:00 2001 From: oskar solich Date: Thu, 17 Sep 2026 09:18:47 +0200 Subject: [PATCH 030/133] docs(changelog): add breaking change 12 for Component.shared_config rename The public Component.shared_config -> private _shared_config rename plus Component.reset_shared_state() (landed earlier on this branch) was not among the 11 breaking changes listed in the [0.9.0] CHANGELOG entry. A consumer resetting shared state between test cases via the old attribute name silently no-ops under the rename, tripping Component.configure()'s "already set" guard from the second test onward with an error that never names the rename. Fixes #97 Co-Authored-By: Claude Sonnet 5 --- CHANGELOG.md | 11 +++++++++++ .../2026-08-28-multi-agent-grouping-changelog.md | 10 ++++++++++ 2 files changed, 21 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f2c4ba6..e9cefc06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -234,6 +234,17 @@ Full migration path, including the one decision to get right before the first de the framework's file list is untouched, so no existing deployment changes. `asbs validate` reports an undotted file as the rename it needs. An already-scaffolded project should rename its file. +12. **`Component.shared_config` is now private (`Component._shared_config`)**, with + `Component.reset_shared_state()` as the one supported way to clear it. The old attribute was + public and writable but read by nothing outside `_ComponentMeta`, so hiding it looked like + code-only cleanup. It is not: a test suite that rebuilds its `AppBuilder` app once per test case + and resets state between cases with the old `Component.shared_config = None` now silently + no-ops, since the real state lives on `_shared_config` — `Component.configure()`'s "already set" + guard then trips starting from the second test in the run, with an error that does not name this + rename. **Any project resetting shared state between test cases must switch to + `Component.reset_shared_state()`** in its fixtures; this also clears `shared_registry`, which + stays public and is otherwise unaffected. A project that never resets shared state between + builds is unaffected. ### Fixed diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 4f5e4ba2..a505c4f4 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7342,3 +7342,13 @@ keep the readable names -- nothing reads those. licence is a legal artefact and somebody's decision rather than a documentation fix. Whoever settles it removes that entry, which a guard case then requires. - **#80** -- the failing example tests and the unenforced test split. +- ~~**Breaking change #12 was missing from the list: `Component.shared_config` → + `Component._shared_config`.**~~ **Closed.** Found during a real compatibility pass against + a consuming project's test suite: its `conftest.py` reset + shared state between test cases via `Component.shared_config = None`, which is a silent no-op + under the rename described above -- the real state lives on `_shared_config` now -- so + `Component.configure()`'s "already set" guard tripped starting from the second test in the run, + 16 of 27 tests failing, with nothing in the error naming this rename. The rename itself was + correct and already reasoned through above; only its absence from the numbered breaking-changes + list was the gap. Added as breaking change 12 in `CHANGELOG.md`'s `[0.9.0]` entry, with the + one-line fix (`Component.reset_shared_state()` in place of the old assignment). From db2b434f524c0bd3864e0745d5d67735b85e57ec Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 18 Sep 2026 12:42:43 +0200 Subject: [PATCH 031/133] docs(guides): state that a grouped container needs an explicit group The migration guide could be followed to the end and produce an image that will not start. Section B changes the Dockerfile to `CMD ["python", "-m", "blueprint.agents.entrypoint"]`, copies agents.toml in beside the settings, and stops -- never saying the container also needs BLUEPRINT_AGENTS or a mounted group file. Three passages actively implied it did not, including one that stated the causal order backwards ("reads agents.toml, works out this process's group") and a summary table whose grouped row was a bare entrypoint command beside two rows that genuinely are complete. There is no such default. GroupConfig.resolve takes the agent list from the group file slice or from BLUEPRINT_AGENTS and raises GroupConfigError when it has neither, before _read_agent_map is called at all -- so "every agent in the map" is not a fallback, it is unreachable. test_no_agents_anywhere_is_an_error pins this deliberately, writing a populated agents.toml into the fixture and asserting the resolve still fails. The refusal is correct and stays: a default of "run everything in the image" would make adding an agent to the map silently change what every deployed process runs -- new consumers, new durables, new routes -- with no Deployment edit. That is the failure the two-file split exists to prevent. `asbs dev` can default from the map because a developer's laptop is the whole deployment; a container cannot. Four edits, all in the migration guide: the entry point's introduction now states the order the code runs in and the rule in its own paragraph; step 2 gains the missing half, both ways to supply the group and the error text without it; step 3 says the map turns a name into code but does not supply the name; the summary table's grouped row carries the variable. deployment.md and README.md needed nothing -- both were already correct. The defect was specific to the migration path, the one path where scaffolding does not supply the answer. Co-Authored-By: Claude Opus 5 (1M context) --- docs/guides/multi-agent-setup.md | 43 +++++++++-- ...26-08-28-multi-agent-grouping-changelog.md | 73 +++++++++++++++++++ 2 files changed, 109 insertions(+), 7 deletions(-) diff --git a/docs/guides/multi-agent-setup.md b/docs/guides/multi-agent-setup.md index 14ce654d..9a9fa2ba 100644 --- a/docs/guides/multi-agent-setup.md +++ b/docs/guides/multi-agent-setup.md @@ -73,8 +73,13 @@ This file is **baked into the image**: it says what the image contains. It does those agents any particular process runs -- that is the deployment's decision, and it arrives separately. -The `Dockerfile` runs `python -m blueprint.agents.entrypoint`, which reads `agents.toml`, works out -this process's group, and serves it. +The `Dockerfile` runs `python -m blueprint.agents.entrypoint`, which resolves which agents this +process runs, looks each one up in `agents.toml` to find its declaration, and serves them. + +**The group is never read from `agents.toml`.** The map says what the image *contains*; which of +those agents a process runs arrives separately, as `BLUEPRINT_AGENTS` or a mounted group file. +There is no default and no "every agent in the map": a container given neither prints one line and +exits before binding its port. See [Environment](#environment). ### Running it @@ -172,7 +177,7 @@ If you are passing **instances** anywhere -- `with_rest_api(OrderApi())` -- chan An instance is constructed at that line, before any namespace exists, so it belongs to the root for ever; a group refuses one at assembly and names the agent and the fix. -### 2. `Dockerfile` -- one command +### 2. `Dockerfile` -- one command, and the group it runs ```diff -CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"] @@ -185,6 +190,22 @@ and copy the map into the image beside your settings: COPY --chown=appuser:appuser agents.toml ./ ``` +**That command is not sufficient on its own.** Unlike `uvicorn src.main:app`, which named the +application it served, the entry point has to be *told* which agents to run, and copying +`agents.toml` does not tell it. Either bake a development default the deployment overrides -- + +```dockerfile +ENV BLUEPRINT_AGENTS="order" +``` + +-- or supply it per run: `-e BLUEPRINT_AGENTS=order`, or a mounted group file. A project scaffolded +by `asbs setup` gets the `ENV` line written for it; a Dockerfile migrated by hand has to add it. +Without either, the container exits at start with + +``` +Cannot start: No agents were resolved for this process. ... +``` + ### 3. `agents.toml` -- a new file ```toml @@ -192,9 +213,12 @@ COPY --chown=appuser:appuser agents.toml ./ module = "src.main:agent" ``` -Required even for a group of one: it is the only thing that turns an agent's name into code. There -is discovery by convention nowhere in this, deliberately -- a set of agents that depends on what -happens to be importable makes a renamed directory a silently removed agent. +Required even for a group of one: it is the only thing that turns an agent's name into code. It is +not what supplies the name -- that is step 2's job, and the two files are separate because they have +different lifetimes. There is discovery by convention nowhere in this, deliberately -- a set of +agents that depends on what happens to be importable makes a renamed directory a silently removed +agent, and a default of "run everything in the map" would make adding an agent silently change what +every existing deployment runs. ### 4. Check it @@ -212,7 +236,12 @@ the move. It never imports your project. |---|---| | Standalone, unmigrated | `uvicorn src.main:app` | | Standalone, migrated (with `create_app`) | `uvicorn src.main:create_app --factory` | -| Grouped, including a group of one | `python -m blueprint.agents.entrypoint` | +| Grouped, including a group of one | `BLUEPRINT_AGENTS=order python -m blueprint.agents.entrypoint` | + +Only the third takes what it serves from outside the image, and that part is **required**: there is +no default to fall back to and the process refuses to start without it. `BLUEPRINT_AGENTS` is the +short form; a mounted `deployment-groups.yaml` does the same job and is what a Kubernetes +Deployment usually uses -- a file declaring exactly one group needs no `BLUEPRINT_GROUP` beside it. --- diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 4f5e4ba2..91565a5f 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -4420,6 +4420,74 @@ went with them. --- +### The migration guide implied a default group, and there is none + +**Documentation only. No code changed, and none should.** + +`docs/guides/multi-agent-setup.md` could be followed to the end and produce an image that will not +start. Its section B -- migrating an existing single-agent project -- changes the `Dockerfile` to +`CMD ["python", "-m", "blueprint.agents.entrypoint"]`, copies `agents.toml` in beside the settings, +and stops. Nothing on that path says the container also needs `BLUEPRINT_AGENTS` or a mounted group +file, and three separate passages actively suggest it does not: + +- "*The `Dockerfile` runs `python -m blueprint.agents.entrypoint`, which reads `agents.toml`, works + out this process's group, and serves it*" -- which states the causal order backwards. The entry + point resolves the group *first* and reads the map afterwards, to turn the names it already has + into modules. +- "*Required even for a group of one: it is the only thing that turns an agent's name into code*", + said of `agents.toml`, which reads as though the map is what makes the group-of-one case work. +- The three-ways table, whose grouped row was a bare `python -m blueprint.agents.entrypoint` beside + two other rows that genuinely are complete commands. + +The behaviour those passages describe does not exist. `GroupConfig.resolve` takes the agent list +from the group file slice or from `BLUEPRINT_AGENTS`, and raises `GroupConfigError` when it has +neither -- *before* `_read_agent_map` is called at all (`group_config.py:166-173`), so "every agent +in the map" is not a fallback that was considered and rejected at runtime, it is not reachable. The +refusal is pinned by `test_no_agents_anywhere_is_an_error`, which deliberately writes a populated +`agents.toml` into the fixture and asserts the resolve still fails: the test's subject is precisely +that a full map does not supply a group. + +**The refusal is right, and the fix is in the prose.** A default of "run everything in the image" +would mean that adding a second agent to `agents.toml` silently changes what every already-deployed +process runs -- new queue-group consumers, new durables, new routes -- with no Deployment edit +anywhere. That is the failure the two-file split exists to prevent: the map has image lifetime, the +group has deployment lifetime, and a default would collapse the two. `asbs dev` *can* default to +every agent in the map (`cli-reference.md`) because a developer's laptop is the whole deployment; +that asymmetry is where the expectation comes from, and it is not one a container can copy. + +Four edits, all in `docs/guides/multi-agent-setup.md`: + +- The introduction to the entry point now states the order the code actually runs in, and follows + it with the rule in its own paragraph: the group is never read from `agents.toml`, there is no + default and no "every agent in the map", and a container given neither exits before binding its + port. +- Section B step 2 is retitled "one command, and the group it runs" and gains the missing half: + that unlike `uvicorn src.main:app`, which named what it served, the entry point has to be told, + and that copying the map does not tell it. It shows both routes -- an `ENV BLUEPRINT_AGENTS` line + as a development default, or `-e` per run -- notes that `asbs setup` writes that `ENV` line while + a hand-migrated `Dockerfile` has to add it, and quotes the `Cannot start:` line a container + produces without it. +- Step 3 keeps its claim about the map and adds what the claim is not: it turns a name into code, + it does not supply the name. The existing argument against discovery by convention is extended + by one clause, since "run everything in the map" is the same mistake in a different costume. +- The three-ways table's grouped row becomes `BLUEPRINT_AGENTS=order python -m + blueprint.agents.entrypoint`, with a paragraph under it saying the group is required, that + `BLUEPRINT_AGENTS` is the short form, and that a mounted `deployment-groups.yaml` declaring + exactly one group needs no `BLUEPRINT_GROUP` beside it. + +`docs/guides/deployment.md` needed nothing: it already says "*With neither, the process stops +before binding its port and prints which of the two is missing*", and gives both `docker run` +shapes. `README.md` already shows `-e BLUEPRINT_AGENTS=...` on every grouped example. The defect +was specific to the migration path, which is also the one path where the scaffolding does not +supply the answer for you -- a project from `asbs setup` gets `ENV BLUEPRINT_AGENTS` written into +its `Dockerfile` and never meets this. + +**Left alone, deliberately:** the error message names only the two environment-variable routes +("*Either mount a group file and name the group with `BLUEPRINT_GROUP`, or set `BLUEPRINT_AGENTS`*") +and omits the mounted-file-with-exactly-one-group case that `_read_group_file` supports, so it tells +you to set `BLUEPRINT_GROUP` when you may not need to. That is a `src/` change and is not part of a +documentation fix; it is listed under Open points. + --- ## Compatibility @@ -7342,3 +7410,8 @@ keep the readable names -- nothing reads those. licence is a legal artefact and somebody's decision rather than a documentation fix. Whoever settles it removes that entry, which a guard case then requires. - **#80** -- the failing example tests and the unenforced test split. +- **The "no agents resolved" message omits a route that works.** It says to mount a group file + *and* name it with `BLUEPRINT_GROUP`, or to set `BLUEPRINT_AGENTS` -- but `_read_group_file` + takes the sole group when a mounted file declares exactly one and `BLUEPRINT_GROUP` is unset, so + the message asks for a variable the reader may not need. A `src/` change, found while correcting + the migration guide's implication that the group has a default; the guide is fixed, this is not. From 419fafe9af283b20c51db16b84c2db618193edd9 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 18 Sep 2026 13:22:17 +0200 Subject: [PATCH 032/133] docs(group): say where the group file lives and how it reaches a container Three documents said a grouped container needs a group and none said how one gets there. The skills stopped at "yes: an agent map and a group"; the migration guide changed the Dockerfile command and copied the map in, which is the half that does not start a container; and every example used the default filename, so BLUEPRINT_GROUP_CONFIG read as a name rather than the path it is. No src/ change is needed -- the variable already takes a path, so one file per group works today. What was missing was saying so, and saying what it costs. - template_for_docker_ignore.txt excluded deployment-groups.yaml and .yml by exact name, which is the whole guard. A repository keeping deployment/groups/ *.yaml matches neither, so a wildcard copy bakes the group files into the layer -- an image serving whichever group was on disk at build time, silent because it does start. The template now states the rule and carries a commented example: an uncommented path would be a convention the framework does not have. - blueprint-multi-agent/SKILL.md gains "Supplying the group" -- the two routes, the five variables, the one-file-per-group layout, and why BLUEPRINT_GROUP is worth setting where a sole group makes it optional. - blueprint-deployment/SKILL.md gains "How the group reaches the container": both docker run shapes, and the group file's own reason for staying out of the build context. - multi-agent-setup.md gains "One file, or one file per group", and its agents.toml example is corrected -- it still showed module alone, written before root became required, so following it produced a startup failure naming a key the example never mentions. - multi-agent-migration.md step 2 regains the half lost when that guide was split out and rewritten. No Kubernetes material added: the framework ships no chart or manifest files and should not. A second open point is recorded -- BLUEPRINT_GROUP_CONFIG pointing at a directory fails as if nothing were mounted. ruff, mypy and 3147 unit tests clean. Co-Authored-By: Claude Opus 5 (1M context) --- ...26-08-28-multi-agent-grouping-changelog.md | 52 ++++++++++++-- .../base_files/template_for_docker_ignore.txt | 9 +++ .../skills/blueprint-deployment/SKILL.md | 26 +++++++ .../skills/blueprint-multi-agent/SKILL.md | 69 +++++++++++++++++++ .../docs/guides/multi-agent-migration.md | 23 +++++++ .../docs/guides/multi-agent-setup.md | 38 +++++++++- 6 files changed, 210 insertions(+), 7 deletions(-) diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 9f91faec..3b368db7 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7061,6 +7061,44 @@ bus. All five renamed to hyphenated forms, and `tests/unit/examples` now holds e `app_name` to `validate_subject_segment`, so the next one cannot ship. The prose and docstrings keep the readable names -- nothing reads those. +### Where the group file lives, and what stops it reaching the image + +Three documents said a container needs a group and none said how one gets there. The skills +stopped at "yes: an agent map and a group"; the migration guide changed the `Dockerfile` command +and copied the map in, which is the half that does not start a container; and every example used +the default filename, so `BLUEPRINT_GROUP_CONFIG` read as a name rather than the path it is. + +No `src/` change -- the variable already takes a path, and one file per group works today. What +was missing was saying so, and saying what it costs. + +- **`template_for_docker_ignore.txt`** excluded `deployment-groups.yaml` and `.yml` by exact + name. That is the whole guard, and a repository keeping `deployment/groups/*.yaml` matches + neither, so a wildcard copy bakes the group files into the layer -- an image that serves + whichever group was on disk when it was built, failing silently because it does start. The + template now states the rule and carries a commented example rather than an active line: an + uncommented path would be a convention the framework does not have, and would quietly do + nothing for anyone whose layout differs. Written by both scaffolds (`generator.py:363`, + `group_setup.py:79`). +- **`blueprint-multi-agent/SKILL.md`** gains *Supplying the group*: the two routes, the five + variables, the one-file-per-group layout, and why `BLUEPRINT_GROUP` is worth setting even + where a sole group makes it optional -- a name absent from the file is refused by name, where + an unnamed sole group is accepted whatever it contains, which is the difference between a + mounted wrong file failing and running. +- **`blueprint-deployment/SKILL.md`** gains *How the group reaches the container*: both + `docker run` shapes, and the group file's own reason for staying out of the build context, + which is not the `.secrets.toml` reason already there. +- **`multi-agent-setup.md`** gains *One file, or one file per group* -- blast radius against a + single reviewable diff -- and its `agents.toml` example is corrected: it still showed `module` + alone, having been written before `root` became required, so following it produced a startup + failure naming a key the example never mentions. +- **`multi-agent-migration.md`** step 2 regains the half lost when the guide was split and + rewritten: the entry point has to be told which agents to run, the map does not tell it, and a + container given neither exits before binding its port. + +No Kubernetes material was added. The framework ships no chart or manifest files and should not; +what it ships is the capabilities a cluster uses -- probes, `POD_NAME`, `scheduler_mode` -- which +`guides/deployment.md` already documents. + --- ## Open points @@ -7413,11 +7451,15 @@ keep the readable names -- nothing reads those. - **The "no agents resolved" message omits a route that works.** It says to mount a group file *and* name it with `BLUEPRINT_GROUP`, or to set `BLUEPRINT_AGENTS` -- but `_read_group_file` takes the sole group when a mounted file declares exactly one and `BLUEPRINT_GROUP` is unset, so - the message asks for a variable the reader may not need. A `src/` change, found while correcting - the migration guide's implication that the group has a default. The guide fix did not survive the - merge of origin (ddaf37c): that guide was split into `multi-agent-migration.md` and rewritten for - standalone serving, so its step 2 again changes the `Dockerfile` command without saying how the - group reaches the container. Both the message and the migration step are still open. + the message asks for a variable the reader may not need. A `src/` change, and the only part of + this still open: the migration step it was found alongside is fixed above, and the docs now say + to set `BLUEPRINT_GROUP` regardless, which makes the message's advice sound rather than + complete. +- **A `BLUEPRINT_GROUP_CONFIG` pointing at a directory fails as if nothing were mounted.** + `_group_file_path` returns it, `path.is_file()` is false (`group_config.py:250`), and the reader + gets "no agents were resolved" -- naming neither the directory nor the fact that a directory is + not a file it can read. Cheap to fix and a plausible mistake now that one file per group is + documented; deliberately not folded into a documentation change. - ~~**Breaking change #12 was missing from the list: `Component.shared_config` → `Component._shared_config`.**~~ **Closed.** Found during a real compatibility pass against a consuming project's test suite: its `conftest.py` reset diff --git a/src/blueprint/agent_generator/base_files/template_for_docker_ignore.txt b/src/blueprint/agent_generator/base_files/template_for_docker_ignore.txt index 7349662e..d38691b9 100644 --- a/src/blueprint/agent_generator/base_files/template_for_docker_ignore.txt +++ b/src/blueprint/agent_generator/base_files/template_for_docker_ignore.txt @@ -27,6 +27,15 @@ agents/**/.dockerignore deployment-groups.yaml deployment-groups.yml +# These two lines cover the default name only. A repository that keeps several groups usually +# keeps one file per group somewhere of its own choosing -- BLUEPRINT_GROUP_CONFIG takes a +# path, so any layout works and the framework has no opinion about it. Whatever that layout +# is, add it here: a folder of group files is not covered by the names above, and one that +# reaches the build context is baked in, which makes the image serve the group that happened +# to be on disk. Uncomment and adjust: +# +# deployment/groups/ + # Local environments and caches, which are large, machine-specific and often not even the right # platform. .venv/ diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md index 0cdbfea4..09186ae1 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md @@ -33,6 +33,32 @@ map at all. **Both need a `.dockerignore`.** `.gitignore` does not apply to a build context, so a wholesale `COPY agents ./agents` bakes every agent's `.secrets.toml` into a layer. `asbs setup` writes one. +The same applies to the **group file**, for a different reason: baked in, it makes the image serve +one group, and the whole point is that one image serves every group. The scaffolded +`.dockerignore` excludes `deployment-groups.yaml` by name; a repository keeping one file per group +under a path of its own has to add that path itself. + +## How the group reaches the container + +`BLUEPRINT_GROUP_CONFIG` takes a path, so the file can live anywhere and be mounted anywhere: + +```bash +# No file at all: the environment supplies the whole group +docker run -e BLUEPRINT_AGENTS=order,billing -e BLUEPRINT_CRITICAL_AGENTS=order my-image + +# A mounted group file, with the group named explicitly +docker run -v ./deployment/groups/checkout.yaml:/app/group.yaml:ro \ + -e BLUEPRINT_GROUP_CONFIG=/app/group.yaml \ + -e BLUEPRINT_GROUP=checkout \ + my-image +``` + +`blueprint-multi-agent` has the full variable table and the one-file-per-group layout. Two things +matter here: the environment overrides the file key by key, so a deployment changes the agent list +without editing what is mounted; and an unresolvable group **exits before the port is bound**, +which is what turns a typo into a restart loop with a readable line instead of a running process +that is short a consumer. + ## The two that break under replicas - **Schedulers.** `scheduler_mode = "in_process"` runs a timer in *every* replica and relies on the diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md index 86e7f45e..5dd794bb 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md @@ -99,6 +99,75 @@ group of one is still a group, and an agent must not have to declare itself one Its components are built at the root namespace, so the routes are the ones the API declares; hosted in a group, the same directory gains an `/api/` prefix. +## Supplying the group + +The map is baked in; the group is not. One image serves every group, so which agents *this* +process runs arrives at container start, by one of two routes. + +**Environment only**, which is the `docker run` and CI shape. No file is read at all: + +```bash +docker run -e BLUEPRINT_AGENTS=order,billing -e BLUEPRINT_CRITICAL_AGENTS=order my-image +``` + +**A mounted group file**, which is what a real deployment usually does, because the composition +is then something reviewable as a diff: + +```yaml +groups: + - name: checkout + agents: [order, billing] + critical_agents: [order] +``` + +| Variable | Default | Meaning | +|---|---|---| +| `BLUEPRINT_GROUP_CONFIG` | `./deployment-groups.yaml` | Path to the group file | +| `BLUEPRINT_GROUP` | -- | Which group in it. Optional when the file declares exactly one | +| `BLUEPRINT_AGENTS` | -- | Comma-separated names, supplying the group with no file at all | +| `BLUEPRINT_CRITICAL_AGENTS` | -- | Comma-separated subset to mark critical | +| `BLUEPRINT_AGENT_MAP` | `./agents.toml` | Path to the map | + +The environment overrides the file key by key, so one deployment changes the agent list without +editing or duplicating a mounted file. Setting `BLUEPRINT_AGENTS` while `BLUEPRINT_GROUP` is +unset skips the file entirely rather than merging with it. + +### Several groups: one file, or one file each + +`BLUEPRINT_GROUP_CONFIG` takes a **path**, so both shapes work and the framework has no opinion +about which. One file holding every group is the default name and reviews as a single diff. One +file per group keeps a typo in one group out of every other group's container: + +``` +deployment/groups/ # an example. Any layout works -- only the path has to be right + checkout.yaml + reporting.yaml +``` + +```bash +docker run -v ./deployment/groups/checkout.yaml:/app/group.yaml:ro \ + -e BLUEPRINT_GROUP_CONFIG=/app/group.yaml \ + -e BLUEPRINT_GROUP=checkout \ + my-image +``` + +Each such file still carries the `groups:` list with its one entry -- there is no single-group +form, and the same file works unchanged if it is later merged back into a shared one. + +**Set `BLUEPRINT_GROUP` even though a sole group makes it optional.** It is what catches the +wrong file being mounted: a name that is not in the file is refused by name, where an unnamed +sole group is taken silently whatever it turns out to contain. + +**Whatever the layout, add it to `.dockerignore`.** The scaffolded one excludes +`deployment-groups.yaml` by name and nothing else, and `.gitignore` does not apply to a build +context. A group file baked into a layer makes the image serve the group that happened to be on +disk when it was built, which is the opposite of the point. + +If the group cannot be resolved -- nothing naming agents, a group absent from the file, an agent +the image does not contain -- the process prints one line and **exits before binding its port**, +so an orchestrator restarts it with something actionable rather than reporting a healthy replica +that is quietly short a consumer. + ## Before promising the move is free An agent **left standalone** is unaffected by any of this. An agent **moved into a group** changes diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md index 5b1784f5..3f8ea5f9 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md @@ -76,6 +76,29 @@ and copy the map into the image beside your settings: COPY --chown=appuser:appuser agents.toml ./ ``` +**That command is not sufficient on its own, and copying the map does not complete it.** Where +`uvicorn src.main:app` named the application it served, the entry point has to be *told* which +agents to run, and the map says only which ones the image contains. A container given neither +`BLUEPRINT_AGENTS` nor a group file prints one line and exits before binding its port: + +``` +Cannot start: No agents were resolved for this process. ... +``` + +Supply it per run -- `-e BLUEPRINT_AGENTS=order`, or a mounted group file with +`-e BLUEPRINT_GROUP=` -- or bake a development default the deployment overrides: + +```dockerfile +ENV BLUEPRINT_AGENTS="order" +``` + +There is no default and no "every agent in the map". That refusal is deliberate: a fallback of +"run everything in the image" would make adding an agent to the map silently change what every +existing deployment runs -- new consumers, new durables, new routes -- with no deployment edit at +all. See [Environment](multi-agent-setup.md#environment) for the variables, and +[One file, or one file per group](multi-agent-setup.md#one-file-or-one-file-per-group) for where +the file itself lives. + ## 3. The image's `agents.toml` -- one entry, not a new file here The entry goes in the **image's** map, at the top of the repository that builds the image -- diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md index b19febc4..cf4c6d08 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md @@ -284,10 +284,12 @@ removed, which is a rebuild anyway. ```toml [agents.order] -module = "src.order.main:agent" +root = "agents/order" +module = "agents.order.src.main:agent" [agents.billing] -module = "src.billing.main:agent" +root = "agents/billing" +module = "agents.billing.src.main:agent" ``` **`deployment-groups.yaml` -- what this process runs.** Never baked in: one image serves every @@ -330,6 +332,38 @@ docker run -e BLUEPRINT_AGENTS=order,billing -e BLUEPRINT_CRITICAL_AGENTS=order Every resolved value is logged with the source it came from, because "which agents did this pod actually start" is the first question asked of a group that misbehaves. +### One file, or one file per group + +`BLUEPRINT_GROUP_CONFIG` is a **path**, so the default name is a default and not a rule. One file +holding every group is what the name `deployment-groups.yaml` suggests, and the composition then +reviews as a single diff. The alternative is one file per group, each declaring exactly one: + +``` +deployment/groups/ # an example: nothing in the framework knows this path + checkout.yaml + reporting.yaml +``` + +```bash +docker run -v ./deployment/groups/checkout.yaml:/app/group.yaml:ro \ + -e BLUEPRINT_GROUP_CONFIG=/app/group.yaml \ + -e BLUEPRINT_GROUP=checkout \ + my-image +``` + +What that buys is blast radius: a typo in `reporting` never reaches `checkout`'s container, +because that container never mounts it. What it costs is the single diff. Each file still carries +the `groups:` list around its one entry -- there is no single-group form, so a file split out of a +shared one, or merged back into it, is the same text either way. + +Name the group anyway. A file declaring exactly one group is taken without `BLUEPRINT_GROUP`, but +setting it is what makes the wrong file loud: a name absent from the file is refused by name, +where a sole unnamed group is accepted whatever it happens to contain. + +Whichever shape, the file must stay out of the build context -- see the scaffolded +`.dockerignore`, which excludes the default name and says why a different path needs a line of +its own. + If the group cannot be resolved -- no agents named, a group that is not in the file, an agent the image does not contain -- the process **stops before binding its port** and prints one line saying which. Kubernetes then crash-loops the pod with something an operator can act on, rather than From 4c3209a0a99515e62de87c3c9eda42c5af29bd44 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 18 Sep 2026 13:24:33 +0200 Subject: [PATCH 033/133] chore(release): 0.9.0a6 --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index b7a563a2..47cf3e66 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta" [project] name = "avs-blueprint-agents" -version = "0.9.0a5" +version = "0.9.0a6" description = "Microservice blueprint for creating agents" authors = [ { name = "Blueprint Team", email = "patrick.maue@bechtle.com" }, From 07a9895eba4c0a1857fe7258dbaf730ce8fd5a87 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 18 Sep 2026 14:06:02 +0200 Subject: [PATCH 034/133] fix(cli): validate --group resolves agent roots the way the runtime does Reported from a consumer repository on 0.9.0a6 and reproduced both ways: `asbs validate --group` at the top said "No agents.toml here" (the map is in deploy/), and `asbs validate --group deploy` resolved root = "agents/riskmanagement/risk_identifier" to deploy/agents/... and called it "not a directory". The runtime accepts that layout. _read_agent_map resolves agent roots against config.get_package_root() -- the image root -- while the map itself is separately relocatable with BLUEPRINT_AGENT_MAP. validate_group resolved roots against the directory holding the map. The two coincide exactly where `asbs setup --group` puts the map, which is why nothing caught it. So the command was not missing a check: it was making a false statement -- "1 issue(s) would stop this image starting" -- about an image that starts, and the reader's correct response to it is to break a layout that worked. - validate_group.py separates the two questions. _agent_map_path() returns where the map is (--agent-map, else BLUEPRINT_AGENT_MAP, else /agents.toml, relative values against the image root as at runtime) and _findings() takes both. Agent roots keep resolving against the image root, now by intent. The absent-map issue names the flag instead of asserting the directory is not an image, and the header prints the map's path when it is not beside the image root. - main.py gains --agent-map PATH on the validate parser. - group_config.py: no behaviour change, three corrected descriptions. Its own missing-root message said "relative to the directory this file is in", which is what the code does not do; GroupConfig.image_root's docstring described the map's directory while the field holds the package root. - The template and four documents now say image root. guides/cli/validate.md documents the flag. test_validate_group.py is new -- validate_group._findings had no test file at all, the second reason this shipped -- and holds the reported layout, the scaffolded one, the flag's resolution rules, and the still-refused root outside the image. test_group_config.py gains the runtime half. 3157 unit tests pass; ruff, mypy and black clean. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 11 ++ ...26-08-28-multi-agent-grouping-changelog.md | 48 +++++++++ .../base_files/group_agents_toml.txt | 7 +- .../skills/blueprint-multi-agent/SKILL.md | 6 +- .../cli/commands/validate_group.py | 50 +++++++-- src/blueprint/agent_generator/cli/main.py | 7 ++ .../docs/guides/cli/validate.md | 12 ++- .../docs/guides/multi-agent-migration.md | 5 +- .../docs/guides/multi-agent-setup.md | 7 +- src/blueprint/agents/group_config.py | 18 ++-- .../cli/commands/test_validate_group.py | 100 ++++++++++++++++++ tests/unit/agents/test_group_config.py | 17 +++ 12 files changed, 265 insertions(+), 23 deletions(-) create mode 100644 tests/unit/agent_generator/cli/commands/test_validate_group.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e9cefc06..f88bf1b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,17 @@ ### Fixed +- **`asbs validate --group` contradicted the runtime about where an agent's `root` points.** The + runtime resolves every `root` against the **image root** -- the directory the process runs in -- + and `BLUEPRINT_AGENT_MAP` may put the map anywhere, so a repository keeping `deploy/agents.toml` + with its agents at the top runs correctly. The validator resolved each `root` against whichever + directory the map sat in, so it reported that layout as `... is not a directory` under the + verdict "would stop this image starting" -- a false statement about a working image, whose + correct reading is to break a layout that worked. The two coincide only where the map is at the + image root, which is what `asbs setup --group` writes, so no test caught it. The command now + takes the directory argument as the image root and `--agent-map PATH` (or `BLUEPRINT_AGENT_MAP`) + as where the map is; a relative path resolves against the image root, as at runtime. The error + for an absent map names the flag. Present since `root` became required in 0.9.0a4. - **An agent settings file that scoped keys under the agent's own name merged into nothing.** `[default.]` in that agent's own `settings.toml` nested to `..*` once the file was merged under the agent's namespace, so every key in it was unreachable -- and the diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 3b368db7..3210559f 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7099,6 +7099,54 @@ No Kubernetes material was added. The framework ships no chart or manifest files what it ships is the capabilities a cluster uses -- probes, `POD_NAME`, `scheduler_mode` -- which `guides/deployment.md` already documents. +### `asbs validate --group` disagreed with the runtime about where `root` points + +Reported from a consumer repository on 0.9.0a6, and reproduced both ways: `asbs validate --group` +at the top said "No agents.toml here" (the map was in `deploy/`), and `asbs validate --group +deploy` resolved `root = "agents/riskmanagement/risk_identifier"` to `deploy/agents/...` and called +it "not a directory". + +The part the report did not reach is the one that decided the fix: **the runtime accepts that +layout.** `_read_agent_map` resolves `agent_root = (root / declared_root)` where `root` is +`config.get_package_root()` -- the image root -- while `path`, the map itself, is separately +relocatable with `BLUEPRINT_AGENT_MAP`. `validate_group._agent_findings` resolved against the +directory holding the map. The two coincide exactly where `asbs setup --group` puts the map, which +is why 3147 tests passed over it. + +So the command was not missing a check. It was making a false statement -- "1 issue(s) would stop +this image starting" -- about an image that starts, and the reader's correct response to it is to +break a layout that worked. + +Four documents, the template and two docstrings all said `root` was relative to the map's own +directory, including `group_config.py`'s own error message for a missing `root` and +`GroupConfig.image_root`'s docstring, which describes the map's directory while the field is +assigned the package root. The code was consistent with none of them and correct anyway: the map +is a packaging manifest, and letting its location define the image root means moving one file +moves every agent. + +- **`validate_group.py`** now separates the two questions. `_agent_map_path(image_root, configured)` + returns where the map is -- `--agent-map`, else `BLUEPRINT_AGENT_MAP`, else `image_root/agents.toml`, + with relative values resolved against the image root exactly as the runtime resolves them -- + and `_findings(image_root, agent_map)` takes both. Agent roots keep resolving against + `image_root`, which is now the runtime's meaning rather than a coincidence. The absent-map issue + names the flag and the variable instead of asserting "this directory is not an image"; the header + prints the map's path when it is not beside the image root, so the reader can see which file was + read. +- **`main.py`** gains `--agent-map PATH` on the validate parser. +- **`group_config.py`** carries no behaviour change and three corrected descriptions: the missing- + `root` message now names the image root, gives its resolved value and says the map can be moved + without moving the agents; `AgentSpec.root` says what it resolves against; `GroupConfig.image_root` + says what it is and, explicitly, what it is not. +- **The template and four documents** say image root instead of "relative to this file". + `guides/cli/validate.md` documents `--agent-map` and why the directory argument and the map are + two arguments rather than one. + +`tests/unit/agent_generator/cli/commands/test_validate_group.py` is new -- `validate_group._findings` +had no test file at all, which is the second reason this shipped -- and holds the reported layout, +the scaffolded one, the flag's resolution rules and the still-refused root outside the image. +`test_group_config.py` gains the runtime half: a relocated map resolves roots against the image +root and leaves `image_root` at the process root. + --- ## Open points diff --git a/src/blueprint/agent_generator/base_files/group_agents_toml.txt b/src/blueprint/agent_generator/base_files/group_agents_toml.txt index f4f65676..5af8a82a 100644 --- a/src/blueprint/agent_generator/base_files/group_agents_toml.txt +++ b/src/blueprint/agent_generator/base_files/group_agents_toml.txt @@ -13,8 +13,11 @@ # # Each agent needs two keys, and both are required: # -# root Where the agent's own directory is, relative to this file. Its settings.toml and -# its src/prompts are read from there. Stated rather than guessed from the module: +# root Where the agent's own directory is, relative to the image root -- the directory the +# process runs in, which is normally the one this file sits in too. It is the image +# root and not this file: BLUEPRINT_AGENT_MAP may put this file elsewhere, and moving +# it must not move every agent. Its settings.toml and its src/prompts are read from +# there. Stated rather than guessed from the module: # a root derived from where a declaration happens to sit is right for one layout and # silently wrong for every other, and an agent reading the group's defaults instead # of its own settings does not announce itself. diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md index 5dd794bb..33d50ce6 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md @@ -58,8 +58,10 @@ module = "agents.some_topic.my_agent.src.main:agent" ``` **Both are required and neither is derived from the other.** `root` is where the agent's files are -(its `settings.toml`, its `src/prompts`), relative to the directory `agents.toml` is in; `module` -is how its code imports. A root guessed from where the declaration sits is right for one layout and +(its `settings.toml`, its `src/prompts`), relative to the **image root** -- the directory the +process runs in, which is usually the one holding `agents.toml` but does not have to be: +`BLUEPRINT_AGENT_MAP` moves the map without moving the agents, and `asbs validate --group +--agent-map ` checks that layout. `module` is how its code imports. A root guessed from where the declaration sits is right for one layout and silently wrong for the rest -- and an agent whose settings were looked for in the wrong place does not fail, it runs on the group's defaults and says nothing. diff --git a/src/blueprint/agent_generator/cli/commands/validate_group.py b/src/blueprint/agent_generator/cli/commands/validate_group.py index bd9a5173..d735b688 100644 --- a/src/blueprint/agent_generator/cli/commands/validate_group.py +++ b/src/blueprint/agent_generator/cli/commands/validate_group.py @@ -11,6 +11,7 @@ passing its probes, which is exactly what makes them expensive to find later. """ +import os import sys import tomllib from argparse import Namespace @@ -22,6 +23,7 @@ from blueprint.agents.layout import check_agent_layout AGENT_MAP_FILE = "agents.toml" +AGENT_MAP_ENV = "BLUEPRINT_AGENT_MAP" def run(args: Namespace) -> None: @@ -35,25 +37,59 @@ def run(args: Namespace) -> None: print(f"Error: Directory does not exist: {image_root}", file=sys.stderr) sys.exit(1) + agent_map = _agent_map_path(image_root, getattr(args, "agent_map", None)) + print(f"Validating Blueprint Agents image: {image_root}") + if agent_map.parent != image_root: + print(f"Agent map: {agent_map}") print() - issues, warnings, notices = _findings(image_root) + issues, warnings, notices = _findings(image_root, agent_map) _report(issues, warnings, notices) sys.exit(1 if issues else 0) -def _findings(image_root: Path) -> tuple[list[str], list[str], list[str]]: - """Return issues, warnings and notices for the image at ``image_root``.""" +def _agent_map_path(image_root: Path, configured: str | None) -> Path: + """Return where the agent map is, which is not necessarily inside the directory being checked. + + The map and the image root answer different questions, and conflating them is what made this + command disagree with the runtime. The runtime resolves every agent ``root`` against the image + root -- the directory the process runs in -- while the map itself may sit anywhere, because + ``BLUEPRINT_AGENT_MAP`` relocates it. A repository keeping its map in ``deploy/`` and its + agents at the top therefore runs, and used to be reported here as an image that would not + start. + + Args: + image_root: The directory being validated, which agent roots resolve against. + configured: ``--agent-map``, if it was given. + + Returns: + The map's path, absolute. Relative values resolve against the image root, the same way + ``BLUEPRINT_AGENT_MAP`` does at runtime. + """ + declared = (configured or os.environ.get(AGENT_MAP_ENV, "") or "").strip() + if not declared: + return image_root / AGENT_MAP_FILE + path = Path(declared) + return path if path.is_absolute() else image_root / path + + +def _findings(image_root: Path, agent_map: Path) -> tuple[list[str], list[str], list[str]]: + """Return issues, warnings and notices for the image at ``image_root``. + + Args: + image_root: The directory agent roots resolve against, as at runtime. + agent_map: The map to read, which may be outside ``image_root``. + """ issues: list[str] = [] warnings: list[str] = [] notices: list[str] = [] - agent_map = image_root / AGENT_MAP_FILE if not agent_map.is_file(): issues.append( - f"No {AGENT_MAP_FILE} here, so this directory is not an image. Run 'asbs setup --group' to create one, " - "or drop --group to validate a single agent." + f"No agent map at {agent_map}, so this directory is not an image. Run 'asbs setup --group' to create " + f"one, point at an existing one with --agent-map (or {AGENT_MAP_ENV}), or drop --group to validate a " + "single agent." ) return issues, warnings, notices @@ -107,7 +143,7 @@ def _agent_findings(image_root: Path, name: str, entry: Any, claimed: dict[Path, if not declared_root or not isinstance(declared_root, str): issues.append( f"Agent '{name}' in {AGENT_MAP_FILE} has no 'root', so there is nowhere to read its settings and prompts " - 'from. Write it as root = "relative/path/to/the/agent".' + 'from. Write it as root = "relative/path/to/the/agent", relative to the image root.' ) return issues, warnings, notices diff --git a/src/blueprint/agent_generator/cli/main.py b/src/blueprint/agent_generator/cli/main.py index dc66c72f..7e745c28 100644 --- a/src/blueprint/agent_generator/cli/main.py +++ b/src/blueprint/agent_generator/cli/main.py @@ -184,6 +184,13 @@ def main() -> None: action="store_true", help="Validate an image rather than a single agent: the agent map, and every agent it points at.", ) + validate_parser.add_argument( + "--agent-map", + metavar="PATH", + help="Where the agent map is, if not agents.toml in the directory being validated. Relative paths resolve " + "against that directory, as BLUEPRINT_AGENT_MAP does at runtime. Agent roots are unaffected: they resolve " + "against the image root either way.", + ) # Dev command dev_parser = subparsers.add_parser( diff --git a/src/blueprint/agent_generator/docs/guides/cli/validate.md b/src/blueprint/agent_generator/docs/guides/cli/validate.md index a7995bad..230cfaae 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/validate.md +++ b/src/blueprint/agent_generator/docs/guides/cli/validate.md @@ -69,12 +69,20 @@ Notices (1): ## asbs validate --group Validates an *image* rather than a single agent: the agent map, and every agent directory it -points at. Run it where `agents.toml` is. +points at. ```bash -asbs validate --group +asbs validate --group # map at the image root +asbs validate --group --agent-map deploy/agents.toml # map kept elsewhere ``` +The directory argument is the **image root** -- what agent `root` values resolve against, and what +the process would run in. `--agent-map` says where the map itself is, which is a separate question: +the map is a packaging manifest, and `BLUEPRINT_AGENT_MAP` lets a repository keep it in `deploy/` +while its agents stay at the top. A relative `--agent-map` resolves against the image root, and the +environment variable is read when the flag is absent, so the command sees the layout the container +will. + It checks, per agent: - `root` and `module` are both present -- neither is derived from the other diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md index 3f8ea5f9..fdcbb0f2 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md @@ -120,8 +120,9 @@ root = "agents/order" module = "agents.order.src.main:agent" ``` -**Both keys are required.** `root` is the agent's own directory, relative to the directory -`agents.toml` is in -- the one holding its `settings.toml` and its `src/`. `module` is how its +**Both keys are required.** `root` is the agent's own directory -- the one holding its +`settings.toml` and its `src/` -- relative to the image root, which is the directory the process +runs in and normally the one holding `agents.toml`. `module` is how its code imports. Neither is derived from the other: a root guessed from where the declaration sits is right for one layout and silently wrong for the rest, and an agent whose settings were looked for in the wrong place does not fail, it runs on the group's defaults without saying so. diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md index cf4c6d08..ff5d5c9a 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md @@ -137,8 +137,11 @@ module = "agents.billing.src.main:agent" ``` **Both keys are required, and `root` is not derived from `module`.** `root` says where the -agent's files are -- its `settings.toml` and its `src/prompts` -- relative to the directory -`agents.toml` is in. `module` says how its code imports. They answer different questions and can +agent's files are -- its `settings.toml` and its `src/prompts` -- relative to the **image root**: +the directory the process runs in, which is where its own `settings.toml` is resolved from too. +That is normally the directory holding `agents.toml`, but it is the image root that counts -- +`BLUEPRINT_AGENT_MAP` can put the map in `deploy/` while the agents stay at the top, and moving +the map must not move every agent with it. `module` says how its code imports. They answer different questions and can legitimately differ, and a root guessed from where a declaration happens to sit is right for one layout and silently wrong for every other. An agent whose settings file was looked for in the wrong place does not fail: it runs on the group's defaults and says nothing. diff --git a/src/blueprint/agents/group_config.py b/src/blueprint/agents/group_config.py index a7691498..bf7494f0 100644 --- a/src/blueprint/agents/group_config.py +++ b/src/blueprint/agents/group_config.py @@ -106,7 +106,8 @@ class AgentSpec: module: Where the agent's ``AppBuilder`` declaration lives, as ``"module.path:attribute"``. Comes from the agent map, never from the group file: what an agent *is* belongs to the image, and only which agents run belongs to the deployment. - root: The agent's own directory, absolute. Comes from the agent map's ``root`` key and + root: The agent's own directory, absolute. Comes from the agent map's ``root`` key, + resolved against the **image root** rather than against the map's own directory, and is where the agent's ``settings.toml`` and its ``src/prompts`` are read from. Stated rather than derived: deriving it from the declaration module's file assumed the declaration sits one fixed level below the agent, which silently resolved to the @@ -140,9 +141,12 @@ class GroupConfig: broker-side identifier may derive from it, or moving an agent between groups would be visible to the broker (C1). agents: The agents to host, in the order the group declared them. - image_root: The directory the agent map was read from, which every agent's ``root`` is - relative to. Carried because a standalone agent's root *is* this directory, and the - rules about where the image's own files may sit differ in that case. + image_root: The image root -- the directory the process resolves its files against, which + every agent's ``root`` is relative to. Deliberately **not** the directory the agent + map was read from: the map is a packaging manifest and ``BLUEPRINT_AGENT_MAP`` may + put it anywhere, so letting its location define the image root would make moving the + file move every agent. Carried because a standalone agent's root *is* this directory, + and the rules about where the image's own files may sit differ in that case. Note: A group declares **no caches**. A cache belongs to the agent that declared it with @@ -341,8 +345,10 @@ def _read_agent_map(cls, env: dict[str, str] | Any, root: Path) -> dict[str, Age if not declared_root or not isinstance(declared_root, str): raise GroupConfigError( f"Agent '{agent_name}' in {path} has no 'root', so there is nowhere to read its settings and " - 'prompts from. Write it as root = "relative/path/to/the/agent", relative to the directory this ' - "file is in. It is required rather than derived: a root guessed from the declaration module is " + f'prompts from. Write it as root = "relative/path/to/the/agent", relative to the image root ' + f"({root}) rather than to this file -- the map can be moved with '{AGENT_MAP_ENV}' without " + "moving the agents. It is required rather than derived: a root guessed from the declaration " + "module is " "right for one layout and silently wrong for every other, and an agent reading the group's " "defaults instead of its own settings does not announce itself." ) diff --git a/tests/unit/agent_generator/cli/commands/test_validate_group.py b/tests/unit/agent_generator/cli/commands/test_validate_group.py new file mode 100644 index 00000000..c3fb2ca7 --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_validate_group.py @@ -0,0 +1,100 @@ +"""`asbs validate --group` -- the image, its agent map, and the agents the map points at. + +What these hold is the one thing the command exists for: that it agrees with the runtime. It is +worse than useless when it does not, because its verdict is phrased as "would stop this image +starting" -- so a disagreement is not a missing check, it is a false statement about a working +image, and the reader's correct response is to break a layout that worked. + +The disagreement these pin is real and shipped: the runtime resolves every agent `root` against +the image root and lets `BLUEPRINT_AGENT_MAP` put the map anywhere, while this command used to +resolve roots against whichever directory the map sat in. The two coincide in the scaffolded +layout, where the map is at the image root, which is why nothing caught it. +""" + +from pathlib import Path + +import pytest + +from blueprint.agent_generator.cli.commands.validate_group import _agent_map_path, _findings + +MAP_ENV = "BLUEPRINT_AGENT_MAP" + + +def _agent_dir(root: Path) -> None: + """Write the smallest directory that is a valid agent: settings beside `src/`.""" + (root / "src").mkdir(parents=True, exist_ok=True) + (root / "src" / "main.py").write_text("agent = None\n", encoding="utf-8") + (root / "settings.toml").write_text('[default]\nmodel_name = "x"\n', encoding="utf-8") + + +def _map_text(root: str, module: str = "agents.orders.src.main:agent") -> str: + return f'[agents.orders]\nroot = "{root}"\nmodule = "{module}"\n' + + +class TestWhereTheMapMayLive: + """The map is a packaging manifest; where it sits does not define the image root.""" + + def test_the_scaffolded_layout_has_the_map_at_the_image_root(self, tmp_path: Path) -> None: + _agent_dir(tmp_path / "agents" / "orders") + (tmp_path / "agents.toml").write_text(_map_text("agents/orders"), encoding="utf-8") + + issues, _, _ = _findings(tmp_path, _agent_map_path(tmp_path, None)) + + assert issues == [] + + def test_a_map_below_the_image_root_still_resolves_roots_against_that_root(self, tmp_path: Path) -> None: + """The reported case: `deploy/agents.toml`, agents at the top. The runtime accepts it.""" + _agent_dir(tmp_path / "agents" / "riskmanagement" / "risk_identifier") + (tmp_path / "deploy").mkdir() + (tmp_path / "deploy" / "agents.toml").write_text( + '[agents.risk_identifier]\nroot = "agents/riskmanagement/risk_identifier"\n' + 'module = "agents.riskmanagement.risk_identifier.src.main:agent"\n', + encoding="utf-8", + ) + + issues, _, _ = _findings(tmp_path, _agent_map_path(tmp_path, "deploy/agents.toml")) + + assert issues == [], "Resolving the root against deploy/ rather than the image root is the defect." + + def test_an_absent_map_names_the_flag_that_points_at_one(self, tmp_path: Path) -> None: + issues, _, _ = _findings(tmp_path, _agent_map_path(tmp_path, None)) + + assert len(issues) == 1 + assert "--agent-map" in issues[0], "A reader whose map is elsewhere needs to be told there is a way to say so." + assert MAP_ENV in issues[0] + + def test_a_root_outside_the_image_is_still_refused(self, tmp_path: Path) -> None: + """Relocating the map does not relax the rule that an agent's files are part of the image.""" + _agent_dir(tmp_path / "outside") + image = tmp_path / "image" + image.mkdir() + (image / "agents.toml").write_text(_map_text("../outside"), encoding="utf-8") + + issues, _, _ = _findings(image, _agent_map_path(image, None)) + + assert any("outside the image" in issue for issue in issues) + + +class TestResolvingTheMapPath: + """`--agent-map` and `BLUEPRINT_AGENT_MAP` resolve the way the runtime resolves them.""" + + def test_the_default_is_the_map_in_the_directory_being_validated(self, tmp_path: Path) -> None: + assert _agent_map_path(tmp_path, None) == tmp_path / "agents.toml" + + def test_a_relative_flag_resolves_against_the_image_root(self, tmp_path: Path) -> None: + assert _agent_map_path(tmp_path, "deploy/agents.toml") == tmp_path / "deploy" / "agents.toml" + + def test_an_absolute_flag_is_taken_as_it_is(self, tmp_path: Path) -> None: + absolute = tmp_path / "elsewhere" / "agents.toml" + + assert _agent_map_path(tmp_path, str(absolute)) == absolute + + def test_the_environment_supplies_it_when_the_flag_does_not(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv(MAP_ENV, "deploy/agents.toml") + + assert _agent_map_path(tmp_path, None) == tmp_path / "deploy" / "agents.toml" + + def test_the_flag_wins_over_the_environment(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv(MAP_ENV, "from/env.toml") + + assert _agent_map_path(tmp_path, "from/flag.toml") == tmp_path / "from" / "flag.toml" diff --git a/tests/unit/agents/test_group_config.py b/tests/unit/agents/test_group_config.py index db4945e9..bb799c68 100644 --- a/tests/unit/agents/test_group_config.py +++ b/tests/unit/agents/test_group_config.py @@ -263,6 +263,23 @@ def test_an_empty_agent_map_is_an_error(self, project: Config, tmp_path: Path) - with pytest.raises(GroupConfigError, match="declares no \\[agents"): GroupConfig.resolve(project, environ={"BLUEPRINT_AGENTS": "invoice", "BLUEPRINT_AGENT_MAP": str(path)}) + def test_a_relocated_map_resolves_roots_against_the_image_root_not_against_itself(self, project: Config, tmp_path: Path) -> None: + """Where the map sits is a packaging decision; it does not move the agents. + + `BLUEPRINT_AGENT_MAP` exists so the manifest can live somewhere of the repository's + choosing -- `deploy/agents.toml` beside the deployment files is the case that found this. + Resolving each `root` against the map's own directory instead would make moving the file + move every agent with it, and the agents here are not under `deploy/`. + """ + relocated = tmp_path / "deploy" + relocated.mkdir() + (relocated / "agents.toml").write_text(AGENT_MAP) + + group = GroupConfig.resolve(project, environ={"BLUEPRINT_AGENTS": "invoice", "BLUEPRINT_AGENT_MAP": "deploy/agents.toml"}) + + assert group.agents[0].root == (tmp_path / "agents/invoice").resolve() + assert group.image_root == tmp_path.resolve(), "The image root is the process's root, not the map's directory." + class TestAgentNamesAreAgentNames: def test_a_name_that_cannot_be_a_namespace_is_refused(self, project: Config) -> None: From 44ea31fadc4b9cce513c244566804e53dce8bf7c Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 18 Sep 2026 15:24:40 +0200 Subject: [PATCH 035/133] chore(release): 0.9.0a7 --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 47cf3e66..c6b336ef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta" [project] name = "avs-blueprint-agents" -version = "0.9.0a6" +version = "0.9.0a7" description = "Microservice blueprint for creating agents" authors = [ { name = "Blueprint Team", email = "patrick.maue@bechtle.com" }, From c45b5c387ec7eb7b422be8f5f474513ffd706cb9 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 18 Sep 2026 15:55:57 +0200 Subject: [PATCH 036/133] docs(migration): one intro, an honest file count, and where the map may live Five findings against multi-agent-migration.md, all traceable to 424d9dc splitting it out of multi-agent-setup.md: the new opening was written and the lifted one was kept. - The intro appeared twice. "Three files change, and nothing else", the link to the one decision to get right first, and "a name you cannot cheaply change" were in the opening paragraph and again, near-verbatim, after the ---. The second copy is gone. - "Three files change, and nothing else" was not true of the guide's own steps. Step 3 moves process-wide keys into the image's settings.toml and may require unprefixing the agent's own. It now says three files carry the migration and names the two that may need an edit, noting that both already exist and whether they are touched depends on what the project sets. - Map relocation was undocumented -- the gap the consumer report started from. New "Keeping the map somewhere else", separating two relocations that the report ran together, because only one needs configuration: a map kept in deploy/ in the repository and copied to the image root needs nothing at runtime and only --agent-map for the tooling, while a map that stays in a subdirectory inside the image needs BLUEPRINT_AGENT_MAP. Both state the point that makes the design legible: no root changes when the map moves, because roots resolve against the image root. - Section 3 opened by contradicting itself, placing the map "at the top of the repository that builds the image" flatly, three paragraphs above wording that hedged "normally the one holding agents.toml". The rule -- not inside an agent -- is now stated as the rule, the top of the repository as the default. - Step 4's "# at the top" comment assumed the same, and now says "where the map is", with the two-argument invocation below it. No src/ behaviour change. 3157 unit tests pass. Co-Authored-By: Claude Opus 5 (1M context) --- ...26-08-28-multi-agent-grouping-changelog.md | 29 +++++++ .../docs/guides/multi-agent-migration.md | 78 +++++++++++++++---- 2 files changed, 91 insertions(+), 16 deletions(-) diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 3210559f..6d6fa068 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7147,6 +7147,35 @@ the scaffolded one, the flag's resolution rules and the still-refused root outsi `test_group_config.py` gains the runtime half: a relocated map resolves roots against the image root and leaves `image_root` at the process root. +### The migration guide said three files and meant five, twice + +Five findings against `multi-agent-migration.md`, all traceable to `a9a8f3b` splitting it out of +`multi-agent-setup.md`: the new opening was written and the lifted one was kept. + +- **The intro appeared twice.** "Three files change, and nothing else", the link to *the one + decision to get right first*, and "a name you cannot cheaply change" were in the opening + paragraph and again, near-verbatim, after the `---`. The second copy is gone. +- **"Three files change, and nothing else" was not true of the guide's own steps.** Step 3 moves + process-wide keys into the image's `settings.toml` and may require unprefixing the agent's own. + It now says three files carry the migration and names the two that may need an edit, with the + distinction that matters to somebody estimating the work: those two already exist, and whether + they are touched depends on what the project already sets. +- **Map relocation was undocumented**, which is the gap the consumer report started from. New + *Keeping the map somewhere else*, and it separates two relocations that the report itself ran + together, because only one of them needs configuration: a map kept in `deploy/` **in the + repository** and copied to the image root (`COPY deploy/agents.toml ./`) needs nothing at + runtime and only `--agent-map` for the tooling, while a map that stays in a subdirectory + **inside the image** needs `BLUEPRINT_AGENT_MAP`. Both state the consequence that makes the + design legible: no `root` changes when the map moves, because roots resolve against the image + root -- a map in `deploy/` naming `root = "agents/order"` still means `/app/agents/order`. +- **Section 3 opened by contradicting itself.** It placed the map "at the top of the repository + that builds the image" flatly, three paragraphs above wording that hedged "normally the one + holding `agents.toml`". The rule -- not inside an agent, which `asbs validate --group` enforces + -- is now stated as the rule, and the top of the repository as the default that `asbs setup + --group` writes. +- **Step 4's `# at the top` comment** assumed the same thing, and now says "where the map is", + with the two-argument invocation below it. + --- ## Open points diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md index fdcbb0f2..3ced9d14 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md @@ -1,19 +1,19 @@ # Migrating an Existing Agent into a Group You have a single-agent project with a `main.py` that builds and serves an application, and you -want it to run beside other agents in one process. Three files change, and nothing else. +want it to run beside other agents in one process. + +**Three files carry the migration:** `src/main.py`, the `Dockerfile`, and the image's +`agents.toml`. Two more may need an edit, depending on what the project already sets -- the +agent's own `settings.toml` if it scopes keys under its own name, and the image's `settings.toml` +if the agent sets process-wide keys. Both are covered in step 3, and both are edits to files that +already exist rather than new ones. Migrating is optional. A project deployed on its own keeps working, unchanged, indefinitely -- there is no deprecation here. See [Multi-Agent Setup](multi-agent-setup.md) for the model this fits into, and read [the one decision to get right first](multi-agent-setup.md#the-one-decision-to-get-right-first) before you start: one of the three files carries a name you cannot cheaply change afterwards. ---- - -Three files change, and nothing else. Read -[the one decision to get right first](multi-agent-setup.md#the-one-decision-to-get-right-first) before you start: one -of the three is a name you cannot cheaply change afterwards. - ## 1. `src/main.py` -- remove two things, add nothing Before: @@ -101,10 +101,12 @@ the file itself lives. ## 3. The image's `agents.toml` -- one entry, not a new file here -The entry goes in the **image's** map, at the top of the repository that builds the image -- -not in the agent's directory. The map says which agents an image contains, which is a packaging -decision; an agent that carried one would be an agent that knows whether it is running alone. -`asbs validate --group` refuses one found inside an agent. +The entry goes in the **image's** map, not in the agent's directory. The map says which agents an +image contains, which is a packaging decision; an agent that carried one would be an agent that +knows whether it is running alone. `asbs validate --group` refuses one found inside an agent. +That is the rule. Where the file sits above an agent is the repository's business -- the top of +the repository that builds the image is the default and what `asbs setup --group` writes, and +[Keeping the map somewhere else](#keeping-the-map-somewhere-else) covers the alternative. If the repository has no image files yet, create them once: @@ -122,15 +124,52 @@ module = "agents.order.src.main:agent" **Both keys are required.** `root` is the agent's own directory -- the one holding its `settings.toml` and its `src/` -- relative to the image root, which is the directory the process -runs in and normally the one holding `agents.toml`. `module` is how its -code imports. Neither is derived from the other: a root guessed from where the declaration sits -is right for one layout and silently wrong for the rest, and an agent whose settings were looked -for in the wrong place does not fail, it runs on the group's defaults without saying so. +runs in and normally the one holding `agents.toml`. `module` is how its code imports. Neither is +derived from the other: a root guessed from where the declaration sits is right for one layout and +silently wrong for the rest, and an agent whose settings were looked for in the wrong place does +not fail, it runs on the group's defaults without saying so. Nothing inside the agent's directory moves. Its `settings.toml` stays beside `src/`, exactly where it was when the project ran on its own -- that sameness is what lets the directory move back out again untouched. +### Keeping the map somewhere else + +The map does not have to sit at the top. A repository that keeps its deployment files together +can keep the map with them, and **no `root` changes when it moves** -- roots resolve against the +image root, not against the map, which is the whole reason they are two different things. + +Two relocations get confused with each other, so take them one at a time. + +**The map moves in the repository, not in the image.** The common case: the file lives in +`deploy/`, and the `Dockerfile` copies it to the image root as before. + +```dockerfile +COPY --chown=appuser:appuser deploy/agents.toml ./ +``` + +Inside the container nothing has moved, so the runtime needs no configuration at all. Only the +tooling, which runs against the repository, has to be told: + +```bash +asbs validate --group . --agent-map deploy/agents.toml +``` + +**The map moves inside the image too.** Rarer, and the only case that needs an environment +variable. Copy it into a subdirectory, then name it: + +```dockerfile +COPY --chown=appuser:appuser deploy/agents.toml ./deploy/ +ENV BLUEPRINT_AGENT_MAP="deploy/agents.toml" +``` + +`BLUEPRINT_AGENT_MAP` is read relative to the image root, and it changes only where the *map* is +looked for. Every agent `root` in it still resolves against the image root, so a map in `deploy/` +naming `root = "agents/order"` means `/app/agents/order`, not `/app/deploy/agents/order`. + +Whichever shape, the agents themselves must stay under the image root -- an agent's files are +part of the image, and a `root` that escapes it is refused at startup and by `asbs validate`. + ### One thing inside the file may have to change The location does not move; the *contents* might. This file **becomes** the agent's scope when it @@ -174,7 +213,14 @@ dropped before the merge with a warning naming the value actually used. ```bash asbs validate # inside the agent's directory: the agent itself -asbs validate --group # at the top: the map, and every agent it points at +asbs validate --group # where the map is: the map, and every agent it points at +``` + +If the map is not beside the directory you are checking, pass both -- the directory is the image +root, `--agent-map` is the file: + +```bash +asbs validate --group . --agent-map deploy/agents.toml ``` `--group` resolves every `root`, reports which `settings.toml` each agent actually reads, refuses a From 6bc9d99015a0e64fa2f25cb1f46dd6b03ab2876b Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 18 Sep 2026 16:03:38 +0200 Subject: [PATCH 037/133] fix(docker): probe a health route the application actually serves Both scaffolded Dockerfiles declared HEALTHCHECK ... CMD curl -f http://localhost:8000/health || exit 1 and ActuatorApi serves /health/live and /health/ready, with nothing at /health. curl -f fails on the 404, so every container built from a scaffold reported unhealthy for its whole life -- compose's `depends_on: service_healthy` never released, and anything reading Docker's own health state saw a permanently failing container that was serving traffic fine. Silent in the sense that matters: the application is up, so nothing in its logs says why. Both now probe /health/live, which is what guides/deployment.md has shown all along -- the templates disagreed with the code and with their own guide. test_the_healthcheck_names_a_route_the_application_serves holds the path in the generated project; nothing did before, which is why this survived. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 8 ++++++++ src/blueprint/agent_generator/base_files/Dockerfile | 2 +- .../agent_generator/base_files/group_Dockerfile | 2 +- .../generator/test_generated_project.py | 13 +++++++++++++ 4 files changed, 23 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f88bf1b5..b3366224 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,14 @@ ### Fixed +- **Both scaffolded `Dockerfile`s declared a `HEALTHCHECK` against a route that does not exist.** + `curl -f http://localhost:8000/health` -- but `ActuatorApi` serves `/health/live` and + `/health/ready`, and nothing at `/health`. `curl -f` fails on the 404, so every container built + from a scaffold reported `unhealthy` for its whole life: compose's `depends_on: + service_healthy` never released, and anything reading Docker's health state saw a permanently + failing container that was in fact serving traffic. Both now probe `/health/live`, which is what + the deployment guide has always shown. A generated-project test holds the path. + - **`asbs validate --group` contradicted the runtime about where an agent's `root` points.** The runtime resolves every `root` against the **image root** -- the directory the process runs in -- and `BLUEPRINT_AGENT_MAP` may put the map anywhere, so a repository keeping `deploy/agents.toml` diff --git a/src/blueprint/agent_generator/base_files/Dockerfile b/src/blueprint/agent_generator/base_files/Dockerfile index 9a143c27..7fe38673 100644 --- a/src/blueprint/agent_generator/base_files/Dockerfile +++ b/src/blueprint/agent_generator/base_files/Dockerfile @@ -98,7 +98,7 @@ ENV PYTHONPATH="/app/src" \ USER appuser HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ - CMD curl -f http://localhost:8000/health || exit 1 + CMD curl -f http://localhost:8000/health/live || exit 1 EXPOSE 8000 diff --git a/src/blueprint/agent_generator/base_files/group_Dockerfile b/src/blueprint/agent_generator/base_files/group_Dockerfile index b4d30157..bf98a12d 100644 --- a/src/blueprint/agent_generator/base_files/group_Dockerfile +++ b/src/blueprint/agent_generator/base_files/group_Dockerfile @@ -57,7 +57,7 @@ USER appuser EXPOSE 8000 HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ - CMD curl -f http://localhost:8000/health || exit 1 + CMD curl -f http://localhost:8000/health/live || exit 1 # Which agents this process runs is the deployment's to say: # diff --git a/tests/unit/agent_generator/generator/test_generated_project.py b/tests/unit/agent_generator/generator/test_generated_project.py index fb2c4267..85c2348c 100644 --- a/tests/unit/agent_generator/generator/test_generated_project.py +++ b/tests/unit/agent_generator/generator/test_generated_project.py @@ -468,6 +468,19 @@ def test_the_documented_run_command_needs_no_group(self, project: Path) -> None: assert "docker run -p 8000:8000 " in dockerfile assert "agent_namespace" not in dockerfile + def test_the_healthcheck_names_a_route_the_application_serves(self, project: Path) -> None: + """A HEALTHCHECK on a 404 does not report "unknown", it reports unhealthy, for ever. + + `ActuatorApi` serves `/health/live` and `/health/ready` and nothing at `/health`, so the + bare path fails `curl -f` on every probe: the container never becomes healthy, compose's + `depends_on: service_healthy` never releases, and an orchestrator reading Docker's own + health state sees a permanently failing container that is in fact serving traffic. + """ + dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") + + assert "/health/live" in dockerfile + assert "8000/health || exit 1" not in dockerfile, "the bare /health is not a route this application serves" + class TestAnUnusableProjectNameIsRefused: """A name that cannot be a namespace fails the generator rather than the deployment.""" From 32fc186d7d2429484e1a89b3fc9482ede2085a9d Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 18 Sep 2026 16:07:09 +0200 Subject: [PATCH 038/133] docs: sweep the pages that still describe the pre-standalone world A coherence pass over the packaged docs, the skills and the templates against the code. Mechanically clean: all 40 pages' links and anchors resolve, all 29 `asbs docs ` targets the skills reference exist, the index matches what is on disk. Five substantive findings, four of them one cause -- 18264c9 changed what a standalone project is, and the pages written before it were not swept. The sixth, the broken HEALTHCHECK, went separately as a fix. - guides/cli/setup.md documented an agents.toml that `asbs setup` does not write, with an example missing the required root, for a file `asbs validate` now refuses outright. setup.py prints the opposite in the same breath. The page now says no map is written and why, and shows the entry to add to the image's map instead. - guides/deployment.md's "The image" described the group image and called it the scaffolded one. There are two images now, and blueprint-deployment's SKILL.md already said so, so the skill and the guide it points at disagreed. The section names both and says which one it is about; the entry-point bullet no longer claims a scaffolded main.py builds nothing, which stopped being true when create_app() was added to it. - setup.py's own output claimed the single-agent Dockerfile "writes a one-agent map". It serves create_app with uvicorn and writes no map -- its Dockerfile says so in a comment three lines above the ENTRYPOINT. - guides/troubleshooting.md's `dapr run` named src.main:app, which a scaffolded project has not defined since the split. - `asbs docs` was registered and undocumented: main.py:149 registers it, every skill tells the reader to run it, and cli-reference.md listed neither it nor setup --group, validate --group or --agent-map. All added. 3158 unit tests pass; ruff and mypy clean. Co-Authored-By: Claude Opus 5 (1M context) --- ...26-08-28-multi-agent-grouping-changelog.md | 33 +++++++++++++++++++ .../agent_generator/cli/commands/setup.py | 2 +- .../docs/guides/cli-reference.md | 16 +++++++++ .../agent_generator/docs/guides/cli/setup.md | 18 +++++++--- .../agent_generator/docs/guides/deployment.md | 17 +++++++--- .../docs/guides/troubleshooting.md | 2 +- 6 files changed, 76 insertions(+), 12 deletions(-) diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 6d6fa068..94175aa1 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7176,6 +7176,39 @@ Five findings against `multi-agent-migration.md`, all traceable to `a9a8f3b` spl - **Step 4's `# at the top` comment** assumed the same thing, and now says "where the map is", with the two-argument invocation below it. +### A coherence sweep of the packaged docs against the code + +Mechanically clean: all 40 pages' links and anchors resolve, all 29 `asbs docs ` targets +referenced by the skills exist, the docs index matches what is on disk, and every `agents.toml` +example carries `root` bar the one below. Six substantive findings, four of them one cause -- +`676731d` changed what a standalone project *is*, and the pages written before it were not swept. + +- **Both scaffolded `Dockerfile`s probed `/health`, which is not a route.** Fixed separately as a + `fix(docker)`; see `CHANGELOG.md`. It is the only one of the six that was shipped behaviour + rather than prose, and the only one older than the standalone change. +- **`guides/cli/setup.md` documented an `agents.toml` that `asbs setup` does not write** -- with + an example missing the required `root`, for a file `asbs validate` now refuses outright. The + CLI prints the opposite in the same breath (`setup.py:199`). The page now states that no map is + written and why, and shows the entry to add to the *image's* map instead. +- **`guides/deployment.md`'s "The image" described the group image and called it the scaffolded + one.** There are two images now, and `blueprint-deployment/SKILL.md` already said so, so the + skill and the guide it points at disagreed. The section opens by naming both and says which one + it is about; the bullet about the entry point no longer claims a scaffolded `main.py` builds + nothing, which stopped being true when `create_app()` was added to it. +- **`setup.py`'s own output claimed the single-agent Dockerfile "writes a one-agent map".** It + serves `create_app` with uvicorn and writes no map -- the Dockerfile says so in a comment three + lines above the `ENTRYPOINT`. +- **`guides/troubleshooting.md`'s `dapr run` named `src.main:app`**, which a scaffolded project + has not defined since the split. +- **`asbs docs` was registered and undocumented.** `main.py:149` registers it, every skill tells + the reader to run it, and `cli-reference.md` listed neither it nor `setup --group`, + `validate --group` or `--agent-map`. All added. + +Noted, not fixed: `tests/unit/agent_generator/generator/test_generated_project.py` joins the list +of files `black --check` wants to reformat and `ruff format --check` considers clean. It is the +disagreement `CLAUDE.local.md` records, it predates this work (reproduced with the change +stashed), and it is not one formatter's to settle mid-change. + --- ## Open points diff --git a/src/blueprint/agent_generator/cli/commands/setup.py b/src/blueprint/agent_generator/cli/commands/setup.py index 1670ed0c..fb7b57bd 100644 --- a/src/blueprint/agent_generator/cli/commands/setup.py +++ b/src/blueprint/agent_generator/cli/commands/setup.py @@ -199,7 +199,7 @@ def run(args: Namespace) -> None: print("\nThis directory carries no agents.toml, and that is deliberate: the agent map says") print("which agents an *image* contains, so an agent holding one would be an agent that") print("knows whether it is running alone. Whoever hosts it supplies the name:") - print(f" - its own Dockerfile writes a one-agent map naming it '{namespace}'") + print(" - its own Dockerfile serves it directly with uvicorn src.main:create_app --factory") print(" - a group image maps it in the repository's agents.toml, with root and module") print(" - asbs dev uses this directory's name unless --name says otherwise") print("\nThat name is the agent's identity on the broker, in telemetry and in its routes") diff --git a/src/blueprint/agent_generator/docs/guides/cli-reference.md b/src/blueprint/agent_generator/docs/guides/cli-reference.md index 802bf0d4..ce85ca9b 100644 --- a/src/blueprint/agent_generator/docs/guides/cli-reference.md +++ b/src/blueprint/agent_generator/docs/guides/cli-reference.md @@ -20,6 +20,19 @@ This page is an index. Each command has its own page so you can read only the pa | `asbs validate` | [validate](cli/validate.md) | Check project structure and configuration | | `asbs dev` | [dev](cli/dev.md) | Run the development server with reload | | `asbs claude` | [claude](cli/claude.md) | Copy the Claude Code resources into a project | +| `asbs docs` | below | Locate or print the documentation shipped with the package | + +### asbs docs + +The documentation ships inside the package, so it matches the version installed rather than +whatever is on a branch somewhere. With no topic it lists every page. + +```bash +asbs docs # every page +asbs docs guides/multi-agent-setup # print that page's path +asbs docs guides/multi-agent-setup --cat # print the page itself +asbs docs --root # the documentation root directory +``` --- @@ -36,12 +49,15 @@ This page is an index. Each command has its own page so you can read only the pa ```bash asbs setup # Scaffold complete project +asbs setup --group # Scaffold an image that hosts several agents asbs create handler [--event-type TYPE] # Add EventHandler asbs create service # Add Service asbs create api # Add RestApi asbs create agent # Add AgentRuntime asbs create scheduler [--cron CRON] # Add Scheduler asbs validate # Validate project structure +asbs validate --group [--agent-map PATH] # Validate an image and every agent it maps asbs dev [--port 8000] # Run dev server +asbs docs [topic] [--cat] # Read the packaged documentation asbs claude [--overwrite] # Install Claude Code resources ``` diff --git a/src/blueprint/agent_generator/docs/guides/cli/setup.md b/src/blueprint/agent_generator/docs/guides/cli/setup.md index 61d8e70d..36348827 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/setup.md +++ b/src/blueprint/agent_generator/docs/guides/cli/setup.md @@ -83,18 +83,26 @@ Components are registered as **classes**, not instances: a component constructed line is constructed before any namespace exists and belongs to the root for ever, which is why a group refuses one. -`asbs setup` also writes `agents.toml`, which maps the agent's name to that declaration: +**`asbs setup` writes no `agents.toml`, and that is deliberate.** The map says which agents an +*image* contains, so an agent carrying one would be an agent that knows whether it is running +alone -- and `asbs validate` refuses one found inside an agent. The project is run with `uvicorn +src.main:create_app --factory`, which needs no map, no group and no namespace. + +Whoever hosts it supplies the name. To host this directory in a group, add it to the **image's** +map, which lives in the repository that builds the image: ```toml [agents.my_ai_service] -module = "src.main:agent" +root = "" +module = ".src.main:agent" ``` +Both keys are required, and `root` resolves against the image root rather than against the map. +See [Multi-Agent Migration](../multi-agent-migration.md) for the three files that change. + That name is the agent's identity everywhere outside the file -- the NATS queue group, part of the JetStream durable name, the cache partition, the OpenTelemetry `service.name` and the `/api/` -route prefix -- so changing it after the first deploy is a consumer migration. The project is run -with `uvicorn src.main:create_app --factory`, which needs no map and no group. A group image runs -`python -m blueprint.agents.entrypoint` instead, and maps this directory from its own `agents.toml`. +route prefix -- so changing it after the first deploy is a consumer migration. --- diff --git a/src/blueprint/agent_generator/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md index 30292ea7..effc6c8d 100644 --- a/src/blueprint/agent_generator/docs/guides/deployment.md +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -24,7 +24,13 @@ Two things shape everything below, and both are recent: ## The image -A scaffolded project ships a multi-stage Dockerfile whose production stage is: +**There are two, and which one you have depends on what you scaffolded.** `asbs setup ` +writes a single-agent image that serves one declaration directly -- `uvicorn src.main:create_app +--factory`, no map, no group, no namespace. `asbs setup --group` writes a group image, which is +the one below. The same agent directory is built by either without editing a line; what differs +is what gets copied and what serves it. + +The group image's production stage: ```dockerfile FROM python:3.13-slim-bookworm AS final @@ -61,10 +67,11 @@ Three things about it are load-bearing: changes only when an agent is added or removed -- which is a rebuild anyway. Which agents a *process* runs is a deployment decision and arrives separately, so baking it would defeat the one property the whole model exists for. -- **The command is `python -m blueprint.agents.entrypoint`**, not `uvicorn src.main:app`. A - scaffolded `src/main.py` declares an agent and builds nothing; the entry point resolves this - process's group, builds it and serves it. A project that has not migrated keeps `uvicorn - src.main:app` and keeps working. +- **The command is `python -m blueprint.agents.entrypoint`**, which is what makes this a *group* + image. A scaffolded `src/main.py` declares an agent and also offers `create_app()`, so the same + file is served directly by a single-agent image and hosted by this one; the entry point resolves + this process's group, builds it and serves it. A project from before the split, whose `main.py` + builds its own application, keeps `uvicorn src.main:app` and keeps working. - **`.secrets.toml` is never copied in.** Mount it, or supply the values as environment variables. ### Building and running diff --git a/src/blueprint/agent_generator/docs/guides/troubleshooting.md b/src/blueprint/agent_generator/docs/guides/troubleshooting.md index 82211c15..6ecf415b 100644 --- a/src/blueprint/agent_generator/docs/guides/troubleshooting.md +++ b/src/blueprint/agent_generator/docs/guides/troubleshooting.md @@ -145,7 +145,7 @@ ConnectionRefusedError: Cannot connect to Dapr sidecar at localhost:3500 For local development, start the application via the Dapr CLI: ```bash -dapr run --app-id my-ai-service --app-port 8000 -- python -m uvicorn src.main:app +dapr run --app-id my-ai-service --app-port 8000 -- python -m uvicorn src.main:create_app --factory ``` In Kubernetes, verify the Dapr annotations are present on the pod: From 6d214c2083435bcf705d2e172f6fa4ce2b0343a5 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 18 Sep 2026 16:09:08 +0200 Subject: [PATCH 039/133] chore(release): 0.9.0a8 --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index c6b336ef..c94c830b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta" [project] name = "avs-blueprint-agents" -version = "0.9.0a7" +version = "0.9.0a8" description = "Microservice blueprint for creating agents" authors = [ { name = "Blueprint Team", email = "patrick.maue@bechtle.com" }, From 80f9db0a496cd2932b7cecd46b0f376e07195aa7 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 11:57:14 +0200 Subject: [PATCH 040/133] feat(cli): ship a blueprint-migration skill and list skills from disk in asbs claude asbs claude copied claude_docs/skills/ wholesale, but no migration skill existed: the migration guide was reachable only as one table row inside blueprint-multi-agent. Add blueprint-migration, route migration requests to it from blueprint-multi-agent, and name it in the shipped CLAUDE.md. The "Next steps" slash-command list was a hand-kept block, so a new skill would have been copied but never announced. ClaudeGenerator now builds it from skill_names() and agent_names(), which read claude_docs/. Guarded by test_claude_generator.py: frontmatter names match their directories, every skill is copied and announced, and CLAUDE.md names every blueprint-* skill. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 6 ++ ...26-08-28-multi-agent-grouping-changelog.md | 28 +++++++ .../agent_generator/claude_docs/CLAUDE.md | 2 +- .../skills/blueprint-migration/SKILL.md | 75 +++++++++++++++++++ .../skills/blueprint-multi-agent/SKILL.md | 4 +- .../generator/claude_generator.py | 26 +++++-- .../generator/test_claude_generator.py | 51 +++++++++++++ 7 files changed, 181 insertions(+), 11 deletions(-) create mode 100644 src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md create mode 100644 tests/unit/agent_generator/generator/test_claude_generator.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b3366224..78554bd5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,12 @@ ### Added +- **A `blueprint-migration` Claude Code skill**, installed by `asbs claude`: moving an existing + single-agent project into a group -- the files it touches, the mistakes that break it, and how + `asbs validate --group` checks it. The migration guide was previously reachable only from inside + `blueprint-multi-agent`. `asbs claude` now lists the skills and agents it installed by reading + them from the package, rather than from a hand-kept list that would have left any new skill + unannounced. - **A standalone agent declares nothing group-related.** `asbs setup` writes a `create_app()` factory beside the declaration, and the generated Dockerfile serves it with `uvicorn src.main:create_app --factory` -- no agent map, no group, no namespace. A group of one diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 94175aa1..ba45179d 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7209,6 +7209,34 @@ of files `black --check` wants to reformat and `ruff format --check` considers c disagreement `CLAUDE.local.md` records, it predates this work (reproduced with the change stashed), and it is not one formatter's to settle mid-change. +### `asbs claude` had no migration skill, and announced its skills from a hand-kept list + +Reported by a colleague during PR review: the skills `asbs claude` installs did not include one +for migration. The command itself dropped nothing -- `ClaudeGenerator.generate()` copies +`claude_docs/skills/` wholesale and `pyproject.toml` packages `claude_docs/**/*` -- but no +migration skill had ever been written. `guides/multi-agent-migration.md` was reachable only as one +row of a table inside `blueprint-multi-agent`, so nothing surfaced as `/blueprint-migration`, and a +user asking Claude to migrate an agent depended on the multi-agent skill's description happening to +match. + +- **New skill `blueprint-migration`.** The five files the migration touches, the rules that break + it (instances instead of classes, the entry point without `BLUEPRINT_AGENTS`, a map inside the + agent, `[default.]` nesting twice), `asbs validate --group`, and the broker-identity change + that makes the move visible. It points at the guide for the diffs rather than repeating them. + `blueprint-multi-agent`'s description now routes migration to it, and the shipped `CLAUDE.md`'s + skill list names it. +- **The "Next steps" slash-command list was a hand-kept block** in `generate()`, so the next skill + added would have been copied and never announced. `skill_names()` and `agent_names()` now read + `claude_docs/` and the output is built from them. +- **Guarded** by `tests/unit/agent_generator/generator/test_claude_generator.py`: every skill's + frontmatter `name` matches its directory (a mismatch installs a skill under a slash command + nobody is told about), every skill is copied and announced, and the shipped `CLAUDE.md` names + every `blueprint-*` reference skill. The existing `test_docs.py` already checks that the new + skill's `asbs docs` targets exist. + +Checked and found complete: every guide under `docs/guides/` now has a skill; `concepts/`, +`components/` and `reference/` are reached through the existing skills rather than one each. + --- ## Open points diff --git a/src/blueprint/agent_generator/claude_docs/CLAUDE.md b/src/blueprint/agent_generator/claude_docs/CLAUDE.md index 8d1c7534..c12f2774 100644 --- a/src/blueprint/agent_generator/claude_docs/CLAUDE.md +++ b/src/blueprint/agent_generator/claude_docs/CLAUDE.md @@ -255,7 +255,7 @@ asbs docs reference/configuration-keys --cat # print its contents ``` Prefer the matching skill (`blueprint-cli`, `blueprint-config`, `blueprint-events`, -`blueprint-multi-agent`, `blueprint-testing`, `blueprint-deployment`, +`blueprint-multi-agent`, `blueprint-migration`, `blueprint-testing`, `blueprint-deployment`, `blueprint-troubleshooting`); each one carries the rules that matter and points at the page for the detail. **Never guess a configuration key or a CLI flag** -- the reference is on disk. diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md new file mode 100644 index 00000000..1f08406b --- /dev/null +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md @@ -0,0 +1,75 @@ +--- +name: blueprint-migration +description: Migrating an existing single-agent Blueprint project so it runs in a multi-agent group - rewriting src/main.py into a declaration, the Dockerfile entry point, the agents.toml entry, and the settings.toml edits the move may need. Use when an existing agent must join a group, or when a migrated agent will not start or runs without its settings. +user-invocable: true +--- + +# Migrating an Agent into a Group + +**Read the guide before editing anything** - it has the before/after for every file: + +```bash +asbs docs guides/multi-agent-migration --cat # the four steps, with diffs +asbs docs guides/multi-agent-setup --cat # the model it fits into, and what changes after +``` + +Migrating is optional. A project left standalone keeps working unchanged, with no deprecation - ask +whether the move is actually wanted before starting it. + +## Choose the name first + +The agent's name in `agents.toml` becomes its queue group, its JetStream durables, its cache +directory and Redis prefix, its telemetry `service.name` and its `/api/` route prefix. +Renaming it after the first grouped deploy is a consumer migration, not a rename. The alphabet is +`[a-z][a-z0-9_]*` - **no dashes**; a name outside it is refused, never repaired. See +`blueprint-multi-agent` for why. + +## What changes + +Three files carry the migration; two more may need an edit. + +| File | Change | +|---|---| +| `src/main.py` | `AppBuilder(config)...build()` becomes `agent = AppBuilder()...` - drop the `config` argument and the `.build()`, keep every `with_*` call | +| `Dockerfile` | `CMD ["python", "-m", "blueprint.agents.entrypoint"]`, and copy `agents.toml` into the image | +| image's `agents.toml` | one `[agents.]` entry with **both** `root` and `module` | +| agent's `settings.toml` | only if it scopes keys as `[default.]`: unprefix to `[default]` | +| image's `settings.toml` | only if the agent sets process-wide keys (`app_port`, `event_bus`, `log_level`, ...): move them up | + +Nothing inside the agent's directory moves. Its `settings.toml` stays beside `src/`. + +## Rules that bite + +- **Classes, not instances.** `with_rest_api(OrderApi())` is built before any namespace exists; a + group refuses it. Pass `OrderApi`. +- **Nothing at import time.** The module is imported into a shared runtime: no client construction, + no `logging.basicConfig()`. +- **Still serving it alone?** Add `def create_app(): return agent.build(Config(...))` and run + `uvicorn src.main:create_app --factory`. It repeats no component. +- **The new `CMD` alone does not start.** The map says which agents the image *contains*, not which + this process *runs*. Without `BLUEPRINT_AGENTS` or a group file the container exits before + binding its port - by design, there is no "run everything" default. +- **The map belongs to the image, never the agent.** `asbs setup --group` creates the image files + if the repository has none. An `agents.toml` inside an agent's directory is refused. +- **`root` and `module` are never derived from each other.** A wrong `root` does not fail - the + agent silently runs on the group's defaults. `root` resolves against the image root, not the map. +- **`[default.]` nests twice once merged** and every key under it becomes unreachable. It + surfaces as a missing model name blaming the agent, not the file. Plain `[default]` serves both + shapes. + +## Check it + +```bash +asbs validate # inside the agent's directory +asbs validate --group # where the map is: the map and every agent it names +``` + +`--group` resolves each `root`, reports which `settings.toml` each agent reads, and flags prefixed +sections and process-wide keys left in an agent. Pass `--agent-map ` if the map is not +beside the directory being checked. + +## Before calling the move invisible + +It is not. On the first grouped deploy the agent's broker-side identity changes once (new durables, +new queue group) and its cache starts cold. Read *What changes, and what does not* in +`guides/multi-agent-setup` before telling anyone otherwise. diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md index 33d50ce6..e410ec12 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md @@ -1,6 +1,6 @@ --- name: blueprint-multi-agent -description: Running several Blueprint agents in one process, and migrating an existing single-agent project into a group. Use for agents.toml, agent namespaces, group deployment, the entrypoint module, or when an existing agent must join a group. +description: Running several Blueprint agents in one process - agents.toml, agent namespaces, supplying the group at container start, and the entrypoint module. Use when designing or deploying a group; for moving an existing single-agent project into one, use blueprint-migration. user-invocable: true --- @@ -15,7 +15,7 @@ two is an edit to a Deployment, not a rebuild. | Case | Read | |---|---| | New project, built as a group from the start | `asbs docs guides/multi-agent-setup --cat` | -| Existing single-agent project joining a group | `asbs docs guides/multi-agent-migration --cat` | +| Existing single-agent project joining a group | The `blueprint-migration` skill, then `asbs docs guides/multi-agent-migration --cat` | | Leave it standalone | Nothing changes. There is no deprecation - this is a legitimate answer | ## The layout, which is not negotiable diff --git a/src/blueprint/agent_generator/generator/claude_generator.py b/src/blueprint/agent_generator/generator/claude_generator.py index f328e503..c462786b 100644 --- a/src/blueprint/agent_generator/generator/claude_generator.py +++ b/src/blueprint/agent_generator/generator/claude_generator.py @@ -33,8 +33,7 @@ class ClaudeGenerator: └── skills/ ├── new-agent-service/ │ └── SKILL.md - └── add-component/ - └── SKILL.md + └── ... one directory per skill under claude_docs/skills/ """ def __init__(self, output_dir: str | Path) -> None: @@ -112,15 +111,26 @@ def generate(self, overwrite: bool = False) -> None: print("\nNext steps:") print(" 1. Open the project in Claude Code — it will pick up src/CLAUDE.md automatically.") print(" 2. Use slash commands:") - print(" /new-agent-service /add-component") - print(" /blueprint-cli /blueprint-config") - print(" /blueprint-events /blueprint-multi-agent") - print(" /blueprint-testing /blueprint-deployment") - print(" /blueprint-troubleshooting") + for name in self.skill_names(): + print(f" /{name}") print(" 3. Use agents:") - print(" @blueprint-architect @blueprint-builder") + for name in self.agent_names(): + print(f" @{name}") print(" 4. The framework docs are on disk; find them with 'asbs docs'.") + def skill_names(self) -> list[str]: + """Return the name of every skill this generator copies, sorted. + + A skill is a directory under ``skills/`` holding a ``SKILL.md``; the directory name is the + slash command. Read from disk rather than listed by hand, so that a skill added to + ``claude_docs/`` is announced without a second edit here. + """ + return sorted(path.parent.name for path in (self._source_dir / "skills").glob("*/SKILL.md")) + + def agent_names(self) -> list[str]: + """Return the name of every agent this generator copies, sorted.""" + return sorted(path.stem for path in (self._source_dir / "agents").glob("*.md")) + # ------------------------------------------------------------------ # Private helpers # ------------------------------------------------------------------ diff --git a/tests/unit/agent_generator/generator/test_claude_generator.py b/tests/unit/agent_generator/generator/test_claude_generator.py new file mode 100644 index 00000000..d32aad0a --- /dev/null +++ b/tests/unit/agent_generator/generator/test_claude_generator.py @@ -0,0 +1,51 @@ +"""What ``asbs claude`` copies into a project, and what it tells the user it copied. + +The skill list used to be printed from a hand-maintained block, so a skill added to +``claude_docs/skills/`` was copied but never announced -- and nothing noticed that the migration +guide had no skill at all. These tests hold the shipped skills, the generator's announcement and +the shipped ``CLAUDE.md`` to one another. +""" + +import re +from pathlib import Path + +import pytest + +from blueprint.agent_generator.generator.claude_generator import ClaudeGenerator + +CLAUDE_DOCS = Path(__file__).resolve().parents[4] / "src" / "blueprint" / "agent_generator" / "claude_docs" + +SKILL_DIRS = sorted(path.parent for path in (CLAUDE_DOCS / "skills").glob("*/SKILL.md")) + +FRONTMATTER_NAME = re.compile(r"\A---\s*\n(?:.*\n)*?name:\s*(\S+)\s*\n(?:.*\n)*?---\s*\n") + + +def test_the_migration_guide_has_a_skill() -> None: + assert "blueprint-migration" in [d.name for d in SKILL_DIRS] + + +@pytest.mark.parametrize("skill_dir", SKILL_DIRS, ids=lambda d: d.name) +def test_skill_frontmatter_name_matches_its_directory(skill_dir: Path) -> None: + match = FRONTMATTER_NAME.match((skill_dir / "SKILL.md").read_text(encoding="utf-8")) + assert match is not None, f"{skill_dir.name}/SKILL.md has no frontmatter name" + assert match.group(1) == skill_dir.name + + +def test_skill_names_reads_every_shipped_skill() -> None: + assert ClaudeGenerator(".").skill_names() == [d.name for d in SKILL_DIRS] + + +def test_generate_copies_and_announces_every_skill(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + ClaudeGenerator(tmp_path).generate() + out = capsys.readouterr().out + + for skill_dir in SKILL_DIRS: + assert (tmp_path / ".claude" / "skills" / skill_dir.name / "SKILL.md").is_file() + assert f"/{skill_dir.name}\n" in out + for agent in (CLAUDE_DOCS / "agents").glob("*.md"): + assert f"@{agent.stem}\n" in out + + +@pytest.mark.parametrize("skill_dir", [d for d in SKILL_DIRS if d.name.startswith("blueprint-")], ids=lambda d: d.name) +def test_shipped_claude_md_points_at_every_reference_skill(skill_dir: Path) -> None: + assert f"`{skill_dir.name}`" in (CLAUDE_DOCS / "CLAUDE.md").read_text(encoding="utf-8") From 31375cca9f04c4b6c6c03dce03438db236d022c1 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 11:57:19 +0200 Subject: [PATCH 041/133] build: set the base version to 0.9.0; release versions come from the tag publish.yml rewrites the version in pyproject.toml from the pushed v* tag before building, so the committed value is only the base. Releases are cut by tagging, not by a version-bump commit. Co-Authored-By: Claude Opus 5.5 (1M context) --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index c94c830b..93caf550 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta" [project] name = "avs-blueprint-agents" -version = "0.9.0a8" +version = "0.9.0" description = "Microservice blueprint for creating agents" authors = [ { name = "Blueprint Team", email = "patrick.maue@bechtle.com" }, From 159611f24fe7ba716cdb684d314774ae951be66b Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 13:44:26 +0200 Subject: [PATCH 042/133] fix(config): keep an environment override when an agent's settings file sets the same key merge_agent_settings promises that DYNACONF___KEY beats the agent's own settings.toml. It did not: Dynaconf upper-cases what it loads, the fragment keeps lower case, and _fill_missing compared verbatim. The fragment's key was written beside the override and Dynaconf folded the two spellings together -- concatenating lists, replacing scalars -- while the key was reported as merged. _fill_missing now matches keys case-insensitively at every level and keeps the spelling already present. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 5 +++ ...26-08-28-multi-agent-grouping-changelog.md | 27 ++++++++++++ src/blueprint/agents/config/config.py | 17 +++++-- .../config/test_agent_settings_fragments.py | 44 +++++++++++++++++++ 4 files changed, 90 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78554bd5..f4240413 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,11 @@ ### Fixed +- **An environment override of a key an agent's own `settings.toml` also sets now wins in a group.** + `DYNACONF___KEY` was compared against the agent file's keys case-sensitively -- Dynaconf + upper-cases what it loads, the file keeps lower case -- so the override was never seen: a list + was concatenated with the file's, a scalar was replaced by the file's value, and the key was + reported as merged. Keys are now matched case-insensitively, at every nesting level. - **Both scaffolded `Dockerfile`s declared a `HEALTHCHECK` against a route that does not exist.** `curl -f http://localhost:8000/health` -- but `ActuatorApi` serves `/health/live` and `/health/ready`, and nothing at `/health`. `curl -f` fails on the 404, so every container built diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index ba45179d..3c92fec9 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7237,6 +7237,33 @@ match. Checked and found complete: every guide under `docs/guides/` now has a skill; `concepts/`, `components/` and `reference/` are reached through the existing skills rather than one each. +### An environment override of a key the agent's file also sets was silently defeated + +Reported by a DevOps review of a first group deployment (their H3). `merge_agent_settings` +promises that an environment override (`DYNACONF___KEY`) is left alone and the agent's file +fills only the gaps. It did not keep that promise for any key the file also set: + +- `DYNACONF_RISK_IDENTIFIER__NATS_SUBSCRIPTIONS='["t.T1.risk.>"]'` against a file setting + `["risk.>", "t.*.risk.>"]` resolved to all three -- the lists were concatenated. +- `DYNACONF_RISK_IDENTIFIER__APP_NAME=FromEnv` resolved to the file's `RiskIdentifier`. +- The merge reported both keys as added. + +**Cause.** Dynaconf stores what it loads upper-cased (`NATS_SUBSCRIPTIONS`); the agent's file is +parsed with `tomllib` and keeps its lower case (`nats_subscriptions`). `Config._fill_missing` +compared keys verbatim, never saw the override, and wrote the fragment's key beside it. Dynaconf +then folded the two spellings into one key -- merging the lists, letting the later scalar win. The +existing precedence tests passed because they set the override through the group's +`settings.toml`, which does not take the upper-case path. + +**Fix.** `_fill_missing` matches keys case-insensitively, at every level, and keeps the spelling of +the key already present. Consequence for deployments: any key an agent's file sets can now be +overridden per agent from the environment, which the reviewer's interim of one process per tenant +depends on. + +Guarded by `TestEnvironmentOverrides` in `test_agent_settings_fragments.py`: a list, a scalar and +a nested key each keep the environment's value, and only the keys the environment left out are +reported. All four fail against the previous `_fill_missing`. + --- ## Open points diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index fb7a411a..63b1a9da 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -731,19 +731,30 @@ def _fill_missing(target: dict[str, Any], incoming: dict[str, Any], prefix: str ``[default..cache] size_limit`` instead of replacing the table or being dropped by it. A leaf already present is never overwritten -- see the precedence rule on :meth:`merge_agent_settings`. + + **Keys are matched case-insensitively.** Dynaconf stores what it loaded upper-cased -- + ``DYNACONF_RISK__NATS_SUBSCRIPTIONS`` arrives as ``NATS_SUBSCRIPTIONS`` -- while an agent's + file is parsed with ``tomllib`` and keeps its lower case. Compared verbatim, the two never + match: the fragment's key is written beside the override instead of yielding to it, and + Dynaconf then folds the two spellings into one, concatenating a list and letting the file + replace a scalar. That silently defeats every environment override of a key the agent's + file also sets. The present key keeps its spelling; only the comparison ignores case. """ + spelled = {str(key).lower(): key for key in target} added: list[str] = [] for key, value in incoming.items(): path = f"{prefix}{key}" - if key not in target: + existing = spelled.get(str(key).lower()) + if existing is None: target[key] = value + spelled[str(key).lower()] = key added.append(path) continue - present = target[key] + present = target[existing] if hasattr(present, "items") and hasattr(value, "items"): nested = dict(present.items()) added.extend(Config._fill_missing(nested, dict(value.items()), prefix=f"{path}.")) - target[key] = nested + target[existing] = nested return tuple(sorted(added)) def resolved_settings(self, namespace: str = "") -> dict[str, Any]: diff --git a/tests/unit/agents/config/test_agent_settings_fragments.py b/tests/unit/agents/config/test_agent_settings_fragments.py index 1ea969dc..b650f1b8 100644 --- a/tests/unit/agents/config/test_agent_settings_fragments.py +++ b/tests/unit/agents/config/test_agent_settings_fragments.py @@ -175,6 +175,50 @@ def test_a_nested_table_is_merged_key_by_key(self, config: Config, tmp_path: Pat assert (view.get("cache.size_limit"), view.get("cache.cache_dir")) == (500, ".cache/orders") +class TestEnvironmentOverrides: + """``DYNACONF___KEY`` beats the agent's own file, for a key the file also sets. + + Dynaconf stores what it loads upper-cased and the fragment keeps its lower case, so a verbatim + comparison never saw the override: the fragment was written beside it, the list was then + concatenated and the scalar replaced -- and the key was reported as merged. + """ + + @pytest.fixture + def overridden(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Config: + monkeypatch.setenv("DYNACONF_RISK__NATS_SUBSCRIPTIONS", '["t.T1.risk.>"]') + monkeypatch.setenv("DYNACONF_RISK__APP_NAME", "FromEnv") + monkeypatch.setenv("DYNACONF_RISK__CACHE__SIZE_LIMIT", "500") + (tmp_path / "settings.toml").write_text('[default]\napp_environment = "development"\n') + return Config(settings_files=["settings.toml"], root_path=str(tmp_path)) + + @pytest.fixture + def merged(self, overridden: Config, tmp_path: Path) -> tuple[str, ...]: + body = """ + [default] + app_name = "RiskIdentifier" + nats_subscriptions = ["risk.>", "t.*.risk.>"] + model_name = "risk-model" + + [default.cache] + size_limit = 100 + cache_dir = ".cache/risk" + """ + return overridden.merge_agent_settings("risk", fragment(tmp_path, "risk", body)) + + def test_a_list_is_replaced_not_concatenated(self, overridden: Config, merged: tuple[str, ...]) -> None: + assert overridden.for_namespace("risk").get("nats_subscriptions") == ["t.T1.risk.>"] + + def test_a_scalar_keeps_the_environments_value(self, overridden: Config, merged: tuple[str, ...]) -> None: + assert overridden.for_namespace("risk").get("app_name") == "FromEnv" + + def test_a_nested_key_keeps_the_environments_value(self, overridden: Config, merged: tuple[str, ...]) -> None: + view = overridden.for_namespace("risk") + assert (view.get("cache.size_limit"), view.get("cache.cache_dir")) == (500, ".cache/risk") + + def test_only_what_the_environment_left_out_is_reported(self, merged: tuple[str, ...]) -> None: + assert merged == ("cache.cache_dir", "model_name") + + class TestProcessScopeKeys: def test_a_port_is_ignored(self, config: Config, tmp_path: Path) -> None: """One process, one HTTP server: a per-agent port is unbindable.""" From 16472c291e924e7c7873d641dbf0bfea9d7bb490 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 14:17:55 +0200 Subject: [PATCH 043/133] fix(nats): require nats_url outside development, and warn when running in development mode NATSClient.connect() defaulted nats_url to nats://localhost:4222. In a pod that reaches nothing, and the background retry loop retried it forever while the process looked alive. NATSClient.on_startup() now resolves the URL: a configured one is used; unset in development falls back to localhost with a WARNING; unset in any other environment raises, naming the key and the variable to set, which the sec. 9.1 startup policy turns into an aborted start or a downed agent. connect() goes through the same resolution. AppBuilder logs once per process that development mode is not suitable for production, since app_environment defaults to development. BREAKING CHANGE: outside app_environment = "development", event_bus = "nats" now requires nats_url. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 9 +++ ...26-08-28-multi-agent-grouping-changelog.md | 34 +++++++++++ .../docs/guides/troubleshooting.md | 18 ++++++ .../docs/reference/configuration-keys.md | 4 +- src/blueprint/agents/app_builder.py | 21 +++++++ .../agents/clients/io/nats_client.py | 54 ++++++++++++++++- .../app_builder/test_development_warning.py | 36 +++++++++++ .../agents/clients/io/test_nats_client.py | 59 ++++++++++++++++++- 8 files changed, 231 insertions(+), 4 deletions(-) create mode 100644 tests/unit/agents/app_builder/test_development_warning.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f4240413..bf5a0267 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -92,6 +92,15 @@ ### Breaking +- **`nats_url` has no default outside development.** With `event_bus = "nats"` and no `nats_url`, + a process whose `app_environment` is anything but `"development"` now fails startup naming the + key -- a standalone or critical agent before the port is bound, a non-critical agent of a group + by being marked down. It used to connect to `nats://localhost:4222`, which in a pod reaches + nothing and retried forever while the pod reported healthy. Development keeps the localhost + fallback, with a WARNING. A broker in the same pod needs `nats_url` set explicitly. +- **A process in development mode logs a WARNING at startup** that it is not suitable for + production. `app_environment` defaults to `"development"`, so a deployment that sets nothing now + says so in its own log. - **`root` is required in `agents.toml`.** Every existing entry needs one line added; a map without it refuses to start rather than guessing. For an image that copied one agent to `/app`, that is `root = "."`. diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 3c92fec9..44c8fd1a 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7264,6 +7264,40 @@ Guarded by `TestEnvironmentOverrides` in `test_agent_settings_fragments.py`: a l a nested key each keep the environment's value, and only the keys the environment left out are reported. All four fail against the previous `_fill_missing`. +### `nats_url` no longer defaults to localhost outside development + +From the same review (their M1). `NATSClient.connect()` read `nats_url` with a default of +`nats://localhost:4222`. In a pod that is almost always wrong, and the failure mode is the worst +available: the connection happens in the background retry loop, which retries every error forever, +so a pod the operator deployed without computed settings kept retrying against itself while the +process looked alive. + +The reviewer asked for the default to go and for startup to fail naming the key. Removing it +outright would have broken the case the default exists for -- a broker on a developer's machine +with nothing configured -- so, agreed with the user, the fallback survives in development only: + +- **`NATSClient.on_startup()`** now resolves the URL through `_resolve_nats_url()`. Set: used. + Unset and `app_environment` is `"development"`: `DEVELOPMENT_NATS_URL`, with a WARNING naming the + agent. Unset anywhere else: `ValueError` naming `nats_url`, the environment, and the variable to + set (following the configured `envvar_prefix`, or unprefixed when there is none). The client + phase of the lifespan runs before the eventing services, so under sec. 9.1 this aborts a + standalone, root or critical agent before the port is bound and marks a non-critical one down -- + the same path `_resolve_queue_group()` takes. +- **`connect()`** uses the resolved URL, and resolves it itself if nothing ran `on_startup()`, so a + lazily connected client cannot reach localhost by the back door either. +- **`AppBuilder._warn_if_development()`**, called once at the start of the lifespan, logs that the + process runs in development mode and is not suitable for production. + +**The residual gap, stated rather than hidden.** `app_environment` itself defaults to +`"development"`, and no scaffolded file sets anything else. A pod that sets neither key therefore +still connects to localhost -- but now under two WARNINGs, one saying the process is in +development mode and one naming the fallback. Closing that fully would mean changing the +default environment, which is a larger decision than this fix; the user chose the warning. + +Docs: `reference/configuration-keys.md` (`nats_url`, `app_environment`) and a new symptom plus a +localhost note in `guides/troubleshooting.md`. Guarded by `TestNATSClientUrl` in +`test_nats_client.py` and `test_development_warning.py`. + --- ## Open points diff --git a/src/blueprint/agent_generator/docs/guides/troubleshooting.md b/src/blueprint/agent_generator/docs/guides/troubleshooting.md index 6ecf415b..06348799 100644 --- a/src/blueprint/agent_generator/docs/guides/troubleshooting.md +++ b/src/blueprint/agent_generator/docs/guides/troubleshooting.md @@ -179,6 +179,24 @@ nats sub test.subject In Kubernetes, verify the NATS service is deployed and the Dapr component configuration points to the correct address. +**Refused against `localhost:4222` inside a pod?** The process is in development mode: `app_environment` is +unset or `"development"`, and `nats_url` is unset, so it fell back to localhost. The log says so twice -- a +WARNING that the service is running in development mode, and one naming the fallback. Set `app_environment` +and `nats_url` for the deployment. + +### `'nats_url' is not set` on Startup + +**Symptom:** Startup fails, or one agent of a group is marked down, with: + +``` +ValueError: 'event_bus' is 'nats' but 'nats_url' is not set (app_environment is 'production'). ... +``` + +**Cause:** Outside development there is no default broker address. + +**Solution:** Set `nats_url` in the group's `settings.toml`, or in the environment as the variable the message +names (`DYNACONF_NATS_URL` with the default prefix). + ### Topic Mapping Mismatches **Symptom:** Events are published but handlers never receive them. diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 501ecd40..193efb76 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -14,7 +14,7 @@ Top-level application settings. |-----|------|---------|-------------| | `app_name` | `str` | `"agent_blueprint"` | Application name. Used in logging, health checks, and OpenTelemetry service identification. | | `app_port` | `int` | `8000` | HTTP port the application listens on. | -| `app_environment` | `str` | `"development"` | Deployment environment identifier (e.g., `"development"`, `"staging"`, `"production"`). | +| `app_environment` | `str` | `"development"` | Deployment environment identifier (e.g., `"development"`, `"staging"`, `"production"`). `"development"` enables development fallbacks such as the localhost default for `nats_url`, and the process logs a WARNING at startup that it is not suitable for production. Being the default, a deployment that sets nothing runs in development mode: set it to anything else to deploy. | | `log_level` | `str` | `"INFO"` | Root log level. One of `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`. | | `log_format` | `str` | `"text"` | Log output format. `"text"` for human-readable, `"json"` for structured JSON logging. | @@ -27,7 +27,7 @@ Settings for the event bus transport layer. | Key | Type | Default | Description | |-----|------|---------|-------------| | `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"`. | +| `nats_url` | `str` | none -- `"nats://localhost:4222"` in development only | NATS server URL. Only used when `event_bus = "nats"`. Unset, a process with `app_environment = "development"` connects to localhost and logs a WARNING saying so; in any other environment startup fails naming this key, because `localhost` is almost always wrong in a container and a client pointed at it retries forever while the pod looks healthy. A broker in the same pod is the exception: set `nats_url` to it explicitly. | | `dapr_pubsub_name` | `str` | `"pubsub"` | Dapr pub/sub component name, used when publishing and in the subscription document served at `GET /dapr/subscribe`. Only used when `event_bus = "dapr"`. | | `dapr_declarative_subscriptions` | `bool` | `false` | Set `true` when Dapr subscriptions are declared outside the application (Kubernetes `Subscription` resources or YAML). The discovery endpoint then serves an empty document, so the sidecar cannot subscribe twice. | | `nats_queue_group` | `str` | value of `app_name` | Queue group joined by every NATS subscription, so exactly one replica processes any given message. Identifies the agent, not the process: it must not contain a pod, container or replica name, or moving the agent between deployments would change which consumer it is. Startup fails if neither this key nor `app_name` yields a name. Applies to the root namespace only -- a client that belongs to a namespace uses the namespace name, so two agents sharing a process never share a group. Only used when `event_bus = "nats"`. | diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index b196ccf3..e43d0380 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -1282,6 +1282,26 @@ async def _start_component(self, kind: str, component: Any, label: str) -> None: return logger.info("%s %s startup completed", kind, label) + @staticmethod + def _warn_if_development(config: Config) -> None: + """Say, once per process, that this process runs with development defaults. + + ``app_environment`` defaults to ``"development"``, so a deployment that sets nothing runs in + development mode -- with the fallbacks that mode allows, such as ``nats_url`` defaulting + to ``localhost``. Those fallbacks are what make a developer's machine work without + configuration; in a pod they are almost always wrong. This line is what makes a deployment + that forgot to leave development mode visible in its own log. + """ + environment = str(config.get("app_environment", "development")) + if environment.lower() != "development": + return + logger.warning( + "This service is running in development mode (app_environment = %r), which is not suitable for " + "production: development falls back to defaults such as a localhost broker. Set app_environment to " + "deploy it.", + environment, + ) + async def _start_loop_diagnostics(self, config: Config) -> None: """Turn on asyncio debug mode, or start the watchdog, whichever this environment wants. @@ -1328,6 +1348,7 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: registry: Registry = Component.shared_registry # type: ignore[assignment] resolved_config = self._require_config() logger.info("Starting up application components") + self._warn_if_development(resolved_config) # Configure OpenTelemetry tracing, one identity per agent (C2). First in startup, # because Component.tracer caches the provider it resolves on first use and every diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index b37e9ec7..bd93fba7 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -27,6 +27,14 @@ logger = logging.getLogger(__name__) +DEVELOPMENT_NATS_URL = "nats://localhost:4222" +"""The broker a development process connects to when ``nats_url`` is unset -- and only then. + +In a container ``localhost`` is almost always wrong -- a broker in the same pod is the exception, and +it can say so -- and a client pointed at it retries forever while the pod looks healthy. So outside ``app_environment = "development"`` an unset ``nats_url`` fails +startup instead of reaching for this. +""" + DEAD_LETTERED_COUNTER = "blueprint.events.dead_lettered" """Events the framework gave up on, whether or not their payload was kept. @@ -136,6 +144,7 @@ class NATSClient(IOClientBase): def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: super().__init__(namespace=namespace) self._connection_name: str = "" + self._nats_url: str = "" self._nats_client: NatsClient | None = None self._js: JetStreamContext | None = None self._use_jetstream: bool = False @@ -541,6 +550,47 @@ def _resolve_connection_name(self) -> str: # Connection # ------------------------------------------------------------------ + async def on_startup(self) -> None: + """Resolve the broker URL, so a missing one fails this agent's startup (M1). + + Runs in the lifespan's client phase, before any connection is attempted. The connection + itself is made in a background retry loop that retries every error forever -- a missing + URL included, which is a configuration error no retry can fix. Resolved here, it is + reported once, against this agent, as ``_resolve_queue_group`` reports its own. + """ + self._nats_url = self._resolve_nats_url() + + def _resolve_nats_url(self) -> str: + """Return the configured ``nats_url``; outside development, refuse to run without one. + + Development falls back to :data:`DEVELOPMENT_NATS_URL` with a WARNING, so a broker on the + developer's machine needs no configuration. Anywhere else there is no fallback: a pod + pointed at ``localhost`` connects to nothing and never says so. + + Raises: + ValueError: if ``nats_url`` is unset or empty and ``app_environment`` is not + ``"development"``. Names the key, the environment, and how to set it. + """ + url = str(self.config.get("nats_url", "") or "").strip() + if url: + return url + environment = str(self.config.get("app_environment", "development")) + if environment.lower() == "development": + logger.warning( + "Agent '%s': 'nats_url' is not set, connecting to %s because app_environment is 'development'. " + "Set 'nats_url' for any other environment -- there, an unset one fails startup.", + self.namespace or ROOT_LABEL, + DEVELOPMENT_NATS_URL, + ) + return DEVELOPMENT_NATS_URL + prefix = self.config.envvar_prefix + variable = f"{prefix}_NATS_URL" if prefix else "NATS_URL" + raise ValueError( + f"'event_bus' is 'nats' but 'nats_url' is not set (app_environment is {environment!r}). Outside " + "development there is no default: localhost is rarely right in a container, and a client pointed at it retries " + f"forever while the pod looks healthy. Set 'nats_url' in the group's settings.toml or as {variable}." + ) + def _is_connected(self) -> bool: return self._nats_client is not None and not self._nats_client.is_closed and self._nats_client.is_connected @@ -549,7 +599,9 @@ async def connect(self) -> None: if self._nats_client is not None and not self._nats_client.is_closed: return - nats_url = self.config.get("nats_url", "nats://localhost:4222") + if not self._nats_url: + self._nats_url = self._resolve_nats_url() + nats_url = self._nats_url self._connection_name = self._resolve_connection_name() try: self._nats_client = await nats.connect( diff --git a/tests/unit/agents/app_builder/test_development_warning.py b/tests/unit/agents/app_builder/test_development_warning.py new file mode 100644 index 00000000..07f9da5f --- /dev/null +++ b/tests/unit/agents/app_builder/test_development_warning.py @@ -0,0 +1,36 @@ +"""A process in development mode says so, once, at startup (M1). + +``app_environment`` defaults to ``"development"``, and development is where fallbacks such as a +localhost broker apply. A deployment that forgot to leave it therefore runs on those fallbacks, +and this WARNING is what makes that visible in its own log. +""" + +import logging +from unittest.mock import MagicMock + +import pytest + +from blueprint.agents.app_builder import AppBuilder + +LOGGER = "blueprint.agents.app_builder" + + +def _config(**values: object) -> MagicMock: + config = MagicMock() + config.get.side_effect = lambda key, default=None: values.get(key, default) + return config + + +@pytest.mark.parametrize("environment", [None, "development", "Development"]) +def test_development_is_announced(environment: str | None, caplog: pytest.LogCaptureFixture) -> None: + values = {} if environment is None else {"app_environment": environment} + with caplog.at_level(logging.WARNING, logger=LOGGER): + AppBuilder._warn_if_development(_config(**values)) + assert "running in development mode" in caplog.text + assert "not suitable for production" in caplog.text + + +def test_another_environment_is_not(caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.WARNING, logger=LOGGER): + AppBuilder._warn_if_development(_config(app_environment="production")) + assert caplog.records == [] diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index 7363f02a..69da7425 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -9,7 +9,7 @@ from nats.js import api as js_api from blueprint.agents.clients.io.io_client_base import subject_is_covered_by -from blueprint.agents.clients.io.nats_client import ConsumerTuning, NATSClient +from blueprint.agents.clients.io.nats_client import DEVELOPMENT_NATS_URL, ConsumerTuning, NATSClient from blueprint.agents.models.errors import CriticalHandlerError, InvalidEventError, RetryableHandlerError from blueprint.agents.models.events import CloudEvent @@ -123,6 +123,63 @@ async def test_connect_raises_on_nats_error(self, nats_client: NATSClient) -> No await nats_client.connect() +class TestNATSClientUrl: + """M1 -- ``nats_url`` falls back to localhost in development only; elsewhere startup fails.""" + + @staticmethod + def _configure(mock_config: MagicMock, **values: object) -> None: + mock_config.get.side_effect = lambda key, default=None: values.get(key, default) + mock_config.envvar_prefix = "DYNACONF" + + async def test_a_configured_url_is_used(self, nats_client: NATSClient, mock_config: MagicMock, caplog) -> None: + self._configure(mock_config, nats_url="nats://broker:4222", app_environment="production") + with caplog.at_level(logging.WARNING, logger="blueprint.agents.clients.io.nats_client"): + await nats_client.on_startup() + assert nats_client._nats_url == "nats://broker:4222" + assert caplog.records == [] + + async def test_development_falls_back_to_localhost(self, nats_client: NATSClient, mock_config: MagicMock, caplog) -> None: + self._configure(mock_config, app_environment="development") + with caplog.at_level(logging.WARNING, logger="blueprint.agents.clients.io.nats_client"): + await nats_client.on_startup() + assert nats_client._nats_url == DEVELOPMENT_NATS_URL + assert "'nats_url' is not set" in caplog.text + + async def test_an_unset_environment_is_development(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """``app_environment`` defaults to development, and this follows the same default.""" + self._configure(mock_config) + await nats_client.on_startup() + assert nats_client._nats_url == DEVELOPMENT_NATS_URL + + @pytest.mark.parametrize("url", [None, "", " "]) + async def test_production_without_a_url_fails(self, nats_client: NATSClient, mock_config: MagicMock, url: str | None) -> None: + self._configure(mock_config, nats_url=url, app_environment="production") + with pytest.raises(ValueError, match=r"'nats_url' is not set \(app_environment is 'production'\).*DYNACONF_NATS_URL"): + await nats_client.on_startup() + + async def test_the_message_names_an_unprefixed_variable(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config, app_environment="production") + mock_config.envvar_prefix = False + with pytest.raises(ValueError, match="or as NATS_URL"): + await nats_client.on_startup() + + async def test_connect_uses_the_url_resolved_at_startup(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config, nats_url="nats://broker:4222", app_environment="production") + await nats_client.on_startup() + mock_nc = MagicMock(is_closed=False, is_connected=True) + with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock, return_value=mock_nc) as connect: + await nats_client.connect() + assert connect.call_args[0][0] == "nats://broker:4222" + + async def test_connect_without_startup_refuses_too(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """A client connected lazily, before any lifespan, must not reach localhost either.""" + self._configure(mock_config, app_environment="production") + with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock) as connect: + with pytest.raises(ValueError, match="'nats_url' is not set"): + await nats_client.connect() + connect.assert_not_awaited() + + class TestNATSClientClose: async def test_close_drains_all_subscriptions(self, connected_nats_client: NATSClient) -> None: sub = MagicMock(drain=AsyncMock(), unsubscribe=AsyncMock()) From eaefebdcfc056d15205393b41d4cf06bae68ba96 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 14:30:34 +0200 Subject: [PATCH 044/133] feat(nats): pass credentials and inbox prefix to the connection, and stop leaking URL credentials Under tenant-scoped auth the only way to authenticate was credentials inside nats_url. NATSClient now reads nats_user/nats_password, nats_token, nats_creds_file and nats_nkey_seed, plus nats_inbox_prefix for accounts not permitted _INBOX.>, and passes them to nats.connect(). They are resolved at startup and refused there when half-set, pointing at a missing file, or configured more than once (URL credentials count as one method). Read per agent, so each agent of a group can have its own account. The connect log line and the /health message both printed the URL with its user:password@; redact_url() now strips it from both. build: nats-py is declared as nats-py[nkeys], which creds files and nkey seeds need (nkeys 0.2.1 + PyNaCl, both Apache-2.0). Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 10 ++ ...26-08-28-multi-agent-grouping-changelog.md | 42 ++++++ pyproject.toml | 2 +- .../docs/reference/configuration-keys.md | 7 + .../agents/clients/io/nats_client.py | 125 ++++++++++++++++-- tests/unit/agents/clients/io/conftest.py | 5 +- .../agents/clients/io/test_nats_client.py | 122 ++++++++++++++++- 7 files changed, 301 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bf5a0267..89cf1794 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,9 @@ ### Fixed +- **Credentials inside `nats_url` no longer reach the log or `/health`.** The connect log line + printed the URL verbatim, and the NATS health message printed the parsed URL including + `user:password@`. Both now show `***@host:port`. - **An environment override of a key an agent's own `settings.toml` also sets now wins in a group.** `DYNACONF___KEY` was compared against the agent file's keys case-sensitively -- Dynaconf upper-cases what it loads, the file keeps lower case -- so the override was never seen: a list @@ -49,6 +52,13 @@ ### Added +- **NATS credentials from their own keys.** `nats_user`/`nats_password`, `nats_token`, + `nats_creds_file` and `nats_nkey_seed` are passed to the connection, so an account under + tenant-scoped auth no longer has to put its credentials inside `nats_url`. At most one method may + be configured; a half-set login, a creds file that is not there, or two methods at once fail + startup. `nats_inbox_prefix` replaces `_INBOX` for accounts not permitted `_INBOX.>`. All are read + per agent, so each agent of a group can have its own account. The dependency on `nats-py` is now + `nats-py[nkeys]`, which creds files and nkey seeds need. - **A `blueprint-migration` Claude Code skill**, installed by `asbs claude`: moving an existing single-agent project into a group -- the files it touches, the mistakes that break it, and how `asbs validate --group` checks it. The migration guide was previously reachable only from inside diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 44c8fd1a..1ac29d42 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7298,6 +7298,48 @@ Docs: `reference/configuration-keys.md` (`nats_url`, `app_environment`) and a ne localhost note in `guides/troubleshooting.md`. Guarded by `TestNATSClientUrl` in `test_nats_client.py` and `test_development_warning.py`. +### NATS connections can carry credentials, and a URL's credentials stop leaking + +From the same review (their M2). Under tenant-scoped auth the broker enforces per-account +permissions, and the only way to authenticate was credentials inside `nats_url` -- which makes the +URL a secret. Two places were not treating it as one: + +- **`connect()` logged it** at INFO in both "Connected to NATS server ..." lines. +- **`health_check()` put `connected_url` in its message**, and that is a `ParseResult` carrying + `user:password@`, so it reached `/health`. The existing tests mocked `connected_url` as a string, + which is why this was never seen; the mocks in `conftest.py` now use a `ParseResult`. + +`/status/env` was already safe: it masks keys by marker and strips userinfo from every URL. + +**What was built.** + +- **`redact_url()`**, module level in `nats_client.py`: returns the URL with its userinfo replaced + by `***`. Used by both call sites above. +- **`NATSClient._resolve_connect_options(nats_url)`**, called from `on_startup()` beside + `_resolve_nats_url()` (and from `connect()` if startup never ran), returns the keyword arguments + that `connect()` now splats into `nats.connect()`: `user`/`password`, `token`, + `user_credentials` (from `nats_creds_file`), `nkeys_seed_str` (from `nats_nkey_seed`) and + `inbox_prefix`. It refuses, at startup: one of `nats_user`/`nats_password` without the other; a + creds file that is not a file; more than one method, counting credentials in the URL as one; a + creds file or seed when the `nkeys` package is not installed; an inbox prefix with whitespace, a + wildcard or a trailing dot. It logs the method's *name* at DEBUG, never a value. +- Every key is read through the agent's view, so per-agent accounts work with + `[default.]` or `DYNACONF___NATS_CREDS_FILE` -- which, since the fix above, the + environment can now override. + +**`nkeys` is now a dependency**, declared as `nats-py[nkeys]` so nats-py chooses the compatible +version (0.2.1, which pulls in PyNaCl 1.6.2; both Apache-2.0). nats-py needs it for creds files and +nkey seeds; decided with the user over an optional extra, because creds files are the normal route +under decentralised auth, which is where tenant-scoped auth is heading. The startup check stays for +an environment installed without it. + +Installing it locally hit the known fatal uv `os error 5` (nkeys ships only as an sdist, and uv +cannot reopen the wheel it builds). Worked around by building the wheel with the system +interpreter's pip and installing that file with uv. `.venv` does not have it yet. + +Docs: five rows in `reference/configuration-keys.md` and a paragraph on choosing one method. +Guarded by `TestNATSClientAuthentication` and `TestRedactUrl` in `test_nats_client.py`. + --- ## Open points diff --git a/pyproject.toml b/pyproject.toml index 93caf550..6efb352c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,7 +40,7 @@ dependencies = [ "python-multipart>=0.0.20", "apscheduler>=3.11.2", "diskcache-rs>=0.4.4", - "nats-py>=2.13.1", + "nats-py[nkeys]>=2.13.1", "croniter>=6.0.0", "pyyaml>=6.0" ] diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 193efb76..35e74071 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -28,6 +28,11 @@ 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` | none -- `"nats://localhost:4222"` in development only | NATS server URL. Only used when `event_bus = "nats"`. Unset, a process with `app_environment = "development"` connects to localhost and logs a WARNING saying so; in any other environment startup fails naming this key, because `localhost` is almost always wrong in a container and a client pointed at it retries forever while the pod looks healthy. A broker in the same pod is the exception: set `nats_url` to it explicitly. | +| `nats_user` / `nats_password` | `str` | unset | Username and password for the NATS connection. Set both or neither. Put the password in `.secrets.toml` or the environment, never in `nats_url`: a URL carrying credentials is itself a secret. Only used when `event_bus = "nats"`. | +| `nats_token` | `str` | unset | Token authentication for the NATS connection. | +| `nats_creds_file` | `str` | unset | Path to a NATS credentials file (JWT + nkey), as issued for an account under decentralised auth. Startup fails if nothing is at that path. Requires the `nkeys` package. | +| `nats_nkey_seed` | `str` | unset | An nkey seed, by value, for nkey authentication. Requires the `nkeys` package. | +| `nats_inbox_prefix` | `str` | `"_INBOX"` | Prefix for request/reply and JetStream API reply subjects. Set it when the account's permissions do not allow `_INBOX.>` -- otherwise every JetStream call times out. No wildcards, no trailing dot. | | `dapr_pubsub_name` | `str` | `"pubsub"` | Dapr pub/sub component name, used when publishing and in the subscription document served at `GET /dapr/subscribe`. Only used when `event_bus = "dapr"`. | | `dapr_declarative_subscriptions` | `bool` | `false` | Set `true` when Dapr subscriptions are declared outside the application (Kubernetes `Subscription` resources or YAML). The discovery endpoint then serves an empty document, so the sidecar cannot subscribe twice. | | `nats_queue_group` | `str` | value of `app_name` | Queue group joined by every NATS subscription, so exactly one replica processes any given message. Identifies the agent, not the process: it must not contain a pod, container or replica name, or moving the agent between deployments would change which consumer it is. Startup fails if neither this key nor `app_name` yields a name. Applies to the root namespace only -- a client that belongs to a namespace uses the namespace name, so two agents sharing a process never share a group. Only used when `event_bus = "nats"`. | @@ -42,6 +47,8 @@ Settings for the event bus transport layer. | `nats_max_deliver` | `int` | `5` | Delivery attempts before the message is dead-lettered. `-1` is unlimited, which means a permanently failing message is retried forever and never dead-lettered; the client logs a warning at startup if you set it. | | `nats_dead_letter_subject` | `str` | `".dead-letter"` | Subject a message is republished to when the framework gives up on it -- either a terminal failure (`InvalidEventError`, `CriticalHandlerError`, or a payload that is not a CloudEvent) or `nats_max_deliver` attempts spent. The original bytes are republished unchanged, with `Blueprint-Dead-Letter-Reason`, `Blueprint-Original-Subject`, `Blueprint-Delivery-Count` and `Blueprint-Event-Id` headers. Set to `""` to disable, which drops those messages and loses their payloads. Startup fails if the subject is a wildcard or is itself one of the subscribed subjects, since that would loop. | +**NATS authentication:** `nats_user`/`nats_password`, `nats_token`, `nats_creds_file`, `nats_nkey_seed` and credentials inside `nats_url` are alternatives -- configure at most one. Two at once fail startup rather than leaving the choice to the client library. All of them are read per agent, so a group can give each agent its own account with `[default.]` or `DYNACONF___NATS_CREDS_FILE`. `/status/env` masks the secret keys, and the URL's credentials are stripped from logs, `/health` and `/status/env`. + --- ## Deployment Identity (environment only) diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index bd93fba7..114b5cb4 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -2,13 +2,16 @@ import asyncio import contextlib +import importlib.util import json import logging import re from collections.abc import Awaitable, Callable from dataclasses import dataclass from functools import cached_property +from pathlib import Path from typing import Any +from urllib.parse import urlsplit, urlunsplit import nats from nats.aio.client import Client as NatsClient @@ -31,10 +34,28 @@ """The broker a development process connects to when ``nats_url`` is unset -- and only then. In a container ``localhost`` is almost always wrong -- a broker in the same pod is the exception, and -it can say so -- and a client pointed at it retries forever while the pod looks healthy. So outside ``app_environment = "development"`` an unset ``nats_url`` fails -startup instead of reaching for this. +it can say so -- and a client pointed at it retries forever while the pod looks healthy. So outside +``app_environment = "development"`` an unset ``nats_url`` fails startup instead of reaching for this. """ + +def redact_url(url: str) -> str: + """Return ``url`` without its ``user:password@`` part, for logs and health messages. + + Credentials in ``nats_url`` are still accepted, so every place that shows the URL has to strip + them: the connect log line and the ``/health`` message both used to print it verbatim. + """ + try: + parts = urlsplit(url) + except ValueError: + return "" + if not parts.username and not parts.password: + return url + host = parts.hostname or "" + netloc = f"{host}:{parts.port}" if parts.port else host + return urlunsplit(parts._replace(netloc=f"***@{netloc}")) + + DEAD_LETTERED_COUNTER = "blueprint.events.dead_lettered" """Events the framework gave up on, whether or not their payload was kept. @@ -145,6 +166,7 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: super().__init__(namespace=namespace) self._connection_name: str = "" self._nats_url: str = "" + self._connect_options: dict[str, Any] = {} self._nats_client: NatsClient | None = None self._js: JetStreamContext | None = None self._use_jetstream: bool = False @@ -551,14 +573,16 @@ def _resolve_connection_name(self) -> str: # ------------------------------------------------------------------ async def on_startup(self) -> None: - """Resolve the broker URL, so a missing one fails this agent's startup (M1). + """Resolve the broker URL and credentials, so a bad one fails this agent's startup (M1, M2). Runs in the lifespan's client phase, before any connection is attempted. The connection itself is made in a background retry loop that retries every error forever -- a missing - URL included, which is a configuration error no retry can fix. Resolved here, it is - reported once, against this agent, as ``_resolve_queue_group`` reports its own. + URL or a half-configured credential included, which are configuration errors no retry can + fix. Resolved here, they are reported once, against this agent, as + ``_resolve_queue_group`` reports its own. """ self._nats_url = self._resolve_nats_url() + self._connect_options = self._resolve_connect_options(self._nats_url) def _resolve_nats_url(self) -> str: """Return the configured ``nats_url``; outside development, refuse to run without one. @@ -591,6 +615,88 @@ def _resolve_nats_url(self) -> str: f"forever while the pod looks healthy. Set 'nats_url' in the group's settings.toml or as {variable}." ) + def _resolve_connect_options(self, nats_url: str) -> dict[str, Any]: + """Return the credential and inbox arguments for ``nats.connect()`` (M2). + + One authentication method at most, each from its own keys: + + - ``nats_user`` and ``nats_password`` -- username and password (``user``, ``password``) + - ``nats_token`` -- a token (``token``) + - ``nats_creds_file`` -- a JWT + nkey credentials file, by path (``user_credentials``) + - ``nats_nkey_seed`` -- an nkey seed, by value (``nkeys_seed_str``) + + Keeping them out of ``nats_url`` is the point: a URL carrying ``user:pass@`` makes the + URL a secret, and every place that shows the URL has to know to strip it. The secret + values belong in ``.secrets.toml`` or the environment; ``/status/env`` masks all four + keys by name. The keys are read through this agent's view, so a group can give each + agent its own account. + + ``nats_inbox_prefix`` replaces ``_INBOX`` for request/reply inboxes and JetStream API + replies. An account restricted by subject permissions is usually not allowed + ``_INBOX.>``, and without this every JetStream call it makes times out. + + Raises: + ValueError: if more than one method is configured (``user:pass@`` in ``nats_url`` + counts as one), if only one of ``nats_user``/``nats_password`` is set, if + ``nats_creds_file`` names no file, if the ``nkeys`` package that creds files + and seeds need is not installed, or if ``nats_inbox_prefix`` is not a subject. + """ + options: dict[str, Any] = {} + methods: list[str] = [] + + user = self._read_str("nats_user") + password = self._read_str("nats_password") + if bool(user) != bool(password): + missing = "nats_password" if user else "nats_user" + raise ValueError(f"'nats_user' and 'nats_password' go together, and '{missing}' is not set.") + if user: + options.update(user=user, password=password) + methods.append("nats_user/nats_password") + + token = self._read_str("nats_token") + if token: + options["token"] = token + methods.append("nats_token") + + creds_file = self._read_str("nats_creds_file") + if creds_file: + if not Path(creds_file).is_file(): + raise ValueError(f"'nats_creds_file' is '{creds_file}', which is not a file. Is the secret mounted there?") + options["user_credentials"] = creds_file + methods.append("nats_creds_file") + + seed = self._read_str("nats_nkey_seed") + if seed: + options["nkeys_seed_str"] = seed + methods.append("nats_nkey_seed") + + if urlsplit(nats_url).username: + methods.append("credentials in 'nats_url'") + if len(methods) > 1: + raise ValueError( + f"NATS authentication is configured more than once: {', '.join(methods)}. The broker accepts one " + "method per connection, and which one nats-py would send is not something to leave to chance. " + "Keep exactly one." + ) + if ("user_credentials" in options or "nkeys_seed_str" in options) and importlib.util.find_spec("nkeys") is None: + raise ValueError( + f"'{methods[0]}' needs the 'nkeys' package to sign the server's challenge, and it is not installed. " + "Install it with: pip install nkeys" + ) + + inbox_prefix = self._read_str("nats_inbox_prefix") + if inbox_prefix: + validate_publish_subject(inbox_prefix, source="'nats_inbox_prefix'") + if inbox_prefix.endswith("."): + raise ValueError(f"'nats_inbox_prefix' is '{inbox_prefix}'. Leave out the trailing dot; nats-py adds it.") + options["inbox_prefix"] = inbox_prefix + + logger.debug("Agent '%s' authenticates to NATS with %s", self.namespace or ROOT_LABEL, methods[0] if methods else "no credentials") + return options + + def _read_str(self, key: str) -> str: + return str(self.config.get(key, "") or "").strip() + def _is_connected(self) -> bool: return self._nats_client is not None and not self._nats_client.is_closed and self._nats_client.is_connected @@ -601,17 +707,19 @@ async def connect(self) -> None: if not self._nats_url: self._nats_url = self._resolve_nats_url() - nats_url = self._nats_url + self._connect_options = self._resolve_connect_options(self._nats_url) + nats_url = redact_url(self._nats_url) self._connection_name = self._resolve_connection_name() try: self._nats_client = await nats.connect( - nats_url, + self._nats_url, name=self._connection_name, max_reconnect_attempts=self.config.get("nats_max_reconnect_attempts", 5), reconnect_time_wait=self.config.get("nats_reconnect_time_wait", 2), connect_timeout=10, disconnected_cb=self._on_disconnected, reconnected_cb=self._on_reconnected, + **self._connect_options, ) self._client = self._nats_client self._use_jetstream = self.config.get("nats_use_jetstream", False) @@ -821,7 +929,8 @@ async def health_check(self) -> ComponentHealth: return ComponentHealth(status="healthy", message="connected; consumption paused while this agent is degraded") if self._subscriptions_managed and not self._subscriptions_ready: return ComponentHealth(status="unhealthy", message="connected but subscriptions not yet established") - server_info = self._nats_client.connected_url # type: ignore[union-attr] + connected = self._nats_client.connected_url # type: ignore[union-attr] + server_info = redact_url(connected.geturl()) if connected is not None else "an unknown server" sub_info = f" ({len(self._subscriptions)} subscriptions active)" if self._subscriptions else "" return ComponentHealth(status="healthy", message=f"Connected to NATS server at {server_info}{sub_info}") diff --git a/tests/unit/agents/clients/io/conftest.py b/tests/unit/agents/clients/io/conftest.py index 36124885..375f3366 100644 --- a/tests/unit/agents/clients/io/conftest.py +++ b/tests/unit/agents/clients/io/conftest.py @@ -1,6 +1,7 @@ """Shared fixtures for IO client unit tests.""" from unittest.mock import AsyncMock, MagicMock +from urllib.parse import urlparse import pytest from nats.js.errors import NotFoundError @@ -80,7 +81,7 @@ def mock_nats_core() -> MagicMock: mock = MagicMock() mock.is_closed = False mock.is_connected = True - mock.connected_url = "nats://localhost:4222" + mock.connected_url = urlparse("nats://localhost:4222") # nats-py returns a ParseResult, not a str mock.publish = AsyncMock() mock.subscribe = AsyncMock(return_value=MagicMock(unsubscribe=AsyncMock())) mock.close = AsyncMock() @@ -109,7 +110,7 @@ def mock_nats_jetstream() -> tuple[MagicMock, MagicMock]: mock_nc = MagicMock() mock_nc.is_closed = False mock_nc.is_connected = True - mock_nc.connected_url = "nats://localhost:4222" + mock_nc.connected_url = urlparse("nats://localhost:4222") # nats-py returns a ParseResult, not a str mock_nc.publish = AsyncMock() mock_nc.close = AsyncMock() mock_nc.jetstream = MagicMock(return_value=mock_js) diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index 69da7425..2c9f9558 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -4,12 +4,13 @@ import json import logging from unittest.mock import AsyncMock, MagicMock, patch +from urllib.parse import urlparse import pytest from nats.js import api as js_api from blueprint.agents.clients.io.io_client_base import subject_is_covered_by -from blueprint.agents.clients.io.nats_client import DEVELOPMENT_NATS_URL, ConsumerTuning, NATSClient +from blueprint.agents.clients.io.nats_client import DEVELOPMENT_NATS_URL, ConsumerTuning, NATSClient, redact_url from blueprint.agents.models.errors import CriticalHandlerError, InvalidEventError, RetryableHandlerError from blueprint.agents.models.events import CloudEvent @@ -180,6 +181,125 @@ async def test_connect_without_startup_refuses_too(self, nats_client: NATSClient connect.assert_not_awaited() +class TestNATSClientAuthentication: + """M2 -- credentials and the inbox prefix reach ``nats.connect()`` from their own keys.""" + + URL = "nats://broker:4222" + + @staticmethod + def _configure(mock_config: MagicMock, **values: object) -> None: + values.setdefault("nats_url", TestNATSClientAuthentication.URL) + mock_config.get.side_effect = lambda key, default=None: values.get(key, default) + mock_config.envvar_prefix = "DYNACONF" + + @staticmethod + async def _connect_kwargs(client: NATSClient) -> dict: + await client.on_startup() + mock_nc = MagicMock(is_closed=False, is_connected=True) + with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock, return_value=mock_nc) as connect: + await client.connect() + return connect.call_args.kwargs + + async def test_no_credentials_passes_none(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config) + kwargs = await self._connect_kwargs(nats_client) + assert not {"user", "password", "token", "user_credentials", "nkeys_seed_str", "inbox_prefix"} & kwargs.keys() + + async def test_user_and_password(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config, nats_user="agent", nats_password="YOUR_PASSWORD_HERE") + kwargs = await self._connect_kwargs(nats_client) + assert (kwargs["user"], kwargs["password"]) == ("agent", "YOUR_PASSWORD_HERE") + + @pytest.mark.parametrize(("given", "missing"), [({"nats_user": "agent"}, "nats_password"), ({"nats_password": "x"}, "nats_user")]) + async def test_half_a_login_fails_startup(self, nats_client: NATSClient, mock_config: MagicMock, given: dict, missing: str) -> None: + self._configure(mock_config, **given) + with pytest.raises(ValueError, match=f"'{missing}' is not set"): + await nats_client.on_startup() + + async def test_token(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config, nats_token="YOUR_TOKEN_HERE") + assert (await self._connect_kwargs(nats_client))["token"] == "YOUR_TOKEN_HERE" + + async def test_creds_file(self, nats_client: NATSClient, mock_config: MagicMock, tmp_path) -> None: + creds = tmp_path / "agent.creds" + creds.write_text("placeholder") + self._configure(mock_config, nats_creds_file=str(creds)) + with patch("blueprint.agents.clients.io.nats_client.importlib.util.find_spec", return_value=object()): + kwargs = await self._connect_kwargs(nats_client) + assert kwargs["user_credentials"] == str(creds) + + async def test_a_creds_file_that_is_not_there_fails_startup(self, nats_client: NATSClient, mock_config: MagicMock, tmp_path) -> None: + self._configure(mock_config, nats_creds_file=str(tmp_path / "missing.creds")) + with pytest.raises(ValueError, match="not a file"): + await nats_client.on_startup() + + async def test_nkey_seed(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config, nats_nkey_seed="YOUR_SEED_HERE") + with patch("blueprint.agents.clients.io.nats_client.importlib.util.find_spec", return_value=object()): + kwargs = await self._connect_kwargs(nats_client) + assert kwargs["nkeys_seed_str"] == "YOUR_SEED_HERE" + + async def test_a_seed_without_nkeys_installed_fails_startup(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config, nats_nkey_seed="YOUR_SEED_HERE") + with patch("blueprint.agents.clients.io.nats_client.importlib.util.find_spec", return_value=None): + with pytest.raises(ValueError, match="needs the 'nkeys' package"): + await nats_client.on_startup() + + @pytest.mark.parametrize( + "values", + [ + {"nats_user": "a", "nats_password": "b", "nats_token": "c"}, + {"nats_token": "c", "nats_nkey_seed": "d"}, + {"nats_url": "nats://a:b@broker:4222", "nats_token": "c"}, + ], + ) + async def test_two_methods_fail_startup(self, nats_client: NATSClient, mock_config: MagicMock, values: dict) -> None: + self._configure(mock_config, **values) + with pytest.raises(ValueError, match="configured more than once"): + await nats_client.on_startup() + + async def test_credentials_in_the_url_alone_still_work(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config, nats_url="nats://a:b@broker:4222") + await nats_client.on_startup() + assert nats_client._connect_options == {} + + async def test_inbox_prefix(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config, nats_inbox_prefix="_INBOX_risk") + assert (await self._connect_kwargs(nats_client))["inbox_prefix"] == "_INBOX_risk" + + @pytest.mark.parametrize("prefix", ["_INBOX.*", "_INBOX.risk.", "has space"]) + async def test_an_unusable_inbox_prefix_fails_startup(self, nats_client: NATSClient, mock_config: MagicMock, prefix: str) -> None: + self._configure(mock_config, nats_inbox_prefix=prefix) + with pytest.raises(ValueError, match="nats_inbox_prefix"): + await nats_client.on_startup() + + async def test_nothing_secret_is_logged(self, nats_client: NATSClient, mock_config: MagicMock, caplog) -> None: + self._configure(mock_config, nats_url="nats://a:YOUR_PASSWORD_HERE@broker:4222") + with caplog.at_level(logging.DEBUG, logger="blueprint.agents.clients.io.nats_client"): + await self._connect_kwargs(nats_client) + assert "YOUR_PASSWORD_HERE" not in caplog.text + assert "***@broker:4222" in caplog.text + + +class TestRedactUrl: + @pytest.mark.parametrize( + ("url", "expected"), + [ + ("nats://broker:4222", "nats://broker:4222"), + ("nats://user:secret@broker:4222", "nats://***@broker:4222"), + ("nats://tokenonly@broker", "nats://***@broker"), + ], + ) + def test_userinfo_is_removed(self, url: str, expected: str) -> None: + assert redact_url(url) == expected + + async def test_the_health_message_does_not_carry_it(self, connected_nats_client: NATSClient) -> None: + connected_nats_client._nats_client.connected_url = urlparse("nats://user:secret@broker:4222") + result = await connected_nats_client.health_check() + assert "secret" not in result.message + assert "***@broker:4222" in result.message + + class TestNATSClientClose: async def test_close_drains_all_subscriptions(self, connected_nats_client: NATSClient) -> None: sub = MagicMock(drain=AsyncMock(), unsubscribe=AsyncMock()) From 49bbf844b3c2e6b7e4a6321191e4f11b1d187d92 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 14:44:31 +0200 Subject: [PATCH 045/133] feat(nats)!: hand the delivery subject to handlers as context["nats_subject"] The tenant-auth plan needs the tenant from the subject the broker checked, not from the publisher-controlled event.tenantid. _subscribe_one() passed its callback only the decoded event, and the handler context held only nats_topic -- the subscription, possibly a wildcard. NATSClient now calls callback(event, msg.subject), and NatsEventing puts the subject into the handler context under NATS_SUBJECT_CONTEXT_KEY. The event itself is never modified; the context is built from transport facts only, so a publisher cannot supply the value. BREAKING CHANGE: ClientBase.subscribe() callbacks are now DeliveryCallback, Callable[[CloudEvent, str], Awaitable[None]]. A one-argument callback passed to NATSClient.subscribe() fails on its first message. Handlers are unaffected. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 9 ++++ ...26-08-28-multi-agent-grouping-changelog.md | 44 ++++++++++++++++ .../docs/components/event-handlers.md | 27 ++++++++++ .../agents/clients/ai/openai_client.py | 4 +- .../agents/clients/ai/vllm_client.py | 4 +- src/blueprint/agents/clients/client_base.py | 14 ++++- .../agents/clients/io/dapr_client.py | 6 +-- .../agents/clients/io/nats_client.py | 10 ++-- src/blueprint/agents/io/api/eventing/dapr.py | 18 ++++--- src/blueprint/agents/io/api/eventing/nats.py | 21 +++++--- .../agents/clients/io/test_nats_client.py | 51 ++++++++++++------- .../unit/agents/io/api/eventing/test_nats.py | 27 ++++++++-- 12 files changed, 187 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 89cf1794..8d707b2f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,10 @@ ### Added +- **Handlers see the subject a NATS message was delivered on**, as `context["nats_subject"]` + (`NATS_SUBJECT_CONTEXT_KEY`), beside `nats_topic`, which is the subscription and may be a + wildcard. It comes from the broker, not the event, so a tenant can be derived from the subject the + broker checked rather than from the publisher-controlled `tenantid`. - **NATS credentials from their own keys.** `nats_user`/`nats_password`, `nats_token`, `nats_creds_file` and `nats_nkey_seed` are passed to the connection, so an account under tenant-scoped auth no longer has to put its credentials inside `nats_url`. At most one method may @@ -102,6 +106,11 @@ ### Breaking +- **`ClientBase.subscribe()` callbacks take the delivery subject.** The contract is now + `DeliveryCallback = Callable[[CloudEvent, str], Awaitable[None]]` (in `clients/client_base.py`): + the event, then the subject it arrived on. Only code that calls `NATSClient.subscribe()` directly, + or implements `ClientBase`, is affected -- handlers are not. A one-argument callback now fails + with a `TypeError` on the first message. - **`nats_url` has no default outside development.** With `event_bus = "nats"` and no `nats_url`, a process whose `app_environment` is anything but `"development"` now fails startup naming the key -- a standalone or critical agent before the port is bound, a non-critical agent of a group diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 1ac29d42..13a61e69 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7340,6 +7340,50 @@ interpreter's pip and installing that file with uv. `.venv` does not have it yet Docs: five rows in `reference/configuration-keys.md` and a paragraph on choosing one method. Guarded by `TestNATSClientAuthentication` and `TestRedactUrl` in `test_nats_client.py`. +### Handlers see the subject a message was delivered on + +From the same review (their cross-repo change 1, the real fix for their W17 interim). The +tenant-auth plan wants the tenant taken from the subject the broker checked, not from the +publisher-controlled `event.tenantid`. `_subscribe_one()` passed its callback only the decoded +event, and the context `NatsEventing` built held `nats_topic` -- the *subscription*, e.g. +`t.*.risk.>`, which says nothing about which tenant matched. + +The reviewer offered two routes: the handler context, or a framework-set CloudEvent extension. +**The context was chosen** because a publisher cannot reach it by construction: the context is +built by the transport edge from transport facts, and nothing in the event is copied into it. An +extension would live in the payload the publisher writes, and the framework would have to +overwrite or strip it on every delivery -- a guarantee that holds only as long as no path forgets. + +**What changed.** + +- **`DeliveryCallback`**, new in `clients/client_base.py`: + `Callable[[CloudEvent[Any], str], Awaitable[None]]`. `ClientBase.subscribe()`'s abstract + signature fixed callbacks to one argument, so passing the subject from NATS alone would have + violated the contract (mypy caught it as an incompatible override). The contract itself is + widened instead, and `NATSClient`, `DaprClient`, `OpenAIClient` and `VLLMClient` use it. +- **`NATSClient._subscribe_one()`**: `await callback(cloud_event, msg.subject)`. +- **`NatsEventing._make_event_callback()`**: the callback takes the subject and builds + `{"nats_topic": topic, NATS_SUBJECT_CONTEXT_KEY: subject}`. The constant is public in + `io/api/eventing/nats.py`. +- **`DaprEventing._make_event_callback()`** accepts and ignores it: `DaprClient` stores its + callbacks and never calls them, because Dapr delivers over HTTP (verified: nothing indexes + `_topic_callbacks`). + +**Breaking**, and recorded as such: a one-argument callback handed to `NATSClient.subscribe()` +now fails on its first message. Handlers are unaffected. Eighteen test callbacks in +`test_nats_client.py` and two call sites in `test_nats.py` were written against the old shape and +were updated. + +**Not covered, and stated:** Dapr has no equivalent. The sidecar delivers to a fixed topic path, +and whether its envelope's `topic` is broker-checked depends on the pubsub component, not on this +framework. A handler under Dapr gets no `nats_subject` and must not assume one. + +Docs: *What the transport puts in `context`* in `components/event-handlers.md`, with the three +transport keys and the rule to derive tenants from the subject. Guarded by +`test_the_delivery_subject_reaches_the_callback` in `test_nats_client.py` and +`TestNatsEventingDeliverySubject` in `test_nats.py`, including an event that carries a spoofed +`nats_subject` extension and a different `tenantid`. + --- ## Open points diff --git a/src/blueprint/agent_generator/docs/components/event-handlers.md b/src/blueprint/agent_generator/docs/components/event-handlers.md index 4f7464b6..b8cb2dbd 100644 --- a/src/blueprint/agent_generator/docs/components/event-handlers.md +++ b/src/blueprint/agent_generator/docs/components/event-handlers.md @@ -130,6 +130,33 @@ class EnricherHandler(EventHandlerBase): return HandlerResult(event_type="webhook.processed", data=enriched) ``` +### What the transport puts in `context` + +Before the first handler runs, the transport that delivered the event writes what it knows about the +delivery: + +| Key | Transport | Value | +|---|---|---| +| `nats_topic` | NATS | The subscription that matched, possibly a wildcard: `t.*.risk.>` | +| `nats_subject` | NATS | The subject the message was delivered on: `t.T1.risk.created` | +| `dapr_topic` | Dapr | The topic the sidecar delivered to | + +**Derive anything security-relevant from `nats_subject`, not from the event.** Every field of the +event -- `tenantid` and any other extension included -- is whatever the publisher wrote. The subject +is what the broker routed, and under subject-scoped publish permissions it is what the broker checked +the publisher was allowed to use. Nothing in the payload can overwrite a context key. + +```python +from blueprint.agents.io.api.eventing.nats import NATS_SUBJECT_CONTEXT_KEY + +async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> None: + tenant = context[NATS_SUBJECT_CONTEXT_KEY].split(".")[1] # t..risk. +``` + +The key is present only for events NATS delivered: a test, a direct `process_event` call or another +transport has no subject, so read it with `.get()` where that can happen. Handlers share `context`, +so a handler earlier in the chain could overwrite it -- do not write to transport keys. + ## Published Event Types Optionally declare the event types this handler can produce. Used for documentation and subscription introspection. diff --git a/src/blueprint/agents/clients/ai/openai_client.py b/src/blueprint/agents/clients/ai/openai_client.py index 944f197c..50b00aca 100644 --- a/src/blueprint/agents/clients/ai/openai_client.py +++ b/src/blueprint/agents/clients/ai/openai_client.py @@ -1,7 +1,6 @@ """OpenAI client implementation.""" import logging -from collections.abc import Awaitable, Callable from typing import Any from openai import AsyncOpenAI @@ -9,6 +8,7 @@ from pydantic_ai.models.openai import OpenAIResponsesModel, OpenAIResponsesModelSettings from pydantic_ai.providers.openai import OpenAIProvider +from ..client_base import DeliveryCallback from .ai_client_base import AIClientBase from ...models.api import ComponentHealth from ...models.events import CloudEvent @@ -30,7 +30,7 @@ async def close(self) -> None: await self._client.close() self._client = None - async def subscribe(self, topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]]) -> None: + async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: logger.warning("OpenAI client does not support subscriptions") async def publish(self, topic: str, event: CloudEvent[Any], routing_key: str | None = None) -> None: diff --git a/src/blueprint/agents/clients/ai/vllm_client.py b/src/blueprint/agents/clients/ai/vllm_client.py index ce8d5d5a..005a4efe 100644 --- a/src/blueprint/agents/clients/ai/vllm_client.py +++ b/src/blueprint/agents/clients/ai/vllm_client.py @@ -1,7 +1,6 @@ """VLLM client implementation.""" import logging -from collections.abc import Awaitable, Callable from typing import Any from openai import AsyncOpenAI @@ -10,6 +9,7 @@ from pydantic_ai.profiles import ModelProfile from pydantic_ai.providers.openai import OpenAIProvider +from ..client_base import DeliveryCallback from .ai_client_base import AIClientBase from ...models.api import ComponentHealth from ...models.events import CloudEvent @@ -38,7 +38,7 @@ async def close(self) -> None: await self._client.close() self._client = None - async def subscribe(self, topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]]) -> None: + async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: logger.warning("VLLM client does not support subscriptions") async def publish(self, topic: str, event: CloudEvent[Any], routing_key: str | None = None) -> None: diff --git a/src/blueprint/agents/clients/client_base.py b/src/blueprint/agents/clients/client_base.py index 1324144f..78d1fd2d 100644 --- a/src/blueprint/agents/clients/client_base.py +++ b/src/blueprint/agents/clients/client_base.py @@ -12,6 +12,18 @@ from ..io.api.actuators.health.health_base import ComponentHealth +DeliveryCallback = Callable[[CloudEvent[Any], str], Awaitable[None]] +"""What a transport's ``subscribe()`` calls for each message: the decoded event, and the subject it arrived on. + +The subject is passed beside the event rather than inside it because it is the one fact about a +delivery the publisher does not control. ``msg.subject`` is what the broker routed -- and, under +subject-scoped permissions, what it checked the publisher was allowed to publish to -- while every +field of the event, a tenant id included, is whatever the publisher wrote. A handler that must know +*which* subject a wildcard subscription matched (``t.*.risk.>`` delivering ``t.T1.risk.created``) +needs the former, so it travels outside the payload, where nothing in the payload can overwrite it. +""" + + class ClientBase(Component, ABC): """Abstract base class for all clients (IO transports, AI providers). @@ -76,7 +88,7 @@ async def close(self) -> None: raise NotImplementedError @abstractmethod - async def subscribe(self, topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]]) -> None: + async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: """Register all topic→callback mappings and begin the managed connection + subscription cycle. Implementations must be non-blocking: store the mapping and start a diff --git a/src/blueprint/agents/clients/io/dapr_client.py b/src/blueprint/agents/clients/io/dapr_client.py index 393b5be8..2ce3697a 100644 --- a/src/blueprint/agents/clients/io/dapr_client.py +++ b/src/blueprint/agents/clients/io/dapr_client.py @@ -4,7 +4,6 @@ import contextlib import json import logging -from collections.abc import Awaitable, Callable from typing import Any import httpx @@ -13,6 +12,7 @@ from ...models.api import ComponentHealth from ...models.events import CloudEvent from .io_client_base import IOClientBase +from ..client_base import DeliveryCallback logger = logging.getLogger(__name__) @@ -54,7 +54,7 @@ class DaprClient(IOClientBase): def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: super().__init__(namespace=namespace) - self._topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = {} + self._topic_callbacks: dict[str, DeliveryCallback] = {} self._subscriptions_ready: bool = False self._subscriptions_managed: bool = False self._retry_task: asyncio.Task[None] | None = None @@ -72,7 +72,7 @@ def subscriptions_ready(self) -> bool: # Managed subscription API # ------------------------------------------------------------------ - async def subscribe(self, topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]]) -> None: + async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: """Store topic→callback mappings and start the background sidecar-ping retry task. Returns immediately; sidecar reachability check happens in the background. diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 114b5cb4..2ae9c7c4 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -6,7 +6,6 @@ import json import logging import re -from collections.abc import Awaitable, Callable from dataclasses import dataclass from functools import cached_property from pathlib import Path @@ -26,6 +25,7 @@ from ...models.api import ComponentHealth from ...models.errors import DeliveryDisposition, disposition_for from ...models.events import CloudEvent +from ..client_base import DeliveryCallback from .io_client_base import IOClientBase, subject_is_covered_by, validate_publish_subject, validate_subject_segment logger = logging.getLogger(__name__) @@ -173,7 +173,7 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: self._publish_via_jetstream: bool = False self._publish_subjects: set[str] = set() self._subscriptions: list[Any] = [] - self._topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = {} + self._topic_callbacks: dict[str, DeliveryCallback] = {} self._queue_group: str = "" self._tuning: ConsumerTuning | None = None self._durables: dict[str, str] = {} @@ -232,7 +232,7 @@ def connection_name(self) -> str: # Managed subscription API # ------------------------------------------------------------------ - async def subscribe(self, topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]]) -> None: + async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: """Register all topic→callback mappings and start the background retry task. Returns immediately; connection and subscription happen in the background. @@ -1147,7 +1147,7 @@ def _consumer_drift(actual: js_api.ConsumerConfig, desired: js_api.ConsumerConfi # Internal — per-topic subscription # ------------------------------------------------------------------ - async def _subscribe_one(self, topic: str, callback: Callable[[CloudEvent[Any]], Awaitable[None]]) -> None: + async def _subscribe_one(self, topic: str, callback: DeliveryCallback) -> None: client = await self.client async def message_handler(msg: Any) -> None: @@ -1160,7 +1160,7 @@ async def message_handler(msg: Any) -> None: return try: - await callback(cloud_event) + await callback(cloud_event, msg.subject) except Exception as ex: disposition = disposition_for(ex) logger.error( diff --git a/src/blueprint/agents/io/api/eventing/dapr.py b/src/blueprint/agents/io/api/eventing/dapr.py index e60dbc2f..c32c3616 100644 --- a/src/blueprint/agents/io/api/eventing/dapr.py +++ b/src/blueprint/agents/io/api/eventing/dapr.py @@ -1,7 +1,7 @@ """Generic Dapr pub/sub endpoints for the agent service (framework-level).""" import logging -from collections.abc import Awaitable, Callable, Coroutine +from collections.abc import Callable, Coroutine from typing import Any from fastapi import Request, Response @@ -9,6 +9,7 @@ from fastapi.responses import JSONResponse from fastapi.routing import APIRoute +from ....clients.client_base import DeliveryCallback from ....clients.io.dapr_client import DaprClient from ....component.namespace import ROOT_LABEL, ROOT_NAMESPACE, namespace_of from ....models.errors import DeliveryDisposition, HandlerError, combined_disposition, disposition_for @@ -138,9 +139,7 @@ async def on_startup(self) -> None: for namespace, topics in topics_by_agent.items(): client = self.registry.get_component(DaprClient, namespace=namespace) self._clients[namespace] = client - topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = { - topic: self._make_event_callback(topic) for topic in topics - } + topic_callbacks: dict[str, DeliveryCallback] = {topic: self._make_event_callback(topic) for topic in topics} logger.info( "Namespace '%s' declares %d topic(s) to the sidecar: %s", namespace or ROOT_LABEL, @@ -152,10 +151,15 @@ async def on_startup(self) -> None: async def on_shutdown(self) -> None: pass - def _make_event_callback(self, topic: str) -> Callable[[CloudEvent[Any]], Awaitable[None]]: - """Return an async callback that routes an incoming Dapr event through the handler chain.""" + def _make_event_callback(self, topic: str) -> DeliveryCallback: + """Return an async callback that routes an incoming Dapr event through the handler chain. - async def _process_event(event: CloudEvent[Any]) -> None: + The subject argument is part of the transport contract (``DeliveryCallback``) and unused + here: ``DaprClient`` stores these callbacks without calling them, because Dapr delivers + over HTTP to ``POST /events/{topic}`` rather than through the client. + """ + + async def _process_event(event: CloudEvent[Any], _subject: str) -> None: try: context = {"dapr_topic": topic} await self._process_cloud_event(event, context, topic) diff --git a/src/blueprint/agents/io/api/eventing/nats.py b/src/blueprint/agents/io/api/eventing/nats.py index 5db230ed..44c33c79 100644 --- a/src/blueprint/agents/io/api/eventing/nats.py +++ b/src/blueprint/agents/io/api/eventing/nats.py @@ -1,9 +1,9 @@ """NATS eventing implementation using NATSClient.""" import logging -from collections.abc import Awaitable, Callable from typing import Any +from ....clients.client_base import DeliveryCallback from ....clients.io.nats_client import NATSClient from ....component.namespace import ROOT_LABEL, ROOT_NAMESPACE from ....models.events import CloudEvent @@ -12,6 +12,15 @@ logger = logging.getLogger(__name__) +NATS_SUBJECT_CONTEXT_KEY = "nats_subject" +"""Handler context key holding the subject a NATS message was delivered on. + +Beside ``nats_topic``, which is the *subscription* -- possibly a wildcard such as ``t.*.risk.>`` -- +this is the concrete subject that matched it, e.g. ``t.T1.risk.created``. It comes from the broker, +never from the event, so a handler can derive a tenant from it without trusting the publisher's +``tenantid``. Present only on events delivered by NATS. +""" + class NatsEventing(EventHandlingBase): """Implements event handling using NATS via NATSClient. @@ -54,9 +63,7 @@ async def on_startup(self) -> None: """Subscribe this agent's topics through this agent's client.""" self._client = self.registry.get_component(NATSClient, namespace=self.namespace) - topic_callbacks: dict[str, Callable[[CloudEvent[Any]], Awaitable[None]]] = { - topic: self._make_event_callback(topic) for topic in self._declared_topics() - } + topic_callbacks: dict[str, DeliveryCallback] = {topic: self._make_event_callback(topic) for topic in self._declared_topics()} if topic_callbacks: logger.info( @@ -96,11 +103,11 @@ def _declared_topics(self) -> list[str]: async def on_shutdown(self) -> None: pass - def _make_event_callback(self, topic: str) -> Callable[[CloudEvent[Any]], Awaitable[None]]: + def _make_event_callback(self, topic: str) -> DeliveryCallback: """Return an async callback that routes an incoming event through the handler chain.""" - async def _process_event(event: CloudEvent[Any]) -> None: - context = {"nats_topic": topic} + async def _process_event(event: CloudEvent[Any], subject: str) -> None: + context = {"nats_topic": topic, NATS_SUBJECT_CONTEXT_KEY: subject} processing_result = await self._process_cloud_event(event, context, topic) logger.debug( "Processed CloudEvent %s on topic %s with status %s", diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index 2c9f9558..0cbe6ab6 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -355,7 +355,7 @@ async def test_undecodable_payload_is_not_dispatched( ) -> None: dispatched = [] - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: dispatched.append(event) handler = await self._handler_for(nats_client, mock_nats_core, _callback) @@ -367,10 +367,25 @@ async def _callback(event: CloudEvent) -> None: assert "unparseable" in caplog.text assert "orders.created" in caplog.text + async def test_the_delivery_subject_reaches_the_callback(self, nats_client: NATSClient, mock_nats_core: MagicMock, cloud_event) -> None: + """H1 -- a wildcard subscription passes on the concrete subject the broker routed.""" + received = [] + + async def _callback(event: CloudEvent, subject: str) -> None: + received.append(subject) + + nats_client._nats_client = mock_nats_core + nats_client._client = mock_nats_core + await nats_client._subscribe_one("t.*.risk.>", _callback) + handler = mock_nats_core.subscribe.await_args.kwargs["cb"] + await handler(MagicMock(subject="t.T1.risk.created", data=json.dumps(dict(cloud_event)).encode())) + + assert received == ["t.T1.risk.created"] + async def test_valid_json_that_is_not_a_cloud_event_is_not_dispatched(self, nats_client: NATSClient, mock_nats_core: MagicMock) -> None: dispatched = [] - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: dispatched.append(event) handler = await self._handler_for(nats_client, mock_nats_core, _callback) @@ -386,7 +401,7 @@ async def test_dispatch_failure_is_logged_with_event_and_topic( cloud_event: CloudEvent, caplog: pytest.LogCaptureFixture, ) -> None: - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: raise RuntimeError("handler exploded") handler = await self._handler_for(nats_client, mock_nats_core, _callback) @@ -401,7 +416,7 @@ async def _callback(event: CloudEvent) -> None: async def test_neither_failure_escapes_into_the_broker_callback( self, nats_client: NATSClient, mock_nats_core: MagicMock, cloud_event: CloudEvent ) -> None: - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: raise RuntimeError("handler exploded") handler = await self._handler_for(nats_client, mock_nats_core, _callback) @@ -412,7 +427,7 @@ async def _callback(event: CloudEvent) -> None: assert nats_client.inflight_handlers == 0 async def test_undecodable_payload_releases_the_inflight_slot(self, nats_client: NATSClient, mock_nats_core: MagicMock) -> None: - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: pass handler = await self._handler_for(nats_client, mock_nats_core, _callback) @@ -460,7 +475,7 @@ async def test_no_handler_found_still_acks(self, nats_client: NATSClient, mock_n msg.ack.assert_awaited_once() async def test_retryable_error_naks(self, nats_client: NATSClient, mock_nats_jetstream: tuple, cloud_event: CloudEvent) -> None: - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: raise RetryableHandlerError(status="error", reason="upstream down") handler = await self._js_handler(nats_client, mock_nats_jetstream, _callback) @@ -470,7 +485,7 @@ async def _callback(event: CloudEvent) -> None: msg.ack.assert_not_awaited() async def test_invalid_event_error_terms(self, nats_client: NATSClient, mock_nats_jetstream: tuple, cloud_event: CloudEvent) -> None: - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: raise InvalidEventError(status="error", reason="no payload") handler = await self._js_handler(nats_client, mock_nats_jetstream, _callback) @@ -482,7 +497,7 @@ async def _callback(event: CloudEvent) -> None: async def test_critical_error_terms(self, nats_client: NATSClient, mock_nats_jetstream: tuple, cloud_event: CloudEvent) -> None: """A critical error is not made less critical by being delivered again.""" - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: raise CriticalHandlerError(status="error", reason="corrupt state") handler = await self._js_handler(nats_client, mock_nats_jetstream, _callback) @@ -491,7 +506,7 @@ async def _callback(event: CloudEvent) -> None: msg.term.assert_awaited_once() async def test_unexpected_exception_naks(self, nats_client: NATSClient, mock_nats_jetstream: tuple, cloud_event: CloudEvent) -> None: - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: raise RuntimeError("boom") handler = await self._js_handler(nats_client, mock_nats_jetstream, _callback) @@ -535,7 +550,7 @@ async def test_failure_to_ack_does_not_escape_the_callback( async def test_dispatch_failure_log_names_the_disposition( self, nats_client: NATSClient, mock_nats_jetstream: tuple, cloud_event: CloudEvent, caplog: pytest.LogCaptureFixture ) -> None: - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: raise InvalidEventError(status="error", reason="no payload") handler = await self._js_handler(nats_client, mock_nats_jetstream, _callback) @@ -597,7 +612,7 @@ async def test_handler_execution_is_counted_and_released( ) -> None: seen_during_handler = [] - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: seen_during_handler.append(nats_client.inflight_handlers) nats_client._nats_client = mock_nats_core @@ -614,7 +629,7 @@ async def _callback(event: CloudEvent) -> None: async def test_handler_count_is_released_when_callback_raises( self, nats_client: NATSClient, mock_nats_core: MagicMock, cloud_event: CloudEvent ) -> None: - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: raise RuntimeError("handler exploded") nats_client._nats_client = mock_nats_core @@ -1212,7 +1227,7 @@ async def _handler(nats_client: NATSClient, mock_config: MagicMock, mock_nats_je async def test_terminal_failure_is_dead_lettered_then_termed( self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent ) -> None: - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: raise InvalidEventError(status="error", reason="no payload") _, mock_js = mock_nats_jetstream @@ -1234,7 +1249,7 @@ async def test_original_bytes_are_republished_unchanged( async def test_headers_name_the_reason_and_origin( self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent ) -> None: - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: raise CriticalHandlerError(status="error", reason="corrupt state") _, mock_js = mock_nats_jetstream @@ -1249,7 +1264,7 @@ async def _callback(event: CloudEvent) -> None: async def test_retry_below_the_limit_naks_without_dead_lettering( self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent ) -> None: - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: raise RetryableHandlerError(status="error", reason="upstream down") _, mock_js = mock_nats_jetstream @@ -1265,7 +1280,7 @@ async def test_final_attempt_is_dead_lettered_instead_of_naked( ) -> None: """Naking the last attempt drops the message silently at max_deliver.""" - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: raise RetryableHandlerError(status="error", reason="upstream down") _, mock_js = mock_nats_jetstream @@ -1279,7 +1294,7 @@ async def _callback(event: CloudEvent) -> None: async def test_unlimited_max_deliver_never_exhausts( self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent ) -> None: - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: raise RetryableHandlerError(status="error", reason="upstream down") handler = await self._handler(nats_client, mock_config, mock_nats_jetstream, _callback, nats_max_deliver=-1) @@ -1290,7 +1305,7 @@ async def _callback(event: CloudEvent) -> None: async def test_unreadable_metadata_costs_a_retry_not_a_payload( self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent ) -> None: - async def _callback(event: CloudEvent) -> None: + async def _callback(event: CloudEvent, subject: str) -> None: raise RetryableHandlerError(status="error", reason="upstream down") handler = await self._handler(nats_client, mock_config, mock_nats_jetstream, _callback, nats_max_deliver=1) diff --git a/tests/unit/agents/io/api/eventing/test_nats.py b/tests/unit/agents/io/api/eventing/test_nats.py index 58dd4e60..3a1202aa 100644 --- a/tests/unit/agents/io/api/eventing/test_nats.py +++ b/tests/unit/agents/io/api/eventing/test_nats.py @@ -4,7 +4,7 @@ import pytest -from blueprint.agents.io.api.eventing.nats import NatsEventing +from blueprint.agents.io.api.eventing.nats import NATS_SUBJECT_CONTEXT_KEY, NatsEventing from blueprint.agents.models.errors import CriticalHandlerError, InvalidEventError, RetryableHandlerError from blueprint.agents.models.events import CloudEvent @@ -208,9 +208,30 @@ def _callback(nats_eventing: NatsEventing, result_or_error) -> object: async def test_handler_errors_reach_the_caller(self, nats_eventing: NatsEventing, cloud_event: CloudEvent, error: Exception) -> None: callback = self._callback(nats_eventing, error) with pytest.raises(type(error)): - await callback(cloud_event) + await callback(cloud_event, "orders.created") async def test_successful_dispatch_returns_none(self, nats_eventing: NatsEventing, cloud_event: CloudEvent, processed_result) -> None: callback = self._callback(nats_eventing, None) nats_eventing._process_cloud_event = AsyncMock(return_value=processed_result) # type: ignore[method-assign] - assert await callback(cloud_event) is None + assert await callback(cloud_event, "orders.created") is None + + +class TestNatsEventingDeliverySubject: + """H1 -- the subject the broker delivered on reaches the handler context, beside the subscription.""" + + async def test_the_context_carries_the_subject_and_the_subscription( + self, nats_eventing: NatsEventing, cloud_event: CloudEvent, processed_result + ) -> None: + nats_eventing._process_cloud_event = AsyncMock(return_value=processed_result) # type: ignore[method-assign] + await nats_eventing._make_event_callback("t.*.risk.>")(cloud_event, "t.T1.risk.created") + + context = nats_eventing._process_cloud_event.await_args.args[1] + assert context == {"nats_topic": "t.*.risk.>", NATS_SUBJECT_CONTEXT_KEY: "t.T1.risk.created"} + + async def test_the_event_cannot_supply_it(self, nats_eventing: NatsEventing, processed_result) -> None: + """A publisher writes the event, including any extension it likes; it does not write the context.""" + spoofed = CloudEvent(id="e1", type="risk.created", source="publisher", tenantid="T2", nats_subject="t.T2.risk.created") + nats_eventing._process_cloud_event = AsyncMock(return_value=processed_result) # type: ignore[method-assign] + await nats_eventing._make_event_callback("t.*.risk.>")(spoofed, "t.T1.risk.created") + + assert nats_eventing._process_cloud_event.await_args.args[1][NATS_SUBJECT_CONTEXT_KEY] == "t.T1.risk.created" From ec9517b2eb18f13411482ee06cbe58d35301c56d Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 15:23:41 +0200 Subject: [PATCH 046/133] fix(nats): keep a latched-down agent from subscribing at startup Spec sec. 9.1 marks a non-critical agent down when a component's on_startup raises, and C4 pauses its clients. Clients start before the eventing endpoint, so an agent whose client failed was paused before it had subscribed -- and subscribe() started the retry loop regardless, which connected and subscribed without reading the pause flag. The latched-down agent consumed events it could not process. A paused client now registers its topics and waits; a pause that arrives while the loop is connecting leaves it connected but unsubscribed; and resume_consumption() starts the loop for a client that never connected. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 5 ++ ...26-08-28-multi-agent-grouping-changelog.md | 38 +++++++++++ .../agents/clients/io/nats_client.py | 35 +++++++++- .../agents/clients/io/test_nats_client.py | 65 +++++++++++++++++++ 4 files changed, 142 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d707b2f..458030ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,11 @@ ### Fixed +- **A non-critical agent marked down at startup no longer consumes events anyway.** When its + client failed `on_startup`, the agent was paused before its eventing endpoint subscribed, and the + subscribe path ignored the pause -- so the latched-down agent connected and took events it could + not process. A paused client now registers its topics and waits; it connects and subscribes only + if the agent is released. - **Credentials inside `nats_url` no longer reach the log or `/health`.** The connect log line printed the URL verbatim, and the NATS health message printed the parsed URL including `user:password@`. Both now show `***@host:port`. diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 13a61e69..1dc22cd4 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7384,10 +7384,48 @@ transport keys and the rule to derive tenants from the subject. Guarded by `TestNatsEventingDeliverySubject` in `test_nats.py`, including an event that carries a spoofed `nats_subject` extension and a different `tenantid`. +### A latched-down agent consumed events anyway (C4) + +Found while verifying a report from the dynamic-subscriptions work: "a non-critical agent whose +`on_startup` raised is marked down, and nothing ever calls `clear_forced_down`". That report is +accurate, and is recorded under *Open points* below -- but checking it turned up a defect that +breaks the **committed** spec, not only the draft's D9. + +**Cause.** Sec. 9.1 marks a non-critical agent down when a component's `on_startup` raises, and +`NamespaceSupervisor._set` pauses its clients (C4). The lifespan starts clients before services, +so an agent whose *client* failed is paused before its `NatsEventing` has subscribed -- there is +nothing to drain, and `pause_consumption()` only sets the flag. `subscribe()` then started the +retry loop regardless, and neither `_start_with_retry()` nor `_connect_and_subscribe()` read the +flag. Reproduced: a client paused before `subscribe()` ended with one live subscription. The same +held for a pause arriving while the loop was still connecting (a later component of the same agent +failing). The pause was only enforced on reconnect and in `health_check()`. + +**Fix, in `NATSClient`.** + +- `subscribe()`: a paused client registers its topics, resolves its queue group and durables (so + configuration errors still surface at startup), and returns without starting the loop. +- `_start_retry_task()`, new: starts the loop unless one is running; used by `subscribe()` and by + `resume_consumption()`. +- `_connect_and_subscribe()`: paused after connecting -> subscribe nothing; `_start_with_retry()` + then leaves `subscriptions_ready` false. +- `resume_consumption()`: a client that never connected starts the loop instead of returning. + +Guarded by `TestAPauseBeforeSubscribing` in `test_nats_client.py`; two of its three cases fail +against the previous code. + --- ## Open points +- **A startup-failure latch is never released.** A non-critical agent whose `on_startup` raised + is latched by `AppBuilder._mark_agent_down` -> `NamespaceSupervisor.mark_down`, and nothing in + `src/` calls `clear_forced_down`, so it stays degraded until the pod restarts. That is what sec. + 9.1 specifies -- it names no recovery -- so it is not a defect against the committed spec; it + violates D9 of the untracked dynamic-subscriptions draft, which proposes retrying `on_startup` + with a budget and then terminating. Terminating is not obviously right for a *deterministic* + failure (a bad key): the restart fails the same way, and crash-looping the pod takes every + healthy agent down with it, which is the blast radius sec. 9.1 exists to remove. Undecided. + - ~~**The generated `settings.toml` writes two sections nothing reads.**~~ **Done.** `[default.logging]` (`level`, `format`) and `[default.observability]` (`otel_enabled`, `token_metrics_enabled`) are sectioned, and the framework reads all four as **flat** keys -- `log_level`, `log_format`, diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 2ae9c7c4..f148dd3c 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -236,6 +236,13 @@ async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: """Register all topic→callback mappings and start the background retry task. Returns immediately; connection and subscription happen in the background. + + **A client that is already paused registers and waits.** An agent marked down in the + lifespan's client phase (spec sec. 9.1) is paused before its eventing endpoint reaches + this call, when there is nothing yet to drain. Starting the retry loop anyway subscribed + it, so a latched-down agent consumed events -- C4 held only for failures that happened + after subscribing. The loop is started by :meth:`resume_consumption` instead, if the + agent is ever released. """ self._topic_callbacks = topic_callbacks self._queue_group = self._resolve_queue_group() @@ -244,6 +251,19 @@ async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: self._tuning = self._resolve_consumer_tuning(list(topic_callbacks)) self._subscriptions_managed = True self._subscriptions_ready = False + if self._consumption_paused: + logger.info( + "Agent '%s' is degraded, so its %d subscription(s) are registered but not started", + self.namespace or ROOT_LABEL, + len(topic_callbacks), + ) + return + self._start_retry_task() + + def _start_retry_task(self) -> None: + """Start the background connect-and-subscribe loop, unless one is already running.""" + if self._retry_task is not None and not self._retry_task.done(): + return self._retry_task = asyncio.ensure_future(self._start_with_retry()) self._retry_task.add_done_callback(self._on_retry_done) @@ -776,7 +796,13 @@ async def resume_consumption(self) -> None: if not self._consumption_paused: return self._consumption_paused = False - if not self._subscriptions_managed or self._nats_client is None: + if not self._subscriptions_managed: + return + if self._nats_client is None: + # Paused before it ever connected -- subscribe() registered the topics and waited. + # The retry loop is what connects and subscribes; a loop still running picks up the + # cleared flag by itself. + self._start_retry_task() return try: await self._subscribe_all() @@ -945,6 +971,8 @@ async def _start_with_retry(self) -> None: while True: try: await self._connect_and_subscribe() + if self._consumption_paused: + return self._subscriptions_ready = True logger.info("NATSClient connected and subscribed successfully") return @@ -981,6 +1009,11 @@ async def _connect_and_subscribe(self) -> None: with contextlib.suppress(Exception): await sub.unsubscribe() self._subscriptions.clear() + if self._consumption_paused: + # Paused while this loop was still connecting: stay connected, subscribe nothing. + # resume_consumption() subscribes over this connection if the agent is released. + logger.info("Agent '%s' connected while degraded; not subscribing", self.namespace or ROOT_LABEL) + return await self._subscribe_all() async def _subscribe_all(self) -> None: diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index 0cbe6ab6..188ccc5a 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -1758,6 +1758,71 @@ async def test_deployment_identity_never_reaches_the_consumer_identity( assert "pod-99" not in client._durable_for("orders.created") +class TestAPauseBeforeSubscribing: + """C4 for an agent marked down in the client phase, before its endpoint subscribes (spec sec. 9.1). + + The pause used to be enforced only on a client that already had subscriptions to drain. A + non-critical agent whose client failed ``on_startup`` is paused first and subscribed second, + and the retry loop ignored the flag -- so the latched-down agent consumed events. + """ + + TOPICS = {"orders.created": AsyncMock()} + + @staticmethod + def _configure(mock_config: MagicMock) -> None: + values = {"app_name": "orders", "nats_url": "nats://broker:4222", "app_environment": "production"} + mock_config.get.side_effect = lambda key, default=None: values.get(key, default) + mock_config.envvar_prefix = "DYNACONF" + + @staticmethod + def _broker() -> MagicMock: + nc = MagicMock(is_closed=False, is_connected=True) + nc.subscribe = AsyncMock(return_value=MagicMock()) + return nc + + async def test_a_paused_client_does_not_subscribe(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config) + await nats_client.pause_consumption() + nc = self._broker() + with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock, return_value=nc) as connect: + await nats_client.subscribe(self.TOPICS) + await asyncio.sleep(0) + connect.assert_not_awaited() + nc.subscribe.assert_not_awaited() + assert nats_client._retry_task is None + assert nats_client.subscriptions_ready is False + + async def test_releasing_it_connects_and_subscribes(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config) + await nats_client.pause_consumption() + nc = self._broker() + with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock, return_value=nc): + await nats_client.subscribe(self.TOPICS) + await nats_client.resume_consumption() + await nats_client._retry_task + nc.subscribe.assert_awaited_once() + assert nats_client.subscriptions_ready is True + + async def test_a_pause_while_connecting_subscribes_nothing(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """Marked down by a later component of the same agent while the loop is still connecting.""" + self._configure(mock_config) + nc = self._broker() + + async def _slow_connect(*_args, **_kwargs): + await nats_client.pause_consumption() + return nc + + with patch("blueprint.agents.clients.io.nats_client.nats.connect", side_effect=_slow_connect): + await nats_client.subscribe(self.TOPICS) + await nats_client._retry_task + nc.subscribe.assert_not_awaited() + assert nats_client.subscriptions_ready is False + + await nats_client.resume_consumption() + nc.subscribe.assert_awaited_once() + assert nats_client.subscriptions_ready is True + + class TestPausingADegradedAgent: """C4: readiness gates HTTP only, so a degraded agent has to be taken off its topics.""" From b486b31ec9533bc87a7c95b14b6d040f585e3633 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 16:06:13 +0200 Subject: [PATCH 047/133] fix(startup): retry a latched agent until it starts, and report the latch in readiness A non-critical agent whose on_startup raised was latched down (sec. 9.1) and nothing ever released it, so it stayed out of service until the pod restarted. AppBuilder now records the failed components and retries them every startup_retry_interval_seconds, in start order; when all have started the latch is released and health checks decide. It never ends the process: a deterministic failure would crash-loop every healthy agent. The latch also never reached readiness: /health/ready reported a latched agent UP with nothing failing. The aggregation now counts it as down and the payload carries a reason. The poll no longer skips aggregation and observe() when no health check is registered. Spec sec. 9.1 is amended accordingly. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 9 ++ ...26-08-28-multi-agent-grouping-changelog.md | 67 +++++++- docs/specs/2026-08-28-multi-agent-grouping.md | 13 +- .../docs/concepts/configuration.md | 4 +- .../docs/concepts/observability.md | 21 ++- .../docs/reference/configuration-keys.md | 1 + src/blueprint/agents/app_builder.py | 125 +++++++++++++++ src/blueprint/agents/config/config.py | 1 + .../agents/io/api/actuators/actuator_api.py | 5 + .../io/api/actuators/health/health_cache.py | 30 +++- .../actuators/health/namespace_supervisor.py | 5 + src/blueprint/agents/models/api.py | 6 + .../test_startup_failure_policy.py | 150 ++++++++++++++++++ .../api/actuators/health/test_health_cache.py | 40 ++++- 14 files changed, 462 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 458030ba..280a749b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,15 @@ ### Fixed +- **An agent latched down at startup is shown as down in `/health/ready`.** The latch paused the + agent and set its gauge to 0, but readiness was computed from health checks alone, so the probe + and the payload reported it `UP` with nothing failing. The payload now shows it `DOWN` with a + `reason`, and the readiness policy counts it. The poll also no longer skips everything when no + health check is registered, which had left both the verdict and resumption unevaluated. +- **An agent latched down at startup recovers without a restart.** Its failed components are + retried every `startup_retry_interval_seconds` (default 30), in start order; when all have + started the latch is released and health checks decide. It never ends the process. `on_startup` + must therefore be safe to call again after it raised. - **A non-critical agent marked down at startup no longer consumes events anyway.** When its client failed `on_startup`, the agent was paused before its eventing endpoint subscribed, and the subscribe path ignored the pause -- so the latched-down agent connected and took events it could diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 1dc22cd4..549d5738 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7413,11 +7413,76 @@ failing). The pause was only enforced on reconnect and in `health_check()`. Guarded by `TestAPauseBeforeSubscribing` in `test_nats_client.py`; two of its three cases fail against the previous code. +### A latched agent recovers, and readiness shows it + +Two findings, one subject: the open point recorded just above ("a startup-failure latch is never +released"), and #3 of an external defect list ("`mark_down` does not affect readiness"). Decided +with the user: retry, never terminate, and show the latch in `/health/ready`. Sec. 9.1 of the spec +is amended to say so. + +**#3, verified.** `HealthCheckCache._aggregate_by_agent` built each namespace's verdict from its +check results and never read the supervisor's latch. A latched agent -- paused, gauge at 0 -- +was therefore `UP` in `/health/ready` with `failing: []`, and `ReadinessPolicy` counted it as +serving. Separately, `_run_health_checks` returned before doing anything when no check was +registered, so neither the verdict nor `supervisor.observe()` ran -- and `observe()` is what +resumes an agent. + +- **`NamespaceReadiness.reason`**, new: why an agent is out of service when no check says so. +- **`NamespaceSupervisor.forced_down`**, new property: every latched namespace and its reason. +- **`_aggregate_by_agent`** reads it: a latched namespace is `False` in `namespace_status` (so + the policy counts it) and `DOWN` with its `reason` in the payload, whatever its checks say. +- **`_run_health_checks`** no longer returns early without checks. +- **`HealthCheckCache.refresh()`** and **`ActuatorApi.refresh_health()`**, new: recompute now. + Called when a latch is set or released, so the probe does not lag one interval behind. + +**Recovery.** + +- **`AppBuilder._start_component`**, non-critical branch: records `(kind, component, label)` in + `_failed_startups[namespace]`, in start order, before latching. +- **`_startup_retry_interval()`**: reads `startup_retry_interval_seconds` at the start of the + lifespan, refusing a non-positive or non-numeric value -- so a bad value fails startup rather + than surfacing on the day an agent first fails. +- **`_start_startup_recovery()`**, after every component has started: one task per latched agent. +- **`_recover_agent()`**: sleeps, then calls `on_startup` on the pending components in order, + stopping at the first that raises (a later one may depend on it). A failure logs a WARNING and + refreshes the latch's reason, so the payload shows the current error. When none are pending: + `clear_forced_down`, INFO, `refresh_health()` -- the refresh runs `observe()`, which resumes + consumption if the checks pass. Never terminates. +- **`_stop_startup_recovery()`**, first thing in shutdown: cancels and awaits the tasks. +- **`_on_recovery_done()`**: the done-callback the design rules require on every spawned task; it + logs a recovery that ended by raising, naming the task's agent. +- **`_mark_agent_down()`** now refreshes readiness after latching. +- `startup_retry_interval_seconds` joins `PROCESS_SCOPE_KEYS`. + +**Why never terminate**, pushing back on D9 of the dynamic-subscriptions draft: a deterministic +failure (a bad key) fails identically after a restart, and the restart crash-loops the pod and +every healthy agent in it -- the blast radius sec. 9.1 exists to remove. The ERROR on the +transition, the gauge, the payload's reason and a WARNING per attempt keep it visible. + +**Re-running `on_startup` was audited** for every framework component that implements it: each +raises before acquiring anything (configuration checks, then the client object) or guards a +repeated start (`SchedulerBase`, `SessionsBus`). User components are now required to be safe too; +`concepts/observability.md` and the spec say so. + +**Checked, not a defect:** the previous commit stops a paused client starting its retry loop, and a +health poll pauses an agent whose NATS check fails -- which looked like it could deadlock an agent +whose broker was down at startup. It cannot: `ClientHealthChecker` calls `client.connect()` before +every check, so polls connect the client independently of the loop, and the poll that finds it +connected resumes and subscribes it. + +Docs: `concepts/observability.md` (retry, the `reason`, the `on_startup` requirement), +`concepts/configuration.md` and `reference/configuration-keys.md` (the key). Guarded by +`TestReadinessShowsTheLatch` and `TestRecovery` in `test_startup_failure_policy.py`, through the +real lifespan: both readiness cases fail without the aggregation change, and four of the six +recovery cases fail with the recovery disabled (the other two assert that it never terminates and +that a bad interval is refused). + --- ## Open points -- **A startup-failure latch is never released.** A non-critical agent whose `on_startup` raised +- ~~**A startup-failure latch is never released.**~~ **Closed** -- see *A latched agent recovers, and + readiness shows it* above. A non-critical agent whose `on_startup` raised is latched by `AppBuilder._mark_agent_down` -> `NamespaceSupervisor.mark_down`, and nothing in `src/` calls `clear_forced_down`, so it stays degraded until the pod restarts. That is what sec. 9.1 specifies -- it names no recovery -- so it is not a defect against the committed spec; it diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md index 079c3ffc..7a1a32ca 100644 --- a/docs/specs/2026-08-28-multi-agent-grouping.md +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -772,11 +772,22 @@ There is no partial build: one process, one `build()`. The `critical` flag is th |---|---|---| | Agent missing from the agent map | exit non-zero | log ERROR, skip | | Module import raises | exit non-zero | log ERROR, skip | -| `on_startup` raises | exit non-zero | mark namespace down, pause consumers (C4), continue | +| `on_startup` raises | exit non-zero | mark namespace down, pause consumers (C4), continue; retry (below) | Exit **MUST** happen before the port is bound, so Kubernetes crash-loops with a readable message rather than reporting a healthy pod that is silently short-staffed. +**A namespace marked down by a startup failure MUST be retried, and MUST NOT end the process.** +Every `startup_retry_interval_seconds` (default 30, process scope) the framework calls `on_startup` +again on that namespace's failed components, in their original start order, stopping at the first +that raises again. When all of them have started, the mark is released and the namespace's health +checks decide from then on. While it is marked, the readiness payload **MUST** report the namespace +`DOWN` with the failure as its reason, whatever its health checks say -- the mark exists because a +component that failed to start may still pass its check. Terminating instead is not a recovery: a +deterministic failure fails the same way after a restart, and the restart takes every healthy +namespace in the process down with it. `on_startup` **MUST** therefore be safe to call again after +it raised. + The default for an unflagged agent is `critical: true`: a partially loaded group whose missing agent's queue has no consumer is a worse failure than no pod at all. diff --git a/src/blueprint/agent_generator/docs/concepts/configuration.md b/src/blueprint/agent_generator/docs/concepts/configuration.md index e9c79a47..9275c272 100644 --- a/src/blueprint/agent_generator/docs/concepts/configuration.md +++ b/src/blueprint/agent_generator/docs/concepts/configuration.md @@ -277,8 +277,8 @@ configuration, not a scope. Some keys describe the *process*, and one process has one of each: `app_port`, `app_host`, `app_workers`, `app_environment`, `envvar_prefix`, `event_bus`, `log_level`, `log_format`, -`suppress_noisy_loggers`, `health_check_interval_seconds`, `readiness_policy`, -`nats_stream_name`. +`suppress_noisy_loggers`, `health_check_interval_seconds`, `startup_retry_interval_seconds`, +`readiness_policy`, `nats_stream_name`. They belong in the image's own `settings.toml`, beside `agents.toml`. Set in an agent's file they are dropped before the merge, with a warning naming the value the process uses instead -- diff --git a/src/blueprint/agent_generator/docs/concepts/observability.md b/src/blueprint/agent_generator/docs/concepts/observability.md index 704743d7..55182c61 100644 --- a/src/blueprint/agent_generator/docs/concepts/observability.md +++ b/src/blueprint/agent_generator/docs/concepts/observability.md @@ -253,9 +253,24 @@ consuming and the gauge returns to `1`. The one exception is a startup failure. If a non-critical agent's `on_startup` raises, the process starts without it and that agent is **latched** down -- its components can often still answer a health check while the agent is unusable, so an observed-health signal would put it straight back -into service on the next poll. A critical agent's `on_startup` failure ends the startup instead, -before the port is bound, so Kubernetes crash-loops the pod with the traceback rather than -reporting a replica that is silently short a consumer. +into service on the next poll. The readiness payload shows it as `DOWN` with a `reason` naming +the component and its error, even though no check is failing. + +A latched agent is **retried**: every `startup_retry_interval_seconds` (default 30) the framework +calls `on_startup` again on the components that failed, in their original order, stopping at the +first that fails again. When all of them start, the latch is released and the agent's health +checks decide from there -- a transient cause, such as a database that was not reachable yet, +recovers without a restart. While it keeps failing, each attempt logs a WARNING and the payload +carries the latest error. It is retried indefinitely and never ends the process: a deterministic +failure, such as a missing key, would fail the same way after a restart, and crash-looping the pod +would take every healthy agent in it down too. + +**So `on_startup` must be safe to call again after it raised.** Raise before acquiring anything, or +release what you acquired before raising; the framework's own components all do. + +A critical agent's `on_startup` failure ends the startup instead, before the port is bound, so +Kubernetes crash-loops the pod with the traceback rather than reporting a replica that is silently +short a consumer. --- diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 35e74071..65896046 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -17,6 +17,7 @@ Top-level application settings. | `app_environment` | `str` | `"development"` | Deployment environment identifier (e.g., `"development"`, `"staging"`, `"production"`). `"development"` enables development fallbacks such as the localhost default for `nats_url`, and the process logs a WARNING at startup that it is not suitable for production. Being the default, a deployment that sets nothing runs in development mode: set it to anything else to deploy. | | `log_level` | `str` | `"INFO"` | Root log level. One of `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`. | | `log_format` | `str` | `"text"` | Log output format. `"text"` for human-readable, `"json"` for structured JSON logging. | +| `startup_retry_interval_seconds` | `float` | `30` | Seconds between attempts to start again the components of a non-critical agent whose `on_startup` raised. The agent stays out of service, shown with a `reason` in `/health/ready`, until every failed component starts; it is retried indefinitely and never ends the process. Must be positive; startup fails otherwise. Process scope. | --- diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index e43d0380..81c24993 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -1,5 +1,7 @@ """Generic FastAPI application setup and configuration.""" +import asyncio +import contextlib import logging from collections.abc import AsyncIterator, Callable, Mapping from contextlib import asynccontextmanager @@ -70,6 +72,15 @@ logger = logging.getLogger(__name__) +STARTUP_RETRY_INTERVAL_KEY = "startup_retry_interval_seconds" +"""Seconds between attempts to start the components of an agent that failed to start (sec. 9.1). + +Process-scope: one process runs one recovery policy. The default matches the health check interval, +so a recovered agent is back in the readiness verdict within about one poll of recovering. +""" + +DEFAULT_STARTUP_RETRY_INTERVAL = 30.0 + @dataclass(frozen=True) class Declaration: @@ -257,6 +268,11 @@ def __init__(self, config: Config | None = None) -> None: # Of those, the ones the deployment said it cannot run without. Read by the # readiness probe under readiness_policy = 'critical' (C3). self._critical_namespaces: list[str] = [] + # Components of non-critical agents whose on_startup raised, per agent and in start order, + # retried after startup until they all start (sec. 9.1). The tasks are held so that + # shutdown can cancel them rather than leave one retrying against a stopping process. + self._failed_startups: dict[str, list[tuple[str, Any, str]]] = {} + self._recovery_tasks: list[asyncio.Task[None]] = [] # ------------------------------------------------------------------ # Configuration @@ -1278,10 +1294,113 @@ async def _start_component(self, kind: str, component: Any, label: str) -> None: exc, exc_info=True, ) + self._failed_startups.setdefault(namespace, []).append((kind, component, label)) await self._mark_agent_down(namespace, f"its {kind.lower()} '{label}' failed to start: {exc}") return logger.info("%s %s startup completed", kind, label) + @staticmethod + def _startup_retry_interval(config: Config) -> float: + """Read ``startup_retry_interval_seconds``, refusing a value that is not a positive number. + + Read at the start of the lifespan, not when the first failure needs it: a bad value would + otherwise surface only on the day an agent fails to start, as a second failure on top. + """ + raw = config.get(STARTUP_RETRY_INTERVAL_KEY, DEFAULT_STARTUP_RETRY_INTERVAL) + try: + interval = float(raw) + except (TypeError, ValueError): + interval = 0.0 + if interval <= 0: + raise ValueError(f"'{STARTUP_RETRY_INTERVAL_KEY}' must be a positive number of seconds, got {raw!r}.") + return interval + + def _start_startup_recovery(self, interval: float) -> None: + """Start one recovery task per agent that is latched down by a startup failure.""" + for namespace in self._failed_startups: + task = asyncio.create_task(self._recover_agent(namespace, interval), name=f"startup-recovery:{namespace}") + task.add_done_callback(self._on_recovery_done) + self._recovery_tasks.append(task) + + @staticmethod + def _on_recovery_done(task: asyncio.Task[None]) -> None: + """Report a recovery that ended by raising, naming its agent (C7). + + The loop itself catches every component failure, so this only fires for a defect in the + loop -- which would otherwise surface as asyncio's "Task exception was never retrieved", + attributed to nobody, while the agent silently stays down for good. + """ + if task.cancelled() or task.exception() is None: + return + logger.error("Startup recovery task '%s' stopped unexpectedly: %s", task.get_name(), task.exception(), exc_info=task.exception()) + + async def _stop_startup_recovery(self) -> None: + """Cancel every recovery still running, before any component is shut down.""" + for task in self._recovery_tasks: + task.cancel() + for task in self._recovery_tasks: + with contextlib.suppress(asyncio.CancelledError): + await task + self._recovery_tasks.clear() + + async def _recover_agent(self, namespace: str, interval: float) -> None: + """Retry an agent's failed components until they all start, then release its latch. + + A non-critical agent whose component raised in ``on_startup`` is latched down (sec. 9.1) + and stays down until something releases it -- and before this, nothing did: the agent was + out of service until the pod restarted, which for a pod that is otherwise healthy may be + never. A transient cause (a database not reachable yet) therefore needed a manual restart. + + **It retries forever and never terminates the process.** A restart fixes nothing a retry + does not, and a *deterministic* failure -- a missing key, a wrong URL -- fails the same way + after the restart, so terminating would crash-loop the pod and take every healthy agent in + the group with it: the blast radius sec. 9.1 exists to remove. While it keeps failing, the + agent stays visibly down: ``blueprint.namespace.up`` is 0, the readiness payload carries the + latest error, and each attempt logs a WARNING. + + The components are retried in the order they originally started, stopping at the first + that fails again: a later one may depend on it, and starting it against a dependency that + is still broken would only produce a second, misleading error. Framework components are + safe to start again after they raised -- each raises before any side effect, or guards a + repeated start -- and user components have to be too; the docs say so. + + Releasing the latch does not by itself put the agent back in service. It hands the decision + back to the agent's health checks, and the health refresh that follows resumes consumption + if they pass. + """ + pending = self._failed_startups[namespace] + attempt = 0 + while pending: + await asyncio.sleep(interval) + attempt += 1 + while pending: + kind, component, label = pending[0] + try: + await component.on_startup() + except Exception as exc: + logger.warning( + "Agent '%s' is still out of service: its %s '%s' failed to start again (attempt %d, next in %.0fs): %s", + namespace, + kind.lower(), + label, + attempt, + interval, + exc, + ) + # The latch stays; only its reason is refreshed, so the readiness payload + # shows the error that is current rather than the first one. + await self._mark_agent_down(namespace, f"its {kind.lower()} '{label}' failed to start: {exc}") + break + logger.info("Agent '%s': %s '%s' started on attempt %d", namespace, kind.lower(), label, attempt) + pending.pop(0) + + supervisor = self._actuator_api.supervisor if self._actuator_api is not None else None + if supervisor is not None: + await supervisor.clear_forced_down(namespace) + logger.info("Agent '%s' started after %d attempt(s); its health checks decide from here", namespace, attempt) + if self._actuator_api is not None: + await self._actuator_api.refresh_health() + @staticmethod def _warn_if_development(config: Config) -> None: """Say, once per process, that this process runs with development defaults. @@ -1340,6 +1459,9 @@ async def _mark_agent_down(self, namespace: str, reason: str) -> None: logger.error("Agent '%s' cannot be marked down: no supervisor is running. Reason was: %s", namespace, reason) return await supervisor.mark_down(namespace, reason) + # The readiness verdict is cached per poll; recompute it now, so the probe and the payload + # show the latch at once instead of up to one health interval later. + await self._actuator_api.refresh_health() # type: ignore[union-attr] def _create_lifespan_manager(self) -> Any: @asynccontextmanager @@ -1349,6 +1471,7 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: resolved_config = self._require_config() logger.info("Starting up application components") self._warn_if_development(resolved_config) + startup_retry_interval = self._startup_retry_interval(resolved_config) # Configure OpenTelemetry tracing, one identity per agent (C2). First in startup, # because Component.tracer caches the provider it resolves on first use and every @@ -1407,6 +1530,7 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: for lifecycle_component in self._lifecycle_components: await self._start_component("Lifecycle component", lifecycle_component, type(lifecycle_component).__name__) + self._start_startup_recovery(startup_retry_interval) logger.info("Application startup completed") yield @@ -1414,6 +1538,7 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: # Shutdown — reverse order # ---------------------------------------------------------- logger.info("Shutting down application components") + await self._stop_startup_recovery() for lifecycle_component in reversed(self._lifecycle_components): try: diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index 63b1a9da..71c1dad3 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -74,6 +74,7 @@ class ConfigError(Exception): "log_format", "suppress_noisy_loggers", "health_check_interval_seconds", + "startup_retry_interval_seconds", "readiness_policy", "dot_placeholder", "nats_stream_name", diff --git a/src/blueprint/agents/io/api/actuators/actuator_api.py b/src/blueprint/agents/io/api/actuators/actuator_api.py index 979196c8..79ff32f3 100644 --- a/src/blueprint/agents/io/api/actuators/actuator_api.py +++ b/src/blueprint/agents/io/api/actuators/actuator_api.py @@ -147,6 +147,11 @@ async def on_startup(self) -> None: self._health_cache.set_health_entries(self._health_entries) await self._health_cache.start() + async def refresh_health(self) -> None: + """Recompute readiness now, for a change no health check observes (a latch set or released).""" + if self._health_cache is not None: + await self._health_cache.refresh() + async def on_shutdown(self) -> None: """Stop the health check cache.""" if self._health_cache is not None: diff --git a/src/blueprint/agents/io/api/actuators/health/health_cache.py b/src/blueprint/agents/io/api/actuators/health/health_cache.py index ac24cd96..ab826621 100644 --- a/src/blueprint/agents/io/api/actuators/health/health_cache.py +++ b/src/blueprint/agents/io/api/actuators/health/health_cache.py @@ -129,11 +129,24 @@ async def get_health_status(self) -> ReadinessResponse: async with self._lock: return self._cached_response + async def refresh(self) -> None: + """Re-run the checks now instead of at the next interval. + + For a change the checks cannot see -- an agent latched down or released -- so that the + readiness probe and the payload reflect it immediately rather than up to one interval later. + """ + await self._run_health_checks() + async def _run_health_checks(self) -> None: - """Run all health checks and update cache.""" + """Run all health checks and update cache. + + **Runs with no checks registered too.** It used to return early, and that skipped more than + the checks: the verdict was never recomputed and the supervisor never observed, so an agent + latched down at startup stayed ``UP`` in the payload, and a released latch never resumed + consumption, because resumption is driven from here. + """ if not self._entries: - logger.debug("No health check providers configured") - return + logger.debug("No health check providers configured; aggregating supervisor state only") try: async with self._lock: @@ -213,7 +226,8 @@ def _aggregate_by_agent(self, components: dict[str, ComponentHealth]) -> tuple[d Whether each namespace passed, and the per-agent section of the readiness payload. """ supervised = set(self._supervisor.status) if self._supervisor is not None else set() - failing: dict[str, list[str]] = {namespace: [] for namespace in supervised} + forced = self._supervisor.forced_down if self._supervisor is not None else {} + failing: dict[str, list[str]] = {namespace: [] for namespace in supervised | set(forced)} for entry in self._entries: result = components.get(entry.key) @@ -221,16 +235,20 @@ def _aggregate_by_agent(self, components: dict[str, ComponentHealth]) -> tuple[d if result is not None and result.status != "healthy": failing[entry.namespace].append(entry.key) + # A latched agent is down whatever its checks say. That is the point of the latch: a + # component that failed to start may answer its health check perfectly while the agent is + # unusable, so the checks alone would report it UP -- to the policy and in the payload. critical = self._critical_namespaces() - namespace_status = {namespace: not keys for namespace, keys in failing.items()} + namespace_status = {namespace: not keys and namespace not in forced for namespace, keys in failing.items()} namespaces = { (namespace or ROOT_LABEL): NamespaceReadiness( - status="UP" if not keys else "DOWN", + status="UP" if namespace_status[namespace] else "DOWN", # The root is shared infrastructure, so it gates readiness under every policy # -- see ReadinessPolicy. Reporting it as critical is what makes the payload # explain the verdict rather than contradict it. critical=not namespace or namespace in critical, failing=keys, + reason=forced.get(namespace), ) for namespace, keys in failing.items() } diff --git a/src/blueprint/agents/io/api/actuators/health/namespace_supervisor.py b/src/blueprint/agents/io/api/actuators/health/namespace_supervisor.py index f09493ae..890d9388 100644 --- a/src/blueprint/agents/io/api/actuators/health/namespace_supervisor.py +++ b/src/blueprint/agents/io/api/actuators/health/namespace_supervisor.py @@ -166,6 +166,11 @@ def forced_down_reason(self, namespace: str) -> str | None: """Why ``namespace`` was latched down, or ``None`` if it was not.""" return self._forced_down.get(namespace) + @property + def forced_down(self) -> Mapping[str, str]: + """Every latched namespace and why, for the readiness verdict and its payload.""" + return dict(self._forced_down) + def _degraded_reason(self, namespace: str) -> str: """The reason to report for a health-driven transition.""" return self._forced_down.get(namespace) or "one or more of its health checks failed" diff --git a/src/blueprint/agents/models/api.py b/src/blueprint/agents/models/api.py index 7e7bd8e3..f12c5ef9 100644 --- a/src/blueprint/agents/models/api.py +++ b/src/blueprint/agents/models/api.py @@ -203,6 +203,12 @@ class NamespaceReadiness(BaseModel): default_factory=list, description="The entry keys of this agent's checks that are not healthy.", ) + reason: str | None = Field( + default=None, + description="Why this agent is out of service when no health check says so -- a component that failed to " + "start. Absent while health checks alone decide.", + examples=["its service 'db' failed to start: connection refused"], + ) class ReadinessResponse(BaseModel): diff --git a/tests/unit/agents/app_builder/test_startup_failure_policy.py b/tests/unit/agents/app_builder/test_startup_failure_policy.py index a3927182..a631a162 100644 --- a/tests/unit/agents/app_builder/test_startup_failure_policy.py +++ b/tests/unit/agents/app_builder/test_startup_failure_policy.py @@ -9,6 +9,7 @@ of the eight startup loops the failure came out of and what the actuator knew by then. """ +import asyncio from collections.abc import Iterator from pathlib import Path from typing import Any @@ -147,3 +148,152 @@ def test_a_flag_of_false_keeps_it_out(self, config: Config) -> None: builder.host_agent("orders", critical=False) assert builder.namespaces == ("orders",) assert builder.critical_namespaces == () + + +# --------------------------------------------------------------------------- +# Recovery: a latched agent is retried until it starts, and readiness shows the latch +# --------------------------------------------------------------------------- + + +class FlakyService(ServiceBase): + """Fails ``failures`` times, then starts. Class state, because the registry constructs it.""" + + failures = 1 + calls = 0 + + async def on_startup(self) -> None: + type(self).calls += 1 + if type(self).calls <= type(self).failures: + raise RuntimeError(f"not reachable yet (call {type(self).calls})") + + async def on_shutdown(self) -> None: + pass + + +class CountingService(ServiceBase): + """Starts fine, and counts how often it was asked to.""" + + calls = 0 + + async def on_startup(self) -> None: + type(self).calls += 1 + + async def on_shutdown(self) -> None: + pass + + +@pytest.fixture +def fast_retry(tmp_path: Path) -> Config: + settings = tmp_path / "settings.toml" + settings.write_text( + '[development]\napp_name = "group"\napp_port = 8000\napp_environment = "development"\nstartup_retry_interval_seconds = 0.01\n' + ) + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + +@pytest.fixture(autouse=True) +def _reset_counters() -> Iterator[None]: + FlakyService.failures, FlakyService.calls, CountingService.calls = 1, 0, 0 + yield + + +def build_with(config: Config, *services: type[ServiceBase]) -> tuple[FastAPI, AppBuilder]: + builder = AppBuilder(config) + builder.host_agent("orders", critical=True) + builder.host_agent("billing", critical=False) + with namespace_scope("orders"): + builder.with_service(QuietService) + with namespace_scope("billing"): + for service in services: + builder.with_service(service) + return builder.build(), builder + + +async def readiness(builder: AppBuilder) -> Any: + assert builder._actuator_api is not None and builder._actuator_api._health_cache is not None + return await builder._actuator_api._health_cache.get_health_status() + + +async def settle(predicate, attempts: int = 200) -> None: + for _ in range(attempts): + if predicate(): + return + await asyncio.sleep(0.01) + raise AssertionError("condition not reached") + + +class TestReadinessShowsTheLatch: + """#3 -- a latched agent was paused and reported 0 on the gauge, yet /health/ready said UP.""" + + async def test_the_agent_is_down_in_the_payload_with_its_reason(self, config: Config) -> None: + app, builder = build(config, critical=False) + async with app.router.lifespan_context(app): + response = await readiness(builder) + assert response.namespaces["billing"].status == "DOWN" + assert "database is unreachable" in (response.namespaces["billing"].reason or "") + assert response.namespaces["orders"].status == "UP" + assert response.namespaces["orders"].reason is None + + async def test_the_default_policy_takes_the_pod_out_of_rotation(self, config: Config) -> None: + app, builder = build(config, critical=False) + async with app.router.lifespan_context(app): + assert (await readiness(builder)).status == "DOWN" + + +class TestRecovery: + async def test_a_transient_failure_recovers_without_a_restart(self, fast_retry: Config) -> None: + app, builder = build_with(fast_retry, FlakyService) + async with app.router.lifespan_context(app): + supervisor = supervisor_of(builder) + await settle(lambda: supervisor.is_up("billing")) + assert supervisor.forced_down_reason("billing") is None + response = await readiness(builder) + assert response.status == "UP" + assert response.namespaces["billing"].reason is None + assert FlakyService.calls == 2 + + async def test_a_persistent_failure_stays_down_and_keeps_saying_why(self, fast_retry: Config, caplog) -> None: + app, builder = build_with(fast_retry, BrokenService) + with caplog.at_level("WARNING", logger="blueprint.agents.app_builder"): + async with app.router.lifespan_context(app): + await settle(lambda: "attempt 2" in caplog.text) + supervisor = supervisor_of(builder) + assert supervisor.is_up("billing") is False + assert "database is unreachable" in (supervisor.forced_down_reason("billing") or "") + assert "still out of service" in caplog.text + + async def test_it_never_ends_the_process(self, fast_retry: Config) -> None: + """A deterministic failure would crash-loop the pod and every healthy agent in it.""" + app, builder = build_with(fast_retry, BrokenService) + async with app.router.lifespan_context(app): + await asyncio.sleep(0.1) + assert supervisor_of(builder).is_up("orders") is True + + async def test_a_later_component_waits_for_the_one_before_it(self, fast_retry: Config) -> None: + """Retried in start order, stopping at the first that fails again: it may be a dependency.""" + FlakyService.failures = 3 + app, builder = build_with(fast_retry, FlakyService, CountingService) + async with app.router.lifespan_context(app): + await settle(lambda: supervisor_of(builder).is_up("billing")) + # CountingService started once at startup (it did not fail) and is never retried. + assert (FlakyService.calls, CountingService.calls) == (4, 1) + + async def test_shutdown_stops_the_recovery(self, fast_retry: Config) -> None: + app, builder = build_with(fast_retry, BrokenService) + async with app.router.lifespan_context(app): + assert builder._recovery_tasks + tasks = list(builder._recovery_tasks) + assert all(task.done() for task in tasks) + assert builder._recovery_tasks == [] + + @pytest.mark.parametrize("value", ["0", "-5", '"soon"']) + async def test_a_bad_interval_fails_startup(self, tmp_path: Path, value: str) -> None: + settings = tmp_path / "settings.toml" + settings.write_text( + f'[development]\napp_name = "group"\napp_port = 8000\napp_environment = "development"\n' + f"startup_retry_interval_seconds = {value}\n" + ) + app, _ = build_with(Config(settings_files=[str(settings)], root_path=str(tmp_path)), QuietService) + with pytest.raises(ValueError, match="startup_retry_interval_seconds"): + async with app.router.lifespan_context(app): + pass diff --git a/tests/unit/agents/io/api/actuators/health/test_health_cache.py b/tests/unit/agents/io/api/actuators/health/test_health_cache.py index 4c34b807..70132878 100644 --- a/tests/unit/agents/io/api/actuators/health/test_health_cache.py +++ b/tests/unit/agents/io/api/actuators/health/test_health_cache.py @@ -204,11 +204,12 @@ class TestTheVerdictIsPerAgent: """C3: the overall status is no longer a fold over every check, but a policy over agents.""" @staticmethod - def _supervisor(namespaces: list[str], critical: set[str]) -> MagicMock: - """A stand-in supervisor: the cache reads its namespaces and its critical set.""" + def _supervisor(namespaces: list[str], critical: set[str], forced: dict[str, str] | None = None) -> MagicMock: + """A stand-in supervisor: the cache reads its namespaces, its critical set and its latches.""" supervisor = MagicMock() supervisor.status = dict.fromkeys(namespaces, True) supervisor.critical_namespaces = frozenset(critical) + supervisor.forced_down = dict(forced or {}) supervisor.observe = AsyncMock() return supervisor @@ -278,3 +279,38 @@ async def test_a_cache_with_no_supervisor_still_answers(self) -> None: cache.set_health_entries(self._entries()) await cache._run_health_checks() assert (await cache.get_health_status()).status == "DOWN" + + +class TestALatchedAgent: + """#3 -- a latched agent is down in the verdict and the payload, whatever its checks say.""" + + REASON = "its service 'db' failed to start: refused" + + async def _run( + self, policy: ReadinessPolicy, critical: set[str], entries: list[HealthCheckEntry] + ) -> tuple[HealthCheckCache, MagicMock]: + supervisor = TestTheVerdictIsPerAgent._supervisor(["", "orders", "billing"], critical, {"billing": self.REASON}) + cache = HealthCheckCache(policy=policy, supervisor=supervisor) + cache.set_health_entries(entries) + await cache._run_health_checks() + return cache, supervisor + + async def test_passing_checks_do_not_make_it_up(self) -> None: + cache, supervisor = await self._run(ReadinessPolicy.ALL, set(), [_entry("db", "healthy", namespace="billing")]) + response = await cache.get_health_status() + assert response.status == "DOWN" + assert (response.namespaces["billing"].status, response.namespaces["billing"].reason) == ("DOWN", self.REASON) + assert response.namespaces["billing"].failing == [] + supervisor.observe.assert_awaited_once_with({"": True, "orders": True, "billing": False}) + + async def test_critical_policy_keeps_the_pod_in_but_says_why(self) -> None: + cache, _ = await self._run(ReadinessPolicy.CRITICAL, {"orders"}, [_entry("db", "healthy", namespace="billing")]) + response = await cache.get_health_status() + assert response.status == "UP" + assert response.namespaces["billing"].reason == self.REASON + + async def test_it_is_reported_with_no_checks_registered_at_all(self) -> None: + """The poll used to return before aggregating, so the verdict and observe() never ran.""" + cache, supervisor = await self._run(ReadinessPolicy.ALL, set(), []) + assert (await cache.get_health_status()).namespaces["billing"].status == "DOWN" + supervisor.observe.assert_awaited_once() From cdb78c45552bc99b43d025ba708c8b40aebba5a5 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 17:13:02 +0200 Subject: [PATCH 048/133] fix(eventing): fail the delivery when a handler result cannot be published publish_handler_event caught every exception and logged a WARNING, so the inbound event was acked and the handler's output was lost. The failure now propagates and the transport naks the event; the handler runs again on redelivery. With idempotency enabled the chain kept its dedup marker after a successful dispatch, so the redelivery would have been skipped as a duplicate. process_event now releases the marker (HandlerChain.release) before re-raising. Result events get a deterministic id -- UUIDv5 over agent, source event, type and position -- so a republished result keeps its id and consumers can deduplicate it. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 6 + ...26-08-28-multi-agent-grouping-changelog.md | 38 ++++++ .../docs/concepts/event-processing.md | 18 +++ src/blueprint/agents/handler/handler_chain.py | 12 ++ .../eventing/event_processing_service.py | 25 ++-- .../eventing/event_publishing_service.py | 112 ++++++++++++------ .../unit/agents/handler/test_handler_chain.py | 24 ++++ .../eventing/test_event_processing_service.py | 41 +++++++ .../eventing/test_event_publishing_service.py | 61 ++++++++++ 9 files changed, 293 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 280a749b..c38b9159 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,12 @@ ### Fixed +- **A handler result that fails to publish fails the delivery.** `publish_handler_event` caught + every exception and logged a WARNING, so the inbound event was acknowledged and the handler's + output was lost. The failure now naks the event -- the handler runs again on redelivery -- and the + dedup marker is released so the redelivery is not skipped. Result events get a deterministic id + (UUIDv5 over agent, source event, type and position) instead of a random one, so a republished + result keeps its id and consumers can deduplicate it. - **An agent latched down at startup is shown as down in `/health/ready`.** The latch paused the agent and set its gauge to 0, but readiness was computed from health checks alone, so the probe and the payload reported it `UP` with nothing failing. The payload now shows it `DOWN` with a diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 549d5738..a4d8318d 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7477,6 +7477,44 @@ real lifespan: both readiness cases fail without the aggregation change, and fou recovery cases fail with the recovery disabled (the other two assert that it never terminates and that a bad interval is refused). +### A handler result that fails to publish fails the delivery (#1) + +**Verified.** `EventPublishingService.publish_handler_event` wrapped everything in +`except Exception` and logged a WARNING; `EventProcessingService.process_event` then returned +normally, the NATS edge acked, and the handler's output was gone -- not redelivered, not +dead-lettered. The result event also got a fresh `uuid4()` per attempt, so even a redelivery +would have reached consumers under a new id. + +**A second defect behind the first, found while fixing it.** With `idempotency_enabled`, the +chain claims the event's marker before dispatch and releases it only when *dispatch* raises. +Publishing happens after `process()` returned, so a publish failure left the marker in place: +fixing only the swallow would have nak'd the event, and the redelivery would have been skipped as +a duplicate -- the output lost one step later. + +**What changed.** + +- **`publish_handler_event()`** no longer catches. A publish failure gets a note + (`exc.add_note`) naming the result's position, type, id and the source event, and propagates. + The two deliberate skips -- no topic mapping, a loop to the source topic -- still only warn. +- **`_result_event_id()`**, new: `uuid5(HANDLER_RESULT_ID_NAMESPACE, agent | source | id | + event_type | index)`, random only for a source event without an id. The agent is in the name + because two agents answering one event can share a `source` (a root-level `app_name`). +- **`publish_handler_event(..., index=)`**, new keyword, passed by `process_event` from + `enumerate(handler_results)`. +- **`process_event()`**: on a publish failure, `self._chain_for(namespace).release(event)`, then + re-raise. +- **`HandlerChain.release(event)`**, new public method over the existing `_release`, resolving + the policy itself; a no-op with dedup off. + +Decided with the user: the redelivery re-runs the handler, including an LLM call. That is the +at-least-once contract every other failure already has, and the deterministic id is what makes the +repeated publish safe downstream. + +Docs: *When publishing a result fails* in `concepts/event-processing.md`. Guarded by +`TestAFailedHandlerPublish` and `TestTheResultIdIsDerived` (`test_event_publishing_service.py`), +`TestAFailedResultPublish` (`test_event_processing_service.py`) and two `release` cases in +`test_handler_chain.py`; all nine behaviour cases fail against the previous code. + --- ## Open points diff --git a/src/blueprint/agent_generator/docs/concepts/event-processing.md b/src/blueprint/agent_generator/docs/concepts/event-processing.md index 6c7da983..6faf84ce 100644 --- a/src/blueprint/agent_generator/docs/concepts/event-processing.md +++ b/src/blueprint/agent_generator/docs/concepts/event-processing.md @@ -148,6 +148,24 @@ async def handle_event(self, event: CloudEvent) -> list[HandlerResult]: ] ``` +### When publishing a result fails + +**A result that cannot be published fails the delivery.** The inbound event is not acknowledged: it +is redelivered, and the handler runs again -- including any LLM call it makes. This is the same +at-least-once contract as a handler that raises; the alternative is an event marked processed +whose output was never sent. If deduplication is enabled, the marker for the inbound event is +released, so the redelivery is not skipped as a duplicate. + +**A result's event id is derived, not random:** a UUIDv5 over the agent, the inbound event's +`source` and `id`, the result's `event_type` and its position in the list. A redelivery therefore +republishes each result under the same id -- including results an earlier attempt had already sent +before a later one failed -- and a consumer that deduplicates on `source` + `id` sees each result +once. Keep the order of a returned list stable for the same input. + +Two cases are skipped with a WARNING rather than failed, because they are configuration rather than +a failure: an `event_type` with no entry in `topic_mapping`, and a result that would be published +to the topic its inbound event came from. + ### Return Any Other Value -- Internal Chaining Returning any other value passes it along internally within the handler chain without publishing to the event bus. This is useful for in-process data transformation between handlers. diff --git a/src/blueprint/agents/handler/handler_chain.py b/src/blueprint/agents/handler/handler_chain.py index f010d949..148a5d1f 100644 --- a/src/blueprint/agents/handler/handler_chain.py +++ b/src/blueprint/agents/handler/handler_chain.py @@ -488,6 +488,18 @@ def _claim(self, event: CloudEvent[Any], policy: IdempotencyPolicy) -> bool: ) return True + def release(self, event: CloudEvent[Any]) -> None: + """Drop this event's dedup marker after a failure that happened after a successful dispatch. + + For the caller that finishes the delivery: a handler result that could not be published + fails the delivery after the chain has already kept its claim, and the redelivery must be + allowed to run the chain again. A no-op when dedup is off. + """ + policy = self._policy + if policy is None: + policy = self._policy = self._resolve_idempotency_policy() + self._release(event, policy) + def _release(self, event: CloudEvent[Any], policy: IdempotencyPolicy) -> None: """Drop the marker after a failed dispatch so the redelivery is allowed to run. diff --git a/src/blueprint/agents/services/eventing/event_processing_service.py b/src/blueprint/agents/services/eventing/event_processing_service.py index ada9c26b..1a942d40 100644 --- a/src/blueprint/agents/services/eventing/event_processing_service.py +++ b/src/blueprint/agents/services/eventing/event_processing_service.py @@ -162,20 +162,29 @@ async def process_event( handler_results: list[HandlerResult] = self._extract_handler_results(handler_result) - for result in handler_results: + for index, result in enumerate(handler_results): if result.event_type: # This agent's publishing service, falling back to a root one. Not the # 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) - await publisher.publish_handler_event( - event_type=result.event_type, - data=result.data, - metadata=result.metadata or {}, - source_event=event, - new_subject=result.subject or new_subject, - ) + try: + await publisher.publish_handler_event( + event_type=result.event_type, + data=result.data, + metadata=result.metadata or {}, + source_event=event, + new_subject=result.subject or new_subject, + index=index, + ) + except Exception: + # The chain claimed this event's dedup marker and kept it, because the + # dispatch succeeded. The failure below naks the event; left in place, the + # marker would make the redelivery a skipped duplicate, and the result this + # publish failed to send would be lost after all. + self._chain_for(namespace).release(event) + raise status = ProcessingStatus.NO_HANDLER_FOUND if handler_result is None else ProcessingStatus.PROCESSED return self._build_result(request_id, handler_results, status) diff --git a/src/blueprint/agents/services/eventing/event_publishing_service.py b/src/blueprint/agents/services/eventing/event_publishing_service.py index 54fe6f7c..083ae888 100644 --- a/src/blueprint/agents/services/eventing/event_publishing_service.py +++ b/src/blueprint/agents/services/eventing/event_publishing_service.py @@ -2,7 +2,7 @@ import logging from typing import Any -from uuid import uuid4 +from uuid import NAMESPACE_URL, uuid4, uuid5 from opentelemetry import trace @@ -17,6 +17,10 @@ logger = logging.getLogger(__name__) +HANDLER_RESULT_ID_NAMESPACE = uuid5(NAMESPACE_URL, "urn:blueprint:handler-result") +"""The UUID namespace a handler result's event id is derived in. Fixed: changing it changes every id.""" + + class EventPublishingService(ServiceBase): """Service for publishing CloudEvents to topics via a configured eventing client. @@ -130,58 +134,94 @@ async def publish_handler_event( metadata: dict[str, Any], source_event: CloudEvent[Any], new_subject: str | None = None, + *, + index: int = 0, ) -> None: """Construct and publish a CloudEvent from a handler result. + **A failed publish raises.** It used to be caught and logged as a WARNING, after which the + delivery that produced the result was acknowledged -- so the handler's output was lost, and + nothing redelivered or dead-lettered it. Raising lets the transport edge nak the inbound + event, which runs the handler again on redelivery: at-least-once, like every other failure. + + **The result's id is derived, not random** -- see :meth:`_result_event_id`. A redelivery + republishes the same result under the same id, so a consumer that deduplicates on + ``(source, id)`` sees one event, including when an earlier attempt published part of a + handler's results before failing. + + Two deliberate skips are not failures and still only warn: an event type with no topic + mapping, and a result that would be published to the topic it came from. + Args: event_type: The event type to publish data: The event data metadata: Additional metadata (used for logging) source_event: The original event that triggered this processing new_subject: Optional subject override + index: This result's position among the results of the same dispatch. Part of the + derived id, so two results of one dispatch never share one. + + Raises: + Exception: whatever publishing raised, with a note naming the result. """ - try: - pub_config = self._get_pub_config() - topic_config = pub_config.topic_mapping.get(event_type) - - if not topic_config: - logger.warning( - "No topic mapping found for handler event type '%s', skipping publication", - event_type, - ) - return - - if topic_config.topic == getattr(source_event, "topic", None): - logger.warning( - "Handler event topic '%s' matches source event topic, skipping publication to prevent loop", - topic_config.topic, - ) - return - - handler_event = GenericCloudEvent( - specversion="1.0", - id=str(uuid4()), - source=self.config.get("app_name", "agent-service"), - type=event_type, - data=data, - subject=new_subject or getattr(source_event, "subject", None), - ) + pub_config = self._get_pub_config() + topic_config = pub_config.topic_mapping.get(event_type) - logger.info( - "Publishing handler event type '%s' to topic '%s'", + if not topic_config: + logger.warning( + "No topic mapping found for handler event type '%s', skipping publication", event_type, + ) + return + + if topic_config.topic == getattr(source_event, "topic", None): + logger.warning( + "Handler event topic '%s' matches source event topic, skipping publication to prevent loop", topic_config.topic, - extra={"event_type": event_type, "event_id": handler_event.id, "metadata": metadata}, ) + return + + handler_event = GenericCloudEvent( + specversion="1.0", + id=self._result_event_id(source_event, event_type, index), + source=self.config.get("app_name", "agent-service"), + type=event_type, + data=data, + subject=new_subject or getattr(source_event, "subject", None), + ) + + logger.info( + "Publishing handler event type '%s' to topic '%s'", + event_type, + topic_config.topic, + extra={"event_type": event_type, "event_id": handler_event.id, "metadata": metadata}, + ) + try: await self.publish_event(handler_event) - - except Exception as e: - logger.warning( - "Failed to publish handler event: %s", - str(e), - extra={"event_type": event_type, "error": str(e), "metadata": metadata}, + except Exception as exc: + exc.add_note( + f"while publishing handler result {index} ('{event_type}', id {handler_event.id}) of event " + f"'{getattr(source_event, 'id', None)}'" ) + raise + + def _result_event_id(self, source_event: CloudEvent[Any], event_type: str, index: int) -> str: + """Derive a handler result's event id from what produced it. + + A UUIDv5 over this agent, the source event's ``source`` and ``id``, the result's type and + its position. The same delivery redelivered yields the same ids; two agents answering the + same event do not collide, because the agent is part of the name -- their results can + share a ``source``, which is a root-level ``app_name``. + + Falls back to a random id for a source event without one, which has nothing stable to + derive from. + """ + source_id = str(getattr(source_event, "id", "") or "").strip() + if not source_id: + return str(uuid4()) + name = "\x1f".join((self.namespace, str(getattr(source_event, "source", "") or ""), source_id, event_type, str(index))) + return str(uuid5(HANDLER_RESULT_ID_NAMESPACE, name)) async def publish_status_event(self, status_data: dict[str, Any], status: str, event_id: str | None = "") -> dict[str, Any]: """Convenience method to publish status events. diff --git a/tests/unit/agents/handler/test_handler_chain.py b/tests/unit/agents/handler/test_handler_chain.py index 169d2ab7..ca67b6a5 100644 --- a/tests/unit/agents/handler/test_handler_chain.py +++ b/tests/unit/agents/handler/test_handler_chain.py @@ -197,6 +197,30 @@ async def can_handle_event(self, event, context): class TestIdempotencyEnabled: + async def test_release_after_a_successful_dispatch_lets_the_redelivery_run( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + """#1 -- a result that failed to publish fails the delivery after the chain kept its claim.""" + _enable_dedup(mock_config, mock_registry) + seen: list[str] = [] + + class Counting(StubHandler): + async def can_handle_event(self, event, context): + seen.append(event.id) + return False + + _wire_handlers(mock_registry, [Counting()]) + + await chain.process(cloud_event, {}) + chain.release(cloud_event) + await chain.process(cloud_event, {}) + + assert seen == ["evt-001", "evt-001"] + + def test_release_with_dedup_off_is_a_no_op(self, chain: HandlerChain, mock_registry: MagicMock, cloud_event: GenericCloudEvent) -> None: + chain.release(cloud_event) + mock_registry.cache_service.delete.assert_not_called() + async def test_same_event_delivered_twice_dispatches_once( self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent ) -> None: 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 cbeabc09..d62f577a 100644 --- a/tests/unit/agents/services/eventing/test_event_processing_service.py +++ b/tests/unit/agents/services/eventing/test_event_processing_service.py @@ -199,3 +199,44 @@ async def _capture(event, *args, **kwargs): event_processing_service.process_event = _capture await event_processing_service.process_rest_request({}) assert captured["event"].type == "rest.request" + + +class TestAFailedResultPublish: + """#1 -- the delivery fails, and the dedup marker is released so the redelivery runs.""" + + @staticmethod + def _wire(service: EventProcessingService, mock_registry: MagicMock, results: list[HandlerResult]) -> tuple[MagicMock, MagicMock]: + chain = MagicMock() + chain.process = AsyncMock(return_value=results) + service._handler_chains[ROOT_NAMESPACE] = chain + publisher = MagicMock() + publisher.publish_handler_event = AsyncMock() + mock_registry.get_component.return_value = publisher + return chain, publisher + + async def test_it_fails_the_delivery_and_releases_the_marker( + self, event_processing_service: EventProcessingService, mock_registry: MagicMock + ) -> None: + chain, publisher = self._wire(event_processing_service, mock_registry, [HandlerResult(event_type="done", data={})]) + publisher.publish_handler_event.side_effect = ConnectionError("broker gone") + event = GenericCloudEvent(id="e1", type="t", source="s") + + with pytest.raises(ConnectionError): + await event_processing_service.process_event(event) + chain.release.assert_called_once() + assert chain.release.call_args.args[0].id == "e1" + + async def test_a_successful_publish_keeps_the_marker( + self, event_processing_service: EventProcessingService, mock_registry: MagicMock + ) -> None: + chain, _ = self._wire(event_processing_service, mock_registry, [HandlerResult(event_type="done", data={})]) + await event_processing_service.process_event(GenericCloudEvent(id="e1", type="t", source="s")) + chain.release.assert_not_called() + + async def test_each_result_is_published_with_its_position( + self, event_processing_service: EventProcessingService, mock_registry: MagicMock + ) -> None: + results = [HandlerResult(event_type="a", data={}), HandlerResult(event_type="b", data={})] + _, publisher = self._wire(event_processing_service, mock_registry, results) + await event_processing_service.process_event(GenericCloudEvent(id="e1", type="t", source="s")) + assert [call.kwargs["index"] for call in publisher.publish_handler_event.await_args_list] == [0, 1] diff --git a/tests/unit/agents/services/eventing/test_event_publishing_service.py b/tests/unit/agents/services/eventing/test_event_publishing_service.py index 10082a1b..7042f876 100644 --- a/tests/unit/agents/services/eventing/test_event_publishing_service.py +++ b/tests/unit/agents/services/eventing/test_event_publishing_service.py @@ -314,3 +314,64 @@ async def test_no_client_at_all_raises(self, real_registry: Registry, mock_confi svc = EventPublishingService() with pytest.raises(ValueError, match="No components of type"): await svc.on_startup() + + +# --------------------------------------------------------------------------- +# #1 -- a failed publish of a handler result is not swallowed, and its id is stable +# --------------------------------------------------------------------------- + + +class TestAFailedHandlerPublish: + async def test_the_failure_reaches_the_caller( + self, event_publishing_service: EventPublishingService, mock_io_client: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + """Swallowed, the delivery was acked and the handler's output was lost.""" + mock_io_client.publish.side_effect = ConnectionError("broker gone") + with pytest.raises(ConnectionError, match="broker gone") as caught: + await event_publishing_service.publish_handler_event( + event_type="test.event", data={}, metadata={}, source_event=cloud_event, index=1 + ) + assert any("handler result 1 ('test.event'" in note for note in caught.value.__notes__) + + async def test_a_deliberate_skip_is_still_not_an_error( + self, event_publishing_service: EventPublishingService, cloud_event: GenericCloudEvent + ) -> None: + await event_publishing_service.publish_handler_event(event_type="unmapped.event", data={}, metadata={}, source_event=cloud_event) + + +class TestTheResultIdIsDerived: + """A redelivery republishes under the same id, so a consumer can deduplicate it.""" + + @staticmethod + async def _published_id(service: EventPublishingService, client: MagicMock, source: GenericCloudEvent, index: int = 0) -> str: + client.publish.reset_mock() + await service.publish_handler_event(event_type="test.event", data={}, metadata={}, source_event=source, index=index) + return client.publish.await_args.args[1].id + + async def test_the_same_delivery_gets_the_same_id( + self, event_publishing_service: EventPublishingService, mock_io_client: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + first = await self._published_id(event_publishing_service, mock_io_client, cloud_event) + again = await self._published_id(event_publishing_service, mock_io_client, cloud_event) + assert first == again + + async def test_two_results_of_one_dispatch_differ( + self, event_publishing_service: EventPublishingService, mock_io_client: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + first = await self._published_id(event_publishing_service, mock_io_client, cloud_event, index=0) + second = await self._published_id(event_publishing_service, mock_io_client, cloud_event, index=1) + assert first != second + + async def test_another_source_event_differs( + self, event_publishing_service: EventPublishingService, mock_io_client: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + other = GenericCloudEvent(id="evt-002", type="test.event", source="test-source") + assert await self._published_id(event_publishing_service, mock_io_client, cloud_event) != await self._published_id( + event_publishing_service, mock_io_client, other + ) + + def test_two_agents_answering_one_event_do_not_collide(self, cloud_event: GenericCloudEvent) -> None: + """Their results can share a source (a root-level app_name), so the agent is in the id.""" + orders, billing = MagicMock(namespace="orders"), MagicMock(namespace="billing") + derive = EventPublishingService._result_event_id + assert derive(orders, cloud_event, "test.event", 0) != derive(billing, cloud_event, "test.event", 0) From 9ffdd3da9ca6bfec01c31b4a38d1ff579b8bdb3b Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 17:24:09 +0200 Subject: [PATCH 049/133] fix(nats)!: enforce the declared JetStream mode instead of falling back to Core NATS connect() called connection.jetstream() and, if that raised, fell back to Core NATS -- no durable consumers, no settlement -- without anyone deciding it. jetstream() asks the server nothing, so the fallback rarely fired and an agent on a server without JetStream failed later, at provisioning. connect() now asks the server for the account's JetStream info. No responders or an API error fail the connection with JetStreamUnavailableError, which the retry loop does not retry. At startup the sec. 9.1 policy applies; found later, AppBuilder shuts the process down (SIGTERM to itself) for the root or a critical agent and marks a non-critical agent down. Core NATS asks the server nothing. BREAKING CHANGE: with nats_use_jetstream = true, a server that does not offer JetStream to the account now fails the agent instead of degrading to Core NATS. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 6 + ...26-08-28-multi-agent-grouping-changelog.md | 41 ++++++ .../docs/concepts/event-processing.md | 9 ++ .../docs/guides/troubleshooting.md | 15 ++ .../docs/reference/configuration-keys.md | 2 +- src/blueprint/agents/app_builder.py | 27 +++- .../agents/clients/io/nats_client.py | 111 +++++++++++++-- .../test_startup_failure_policy.py | 30 ++++ .../agents/clients/io/test_nats_client.py | 134 +++++++++++++++++- 9 files changed, 362 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c38b9159..2c0247ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -126,6 +126,12 @@ ### Breaking +- **`nats_use_jetstream = true` is enforced against the server; there is no fallback to Core + NATS.** The server is asked for the account's JetStream information on connecting. If it does not + offer JetStream, the agent fails: at startup through the startup failure policy, later (broker + unreachable at startup) by shutting the process down for the root or a critical agent and marking + a non-critical one down. The previous fallback rarely triggered, and when it did it dropped + durable consumers and acknowledgements without anyone deciding it. - **`ClientBase.subscribe()` callbacks take the delivery subject.** The contract is now `DeliveryCallback = Callable[[CloudEvent, str], Awaitable[None]]` (in `clients/client_base.py`): the event, then the subject it arrived on. Only code that calls `NATSClient.subscribe()` directly, diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index a4d8318d..9c636132 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7515,6 +7515,47 @@ Docs: *When publishing a result fails* in `concepts/event-processing.md`. Guarde `TestAFailedResultPublish` (`test_event_processing_service.py`) and two `release` cases in `test_handler_chain.py`; all nine behaviour cases fail against the previous code. +### The declared transport mode is enforced (#4, decision D) + +**Verified.** `NATSClient.connect()` called `connection.jetstream()` inside a `try` and, if it +raised, logged a WARNING and set `_use_jetstream = False` -- falling back to Core NATS: no durable +consumers, and `_settle` returns early on Core NATS, so every handler failure was dropped. Worse, the +fallback almost never fired: `jetstream()` only builds a local context and asks the server nothing, +so an agent on a server without JetStream connected "successfully" and failed later, confusingly, +at stream provisioning. + +Decided with the user: `nats_use_jetstream` is the declaration, and a server that does not match it +fails the agent. Core declared on a JetStream-enabled server is fine -- Core NATS works everywhere. + +**What changed, in `nats_client.py`.** + +- **`JetStreamUnavailableError`**, new: the declared-JetStream-but-not-offered error. +- **`_require_jetstream()`**, new, called by `connect()` right after `jetstream()`: sends + `account_info()`. `NoRespondersError` and `APIError` (which covers `ServiceUnavailableError`) + are answers: the connection is closed, the error recorded in `_jetstream_mismatch`, reported + (below), and raised. A `nats.errors.TimeoutError` is not an answer and propagates as an ordinary, + retried connection failure. The fallback block is gone. +- **`_start_with_retry()`** re-raises `JetStreamUnavailableError` without retrying. +- **`health_check()`** reports the recorded mismatch as the unhealthy message. +- **`on_startup()`**: if a mismatch was recorded -- normally by the actuator's first health poll, + which connects every client before any component starts -- it probes again (`connect()`), so the + startup failure policy (sec. 9.1) applies and a retried startup sees a fixed server. It then marks + the client started. +- **`set_fatal_handler()`**, **`_report_fatal()`**: after startup, a mismatch is handed once to the + installed handler, as a watched task. + +**In `app_builder.py`:** every `NATSClient` gets `set_fatal_handler(self._on_transport_fatal)`. +**`_on_transport_fatal()`**, new: the root or a critical agent logs CRITICAL and sends SIGTERM to the +process (`signal.raise_signal`), so uvicorn runs the graceful shutdown and the other agents drain; a +non-critical agent is marked down and stays down, because this is a deployment error no retry fixes +(it is deliberately not added to the startup-recovery list). + +Docs: `nats_use_jetstream` in `reference/configuration-keys.md`, *JetStream delivery* in +`concepts/event-processing.md`, a new symptom in `guides/troubleshooting.md`. Guarded by +`TestTheDeclaredModeIsEnforced` (`test_nats_client.py`, 12 cases) and +`TestAFatalTransportErrorAfterStartup` (`test_startup_failure_policy.py`, 3 cases). One existing +test (`test_connect_enables_jetstream_when_configured`) needed `account_info` mocked as awaitable. + --- ## Open points diff --git a/src/blueprint/agent_generator/docs/concepts/event-processing.md b/src/blueprint/agent_generator/docs/concepts/event-processing.md index 6faf84ce..487b5734 100644 --- a/src/blueprint/agent_generator/docs/concepts/event-processing.md +++ b/src/blueprint/agent_generator/docs/concepts/event-processing.md @@ -258,6 +258,15 @@ With `nats_use_jetstream = true` the framework creates one **durable consumer pe configured stream and binds every replica to it through the agent's queue group, so exactly one replica handles each message. What happens to a delivery is decided at the transport edge: +**`nats_use_jetstream` is checked against the server.** On connecting, the framework asks the +server for the account's JetStream information. If JetStream is not there -- not enabled on the +server, or not for this account -- the agent fails, and there is no fallback to Core NATS: that +would silently drop durable consumers and acknowledgements. At startup the startup failure policy +applies. If the broker was unreachable at startup and the mismatch shows up later, the root or a +critical agent shuts the process down (SIGTERM to itself, so the other agents still drain), and a +non-critical agent is marked down until the pod restarts. A timeout on that request is not treated +as an answer; it is retried like any other connection failure. + | Outcome | Disposition | |---------|-------------| | The handler chain returned, including "no handler matched" | `ack` | diff --git a/src/blueprint/agent_generator/docs/guides/troubleshooting.md b/src/blueprint/agent_generator/docs/guides/troubleshooting.md index 06348799..3da47f84 100644 --- a/src/blueprint/agent_generator/docs/guides/troubleshooting.md +++ b/src/blueprint/agent_generator/docs/guides/troubleshooting.md @@ -197,6 +197,21 @@ ValueError: 'event_bus' is 'nats' but 'nats_url' is not set (app_environment is **Solution:** Set `nats_url` in the group's `settings.toml`, or in the environment as the variable the message names (`DYNACONF_NATS_URL` with the default prefix). +### `does not offer JetStream to this account` + +**Symptom:** Startup fails, an agent is marked down, or the process shuts itself down, with: + +``` +JetStreamUnavailableError: Agent 'orders' declares 'nats_use_jetstream = true', but the NATS server at ... does not offer JetStream to this account +``` + +**Cause:** The agent is configured for JetStream and the server answered that JetStream is not +available -- not enabled on the server (`jetstream {}` missing from its configuration), or not +enabled for the account the connection authenticates as. + +**Solution:** Enable JetStream for that server and account, or set `nats_use_jetstream = false` +if the agent is meant to run on Core NATS. The framework does not fall back on its own. + ### Topic Mapping Mismatches **Symptom:** Events are published but handlers never receive them. diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 65896046..93b0d435 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -40,7 +40,7 @@ Settings for the event bus transport layer. | `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. | | `event_client_drain_timeout` | `float` | `30.0` | Seconds allowed at shutdown for in-flight message handlers to finish before the broker connection is closed. Bounds the whole shutdown sequence, so keep it below the pod's termination grace period. | -| `nats_use_jetstream` | `bool` | `false` | Consume through a durable JetStream consumer instead of Core NATS. The keys below apply only when this is `true`. | +| `nats_use_jetstream` | `bool` | `false` | Consume through a durable JetStream consumer instead of Core NATS. The keys below apply only when this is `true`. **A declaration, enforced:** with `true`, a server that does not offer JetStream to the account fails the agent -- at startup through the startup failure policy, or, if the broker was unreachable then, when it first connects: the root or a critical agent shuts the process down, a non-critical agent is marked down. There is no fallback to Core NATS. With `false`, the server is not asked; Core NATS works on a JetStream-enabled server too. | | `nats_stream_name` | `str` | `"EVENTS"` | Stream the durable consumers are created on. The framework creates it if it is missing, and widens an existing one to cover every subscribed subject plus the dead-letter subject; it never removes a subject. | | `nats_durable_name` | `str` | `"-durable"` | Name of the durable consumer. Derived from the topic by default, with `.`, `*`, `>` and whitespace replaced by `_` because NATS rejects them in a consumer name. A client that belongs to a namespace prefixes it (`"--durable"`), so two agents subscribing to the same topic get a consumer each. Setting it explicitly is only valid with a single subscribed topic: a durable filters one subject, and under a namespace it must be scoped per namespace or every namespace binds to the same consumer. | | `nats_ack_wait` | `float` | `300.0` | Seconds the broker waits for an acknowledgement before redelivering. **Must exceed the p99 duration of your slowest handler**, or long inference is redelivered to another replica while the first is still working. The default is deliberately far above the NATS default of 30 s because handlers in this framework call models. | diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index 81c24993..3a182909 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -3,6 +3,7 @@ import asyncio import contextlib import logging +import signal from collections.abc import AsyncIterator, Callable, Mapping from contextlib import asynccontextmanager from dataclasses import dataclass @@ -1083,7 +1084,7 @@ def _wire_transport(self, registry: Registry, namespace: str, event_bus_type: st # The client is per agent; the endpoint is not. See _wire_dapr_endpoint. DaprClient(namespace=namespace) # auto-registers elif event_bus_type == "nats": - NATSClient(namespace=namespace) # auto-registers + NATSClient(namespace=namespace).set_fatal_handler(self._on_transport_fatal) # auto-registers if consumes: self._eventing_components.append(NatsEventing(namespace=namespace)) elif event_bus_type == "sessions": @@ -1299,6 +1300,30 @@ async def _start_component(self, kind: str, component: Any, label: str) -> None: return logger.info("%s %s startup completed", kind, label) + async def _on_transport_fatal(self, namespace: str, error: BaseException) -> None: + """Act on a transport that found, after startup, that its agent cannot run at all. + + The startup failure policy (sec. 9.1) decides at startup; this is the same decision for the + case where the broker was not reachable then, so the failure surfaced later, in the + connection loop or a health poll. The root and a critical agent end the process -- a pod + that stays up without them is a replica silently short a consumer, the very case sec. 9.1 + exits for. A non-critical agent is marked down, and stays down: unlike a startup failure, + this is a deployment error that no retry fixes. + + The process is ended with SIGTERM to itself, so uvicorn runs the normal graceful shutdown + -- the other agents drain -- instead of the interpreter stopping mid-flight. + """ + if not namespace or namespace in self._critical_namespaces: + logger.critical( + "Agent '%s' cannot run, and it is %s, so the process is shut down: %s", + namespace or ROOT_LABEL, + "the root" if not namespace else "critical", + error, + ) + signal.raise_signal(signal.SIGTERM) + return + await self._mark_agent_down(namespace, str(error)) + @staticmethod def _startup_retry_interval(config: Config) -> float: """Read ``startup_retry_interval_seconds``, refusing a value that is not a positive number. diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index f148dd3c..55669e7b 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -6,6 +6,7 @@ import json import logging import re +from collections.abc import Awaitable, Callable from dataclasses import dataclass from functools import cached_property from pathlib import Path @@ -16,7 +17,8 @@ from nats.aio.client import Client as NatsClient from nats.js import api as js_api from nats.js.client import JetStreamContext -from nats.js.errors import NotFoundError +from nats.errors import NoRespondersError +from nats.js.errors import APIError, NotFoundError from opentelemetry.metrics import Counter from ...component.namespace import ROOT_LABEL, ROOT_NAMESPACE @@ -39,6 +41,19 @@ """ +class JetStreamUnavailableError(RuntimeError): + """The agent declared ``nats_use_jetstream = true`` and the server does not offer JetStream to it. + + A deployment error, not a transient one: no retry makes a server grow JetStream. It is therefore + never retried by the connection loop, and it fails the agent -- at startup through the startup + failure policy (spec sec. 9.1), later through the fatal handler :class:`AppBuilder` installs. + """ + + +FatalHandler = Callable[[str, BaseException], Awaitable[None]] +"""Called once when a client finds, after startup, that its agent cannot run at all: namespace, error.""" + + def redact_url(url: str) -> str: """Return ``url`` without its ``user:password@`` part, for logs and health messages. @@ -167,6 +182,10 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: self._connection_name: str = "" self._nats_url: str = "" self._connect_options: dict[str, Any] = {} + self._jetstream_mismatch: JetStreamUnavailableError | None = None + self._started = False + self._fatal_handler: FatalHandler | None = None + self._fatal_reported = False self._nats_client: NatsClient | None = None self._js: JetStreamContext | None = None self._use_jetstream: bool = False @@ -603,6 +622,22 @@ async def on_startup(self) -> None: """ self._nats_url = self._resolve_nats_url() self._connect_options = self._resolve_connect_options(self._nats_url) + if self._jetstream_mismatch is not None: + # Found by a connect that ran before this -- normally the actuator's first health poll, + # which connects every client before any component starts. Probed again rather than + # re-raised, so a retried startup (sec. 9.1) sees a server that has since been fixed. + self._jetstream_mismatch = None + await self.connect() + self._started = True + + def set_fatal_handler(self, handler: FatalHandler) -> None: + """Install what is called when this agent turns out, after startup, to be unable to run. + + Before startup has finished, such a failure is raised from :meth:`on_startup` instead, where + the startup failure policy handles it. After it, nothing awaits the connection -- it happens + in the retry loop or a health poll -- so it is handed to this handler, once. + """ + self._fatal_handler = handler def _resolve_nats_url(self) -> str: """Return the configured ``nats_url``; outside development, refuse to run without one. @@ -746,20 +781,70 @@ async def connect(self) -> None: self._publish_via_jetstream = self._resolve_publish_mode() self._publish_subjects = self._resolve_publish_subjects() if self._use_jetstream: - try: - self._js = self._nats_client.jetstream() - logger.info("Connected to NATS server with JetStream at %s as '%s'", nats_url, self._connection_name) - except Exception as e: - logger.warning("JetStream initialization failed, falling back to Core NATS: %s", str(e)) - self._use_jetstream = False - self._publish_via_jetstream = False - - if not self._use_jetstream: + self._js = self._nats_client.jetstream() + await self._require_jetstream(nats_url) + logger.info("Connected to NATS server with JetStream at %s as '%s'", nats_url, self._connection_name) + else: logger.info("Connected to NATS server (Core NATS) at %s as '%s'", nats_url, self._connection_name) + except JetStreamUnavailableError: + raise except Exception as e: logger.error("Failed to connect to NATS: %s", str(e)) raise + async def _require_jetstream(self, nats_url: str) -> None: + """Fail the connection if the server does not offer JetStream to this account. + + ``connection.jetstream()`` only builds a local context and asks the server nothing, so the + fallback this replaces -- "JetStream initialization failed, falling back to Core NATS" -- + almost never fired, and when it did it silently dropped durability: no durable consumer, + and no settlement, so every handler failure was lost. Nobody had decided that. The account + info request is the cheapest call that the server answers only when JetStream is there. + + A timeout proves nothing either way and stays an ordinary connection failure, retried like + any other. No responders (no JetStream on the server) and an API error (not enabled for the + account) are answers, and they are final. + + Raises: + JetStreamUnavailableError: the server answered, and JetStream is not available. + """ + try: + await self._js.account_info() # type: ignore[union-attr] + except (NoRespondersError, APIError) as exc: + error = JetStreamUnavailableError( + f"Agent '{self.namespace or ROOT_LABEL}' declares 'nats_use_jetstream = true', but the NATS server at " + f"{nats_url} does not offer JetStream to this account ({type(exc).__name__}: {exc}). It is not retried " + "and there is no fallback to Core NATS, which would drop durable consumers and acknowledgements " + "without anyone deciding it. Enable JetStream on the server or account, or set " + "'nats_use_jetstream = false' if Core NATS is intended." + ) + await self._nats_client.close() # type: ignore[union-attr] + self._nats_client = None + self._js = None + self._client = None + self._jetstream_mismatch = error + self._report_fatal(error) + raise error from exc + + def _report_fatal(self, error: BaseException) -> None: + """Hand a fatal error found after startup to the installed handler, once.""" + if not self._started or self._fatal_handler is None or self._fatal_reported: + return + self._fatal_reported = True + task = asyncio.ensure_future(self._fatal_handler(self.namespace, error)) + task.add_done_callback(self._on_fatal_handler_done) + + def _on_fatal_handler_done(self, task: asyncio.Task[None]) -> None: + """Report a fatal handler that itself raised, naming the agent (C7).""" + if task.cancelled() or task.exception() is None: + return + logger.error( + "Agent '%s': handling a fatal transport error failed: %s", + self.namespace or ROOT_LABEL, + task.exception(), + exc_info=task.exception(), + ) + async def pause_consumption(self) -> None: """Drain this agent's subscriptions so its events redeliver elsewhere (C4). @@ -949,6 +1034,8 @@ async def health_check(self) -> ComponentHealth: self-sustaining: the agent could never be seen to recover, so consumption would never resume, and a transient Redis outage would take the agent off its topics permanently. """ + if self._jetstream_mismatch is not None: + return ComponentHealth(status="unhealthy", message=str(self._jetstream_mismatch)) if not self._is_connected(): return ComponentHealth(status="unhealthy", message="NATS client not connected") if self._consumption_paused: @@ -976,6 +1063,10 @@ async def _start_with_retry(self) -> None: self._subscriptions_ready = True logger.info("NATSClient connected and subscribed successfully") return + except JetStreamUnavailableError: + # Final, not transient: retrying would log the same answer forever. + self._subscriptions_ready = False + raise except Exception as e: attempt += 1 self._subscriptions_ready = False diff --git a/tests/unit/agents/app_builder/test_startup_failure_policy.py b/tests/unit/agents/app_builder/test_startup_failure_policy.py index a631a162..efa38c4f 100644 --- a/tests/unit/agents/app_builder/test_startup_failure_policy.py +++ b/tests/unit/agents/app_builder/test_startup_failure_policy.py @@ -10,9 +10,11 @@ """ import asyncio +import signal from collections.abc import Iterator from pathlib import Path from typing import Any +from unittest.mock import AsyncMock, patch import pytest from fastapi import FastAPI @@ -297,3 +299,31 @@ async def test_a_bad_interval_fails_startup(self, tmp_path: Path, value: str) -> with pytest.raises(ValueError, match="startup_retry_interval_seconds"): async with app.router.lifespan_context(app): pass + + +class TestAFatalTransportErrorAfterStartup: + """D -- the startup failure policy, for a failure that surfaced after startup.""" + + @staticmethod + def _builder(config: Config) -> AppBuilder: + builder = AppBuilder(config) + builder.host_agent("orders", critical=True) + builder.host_agent("billing", critical=False) + builder._critical_namespaces = ["orders"] + return builder + + @pytest.mark.parametrize("namespace", ["", "orders"], ids=["root", "critical"]) + async def test_the_root_or_a_critical_agent_ends_the_process(self, config: Config, namespace: str, caplog) -> None: + builder = self._builder(config) + with patch("blueprint.agents.app_builder.signal.raise_signal") as raise_signal, caplog.at_level("CRITICAL"): + await builder._on_transport_fatal(namespace, RuntimeError("no JetStream")) + raise_signal.assert_called_once_with(signal.SIGTERM) + assert "the process is shut down" in caplog.text + + async def test_a_non_critical_agent_is_marked_down(self, config: Config) -> None: + builder = self._builder(config) + builder._mark_agent_down = AsyncMock() # type: ignore[method-assign] + with patch("blueprint.agents.app_builder.signal.raise_signal") as raise_signal: + await builder._on_transport_fatal("billing", RuntimeError("no JetStream")) + raise_signal.assert_not_called() + builder._mark_agent_down.assert_awaited_once_with("billing", "no JetStream") diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index 188ccc5a..c95ee978 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -7,10 +7,19 @@ from urllib.parse import urlparse import pytest +from nats.errors import NoRespondersError +from nats.errors import TimeoutError as NatsTimeoutError from nats.js import api as js_api +from nats.js.errors import APIError, ServiceUnavailableError from blueprint.agents.clients.io.io_client_base import subject_is_covered_by -from blueprint.agents.clients.io.nats_client import DEVELOPMENT_NATS_URL, ConsumerTuning, NATSClient, redact_url +from blueprint.agents.clients.io.nats_client import ( + DEVELOPMENT_NATS_URL, + ConsumerTuning, + JetStreamUnavailableError, + NATSClient, + redact_url, +) from blueprint.agents.models.errors import CriticalHandlerError, InvalidEventError, RetryableHandlerError from blueprint.agents.models.events import CloudEvent @@ -106,6 +115,7 @@ async def test_connect_enables_jetstream_when_configured(self, nats_client: NATS True if key == "nats_use_jetstream" else {"nats_url": "nats://localhost:4222"}.get(key, default) ) mock_js = MagicMock() + mock_js.account_info = AsyncMock() mock_nc = MagicMock(is_closed=False, is_connected=True) mock_nc.jetstream = MagicMock(return_value=mock_js) with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock) as mock_connect: @@ -2038,3 +2048,125 @@ def test_a_wildcard_stream_needs_no_widening(self, nats_client: NATSClient) -> N assert wanted, "the client wanted no subjects at all, so this asserts nothing" assert all(subject_is_covered_by(subject, "orders.>") for subject in wanted) + + +class TestTheDeclaredModeIsEnforced: + """D -- nats_use_jetstream is a declaration: a server without JetStream fails the agent. + + It used to be a wish. connection.jetstream() asks the server nothing, and the rare failure it + did catch fell back to Core NATS -- no durable consumers, no settlement -- without anyone + deciding it. + """ + + @staticmethod + def _configure(mock_config: MagicMock, *, jetstream: bool) -> None: + values = {"app_name": "orders", "nats_url": "nats://broker:4222", "app_environment": "production", "nats_use_jetstream": jetstream} + mock_config.get.side_effect = lambda key, default=None: values.get(key, default) + mock_config.envvar_prefix = "DYNACONF" + + @staticmethod + def _server(account_info: AsyncMock) -> MagicMock: + js = MagicMock() + js.account_info = account_info + nc = MagicMock(is_closed=False, is_connected=True) + nc.jetstream = MagicMock(return_value=js) + nc.close = AsyncMock() + return nc + + async def _connect(self, client: NATSClient, nc: MagicMock) -> None: + with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock, return_value=nc): + await client.connect() + + @pytest.mark.parametrize( + "answer", + [ + ServiceUnavailableError(), + NoRespondersError(), + APIError(code=503, err_code=10039, description="jetstream not enabled for account"), + ], + ids=["no-jetstream-on-server", "no-responders", "not-enabled-for-account"], + ) + async def test_a_server_without_jetstream_fails_the_connection( + self, nats_client: NATSClient, mock_config: MagicMock, answer: Exception + ) -> None: + self._configure(mock_config, jetstream=True) + nc = self._server(AsyncMock(side_effect=answer)) + with pytest.raises(JetStreamUnavailableError, match="nats_use_jetstream = true"): + await self._connect(nats_client, nc) + nc.close.assert_awaited_once() + assert nats_client._nats_client is None + assert nats_client._use_jetstream is True + + async def test_it_is_reported_by_the_health_check(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config, jetstream=True) + with pytest.raises(JetStreamUnavailableError): + await self._connect(nats_client, self._server(AsyncMock(side_effect=ServiceUnavailableError()))) + health = await nats_client.health_check() + assert health.status == "unhealthy" + assert "does not offer JetStream" in (health.message or "") + + async def test_a_timeout_is_not_an_answer(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """No reply proves nothing; it stays an ordinary, retried connection failure.""" + self._configure(mock_config, jetstream=True) + with pytest.raises(NatsTimeoutError): + await self._connect(nats_client, self._server(AsyncMock(side_effect=NatsTimeoutError()))) + assert nats_client._jetstream_mismatch is None + + async def test_a_server_with_jetstream_connects(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config, jetstream=True) + await self._connect(nats_client, self._server(AsyncMock())) + assert nats_client._js is not None + + async def test_core_asks_the_server_nothing(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """Core NATS works on every server; JetStream being enabled there does not matter.""" + self._configure(mock_config, jetstream=False) + info = AsyncMock() + await self._connect(nats_client, self._server(info)) + info.assert_not_awaited() + + async def test_the_retry_loop_does_not_retry_it(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config, jetstream=True) + connect = AsyncMock(return_value=self._server(AsyncMock(side_effect=ServiceUnavailableError()))) + with patch("blueprint.agents.clients.io.nats_client.nats.connect", connect): + with pytest.raises(JetStreamUnavailableError): + await nats_client._start_with_retry() + connect.assert_awaited_once() + + async def test_startup_fails_when_a_poll_found_it_first(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """The actuator's first health poll connects every client before any component starts.""" + self._configure(mock_config, jetstream=True) + nc = self._server(AsyncMock(side_effect=ServiceUnavailableError())) + with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock, return_value=nc): + with pytest.raises(JetStreamUnavailableError): + await nats_client.connect() + with pytest.raises(JetStreamUnavailableError): + await nats_client.on_startup() + + async def test_a_retried_startup_sees_a_fixed_server(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config, jetstream=True) + with pytest.raises(JetStreamUnavailableError): + await self._connect(nats_client, self._server(AsyncMock(side_effect=ServiceUnavailableError()))) + with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock, return_value=self._server(AsyncMock())): + await nats_client.on_startup() + assert nats_client._jetstream_mismatch is None + + async def test_after_startup_it_goes_to_the_fatal_handler_once(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config, jetstream=True) + handler = AsyncMock() + nats_client.set_fatal_handler(handler) + await nats_client.on_startup() + for _ in range(3): + with pytest.raises(JetStreamUnavailableError): + await self._connect(nats_client, self._server(AsyncMock(side_effect=ServiceUnavailableError()))) + await asyncio.sleep(0) + handler.assert_awaited_once() + assert handler.await_args.args[0] == nats_client.namespace + + async def test_before_startup_it_is_left_to_on_startup(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config, jetstream=True) + handler = AsyncMock() + nats_client.set_fatal_handler(handler) + with pytest.raises(JetStreamUnavailableError): + await self._connect(nats_client, self._server(AsyncMock(side_effect=ServiceUnavailableError()))) + await asyncio.sleep(0) + handler.assert_not_awaited() From ddab8d24c6f932b0e8ad655dbc0c3930bb2a29b0 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 17:29:37 +0200 Subject: [PATCH 050/133] fix(handler): claim the dedup marker atomically HandlerChain._claim checked the marker with exists() and then wrote it with set(), so two replicas handed the same event between the two calls both dispatched it. It now uses CacheService.claim(), the atomic set-if-absent the scheduler already uses. Release on failure is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 4 +++ ...26-08-28-multi-agent-grouping-changelog.md | 18 ++++++++++++ .../docs/reference/configuration-keys.md | 2 +- src/blueprint/agents/handler/handler_chain.py | 18 +++++------- .../unit/agents/handler/test_handler_chain.py | 29 +++++++++++++++++++ 5 files changed, 60 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c0247ea..b4e2ad4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,10 @@ ### Fixed +- **Event deduplication claims atomically.** The handler chain checked for the marker with + `exists()` and then wrote it with `set()`, so two replicas handed the same event at the same moment + both passed the check and both dispatched. It now uses the cache's atomic `claim()`, which already + existed for the scheduler's tick claim. - **A handler result that fails to publish fails the delivery.** `publish_handler_event` caught every exception and logged a WARNING, so the inbound event was acknowledged and the handler's output was lost. The failure now naks the event -- the handler runs again on redelivery -- and the diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 9c636132..daf3adc5 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7556,6 +7556,24 @@ Docs: `nats_use_jetstream` in `reference/configuration-keys.md`, *JetStream deli `TestAFatalTransportErrorAfterStartup` (`test_startup_failure_policy.py`, 3 cases). One existing test (`test_connect_enables_jetstream_when_configured`) needed `account_info` mocked as awaitable. +### Event deduplication claims atomically (#6) + +**Verified.** `HandlerChain._claim` called `cache.exists()` and then `cache.set()`: two replicas +handed the same event between those calls both passed and both dispatched. The class docstring +admitted it. `CacheService.claim()` -- atomic set-if-absent, `add` on the disk cache and `SET NX` +on Redis, whose own docstring names event deduplication as a purpose -- was used only by the +scheduler. + +**Change:** `_claim` returns `self.registry.cache_service.claim(key, marker, namespace=..., ttl=...)`. +The release on failure (`_release` / `release`) is unchanged: it deletes the marker. The docstring +and `idempotency_enabled` in `reference/configuration-keys.md` now describe what the claim +guarantees: atomic across replicas that share a cache, per pod otherwise, and failing open on a cache +error. + +Guarded by `test_the_claim_is_one_atomic_call` in `test_handler_chain.py`, which simulates the race +window (`exists()` says absent, `claim()` says taken) and fails against the previous code. The stub +cache in that file gained `claim()`. + --- ## Open points diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 93b0d435..3f43ae72 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -123,7 +123,7 @@ effects is acceptable is a property of the product, not of the framework. | Key | Type | Default | Description | |-----|------|---------|-------------| -| `idempotency_enabled` | `bool` | `false` | Skip an event whose `id` and `source` were already dispatched within the window. Requires `idempotency_ttl` and a registered cache (`.with_cache()`); startup fails if either is missing, rather than leaving deduplication silently off. Best-effort: the claim is check-then-set, so two replicas handed the same event at the same instant can both dispatch, and a cache error fails open. | +| `idempotency_enabled` | `bool` | `false` | Skip an event whose `id` and `source` were already dispatched within the window. Requires `idempotency_ttl` and a registered cache (`.with_cache()`); startup fails if either is missing, rather than leaving deduplication silently off. The claim is the cache's atomic set-if-absent, so replicas sharing a cache (Redis, or a disk cache on a shared volume) cannot both dispatch the same event; a per-pod cache deduplicates within that pod only, and a cache error fails open. | | `idempotency_ttl` | `int` | -- | Seconds a processed event is remembered. No default on purpose -- it must outlast the broker's redelivery window (`nats_ack_wait` * `nats_max_deliver` on JetStream, the component's retry policy under Dapr), and a window that expires before the last redelivery looks exactly like deduplication not working. | --- diff --git a/src/blueprint/agents/handler/handler_chain.py b/src/blueprint/agents/handler/handler_chain.py index 148a5d1f..3bc0498e 100644 --- a/src/blueprint/agents/handler/handler_chain.py +++ b/src/blueprint/agents/handler/handler_chain.py @@ -187,10 +187,11 @@ class HandlerChain(Component): claim, because the failure naks and the redelivery must be allowed to run: a claim kept across a failure would turn every retry into a silent no-op. - The claim is check-then-set, not a lock. Two replicas handed the same event at the - same instant can both pass the check, and a cache that is unreachable fails open -- - both dispatch. This narrows the duplicate window; it does not close it, and a handler - whose side effects must never repeat still needs its own reconciliation. + The claim is the cache's atomic set-if-absent (``CacheService.claim``), so two replicas + handed the same event at the same instant cannot both win it -- with a cache they share + (Redis, or a disk cache on a shared volume). A per-pod cache deduplicates within one pod + only, and a cache that is unreachable fails open: both dispatch. A handler whose side + effects must never repeat still needs its own reconciliation. Config keys ~~~~~~~~~~~ @@ -476,17 +477,14 @@ def _claim(self, event: CloudEvent[Any], policy: IdempotencyPolicy) -> bool: if key is None: return True - cache = self.registry.cache_service - if cache.exists(key, namespace=IDEMPOTENCY_CACHE_NAMESPACE): - return False - - cache.set( + # One atomic set-if-absent, not exists() then set(): between those two calls a second + # replica handed the same event passes the check too, and both dispatch. + return self.registry.cache_service.claim( key, {"seen_at": time.time(), "event_type": event.type}, namespace=IDEMPOTENCY_CACHE_NAMESPACE, ttl=policy.ttl, ) - return True def release(self, event: CloudEvent[Any]) -> None: """Drop this event's dedup marker after a failure that happened after a successful dispatch. diff --git a/tests/unit/agents/handler/test_handler_chain.py b/tests/unit/agents/handler/test_handler_chain.py index ca67b6a5..2967245c 100644 --- a/tests/unit/agents/handler/test_handler_chain.py +++ b/tests/unit/agents/handler/test_handler_chain.py @@ -159,6 +159,12 @@ def set(self, key: Any, value: Any, namespace: str = "default", ttl: int | None def delete(self, key: Any, namespace: str = "default") -> bool: return self.store.pop(self._key(key), None) is not None + def claim(self, key: Any, value: Any, namespace: str = "default", ttl: int | None = None) -> bool: + if self.exists(key, namespace): + return False + self.set(key, value, namespace=namespace, ttl=ttl) + return True + def _enable_dedup(mock_config: MagicMock, mock_registry: MagicMock, ttl: int = 60) -> _StubCache: """Turn dedup on with a working cache, and return that cache.""" @@ -197,6 +203,29 @@ async def can_handle_event(self, event, context): class TestIdempotencyEnabled: + async def test_the_claim_is_one_atomic_call( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + """#6 -- exists() then set() let two replicas both pass; the atomic claim decides alone. + + Simulates the race window: exists() still says "absent", but another replica's claim won. + """ + cache = _enable_dedup(mock_config, mock_registry) + cache.exists = lambda key, namespace="default": False # type: ignore[method-assign] + cache.claim = lambda key, value, namespace="default", ttl=None: False # type: ignore[method-assign] + seen: list[str] = [] + + class Counting(StubHandler): + async def can_handle_event(self, event, context): + seen.append(event.id) + return False + + _wire_handlers(mock_registry, [Counting()]) + + await chain.process(cloud_event, {}) + + assert seen == [] + async def test_release_after_a_successful_dispatch_lets_the_redelivery_run( self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent ) -> None: From 46ac4c42ec78ee5cfa60fef41573e82af5fb005f Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 17:33:07 +0200 Subject: [PATCH 051/133] fix(agent): pass the configured result and deps types to the agent with_result_type() and with_deps_type() stored their types and build() never passed them to AgentRuntime, so a structured-output agent returned str. They now reach the agent as output_type and deps_type; a type given to build() as well is refused. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 4 ++ ...26-08-28-multi-agent-grouping-changelog.md | 17 +++++++++ src/blueprint/agents/agent/agent_builder.py | 21 +++++++++-- tests/unit/agents/agent/test_agent_builder.py | 37 +++++++++++++++++++ 4 files changed, 76 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b4e2ad4b..9daa94ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,10 @@ ### Fixed +- **`AgentBuilder.with_result_type()` and `with_deps_type()` take effect.** Both were stored and + never passed to the agent, so a structured-output agent returned plain `str` and the documented + `result.output.` failed. They are now passed as `output_type` and `deps_type`. Giving the + same value to `build()` as a keyword as well is refused. - **Event deduplication claims atomically.** The handler chain checked for the marker with `exists()` and then wrote it with `set()`, so two replicas handed the same event at the same moment both passed the check and both dispatched. It now uses the cache's atomic `claim()`, which already diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index daf3adc5..dd458446 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7574,6 +7574,23 @@ Guarded by `test_the_claim_is_one_atomic_call` in `test_handler_chain.py`, which window (`exists()` says absent, `claim()` says taken) and fails against the previous code. The stub cache in that file gained `claim()`. +### Structured output and deps types reach the agent (#2) + +**Verified.** `AgentBuilder.with_result_type()` and `with_deps_type()` set `_result_type` and +`_deps_type`; `build()` constructed `AgentRuntime(system_prompt=..., tools=..., **kwargs)` with +neither, and `_result_type` appeared only in a log line. `components/agents.md` documents +`result.output.`, which failed on the `str` the agent actually returned. The only working +route was `build(output_type=X)` through the kwargs check. + +**Change, in `build()`:** each configured type is put into the agent kwargs (`output_type`, +`deps_type`); a type given both ways raises `ValueError`. Unset now means `None` rather than the +`BaseModel` / `type(None)` placeholders, so pydantic-ai's defaults apply untouched. The build log +says `str (default)` when no result type was set. + +Guarded by `TestStructuredOutputReachesTheAgent` in `test_agent_builder.py`: three of its five +cases fail against the previous code (the other two check that unset changes nothing and that the +kwargs route still works). + --- ## Open points diff --git a/src/blueprint/agents/agent/agent_builder.py b/src/blueprint/agents/agent/agent_builder.py index 9eea8bdf..f6ab4996 100644 --- a/src/blueprint/agents/agent/agent_builder.py +++ b/src/blueprint/agents/agent/agent_builder.py @@ -87,8 +87,9 @@ def __init__( self._model_name_override: str = "" self._system_prompt: str | None = None self._tools: list[Tool] = [] - self._result_type: type[BaseModel] = BaseModel - self._deps_type: type[Any] = type(None) + # None means "not configured": pydantic-ai's own defaults apply (str output, no deps). + self._result_type: type[Any] | None = None + self._deps_type: type[Any] | None = None self._meter = meter self._package_root = Path(package_root) if package_root else "" self._metrics_enabled: bool = True @@ -375,6 +376,20 @@ def build(self, config: Config | None = None, **kwargs: Any) -> AgentRuntime: if kwarg not in allowed: raise ValueError(f"Unexpected keyword argument for Agent: {kwarg}") + # The structured output and deps types reach the agent. with_result_type() and + # with_deps_type() used to store them and nothing else -- AgentRuntime never received + # either, so a documented `result.output.` was a str and failed at the attribute. + # Given both ways, the builder refuses rather than silently picking one. + for builder_value, agent_kwarg, method in ( + (self._result_type, "output_type", "with_result_type"), + (self._deps_type, "deps_type", "with_deps_type"), + ): + if builder_value is None: + continue + if agent_kwarg in kwargs: + raise ValueError(f"'{agent_kwarg}' is given to build() and set by {method}(); set it one way only.") + kwargs[agent_kwarg] = builder_value + # AgentRuntime takes its registry name as a required argument and nothing was passing # one: AppBuilder.with_agent(agent, name=...) keeps that name on the *declaration* and # assigns it after construction, so this call raised TypeError before it could get @@ -404,7 +419,7 @@ def build(self, config: Config | None = None, **kwargs: Any) -> AgentRuntime: self._ai_config.provider, self._ai_config.model_name, len(self._tools), - self._result_type.__name__, + self._result_type.__name__ if self._result_type is not None else "str (default)", ) return runtime diff --git a/tests/unit/agents/agent/test_agent_builder.py b/tests/unit/agents/agent/test_agent_builder.py index 35c324af..35a54a6c 100644 --- a/tests/unit/agents/agent/test_agent_builder.py +++ b/tests/unit/agents/agent/test_agent_builder.py @@ -307,3 +307,40 @@ def test_build_raises_for_unknown_kwarg(self, builder_with_model: AgentBuilder) ): with pytest.raises(ValueError, match="Unexpected keyword argument"): builder_with_model.build(completely_unknown_kwarg="foo") + + +class TestStructuredOutputReachesTheAgent: + """#2 -- with_result_type / with_deps_type were stored and never passed to AgentRuntime.""" + + class Summary(BaseModel): + text: str + + @staticmethod + def _build(builder: AgentBuilder, **kwargs: object) -> MagicMock: + builder.with_model_from_config().with_system_prompt("system") + with patch.dict("blueprint.agents.agent.agent_builder._CLIENT_MAP", {"openai": MagicMock(return_value=MagicMock())}): + with patch("blueprint.agents.agent.agent_builder.PromptLoader.load_prompt", return_value="prompt"): + with patch("blueprint.agents.agent.agent_builder.AgentRuntime") as runtime: + builder.build(**kwargs) + return runtime + + def test_the_result_type_is_the_output_type(self, builder: AgentBuilder, mock_registry: MagicMock) -> None: + runtime = self._build(builder.with_result_type(self.Summary)) + assert runtime.call_args.kwargs["output_type"] is self.Summary + + def test_the_deps_type_is_passed(self, builder: AgentBuilder, mock_registry: MagicMock) -> None: + runtime = self._build(builder.with_deps_type(dict)) + assert runtime.call_args.kwargs["deps_type"] is dict + + def test_unset_leaves_pydantic_ai_defaults(self, builder: AgentBuilder, mock_registry: MagicMock) -> None: + runtime = self._build(builder) + assert "output_type" not in runtime.call_args.kwargs + assert "deps_type" not in runtime.call_args.kwargs + + def test_set_both_ways_is_refused(self, builder: AgentBuilder, mock_registry: MagicMock) -> None: + with pytest.raises(ValueError, match="set it one way only"): + self._build(builder.with_result_type(self.Summary), output_type=str) + + def test_the_old_kwarg_route_still_works(self, builder: AgentBuilder, mock_registry: MagicMock) -> None: + runtime = self._build(builder, output_type=self.Summary) + assert runtime.call_args.kwargs["output_type"] is self.Summary From 5259e4f369d366c94329a3a8f2e1508bac2b8a9c Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 17:47:21 +0200 Subject: [PATCH 052/133] fix(group): build each agent from its own copy of a shared AgentBuilder A group replays one declaration once per agent, and AgentBuilder.build() is single-use, so the second agent sharing a declaration failed with "already been called". AppBuilder._construct now builds from a shallow copy of the recorded builder, and build() gives each agent its own tool list. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 4 ++ ...26-08-28-multi-agent-grouping-changelog.md | 22 ++++++++++ src/blueprint/agents/agent/agent_builder.py | 3 +- src/blueprint/agents/app_builder.py | 12 +++++- tests/unit/agents/test_agent_group.py | 40 +++++++++++++++++++ 5 files changed, 79 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9daa94ae..cbd3ce72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,10 @@ ### Fixed +- **One declaration with an `AgentBuilder` can serve several agents of a group.** A group replays + a declaration once per agent, and `AgentBuilder.build()` is single-use, so the second agent failed + with "AgentBuilder.build() has already been called". Each agent now builds from its own copy of + the builder, with its own tool list. - **`AgentBuilder.with_result_type()` and `with_deps_type()` take effect.** Both were stored and never passed to the agent, so a structured-output agent returned plain `str` and the documented `result.output.` failed. They are now passed as `output_type` and `deps_type`. Giving the diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index dd458446..946c43bf 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7591,6 +7591,28 @@ Guarded by `TestStructuredOutputReachesTheAgent` in `test_agent_builder.py`: thr cases fail against the previous code (the other two check that unset changes nothing and that the kwargs route still works). +### One `AgentBuilder` declaration serves several agents (#10) + +**Verified by reproduction** (the list marked it unverified): `AgentGroup("pair", {"order": decl, +"billing": decl})` with `decl = AppBuilder().with_agent(AgentBuilder(...))` raised +`RuntimeError: AgentBuilder.build() has already been called` for the second agent, through the real +`build()`. `AgentGroup`'s own docstring calls one declaration serving several agents the group's +central property; no test covered it with an agent. + +**Change.** `AppBuilder._construct` builds from `copy.copy(declaration.target)` instead of the +recorded builder. The builder is a recipe; `build()` stores what it resolved on the builder, which +is why it is single-use, and a copy per agent keeps that guard for direct use while letting a group +build the recipe once per agent. The recorded builder stays unbuilt. `AgentBuilder.build()` now +hands `list(self._tools)` to the runtime, so copies of one builder do not give two agents one tool +list. + +Not a conflict with `_refuse_state_shared_between_agents`, which refuses *user* objects passed as +arguments rather than copying them: the builder is the framework's own declaration type, and copying +it is the framework's decision. + +Guarded by `TestOneAgentBuilderServesSeveralAgents` in `test_agent_group.py` (3 cases, all failing +against the previous code). + --- ## Open points diff --git a/src/blueprint/agents/agent/agent_builder.py b/src/blueprint/agents/agent/agent_builder.py index f6ab4996..7ebd4fe3 100644 --- a/src/blueprint/agents/agent/agent_builder.py +++ b/src/blueprint/agents/agent/agent_builder.py @@ -402,7 +402,8 @@ def build(self, config: Config | None = None, **kwargs: Any) -> AgentRuntime: kwargs.setdefault("name", self._runtime_name) runtime = AgentRuntime( system_prompt=self._system_prompt, - tools=self._tools if self._tools else [], + # A new list per agent: copies of one builder share it, and each agent owns its tools. + tools=list(self._tools), **kwargs, ) runtime._ai_client = self._ai_client diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index 3a182909..a0878ab7 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -2,6 +2,7 @@ import asyncio import contextlib +import copy import logging import signal from collections.abc import AsyncIterator, Callable, Mapping @@ -641,6 +642,14 @@ def _construct(self, declaration: Declaration, config: Config) -> Any: read from its own section rather than from the root or from a neighbour's. That is the whole of D6, and it is why this method takes ``config`` at all. + **Each agent builds from its own copy of the builder.** A group replays one declaration + once per agent -- the same ``AppBuilder`` named twice in the map -- and + ``AgentBuilder.build`` is single-use, because it stores what it resolved (the AI config, + the client, the prompt) on the builder. Building the recorded builder itself therefore + raised "already been called" for the second agent. The builder is the recipe, not the + agent, so a shallow copy per build is exactly "one declaration, several agents"; the + recorded builder stays unbuilt, and so does the single-use guard for direct use. + Args: declaration: The recorded call to replay. config: The application's configuration, scoped per declaration as needed. @@ -652,7 +661,8 @@ def _construct(self, declaration: Declaration, config: Config) -> Any: instance = declaration.target elif isinstance(declaration.target, AgentBuilder): with construction_scope(declaration.namespace): - instance = declaration.target.build(config.for_namespace(declaration.namespace), **declaration.kwargs) + recipe = copy.copy(declaration.target) + instance = recipe.build(config.for_namespace(declaration.namespace), **declaration.kwargs) else: with construction_scope(declaration.namespace): instance = declaration.target(**declaration.kwargs) diff --git a/tests/unit/agents/test_agent_group.py b/tests/unit/agents/test_agent_group.py index 1c91e75a..5424d917 100644 --- a/tests/unit/agents/test_agent_group.py +++ b/tests/unit/agents/test_agent_group.py @@ -24,6 +24,7 @@ import pytest +from blueprint.agents.agent.agent_builder import AgentBuilder from blueprint.agents.agent_group import AgentGroup from blueprint.agents.app_builder import AppBuilder from blueprint.agents.component.component import Component @@ -559,3 +560,42 @@ def test_a_group_that_was_given_none_merges_nothing(self, config: Config) -> Non group.assemble(config) assert group.settings == {} + + +class TestOneAgentBuilderServesSeveralAgents: + """#10 -- AgentBuilder.build() is single-use, and a group replays one declaration per agent.""" + + @staticmethod + def _assemble(config: Config, declaration: AppBuilder, names: tuple[str, ...]) -> list[dict[str, Any]]: + built: list[dict[str, Any]] = [] + + def _runtime(**kwargs: Any) -> MagicMock: + built.append(kwargs) + return MagicMock(name=kwargs["name"]) + + ai = MagicMock(model_name="m", provider="openai", max_tokens=None, temperature=None) + with ( + patch.object(type(config), "get_ai_config", return_value=ai), + patch.dict("blueprint.agents.agent.agent_builder._CLIENT_MAP", {"openai": MagicMock(return_value=MagicMock())}), + patch("blueprint.agents.agent.agent_builder.PromptLoader.load_prompt", return_value="prompt"), + patch("blueprint.agents.agent.agent_builder.AgentRuntime", side_effect=_runtime), + ): + AgentGroup("pair", dict.fromkeys(names, declaration)).assemble(config) + return built + + def test_each_agent_gets_its_own_build(self, config: Config) -> None: + agent = AgentBuilder(runtime_name="assistant").with_model_from_config().with_system_prompt("system") + built = self._assemble(config, AppBuilder().with_agent(agent), ("order", "billing")) + assert len(built) == 2 + + def test_the_recorded_builder_stays_unbuilt(self, config: Config) -> None: + agent = AgentBuilder(runtime_name="assistant").with_model_from_config().with_system_prompt("system") + self._assemble(config, AppBuilder().with_agent(agent), ("order", "billing")) + assert agent._built is False + + def test_the_agents_do_not_share_a_tool_list(self, config: Config) -> None: + agent = AgentBuilder(runtime_name="assistant").with_model_from_config().with_system_prompt("system") + agent.with_tool("lookup", lambda: "x") + built = self._assemble(config, AppBuilder().with_agent(agent), ("order", "billing")) + assert built[0]["tools"] is not built[1]["tools"] + assert built[0]["tools"] == built[1]["tools"] From 191d3940adb998338cd02eb1394c9b0949552a88 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 17:53:07 +0200 Subject: [PATCH 053/133] fix(clients): give the vLLM timeout its own key, and send the Dapr routing key as metadata VLLMClient took its HTTP timeout from model_max_tokens, so 4096 tokens meant 68 minutes. New key model_timeout (default 60 for vLLM; passed to the OpenAI client only when set). DaprClient sent metadata.routingKey as an HTTP header, which Dapr's publish API does not read; it is now a query parameter. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 5 +++++ ...26-08-28-multi-agent-grouping-changelog.md | 16 ++++++++++++++ .../docs/reference/configuration-keys.md | 1 + .../agents/clients/ai/openai_client.py | 9 ++++++-- .../agents/clients/ai/vllm_client.py | 8 ++++++- .../agents/clients/io/dapr_client.py | 8 ++++--- src/blueprint/agents/config/config.py | 1 + src/blueprint/agents/models/config.py | 1 + .../agents/clients/ai/test_openai_client.py | 9 +++++++- .../agents/clients/ai/test_vllm_client.py | 21 +++++++++++++++++++ .../agents/clients/io/test_dapr_client.py | 13 ++++++------ 11 files changed, 79 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cbd3ce72..cca76f04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,11 @@ ### Fixed +- **The vLLM request timeout has its own key.** It was taken from `model_max_tokens`, so 4096 + tokens meant a 68-minute HTTP timeout and 5 tokens a 5-second one. `model_timeout` (seconds, + default 60 for vLLM) sets it now, and applies to the OpenAI client too when set. +- **The Dapr routing key reaches the sidecar.** It was sent as an HTTP header, which Dapr's publish + API does not read; it is now the `metadata.routingKey` query parameter. - **One declaration with an `AgentBuilder` can serve several agents of a group.** A group replays a declaration once per agent, and `AgentBuilder.build()` is single-use, so the second agent failed with "AgentBuilder.build() has already been called". Each agent now builds from its own copy of diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 946c43bf..6f3d4dbf 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7613,6 +7613,22 @@ it is the framework's decision. Guarded by `TestOneAgentBuilderServesSeveralAgents` in `test_agent_group.py` (3 cases, all failing against the previous code). +### vLLM timeout and Dapr routing key (#7, #8) + +- **#7, verified.** `VLLMClient.create_model` passed `timeout=ai_config.max_tokens or 60` to + `AsyncOpenAI`. New key `model_timeout` (resolved per runtime like the other `model_*` keys) -> + `AIConfig.timeout` (`gt=0`, so a non-positive value is a validation error), and the vLLM client + uses it with a 60 s default (`DEFAULT_VLLM_TIMEOUT`). The OpenAI client passes it only when set, + so its SDK default is otherwise unchanged. +- **#8, checked against Dapr's publish API**, which reads metadata from query parameters prefixed + `metadata.`: `DaprClient.publish` put `metadata.routingKey` in the headers, where the sidecar + ignores it. It is now sent as `params`. Not exercised against a running sidecar here; Dapr is not + used by the project this round serves. + +Guarded by `TestTheRequestTimeout` (`test_vllm_client.py`) and the two routing-key cases in +`test_dapr_client.py`, which replace the two that asserted the header; four cases fail against the +previous code. + --- ## Open points diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 3f43ae72..f1b38f2a 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -163,6 +163,7 @@ Each named runtime defines model provider settings. The `default` runtime is use | `model_api_key` | `str` | -- | API key for the model provider. Can also be set via environment variable. | | `model_base_url` | `str` | -- | Base URL for the model API. Required for `"vllm"` and custom OpenAI-compatible endpoints. | | `model_max_tokens` | `int` | -- | Maximum number of tokens in the model response. | +| `model_timeout` | `float` | `60` for `"vllm"`, the SDK's default for `"openai"` | HTTP timeout per model request, in seconds. Must be positive. Settable per runtime like the other `model_*` keys. | | `model_temperature` | `float` | -- | Sampling temperature. Lower values produce more deterministic output. | | `concurrent_requests` | `int` | -- | Maximum number of concurrent requests to the model provider. | diff --git a/src/blueprint/agents/clients/ai/openai_client.py b/src/blueprint/agents/clients/ai/openai_client.py index 50b00aca..6d3f339e 100644 --- a/src/blueprint/agents/clients/ai/openai_client.py +++ b/src/blueprint/agents/clients/ai/openai_client.py @@ -3,7 +3,7 @@ import logging from typing import Any -from openai import AsyncOpenAI +from openai import NOT_GIVEN, AsyncOpenAI from pydantic_ai.models import Model from pydantic_ai.models.openai import OpenAIResponsesModel, OpenAIResponsesModelSettings from pydantic_ai.providers.openai import OpenAIProvider @@ -42,7 +42,12 @@ def create_model(self) -> Model: raise RuntimeError("Model already created") ai_config = self.config.get_ai_config(self._runtime_name) - self._client = AsyncOpenAI(max_retries=3, api_key=ai_config.api_key) + # model_timeout applies here too when set; otherwise the SDK's own default stands. + self._client = AsyncOpenAI( + max_retries=3, + api_key=ai_config.api_key, + timeout=ai_config.timeout if ai_config.timeout is not None else NOT_GIVEN, + ) settings = OpenAIResponsesModelSettings(**ai_config.model_settings) # type: ignore[typeddict-item] provider = OpenAIProvider(openai_client=self._client) self._model = OpenAIResponsesModel( diff --git a/src/blueprint/agents/clients/ai/vllm_client.py b/src/blueprint/agents/clients/ai/vllm_client.py index 005a4efe..ec461106 100644 --- a/src/blueprint/agents/clients/ai/vllm_client.py +++ b/src/blueprint/agents/clients/ai/vllm_client.py @@ -24,6 +24,10 @@ ) +DEFAULT_VLLM_TIMEOUT = 60.0 +"""Seconds per model request when ``model_timeout`` is not set.""" + + class VLLMClient(AIClientBase): """VLLM client for AI model interactions (OpenAI-compatible API).""" @@ -54,7 +58,9 @@ def create_model(self) -> Model: max_retries=3, base_url=ai_config.base_url, api_key=ai_config.api_key, - timeout=ai_config.max_tokens if ai_config.max_tokens else 60, + # Its own key. It used to be max_tokens -- a token count read as seconds, so + # 4096 tokens meant a 68-minute timeout and 5 tokens a 5-second one. + timeout=ai_config.timeout or DEFAULT_VLLM_TIMEOUT, ) provider = OpenAIProvider(openai_client=self._client) self._model = OpenAIChatModel( diff --git a/src/blueprint/agents/clients/io/dapr_client.py b/src/blueprint/agents/clients/io/dapr_client.py index 2ce3697a..2dab31ae 100644 --- a/src/blueprint/agents/clients/io/dapr_client.py +++ b/src/blueprint/agents/clients/io/dapr_client.py @@ -126,12 +126,14 @@ async def publish( effective_pubsub = pubsub_name or self.config.get("dapr_pubsub_name", "pubsub") url = f"{dapr_url}/v1.0/publish/{effective_pubsub}/{topic}" headers = {"Content-Type": "application/cloudevents+json"} - if routing_key: - headers["metadata.routingKey"] = routing_key + # Dapr's publish API takes metadata as query parameters prefixed with "metadata." -- it + # was sent as an HTTP header, which the sidecar does not read, so the routing key was + # silently dropped. + params = {"metadata.routingKey": routing_key} if routing_key else {} data = json.dumps(dict(event)) try: - response = await client.post(url, content=data, headers=headers) + response = await client.post(url, content=data, headers=headers, params=params) response.raise_for_status() logger.debug("Published event to Dapr topic '%s': %s", topic, event.id) except Exception as e: diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index 71c1dad3..1646f6f4 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -1125,6 +1125,7 @@ def get_with_fallback(key: str) -> Any: base_url=base_url, model_settings=model_settings, max_tokens=get_with_fallback("model_max_tokens"), + timeout=get_with_fallback("model_timeout"), temperature=get_with_fallback("model_temperature"), concurrency_limit=get_with_fallback("concurrent_requests"), usage_limits=UsageLimits( diff --git a/src/blueprint/agents/models/config.py b/src/blueprint/agents/models/config.py index 084955e2..a55a081d 100644 --- a/src/blueprint/agents/models/config.py +++ b/src/blueprint/agents/models/config.py @@ -125,6 +125,7 @@ class AIConfig(BaseModel): api_key: str | None = Field(None, description="API key") base_url: str | None = Field(None, description="Base URL for API") max_tokens: int | None = Field(None, description="Max tokens per request") + timeout: float | None = Field(None, gt=0, description="HTTP timeout per model request, in seconds") temperature: float | None = Field(None, description="Temperature for generation") concurrency_limit: int | None = Field(None, description="Max concurrent requests") usage_limits: UsageLimits = Field(default_factory=UsageLimits, description="Usage limits") diff --git a/tests/unit/agents/clients/ai/test_openai_client.py b/tests/unit/agents/clients/ai/test_openai_client.py index e8e999b8..1eb8b9d4 100644 --- a/tests/unit/agents/clients/ai/test_openai_client.py +++ b/tests/unit/agents/clients/ai/test_openai_client.py @@ -3,6 +3,7 @@ from unittest.mock import AsyncMock, MagicMock import pytest +from openai import NOT_GIVEN from blueprint.agents.clients.ai.openai_client import OpenAIClient @@ -49,7 +50,13 @@ def test_create_model_returns_model_instance(self, openai_client: OpenAIClient, def test_create_model_builds_async_openai_with_api_key(self, openai_client: OpenAIClient, patch_openai_deps: dict) -> None: openai_client.create_model() - patch_openai_deps["async_openai"].assert_called_once_with(max_retries=3, api_key="test-api-key") + patch_openai_deps["async_openai"].assert_called_once_with(max_retries=3, api_key="test-api-key", timeout=NOT_GIVEN) + + def test_model_timeout_is_passed_when_set(self, openai_client: OpenAIClient, patch_openai_deps: dict, mock_ai_config) -> None: + """#7 -- model_timeout applies to the OpenAI client too; unset leaves the SDK default.""" + mock_ai_config.timeout = 30.0 + openai_client.create_model() + assert patch_openai_deps["async_openai"].call_args.kwargs["timeout"] == 30.0 def test_create_model_sets_client(self, openai_client: OpenAIClient, patch_openai_deps: dict) -> None: # noqa: ARG002 openai_client.create_model() diff --git a/tests/unit/agents/clients/ai/test_vllm_client.py b/tests/unit/agents/clients/ai/test_vllm_client.py index a4515534..829b6c84 100644 --- a/tests/unit/agents/clients/ai/test_vllm_client.py +++ b/tests/unit/agents/clients/ai/test_vllm_client.py @@ -104,3 +104,24 @@ async def test_unhealthy_on_connection_error(self, vllm_client: VLLMClient) -> N assert result.status == "unhealthy" assert "timeout" in result.message + + +class TestTheRequestTimeout: + """#7 -- the HTTP timeout came from max_tokens: 4096 tokens meant 68 minutes.""" + + def test_max_tokens_no_longer_sets_it(self, vllm_client: VLLMClient, patch_vllm_deps: dict) -> None: + vllm_client.create_model() + assert patch_vllm_deps["async_openai"].call_args.kwargs["timeout"] == 60.0 + + def test_model_timeout_sets_it(self, vllm_client: VLLMClient, patch_vllm_deps: dict, mock_ai_config) -> None: + mock_ai_config.timeout = 12.5 + vllm_client.create_model() + assert patch_vllm_deps["async_openai"].call_args.kwargs["timeout"] == 12.5 + + def test_a_non_positive_timeout_is_refused(self) -> None: + from pydantic import ValidationError + + from blueprint.agents.models.config import AIConfig + + with pytest.raises(ValidationError): + AIConfig(timeout=0) diff --git a/tests/unit/agents/clients/io/test_dapr_client.py b/tests/unit/agents/clients/io/test_dapr_client.py index 0bc94ca5..a7f7a2b0 100644 --- a/tests/unit/agents/clients/io/test_dapr_client.py +++ b/tests/unit/agents/clients/io/test_dapr_client.py @@ -103,25 +103,26 @@ async def test_publish_serialises_event_as_json( assert parsed["id"] == "test-event-id" assert parsed["type"] == "test.event" - async def test_publish_adds_routing_key_header_when_provided( + async def test_publish_sends_the_routing_key_as_a_query_parameter( self, connected_dapr_client: DaprClient, mock_httpx_client: MagicMock, cloud_event: CloudEvent, ) -> None: + """#8 -- Dapr reads publish metadata from the query string; as a header it was dropped.""" await connected_dapr_client.publish("topic", cloud_event, routing_key="rk-123") - headers = mock_httpx_client.post.call_args[1]["headers"] - assert headers["metadata.routingKey"] == "rk-123" + kwargs = mock_httpx_client.post.call_args[1] + assert kwargs["params"] == {"metadata.routingKey": "rk-123"} + assert "metadata.routingKey" not in kwargs["headers"] - async def test_publish_omits_routing_key_header_when_not_provided( + async def test_publish_omits_the_routing_key_when_not_provided( self, connected_dapr_client: DaprClient, mock_httpx_client: MagicMock, cloud_event: CloudEvent, ) -> None: await connected_dapr_client.publish("topic", cloud_event) - headers = mock_httpx_client.post.call_args[1]["headers"] - assert "metadata.routingKey" not in headers + assert mock_httpx_client.post.call_args[1]["params"] == {} async def test_publish_uses_custom_pubsub_name( self, From d52d01a52839ad906ea37d606ca8d9e884f0ada1 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 17:59:03 +0200 Subject: [PATCH 054/133] fix(rest): stop logging request bodies, and keep the caller's request id RestApiBase._process_resource logged the whole request payload at INFO; it now logs only its type. EventProcessingService.process_event replaced the request id the REST layer had created and returned as the problem details traceId; a caller's id is now kept. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 6 ++++ ...26-08-28-multi-agent-grouping-changelog.md | 15 ++++++++ src/blueprint/agents/io/api/rest_api_base.py | 4 ++- .../eventing/event_processing_service.py | 5 ++- .../unit/agents/io/api/test_rest_api_base.py | 35 ++++++++++++++++++- .../eventing/test_event_processing_service.py | 25 +++++++++++++ 6 files changed, 87 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cca76f04..6f247a6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,12 @@ ### Fixed +- **REST request bodies are no longer logged.** `RestApiBase._process_resource` put the whole + payload into the `extra` of an INFO line, so personal data and secrets in a request body reached + the logs. Only the payload's type is logged now. +- **A REST request keeps one request id.** `process_event` replaced the id the REST layer had + created, logged and returned as the RFC 7807 `traceId`, so processing ran under a second id that + matched nothing the caller saw. A caller's id is now kept. - **The vLLM request timeout has its own key.** It was taken from `model_max_tokens`, so 4096 tokens meant a 68-minute HTTP timeout and 5 tokens a 5-second one. `model_timeout` (seconds, default 60 for vLLM) sets it now, and applies to the OpenAI client too when set. diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 6f3d4dbf..df04be6f 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7629,6 +7629,21 @@ Guarded by `TestTheRequestTimeout` (`test_vllm_client.py`) and the two routing-k `test_dapr_client.py`, which replace the two that asserted the header; four cases fail against the previous code. +### REST payload logging and request id (#12, #13) + +- **#12, verified.** `RestApiBase._process_resource` logged `extra={"payload": payload, ...}` at + INFO -- the full request body, against the org's PII rule and the repo's rule that sensitive data + is not logged at any level. Replaced by `payload_type`. +- **#13, verified end to end.** `_process_resource` creates a `request_id`, sets it as + `request.state.trace_id` (the problem-details `traceId`) and passes it in `context` through + `process_rest_request` to `process_event` -- which assigned `context["request_id"] = str(uuid4())` + unconditionally. It now keeps `context.get("request_id")` and only makes one when absent, so the + NATS and Dapr paths, which pass none, are unchanged. + +Guarded by `TestProcessResourceLogging` (`test_rest_api_base.py`) and `TestTheRequestIdIsKept` +(`test_event_processing_service.py`); one case of each fails against the previous code, the other +pins the part that was already right. + --- ## Open points diff --git a/src/blueprint/agents/io/api/rest_api_base.py b/src/blueprint/agents/io/api/rest_api_base.py index 94c6e650..7b68f9ff 100644 --- a/src/blueprint/agents/io/api/rest_api_base.py +++ b/src/blueprint/agents/io/api/rest_api_base.py @@ -182,7 +182,9 @@ async def _process_resource(self, request: Request, payload: Any) -> ProcessReso "path": request.url.path, "method": request.method, "client_ip": request.client.host if request.client else None, - "payload": payload, + # The type, never the body: a request body is where personal data and secrets + # arrive, and it used to be logged here in full, at INFO. + "payload_type": type(payload).__name__, }, ) diff --git a/src/blueprint/agents/services/eventing/event_processing_service.py b/src/blueprint/agents/services/eventing/event_processing_service.py index 1a942d40..24bef789 100644 --- a/src/blueprint/agents/services/eventing/event_processing_service.py +++ b/src/blueprint/agents/services/eventing/event_processing_service.py @@ -118,7 +118,10 @@ async def process_event( if context is None: context = {} - request_id = str(uuid4()) + # The caller's id if it has one. The REST path creates one, logs it and returns it as the + # RFC 7807 traceId; overwriting it here gave processing a second id that matched nothing + # the caller could see. + request_id = str(context.get("request_id") or uuid4()) context["request_id"] = request_id span = trace.get_current_span() span.set_attribute("request_id", request_id) 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 6ff56843..78960d57 100644 --- a/tests/unit/agents/io/api/test_rest_api_base.py +++ b/tests/unit/agents/io/api/test_rest_api_base.py @@ -1,6 +1,6 @@ """Unit tests for RestApiBase.""" -from unittest.mock import MagicMock +from unittest.mock import AsyncMock, MagicMock from blueprint.agents.io.api.rest_api_base import RestApiBase @@ -253,3 +253,36 @@ def test_known_status_code_returns_phrase(self) -> None: def test_unknown_status_code_returns_unknown_error(self) -> None: assert RestApiBase._resolve_status_title(999) == "Unknown Error" + + +class TestProcessResourceLogging: + """#12 -- the request body was logged in full at INFO.""" + + async def test_the_payload_is_not_logged(self, mock_config: MagicMock, mock_registry: MagicMock, caplog) -> None: + api = _MinimalApi() + service = MagicMock() + service.process_rest_request = AsyncMock(return_value=MagicMock(status="processed", message="ok", result=[])) + mock_registry.get_service.return_value = service + request = MagicMock() + request.url.path = "/process" + request.method = "POST" + secret = {"email": "person@example.invalid", "token": "YOUR_TOKEN_HERE"} + + with caplog.at_level("DEBUG"): + await api._process_resource(request, secret) + + for record in caplog.records: + assert "person@example.invalid" not in repr(record.__dict__) + assert "YOUR_TOKEN_HERE" not in repr(record.__dict__) + + async def test_the_request_id_reaches_processing(self, mock_config: MagicMock, mock_registry: MagicMock) -> None: + api = _MinimalApi() + service = MagicMock() + service.process_rest_request = AsyncMock(return_value=MagicMock(status="processed", message="ok", result=[])) + mock_registry.get_service.return_value = service + request = MagicMock() + + await api._process_resource(request, {}) + + context = service.process_rest_request.await_args.args[1] + assert context["request_id"] == request.state.trace_id 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 d62f577a..4aaf5b83 100644 --- a/tests/unit/agents/services/eventing/test_event_processing_service.py +++ b/tests/unit/agents/services/eventing/test_event_processing_service.py @@ -240,3 +240,28 @@ async def test_each_result_is_published_with_its_position( _, publisher = self._wire(event_processing_service, mock_registry, results) await event_processing_service.process_event(GenericCloudEvent(id="e1", type="t", source="s")) assert [call.kwargs["index"] for call in publisher.publish_handler_event.await_args_list] == [0, 1] + + +class TestTheRequestIdIsKept: + """#13 -- process_event replaced the caller's request_id with a new uuid4.""" + + async def test_a_callers_id_survives_processing(self, event_processing_service: EventProcessingService) -> None: + chain = MagicMock() + chain.process = AsyncMock(return_value=None) + event_processing_service._handler_chains[ROOT_NAMESPACE] = chain + context = {"request_id": "rest-123"} + + result = await event_processing_service.process_event(GenericCloudEvent(id="e1", type="t", source="s"), context) + + assert context["request_id"] == "rest-123" + assert result.request_id == "rest-123" + + async def test_without_one_an_id_is_made(self, event_processing_service: EventProcessingService) -> None: + chain = MagicMock() + chain.process = AsyncMock(return_value=None) + event_processing_service._handler_chains[ROOT_NAMESPACE] = chain + context: dict = {} + + await event_processing_service.process_event(GenericCloudEvent(id="e1", type="t", source="s"), context) + + assert context["request_id"] From 8147b60512c7d2cdfb03dbb1d6fb62a28c3d23cd Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 18:01:55 +0200 Subject: [PATCH 055/133] fix(sessions): bound the job handler's replay guard in time and size SessionsJobHandler kept every finished job's id in a set that was never pruned. RecentJobIds remembers an id for SEEN_TTL_SECONDS (3600) and at most SEEN_MAX_ENTRIES (10,000) ids, which covers the redelivery it guards against. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 3 ++ ...26-08-28-multi-agent-grouping-changelog.md | 18 +++++++ .../agents/handler/sessions_job_handler.py | 52 ++++++++++++++++++- .../handler/test_sessions_job_handler.py | 41 +++++++++++++++ 4 files changed, 112 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f247a6a..e4bee388 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,9 @@ ### Fixed +- **`SessionsJobHandler` no longer grows without bound.** Its replay guard kept every finished + job's id for the life of the process. It now remembers an id for an hour and at most 10,000 ids + (`SEEN_TTL_SECONDS`, `SEEN_MAX_ENTRIES`, overridable per subclass). - **REST request bodies are no longer logged.** `RestApiBase._process_resource` put the whole payload into the `extra` of an INFO line, so personal data and secrets in a request body reached the logs. Only the payload's type is logged now. diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index df04be6f..7650d12c 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7644,6 +7644,24 @@ Guarded by `TestProcessResourceLogging` (`test_rest_api_base.py`) and `TestTheRe (`test_event_processing_service.py`); one case of each fails against the previous code, the other pins the part that was already right. +### The sessions replay guard is bounded (#14) + +**Verified.** `SessionsJobHandler._seen` was a `set[UUID]` added to on every terminal outcome +(complete, fail, cancel) and never pruned: one UUID per finished job, for the life of the process. + +**Change.** New `RecentJobIds` in `sessions_job_handler.py`: an `OrderedDict` of id -> monotonic +time with `add()`, `__contains__` and `__len__`, evicting ids older than `ttl` and the oldest beyond +`max_entries`. `_seen` is one, sized by the class attributes `SEEN_TTL_SECONDS = 3600` and +`SEEN_MAX_ENTRIES = 10_000`. Its purpose is recognising a *redelivery*, which arrives in minutes; a +redelivery after the window is processed again, which the terminal call's retry already tolerates. +The handler's own tests use `in` and `.add()`, and pass unchanged. + +The finding also noted that this guard is per process and inconsistent with the chain's cache-based +dedup. That is true and deliberate here: the guard protects one handler instance against the +sessions bus redelivering to it; unifying it with the cache is a design change, not a fix. + +Guarded by `TestTheReplayGuardIsBounded` in `test_sessions_job_handler.py` (3 cases). + --- ## Open points diff --git a/src/blueprint/agents/handler/sessions_job_handler.py b/src/blueprint/agents/handler/sessions_job_handler.py index 5bbcb4b3..ebca5096 100644 --- a/src/blueprint/agents/handler/sessions_job_handler.py +++ b/src/blueprint/agents/handler/sessions_job_handler.py @@ -56,6 +56,7 @@ async def process(self, payload: BatchPayload, context: dict) -> BatchResult: import logging import time from abc import ABC, abstractmethod +from collections import OrderedDict from collections.abc import Awaitable, Callable from typing import Any, ClassVar from uuid import UUID @@ -73,6 +74,46 @@ async def process(self, payload: BatchPayload, context: dict) -> BatchResult: logger = logging.getLogger(__name__) +class RecentJobIds: + """The ids of recently finished jobs, forgotten after a while and capped in number. + + The replay guard needs to recognise a *redelivery* of a finished job, and a redelivery arrives + within minutes. A plain set kept every id for the life of the process -- one UUID per finished + job, never pruned -- so memory grew without bound. This keeps an id for ``ttl`` seconds and at + most ``max_entries`` ids, evicting the oldest first; a redelivery after that is processed again, + which the terminal call's retry already has to tolerate. + """ + + def __init__(self, ttl: float, max_entries: int) -> None: + self._ttl = ttl + self._max_entries = max_entries + self._added: OrderedDict[UUID, float] = OrderedDict() + + def add(self, job_id: UUID) -> None: + """Remember ``job_id`` as finished now.""" + self._evict_expired() + self._added.pop(job_id, None) + self._added[job_id] = time.monotonic() + while len(self._added) > self._max_entries: + self._added.popitem(last=False) + + def __contains__(self, job_id: object) -> bool: + self._evict_expired() + return job_id in self._added + + def __len__(self) -> int: + self._evict_expired() + return len(self._added) + + def _evict_expired(self) -> None: + cutoff = time.monotonic() - self._ttl + while self._added: + oldest = next(iter(self._added.values())) + if oldest > cutoff: + return + self._added.popitem(last=False) + + class SessionsJobHandler(EventHandlerBase, ABC): """Abstract base wrapping the sessions-service job lifecycle. @@ -123,13 +164,20 @@ def __init_subclass__(cls, **kwargs: Any) -> None: f"alias property and is silently ignored by the retry logic. Set {new_name!r} instead." ) + SEEN_TTL_SECONDS: ClassVar[float] = 3600.0 + """How long a finished job's id is remembered for recognising a redelivery.""" + + SEEN_MAX_ENTRIES: ClassVar[int] = 10_000 + """How many finished job ids are remembered at most; the oldest is forgotten first.""" + def __init__(self, priority: int = 100) -> None: super().__init__(priority=priority) self._agent_id: str | None = None # Concurrent duplicate guard; populated at entry, cleared in `finally`. self._in_flight: set[UUID] = set() - # Replay guard; populated only on a terminal outcome (complete/cancel). - self._seen: set[UUID] = set() + # Replay guard; populated only on a terminal outcome (complete/cancel). Bounded in time + # and size -- see RecentJobIds. + self._seen = RecentJobIds(ttl=self.SEEN_TTL_SECONDS, max_entries=self.SEEN_MAX_ENTRIES) async def on_startup(self) -> None: """Resolve the agent id from ``sessions_service`` config (required).""" diff --git a/tests/unit/agents/handler/test_sessions_job_handler.py b/tests/unit/agents/handler/test_sessions_job_handler.py index 8ff1a026..1df2c54c 100644 --- a/tests/unit/agents/handler/test_sessions_job_handler.py +++ b/tests/unit/agents/handler/test_sessions_job_handler.py @@ -819,3 +819,44 @@ async def boom(_p: Any, _c: Any) -> _Result: assert kwargs["error"]["message"] == "bad input" assert kwargs["error"]["code"] == "ValueError" assert job_id in handler._seen + + +class TestTheReplayGuardIsBounded: + """#14 -- the set of finished job ids grew by one UUID per job for the life of the process.""" + + def test_an_id_is_remembered(self) -> None: + from uuid import uuid4 + + from blueprint.agents.handler.sessions_job_handler import RecentJobIds + + seen = RecentJobIds(ttl=60, max_entries=10) + job = uuid4() + seen.add(job) + assert job in seen + + def test_the_oldest_is_forgotten_past_the_cap(self) -> None: + from uuid import uuid4 + + from blueprint.agents.handler.sessions_job_handler import RecentJobIds + + seen = RecentJobIds(ttl=60, max_entries=3) + jobs = [uuid4() for _ in range(5)] + for job in jobs: + seen.add(job) + assert len(seen) == 3 + assert jobs[0] not in seen and jobs[1] not in seen + assert all(job in seen for job in jobs[2:]) + + def test_an_id_is_forgotten_after_the_ttl(self, monkeypatch) -> None: + from uuid import uuid4 + + from blueprint.agents.handler import sessions_job_handler + + clock = [1000.0] + monkeypatch.setattr(sessions_job_handler.time, "monotonic", lambda: clock[0]) + seen = sessions_job_handler.RecentJobIds(ttl=60, max_entries=10) + job = uuid4() + seen.add(job) + clock[0] += 61 + assert job not in seen + assert len(seen) == 0 From 9b4560ceb174e8a33fda638c061d3fbc4e0ddd78 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 18:13:23 +0200 Subject: [PATCH 056/133] fix(generator): scaffold a project that builds, and stop contradicting the agent layout - Dockerfile: stop copying a README.md that is never generated. - settings.txt: do not choose scheduler_mode (it has no default by design), match the tick-topic comment to the code, drop an internal model host. - validate: an agent carries no agents.toml; say it belongs to the image (as a notice) instead of telling the agent to add one. - setup: a standalone agent's routes are under /api, not /api/. - generator: raise ValueError instead of sys.exit(1) on an invalid config; drop an unused template variable. - Remove the unreferenced assistant_integrations/CLAUDE.md from the package. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 8 ++ ...26-08-28-multi-agent-grouping-changelog.md | 29 ++++++ pyproject.toml | 2 +- .../assistant_integrations/CLAUDE.md | 99 ------------------- .../agent_generator/base_files/Dockerfile | 4 +- .../agent_generator/base_files/settings.txt | 18 ++-- .../agent_generator/cli/commands/setup.py | 5 +- .../agent_generator/cli/commands/validate.py | 20 ++-- .../agent_generator/generator/generator.py | 14 +-- .../cli/commands/test_validate_group_gates.py | 13 +-- .../generator/test_generated_project.py | 37 +++++++ 11 files changed, 116 insertions(+), 133 deletions(-) delete mode 100644 src/blueprint/agent_generator/assistant_integrations/CLAUDE.md diff --git a/CHANGELOG.md b/CHANGELOG.md index e4bee388..96f7d20e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,14 @@ ### Fixed +- **Scaffolding fixes.** The generated `Dockerfile` copied a `README.md` that nothing generates, so + `docker build` on a fresh project failed; the generated `settings.toml` chose `scheduler_mode = + "in_process"`, defeating its deliberate lack of a default, and carried an internal model host; + `asbs validate` told an agent to add an `agents.toml`, which an agent must not carry, and now + points at the image's map instead (as a notice); `asbs setup` said a standalone agent's routes + were under `/api/`; the generator called `sys.exit(1)` from library code on an invalid + config and now raises `ValueError`. The unreferenced `assistant_integrations/CLAUDE.md` is no + longer packaged. - **`SessionsJobHandler` no longer grows without bound.** Its replay guard kept every finished job's id for the life of the process. It now remembers an id for an hour and at most 10,000 ids (`SEEN_TTL_SECONDS`, `SEEN_MAX_ENTRIES`, overridable per subclass). diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 7650d12c..5222a5b0 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7662,6 +7662,35 @@ sessions bus redelivering to it; unifying it with the cache is a design change, Guarded by `TestTheReplayGuardIsBounded` in `test_sessions_job_handler.py` (3 cases). +### Generator and CLI (#11 and the low-priority generator findings) + +All verified before changing: + +- **`base_files/Dockerfile`** copied `pyproject.toml README.md`; no `README.md` is generated and the + generated `pyproject.toml` declares no readme. Now copies the manifest only. +- **`asbs validate`** warned an agent directory that it had no `agents.toml` and told it to add + one -- the opposite of `layout.py`, `asbs setup` and the migration guide, which all say the map + belongs to the image. `NO_AGENT_MAP_WARNING` became `NO_AGENT_MAP_NOTICE`: a notice that the map + belongs to the image, pointing at `asbs validate --group` and the migration guide. The test that + pinned the old advice (`test_a_project_without_one_is_told_the_three_changes`) now pins the new. +- **`asbs setup`** printed "this agent's routes are under /api/{namespace}"; a standalone + `create_app` builds at the root. It now names both. +- **`base_files/settings.txt`**: `scheduler_mode = "in_process"` was active, choosing the value the + framework deliberately has no default for; both values are now commented out. Its tick-topic + comment said `.scheduler...`; the code derives `.scheduler...` and falls back to + `app_name` only at the root. `model_base_url` named an internal host; now a placeholder. +- **`generator.py`** passed an `agent_namespace` template variable the Dockerfile has no token for + (removed, with its now unused import), and `load_config` called `sys.exit(1)` on an invalid + config; it raises `ValueError` after the `try`, and the CLI entry point still turns it into exit + status 1. +- **`assistant_integrations/CLAUDE.md`** was packaged (`pyproject.toml` package-data) and read by + nothing. Removed with its package-data entry. + +Guarded by `test_every_file_the_dockerfile_copies_is_generated` (checks every build-context +`COPY` source exists in a generated project), `TestTheGeneratedSettings` and +`TestAnInvalidGeneratorConfig` in `test_generated_project.py`, all four failing against the previous +templates and code; and the rewritten validate case in `test_validate_group_gates.py`. + --- ## Open points diff --git a/pyproject.toml b/pyproject.toml index 6efb352c..aa1ec0c6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -108,7 +108,7 @@ packages = [ [tool.setuptools.package-data] "blueprint.agents" = ["py.typed"] -"blueprint.agent_generator" = ["base_files/**/*", "assistant_integrations/**/*", "claude_docs/**/*", "docs/**/*"] +"blueprint.agent_generator" = ["base_files/**/*", "claude_docs/**/*", "docs/**/*"] [tool.black] line-length = 140 diff --git a/src/blueprint/agent_generator/assistant_integrations/CLAUDE.md b/src/blueprint/agent_generator/assistant_integrations/CLAUDE.md deleted file mode 100644 index b3258c65..00000000 --- a/src/blueprint/agent_generator/assistant_integrations/CLAUDE.md +++ /dev/null @@ -1,99 +0,0 @@ -# Claude Code Guidelines - -This file is read automatically by Claude Code at the start of every session. - -## Framework - -This project uses the **Blueprint Agents** framework. All application components extend -base classes from the framework: - -| Class | Import | Purpose | -|---|---|---| -| `EventHandlerBase` | `blueprint.agents.handler` | CloudEvent processing (chain-of-responsibility) | -| `ServiceBase` | `blueprint.agents.services` | Domain logic, state, orchestration | -| `AgentRuntime` | via `AgentBuilder` from `blueprint.agents` | LLM agents (wraps pydantic-ai) | -| `RestApiBase` | `blueprint.agents.io.api` | HTTP endpoints via FastAPI | -| `SchedulerBase` | `blueprint.agents.io.api.scheduling` | Background cron tasks | - -## Key Architecture Rules - -- **Never access `self.registry` or `self.config` in `__init__`** — they are not linked until after construction. Always resolve dependencies in `on_startup()`. -- **Register dependencies before dependents** — services before handlers/agents that use them. -- **`main.py` is wiring only** — no business logic. -- **Services contain ALL business logic** — handlers and APIs are thin delegation layers with one method per responsibility. -- No global state, no module-level component instances. - -```python -# Correct — resolve in on_startup() -class MyHandler(EventHandlerBase): - async def on_startup(self) -> None: - self._service = self.registry.get_service(MyService) - - async def handle_event(self, event, context): - payload = self.extract_payload(event, MyModel) # Typed extraction with validation - return await self._service.process(payload) -``` - -## Code Style - -- Complete type hints on every method signature -- All I/O must be `async` / `await` — never blocking I/O in async code -- Every public method needs a docstring (one-liner is fine for simple methods) -- Use `%s`-style args in log calls, not f-strings (deferred formatting) -- Validate all external input with Pydantic at system boundaries -- Never hardcode secrets — use environment variables via `.secrets.toml` -- **No `assert` statements in production code** — `assert` is only permitted in test files (`tests/`) -- **All imports at the top of the file** — never inside methods, functions, or classes - -## Agent Prompts - -- **System prompt** (`system.prompt`): Static context — no dynamic inputs. Loaded by `AgentBuilder.with_system_prompt()`. -- **Instruction prompt** (`instruction.prompt`): Contains `{placeholders}` for dynamic inputs. -- Files go in `src/prompts/` as `.prompt` files - -**Always use `agent.get_prompt().format()` for user prompts with variable inputs:** - -```python -prompt = self._agent.get_prompt("instruction").format( - ticket_text=ticket_text, - customer_tier=customer_tier, -) -result = await self._agent.run(user_prompt=prompt) -``` - -## Error Handling - -- Define domain-specific exceptions when callers need to catch them selectively -- Always use context managers (`async with`) for files, HTTP clients, DB connections -- Set explicit timeouts on all external calls -- Never log passwords, tokens, or API keys - -## Testing - -- Test files: `test_.py` | Classes: `Test` | Methods: `test__` -- Use `MagicMock(spec=...)` for sync deps, `AsyncMock()` for async deps -- Shared fixtures in `conftest.py` -- `asyncio_mode = auto` in `pytest.ini` - -## Project Structure - -``` -src/ -├── main.py # AppBuilder wiring only -├── api/ # RestApiBase subclasses -├── handlers/ # EventHandlerBase subclasses -├── services/ # ServiceBase subclasses -├── schedulers/ # SchedulerBase subclasses -├── agents/ # AgentBuilder setup code -├── models/ # Pydantic models -└── prompts/ # .prompt files (system + instruction) -``` - -## Running the Service - -```bash -pip install -e . -uvicorn src.main:app --reload # development -pytest tests/ # run tests -asbs validate # validate project structure -``` diff --git a/src/blueprint/agent_generator/base_files/Dockerfile b/src/blueprint/agent_generator/base_files/Dockerfile index 7fe38673..9f32a2ed 100644 --- a/src/blueprint/agent_generator/base_files/Dockerfile +++ b/src/blueprint/agent_generator/base_files/Dockerfile @@ -11,7 +11,9 @@ WORKDIR /app # Layer 1: Copy dependency manifests and install dependencies # This layer caches if only code changes, not deps -COPY pyproject.toml README.md ./ +# Only the manifest: the generated pyproject.toml declares no readme, and no README.md is +# generated, so copying one failed a fresh `docker build` at this line. +COPY pyproject.toml ./ RUN uv pip install --system --no-cache \ --upgrade pip setuptools wheel && \ diff --git a/src/blueprint/agent_generator/base_files/settings.txt b/src/blueprint/agent_generator/base_files/settings.txt index 45023324..28008ef5 100644 --- a/src/blueprint/agent_generator/base_files/settings.txt +++ b/src/blueprint/agent_generator/base_files/settings.txt @@ -4,7 +4,7 @@ app_version = "0.1.0" app_description debug = true model_provider = "vllm" -model_base_url = "https://avs-vllm.q14.net/v1" +model_base_url = "https://YOUR_VLLM_HOST/v1" # Event deduplication is off by default: a handler may be run more than once for the # same event, because delivery is at-least-once and an acknowledgement can always be @@ -15,13 +15,15 @@ model_base_url = "https://avs-vllm.q14.net/v1" # idempotency_ttl = 1500 # Required as soon as a scheduler is registered -- it has no default, because neither -# value is safe to inherit. "event" starts no in-process timer: the tick arrives as an -# event on .scheduler., published by an external CronJob, so -# exactly one replica runs it -- and it needs event_bus set. "in_process" runs an -# APScheduler timer in the process and claims each tick in the cache so one replica -# runs it; it is right for local development and plain Docker, and it needs -# .with_cache() or every replica runs every tick. -scheduler_mode = "in_process" +# value is safe to inherit, and this template does not choose for you. "event" starts no +# in-process timer: the tick arrives as an event on .scheduler. +# (.scheduler. when the agent is served on its own), published +# by an external CronJob, so exactly one replica runs it -- and it needs event_bus set. +# "in_process" runs an APScheduler timer in the process and claims each tick in the cache +# so one replica runs it; it is right for local development and plain Docker, and it +# needs .with_cache() or every replica runs every tick. +# scheduler_mode = "event" +# scheduler_mode = "in_process" # Set this to publish events without consuming any -- a scheduler that reports what # it did, for instance. A handler already implies a client, so only publish-only diff --git a/src/blueprint/agent_generator/cli/commands/setup.py b/src/blueprint/agent_generator/cli/commands/setup.py index fb7b57bd..fd85e2db 100644 --- a/src/blueprint/agent_generator/cli/commands/setup.py +++ b/src/blueprint/agent_generator/cli/commands/setup.py @@ -193,7 +193,10 @@ def run(args: Namespace) -> None: print(" (A .secrets.toml with a placeholder has been created for you)") print(" 3. Run the generated tests: pytest") print(" 4. Run the service: asbs dev") - print(f" 5. View API docs at: http://localhost:8000/docs (this agent's routes are under /api/{namespace})") + print( + f" 5. View API docs at: http://localhost:8000/docs (served alone, this agent's routes are under /api; " + f"hosted in a group, under /api/{namespace})" + ) print("\nsrc/main.py declares this agent; it does not build an application.") print("\nThis directory carries no agents.toml, and that is deliberate: the agent map says") diff --git a/src/blueprint/agent_generator/cli/commands/validate.py b/src/blueprint/agent_generator/cli/commands/validate.py index fa8a12a1..cf0b6a2f 100644 --- a/src/blueprint/agent_generator/cli/commands/validate.py +++ b/src/blueprint/agent_generator/cli/commands/validate.py @@ -217,17 +217,15 @@ def _idempotency_notice(project_dir: Path) -> str | None: # missing is the honest shape. # ---------------------------------------------------------------------------------------------- -NO_AGENT_MAP_WARNING = "\n".join( +NO_AGENT_MAP_NOTICE = "\n".join( [ - "No agents.toml, so this project cannot be hosted by 'python -m blueprint.agents.entrypoint'.", - " That is not a fault in a project deployed on its own, which is served by its own", - " src/main.py as it always was. To make it hostable, three changes and nothing else:", - " - src/main.py: 'agent = AppBuilder()...' -- drop the config argument and the", - " trailing .build(), so the file declares rather than builds;", - " - Dockerfile: the command becomes 'python -m blueprint.agents.entrypoint';", - " - agents.toml: one [agents.] entry pointing at 'src.main:agent'.", - " The name chosen there becomes the queue group, part of the durable name and the", - " /api/ prefix, so it is a consumer migration to change after the first deploy.", + "No agents.toml here, which is right for an agent: the map says which agents an *image*", + " contains, so it belongs to the image that hosts this agent, never to the agent itself.", + " Served on its own, the agent needs none. To host it in a group, add one entry to the", + " image's agents.toml ([agents.] with root and module) and check the image with", + " 'asbs validate --group' -- see 'asbs docs guides/multi-agent-migration'. The name chosen", + " there becomes the queue group, part of the durable name and the /api/ prefix, so", + " it is a consumer migration to change after the first deploy.", ] ) @@ -247,7 +245,7 @@ def _group_findings(project_dir: Path) -> tuple[list[str], list[str], list[str]] agent_map_file = project_dir / AGENT_MAP_FILE if not agent_map_file.is_file(): - warnings.append(NO_AGENT_MAP_WARNING) + notices.append(NO_AGENT_MAP_NOTICE) agents: dict[str, str] = {} else: agents, map_issues = _read_agent_map(agent_map_file) diff --git a/src/blueprint/agent_generator/generator/generator.py b/src/blueprint/agent_generator/generator/generator.py index 7b7eaf33..56cb748f 100644 --- a/src/blueprint/agent_generator/generator/generator.py +++ b/src/blueprint/agent_generator/generator/generator.py @@ -7,7 +7,6 @@ from pathlib import Path from typing import Any -from .part_generators.part_generator_base import PartGeneratorBase from .part_generators import ( APIPartGenerator, CopyPartGenerator, @@ -78,10 +77,6 @@ def load_config(self) -> None: self.config = json.load(f) logger.debug(f"Loaded config: {json.dumps(self.config, indent=2, default=str)}") - if not self._config_is_valid(): - sys.exit(1) - logger.info("Configuration is valid") - except json.JSONDecodeError as e: error_msg = f"Invalid JSON in config file {self.config_path}: {e}" logger.error(error_msg, exc_info=True) @@ -91,6 +86,14 @@ def load_config(self) -> None: logger.error(error_msg, exc_info=True) raise + # Raised, not sys.exit(1): this is library code, and exiting the interpreter from it took + # the decision away from every caller -- a test, or a tool embedding the generator. The + # command-line entry point already turns an exception into a message and exit status 1. + # _config_is_valid has logged each problem it found. + if not self._config_is_valid(): + raise ValueError(f"Config file {self.config_path} is not valid; the problems are logged above.") + logger.info("Configuration is valid") + def _config_is_valid(self) -> bool: """Validate the configuration structure and cross-references. @@ -351,7 +354,6 @@ def _create_files_from_templates(self) -> None: "", "Dockerfile", "Dockerfile", - template_vars={"agent_namespace": PartGeneratorBase.agent_namespace(self.config)}, ).create_file(out) # Create .gitignore diff --git a/tests/unit/agent_generator/cli/commands/test_validate_group_gates.py b/tests/unit/agent_generator/cli/commands/test_validate_group_gates.py index c80a34ba..06e0adae 100644 --- a/tests/unit/agent_generator/cli/commands/test_validate_group_gates.py +++ b/tests/unit/agent_generator/cli/commands/test_validate_group_gates.py @@ -32,14 +32,15 @@ def _agent(name: str = "orders", module: str = "src.main:agent") -> str: class TestTheAgentMap: """The map is how a name reaches code; the gate is everything that stops it.""" - def test_a_project_without_one_is_told_the_three_changes(self, tmp_path: Path) -> None: - issues, warnings, _ = _group_findings(_project(tmp_path)) + def test_an_agent_without_one_is_not_told_to_add_one(self, tmp_path: Path) -> None: + """An agent carries no map by design; it used to be warned and told to add one here.""" + issues, warnings, notices = _group_findings(_project(tmp_path)) assert not issues, "A project deployed on its own is not broken, so this is never an issue." - assert len(warnings) == 1 - assert "src/main.py" in warnings[0] - assert "Dockerfile" in warnings[0] - assert "agents.toml" in warnings[0] + assert warnings == [] + assert len(notices) == 1 + assert "belongs to the image" in notices[0] + assert "asbs validate --group" in notices[0] def test_a_well_formed_map_passes_silently(self, tmp_path: Path) -> None: issues, warnings, _ = _group_findings(_project(tmp_path, agent_map=_agent())) diff --git a/tests/unit/agent_generator/generator/test_generated_project.py b/tests/unit/agent_generator/generator/test_generated_project.py index 85c2348c..74ecabcc 100644 --- a/tests/unit/agent_generator/generator/test_generated_project.py +++ b/tests/unit/agent_generator/generator/test_generated_project.py @@ -461,6 +461,19 @@ def test_no_group_is_baked_into_the_production_image(self, project: Path) -> Non assert "ENV BLUEPRINT_AGENTS" not in final_stage assert "BLUEPRINT_GROUP" not in final_stage.replace("BLUEPRINT_GROUP=", "") + def test_every_file_the_dockerfile_copies_is_generated(self, project: Path) -> None: + """#11 -- it copied a README.md nothing generates, so a fresh `docker build` failed.""" + dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") + sources = [] + for line in dockerfile.splitlines(): + words = line.split() + if not words or words[0] != "COPY" or any(word.startswith("--from") for word in words): + continue + sources.extend(word for word in words[1:-1] if not word.startswith("--")) + assert sources, "the Dockerfile copies nothing from the build context" + missing = [source for source in sources if not (project / source).exists()] + assert missing == [] + def test_the_documented_run_command_needs_no_group(self, project: Path) -> None: """A placeholder here is a command that looks runnable and is not.""" dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") @@ -490,3 +503,27 @@ def test_a_leading_digit_is_refused_with_the_reason(self) -> None: with pytest.raises(ValueError, match="cannot be used"): PartGeneratorBase.agent_namespace({"name": "2ndAgent"}) + + +class TestTheGeneratedSettings: + """What settings.toml must not decide for the author, or bake in.""" + + def test_no_scheduler_mode_is_chosen(self, project: Path) -> None: + """It has no default by design; an active line in the template chose one anyway.""" + settings = (project / "settings.toml").read_text(encoding="utf-8") + active = [line for line in settings.splitlines() if line.startswith("scheduler_mode")] + assert active == [] + + def test_no_internal_host_is_baked_in(self, project: Path) -> None: + assert "q14.net" not in (project / "settings.toml").read_text(encoding="utf-8") + + +class TestAnInvalidGeneratorConfig: + def test_it_raises_instead_of_exiting_the_interpreter(self, tmp_path: Path) -> None: + """Library code: sys.exit took the decision away from every caller.""" + config_file = tmp_path / "generator-config.json" + config_file.write_text(json.dumps({"name": "Incomplete"}), encoding="utf-8") + generator = AgentGenerator(str(config_file), str(tmp_path / "out")) + + with pytest.raises(ValueError, match="is not valid"): + generator.load_config() From 44ffcf2f1534b0d5cfc7f4eb4344c7cc12263790 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 18:22:29 +0200 Subject: [PATCH 057/133] fix(telemetry)!: record event counters on the agent's own meter, labelled agent blueprint.events.unhandled and blueprint.events.duplicate were created at import on the global meter, so they reported under the root's resource for every agent, and were labelled namespace where every other metric uses agent. EventHandlingBase._count creates them per agent on first use. Also declares opentelemetry-instrumentation-httpx, which telemetry.py imports and pyproject.toml did not list. BREAKING CHANGE: the two counters carry the label agent (root: ) instead of namespace (root: ""). Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 7 +++ ...26-08-28-multi-agent-grouping-changelog.md | 22 +++++++ docs/specs/2026-08-28-multi-agent-grouping.md | 2 +- pyproject.toml | 1 + .../docs/concepts/observability.md | 4 +- .../io/api/eventing/event_handling_base.py | 46 ++++++++------ .../api/eventing/test_event_handling_base.py | 60 +++++++++++++------ 7 files changed, 103 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 96f7d20e..0bcd3a07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ ### Fixed +- **`opentelemetry-instrumentation-httpx` is a declared dependency.** `telemetry.py` imports it, + and it was installed only because something else happened to pull it in. - **Scaffolding fixes.** The generated `Dockerfile` copied a `README.md` that nothing generates, so `docker build` on a fresh project failed; the generated `settings.toml` chose `scheduler_mode = "in_process"`, defeating its deliberate lack of a default, and carried an internal model host; @@ -160,6 +162,11 @@ ### Breaking +- **`blueprint.events.unhandled` and `blueprint.events.duplicate` carry `agent`, not + `namespace`,** and are recorded on the agent's own meter. They were created at import on the + global meter, so they reported under the root's resource for every agent, with a label no other + metric uses. The root is labelled ``, as everywhere else. Dashboards on the old label need + the new one. - **`nats_use_jetstream = true` is enforced against the server; there is no fallback to Core NATS.** The server is asked for the account's JetStream information on connecting. If it does not offer JetStream, the agent fails: at startup through the startup failure policy, later (broker diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 5222a5b0..b7c3918c 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7691,6 +7691,28 @@ Guarded by `test_every_file_the_dockerfile_copies_is_generated` (checks every bu `TestAnInvalidGeneratorConfig` in `test_generated_project.py`, all four failing against the previous templates and code; and the rewritten validate case in `test_validate_group_gates.py`. +### Event counters on the agent's meter; the httpx instrumentation declared (metrics findings) + +- **Verified.** `event_handling_base.py` created `blueprint.events.unhandled` and + `blueprint.events.duplicate` at import on `metrics.get_meter(__name__)` -- the global provider -- + so every agent's count reported under the root's resource (C2), labelled `namespace` where every + other metric uses `agent`. **`EventHandlingBase._count(name, namespace, topic)`**, new: creates + the counter on `agent_meter(namespace, ...)` on first use -- the per-agent providers do not exist + at construction -- caches it per (counter, agent) on the instance, and labels + `{"agent": namespace or ROOT_LABEL, "topic": topic}`. The cache is keyed by agent, not topic, so + the no-per-topic-state guarantee holds; `test_many_distinct_topics_leave_no_state_behind` now + measures after the first event and asserts the cache stays at one entry. +- **Breaking for dashboards:** the label is now `agent`, and the root reports `` instead of + `""`. Listed in `CHANGELOG.md`'s Breaking section. +- **Verified.** `telemetry.py` imports `opentelemetry.instrumentation.httpx`, which `pyproject.toml` + did not declare; it is now declared (`>=0.59b0`, matching the other instrumentation). The unused + `opentelemetry-instrumentation-fastapi` was **not** removed: it belongs to trace propagation (#15), + deferred, and removing a dependency is not this change's call. + +Spec: the acceptance-criteria line for `blueprint.events.unhandled` says (agent, topic). +`concepts/observability.md` lists the two labels. Guarded by the converted accounting tests and the +new `test_it_is_counted_on_the_agents_own_meter` in `test_event_handling_base.py`. + --- ## Open points diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md index 7a1a32ca..5300ed47 100644 --- a/docs/specs/2026-08-28-multi-agent-grouping.md +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -980,7 +980,7 @@ unticked box is not done, and says why. carried as dead code, so the second half has nothing to check yet. - [ ] Unhandled events per (namespace, topic) and namespaces-per-subject fan-out are both exposed, neither reported as a fault and neither keeping per-topic state (sec. 7.2, sec. 7.7). - `blueprint.events.unhandled` carries (namespace, topic); the namespaces-per-subject fan-out + `blueprint.events.unhandled` carries (agent, topic), on the agent's own meter; the namespaces-per-subject fan-out gauge is not implemented. - [ ] Marginal RSS per additional idle namespace measured and published, reusing #36's benchmark harness. #32 measures ~6 MB per forked child with shared libraries; a diff --git a/pyproject.toml b/pyproject.toml index aa1ec0c6..bf460cac 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,6 +35,7 @@ dependencies = [ "opentelemetry-api>=1.38.0", "opentelemetry-sdk>=1.38.0", "opentelemetry-instrumentation-fastapi>=0.59b0", + "opentelemetry-instrumentation-httpx>=0.59b0", "opentelemetry-exporter-otlp>=1.38.0", "dapr>=1.16.0", "python-multipart>=0.0.20", diff --git a/src/blueprint/agent_generator/docs/concepts/observability.md b/src/blueprint/agent_generator/docs/concepts/observability.md index 55182c61..ae31e1ba 100644 --- a/src/blueprint/agent_generator/docs/concepts/observability.md +++ b/src/blueprint/agent_generator/docs/concepts/observability.md @@ -103,8 +103,8 @@ An exception propagating out of the method sets the span status to `ERROR` befor |---|---|---| | `blueprint.namespace.up` | gauge | `1` while an agent is serving, `0` once it is not. Carries `agent`. | | `blueprint.namespace.inflight` | gauge | Dispatches that agent has in progress. Carries `agent`. | -| `blueprint.events.unhandled` | counter | Events an agent received and found nothing to do with. | -| `blueprint.events.duplicate` | counter | Events an agent recognised as already processed. | +| `blueprint.events.unhandled` | counter | Events an agent received and found nothing to do with. Carries `agent` and `topic`. | +| `blueprint.events.duplicate` | counter | Events an agent recognised as already processed. Carries `agent` and `topic`. | | `llm.tokens.count` | counter | Tokens consumed, by an agent's model calls. | | `llm.response.latency` | histogram | Model call duration. | diff --git a/src/blueprint/agents/io/api/eventing/event_handling_base.py b/src/blueprint/agents/io/api/eventing/event_handling_base.py index c0049f90..6f39ee09 100644 --- a/src/blueprint/agents/io/api/eventing/event_handling_base.py +++ b/src/blueprint/agents/io/api/eventing/event_handling_base.py @@ -6,11 +6,12 @@ from abc import ABC, abstractmethod from typing import Any -from opentelemetry import metrics +from opentelemetry.metrics import Counter from ....component.component import traced from ....component.namespace import ROOT_LABEL from ....handler.handler_chain import DUPLICATE_CONTEXT_KEY +from ....io.telemetry.providers import agent_meter from ....models import ProcessingResult, ProcessingStatus from ....models.errors import DeliveryDisposition from ....models.events import CloudEvent @@ -20,17 +21,13 @@ logger = logging.getLogger(__name__) -_UNHANDLED_EVENTS = metrics.get_meter(__name__).create_counter( - name="blueprint.events.unhandled", - description="Events a namespace received and found nothing to do with", - unit="{event}", -) +UNHANDLED_EVENTS_COUNTER = "blueprint.events.unhandled" +DUPLICATE_EVENTS_COUNTER = "blueprint.events.duplicate" -_DUPLICATE_EVENTS = metrics.get_meter(__name__).create_counter( - name="blueprint.events.duplicate", - description="Events a namespace recognised as already processed and did not dispatch", - unit="{event}", -) +_COUNTER_DESCRIPTIONS = { + UNHANDLED_EVENTS_COUNTER: "Events an agent received and found nothing to do with", + DUPLICATE_EVENTS_COUNTER: "Events an agent recognised as already processed and did not dispatch", +} class EventHandlingBase(RestApiBase, CloudEventProcessorMixin, ABC): @@ -106,15 +103,28 @@ async def _process_cloud_event( agent = self.namespace if namespace is None else namespace logger.debug("Processing CloudEvent %s for namespace '%s'", cloud_event.id, agent or ROOT_LABEL) processing_result = await self._dispatch_cloud_event(cloud_event, context, namespace=agent) - # The agent this dispatch was for, not a hardcoded root. Both counters are documented as - # per-namespace and were attributing every event in the process to the root, so a group - # would have reported one agent's broad subscription as everybody's. The value is the - # namespace verbatim, so a single-agent application keeps reporting '' and its existing - # dashboards do not see a new label value. + # The agent this dispatch was for, not a hardcoded root: a group would otherwise report one + # agent's broad subscription as everybody's. if context.get(DUPLICATE_CONTEXT_KEY): - _DUPLICATE_EVENTS.add(1, {"namespace": agent, "topic": topic}) + self._count(DUPLICATE_EVENTS_COUNTER, agent, topic) logger.debug("Event %s on topic '%s' was already processed by '%s'", cloud_event.id, topic, agent or ROOT_LABEL) elif processing_result.status is ProcessingStatus.NO_HANDLER_FOUND: - _UNHANDLED_EVENTS.add(1, {"namespace": agent, "topic": topic}) + self._count(UNHANDLED_EVENTS_COUNTER, agent, topic) logger.debug("No handler in '%s' had work for event %s on topic '%s'", agent or ROOT_LABEL, cloud_event.id, topic) return processing_result + + def _count(self, name: str, namespace: str, topic: str) -> None: + """Add one to ``name`` on ``namespace``'s own meter, labelled like every other agent metric. + + The two counters used to be created once, at import, on the global meter -- so they + reported under the root's resource whatever agent they counted (C2), and they were + labelled ``namespace`` where every other metric says ``agent``. They are created per agent + on first use instead: the per-agent meter providers do not exist until the lifespan has + configured telemetry, which is after this component is constructed. + """ + counters: dict[tuple[str, str], Counter] = self.__dict__.setdefault("_event_counters", {}) + counter = counters.get((name, namespace)) + if counter is None: + counter = agent_meter(namespace, __name__).create_counter(name=name, description=_COUNTER_DESCRIPTIONS[name], unit="{event}") + counters[(name, namespace)] = counter + counter.add(1, {"agent": namespace or ROOT_LABEL, "topic": topic}) diff --git a/tests/unit/agents/io/api/eventing/test_event_handling_base.py b/tests/unit/agents/io/api/eventing/test_event_handling_base.py index 79de04e6..73347fd8 100644 --- a/tests/unit/agents/io/api/eventing/test_event_handling_base.py +++ b/tests/unit/agents/io/api/eventing/test_event_handling_base.py @@ -1,15 +1,30 @@ """Unit tests for EventHandlingBase._unwrap_nested_cloud_event and handle_event.""" import json +from collections import defaultdict +from collections.abc import Iterator +from contextlib import contextmanager from unittest.mock import AsyncMock, MagicMock, patch import pytest from blueprint.agents.handler.handler_chain import DUPLICATE_CONTEXT_KEY from blueprint.agents.io.api.eventing.dapr import DaprEventing +from blueprint.agents.io.api.eventing.event_handling_base import DUPLICATE_EVENTS_COUNTER, UNHANDLED_EVENTS_COUNTER from blueprint.agents.models.events import CloudEvent from blueprint.agents.models.result import ProcessingResult + +@contextmanager +def _counters() -> Iterator[dict[str, MagicMock]]: + """Stand-in counters, one per name, created through the agent's meter as the code does.""" + counters: dict[str, MagicMock] = defaultdict(MagicMock) + meter = MagicMock() + meter.create_counter.side_effect = lambda name, **_: counters[name] + with patch("blueprint.agents.io.api.eventing.event_handling_base.agent_meter", return_value=meter): + yield counters + + # --------------------------------------------------------------------------- # _unwrap_nested_cloud_event # --------------------------------------------------------------------------- @@ -178,20 +193,20 @@ async def test_unmatched_event_is_counted( ) -> None: self._returning(dapr_eventing, unhandled_result) - with patch("blueprint.agents.io.api.eventing.event_handling_base._UNHANDLED_EVENTS") as counter: + with _counters() as counters: await dapr_eventing._process_cloud_event(cloud_event, {}, "orders.created") - counter.add.assert_called_once_with(1, {"namespace": "", "topic": "orders.created"}) + counters[UNHANDLED_EVENTS_COUNTER].add.assert_called_once_with(1, {"agent": "", "topic": "orders.created"}) async def test_matched_event_is_not_counted( self, dapr_eventing: DaprEventing, cloud_event: CloudEvent, processed_result: ProcessingResult ) -> None: self._returning(dapr_eventing, processed_result) - with patch("blueprint.agents.io.api.eventing.event_handling_base._UNHANDLED_EVENTS") as counter: + with _counters() as counters: await dapr_eventing._process_cloud_event(cloud_event, {}, "orders.created") - counter.add.assert_not_called() + counters[UNHANDLED_EVENTS_COUNTER].add.assert_not_called() async def test_every_unmatched_event_is_counted( self, dapr_eventing: DaprEventing, cloud_event: CloudEvent, unhandled_result: ProcessingResult @@ -199,11 +214,11 @@ async def test_every_unmatched_event_is_counted( """The count is read as a ratio against received volume, so it must not be deduplicated.""" self._returning(dapr_eventing, unhandled_result) - with patch("blueprint.agents.io.api.eventing.event_handling_base._UNHANDLED_EVENTS") as counter: + with _counters() as counters: for _ in range(5): await dapr_eventing._process_cloud_event(cloud_event, {}, "orders.created") - assert counter.add.call_count == 5 + assert counters[UNHANDLED_EVENTS_COUNTER].add.call_count == 5 async def test_unmatched_event_is_not_reported_as_a_fault( self, @@ -220,17 +235,32 @@ async def test_unmatched_event_is_not_reported_as_a_fault( assert [r for r in caplog.records if r.levelname in {"WARNING", "ERROR", "CRITICAL"}] == [] + async def test_it_is_counted_on_the_agents_own_meter( + self, dapr_eventing: DaprEventing, cloud_event: CloudEvent, unhandled_result: ProcessingResult + ) -> None: + """Created at import on the global meter, it reported under the root's resource (C2).""" + self._returning(dapr_eventing, unhandled_result) + meter = MagicMock() + with patch("blueprint.agents.io.api.eventing.event_handling_base.agent_meter", return_value=meter) as agent_meter: + await dapr_eventing._process_cloud_event(cloud_event, {}, "orders.created", namespace="orders") + + assert agent_meter.call_args.args[0] == "orders" + meter.create_counter.return_value.add.assert_called_once_with(1, {"agent": "orders", "topic": "orders.created"}) + async def test_many_distinct_topics_leave_no_state_behind( self, dapr_eventing: DaprEventing, cloud_event: CloudEvent, unhandled_result: ProcessingResult ) -> None: """Under Dapr the topic comes from a URL path, so remembering each one is caller-controlled growth.""" self._returning(dapr_eventing, unhandled_result) + # The first event creates this agent's counter; that is per (counter, agent), not per topic. + await dapr_eventing._process_cloud_event(cloud_event, {}, "topic.first") before = len(dapr_eventing.__dict__) for index in range(100): await dapr_eventing._process_cloud_event(cloud_event, {}, f"topic.{index}") assert len(dapr_eventing.__dict__) == before + assert len(dapr_eventing.__dict__["_event_counters"]) == 1 # --------------------------------------------------------------------------- @@ -261,14 +291,11 @@ async def test_duplicate_is_counted_as_a_duplicate_not_as_unhandled( mock_registry.get_service.return_value.process_event = self._flagging_process_event(unhandled_result) mock_registry.correlation_context.set.return_value = MagicMock() - with ( - patch("blueprint.agents.io.api.eventing.event_handling_base._DUPLICATE_EVENTS") as duplicates, - patch("blueprint.agents.io.api.eventing.event_handling_base._UNHANDLED_EVENTS") as unhandled, - ): + with _counters() as counters: await dapr_eventing.handle_event("orders", cloud_event) - duplicates.add.assert_called_once_with(1, {"namespace": "", "topic": "orders"}) - unhandled.add.assert_not_called() + counters[DUPLICATE_EVENTS_COUNTER].add.assert_called_once_with(1, {"agent": "", "topic": "orders"}) + counters[UNHANDLED_EVENTS_COUNTER].add.assert_not_called() async def test_duplicate_still_acknowledges( self, @@ -295,11 +322,8 @@ async def test_unmatched_event_is_still_counted_as_unhandled( mock_registry.get_service.return_value.process_event = AsyncMock(return_value=unhandled_result) mock_registry.correlation_context.set.return_value = MagicMock() - with ( - patch("blueprint.agents.io.api.eventing.event_handling_base._DUPLICATE_EVENTS") as duplicates, - patch("blueprint.agents.io.api.eventing.event_handling_base._UNHANDLED_EVENTS") as unhandled, - ): + with _counters() as counters: await dapr_eventing.handle_event("orders", cloud_event) - unhandled.add.assert_called_once_with(1, {"namespace": "", "topic": "orders"}) - duplicates.add.assert_not_called() + counters[UNHANDLED_EVENTS_COUNTER].add.assert_called_once_with(1, {"agent": "", "topic": "orders"}) + counters[DUPLICATE_EVENTS_COUNTER].add.assert_not_called() From fb6550b3d4b0d1d11c18f766a193187d75137a51 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 18:39:05 +0200 Subject: [PATCH 058/133] fix: log each failure once, fix the health status vocabulary, and correct stale docs - The handler chain and EventProcessingService logged a handler failure at ERROR before re-raising, and the transport edge logged it again; only the edge logs it now. DaprClient.publish, NATSClient.connect and Config.validate stop logging before raising. - HealthCheckerBase's example and SessionsServiceHealthChecker used UP/DOWN, which readiness counts as failing; now healthy/unhealthy. - Rewrite the health README (it described classes that do not exist) and fix stale docstrings and docs (RestApiBase, EventHandlerBase, namespace_of, Registry, components/services.md). Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 12 + ...26-08-28-multi-agent-grouping-changelog.md | 40 ++ .../docs/components/services.md | 2 +- .../agents/clients/io/dapr_client.py | 10 +- .../agents/clients/io/nats_client.py | 4 +- src/blueprint/agents/component/__init__.py | 2 +- src/blueprint/agents/component/namespace.py | 4 +- src/blueprint/agents/component/registry.py | 2 +- src/blueprint/agents/config/config.py | 5 +- .../agents/handler/event_handler_base.py | 3 +- src/blueprint/agents/handler/handler_chain.py | 4 +- .../agents/io/api/actuators/health/README.md | 390 ++---------------- .../io/api/actuators/health/health_base.py | 6 +- .../api/actuators/health/sessions_health.py | 8 +- src/blueprint/agents/io/api/rest_api_base.py | 20 +- .../eventing/event_processing_service.py | 11 +- .../unit/agents/handler/test_handler_chain.py | 14 + .../actuators/health/test_sessions_health.py | 10 +- 18 files changed, 135 insertions(+), 412 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0bcd3a07..b18495f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,18 @@ ### Fixed +- **A handler failure is logged once.** The handler chain and `EventProcessingService` each logged + it at ERROR before re-raising, and the transport edge logged it again with its disposition -- + up to three copies per failure. Only the edge logs it now. `DaprClient.publish`, `NATSClient.connect` + and `Config.validate` stop logging before raising, too. +- **The documented health-check example reported a failing check.** `HealthCheckerBase`'s example + returned `status="UP"`, but readiness counts anything other than `"healthy"` as failing; + `SessionsServiceHealthChecker` returned `UP`/`DOWN` and so always counted as down. Both now use + `"healthy"`/`"unhealthy"`. +- **Stale documentation:** the health package README described three classes that do not exist + (rewritten); `components/services.md` said `ServiceBase` has no abstract methods (it has two); + the `RestApiBase` and `EventHandlerBase` docstring examples did not run; `namespace_of` and the + registry's log line described code that has moved on. - **`opentelemetry-instrumentation-httpx` is a declared dependency.** `telemetry.py` imports it, and it was installed only because something else happened to pull it in. - **Scaffolding fixes.** The generated `Dockerfile` copied a `README.md` that nothing generates, so diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index b7c3918c..b9575535 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7713,10 +7713,50 @@ Spec: the acceptance-criteria line for `blueprint.events.unhandled` says (agent, `concepts/observability.md` lists the two labels. Guarded by the converted accounting tests and the new `test_it_is_counted_on_the_agents_own_meter` in `test_event_handling_base.py`. +### Log once, and documentation that matches the code (low-priority findings) + +**Log or raise, not both** (the repo's logging rule), all verified: + +- `HandlerChain._dispatch` logged a failing handler at ERROR and re-raised; so did + `EventProcessingService.process_event`; and the transport edge -- NATS `message_handler`, Dapr + `_process_event` / fan-out, REST `_process_resource` (`logger.exception`) -- logged it again with + its disposition. Verified each edge logs before removing the two inner ones; one failure is now + one ERROR line. The chain still records the exception on the span. +- `DaprClient.publish` logged and re-raised a publish failure; now it only raises. +- `NATSClient.connect` logged "Failed to connect" and re-raised; the retry loop already logs each + attempt. Now it adds a note with the (redacted) URL and raises. +- `Config.validate` logged each of its three failure kinds before raising `ConfigError`. + +**Found while rewriting the health README:** `HealthCheckerBase`'s docstring example returned +`status="UP"` and documented `"UP"`/`"DOWN"`, while `HealthCheckCache` counts anything other than +`"healthy"` as failing -- so a check written from the example was permanently failing. This is +the "status vocabulary is split" finding, and `SessionsServiceHealthChecker` had the same bug. Both +now use `"healthy"`/`"unhealthy"`; the docstring says why `"UP"` is wrong for a component. + +**Docs and docstrings:** `io/api/actuators/health/README.md` (383 lines describing +`DaprPubSubHealthChecker`, `VLLMProviderHealthChecker` and `HealthCheckerRegistry`, none of which +exist) rewritten to the actual modules; `components/services.md` (the two abstract lifecycle +methods); `RestApiBase` module docstring (syntactically broken, called a non-existent +`get_registry()`); `EventHandlerBase` example (subclassed `EventHandler`, assigned `self.name`); +`namespace_of` (the namespace lives on `Component` now); "ComponentRegistry" in the registry's log +line and `component/__init__.py`. + +**Observed, not changed:** `TestClaimedTick::test_three_replicas_run_one_tick` failed once in a full +run (two replicas claimed one tick) and passed five times in a row alone. Nothing in this change +touches the scheduler or `DiskCacheService`; `DiskCacheService.claim` documents one non-atomic path +(taking over an expired claim), which is the likely cause. Recorded under *Open points*. + +Guarded by `test_a_handler_failure_is_raised_not_logged` (`test_handler_chain.py`) and the +vocabulary cases in `test_sessions_health.py`. + --- ## Open points +- **`test_three_replicas_run_one_tick` is flaky in a full run.** Seen once on 2026-09-24 (two of three + replicas ran one tick), passing alone. Likely `DiskCacheService.claim`'s documented non-atomic + takeover of an expired claim, or a run straddling a minute boundary; not investigated. + - ~~**A startup-failure latch is never released.**~~ **Closed** -- see *A latched agent recovers, and readiness shows it* above. A non-critical agent whose `on_startup` raised is latched by `AppBuilder._mark_agent_down` -> `NamespaceSupervisor.mark_down`, and nothing in diff --git a/src/blueprint/agent_generator/docs/components/services.md b/src/blueprint/agent_generator/docs/components/services.md index 2afdf172..cffbf664 100644 --- a/src/blueprint/agent_generator/docs/components/services.md +++ b/src/blueprint/agent_generator/docs/components/services.md @@ -32,7 +32,7 @@ class MyService(ServiceBase): super().__init__() ``` -ServiceBase provides access to `self.registry` and `self.config` inherited from Component. There are no abstract methods to implement -- add whatever public methods your domain requires. +ServiceBase provides access to `self.registry` and `self.config` inherited from Component. It has two abstract methods, `on_startup()` and `on_shutdown()` (see *Lifecycle Hooks* below) -- implement both, even if one does nothing -- and otherwise add whatever public methods your domain requires. ## Lifecycle Hooks diff --git a/src/blueprint/agents/clients/io/dapr_client.py b/src/blueprint/agents/clients/io/dapr_client.py index 2dab31ae..5797d374 100644 --- a/src/blueprint/agents/clients/io/dapr_client.py +++ b/src/blueprint/agents/clients/io/dapr_client.py @@ -132,13 +132,9 @@ async def publish( params = {"metadata.routingKey": routing_key} if routing_key else {} data = json.dumps(dict(event)) - try: - response = await client.post(url, content=data, headers=headers, params=params) - response.raise_for_status() - logger.debug("Published event to Dapr topic '%s': %s", topic, event.id) - except Exception as e: - logger.error("Failed to publish event to Dapr topic '%s': %s", topic, str(e)) - raise + response = await client.post(url, content=data, headers=headers, params=params) + response.raise_for_status() + logger.debug("Published event to Dapr topic '%s': %s", topic, event.id) # ------------------------------------------------------------------ # Health diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 55669e7b..9967e428 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -789,7 +789,9 @@ async def connect(self) -> None: except JetStreamUnavailableError: raise except Exception as e: - logger.error("Failed to connect to NATS: %s", str(e)) + # Raised, not logged: the retry loop logs each failed attempt, and a caller outside it + # decides for itself. Logging here as well doubled every connection failure. + e.add_note(f"while connecting to NATS at {nats_url}") raise async def _require_jetstream(self, nats_url: str) -> None: diff --git a/src/blueprint/agents/component/__init__.py b/src/blueprint/agents/component/__init__.py index 7d435732..72c55f5a 100644 --- a/src/blueprint/agents/component/__init__.py +++ b/src/blueprint/agents/component/__init__.py @@ -5,7 +5,7 @@ All components extend Component and inherit: - name -> str -- registry -> ComponentRegistry +- registry -> Registry - config -> Config - on_startup() and on_shutdown() for lifecycle management """ diff --git a/src/blueprint/agents/component/namespace.py b/src/blueprint/agents/component/namespace.py index 7fd7e928..f4c9e15d 100644 --- a/src/blueprint/agents/component/namespace.py +++ b/src/blueprint/agents/component/namespace.py @@ -272,8 +272,8 @@ def qualified_entry_name(namespace: str, name: str) -> str: def namespace_of(component: Any) -> str: """Return the namespace a component belongs to, or the root for one that has none. - Read with ``getattr`` because the namespace currently lives on the bases that own - one (transport clients, publishing service) rather than on ``Component`` itself. + Every ``Component`` carries its namespace. Read with ``getattr`` so that an object which is + not a component -- a health checker, a plain value -- answers the root instead of raising. """ return str(getattr(component, "namespace", ROOT_NAMESPACE) or ROOT_NAMESPACE) diff --git a/src/blueprint/agents/component/registry.py b/src/blueprint/agents/component/registry.py index 9a5249b3..879836cd 100644 --- a/src/blueprint/agents/component/registry.py +++ b/src/blueprint/agents/component/registry.py @@ -88,7 +88,7 @@ def __init__(self, component_class: Any) -> None: self._default_namespace: str | None = None self._views: dict[str, Registry] = {} - logger.info("ComponentRegistry initialized") + logger.info("Registry initialized") def _resolve_single(self, name_or_class: str | type[T], base_type: type[T], namespace: str | None = None) -> T: """Resolve a single component by name string or concrete class. diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index 1646f6f4..e1f2cc26 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -1299,17 +1299,14 @@ def validate(self) -> bool: except ValidationError as exc: # Handle Dynaconf validation errors without stack trace error_msg = str(exc) - logger.error("Configuration validation failed: %s", error_msg) self._validation_errors.append(error_msg) raise ConfigError(error_msg) from None except ConfigError as exc: - # Re-raise ConfigError without stack trace - logger.error("Configuration validation failed: %s", exc) + # Re-raised, not logged: the caller decides (log or raise, not both). self._validation_errors.append(str(exc)) raise except Exception as exc: # Catch any other unexpected errors with stack trace for debugging - logger.error("Unexpected configuration error: %s", exc, exc_info=True) self._validation_errors.append(str(exc)) raise ConfigError(str(exc)) from exc diff --git a/src/blueprint/agents/handler/event_handler_base.py b/src/blueprint/agents/handler/event_handler_base.py index 538fb2fa..a02f69fe 100644 --- a/src/blueprint/agents/handler/event_handler_base.py +++ b/src/blueprint/agents/handler/event_handler_base.py @@ -46,10 +46,9 @@ class EventHandlerBase(Component, ABC): Usage in custom code: ```python - class MyHandler(EventHandler): + class MyHandler(EventHandlerBase): def __init__(self): super().__init__(priority=20) - self.name = "MyHandler" async def can_handle_event(self, event, context): return True diff --git a/src/blueprint/agents/handler/handler_chain.py b/src/blueprint/agents/handler/handler_chain.py index 3bc0498e..c10b3e7d 100644 --- a/src/blueprint/agents/handler/handler_chain.py +++ b/src/blueprint/agents/handler/handler_chain.py @@ -361,7 +361,9 @@ async def _dispatch(self, event: CloudEvent[Any], context: dict[str, Any]) -> An logger.info("Handler '%s' passed event '%s' to next handler", handler.name, event.type) except Exception as e: - logger.error("Handler '%s' failed: %s", handler.name, str(e), exc_info=True) + # Not logged here: the transport edge logs it with the topic and the disposition it + # chose (spec sec. 7.2), which this layer does not know. Logging here as well put + # every handler failure in the log two or three times. span.record_exception(e) raise diff --git a/src/blueprint/agents/io/api/actuators/health/README.md b/src/blueprint/agents/io/api/actuators/health/README.md index fa464ebc..cc9088db 100644 --- a/src/blueprint/agents/io/api/actuators/health/README.md +++ b/src/blueprint/agents/io/api/actuators/health/README.md @@ -1,383 +1,47 @@ -# Health Check System +# Health checks -Comprehensive health check framework for monitoring application components and dependencies. +Readiness is computed from registered health checks, per agent, and cached. This directory holds +the pieces; `ActuatorApi` wires them and serves `/health/live` and `/health/ready`. -## Overview +## Writing a check -The health check system provides a unified interface for monitoring the status of various application components (Dapr, AI providers, custom services, etc.). It supports: - -- **Extensible architecture**: Easy to add custom health checkers -- **Async operations**: Non-blocking health checks -- **Caching**: Periodic background updates to reduce resource consumption -- **Registry pattern**: Dynamic registration and management of health checkers -- **Type safety**: Full type hints and Protocol/ABC support - -## Architecture - -### Core Components - -``` -HealthCheckerBase (Abstract Base Class) - ├── DaprPubSubHealthChecker - ├── VLLMProviderHealthChecker - └── CustomHealthChecker (user-defined) - -HealthCheckerRegistry - └── Manages all registered health checkers - -HealthCheckCache - └── Caches health check results with periodic updates - -ActuatorApi - └── Exposes health check endpoints (/health/live, /health/ready) -``` - -## Classes - -### 1. HealthCheckerBase - -**Location**: `base.py` - -Abstract base class that all health checkers must inherit from. +Subclass `HealthCheckerBase` and return a `ComponentHealth`: ```python -from blueprint.agents.services.health import HealthCheckerBase -from blueprint.agents.models.api import ComponentHealth - - -class CustomHealthChecker(HealthCheckerBase): - async def health_check(self) -> ComponentHealth: - """Perform health check logic.""" - try: - # Check component status - is_healthy = await check_service() - return ComponentHealth( - status="UP" if is_healthy else "DOWN", message="Service is operational" if is_healthy else "Service unavailable" - ) - except Exception as e: - return ComponentHealth(status="DOWN", message=str(e)) -``` - -**Key Method**: -- `async def health_check(self) -> ComponentHealth`: Perform health check and return status - -**Returns**: `ComponentHealth` object with: -- `status`: "UP" or "DOWN" -- `message`: Human-readable status message - -### 2. DaprPubSubHealthChecker - -**Location**: `dapr_pubsub.py` - -Monitors Dapr sidecar availability and pub/sub connectivity. - -```python -from blueprint.agents.services.health import DaprPubSubHealthChecker -from blueprint.agents.config import Config - -config = Config(...) -checker = DaprPubSubHealthChecker(config) -status = await checker.health_check() -``` - -**Configuration**: -- `health_check_dapr`: Enable/disable Dapr checks (default: True) -- `dapr_http_port`: Dapr HTTP port (default: 3500) - -**Checks**: -- Dapr sidecar reachability via `/v1.0/healthz` endpoint - -### 3. VLLMProviderHealthChecker - -**Location**: `vllm_provider.py` - -Monitors AI model provider health (vLLM, OpenAI). - -```python -from blueprint.agents.services.health import VLLMProviderHealthChecker -from blueprint.agents.config import Config - -config = Config(...) -checker = VLLMProviderHealthChecker(config, runtime_names=["default", "custom"]) -status = await checker.health_check() -``` - -**Configuration**: -- `health_check_ai_provider`: Enable/disable AI provider checks (default: True) -- Runtime-specific AI config (base_url, api_key, model_name) - -**Checks**: -- vLLM: Reachability via `/health` endpoint -- OpenAI: Configured but not actively checked (API-based) - -### 4. HealthCheckerRegistry - -**Location**: `registry.py` - -Manages registration and retrieval of health checkers. - -```python -from blueprint.agents.services.health import HealthCheckerRegistry, HealthCheckerBase - -registry = HealthCheckerRegistry() - -# Register a checker -registry.register("database", DatabaseHealthChecker()) - -# Register or replace -registry.register_or_replace("cache", CacheHealthChecker()) - -# Retrieve -checker = registry.get("database") - -# Check existence -if registry.has("database"): - print("Database checker registered") - -# List all -all_checkers = registry.get_all() # Returns dict[str, HealthCheckerBase] - -# Get names -names = registry.list_names() # Returns list[str] - -# Clear all -registry.clear() -``` - -**Methods**: -- `register(name, checker)`: Register a new checker (raises ValueError if exists) -- `register_or_replace(name, checker)`: Register or replace existing -- `get(name) -> HealthCheckerBase | None`: Get checker by name -- `get_all() -> dict[str, HealthCheckerBase]`: Get all checkers -- `has(name) -> bool`: Check if registered -- `list_names() -> list[str]`: List all checker names -- `clear()`: Remove all checkers - -### 5. HealthCheckCache - -**Location**: `cache.py` - -Caches health check results and performs periodic background updates. - -```python -from blueprint.agents.services.health.cache import HealthCheckCache - -cache = HealthCheckCache(check_interval_seconds=30) - -# Set health check providers -providers = {"dapr": DaprPubSubHealthChecker(config), "ai_provider": VLLMProviderHealthChecker(config)} -cache.set_health_check_provider(providers) - -# Start background scheduler -await cache.start() - -# Get cached results -results = await cache.get_health_checks() - -# Stop scheduler -await cache.stop() -``` - -## Usage Patterns - -### Pattern 1: Using AppBuilder - -```python -from blueprint.agents import AppBuilder, Config -from blueprint.agents.services.health import HealthCheckerBase +from blueprint.agents.io.api.actuators.health import HealthCheckerBase from blueprint.agents.models.api import ComponentHealth class DatabaseHealthChecker(HealthCheckerBase): async def health_check(self) -> ComponentHealth: - # Check database connection - return ComponentHealth(status="UP", message="DB OK") - - -config = Config(...) -builder = AppBuilder(config) - -# Register custom health checker -builder.with_health_checker("database", DatabaseHealthChecker()) -builder.with_health_checker("cache", CacheHealthChecker()) - -app = builder.build() -``` - -### Pattern 2: Direct Registry Usage - -```python -from blueprint.agents.services.health import HealthCheckerRegistry, HealthCheckerBase - -registry = HealthCheckerRegistry() - -# Register multiple checkers -registry.register("service1", Service1HealthChecker()) -registry.register("service2", Service2HealthChecker()) - -# Get all for ActuatorApi -all_checkers = registry.get_all() -``` - -### Pattern 3: Custom Health Checker - -```python -from blueprint.agents.services.health import HealthCheckerBase -from blueprint.agents.models.api import ComponentHealth -import httpx - - -class ExternalAPIHealthChecker(HealthCheckerBase): - def __init__(self, api_url: str): - self.api_url = api_url - - async def health_check(self) -> ComponentHealth: - try: - async with httpx.AsyncClient(timeout=5.0) as client: - response = await client.get(f"{self.api_url}/health") - response.raise_for_status() - return ComponentHealth(status="UP", message=f"API reachable at {self.api_url}") - except Exception as e: - return ComponentHealth(status="DOWN", message=f"API unreachable: {e}") -``` - -## Integration with AppBuilder - -The health check system is fully integrated into `AppBuilder`: - -```python -builder = AppBuilder(config) - -# Default health checkers are automatically registered: -# - DaprPubSubHealthChecker (if Dapr enabled) -# - VLLMProviderHealthChecker (if agents registered) - -# Add custom health checkers -builder.with_health_checker("custom", CustomHealthChecker()) - -# Build app with all health checks -app = builder.build() -``` - -**Endpoints**: -- `GET /health/live`: Liveness probe (always returns 200 if app is running) -- `GET /health/ready`: Readiness probe (returns 200 only if all health checks pass) -- `GET /info`: Service information and dependency status - -## Health Check Results - -Health checks return `ComponentHealth` objects: - -```python -from blueprint.agents.models.api import ComponentHealth - -health = ComponentHealth( - status="UP", # or "DOWN" - message="Service is operational", -) - -# Response format -{"status": "UP", "message": "Service is operational"} + ok = await ping_database() + return ComponentHealth(status="healthy" if ok else "unhealthy", message="database reachable" if ok else "no answer") ``` -## Configuration +**The status of a component is `"healthy"` or `"unhealthy"`.** Anything other than `"healthy"` +counts as failing -- `"UP"` included, which the payload uses for agents and the pod, not for +components. A check that raises counts as unhealthy. -Health checks are configured via `Config`: +Register it on the builder, inside the agent it belongs to: ```python -# settings.toml -[health_check] -health_check_dapr = true -health_check_ai_provider = true -health_check_interval_seconds = 30 -dapr_http_port = 3500 -``` - -## Best Practices - -1. **Inherit from HealthCheckerBase**: All custom health checkers must inherit from the abstract base class -2. **Handle Exceptions**: Always catch exceptions and return appropriate `ComponentHealth` status -3. **Use Timeouts**: Set reasonable timeouts for external service checks -4. **Log Appropriately**: Use DEBUG for successful checks, WARNING for failures -5. **Keep Checks Fast**: Health checks should complete within seconds -6. **Register Early**: Register health checkers before building the app - -## Example: Complete Setup - -```python -from blueprint.agents import AppBuilder, Config -from blueprint.agents.services.health import HealthCheckerBase -from blueprint.agents.models.api import ComponentHealth -from pathlib import Path - - -# Define custom health checker -class RedisHealthChecker(HealthCheckerBase): - def __init__(self, redis_url: str): - self.redis_url = redis_url - - async def health_check(self) -> ComponentHealth: - try: - import redis.asyncio as redis - - r = await redis.from_url(self.redis_url, socket_connect_timeout=2) - await r.ping() - await r.close() - return ComponentHealth(status="UP", message="Redis OK") - except Exception as e: - return ComponentHealth(status="DOWN", message=f"Redis error: {e}") - - -# Setup -config = Config(settings_files=["settings.toml"], root_path=Path(__file__).parent) - -builder = AppBuilder(config) - -# Register custom health checkers -builder.with_health_checker("redis", RedisHealthChecker("redis://localhost:6379")) -builder.with_health_checker("database", DatabaseHealthChecker()) - -# Build app -app = builder.build() - -# Health endpoints are now available: -# GET /health/live -> Liveness probe -# GET /health/ready -> Readiness probe with all checks -# GET /info -> Service info -``` - -## Testing - -```python -import pytest -from blueprint.agents.services.health import HealthCheckerBase -from blueprint.agents.models.api import ComponentHealth - - -class TestHealthChecker(HealthCheckerBase): - async def health_check(self) -> ComponentHealth: - return ComponentHealth(status="UP", message="Test OK") - - -@pytest.mark.asyncio -async def test_health_checker(): - checker = TestHealthChecker() - result = await checker.health_check() - assert result.status == "UP" - assert "Test OK" in result.message +AppBuilder().with_health_checker("db", DatabaseHealthChecker()) ``` -## Files +In a group, two agents may both register `"db"`; they appear as `orders.db` and `billing.db`. -- `base.py`: Abstract base class `HealthCheckerBase` -- `dapr_pubsub.py`: Dapr health checker implementation -- `vllm_provider.py`: AI provider health checker implementation -- `registry.py`: Health checker registry -- `cache.py`: Health check result caching with background updates -- `__init__.py`: Module exports +## What is here -## See Also +| Module | Purpose | +|---|---| +| `health_base.py` | `HealthCheckerBase`, and `HealthCheckEntry` -- a check with the agent it belongs to, carried as data. | +| `client_health.py` | `ClientHealthChecker`, registered by the framework for every transport client. It calls `connect()` before each check. | +| `cache_health.py` | `CacheHealthChecker`, registered for every named cache. | +| `sessions_health.py` | `SessionsServiceHealthChecker`, a heartbeat-age check for the sessions bus. Not registered by the framework. | +| `health_cache.py` | `HealthCheckCache`: runs the checks every `health_check_interval_seconds`, reduces them to one verdict per agent, applies the readiness policy and tells the supervisor. `refresh()` recomputes at once. | +| `namespace_supervisor.py` | `NamespaceSupervisor`: per-agent up/down, the `blueprint.namespace.up` gauge and ERROR event (C7), pausing a degraded agent's consumption (C4), and the startup-failure latch. | +| `readiness_policy.py` | `ReadinessPolicy`: `all`, `critical` or `any` -- which degraded agents take the pod out of rotation (C3). | -- `ActuatorApi`: Exposes health check endpoints -- `HealthCheckCache`: Caches health check results -- `AppBuilder.with_health_checker()`: Register custom health checkers +The concepts -- what makes an agent degraded, what happens then, and how the policy decides -- are +documented for users in `src/blueprint/agent_generator/docs/concepts/observability.md` +(`asbs docs observability --cat`). diff --git a/src/blueprint/agents/io/api/actuators/health/health_base.py b/src/blueprint/agents/io/api/actuators/health/health_base.py index 45a8144c..67d3e56e 100644 --- a/src/blueprint/agents/io/api/actuators/health/health_base.py +++ b/src/blueprint/agents/io/api/actuators/health/health_base.py @@ -18,7 +18,7 @@ class HealthCheckerBase(ABC): class CustomHealthChecker(HealthCheckerBase): async def health_check(self) -> ComponentHealth: # Perform health check logic - return ComponentHealth(status="UP", message="Service OK") + return ComponentHealth(status="healthy", message="Service OK") ``` """ @@ -27,7 +27,9 @@ async def health_check(self) -> ComponentHealth: """Perform health check and return component status. Returns: - ComponentHealth: Status object with status ("UP" or "DOWN") and message. + ComponentHealth: Status object with status ``"healthy"`` or ``"unhealthy"`` and a + message. Anything other than ``"healthy"`` counts as failing -- ``"UP"`` included, + which the readiness payload uses for agents and the pod, not for components. Raises: Exception: Any exceptions are caught by the caller and logged. diff --git a/src/blueprint/agents/io/api/actuators/health/sessions_health.py b/src/blueprint/agents/io/api/actuators/health/sessions_health.py index 8abf639b..833763bf 100644 --- a/src/blueprint/agents/io/api/actuators/health/sessions_health.py +++ b/src/blueprint/agents/io/api/actuators/health/sessions_health.py @@ -56,7 +56,7 @@ async def health_check(self) -> ComponentHealth: except Exception as e: logger.error("Sessions service REST API health check failed: %s", e) return ComponentHealth( - status="DOWN", + status="unhealthy", message=f"REST API unreachable: {str(e)}", details={"rest_api": "disconnected", "error": str(e)}, ) @@ -70,14 +70,14 @@ async def health_check(self) -> ComponentHealth: if time_since_heartbeat < 60: details["sse_connection"] = "active" return ComponentHealth( - status="UP", + status="healthy", message="Sessions service healthy", details=details, ) else: details["sse_connection"] = "stale" return ComponentHealth( - status="DOWN", + status="unhealthy", message=f"SSE connection stale (last heartbeat {int(time_since_heartbeat)}s ago)", details=details, ) @@ -86,7 +86,7 @@ async def health_check(self) -> ComponentHealth: details["sse_connection"] = "unknown" details["last_heartbeat_seconds_ago"] = None return ComponentHealth( - status="UP", + status="healthy", message="Sessions service REST API healthy, SSE status unknown", details=details, ) diff --git a/src/blueprint/agents/io/api/rest_api_base.py b/src/blueprint/agents/io/api/rest_api_base.py index 7b68f9ff..1f1a142a 100644 --- a/src/blueprint/agents/io/api/rest_api_base.py +++ b/src/blueprint/agents/io/api/rest_api_base.py @@ -1,21 +1,23 @@ """Generic RESTful API base class for the agent service (framework-level). -Subclasses register routes by decorating methods the class-level HTTP verb helpers. +Subclasses register routes by decorating methods with the class-level HTTP verb helpers. Example:: - class MyApi(RestApiBase): - def __init__(self) -> None: - super().__init__() + class ItemApi(RestApiBase): + async def on_startup(self) -> None: + self._items = self.registry.get_service(ItemService) - tags=["Status"], - @RestApiBase.get("/items", response_model=list[Item], tags=["Items"], summary="Get for Items") + async def on_shutdown(self) -> None: + pass + + @RestApiBase.get("/items", response_model=list[Item], tags=["Items"], summary="List items") async def list_items(self) -> list[Item]: - return await self.get_registry().get_service("item_service").all() + return await self._items.all() - @RestApiBase.post("/items", response_model=Item, tags=["Items"], summary="Create for Items") + @RestApiBase.post("/items", response_model=Item, tags=["Items"], summary="Create an item") async def create_item(self, payload: ItemRequest) -> Item: - return await self.get_registry().get_service("item_service").create(payload) + return await self._items.create(payload) """ from __future__ import annotations diff --git a/src/blueprint/agents/services/eventing/event_processing_service.py b/src/blueprint/agents/services/eventing/event_processing_service.py index 24bef789..99662294 100644 --- a/src/blueprint/agents/services/eventing/event_processing_service.py +++ b/src/blueprint/agents/services/eventing/event_processing_service.py @@ -192,15 +192,8 @@ async def process_event( status = ProcessingStatus.NO_HANDLER_FOUND if handler_result is None else ProcessingStatus.PROCESSED return self._build_result(request_id, handler_results, status) - except Exception as e: - logger.error( - "Event processing failed for request %s: %s", - request_id, - str(e), - extra={"request_id": request_id, "error": str(e)}, - exc_info=True, - ) - raise + # A failure propagates unlogged: every caller is a transport edge (NATS, Dapr, REST) that + # logs it with what it decided to do about it. Logging here too duplicated each failure. finally: self._correlation_context.reset(correlation_token) diff --git a/tests/unit/agents/handler/test_handler_chain.py b/tests/unit/agents/handler/test_handler_chain.py index 2967245c..5bcd0a27 100644 --- a/tests/unit/agents/handler/test_handler_chain.py +++ b/tests/unit/agents/handler/test_handler_chain.py @@ -130,6 +130,20 @@ async def handle_event(self, event, context): with pytest.raises(RuntimeError, match="handler exploded"): await chain.process(cloud_event, {}) + async def test_a_handler_failure_is_raised_not_logged( + self, chain: HandlerChain, mock_registry: MagicMock, cloud_event: GenericCloudEvent, caplog: pytest.LogCaptureFixture + ) -> None: + """The transport edge logs it with its disposition; logging here too doubled every failure.""" + + class BrokenHandler(StubHandler): + async def handle_event(self, event, context): + raise RuntimeError("handler exploded") + + _wire_handlers(mock_registry, [BrokenHandler()]) + with caplog.at_level("ERROR", logger="blueprint.agents.handler.handler_chain"), pytest.raises(RuntimeError): + await chain.process(cloud_event, {}) + assert caplog.records == [] + # --------------------------------------------------------------------------- # Idempotency (P4, spec sec. 7.4) diff --git a/tests/unit/agents/io/api/actuators/health/test_sessions_health.py b/tests/unit/agents/io/api/actuators/health/test_sessions_health.py index 51cab8b5..d67a9234 100644 --- a/tests/unit/agents/io/api/actuators/health/test_sessions_health.py +++ b/tests/unit/agents/io/api/actuators/health/test_sessions_health.py @@ -46,7 +46,7 @@ def mock_http(checker: SessionsServiceHealthChecker): class TestRestApiCheck: async def test_healthy_when_api_returns_200(self, checker: SessionsServiceHealthChecker, mock_http: AsyncMock) -> None: result = await checker.health_check() - assert result.status == "UP" + assert result.status == "healthy" async def test_rest_url_includes_health_endpoint(self, checker: SessionsServiceHealthChecker, mock_http: AsyncMock) -> None: await checker.health_check() @@ -61,7 +61,7 @@ async def test_api_key_passed_in_header(self, checker: SessionsServiceHealthChec async def test_down_when_request_error(self, checker: SessionsServiceHealthChecker, mock_http: AsyncMock) -> None: mock_http.get.side_effect = httpx.RequestError("connection refused") result = await checker.health_check() - assert result.status == "DOWN" + assert result.status == "unhealthy" async def test_down_message_contains_error(self, checker: SessionsServiceHealthChecker, mock_http: AsyncMock) -> None: mock_http.get.side_effect = httpx.RequestError("connection refused") @@ -83,13 +83,13 @@ class TestHeartbeatTracking: async def test_up_when_heartbeat_is_fresh(self, checker: SessionsServiceHealthChecker, mock_http: AsyncMock) -> None: checker._last_heartbeat = datetime.now(UTC) - timedelta(seconds=10) result = await checker.health_check() - assert result.status == "UP" + assert result.status == "healthy" assert result.details["sse_connection"] == "active" async def test_down_when_heartbeat_is_stale(self, checker: SessionsServiceHealthChecker, mock_http: AsyncMock) -> None: checker._last_heartbeat = datetime.now(UTC) - timedelta(seconds=90) result = await checker.health_check() - assert result.status == "DOWN" + assert result.status == "unhealthy" assert result.details["sse_connection"] == "stale" async def test_stale_message_contains_seconds_ago(self, checker: SessionsServiceHealthChecker, mock_http: AsyncMock) -> None: @@ -101,7 +101,7 @@ async def test_stale_message_contains_seconds_ago(self, checker: SessionsService class TestNoHeartbeat: async def test_up_when_no_heartbeat_yet(self, checker: SessionsServiceHealthChecker, mock_http: AsyncMock) -> None: result = await checker.health_check() - assert result.status == "UP" + assert result.status == "healthy" assert result.details["sse_connection"] == "unknown" From 54c309ab14af0826353c712b3135bd730c256764 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 24 Sep 2026 18:45:39 +0200 Subject: [PATCH 059/133] refactor(models): remove the empty event_routing module and unused example models models/event_routing.py was empty and imported by nothing. AnalysisRequest and AnalysisResponse were an old example domain the framework never used and the package did not export. Public API that is unused today is kept. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 3 ++ ...26-08-28-multi-agent-grouping-changelog.md | 21 ++++++++++++ src/blueprint/agents/models/event_routing.py | 0 src/blueprint/agents/models/result.py | 32 +------------------ tests/unit/agents/models/TESTS.md | 4 +-- tests/unit/agents/models/test_result.py | 27 ++-------------- 6 files changed, 29 insertions(+), 58 deletions(-) delete mode 100644 src/blueprint/agents/models/event_routing.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b18495f8..ea82de46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -174,6 +174,9 @@ ### Breaking +- **Removed unused internals:** the empty module `blueprint.agents.models.event_routing`, and the + example-domain models `AnalysisRequest` and `AnalysisResponse` in `blueprint.agents.models.result`, + which nothing in the framework used and the package did not export. - **`blueprint.events.unhandled` and `blueprint.events.duplicate` carry `agent`, not `namespace`,** and are recorded on the agent's own meter. They were created at import on the global meter, so they reported under the root's resource for every agent, with a label no other diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index b9575535..e75d8092 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7749,6 +7749,27 @@ touches the scheduler or `DiskCacheService`; `DiskCacheService.claim` documents Guarded by `test_a_handler_failure_is_raised_not_logged` (`test_handler_chain.py`) and the vocabulary cases in `test_sessions_health.py`. +### Dead code: only what is internal (decision E) + +Decided with the user: remove what is clearly internal, keep public API for now. + +**Removed:** `models/event_routing.py` (0 bytes, imported by nothing); `AnalysisRequest` and +`AnalysisResponse` in `models/result.py` -- an old example domain, not exported by +`blueprint.agents.models`, used by nothing but `AnalysisRequest`'s own validator tests, which went +with it (and the now unused `model_validator` import). `tests/unit/agents/models/TESTS.md` updated. + +**Kept, deliberately:** + +- Public API, per decision E: the unused registry getters, `EventPublishingService.publish_status_event`, + `get_topic_for_event_type`, `get_available_event_types`, `AgentRuntime.run_with_prompt(_sync)`, + `EventHandlerBase.get_published_event_types`, `Config.get_sessions_config`, and `RuntimeConfig` + (exported in `models.__all__`). +- `IOBase` -- empty, but the base of `RestApiBase` and `TelemetryManager`, so not dead. +- `DaprEventing._make_event_callback` -- proposed for removal, kept on inspection: `ClientBase.subscribe()` + requires the callbacks by contract, so removing them means changing that contract again. Its + docstring (since `75bc08e`) says they are never invoked. +- `NamespaceSupervisor.clear_forced_down` has a caller since the startup-recovery change. + --- ## Open points diff --git a/src/blueprint/agents/models/event_routing.py b/src/blueprint/agents/models/event_routing.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/blueprint/agents/models/result.py b/src/blueprint/agents/models/result.py index c4c9d70d..e77e7d3d 100644 --- a/src/blueprint/agents/models/result.py +++ b/src/blueprint/agents/models/result.py @@ -5,7 +5,7 @@ from typing import Any from uuid import UUID -from pydantic import BaseModel, Field, field_validator, model_validator +from pydantic import BaseModel, Field, field_validator from .events import HandlerResult @@ -67,36 +67,6 @@ def sort_evidence_by_confidence(cls, v: list[Evidence]) -> list[Evidence]: return v -class AnalysisRequest(BaseModel): - """A generic request to analyze a resource.""" - - resource_id: str | None = Field(None, description="The ID of a resource to fetch and analyze.") - resource: dict[str, Any] | None = Field(None, description="The full resource data to analyze directly.") - - force_recheck: bool = Field( - default=False, - description="If true, forces a re-analysis even if a cached result exists.", - ) - - @model_validator(mode="before") - @classmethod - def check_resource_or_id_provided(cls, values: dict[str, Any]) -> dict[str, Any]: - """Ensures that either a resource or its ID is provided, but not both.""" - if not values.get("resource_id") and not values.get("resource"): - raise ValueError("Either 'resource_id' or 'resource' must be provided.") - if values.get("resource_id") and values.get("resource"): - raise ValueError("Provide either 'resource_id' or 'resource', not both.") - return values - - -class AnalysisResponse(BaseModel): - """A generic response containing the result of an analysis.""" - - success: bool = Field(..., description="Indicates whether the analysis was successfully completed.") - result: AgentOutput | None = Field(None, description="The output of the analysis if successful.") - error: str | None = Field(None, description="An error message if the analysis failed.") - - class ProcessingStatus(StrEnum): """Enumeration of processing outcomes.""" diff --git a/tests/unit/agents/models/TESTS.md b/tests/unit/agents/models/TESTS.md index 879e4ba3..d9085cd1 100644 --- a/tests/unit/agents/models/TESTS.md +++ b/tests/unit/agents/models/TESTS.md @@ -10,7 +10,7 @@ Test coverage for `src/blueprint/agents/models/`. |---|---|---| | `test_config.py` | `EventPublishingConfig` | `normalize_topic_mapping`: `TopicConfig` / dict / plain-string / invalid-type values, non-dict mapping → error; `_parse_mapping_string`: empty string, quoted-key string, unquoted-key string (auto-quoting regex), non-brace format → error, malformed brace string → error; `_parse_topic_config_value`: plain string, `map[topic:t]`, `map[topic:t routing_key:rk]`, empty `map[]` → error, missing `topic` entry → error, entry without `:` → error | | `test_events.py` | `CloudEvent` | `validate_time_format`: Z-suffix, `+00:00` offset, missing timezone → error, non-string → error, default factory produces valid timestamp; `validate_data_exclusivity`: data-only, data_base64-only, neither, both → error | -| `test_result.py` | `Evidence`, `AgentOutput`, `AnalysisRequest` | `Evidence.confidence` ge/le constraints (0.0/1.0 pass, outside → error); `AgentOutput.sort_evidence_by_confidence`: empty list, single item, multiple items sorted descending, already-sorted input; `AnalysisRequest.check_resource_or_id_provided`: resource_id only, resource only, neither → error, both → error | +| `test_result.py` | `Evidence`, `AgentOutput` | `Evidence.confidence` ge/le constraints (0.0/1.0 pass, outside → error); `AgentOutput.sort_evidence_by_confidence`: empty list, single item, multiple items sorted descending, already-sorted input | --- @@ -18,7 +18,7 @@ Test coverage for `src/blueprint/agents/models/`. ### Only files with non-trivial logic are tested -`api.py`, `status.py`, and `event_routing.py` contain only Pydantic field definitions with no custom validators or methods. `errors.py` defines three trivial exception subclasses. None of these files have test modules. +`api.py` and `status.py` contain only Pydantic field definitions with no custom validators or methods. `errors.py` defines three trivial exception subclasses. None of these files have test modules. ### Private helpers tested via model construction, not called directly diff --git a/tests/unit/agents/models/test_result.py b/tests/unit/agents/models/test_result.py index 5ec33d89..6ed10082 100644 --- a/tests/unit/agents/models/test_result.py +++ b/tests/unit/agents/models/test_result.py @@ -1,9 +1,9 @@ -"""Unit tests for AgentOutput and AnalysisRequest validators.""" +"""Unit tests for AgentOutput and Evidence validators.""" import pytest from pydantic import ValidationError -from blueprint.agents.models.result import AgentOutput, AnalysisRequest, Evidence +from blueprint.agents.models.result import AgentOutput, Evidence def _evidence(confidence: float, label: str = "e") -> Evidence: @@ -65,26 +65,3 @@ def test_already_sorted_input_unchanged(self) -> None: output = self._output(items) confidences = [e.confidence for e in output.evidence] assert confidences == sorted(confidences, reverse=True) - - -# --------------------------------------------------------------------------- -# AnalysisRequest.check_resource_or_id_provided -# --------------------------------------------------------------------------- - - -class TestAnalysisRequestValidator: - def test_only_resource_id_is_valid(self) -> None: - req = AnalysisRequest(resource_id="res-1") - assert req.resource_id == "res-1" - - def test_only_resource_dict_is_valid(self) -> None: - req = AnalysisRequest(resource={"id": "res-1"}) - assert req.resource == {"id": "res-1"} - - def test_neither_field_raises(self) -> None: - with pytest.raises(ValidationError, match="Either 'resource_id' or 'resource'"): - AnalysisRequest() - - def test_both_fields_raises(self) -> None: - with pytest.raises(ValidationError, match="not both"): - AnalysisRequest(resource_id="r", resource={"id": "r"}) From 5838aabf48986c1dc6354bd028218b518d302941 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 25 Sep 2026 12:35:08 +0200 Subject: [PATCH 060/133] fix(logging): restore a standalone agent's pre-namespace log lines A standalone agent (namespace "", no group) logs again exactly what v0.8.1 logged: no "" labels, no "as ''" suffix, one line per auto-subscribed topic, and the original wording of the cache, registry, handler-chain, readiness, health-check and config lines. Grouped agents keep their labelled lines. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 7 ++ ...26-08-28-multi-agent-grouping-changelog.md | 41 ++++++++ src/blueprint/agents/app_builder.py | 54 +++++++---- .../agents/clients/io/nats_client.py | 31 +++++-- src/blueprint/agents/component/registry.py | 11 ++- src/blueprint/agents/config/config.py | 13 ++- src/blueprint/agents/handler/handler_chain.py | 5 +- .../agents/io/api/actuators/actuator_api.py | 18 ++-- .../io/api/actuators/health/health_cache.py | 10 +- src/blueprint/agents/io/api/eventing/nats.py | 22 +++-- .../app_builder/test_standalone_log_lines.py | 93 +++++++++++++++++++ .../agents/clients/io/test_nats_client.py | 25 +++++ tests/unit/agents/component/test_registry.py | 23 +++++ .../unit/agents/handler/test_handler_chain.py | 15 +++ .../api/actuators/health/test_health_cache.py | 16 ++++ .../io/api/actuators/test_actuator_api.py | 22 +++++ .../unit/agents/io/api/eventing/test_nats.py | 36 +++++++ 17 files changed, 386 insertions(+), 56 deletions(-) create mode 100644 tests/unit/agents/app_builder/test_standalone_log_lines.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ea82de46..bf64bd17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,13 @@ ### Fixed +- **A standalone agent logs what it logged before the namespace feature.** Log lines and error + messages that existed in 0.8.1 had been reworded for groups, with `` standing in for a + standalone agent's empty namespace -- e.g. `Eventing component startup completed`, + `No handler in namespace '' processed event`, the NATS connect and subscribe lines, the + cache registration lines, `Health check failed for …`, `Readiness probe failed: …`, the + configuration and OpenTelemetry lines, and the registry's "no cache" and "already exists" + errors. A standalone agent emits the 0.8.1 wording again; a grouped process keeps the new one. - **A handler failure is logged once.** The handler chain and `EventProcessingService` each logged it at ERROR before re-raising, and the transport edge logged it again with its disposition -- up to three copies per failure. Only the edge logs it now. `DaprClient.publish`, `NATSClient.connect` diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index e75d8092..59258a74 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7770,6 +7770,47 @@ with it (and the now unused `model_validator` import). `tests/unit/agents/models docstring (since `75bc08e`) says they are never invoked. - `NamespaceSupervisor.clear_forced_down` has a caller since the startup-recovery change. +### A standalone agent's existing output is restored (audit against v0.8.1) + +**Why.** The user's rule for this feature: nothing built for namespaces may change what a +standalone agent (namespace `""`) emits. An audit of v0.8.1 against this branch, for namespace +`""`, found `ROOT_LABEL` (``) -- which the spec mandates only for the NATS connection name +(sec. 6) -- used as the general rendering of "no namespace", so lines a standalone agent had always +logged were reworded. The namespace-derived identifiers themselves are clean for the root (no +prefix on queue group, durable, routes, cache or registry names). + +**Scope, as decided:** outputs that existed in v0.8.1 and changed are restored where that needs no +change of behaviour; outputs that are new are left alone for now; nothing is worked around. + +**Restored, each as `if namespace: else: `:** + +- `AppBuilder`: "Caching disabled"; "Registered with cache_dir=... (locking=...)" for the + root's default cache; the no-event-bus WARNING; "Eventing component startup completed / failed" + and "Eventing component shutdown failed" (the root's endpoint is now passed unlabelled to + `_start_component`, which omits an empty label). +- `Registry`: "Registering cache service: "; `ValueError("No cache service registered")`; + `ValueError("Component with name already exists")`; the "does not exist" suffix only for a + named namespace. +- `HandlerChain`: "No handler processed event ''". +- `NatsEventing`: one "NatsEventing: auto-subscribed to topic ''" per topic, and + "NatsEventing: no auto-subscriptions configured". +- `NATSClient`: "Connected to NATS server (Core NATS) / with JetStream at " without the + connection name (`_log_connected`); "Subscribed to JetStream / Core NATS topic ''" without + durable, deliver group or queue group. The URL stays redacted -- that is a security fix. +- `HealthCheckCache`: "Health check failed for : "; `ActuatorApi`: "Readiness probe + failed: " when the process hosts no agents. +- `TelemetryManager`: "OpenTelemetry configured for service ''" when no group is set; + `Config`: "Loading configuration properties for environment: " with the default prefix. + +Guarded by `test_standalone_log_lines.py` (6 cases, including "building a standalone agent logs no +``") and `Standalone*` cases in the NATS client, NATS eventing, handler chain, registry, +health cache and actuator tests (10 cases); all 16 fail against the previous code. No existing test +had pinned any of these lines, which is how they changed unnoticed. + +**Not restored -- listed for the user, not worked around:** the Dapr degraded reason, the +behaviour changes of the transport fixes, `Config` behaviour changes, the scheduler line, and the +new outputs (metrics, span and resource attributes, new log lines). + --- ## Open points diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index a0878ab7..f8fd2584 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -714,7 +714,10 @@ def with_cache(self, enabled: bool = True, enable_locking: bool = True, *, name: ValueError: if ``name`` cannot serve as a cache name. """ if not enabled: - logger.info("Caching disabled; cache '%s' is not registered", name) + if name == DEFAULT_CACHE_NAME and not current_namespace(): + logger.info("Caching disabled") + else: + logger.info("Caching disabled; cache '%s' is not registered", name) return self # Validated now, not at replay: the name becomes a directory segment and a Redis key @@ -770,13 +773,21 @@ def _create_cache(self, declaration: Declaration, config: Config) -> None: ) registry: Registry = Component.shared_registry # type: ignore[assignment] registry.add_cache(name, cache_service, namespace=namespace) - logger.info( - "Registered cache '%s' for agent '%s' as %s (locking=%s)", - name, - namespace or ROOT_LABEL, - type(cache_service).__name__, - enable_locking, - ) + if name == DEFAULT_CACHE_NAME and not namespace: + logger.info( + "Registered %s with cache_dir=%s (locking=%s)", + type(cache_service).__name__, + config.get_cache_config().cache_dir, + enable_locking, + ) + else: + logger.info( + "Registered cache '%s' for agent '%s' as %s (locking=%s)", + name, + namespace or ROOT_LABEL, + type(cache_service).__name__, + enable_locking, + ) def with_health_checker(self, name: str, checker: "HealthCheckerBase") -> "AppBuilder": """Declare a custom health checker for the readiness probe. @@ -1104,6 +1115,11 @@ def _wire_transport(self, registry: Registry, namespace: str, event_bus_type: st # lifespan hook still drives on_startup / on_shutdown without polluting the # router-mount path. self._lifecycle_components.append(SessionsBus(namespace=namespace)) + elif not namespace: + logger.warning( + "Event handlers are registered but no valid event_bus configured " + "('dapr', 'nats', or 'sessions'). Event handling will be disabled." + ) else: logger.warning( "Namespace '%s' has event handlers registered but no valid event_bus is configured " @@ -1295,7 +1311,7 @@ async def _start_component(self, kind: str, component: Any, label: str) -> None: except Exception as exc: namespace = namespace_of(component) if not namespace or namespace in self._critical_namespaces: - logger.error("%s %s startup failed: %s", kind, label, exc, exc_info=True) + logger.error("%s startup failed: %s", f"{kind} {label}" if label else kind, exc, exc_info=True) raise logger.error( "%s %s startup failed and agent '%s' is not critical, so the process starts without it: %s", @@ -1308,7 +1324,7 @@ async def _start_component(self, kind: str, component: Any, label: str) -> None: self._failed_startups.setdefault(namespace, []).append((kind, component, label)) await self._mark_agent_down(namespace, f"its {kind.lower()} '{label}' failed to start: {exc}") return - logger.info("%s %s startup completed", kind, label) + logger.info("%s startup completed", f"{kind} {label}" if label else kind) async def _on_transport_fatal(self, namespace: str, error: BaseException) -> None: """Act on a transport that found, after startup, that its agent cannot run at all. @@ -1559,7 +1575,8 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: # Eventing components (one Dapr / NATS endpoint per agent that consumes) for eventing_component in self._eventing_components: - await self._start_component("Eventing component", eventing_component, eventing_component.namespace or ROOT_LABEL) + # The root's endpoint is unlabelled, so a standalone agent logs what it always has. + await self._start_component("Eventing component", eventing_component, eventing_component.namespace) # Routerless lifecycle components (e.g. SessionsBus). for lifecycle_component in self._lifecycle_components: @@ -1590,12 +1607,15 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: try: await eventing_component.on_shutdown() except Exception as e: - logger.error( - "Eventing component for namespace '%s' shutdown failed: %s", - eventing_component.namespace or ROOT_LABEL, - e, - exc_info=True, - ) + if not eventing_component.namespace: + logger.error("Eventing component shutdown failed: %s", e, exc_info=True) + else: + logger.error( + "Eventing component for namespace '%s' shutdown failed: %s", + eventing_component.namespace, + e, + exc_info=True, + ) for scheduler in registry.get_schedulers(): try: diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 9967e428..69c73072 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -783,9 +783,9 @@ async def connect(self) -> None: if self._use_jetstream: self._js = self._nats_client.jetstream() await self._require_jetstream(nats_url) - logger.info("Connected to NATS server with JetStream at %s as '%s'", nats_url, self._connection_name) + self._log_connected("with JetStream", nats_url) else: - logger.info("Connected to NATS server (Core NATS) at %s as '%s'", nats_url, self._connection_name) + self._log_connected("(Core NATS)", nats_url) except JetStreamUnavailableError: raise except Exception as e: @@ -794,6 +794,13 @@ async def connect(self) -> None: e.add_note(f"while connecting to NATS at {nats_url}") raise + def _log_connected(self, mode: str, nats_url: str) -> None: + """Log the connection; a standalone agent's line is the one it has always logged.""" + if self.namespace: + logger.info("Connected to NATS server %s at %s as '%s'", mode, nats_url, self._connection_name) + else: + logger.info("Connected to NATS server %s at %s", mode, nats_url) + async def _require_jetstream(self, nats_url: str) -> None: """Fail the connection if the server does not offer JetStream to this account. @@ -1321,15 +1328,21 @@ async def message_handler(msg: Any) -> None: cb=message_handler, manual_ack=True, ) - logger.info( - "Subscribed to JetStream topic '%s' via durable '%s' in deliver group '%s'", - topic, - durable_name, - consumer_config.deliver_group or "", - ) + if self.namespace: + logger.info( + "Subscribed to JetStream topic '%s' via durable '%s' in deliver group '%s'", + topic, + durable_name, + consumer_config.deliver_group or "", + ) + else: + logger.info("Subscribed to JetStream topic '%s'", topic) else: sub = await client.subscribe(topic, queue=self._queue_group, cb=message_handler) - logger.info("Subscribed to Core NATS topic '%s' in queue group '%s'", topic, self._queue_group) + if self.namespace: + logger.info("Subscribed to Core NATS topic '%s' in queue group '%s'", topic, self._queue_group) + else: + logger.info("Subscribed to Core NATS topic '%s'", topic) self._subscriptions.append(sub) diff --git a/src/blueprint/agents/component/registry.py b/src/blueprint/agents/component/registry.py index 879836cd..f91a1718 100644 --- a/src/blueprint/agents/component/registry.py +++ b/src/blueprint/agents/component/registry.py @@ -363,6 +363,8 @@ def add_cache(self, name: str, cache: CacheService, *, namespace: str | None = N type(self._caches[key]).__name__, type(cache).__name__, ) + elif name == DEFAULT_CACHE_NAME and not agent: + logger.info("Registering cache service: %s", type(cache).__name__) else: logger.info("Registering cache '%s' for agent '%s': %s", name, agent or ROOT_LABEL, type(cache).__name__) self._caches[key] = cache @@ -448,7 +450,8 @@ def cache_service(self) -> CacheService: """ if not self.get_all_caches(): - raise ValueError(f"No cache service registered for agent '{self._cache_owner(None) or ROOT_LABEL}'") + owner = self._cache_owner(None) + raise ValueError(f"No cache service registered for agent '{owner}'" if owner else "No cache service registered") return self.get_cache() @cache_service.setter @@ -474,7 +477,9 @@ def add_component(self, name: str, component: Any) -> None: if name in self._components: existing = type(self._components[name]).__name__ - agent = namespace_of(component) or ROOT_LABEL + agent = namespace_of(component) + if not agent: + raise ValueError(f"Component with name {name} already exists") raise ValueError( f"Component name '{name}' is already taken by a {existing}, so {type(component).__name__} in namespace " f"'{agent}' cannot register under it. Registry names have to be unique across the whole process: they " @@ -562,7 +567,7 @@ def get_component(self, name_or_class: str | Any, namespace: str | None = None) component = self._lookup(name_or_class, namespace) if component is None: - in_namespace = "" if namespace is None else f" in namespace '{namespace or ROOT_LABEL}' or at the root" + in_namespace = f" in namespace '{namespace}' or at the root" if namespace else "" raise ValueError(f"Component with name {name_or_class} does not exist{in_namespace}") return component diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index e1f2cc26..cb83fe9e 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -228,11 +228,14 @@ def __init__( # environment the process loaded -- a fragment's [development] section is that agent's # development section, not a table it happens to have called that. self._environment = str(app_env) - logger.info( - "Loading configuration properties for environment: %s (environment overrides read from %s)", - app_env, - f"{self._envvar_prefix}_*" if self._envvar_prefix else "the whole process environment, unprefixed", - ) + if self._envvar_prefix == DEFAULT_ENVVAR_PREFIX: + logger.info("Loading configuration properties for environment: %s", app_env) + else: + logger.info( + "Loading configuration properties for environment: %s (environment overrides read from %s)", + app_env, + f"{self._envvar_prefix}_*" if self._envvar_prefix else "the whole process environment, unprefixed", + ) # A scoped view validates neither app_name nor a per-agent port. # diff --git a/src/blueprint/agents/handler/handler_chain.py b/src/blueprint/agents/handler/handler_chain.py index c10b3e7d..c18ce674 100644 --- a/src/blueprint/agents/handler/handler_chain.py +++ b/src/blueprint/agents/handler/handler_chain.py @@ -367,7 +367,10 @@ async def _dispatch(self, event: CloudEvent[Any], context: dict[str, Any]) -> An span.record_exception(e) raise - logger.warning("No handler in namespace '%s' processed event '%s'", self.namespace or ROOT_LABEL, event.type) + if self.namespace: + logger.warning("No handler in namespace '%s' processed event '%s'", self.namespace, event.type) + else: + logger.warning("No handler processed event '%s'", event.type) return None # ------------------------------------------------------------------ diff --git a/src/blueprint/agents/io/api/actuators/actuator_api.py b/src/blueprint/agents/io/api/actuators/actuator_api.py index 79ff32f3..75a31050 100644 --- a/src/blueprint/agents/io/api/actuators/actuator_api.py +++ b/src/blueprint/agents/io/api/actuators/actuator_api.py @@ -209,13 +209,17 @@ async def readiness_probe(self) -> ReadinessResponse: # The agents, not only the components: in a group the first question asked of a # failing probe is whose failure took the pod out, and the payload's per-agent # section is the only thing that answers it under a policy other than 'all'. - degraded = [name for name, agent in response.namespaces.items() if agent.status != "UP"] - logger.warning( - "Readiness probe failed under policy '%s'; degraded agent(s): %s; components: %s", - response.policy, - ", ".join(degraded) or "none reported", - response.components, - ) + if not any(self._namespaces): + # A standalone agent: no policy and no agents to name, so the line it always logged. + logger.warning("Readiness probe failed: %s", response.components) + else: + degraded = [name for name, agent in (response.namespaces or {}).items() if agent.status != "UP"] + logger.warning( + "Readiness probe failed under policy '%s'; degraded agent(s): %s; components: %s", + response.policy, + ", ".join(degraded) or "none reported", + response.components, + ) raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=response.model_dump(), diff --git a/src/blueprint/agents/io/api/actuators/health/health_cache.py b/src/blueprint/agents/io/api/actuators/health/health_cache.py index ab826621..02789076 100644 --- a/src/blueprint/agents/io/api/actuators/health/health_cache.py +++ b/src/blueprint/agents/io/api/actuators/health/health_cache.py @@ -161,12 +161,10 @@ async def _run_health_checks(self) -> None: if isinstance(result, BaseException): # The agent is named separately from the entry key, because that is the # question asked of a group: whose check is failing, not only which one. - logger.warning( - "Health check '%s' of agent '%s' failed: %s", - entry.name, - entry.agent, - result, - ) + if entry.namespace: + logger.warning("Health check '%s' of agent '%s' failed: %s", entry.name, entry.namespace, result) + else: + logger.warning("Health check failed for %s: %s", entry.key, result) components[entry.key] = ComponentHealth( status="unhealthy", message=f"Check failed: {result}", diff --git a/src/blueprint/agents/io/api/eventing/nats.py b/src/blueprint/agents/io/api/eventing/nats.py index 44c33c79..dade87f8 100644 --- a/src/blueprint/agents/io/api/eventing/nats.py +++ b/src/blueprint/agents/io/api/eventing/nats.py @@ -5,7 +5,7 @@ from ....clients.client_base import DeliveryCallback from ....clients.io.nats_client import NATSClient -from ....component.namespace import ROOT_LABEL, ROOT_NAMESPACE +from ....component.namespace import ROOT_NAMESPACE from ....models.events import CloudEvent from ..rest_api_base import RestApiBase from .event_handling_base import EventHandlingBase @@ -66,15 +66,21 @@ async def on_startup(self) -> None: topic_callbacks: dict[str, DeliveryCallback] = {topic: self._make_event_callback(topic) for topic in self._declared_topics()} if topic_callbacks: - logger.info( - "Namespace '%s' subscribes to %d topic(s): %s", - self.namespace or ROOT_LABEL, - len(topic_callbacks), - ", ".join(topic_callbacks), - ) + if self.namespace: + logger.info( + "Namespace '%s' subscribes to %d topic(s): %s", + self.namespace, + len(topic_callbacks), + ", ".join(topic_callbacks), + ) + else: + for topic in topic_callbacks: + logger.info("NatsEventing: auto-subscribed to topic '%s'", topic) await self._client.subscribe(topic_callbacks) + elif self.namespace: + logger.info("NatsEventing: no auto-subscriptions configured for namespace '%s'", self.namespace) else: - logger.info("NatsEventing: no auto-subscriptions configured for namespace '%s'", self.namespace or ROOT_LABEL) + logger.info("NatsEventing: no auto-subscriptions configured") def _declared_topics(self) -> list[str]: """Return the topics this agent subscribes to, in declaration order. diff --git a/tests/unit/agents/app_builder/test_standalone_log_lines.py b/tests/unit/agents/app_builder/test_standalone_log_lines.py new file mode 100644 index 00000000..2d6d93f3 --- /dev/null +++ b/tests/unit/agents/app_builder/test_standalone_log_lines.py @@ -0,0 +1,93 @@ +"""A standalone agent logs what it logged before the namespace feature (v0.8.1). + +The namespace feature must not change what a single-agent application emits. Every line checked +here existed in v0.8.1 and was reworded when agents gained namespaces -- with ```` standing in +for the empty namespace. For a standalone agent the old wording is restored; a grouped process keeps +the new one, which names the agent. +""" + +from collections.abc import Iterator +from pathlib import Path +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from blueprint.agents.app_builder import AppBuilder +from blueprint.agents.config import Config +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.io.telemetry.providers import reset_providers + + +class QuietHandler(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + async def can_handle_event(self, event, context) -> bool: # type: ignore[no-untyped-def] + return False + + async def handle_event(self, event, context) -> None: # type: ignore[no-untyped-def] + return None + + +@pytest.fixture(autouse=True) +def _forget_providers() -> Iterator[None]: + reset_providers() + yield + reset_providers() + + +@pytest.fixture +def config(tmp_path: Path) -> Config: + settings = tmp_path / "settings.toml" + settings.write_text( + f'[development]\napp_name = "standalone"\napp_port = 8000\napp_environment = "development"\n\n' + f'[development.cache]\ncache_dir = "{(tmp_path / "cache").as_posix()}"\n' + ) + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + +def test_caching_disabled(config: Config, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level("INFO", logger="blueprint.agents.app_builder"): + AppBuilder(config).with_cache(False) + assert "Caching disabled" in caplog.messages + + +def test_the_cache_is_registered(config: Config, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level("INFO"): + AppBuilder(config).with_cache().build() + assert f"Registered DiskCacheService with cache_dir={(tmp_path / 'cache').as_posix()} (locking=True)" in caplog.messages + assert "Registering cache service: DiskCacheService" in caplog.messages + + +def test_handlers_without_an_event_bus(config: Config, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level("WARNING", logger="blueprint.agents.app_builder"): + AppBuilder(config).with_handler(QuietHandler).build() + assert ( + "Event handlers are registered but no valid event_bus configured ('dapr', 'nats', or 'sessions'). Event handling will be disabled." + ) in caplog.messages + + +async def test_the_eventing_endpoint_starts(config: Config, caplog: pytest.LogCaptureFixture) -> None: + builder = AppBuilder(config) + endpoint = MagicMock(namespace="") + endpoint.on_startup = AsyncMock() + with caplog.at_level("INFO", logger="blueprint.agents.app_builder"): + await builder._start_component("Eventing component", endpoint, endpoint.namespace) + assert caplog.messages == ["Eventing component startup completed"] + + +def test_the_configuration_line(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: + settings = tmp_path / "settings.toml" + settings.write_text('[development]\napp_name = "standalone"\n') + with caplog.at_level("INFO", logger="blueprint.agents.config.config"): + Config(settings_files=[str(settings)], root_path=str(tmp_path)) + assert "Loading configuration properties for environment: development" in caplog.messages + + +def test_building_a_standalone_agent_names_no_root(config: Config, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level("INFO"): + AppBuilder(config).with_cache().with_handler(QuietHandler).build() + assert [record.getMessage() for record in caplog.records if "" in record.getMessage()] == [] diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index c95ee978..168ad959 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -2170,3 +2170,28 @@ async def test_before_startup_it_is_left_to_on_startup(self, nats_client: NATSCl await self._connect(nats_client, self._server(AsyncMock(side_effect=ServiceUnavailableError()))) await asyncio.sleep(0) handler.assert_not_awaited() + + +# --------------------------------------------------------------------------- +# A standalone agent logs what v0.8.1 logged +# --------------------------------------------------------------------------- + + +class TestStandaloneLogLines: + """No connection name, no queue group, no durable, no '' in a standalone agent's lines.""" + + async def test_the_connect_line(self, nats_client: NATSClient, caplog: pytest.LogCaptureFixture) -> None: + nc = MagicMock(is_closed=False, is_connected=True) + with ( + patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock, return_value=nc), + caplog.at_level("INFO", logger="blueprint.agents.clients.io.nats_client"), + ): + await nats_client.connect() + assert "Connected to NATS server (Core NATS) at nats://localhost:4222" in caplog.messages + assert not any("" in message for message in caplog.messages) + + async def test_the_subscribe_line(self, connected_nats_client: NATSClient, caplog: pytest.LogCaptureFixture) -> None: + connected_nats_client._queue_group = "test-agent" + with caplog.at_level("INFO", logger="blueprint.agents.clients.io.nats_client"): + await connected_nats_client._subscribe_one("orders.created", AsyncMock()) + assert caplog.messages == ["Subscribed to Core NATS topic 'orders.created'"] diff --git a/tests/unit/agents/component/test_registry.py b/tests/unit/agents/component/test_registry.py index d7465912..59fb0540 100644 --- a/tests/unit/agents/component/test_registry.py +++ b/tests/unit/agents/component/test_registry.py @@ -583,3 +583,26 @@ def test_an_explicit_namespace_may_name_this_view_or_the_root(self, grouped_regi def test_the_application_registry_still_sees_everything(self, grouped_registry: Registry) -> None: """build() and the lifespan hold the unscoped registry and must keep iterating all of it.""" assert len(grouped_registry.get_components_by_type(_Namespaced)) == 3 + + +# --------------------------------------------------------------------------- +# A standalone agent logs what v0.8.1 logged +# --------------------------------------------------------------------------- + + +class TestStandaloneMessages: + def test_the_cache_registration_line(self, registry: Registry, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.INFO, logger="blueprint.agents.component.registry"): + registry.cache_service = MagicMock() + assert "Registering cache service: MagicMock" in caplog.messages + + def test_no_cache_registered(self, registry: Registry) -> None: + with pytest.raises(ValueError) as caught: + _ = registry.cache_service + assert str(caught.value) == "No cache service registered" + + def test_a_duplicate_name(self, registry: Registry) -> None: + registry.add_component("x", StubA()) + with pytest.raises(ValueError) as caught: + registry.add_component("x", StubB()) + assert str(caught.value) == "Component with name x already exists" diff --git a/tests/unit/agents/handler/test_handler_chain.py b/tests/unit/agents/handler/test_handler_chain.py index 5bcd0a27..d8032b60 100644 --- a/tests/unit/agents/handler/test_handler_chain.py +++ b/tests/unit/agents/handler/test_handler_chain.py @@ -408,3 +408,18 @@ async def test_enabled_as_a_string_is_accepted(self, chain: HandlerChain, mock_r await chain.on_startup() assert chain._policy == IdempotencyPolicy(enabled=True, ttl=900) + + +# --------------------------------------------------------------------------- +# A standalone agent logs what v0.8.1 logged +# --------------------------------------------------------------------------- + + +class TestStandaloneLogLines: + async def test_no_handler_line( + self, chain: HandlerChain, mock_registry: MagicMock, cloud_event: GenericCloudEvent, caplog: pytest.LogCaptureFixture + ) -> None: + _wire_handlers(mock_registry, [StubHandler(result=None)]) + with caplog.at_level("WARNING", logger="blueprint.agents.handler.handler_chain"): + await chain.process(cloud_event, {}) + assert caplog.messages == [f"No handler processed event '{cloud_event.type}'"] diff --git a/tests/unit/agents/io/api/actuators/health/test_health_cache.py b/tests/unit/agents/io/api/actuators/health/test_health_cache.py index 70132878..604a1288 100644 --- a/tests/unit/agents/io/api/actuators/health/test_health_cache.py +++ b/tests/unit/agents/io/api/actuators/health/test_health_cache.py @@ -314,3 +314,19 @@ async def test_it_is_reported_with_no_checks_registered_at_all(self) -> None: cache, supervisor = await self._run(ReadinessPolicy.ALL, set(), []) assert (await cache.get_health_status()).namespaces["billing"].status == "DOWN" supervisor.observe.assert_awaited_once() + + +# --------------------------------------------------------------------------- +# A standalone agent logs what v0.8.1 logged +# --------------------------------------------------------------------------- + + +class TestStandaloneLogLines: + async def test_a_failing_check(self, caplog: pytest.LogCaptureFixture) -> None: + checker = MagicMock() + checker.health_check = AsyncMock(side_effect=RuntimeError("boom")) + cache = HealthCheckCache() + cache.set_health_entries([HealthCheckEntry(name="db", namespace="", checker=checker)]) + with caplog.at_level("WARNING", logger="blueprint.agents.io.api.actuators.health.health_cache"): + await cache._run_health_checks() + assert caplog.messages == ["Health check failed for db: boom"] diff --git a/tests/unit/agents/io/api/actuators/test_actuator_api.py b/tests/unit/agents/io/api/actuators/test_actuator_api.py index 1f440a20..6461dbc2 100644 --- a/tests/unit/agents/io/api/actuators/test_actuator_api.py +++ b/tests/unit/agents/io/api/actuators/test_actuator_api.py @@ -431,3 +431,25 @@ async def test_the_supervisor_knows_every_hosted_agent(self, mock_config: MagicM def test_there_is_no_supervisor_before_startup(self, actuator_api: ActuatorApi) -> None: """The gauges belong to per-agent providers, which the lifespan configures first.""" assert actuator_api.supervisor is None + + +# --------------------------------------------------------------------------- +# A standalone agent logs what v0.8.1 logged +# --------------------------------------------------------------------------- + + +class TestStandaloneReadinessLine: + async def test_the_failed_probe_line(self, actuator_api: ActuatorApi, mock_config: MagicMock, caplog: pytest.LogCaptureFixture) -> None: + from fastapi import HTTPException + + from blueprint.agents.models.api import ComponentHealth, ReadinessResponse + + mock_config.has_validation_errors = MagicMock(return_value=False) + components = {"cache": ComponentHealth(status="unhealthy", message="Redis unreachable")} + actuator_api._health_cache = MagicMock() + actuator_api._health_cache.get_health_status = AsyncMock(return_value=ReadinessResponse(status="DOWN", components=components)) + actuator_api._health_cache.get_cache_age_seconds = MagicMock(return_value=0.5) + + with caplog.at_level("WARNING"), pytest.raises(HTTPException): + await actuator_api.readiness_probe() + assert f"Readiness probe failed: {components}" in caplog.messages diff --git a/tests/unit/agents/io/api/eventing/test_nats.py b/tests/unit/agents/io/api/eventing/test_nats.py index 3a1202aa..b4bc7b5b 100644 --- a/tests/unit/agents/io/api/eventing/test_nats.py +++ b/tests/unit/agents/io/api/eventing/test_nats.py @@ -235,3 +235,39 @@ async def test_the_event_cannot_supply_it(self, nats_eventing: NatsEventing, pro await nats_eventing._make_event_callback("t.*.risk.>")(spoofed, "t.T1.risk.created") assert nats_eventing._process_cloud_event.await_args.args[1][NATS_SUBJECT_CONTEXT_KEY] == "t.T1.risk.created" + + +# --------------------------------------------------------------------------- +# A standalone agent logs what v0.8.1 logged +# --------------------------------------------------------------------------- + + +class TestStandaloneSubscriptionLines: + @staticmethod + def _wire(mock_registry: MagicMock, mock_config: MagicMock, topics: list[str]) -> None: + handler = MagicMock() + handler.get_subscribed_topics.return_value = topics + client = MagicMock() + client.subscribe = AsyncMock() + mock_registry.get_component.return_value = client + mock_registry.get_event_handler.return_value = [handler] if topics else [] + mock_config.get_nats_subscription_config.return_value = [] + + async def test_one_line_per_topic( + self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock, caplog: pytest.LogCaptureFixture + ) -> None: + self._wire(mock_registry, mock_config, ["a.created", "b.created"]) + with caplog.at_level("INFO", logger="blueprint.agents.io.api.eventing.nats"): + await nats_eventing.on_startup() + assert caplog.messages == [ + "NatsEventing: auto-subscribed to topic 'a.created'", + "NatsEventing: auto-subscribed to topic 'b.created'", + ] + + async def test_no_topics( + self, nats_eventing: NatsEventing, mock_registry: MagicMock, mock_config: MagicMock, caplog: pytest.LogCaptureFixture + ) -> None: + self._wire(mock_registry, mock_config, []) + with caplog.at_level("INFO", logger="blueprint.agents.io.api.eventing.nats"): + await nats_eventing.on_startup() + assert caplog.messages == ["NatsEventing: no auto-subscriptions configured"] From 65bf410df25b6a6c59019d7638182f6bf432b427 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 25 Sep 2026 12:37:06 +0200 Subject: [PATCH 061/133] fix(config): let a standalone agent read hostname, pod_name and blueprint_group Config.get() refused the deployment identity keys on every Config; v0.8.1 returned them. The refusal now applies only to a namespace view, where the keys would otherwise read a value that is not the agent's own. Records the two intended breaking changes in the changelog: Config() no longer configures logging, and Config.settings is read-only. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 9 +++++++++ ...2026-08-28-multi-agent-grouping-changelog.md | 14 ++++++++++++++ src/blueprint/agents/config/config.py | 13 ++++++++----- tests/unit/agents/config/test_envvar_prefix.py | 15 ++++++++++++--- .../unit/agents/config/test_namespace_views.py | 17 +++++++++-------- 5 files changed, 52 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bf64bd17..83e34502 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,9 @@ ### Fixed +- **A standalone agent's `Config` reads `hostname`, `pod_name` and `blueprint_group` again.** Since + the 0.9 alphas, `get()` raised for these keys everywhere. The refusal exists so that an agent in a + group cannot depend on where it runs; it now applies only to an agent's view in a group. - **A standalone agent logs what it logged before the namespace feature.** Log lines and error messages that existed in 0.8.1 had been reworded for groups, with `` standing in for a standalone agent's empty namespace -- e.g. `Eventing component startup completed`, @@ -392,6 +395,12 @@ Full migration path, including the one decision to get right before the first de `Component.reset_shared_state()`** in its fixtures; this also clears `shared_registry`, which stays public and is otherwise unaffected. A project that never resets shared state between builds is unaffected. +15. **`Config()` no longer configures logging.** Constructing a `Config` used to set up the root + logger; library code must not, so `AppBuilder` does it now. A script or test that builds only a + `Config` and relied on its logging setup has to configure logging itself. +16. **`Config.settings` is read-only.** It was a plain attribute; assigning to it now raises + `AttributeError`. Replacing the settings tree underneath a running configuration bypasses every + agent's view of it and is not supported. ### Fixed diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 59258a74..fd193e63 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7807,6 +7807,20 @@ Guarded by `test_standalone_log_lines.py` (6 cases, including "building a standa health cache and actuator tests (10 cases); all 16 fail against the previous code. No existing test had pinned any of these lines, which is how they changed unnoticed. +**`Config` behaviour, decided with the user.** `get("hostname" / "pod_name" / "blueprint_group")` +raised `ValueError` on every configuration since the deployment-identity blocklist (C6). The user +asked what those keys have to do with namespaces: nothing directly -- C6 keeps an agent from +knowing *where* it runs, and the pod keys were blocked alongside the group because the connection +name uses them. For a standalone agent there is no group to keep out of reach, and with the default +prefix the keys are ordinary settings anyway. `Config.get` now refuses them only on a view +(`self._is_view`), which is what agent code in a group holds; the process's own configuration -- +a standalone agent's and the framework's -- reads them as in v0.8.1. Tests: the refusal cases now go +through a view, plus a case that the process configuration reads all three and, with the prefix +disabled, a standalone agent reading the environment value. `reference/configuration-keys.md` +says so, and its connection-name paragraph, stale since the pod-only change, is corrected. +The two other `Config` changes stay, as breaking changes 15 and 16 in `CHANGELOG.md` [0.9.0]: +`Config()` no longer configures logging, and `Config.settings` is read-only. + **Not restored -- listed for the user, not worked around:** the Dapr degraded reason, the behaviour changes of the transport fixes, `Config` behaviour changes, the scheduler line, and the new outputs (metrics, span and resource attributes, new log lines). diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index cb83fe9e..d5d41719 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -987,12 +987,15 @@ def get(self, key: str, default: Any = None) -> Any: """Get a configuration value, scope-aware when ``agent_scope`` is set. Raises: - ValueError: for a key in :data:`DEPLOYMENT_IDENTITY_KEYS`. Raised rather than answered - with ``None``, because ``None`` reads as "not configured" and would send the caller - hunting for a missing setting instead of telling them the value is deliberately out - of reach (C6). Every typed getter funnels through here, so one check covers them all. + ValueError: for a key in :data:`DEPLOYMENT_IDENTITY_KEYS`, **asked through an agent's view**. + Raised rather than answered with ``None``, because ``None`` reads as "not configured" + and would send the caller hunting for a missing setting instead of telling them the + value is deliberately out of reach (C6). Every typed getter funnels through here, so + one check covers them all. The process's own configuration -- a standalone agent's, + and the framework's -- reads these keys as it always could: there is no group to be + kept out of reach of, and refusing them changed what a standalone agent could read. """ - if key.lower() in DEPLOYMENT_IDENTITY_KEYS: + if self._is_view and key.lower() in DEPLOYMENT_IDENTITY_KEYS: raise ValueError( f"'{key}' is deployment identity, not configuration, and is deliberately unreadable through " "Config (C6): code that can read the group or the pod can be written to depend on them, and " diff --git a/tests/unit/agents/config/test_envvar_prefix.py b/tests/unit/agents/config/test_envvar_prefix.py index 23b5e6d3..2413b2a3 100644 --- a/tests/unit/agents/config/test_envvar_prefix.py +++ b/tests/unit/agents/config/test_envvar_prefix.py @@ -131,13 +131,22 @@ def test_an_unprefixed_variable_resolves(self, settings_file: Path, monkeypatch: assert load(settings_file).get("model_name") == "bare" @pytest.mark.parametrize("key", sorted(DEPLOYMENT_IDENTITY_KEYS)) - def test_deployment_identity_stays_unreadable(self, settings_file: Path, monkeypatch: pytest.MonkeyPatch, key: str) -> None: - """The whole process environment is now in the tree -- C6 is what keeps identity out of reach.""" + def test_deployment_identity_stays_unreadable_for_an_agent( + self, settings_file: Path, monkeypatch: pytest.MonkeyPatch, key: str + ) -> None: + """The whole process environment is now in the tree -- C6 is what keeps identity out of an agent's reach.""" monkeypatch.setenv(ENVVAR_PREFIX_OVERRIDE, "false") monkeypatch.setenv(key.upper(), "leaked") config = load(settings_file) with pytest.raises(ValueError, match="deployment identity"): - config.get(key) + config.for_namespace("orders").get(key) + + @pytest.mark.parametrize("key", sorted(DEPLOYMENT_IDENTITY_KEYS)) + def test_a_standalone_agent_reads_it(self, settings_file: Path, monkeypatch: pytest.MonkeyPatch, key: str) -> None: + """No group, nothing to keep out of reach: unprefixed means the whole environment.""" + monkeypatch.setenv(ENVVAR_PREFIX_OVERRIDE, "false") + monkeypatch.setenv(key.upper(), "visible") + assert load(settings_file).get(key) == "visible" class TestRejections: diff --git a/tests/unit/agents/config/test_namespace_views.py b/tests/unit/agents/config/test_namespace_views.py index 7e849d6e..c87604d0 100644 --- a/tests/unit/agents/config/test_namespace_views.py +++ b/tests/unit/agents/config/test_namespace_views.py @@ -98,22 +98,23 @@ class TestDeploymentIdentityIsNotConfiguration: """C6 -- agent code that can read its group can be written to depend on it.""" @pytest.mark.parametrize("key", sorted(DEPLOYMENT_IDENTITY_KEYS)) - def test_deployment_keys_are_refused(self, two_agent_config: Config, key: str) -> None: + def test_deployment_keys_are_refused_to_an_agent(self, two_agent_config: Config, key: str) -> None: with pytest.raises(ValueError, match="deployment identity"): - two_agent_config.get(key) - - def test_the_refusal_holds_for_a_view(self, two_agent_config: Config) -> None: - with pytest.raises(ValueError, match="deployment identity"): - two_agent_config.for_namespace("orders").get("BLUEPRINT_GROUP") + two_agent_config.for_namespace("orders").get(key) def test_the_check_is_case_insensitive(self, two_agent_config: Config) -> None: with pytest.raises(ValueError, match="deployment identity"): - two_agent_config.get("Pod_Name") + two_agent_config.for_namespace("orders").get("Pod_Name") def test_it_raises_rather_than_answering_none(self, two_agent_config: Config) -> None: """None would read as 'not configured' and send the caller hunting for a missing key.""" with pytest.raises(ValueError): - two_agent_config.get("hostname", "a-default") + two_agent_config.for_namespace("orders").get("hostname", "a-default") + + @pytest.mark.parametrize("key", sorted(DEPLOYMENT_IDENTITY_KEYS)) + def test_the_process_configuration_reads_them_as_before(self, two_agent_config: Config, key: str) -> None: + """A standalone agent's configuration -- and the framework's -- is not a view; nothing is refused.""" + assert two_agent_config.get(key, "a-default") == "a-default" def test_an_ordinary_key_is_unaffected(self, two_agent_config: Config) -> None: assert two_agent_config.get("app_name") == "root-app" From 3200e12339f4078f8f54f199c5d11cf926155d36 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 25 Sep 2026 12:43:24 +0200 Subject: [PATCH 062/133] fix(nats): name a standalone agent's connection after its pod alone A standalone agent's NATS connection was named "..", implying a namespace and a group that do not exist for it. It is now named after the pod alone, and left unnamed -- as in v0.8.1 -- when the pod cannot be told either. A grouped agent keeps "..". The spec's section 6 records the standalone exception. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 4 ++ ...26-08-28-multi-agent-grouping-changelog.md | 11 ++++ docs/specs/2026-08-28-multi-agent-grouping.md | 5 ++ .../agent_generator/docs/guides/deployment.md | 4 +- .../docs/reference/configuration-keys.md | 12 +++-- .../agents/clients/io/nats_client.py | 17 +++++-- .../agents/clients/io/test_nats_client.py | 50 +++++++++++++++---- 7 files changed, 85 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 83e34502..8a04294e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ - **A standalone agent's `Config` reads `hostname`, `pod_name` and `blueprint_group` again.** Since the 0.9 alphas, `get()` raised for these keys everywhere. The refusal exists so that an agent in a group cannot depend on where it runs; it now applies only to an agent's view in a group. +- **A standalone agent's NATS connection is named after its pod alone.** It was named + `..`, implying a namespace and a group that do not exist for it. Before the + namespace feature it sent no name; now it sends the pod (or host) name, and none if that cannot + be determined. Agents in a group keep `..`. - **A standalone agent logs what it logged before the namespace feature.** Log lines and error messages that existed in 0.8.1 had been reworded for groups, with `` standing in for a standalone agent's empty namespace -- e.g. `Eventing component startup completed`, diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index fd193e63..d93674d9 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7807,6 +7807,17 @@ Guarded by `test_standalone_log_lines.py` (6 cases, including "building a standa health cache and actuator tests (10 cases); all 16 fail against the previous code. No existing test had pinned any of these lines, which is how they changed unnoticed. +**The NATS connection name, decided with the user.** v0.8.1 sent none; the feature named every +connection `f"{namespace}.{group}.{pod}"`, so a standalone agent appeared in `/connz` as +`..`. The user chose to keep a name -- more information is good -- but not to +imply a group where none exists. `NATSClient._resolve_connection_name` now returns the pod alone +when the namespace is `""` and `BLUEPRINT_GROUP` is unset, and `""` when the pod is unknown too; +`connect()` passes `name=self._connection_name or None`, so the latter sends no name, as v0.8.1 did. +The root of a grouped process keeps the full form, since its group exists. Spec sec. 6 is amended +with the exception; `reference/configuration-keys.md` and `guides/deployment.md` say so. The +connection-name tests were rewritten for the standalone case and one added for the namespaced form +with placeholders. + **`Config` behaviour, decided with the user.** `get("hostname" / "pod_name" / "blueprint_group")` raised `ValueError` on every configuration since the deployment-identity blocklist (C6). The user asked what those keys have to do with namespaces: nothing directly -- C6 keeps an agent from diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md index 5300ed47..eac4c16c 100644 --- a/docs/specs/2026-08-28-multi-agent-grouping.md +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -432,6 +432,11 @@ deployment may have no access to. The cost argument above justifies a connection that uses one*; it does not justify one per namespace that does not. Connection name **MUST** be `f"{namespace}.{group}.{pod}"`, and **MUST NOT** feed C1 naming. +**Exception -- a standalone agent** (namespace `""` and no `BLUEPRINT_GROUP`): the name **MUST** be +the pod alone, and **MUST** be omitted when the pod cannot be determined. Neither a namespace nor a +group exists for it, and `..` would imply a grouping that is not there; an +omitted name is what a standalone agent sent before this feature. The root of a *grouped* process +keeps the full form. An absent segment **MUST** be filled with a placeholder rather than left empty -- `` for the root namespace, `` for an unset `BLUEPRINT_GROUP`, `` when the replica cannot be identified -- so all three positions always carry a value, a name never degenerates into diff --git a/src/blueprint/agent_generator/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md index effc6c8d..25498728 100644 --- a/src/blueprint/agent_generator/docs/guides/deployment.md +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -272,8 +272,8 @@ spec: ``` `POD_NAME` is worth injecting: the framework reads it for the telemetry `service.instance.id` and -for the NATS connection name (`..`), which is what makes "which replica did -that" answerable from the broker's own connection list. +for the NATS connection name (`..`; a standalone agent's is the pod alone), which +is what makes "which replica did that" answerable from the broker's own connection list. ### The group file as a ConfigMap diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index f1b38f2a..d7117e84 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -62,13 +62,19 @@ change which broker-side consumer it is. | Variable | Default | Description | |-----|---------|-------------| -| `BLUEPRINT_GROUP` | `` in the connection name | Deployment group this process was started as. Appears in the middle position of the NATS connection name. | +| `BLUEPRINT_GROUP` | `` in the connection name | Deployment group this process was started as. Appears in the middle position of the NATS connection name, which is `..`. A standalone agent -- no namespace, no group -- is named after its pod alone, and sends no name if the pod cannot be determined. | | `POD_NAME` | -- | Replica identity, preferred over `HOSTNAME` because a deployment can set it explicitly through the Kubernetes downward API. Appears in the last position of the connection name. | | `HOSTNAME` | the host name, else `` | Used when `POD_NAME` is unset; the kubelet sets it to the pod name. | Every NATS connection is named `..`, which is what makes a pod's -contents legible in the broker's `/connz` output. The namespace segment is `` for an -application that never names one -- that is, for every single-agent application. +contents legible in the broker's `/connz` output. A single-agent application -- no namespace and no +group -- is named after its pod alone, and sends no name if the pod cannot be determined; the root +of a grouped process is `..`. + +These variables are read by the framework, not through `Config`. An agent in a group cannot read +`blueprint_group`, `pod_name` or `hostname` through its configuration -- `get()` raises -- so that no +agent can be written to depend on where it runs. A single-agent application's configuration reads +them like any other key. An absent value becomes a bracketed placeholder rather than an empty segment, so a name never degenerates into `..pod-7`. The brackets are not decoration: they are excluded from the namespace diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 69c73072..d87eac7b 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -22,7 +22,7 @@ from opentelemetry.metrics import Counter from ...component.namespace import ROOT_LABEL, ROOT_NAMESPACE -from ...deployment import deployment_group, pod_identity +from ...deployment import UNGROUPED_LABEL, UNKNOWN_POD_LABEL, deployment_group, pod_identity from ...io.telemetry.providers import agent_meter from ...models.api import ComponentHealth from ...models.errors import DeliveryDisposition, disposition_for @@ -599,13 +599,22 @@ def _resolve_connection_name(self) -> str: absent, so the name cannot degenerate into ``"..pod-7"`` and "no group" stays distinguishable from "a group whose name is empty". + **A standalone agent is named after its pod alone** -- no namespace and no group set. + Neither exists for it, and a name reading ``..pod`` would imply a + grouping that is not there. If the pod cannot be told either, no name is sent at all, + as before the namespace feature, rather than a name made only of a placeholder. The + root of a *grouped* process keeps the full form: its group exists. + **This value must never reach the queue group or the durable name.** It contains the pod, so a consumer identity derived from it would change on every restart and on every regrouping, which is precisely what C1 forbids. It is deliberately not stored anywhere those two are resolved from. """ - namespace = self.namespace or ROOT_LABEL - return f"{namespace}.{deployment_group()}.{pod_identity()}" + group = deployment_group() + pod = pod_identity() + if not self.namespace and group == UNGROUPED_LABEL: + return "" if pod == UNKNOWN_POD_LABEL else pod + return f"{self.namespace or ROOT_LABEL}.{group}.{pod}" # ------------------------------------------------------------------ # Connection @@ -768,7 +777,7 @@ async def connect(self) -> None: try: self._nats_client = await nats.connect( self._nats_url, - name=self._connection_name, + name=self._connection_name or None, max_reconnect_attempts=self.config.get("nats_max_reconnect_attempts", 5), reconnect_time_wait=self.config.get("nats_reconnect_time_wait", 2), connect_timeout=10, diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index 168ad959..61e1d8e1 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -1689,28 +1689,34 @@ def test_empty_namespace_is_named_rather_than_left_blank(self, nats_client: NATS monkeypatch.setenv("POD_NAME", "pod-1") assert nats_client._resolve_connection_name() == ".billing.pod-1" - def test_unset_group_is_named_rather_than_left_blank(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + def test_a_standalone_agent_is_named_after_its_pod_alone(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + """No namespace and no group exist for it, so the name implies neither.""" monkeypatch.delenv("BLUEPRINT_GROUP", raising=False) monkeypatch.setenv("POD_NAME", "pod-1") - assert nats_client._resolve_connection_name() == "..pod-1" + assert nats_client._resolve_connection_name() == "pod-1" def test_pod_name_wins_over_hostname(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("BLUEPRINT_GROUP", raising=False) monkeypatch.setenv("POD_NAME", "from-downward-api") monkeypatch.setenv("HOSTNAME", "from-kubelet") - assert nats_client._resolve_connection_name().endswith(".from-downward-api") + assert nats_client._resolve_connection_name() == "from-downward-api" def test_hostname_is_used_when_pod_name_is_absent(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("BLUEPRINT_GROUP", raising=False) monkeypatch.delenv("POD_NAME", raising=False) monkeypatch.setenv("HOSTNAME", "from-kubelet") - assert nats_client._resolve_connection_name().endswith(".from-kubelet") + assert nats_client._resolve_connection_name() == "from-kubelet" def test_falls_back_to_the_host_name(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("BLUEPRINT_GROUP", raising=False) monkeypatch.delenv("POD_NAME", raising=False) monkeypatch.delenv("HOSTNAME", raising=False) monkeypatch.setattr("blueprint.agents.deployment.socket.gethostname", lambda: "laptop") - assert nats_client._resolve_connection_name().endswith(".laptop") + assert nats_client._resolve_connection_name() == "laptop" - def test_unresolvable_host_still_yields_a_name(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + def test_an_unresolvable_host_sends_no_name_when_standalone(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + """Not a name made only of a placeholder: nothing, as before the namespace feature.""" + monkeypatch.delenv("BLUEPRINT_GROUP", raising=False) monkeypatch.delenv("POD_NAME", raising=False) monkeypatch.delenv("HOSTNAME", raising=False) @@ -1718,7 +1724,33 @@ def _raise() -> str: raise OSError("no host name") monkeypatch.setattr("blueprint.agents.deployment.socket.gethostname", _raise) - assert nats_client._resolve_connection_name().endswith(".") + assert nats_client._resolve_connection_name() == "" + + async def test_no_name_reaches_nats_then(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("BLUEPRINT_GROUP", raising=False) + monkeypatch.delenv("POD_NAME", raising=False) + monkeypatch.delenv("HOSTNAME", raising=False) + + def _raise() -> str: + raise OSError("no host name") + + monkeypatch.setattr("blueprint.agents.deployment.socket.gethostname", _raise) + with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock) as mock_connect: + mock_connect.return_value = MagicMock(is_closed=False, is_connected=True) + await nats_client.connect() + assert mock_connect.call_args[1]["name"] is None + + def test_an_agent_with_a_namespace_keeps_every_position(self, mock_config: MagicMock, monkeypatch: pytest.MonkeyPatch) -> None: + """The spec's form, placeholders included, wherever a namespace or a group exists.""" + monkeypatch.delenv("BLUEPRINT_GROUP", raising=False) + monkeypatch.delenv("POD_NAME", raising=False) + monkeypatch.delenv("HOSTNAME", raising=False) + + def _raise() -> str: + raise OSError("no host name") + + monkeypatch.setattr("blueprint.agents.deployment.socket.gethostname", _raise) + assert _namespaced_client(mock_config, "orders")._resolve_connection_name() == "orders.." def test_a_dotted_group_cannot_add_a_segment(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: """Four segments would misattribute the connection; the name is three by construction.""" @@ -1734,10 +1766,10 @@ def test_a_group_cannot_forge_a_placeholder(self, nats_client: NATSClient, monke monkeypatch.setenv("POD_NAME", "pod-1") assert nats_client._resolve_connection_name() == "._ungrouped_.pod-1" - def test_an_fqdn_hostname_stays_one_segment(self, nats_client: NATSClient, monkeypatch: pytest.MonkeyPatch) -> None: + def test_an_fqdn_hostname_stays_one_segment(self, mock_config: MagicMock, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.delenv("POD_NAME", raising=False) monkeypatch.setenv("HOSTNAME", "web-7.eu.internal") - name = nats_client._resolve_connection_name() + name = _namespaced_client(mock_config, "orders")._resolve_connection_name() assert name.endswith(".web-7_eu_internal") assert name.count(".") == 2 From 94043c2f893ff43555fa1240da16d5b5ed6b5964 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 25 Sep 2026 12:45:27 +0200 Subject: [PATCH 063/133] fix(actuator): give a standalone agent's readiness and env payloads their v0.8.1 shape /health/ready carries policy and namespaces, and /status/env carries namespaces, only when the process hosts a group. A standalone agent's payloads are keyed exactly as in v0.8.1 again; the fields are optional and excluded from the JSON when unset, so no key appears as null. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 5 ++ ...26-08-28-multi-agent-grouping-changelog.md | 22 +++++ .../docs/concepts/observability.md | 3 + .../agent_generator/docs/guides/deployment.md | 4 +- .../agent_generator/docs/guides/testing.md | 7 +- .../agents/io/api/actuators/actuator_api.py | 24 +++-- .../io/api/actuators/health/health_cache.py | 11 ++- src/blueprint/agents/models/api.py | 18 ++-- src/blueprint/agents/models/status.py | 8 +- .../app_builder/test_standalone_readiness.py | 89 +++++++++++++++++++ .../io/api/actuators/test_actuator_api.py | 7 +- 11 files changed, 171 insertions(+), 27 deletions(-) create mode 100644 tests/unit/agents/app_builder/test_standalone_readiness.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a04294e..5b88c31f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ - **A standalone agent's `Config` reads `hostname`, `pod_name` and `blueprint_group` again.** Since the 0.9 alphas, `get()` raised for these keys everywhere. The refusal exists so that an agent in a group cannot depend on where it runs; it now applies only to an agent's view in a group. +- **A standalone agent's `/health/ready` has its original shape again.** The body gained `policy` + and a `namespaces` section keyed `""`, which describe the agents of a group. They now appear + only when the process hosts a group; a standalone agent gets `status` and `components`, as before. + The same holds for `/status/env`: its `namespaces` breakdown appears only in a group (the new + `envvar_prefix` field stays), and its log line is the 0.8.1 one for a standalone agent. - **A standalone agent's NATS connection is named after its pod alone.** It was named `..`, implying a namespace and a group that do not exist for it. Before the namespace feature it sent no name; now it sends the pod (or host) name, and none if that cannot diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index d93674d9..0e164418 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7818,6 +7818,28 @@ with the exception; `reference/configuration-keys.md` and `guides/deployment.md` connection-name tests were rewritten for the standalone case and one added for the namespaced form with placeholders. +**`/health/ready`, decided with the user:** "a `namespaces` key only in a group". `ReadinessResponse.policy` +and `.namespaces` are now `None` by default with `Field(exclude_if=lambda value: value is None)`, so +they are omitted from the JSON and from the 503 `detail` (`model_dump`) when unset -- without +`exclude_none` on the route, which would also drop the `null` values inside `components` that +v0.8.1 returned. `HealthCheckCache` sets both only when a namespace besides the root is supervised +(`self._grouped`). `policy` goes with `namespaces` under the same rule: it decides between agents, +and a standalone process has none. Nothing needed flattening: for a standalone agent the root's +entry repeats the top-level `status`, `failing` is derivable from `components`, `critical` is always +true, and `reason` is only ever set for a latched non-critical agent. Guarded by +`test_standalone_readiness.py` over HTTP through the real lifespan (keys, a `null` inside +`components` kept, and the group form). `guides/testing.md` had an example asserting +`namespaces[""]` for a single-agent application; corrected, and the two payload +descriptions say when the fields appear. + +**`/status/env`, same rule:** `EnvironmentStatus.namespaces` is `None` by default with `exclude_if`, +and `env_status` fills it only when the application's own configuration hosts namespaces -- so a +standalone agent's response has no `namespaces` key, where it had `{}`. `envvar_prefix` stays, as the +user decided: it is new and not about groups. The log line is the v0.8.1 one ("Returning environment +status for env ") for a standalone agent with the default prefix, keeps the override source +for a custom prefix, and adds the namespace count only in a group. Two env-status tests expected +`{}` and now expect no key; `test_standalone_readiness.py` checks the key is absent over HTTP. + **`Config` behaviour, decided with the user.** `get("hostname" / "pod_name" / "blueprint_group")` raised `ValueError` on every configuration since the deployment-identity blocklist (C6). The user asked what those keys have to do with namespaces: nothing directly -- C6 keeps an agent from diff --git a/src/blueprint/agent_generator/docs/concepts/observability.md b/src/blueprint/agent_generator/docs/concepts/observability.md index ae31e1ba..1e602bfb 100644 --- a/src/blueprint/agent_generator/docs/concepts/observability.md +++ b/src/blueprint/agent_generator/docs/concepts/observability.md @@ -194,6 +194,9 @@ single-agent payload's keys are unchanged. `namespaces` exists because the polic no longer derivable from `components`: the pod above answers `UP` with a failing check in it, and without the per-agent section that reads as a contradiction. +**`policy` and `namespaces` appear only when the process hosts a group.** A standalone agent's +payload is `status` and `components`, exactly as before agents existed. + ### Custom health checks A checker is an object implementing `HealthCheckerBase`, not a callable: diff --git a/src/blueprint/agent_generator/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md index 25498728..0549bc2d 100644 --- a/src/blueprint/agent_generator/docs/guides/deployment.md +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -541,7 +541,9 @@ single-agent application is entirely root. `components` is keyed by entry name -- bare at the root, `.` for an agent -- so a single-agent payload's keys are unchanged. `namespaces` exists because the policy makes `status` no -longer derivable from `components`: the pod above answers `UP` with a failing check in it. +longer derivable from `components`: the pod above answers `UP` with a failing check in it. Both +`policy` and `namespaces` appear only when the process hosts a group; a standalone agent's payload +is `status` and `components`. ### Broker startup diff --git a/src/blueprint/agent_generator/docs/guides/testing.md b/src/blueprint/agent_generator/docs/guides/testing.md index de35afe1..71b65bb3 100644 --- a/src/blueprint/agent_generator/docs/guides/testing.md +++ b/src/blueprint/agent_generator/docs/guides/testing.md @@ -305,10 +305,11 @@ class TestAppIntegration: assert data["status"] == "UP" assert "components" in data - async def test_readiness_reports_each_agent(self, client): - # One entry per agent the process hosts, "" for a single-agent application. + async def test_readiness_has_no_group_fields(self, client): + # A standalone agent's payload is status and components; "policy" and "namespaces" + # appear only when the process hosts a group of agents. response = await client.get("/health/ready") - assert response.json()["namespaces"][""]["status"] == "UP" + assert set(response.json()) == {"status", "components"} ``` ### Testing Endpoint Behavior diff --git a/src/blueprint/agents/io/api/actuators/actuator_api.py b/src/blueprint/agents/io/api/actuators/actuator_api.py index 75a31050..75f78391 100644 --- a/src/blueprint/agents/io/api/actuators/actuator_api.py +++ b/src/blueprint/agents/io/api/actuators/actuator_api.py @@ -17,6 +17,7 @@ from ....component.namespace import ROOT_NAMESPACE from ....component.registry import Registry from ....config import Config +from ....config.config import DEFAULT_ENVVAR_PREFIX from ....models.api import LivenessResponse, ReadinessResponse from ....models.status import BuildStatus, EnvironmentStatus, LLMStatus, ServiceInfo, VLLMInfo from .health.health_cache import HealthCheckCache @@ -293,16 +294,23 @@ async def env_status(self) -> EnvironmentStatus: # The per-agent breakdown is the operator's view of the whole process, so it exists only # on the application's own configuration. Listing neighbours from inside an agent is the # thing C6 exists to prevent, and `config.namespaces` refuses on a view for that reason. - namespaces: dict[str, dict[str, Any]] = {} - if not config.is_view: + # It exists only for a group, too: a standalone agent's response has no "namespaces" key. + namespaces: dict[str, dict[str, Any]] | None = None + if not config.is_view and config.namespaces: namespaces = {name: self._sanitize_config(config.resolved_settings(name)) for name in config.namespaces} - logger.info( - "Returning environment status for env %s (%d namespace(s), overrides read from %s)", - environment, - len(namespaces), - f"{config.envvar_prefix}_*" if config.envvar_prefix else "the whole process environment, unprefixed", - ) + overrides = f"{config.envvar_prefix}_*" if config.envvar_prefix else "the whole process environment, unprefixed" + if namespaces is not None: + logger.info( + "Returning environment status for env %s (%d namespace(s), overrides read from %s)", + environment, + len(namespaces), + overrides, + ) + elif config.envvar_prefix == DEFAULT_ENVVAR_PREFIX: + logger.info("Returning environment status for env %s", environment) + else: + logger.info("Returning environment status for env %s (overrides read from %s)", environment, overrides) return EnvironmentStatus( environment=environment, diff --git a/src/blueprint/agents/io/api/actuators/health/health_cache.py b/src/blueprint/agents/io/api/actuators/health/health_cache.py index 02789076..c881396c 100644 --- a/src/blueprint/agents/io/api/actuators/health/health_cache.py +++ b/src/blueprint/agents/io/api/actuators/health/health_cache.py @@ -61,10 +61,15 @@ def __init__( self._scheduler: AsyncIOScheduler | None = None self._policy = policy self._supervisor = supervisor + # A group's payload says which policy decides and how each agent stands; a standalone + # agent's has neither, as before agents existed. Decided by whether any namespace besides + # the root is supervised. + self._grouped = supervisor is not None and any(supervisor.status) self._cached_response: ReadinessResponse = ReadinessResponse( status=initial_status, components={}, - policy=policy.value, + policy=policy.value if self._grouped else None, + namespaces={} if self._grouped else None, ) self._last_update: datetime = datetime.now() self._lock = asyncio.Lock() @@ -179,8 +184,8 @@ async def _run_health_checks(self) -> None: self._cached_response = ReadinessResponse( status=overall_status, components=components, - policy=self._policy.value, - namespaces=namespaces, + policy=self._policy.value if self._grouped else None, + namespaces=namespaces if self._grouped else None, ) self._last_update = datetime.now() diff --git a/src/blueprint/agents/models/api.py b/src/blueprint/agents/models/api.py index f12c5ef9..f6f45903 100644 --- a/src/blueprint/agents/models/api.py +++ b/src/blueprint/agents/models/api.py @@ -223,14 +223,20 @@ class ReadinessResponse(BaseModel): ..., description="Health status of individual components.", ) - policy: str = Field( - default="all", - description="The readiness policy in force, which decides how a degraded agent affects the overall status.", + # Both are about the agents of a group, so both exist only in a group's payload. A standalone + # agent's response has exactly the shape it had before agents existed: status and components. + policy: str | None = Field( + default=None, + exclude_if=lambda value: value is None, + description="The readiness policy in force, which decides how a degraded agent affects the overall status. " + "Present only when the process hosts a group of agents.", examples=["all", "critical", "any"], ) - namespaces: dict[str, NamespaceReadiness] = Field( - default_factory=dict, - description="Per-agent health, keyed by agent name ('' for the root namespace).", + namespaces: dict[str, NamespaceReadiness] | None = Field( + default=None, + exclude_if=lambda value: value is None, + description="Per-agent health, keyed by agent name ('' for the root namespace). Present only when the " + "process hosts a group of agents.", ) model_config = ConfigDict( diff --git a/src/blueprint/agents/models/status.py b/src/blueprint/agents/models/status.py index 2272a3d7..d53302e3 100644 --- a/src/blueprint/agents/models/status.py +++ b/src/blueprint/agents/models/status.py @@ -46,11 +46,13 @@ class EnvironmentStatus(BaseModel): ..., description="Sanitized configuration the root namespace resolves.", ) - namespaces: dict[str, dict[str, Any]] = Field( - default_factory=dict, + namespaces: dict[str, dict[str, Any]] | None = Field( + default=None, + exclude_if=lambda value: value is None, description=( "Sanitized configuration each co-hosted agent resolves, flattened as that agent " - "reads it -- inherited root keys included. Empty for a single-agent service." + "reads it -- inherited root keys included. Present only when the process hosts a group " + "of agents." ), ) diff --git a/tests/unit/agents/app_builder/test_standalone_readiness.py b/tests/unit/agents/app_builder/test_standalone_readiness.py new file mode 100644 index 00000000..d3f5fabd --- /dev/null +++ b/tests/unit/agents/app_builder/test_standalone_readiness.py @@ -0,0 +1,89 @@ +"""A standalone agent's ``/health/ready`` has the shape it had before the namespace feature. + +``policy`` and ``namespaces`` describe the agents of a group. A process that hosts no group gets +neither -- only ``status`` and ``components``, as in v0.8.1. Driven over HTTP through the real +lifespan, because what matters is the JSON a probe or a dashboard actually receives. +""" + +from collections.abc import Iterator +from pathlib import Path + +import httpx +import pytest + +from blueprint.agents.app_builder import AppBuilder +from blueprint.agents.component.namespace import namespace_scope +from blueprint.agents.config import Config +from blueprint.agents.io.api.actuators.health import HealthCheckerBase +from blueprint.agents.io.telemetry.providers import reset_providers +from blueprint.agents.models.api import ComponentHealth +from blueprint.agents.services.service_base import ServiceBase + + +class SilentCheck(HealthCheckerBase): + """A healthy check without a message, so the payload carries a ``null`` that must survive.""" + + async def health_check(self) -> ComponentHealth: + return ComponentHealth(status="healthy", message=None) + + +class QuietService(ServiceBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + +@pytest.fixture(autouse=True) +def _forget_providers() -> Iterator[None]: + reset_providers() + yield + reset_providers() + + +@pytest.fixture +def config(tmp_path: Path) -> Config: + settings = tmp_path / "settings.toml" + settings.write_text('[development]\napp_name = "standalone"\napp_port = 8000\napp_environment = "development"\n') + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + +async def _ready(builder: AppBuilder) -> dict: + app = builder.build() + async with app.router.lifespan_context(app): + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: + response = await client.get("/health/ready") + assert response.status_code == 200 + return response.json() + + +async def test_a_standalone_agent_gets_status_and_components_only(config: Config) -> None: + body = await _ready(AppBuilder(config).with_health_checker("db", SilentCheck())) + assert set(body) == {"status", "components"} + + +async def test_a_null_inside_components_is_kept(config: Config) -> None: + """Only the two group fields are conditional; the rest serialises exactly as before.""" + body = await _ready(AppBuilder(config).with_health_checker("db", SilentCheck())) + assert body["components"]["db"] == {"status": "healthy", "message": None, "details": None} + + +async def test_a_group_gets_the_policy_and_its_agents(config: Config) -> None: + builder = AppBuilder(config) + builder.host_agent("orders", critical=True) + with namespace_scope("orders"): + builder.with_service(QuietService) + body = await _ready(builder) + assert body["policy"] == "all" + assert set(body["namespaces"]) == {"", "orders"} + + +async def test_status_env_has_no_namespaces_key_when_standalone(config: Config) -> None: + """The same rule for /status/env: the per-agent breakdown exists only in a group.""" + app = AppBuilder(config).build() + async with app.router.lifespan_context(app): + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: + response = await client.get("/status/env") + assert response.status_code == 200 + assert "namespaces" not in response.json() diff --git a/tests/unit/agents/io/api/actuators/test_actuator_api.py b/tests/unit/agents/io/api/actuators/test_actuator_api.py index 6461dbc2..4a9167da 100644 --- a/tests/unit/agents/io/api/actuators/test_actuator_api.py +++ b/tests/unit/agents/io/api/actuators/test_actuator_api.py @@ -267,9 +267,10 @@ def grouped_config(tmp_path: Path, mock_registry: MagicMock) -> Config: class TestEnvStatus: async def test_a_single_agent_service_reports_no_namespaces(self, grouped_config: Config) -> None: - """Nothing has asked for a view, so the response is shaped as it always was.""" + """Nothing has asked for a view, so the response is shaped as it always was -- no "namespaces" key.""" result = await ActuatorApi().env_status() - assert result.namespaces == {} + assert result.namespaces is None + assert "namespaces" not in result.model_dump(mode="json") assert result.settings["MODEL_NAME"] == "root-model" async def test_each_namespace_that_asked_for_config_is_reported(self, grouped_config: Config) -> None: @@ -338,7 +339,7 @@ async def test_an_agent_scoped_actuator_reports_only_its_own_scope(self, grouped result = await ActuatorApi().env_status() - assert result.namespaces == {} + assert result.namespaces is None # Its own scope: 'orders' overrides app_name, and this asserted the root's value until # the endpoint actually did what its comment claimed. assert result.settings["APP_NAME"] == "orders" From f6a65ec19ff1e1349d29d622e0e73e80be6fe02a Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 25 Sep 2026 12:47:24 +0200 Subject: [PATCH 064/133] fix(nats): make JetStream consumer settings opt-in and reuse 0.8 durables The framework set ack_wait 300 s, max_ack_pending 16 and max_deliver 5 on every consumer it created. Unset, each setting is now left to the server's default, as in v0.8.1; drift detection skips settings that are not configured, and an unset max_deliver counts as unlimited. A durable left by 0.8 (no deliver group) is used as it is -- recreating it would replay or gap -- and announced at startup with a DEPRECATED warning, since it cannot be shared by replicas. Integration tests pin that upgrade path against the real broker. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 33 +++++ ...26-08-28-multi-agent-grouping-changelog.md | 47 +++++++ .../docs/concepts/event-processing.md | 14 +- .../agent_generator/docs/guides/deployment.md | 29 +++-- .../docs/reference/configuration-keys.md | 7 +- .../agents/clients/io/nats_client.py | 83 ++++++++---- tests/integration/conftest.py | 2 +- tests/integration/docker-compose.yml | 4 +- tests/integration/test_upgrade_from_0_8.py | 121 ++++++++++++++++++ .../agents/clients/io/test_nats_client.py | 82 +++++++++++- 10 files changed, 372 insertions(+), 50 deletions(-) create mode 100644 tests/integration/test_upgrade_from_0_8.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b88c31f..77a4ad66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -207,6 +207,13 @@ unreachable at startup) by shutting the process down for the root or a critical agent and marking a non-critical one down. The previous fallback rarely triggered, and when it did it dropped durable consumers and acknowledgements without anyone deciding it. +- **JetStream consumer settings are opt-in again.** The framework set `ack_wait` 300 s, + `max_ack_pending` 16 and `max_deliver` 5 on every consumer it created, overriding the server's + defaults for deployments that had configured nothing. `nats_ack_wait`, `nats_max_ack_pending` and + `nats_max_deliver` are now applied only when set; unset, the server's default stands (NATS: 30 s, + 1000, unlimited). With `nats_max_deliver` unset, a message that keeps failing is retried without + limit and never dead-lettered, as before 0.9.0 -- set it to bound retries. Consumers that already + exist keep their settings, and an unset key is not reported as a difference. - **`ClientBase.subscribe()` callbacks take the delivery subject.** The contract is now `DeliveryCallback = Callable[[CloudEvent, str], Awaitable[None]]` (in `clients/client_base.py`): the event, then the subject it arrived on. Only code that calls `NATSClient.subscribe()` directly, @@ -288,6 +295,32 @@ ### Added - **`AppBuilder.build()` now sources `docs_url`/`redoc_url`/`openapi_url` from config** (#191, defaults unchanged: `/docs`, `/redoc`, `/openapi.json`). Previously these were hardcoded at `FastAPI()` construction, so a consumer could not disable the built-in `/docs` route without mutating `app.router.routes` after the fact — fragile because it depends on FastAPI's internal route-registration shape (bechtleav360/avs.ai.idac.service-sessions#191). Set `docs_url = "@none"` (Dynaconf's `None` cast) in `settings.toml` to opt out before the route is ever registered. Set at the root of `settings.toml`, not under an `agent_scope` block (`Config._scoped_get()` falls back to the root value when a scoped lookup is `None`). Note FastAPI only registers `docs_url`/`redoc_url` when `openapi_url` is also set, so disabling `openapi_url` disables all three. +### Deprecated + +- **JetStream consumers created before 0.9.** 0.8 left each durable delivering to a random inbox + with no deliver group, so only one replica can consume from it. Such a consumer is still found + under its name and used exactly as it is -- it is never recreated, which would replay or gap -- + but it is logged at startup as `DEPRECATED` and will not be supported in a future release. + Delete it during a maintenance window; the framework then recreates it so that every replica + shares it. + +### Upgrading a standalone agent from 0.8 + +What the broker sees change when an agent that ran on 0.8 starts on this version, with +`nats_use_jetstream = true`: + +- **Existing durables are reused**, found under the same name for a topic without `.`, `*`, `>` or + whitespace (`orders` -> `orders-durable`), and announced as deprecated (above). For a topic with a + dot the name is now `orders_created-durable`; 0.8's `orders.created-durable` is a name the broker + refuses, so no such consumer can exist to be orphaned. +- **`nats_durable_name` with several topics fails startup.** 0.8 gave all of them one consumer, of + which only the first topic's subscription worked. +- **The stream is widened, never narrowed.** 0.8 created it over `.>` and never touched + it again; this version adds every subscribed topic, the dead-letter subject and, when publishing + through JetStream, the publish subjects. +- **Core NATS subscriptions join a queue group** (`nats_queue_group`, else `app_name`), so each + message reaches one replica instead of every one. + ## [0.9.0] - 2026-09-14 **Multi-agent grouping.** How many agents share a process becomes a *deployment* parameter rather diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 0e164418..2f3cf669 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7840,6 +7840,53 @@ status for env ") for a standalone agent with the default prefix, keeps the for a custom prefix, and adds the namespace count only in a group. Two env-status tests expected `{}` and now expect no key; `test_standalone_readiness.py` checks the key is absent over HTTP. +**JetStream consumer settings, decided with the user: "we do not change server defaults".** P1/P3 +made the framework set `ack_wait` 300 s, `max_ack_pending` 16 and `max_deliver` 5 on every consumer +it created; v0.8.1 left all three to the server. Now: + +- `ConsumerTuning.ack_wait`, `.max_ack_pending`, `.max_deliver` are `None` when not configured. + `_resolve_consumer_tuning` reads them through new `_read_optional_float` / `_read_optional_int` + and validates only configured values; the warning for an explicit `-1` stays. +- `_consumer_config` passes them as they are; nats-py leaves `max_deliver` and `max_ack_pending` out + and sends `ack_wait: 0`, which the server reads as its default (not verified against a broker). +- `_deliveries_exhausted` treats an unset `max_deliver` as unlimited -- the server's default -- so no + delivery is the last one and exhaustion never dead-letters. +- `_consumer_drift` ignores a setting the configuration leaves unset, so a consumer created by an + earlier alpha with 300 / 16 / 5 is not reported as drifting. + +Consequence, stated in the docs: unset `nats_max_deliver` means unlimited retries and no dead +letter on exhaustion, and dedup's TTL window needs it set. Docs: the three rows and the example in +`reference/configuration-keys.md`, `guides/deployment.md` (keys, the dedup window, scaling), the +disposition table in `concepts/event-processing.md`, and the class docstring. While there, fixed +`guides/deployment.md` still calling dedup "exists-then-set, not atomic", missed by the atomic-claim +change. Tests: the tuning-defaults test now expects `None`; new cases for a value left out of the +consumer, an unset `max_deliver` never exhausting, and an unset value not reported as drift; the +drift test sets `nats_ack_wait` so it still has a difference to report. + +**The durable consumer's creation and binding, decided with the user: keep it, reuse old durables, +deprecate them.** The user's worry was that the upgrade silently creates durables. It does not: +Core NATS stays the default, and under `nats_use_jetstream = true` v0.8.1 already created a +durable (`js.subscribe(topic, durable=f"{topic}-durable", manual_ack=True)`). What changed is the +form of a *new* durable -- a named `_DELIVER.` subject and a deliver group -- because the +v0.8.1 form can serve one replica: nats-py refuses a second `js.subscribe` to a push-bound consumer +without a deliver group ("consumer is already bound to a subscription"). An existing durable was +already left as it is by `_ensure_consumer`. New: when that existing consumer has no deliver group +-- the pre-0.9 form -- a `DEPRECATED` WARNING names it, its deliver subject, and the fix (delete it +in a maintenance window), and the missing deliver group is no longer also reported as drift +(`_consumer_drift(..., ignore=("deliver_group",))`). + +Unit tests: `test_a_pre_09_consumer_is_still_used_as_it_is` (no `add_consumer`, bound with the +broker's own config) and `test_a_pre_09_consumer_is_announced_as_deprecated` (one deprecation, no +drift line); the drift test now uses a consumer with a *different* deliver group. Integration +tests, `tests/integration/test_upgrade_from_0_8.py`, against the compose broker: a consumer created +exactly as 0.8 left it is used as it is (no second consumer, same deliver subject, no deliver +group, and it delivers), is announced as deprecated, and the broker (or nats-py) refuses a dotted +durable name -- which is why the dotted-topic rename orphans nothing. Not run here: no Docker in +this environment. `CHANGELOG.md` gains a Deprecated section and "Upgrading a standalone agent from +0.8" (reused durables, the dotted name, `nats_durable_name` with several topics, the widened +stream, the Core NATS queue group). Two stale comments fixed on the way: `integration_config`'s +"the framework default is 300" and `docker-compose.yml`'s "falls back to Core NATS". + **`Config` behaviour, decided with the user.** `get("hostname" / "pod_name" / "blueprint_group")` raised `ValueError` on every configuration since the deployment-identity blocklist (C6). The user asked what those keys have to do with namespaces: nothing directly -- C6 keeps an agent from diff --git a/src/blueprint/agent_generator/docs/concepts/event-processing.md b/src/blueprint/agent_generator/docs/concepts/event-processing.md index 487b5734..8b51675a 100644 --- a/src/blueprint/agent_generator/docs/concepts/event-processing.md +++ b/src/blueprint/agent_generator/docs/concepts/event-processing.md @@ -267,20 +267,28 @@ critical agent shuts the process down (SIGTERM to itself, so the other agents st non-critical agent is marked down until the pod restarts. A timeout on that request is not treated as an answer; it is retried like any other connection failure. +**A delivery is acknowledged only when its work is complete.** Complete means the handler chain +returned *and* every result it returned was published. Anything short of that is never an `ack`: +it is a `nak`, so the event is delivered again, or a dead letter when retrying cannot help. An +`ack` for work that did not finish would tell the broker the event is done while its outcome is +lost -- nothing redelivers it and nothing records it. + | Outcome | Disposition | |---------|-------------| -| The handler chain returned, including "no handler matched" | `ack` | +| The handler chain returned and every result was published, including "no handler matched" | `ack` | +| A result could not be published | `nak` -- the handler runs again on redelivery; with deduplication on, its marker is released first | | `RetryableHandlerError`, or any unexpected exception | `nak` -- redelivered after `nats_ack_wait` | | `InvalidEventError` or `CriticalHandlerError` | dead-lettered, then `term` | | The payload is not a parseable CloudEvent | dead-lettered, then `term` | -| The last delivery `nats_max_deliver` allows failed again | dead-lettered, then `term` | +| The last delivery `nats_max_deliver` allows failed again (only when `nats_max_deliver` is set) | dead-lettered, then `term` | Dead-lettering republishes the **original bytes**, unchanged, to `nats_dead_letter_subject`, with the reason, the original subject, the delivery count and the event id in headers. The subject is added to the stream when the framework provisions it, so dead letters are persisted rather than dropped on the floor, and consuming them is an ordinary subscription. -Two settings interact and are worth choosing together: +Two settings interact and are worth choosing together. The framework sets neither on its own -- +unset, each is the server's default: - **`nats_ack_wait` must exceed your slowest handler.** It is the broker's patience, not the client's: when it expires the message is redelivered to another replica while the first one is diff --git a/src/blueprint/agent_generator/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md index 0549bc2d..aeece582 100644 --- a/src/blueprint/agent_generator/docs/guides/deployment.md +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -339,12 +339,15 @@ scaling out and regrouping are independent of each other. Two keys to set deliberately: -- **`nats_ack_wait`** (default `300.0` seconds) must exceed your p99 handler duration. Set it below - that and the broker redelivers work that is still in progress, to a second replica. -- **`nats_max_ack_pending`** (default `16`) is the in-flight limit **across every replica sharing - the consumer**, not per replica. Scaling to eight replicas with the default gives you sixteen - concurrent messages in total, which is usually the reason throughput does not improve with pod - count. +Unset, each is the server's default: the framework sets no consumer setting on its own. + +- **`nats_ack_wait`** (server default: 30 s on NATS) must exceed your p99 handler duration. Set it + below that and the broker redelivers work that is still in progress, to a second replica. +- **`nats_max_ack_pending`** is the in-flight limit **across every replica sharing the consumer**, + not per replica. Set it deliberately: it decides how many messages all replicas together work on + at once. +- **`nats_max_deliver`** bounds retries. Unset it is unlimited, so a message that keeps failing is + retried forever and never dead-lettered. ### 3. Deduplication, if your handlers need it @@ -357,10 +360,11 @@ Two honest answers, and the framework will not choose for you: - set `idempotency_enabled = true` and `idempotency_ttl`. **The TTL must outlast the broker's redelivery window**, which is -`nats_ack_wait * nats_max_deliver`: +`nats_ack_wait * nats_max_deliver` -- so dedup needs `nats_max_deliver` set, since unlimited +retries have no window to outlast: ``` -300 s x 5 = 1500 s # the defaults +300 s x 5 = 1500 s # nats_ack_wait = 300, nats_max_deliver = 5 idempotency_ttl = 1800 # with headroom for clock skew and a slow restart ``` @@ -369,9 +373,8 @@ prevent. Too long only costs cache entries. If you raise `nats_ack_wait` or `nat raise this with them. Two limits to know: dedup needs the agent to declare `with_cache()` -- the marker lives in that -agent's own cache -- and `exists`-then-`set` is not atomic on either backend, so two replicas handed -the same event in the same instant can both dispatch. It closes the ordinary window, not every -window. +agent's own cache -- and the claim is atomic only across replicas that share that cache (Redis, or +a disk cache on a shared volume); a per-pod cache deduplicates within one pod. **Grouped Dapr is the exception that wants dedup on.** A group has one Dapr endpoint: it publishes the union of every agent's topics and fans each delivery out to the agents that declared it, and the @@ -417,8 +420,8 @@ spec: CPU is a poor signal for an event-driven agent that spends its time waiting on an LLM. Consumer lag or in-flight count is the metric you actually want to scale on, and reaching it needs a metrics -adapter. Raise `nats_max_ack_pending` before adding replicas: with the default, more pods share the -same sixteen in-flight messages. +adapter. Check `nats_max_ack_pending` before adding replicas: it limits the in-flight messages of all +pods together, so more pods under the same limit do not process more at once. --- diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index d7117e84..23541664 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -43,9 +43,9 @@ Settings for the event bus transport layer. | `nats_use_jetstream` | `bool` | `false` | Consume through a durable JetStream consumer instead of Core NATS. The keys below apply only when this is `true`. **A declaration, enforced:** with `true`, a server that does not offer JetStream to the account fails the agent -- at startup through the startup failure policy, or, if the broker was unreachable then, when it first connects: the root or a critical agent shuts the process down, a non-critical agent is marked down. There is no fallback to Core NATS. With `false`, the server is not asked; Core NATS works on a JetStream-enabled server too. | | `nats_stream_name` | `str` | `"EVENTS"` | Stream the durable consumers are created on. The framework creates it if it is missing, and widens an existing one to cover every subscribed subject plus the dead-letter subject; it never removes a subject. | | `nats_durable_name` | `str` | `"-durable"` | Name of the durable consumer. Derived from the topic by default, with `.`, `*`, `>` and whitespace replaced by `_` because NATS rejects them in a consumer name. A client that belongs to a namespace prefixes it (`"--durable"`), so two agents subscribing to the same topic get a consumer each. Setting it explicitly is only valid with a single subscribed topic: a durable filters one subject, and under a namespace it must be scoped per namespace or every namespace binds to the same consumer. | -| `nats_ack_wait` | `float` | `300.0` | Seconds the broker waits for an acknowledgement before redelivering. **Must exceed the p99 duration of your slowest handler**, or long inference is redelivered to another replica while the first is still working. The default is deliberately far above the NATS default of 30 s because handlers in this framework call models. | -| `nats_max_ack_pending` | `int` | `16` | Unacknowledged messages the consumer may have outstanding at once, counted across every replica sharing it. `-1` is unlimited. Keep it close to the number of replicas: a push subscription runs its callbacks one at a time, so anything much larger queues messages inside the client while their `nats_ack_wait` is already running down. | -| `nats_max_deliver` | `int` | `5` | Delivery attempts before the message is dead-lettered. `-1` is unlimited, which means a permanently failing message is retried forever and never dead-lettered; the client logs a warning at startup if you set it. | +| `nats_ack_wait` | `float` | unset -- the server's default (NATS: 30 s) | Seconds the broker waits for an acknowledgement before redelivering. **Must exceed the p99 duration of your slowest handler**, or long inference is redelivered to another replica while the first is still working. Handlers that call models usually need more than the NATS default, so set it. | +| `nats_max_ack_pending` | `int` | unset -- the server's default (NATS: 1000) | Unacknowledged messages the consumer may have outstanding at once, counted across every replica sharing it. `-1` is unlimited. Keep it close to the number of replicas: a push subscription runs its callbacks one at a time, so anything much larger queues messages inside the client while their `nats_ack_wait` is already running down. | +| `nats_max_deliver` | `int` | unset -- the server's default (NATS: unlimited) | Delivery attempts before the message is dead-lettered. Unlimited -- the default, or `-1` -- means a permanently failing message is retried forever and never dead-lettered; the client logs a warning at startup if you set `-1` explicitly. Set a positive limit to bound retries. | | `nats_dead_letter_subject` | `str` | `".dead-letter"` | Subject a message is republished to when the framework gives up on it -- either a terminal failure (`InvalidEventError`, `CriticalHandlerError`, or a payload that is not a CloudEvent) or `nats_max_deliver` attempts spent. The original bytes are republished unchanged, with `Blueprint-Dead-Letter-Reason`, `Blueprint-Original-Subject`, `Blueprint-Delivery-Count` and `Blueprint-Event-Id` headers. Set to `""` to disable, which drops those messages and loses their payloads. Startup fails if the subject is a wildcard or is itself one of the subscribed subjects, since that would loop. | **NATS authentication:** `nats_user`/`nats_password`, `nats_token`, `nats_creds_file`, `nats_nkey_seed` and credentials inside `nats_url` are alternatives -- configure at most one. Two at once fail startup rather than leaving the choice to the client library. All of them are read per agent, so a group can give each agent its own account with `[default.]` or `DYNACONF___NATS_CREDS_FILE`. `/status/env` masks the secret keys, and the URL's credentials are stripped from logs, `/health` and `/status/env`. @@ -247,6 +247,7 @@ event_client_drain_timeout = 30.0 # shutdown budget for in-flight handlers # JetStream consumer (only when nats_use_jetstream = true) nats_use_jetstream = false nats_stream_name = "EVENTS" +# Unset, each of these is the server's default; the framework sets none of them on its own. nats_ack_wait = 300.0 # must exceed the p99 handler duration nats_max_ack_pending = 16 # outstanding messages across all replicas nats_max_deliver = 5 # attempts before the message is dead-lettered diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index d87eac7b..075044da 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -94,9 +94,11 @@ class ConsumerTuning: happens. """ - ack_wait: float - max_ack_pending: int - max_deliver: int + # None means "not configured": the setting is left out of the consumer, so the server's + # default applies -- as it did before the framework set any of them. + ack_wait: float | None + max_ack_pending: int | None + max_deliver: int | None dead_letter_subject: str @@ -167,12 +169,12 @@ class NATSClient(IOClientBase): ``event_client_retry_delay`` (float, default 5.0): seconds between retries. ``event_client_drain_timeout`` (float, default 30.0): seconds allowed for in-flight handlers to finish during shutdown. - ``nats_ack_wait`` (float, default 300.0): seconds the broker waits for an + ``nats_ack_wait`` (float, unset = server default): seconds the broker waits for an acknowledgement before redelivering. Must exceed p99 handler duration. - ``nats_max_ack_pending`` (int, default 16): unacknowledged messages allowed at once - across every replica sharing the consumer; ``-1`` = unlimited. - ``nats_max_deliver`` (int, default 5): delivery attempts before a message is - dead-lettered; ``-1`` = unlimited, which disables dead-lettering on exhaustion. + ``nats_max_ack_pending`` (int, unset = server default): unacknowledged messages allowed + at once across every replica sharing the consumer; ``-1`` = unlimited. + ``nats_max_deliver`` (int, unset = server default, unlimited): delivery attempts before a + message is dead-lettered; unlimited disables dead-lettering on exhaustion. ``nats_dead_letter_subject`` (str, default ``".dead-letter"``): where a message goes when the framework gives up on it; ``""`` disables it and loses the payload. """ @@ -426,20 +428,25 @@ def _resolve_consumer_tuning(self, topics: list[str]) -> ConsumerTuning: must fail the caller's startup rather than disappear into the background retry task, which would retry a config error forever. + **Each setting is opt-in.** An unset key is left out of the consumer and the server's + default applies (NATS: ``ack_wait`` 30 s, ``max_ack_pending`` 1000, ``max_deliver`` + unlimited). The framework used to set 300 s / 16 / 5 on every consumer it created, + which changed the server's behaviour for deployments that had configured nothing. + Raises: - ValueError: if a value is not a number, is zero, or is a negative value other - than ``-1``. + ValueError: if a configured value is not a number, is zero, or is a negative value + other than ``-1``. """ - ack_wait = self._read_float("nats_ack_wait", 300.0) - if ack_wait <= 0: + ack_wait = self._read_optional_float("nats_ack_wait") + if ack_wait is not None and ack_wait <= 0: raise ValueError(f"'nats_ack_wait' must be greater than 0, got {ack_wait}. It is the redelivery timeout, in seconds.") - max_ack_pending = self._read_int("nats_max_ack_pending", 16) - if max_ack_pending == 0 or max_ack_pending < -1: + max_ack_pending = self._read_optional_int("nats_max_ack_pending") + if max_ack_pending is not None and (max_ack_pending == 0 or max_ack_pending < -1): raise ValueError(f"'nats_max_ack_pending' must be a positive count or -1 for unlimited, got {max_ack_pending}.") - max_deliver = self._read_int("nats_max_deliver", 5) - if max_deliver == 0 or max_deliver < -1: + max_deliver = self._read_optional_int("nats_max_deliver") + if max_deliver is not None and (max_deliver == 0 or max_deliver < -1): raise ValueError(f"'nats_max_deliver' must be a positive count or -1 for unlimited, got {max_deliver}.") if max_deliver == -1: logger.warning( @@ -576,6 +583,18 @@ def _read_float(self, key: str, default: float) -> float: except (TypeError, ValueError) as exc: raise ValueError(f"Config key '{key}' must be a number, got {raw!r}.") from exc + def _read_optional_float(self, key: str) -> float | None: + """Read ``key`` as a number, or ``None`` when it is not configured.""" + if self.config.get(key, None) is None: + return None + return self._read_float(key, 0.0) + + def _read_optional_int(self, key: str) -> int | None: + """Read ``key`` as an integer, or ``None`` when it is not configured.""" + if self.config.get(key, None) is None: + return None + return self._read_int(key, 0) + def _read_int(self, key: str, default: int) -> int: raw = self.config.get(key, default) try: @@ -1264,7 +1283,22 @@ async def _ensure_consumer(self, topic: str, durable: str) -> js_api.ConsumerCon ) return desired - drift = self._consumer_drift(info.config, desired) + legacy = not info.config.deliver_group + if legacy: + # A consumer from before 0.9: created by js.subscribe with an inbox deliver subject and + # no deliver group. Still used exactly as it is -- recreating it would replay or gap -- + # but only one replica can bind to it, so the form is on its way out. + logger.warning( + "DEPRECATED: JetStream consumer '%s' on stream '%s' was created without a deliver group, the form " + "used before 0.9 (it delivers to '%s'). It is still used as it is, but this form will not be supported " + "in a future release: only one replica can consume from it. Delete it during a maintenance window and " + "the framework recreates it so that every replica shares it.", + durable, + stream, + info.config.deliver_subject, + ) + # The missing deliver group is what the deprecation already says; not repeated as drift. + drift = self._consumer_drift(info.config, desired, ignore=("deliver_group",) if legacy else ()) if drift: logger.warning( "JetStream consumer '%s' on stream '%s' already exists with different settings (%s). " @@ -1277,12 +1311,16 @@ async def _ensure_consumer(self, topic: str, durable: str) -> js_api.ConsumerCon return info.config @staticmethod - def _consumer_drift(actual: js_api.ConsumerConfig, desired: js_api.ConsumerConfig) -> list[str]: - """Name the settings on which an existing consumer differs from the wanted one.""" + def _consumer_drift(actual: js_api.ConsumerConfig, desired: js_api.ConsumerConfig, *, ignore: tuple[str, ...] = ()) -> list[str]: + """Name the settings on which an existing consumer differs from the wanted one. + + A setting the configuration leaves unset asks for nothing, so it cannot differ: the + broker's value, default or not, is what the deployment chose by not choosing. + """ return [ f"{field}: broker has {getattr(actual, field)!r}, config asks for {getattr(desired, field)!r}" for field in ("filter_subject", "deliver_group", "ack_wait", "max_ack_pending", "max_deliver") - if getattr(actual, field) != getattr(desired, field) + if field not in ignore and getattr(desired, field) is not None and getattr(actual, field) != getattr(desired, field) ] # ------------------------------------------------------------------ @@ -1412,8 +1450,9 @@ def _deliveries_exhausted(self, msg: Any) -> bool: and is never exhausted. A message whose JetStream metadata cannot be read is treated as not exhausted, so an unreadable header can only cost a retry, never a payload. """ - max_deliver = self._tuning.max_deliver if self._tuning else -1 - if max_deliver < 0: + # Not configured means the server's default, which is unlimited. + max_deliver = self._tuning.max_deliver if self._tuning else None + if max_deliver is None or max_deliver < 0: return False delivered = self._delivery_count(msg) return delivered is not None and delivered >= max_deliver diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index a2b2876b..ffca9ae8 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -220,7 +220,7 @@ def integration_config( f'nats_queue_group = "{subject_prefix}"\n' "nats_use_jetstream = true\n" # Well above any handler here, and short enough that a test asserting *no* redelivery can - # afford to wait the whole window out. The framework default is 300. + # afford to wait the whole window out. Unset, it would be the server's default (30 s). "nats_ack_wait = 2.0\n" "nats_max_deliver = 3\n" # The client retries the initial connect forever by default, which turns "the broker diff --git a/tests/integration/docker-compose.yml b/tests/integration/docker-compose.yml index 454f5cba..cc73c059 100644 --- a/tests/integration/docker-compose.yml +++ b/tests/integration/docker-compose.yml @@ -19,8 +19,8 @@ services: image: nats:2.10-alpine container_name: blueprint-test-nats # --jetstream is what the framework needs for durables, dead letters and max_deliver; - # without it every subscription silently falls back to Core NATS and the acknowledgement - # tests assert nothing. --http_port exposes /healthz and /connz, which is also where the + # without it an agent with nats_use_jetstream = true fails to start (there is no fallback + # to Core NATS). --http_port exposes /healthz and /connz, which is also where the # connection names the client sets (namespace.group.pod) can be read back. command: ["--jetstream", "--store_dir=/tmp/nats", "--http_port=8222"] ports: diff --git a/tests/integration/test_upgrade_from_0_8.py b/tests/integration/test_upgrade_from_0_8.py new file mode 100644 index 00000000..a6cded49 --- /dev/null +++ b/tests/integration/test_upgrade_from_0_8.py @@ -0,0 +1,121 @@ +"""What an agent upgrading from 0.8 finds on the broker, and what it does with it. + +0.8 subscribed with ``js.subscribe(topic, durable=f"{topic}-durable", manual_ack=True)``, which +left a durable consumer delivering to a random inbox with no deliver group. 0.9 creates its own +consumers with a named deliver subject and a deliver group, so every replica can share one -- but +it must not touch a consumer that already exists: recreating a durable replays or gaps. These +assert, against the real broker, that an existing 0.8 consumer is used exactly as it is and is +announced as deprecated, and they pin the broker behaviour the upgrade path relies on. +""" + +import uuid +from typing import Any + +import pytest +from nats.aio.client import Client as NatsClient +from nats.js import JetStreamContext +from nats.js import api as js_api +from nats.js.errors import APIError + +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.events import GenericCloudEvent + +from .helpers import wait_until + + +@pytest.fixture +def undotted_topic(subject_prefix: str) -> str: + """A topic without a dot, so 0.8 and 0.9 derive the same durable name for it.""" + return f"{subject_prefix}_orders" + + +def recording_handler(topic: str, seen: list[str]) -> type[EventHandlerBase]: + class RecordingHandler(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return [topic] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> None: + seen.append(event.id) + + return RecordingHandler + + +async def a_08_consumer(nats_connection: NatsClient, stream: str, topic: str) -> js_api.ConsumerConfig: + """Create the stream and the durable exactly as 0.8's js.subscribe left them.""" + js = nats_connection.jetstream() + await js.add_stream(name=stream, subjects=[topic]) + config = js_api.ConsumerConfig( + durable_name=f"{topic}-durable", + filter_subject=topic, + deliver_subject=nats_connection.new_inbox(), + ack_policy=js_api.AckPolicy.EXPLICIT, + ) + await js.add_consumer(stream, config=config) + return config + + +class TestAnExistingConsumerFrom08: + async def test_it_is_used_as_it_is( + self, nats_app: Any, nats_connection: NatsClient, jetstream_stream: str, undotted_topic: str + ) -> None: + before = await a_08_consumer(nats_connection, jetstream_stream, undotted_topic) + seen: list[str] = [] + event = GenericCloudEvent(id=str(uuid.uuid4()), source="integration-test", type="orders.created", data={}) + + async with nats_app(recording_handler(undotted_topic, seen)): + js: JetStreamContext = nats_connection.jetstream() + await js.publish(undotted_topic, event.model_dump_json().encode()) + await wait_until(lambda: event.id in seen, timeout=15, description="the 0.8 consumer to deliver") + + consumers = await js.consumers_info(jetstream_stream) + after = await js.consumer_info(jetstream_stream, f"{undotted_topic}-durable") + + assert [consumer.name for consumer in consumers] == [f"{undotted_topic}-durable"], "no second consumer was created" + assert after.config.deliver_subject == before.deliver_subject + assert not after.config.deliver_group + + async def test_it_is_announced_as_deprecated( + self, + nats_app: Any, + nats_connection: NatsClient, + jetstream_stream: str, + undotted_topic: str, + caplog: pytest.LogCaptureFixture, + ) -> None: + await a_08_consumer(nats_connection, jetstream_stream, undotted_topic) + with caplog.at_level("WARNING", logger="blueprint.agents.clients.io.nats_client"): + async with nats_app(recording_handler(undotted_topic, [])): + pass + assert any(message.startswith("DEPRECATED") and f"'{undotted_topic}-durable'" in message for message in caplog.messages) + + +class TestTheBrokerRefusesADottedConsumerName: + """Why a 0.8 durable for a topic with a dot cannot exist: 0.8 derived ``orders.created-durable``. + + 0.9 derives ``orders_created-durable`` for the same topic. That rename orphans nothing only if + the server never accepted the dotted name -- which is what this pins. + """ + + async def test_the_name_is_rejected(self, nats_connection: NatsClient, jetstream: JetStreamContext, subject_prefix: str) -> None: + stream = f"IT_{subject_prefix.upper()}" + topic = f"{subject_prefix}.orders.created" + # Refused by the server, or by nats-py before it gets there -- 0.8 went through nats-py too. + with pytest.raises((APIError, ValueError)): + await jetstream.add_consumer( + stream, + config=js_api.ConsumerConfig( + durable_name=f"{topic}-durable", + filter_subject=topic, + deliver_subject=nats_connection.new_inbox(), + ack_policy=js_api.AckPolicy.EXPLICIT, + ), + ) diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index 61e1d8e1..8db6aff3 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -893,17 +893,35 @@ async def test_core_nats_resolves_no_tuning(self, nats_client: NATSClient) -> No await nats_client.subscribe({"topic.a": AsyncMock()}) assert nats_client.consumer_tuning is None - async def test_defaults_are_resolved_when_jetstream_is_on( + async def test_unset_keys_leave_the_server_defaults( self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple ) -> None: + """The framework used to set 300 s / 16 / 5 on every consumer; now it sets nothing unasked.""" await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) assert nats_client.consumer_tuning == ConsumerTuning( - ack_wait=300.0, - max_ack_pending=16, - max_deliver=5, + ack_wait=None, + max_ack_pending=None, + max_deliver=None, dead_letter_subject="test-agent.dead-letter", ) + async def test_an_unset_value_is_left_out_of_the_consumer( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + sent = nats_client._consumer_config("orders.created", "orders_created-durable").as_dict() + assert "max_deliver" not in sent + assert "max_ack_pending" not in sent + + async def test_an_unset_max_deliver_never_exhausts( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + """The server's default is unlimited, so no delivery is ever the last one.""" + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + msg = MagicMock() + msg.metadata.num_delivered = 1000 + assert nats_client._deliveries_exhausted(msg) is False + async def test_configured_values_win(self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple) -> None: await _prepare_js_client( nats_client, @@ -1192,9 +1210,13 @@ async def test_existing_consumer_is_not_rewritten( async def test_drift_from_an_existing_consumer_is_reported( self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, caplog: pytest.LogCaptureFixture ) -> None: - mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"], nats_ack_wait=300.0) existing = js_api.ConsumerConfig( - durable_name="orders_created-durable", filter_subject="orders.created", deliver_subject="_DELIVER.old", ack_wait=30.0 + durable_name="orders_created-durable", + filter_subject="orders.created", + deliver_subject="_DELIVER.old", + deliver_group="another-group", + ack_wait=30.0, ) mock_js.consumer_info = AsyncMock(return_value=MagicMock(config=existing)) with caplog.at_level("WARNING"): @@ -1202,6 +1224,54 @@ async def test_drift_from_an_existing_consumer_is_reported( assert "already exists with different settings" in caplog.text assert "deliver_group" in caplog.text assert "ack_wait" in caplog.text + assert "DEPRECATED" not in caplog.text + + @staticmethod + def _pre_09_consumer() -> js_api.ConsumerConfig: + """What js.subscribe(topic, durable=..., manual_ack=True) left behind before 0.9.""" + return js_api.ConsumerConfig( + durable_name="orders-durable", + filter_subject="orders", + deliver_subject="_INBOX.abc123", + ack_policy=js_api.AckPolicy.EXPLICIT, + ) + + async def test_a_pre_09_consumer_is_still_used_as_it_is( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders"]) + existing = self._pre_09_consumer() + mock_js.consumer_info = AsyncMock(return_value=MagicMock(config=existing)) + await nats_client._subscribe_one("orders", AsyncMock()) + mock_js.add_consumer.assert_not_awaited() + assert mock_js.subscribe_bind.await_args.kwargs["config"] is existing + assert mock_js.subscribe_bind.await_args.kwargs["consumer"] == "orders-durable" + + async def test_a_pre_09_consumer_is_announced_as_deprecated( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, caplog: pytest.LogCaptureFixture + ) -> None: + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders"]) + mock_js.consumer_info = AsyncMock(return_value=MagicMock(config=self._pre_09_consumer())) + with caplog.at_level("WARNING", logger="blueprint.agents.clients.io.nats_client"): + await nats_client._subscribe_one("orders", AsyncMock()) + deprecations = [message for message in caplog.messages if message.startswith("DEPRECATED")] + assert len(deprecations) == 1 + assert "'orders-durable'" in deprecations[0] + assert "will not be supported in a future release" in deprecations[0] + # The missing deliver group is the deprecation; it is not reported a second time as drift. + assert not any("already exists with different settings" in message for message in caplog.messages) + + async def test_an_unset_value_is_not_reported_as_drift( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, caplog: pytest.LogCaptureFixture + ) -> None: + """Configuring nothing asks for nothing; the broker's value is not a difference.""" + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + existing = nats_client._consumer_config("orders.created", "orders_created-durable") + existing.ack_wait, existing.max_deliver = 30.0, 7 + mock_js.consumer_info = AsyncMock(return_value=MagicMock(config=existing)) + with caplog.at_level("WARNING"): + await nats_client._subscribe_one("orders.created", AsyncMock()) + assert "already exists" not in caplog.text async def test_matching_existing_consumer_is_silent( self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, caplog: pytest.LogCaptureFixture From 71a29fc23c30e793d647d84b67b42ab04566b1a1 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 25 Sep 2026 12:49:14 +0200 Subject: [PATCH 065/133] fix(telemetry): honour OTEL_RESOURCE_ATTRIBUTES and write no placeholder attributes Resource attributes the framework set replaced the values a deployment declared in OTEL_RESOURCE_ATTRIBUTES / OTEL_SERVICE_NAME. Declared keys are now left out of what the framework sets, so the environment's values are used unchanged. A standalone agent's resource carries no deployment.group, and an unknown pod writes no service.instance.id. Records the get_meter export as a breaking change. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 12 ++++ ...26-08-28-multi-agent-grouping-changelog.md | 16 +++++ .../docs/concepts/observability.md | 10 +++- .../agents/io/telemetry/telemetry.py | 46 ++++++++++---- .../agents/io/telemetry/test_telemetry.py | 60 +++++++++++++++++++ 5 files changed, 130 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 77a4ad66..c349834e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ - **A standalone agent's `Config` reads `hostname`, `pod_name` and `blueprint_group` again.** Since the 0.9 alphas, `get()` raised for these keys everywhere. The refusal exists so that an agent in a group cannot depend on where it runs; it now applies only to an agent's view in a group. +- **`OTEL_RESOURCE_ATTRIBUTES` is honoured.** The framework set `service.name`, `deployment.group` + and `service.instance.id` in code, which the OpenTelemetry SDK lets win over the environment, so + a value a deployment declared was silently replaced -- `service.name` included, since 0.8. A key + declared in `OTEL_RESOURCE_ATTRIBUTES` or `OTEL_SERVICE_NAME` is now used exactly as declared; + the framework fills only what was left out. A standalone agent's resource carries no + `deployment.group` (it was ``), and no placeholder instance id when the pod is unknown. - **A standalone agent's `/health/ready` has its original shape again.** The body gained `policy` and a `namespaces` section keyed `""`, which describe the agents of a group. They now appear only when the process hosts a group; a standalone agent gets `status` and `components`, as before. @@ -443,6 +449,12 @@ Full migration path, including the one decision to get right before the first de 16. **`Config.settings` is read-only.** It was a plain attribute; assigning to it now raises `AttributeError`. Replacing the settings tree underneath a running configuration bypasses every agent's view of it and is not supported. +17. **Metrics a project records itself are now exported.** With OpenTelemetry enabled, the framework + registers a global `MeterProvider` that exports over OTLP. Before, it registered none, so a + counter a project created through `metrics.get_meter(...)` was silently discarded; the same + unchanged code now reaches the collector, which can add series -- and cost -- to a metrics + backend. A project that registered its own `MeterProvider` first keeps it: the SDK refuses a + second one and the framework's is not installed. ### Fixed diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 2f3cf669..76b048a0 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7901,6 +7901,22 @@ says so, and its connection-name paragraph, stale since the pod-only change, is The two other `Config` changes stay, as breaking changes 15 and 16 in `CHANGELOG.md` [0.9.0]: `Config()` no longer configures logging, and `Config.settings` is read-only. +**Telemetry, decided with the user.** (1) "We *must* use the values in `OTEL_RESOURCE_ATTRIBUTES`: +without the variable, do your own thing; with it, follow it strictly." `Resource.create(attrs)` +lets explicit attributes override the environment, so the framework's `service.name`, +`deployment.group` and `service.instance.id` replaced declared values -- `service.name` already in +v0.8.1. New module function `_framework_attributes(service_name, group, pod)` in `telemetry.py`: +builds the framework's attributes, omits `deployment.group` without a group and +`service.instance.id` for an unknown pod (no placeholders), then drops every key that +`OTELResourceDetector().detect()` reports as declared (it reads `OTEL_RESOURCE_ATTRIBUTES` and +`OTEL_SERVICE_NAME`); `Resource.create` supplies those from the environment. Read as "declared keys +win, the framework fills the rest"; in a group a declared `service.name` therefore names every +agent alike, which the docs state. Found on the way: OpenTelemetry SDK 1.44 sets a random +`service.instance.id` itself when none is given, so an unknown pod now shows the SDK's default. +Tests: `TestTheDeploymentDeclaresTheResource` (4 cases; three fail against the previous code). +(2) The global `MeterProvider` stays; its side effect -- a project's own `metrics.get_meter()` +metrics are now exported -- is breaking change 17 in `CHANGELOG.md` [0.9.0]. + **Not restored -- listed for the user, not worked around:** the Dapr degraded reason, the behaviour changes of the transport fixes, `Config` behaviour changes, the scheduler line, and the new outputs (metrics, span and resource attributes, new log lines). diff --git a/src/blueprint/agent_generator/docs/concepts/observability.md b/src/blueprint/agent_generator/docs/concepts/observability.md index 1e602bfb..3f45fae6 100644 --- a/src/blueprint/agent_generator/docs/concepts/observability.md +++ b/src/blueprint/agent_generator/docs/concepts/observability.md @@ -43,8 +43,14 @@ its own resource: | Attribute | Value | |---|---| | `service.name` | The agent's own name. `otel_service_name` for the root namespace. | -| `deployment.group` | `BLUEPRINT_GROUP`, or ``. Set by the framework; no supported API exposes it (C6). | -| `service.instance.id` | `POD_NAME`, else `HOSTNAME`, else the host name, else ``. | +| `deployment.group` | `BLUEPRINT_GROUP`. Absent when no group is set -- a single-agent application belongs to none. Set by the framework; no supported API exposes it to an agent (C6). | +| `service.instance.id` | `POD_NAME`, else `HOSTNAME`, else the host name. When none can be told, the framework sets nothing and the OpenTelemetry SDK's own default applies. | + +**What the deployment declares wins.** A key set in `OTEL_RESOURCE_ATTRIBUTES` (or +`service.name` in `OTEL_SERVICE_NAME`) is used exactly as declared; the framework sets only the +attributes the deployment left out, and never replaces a declared one. In a group, declaring +`service.name` this way gives every agent the same name -- the deployment's choice, not the +framework's. So an agent called `orders` reports `service.name = "orders"` whether it runs alone or beside nineteen others, and a dashboard keyed on it cannot tell which. A single-agent application keeps diff --git a/src/blueprint/agents/io/telemetry/telemetry.py b/src/blueprint/agents/io/telemetry/telemetry.py index a1ab73ab..5506b5d5 100644 --- a/src/blueprint/agents/io/telemetry/telemetry.py +++ b/src/blueprint/agents/io/telemetry/telemetry.py @@ -9,10 +9,13 @@ single-agent application's traces are identical to what it produced before any of this existed. ``deployment.group`` Which group this pod runs, from the environment. Set by the framework - and readable through no supported API (C6). -``service.instance.id`` Which replica this is. + and readable through no supported API (C6). Absent without a group. +``service.instance.id`` Which replica this is. Absent when it cannot be told. ======================== ====================================================================== +A key the deployment declares in ``OTEL_RESOURCE_ATTRIBUTES`` or ``OTEL_SERVICE_NAME`` is never +replaced -- see :func:`_framework_attributes`. + **The empty namespace is the one that must not regress.** Implemented naively -- one provider, ``service.name`` set to the group -- every existing dashboard would go dark on the day the framework was upgraded, before anybody grouped anything. So the root is built first, from @@ -37,18 +40,40 @@ from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader -from opentelemetry.sdk.resources import Resource +from opentelemetry.sdk.resources import OTELResourceDetector, Resource from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor from ...component.namespace import ROOT_NAMESPACE -from ...deployment import deployment_group, pod_identity +from ...deployment import UNGROUPED_LABEL, UNKNOWN_POD_LABEL, deployment_group, pod_identity from ..io_base import IOBase from .providers import has_providers, meter_provider, register_providers, tracer_provider logger = logging.getLogger(__name__) +def _framework_attributes(service_name: str, group: str, pod: str) -> dict[str, str]: + """The resource attributes the framework sets, minus every key the deployment declared. + + **What the deployment declares is used as it is.** ``OTEL_RESOURCE_ATTRIBUTES`` (and + ``OTEL_SERVICE_NAME``) are how a platform labels every service's telemetry without touching its + code, and ``Resource.create`` merges them underneath whatever it is given -- so an attribute + set here used to replace a declared one silently. Declared keys are left out of what the + framework sets; ``Resource.create`` then supplies them from the environment, unchanged. + + **Only attributes that exist.** A group that is not set and a pod that cannot be told are not + written as placeholders: a standalone agent's resource carries no ``deployment.group``, since it + belongs to no group. + """ + attributes = {"service.name": service_name} + if group != UNGROUPED_LABEL: + attributes["deployment.group"] = group + if pod != UNKNOWN_POD_LABEL: + attributes["service.instance.id"] = pod + declared = OTELResourceDetector().detect().attributes + return {key: value for key, value in attributes.items() if key not in declared} + + class TelemetryManager(IOBase): """Object-oriented manager for logging and tracing setup.""" @@ -130,13 +155,7 @@ def _configure_namespace( provider's own. """ service_name = root_service_name if namespace == ROOT_NAMESPACE else namespace - resource = Resource.create( - { - "service.name": service_name, - "deployment.group": group, - "service.instance.id": pod, - } - ) + resource = Resource.create(_framework_attributes(service_name, group, pod)) provider = TracerProvider(resource=resource) for processor in span_processors: @@ -150,7 +169,10 @@ def _configure_namespace( readers = [PeriodicExportingMetricReader(exporter) for exporter in metric_exporters] register_providers(namespace, provider, MeterProvider(resource=resource, metric_readers=readers)) - logger.info("OpenTelemetry configured for service '%s' in group '%s'", service_name, group) + if group == UNGROUPED_LABEL: + logger.info("OpenTelemetry configured for service '%s'", service_name) + else: + logger.info("OpenTelemetry configured for service '%s' in group '%s'", service_name, group) def _setup_instrumentation(self) -> None: """Enable automatic instrumentation for supported libraries.""" diff --git a/tests/unit/agents/io/telemetry/test_telemetry.py b/tests/unit/agents/io/telemetry/test_telemetry.py index 20bcdb87..ee33d273 100644 --- a/tests/unit/agents/io/telemetry/test_telemetry.py +++ b/tests/unit/agents/io/telemetry/test_telemetry.py @@ -234,3 +234,63 @@ def test_none_attribute_values_are_skipped(self) -> None: called_keys = [call[0][0] for call in mock_span.set_attribute.call_args_list] assert "key" not in called_keys assert "other" in called_keys + + +class TestTheDeploymentDeclaresTheResource: + """OTEL_RESOURCE_ATTRIBUTES is the deployment's word: declared values are used as they are.""" + + @pytest.fixture + def configure(self, telemetry_manager: TelemetryManager, mock_config: MagicMock, enabled_observability: ObservabilityConfig): + def _configure(*namespaces: str) -> None: + mock_config.get_observability_config.return_value = enabled_observability + with ( + patch.object(telemetry_manager, "_build_exporters", return_value=[MagicMock()]), + patch.object(telemetry_manager, "_build_metric_exporters", return_value=[]), + patch.object(telemetry_manager, "_setup_instrumentation"), + ): + telemetry_manager.configure_tracing(namespaces) + + return _configure + + @staticmethod + def _attributes(namespace: str) -> dict[str, object]: + provider = tracer_provider(namespace) + assert provider is not None + return dict(provider.resource.attributes) + + def test_a_declared_value_is_not_replaced(self, configure, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("OTEL_RESOURCE_ATTRIBUTES", "service.instance.id=declared-7,service.name=declared-service") + monkeypatch.setenv("POD_NAME", "pod-7") + configure() + attributes = self._attributes("") + assert attributes["service.instance.id"] == "declared-7" + assert attributes["service.name"] == "declared-service" + + def test_an_undeclared_key_is_still_filled(self, configure, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("OTEL_RESOURCE_ATTRIBUTES", "deployment.environment=prod") + monkeypatch.setenv("POD_NAME", "pod-7") + configure() + attributes = self._attributes("") + assert attributes["deployment.environment"] == "prod" + assert attributes["service.instance.id"] == "pod-7" + assert attributes["service.name"] == "test-service" + + def test_a_standalone_agent_has_no_deployment_group(self, configure, monkeypatch: pytest.MonkeyPatch) -> None: + """No group exists for it, so no placeholder group is written.""" + monkeypatch.delenv("OTEL_RESOURCE_ATTRIBUTES", raising=False) + monkeypatch.delenv("BLUEPRINT_GROUP", raising=False) + configure() + assert "deployment.group" not in self._attributes("") + + def test_an_unknown_pod_writes_no_placeholder(self, configure, monkeypatch: pytest.MonkeyPatch) -> None: + """The framework writes nothing; the SDK's own default instance id stands, as without the framework.""" + monkeypatch.delenv("OTEL_RESOURCE_ATTRIBUTES", raising=False) + monkeypatch.delenv("POD_NAME", raising=False) + monkeypatch.delenv("HOSTNAME", raising=False) + + def _raise() -> str: + raise OSError("no host name") + + monkeypatch.setattr("blueprint.agents.deployment.socket.gethostname", _raise) + configure() + assert self._attributes("").get("service.instance.id") != "" From c30b0b540eb3a767fbd9760152a0f89e43664e39 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 25 Sep 2026 12:51:03 +0200 Subject: [PATCH 066/133] docs: record the remaining breaking changes and the repo's language CHANGELOG: the scheduler tick running on one replica and the Core NATS queue group are listed as breaking; the cache-key item states precisely which caches move. CLAUDE.md states that the repository is written entirely in English. (The rule that a message is acked only once its work is complete went in with the consumer-settings commit, whose hunk in event-processing.md it shares.) Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 24 ++++++++++++++----- CLAUDE.md | 5 ++++ ...26-08-28-multi-agent-grouping-changelog.md | 20 ++++++++++++++++ 3 files changed, 43 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c349834e..8935c03d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -405,12 +405,14 @@ Full migration path, including the one decision to get right before the first de Service"` and no `foo.otel_service_name` sees `service.name` change from `Foo Service` to `foo`. Migration is one line: set `.otel_service_name` to whatever the dashboards key on. A project that passes no `agent_scope` is unaffected. -6. **Cache keys moved, twice.** A cache is now private to the agent that declared it, keyed on - `(namespace, name)` with its own subdirectory and Redis prefix. An application upgrading with a - persistent Redis cache or a mounted disk cache sees its old entries as **absent** — a cold cache, - not an error. A group still needs exactly one writable mount, since an agent's store is a - subdirectory of `cache.cache_dir`. If any cache entry is load-bearing rather than an - optimisation, migrate it deliberately. +6. **Cache keys moved, twice -- for named caches and for agents in a group.** A cache is now + private to the agent that declared it, keyed on `(namespace, name)` with its own subdirectory + and Redis prefix. Such a cache upgrading with persistent Redis or a mounted disk cache sees its + old entries as **absent** — a cold cache, not an error. **A standalone agent's default cache is + unaffected:** its directory, Redis prefix and keys are unchanged, so it keeps its entries. A + group still needs exactly one writable mount, since an agent's store is a subdirectory of + `cache.cache_dir`. If any cache entry is load-bearing rather than an optimisation, migrate it + deliberately. 7. **Four declaration surfaces are deleted**: `AgentRegistration`, `RegisteredComponent`, `NamespaceBuilder`, and `AppBuilder.with_namespace` / `with_registration`. `AppBuilder` is the one declaration surface; `AgentGroup` collects named declarations into a process. Passing an @@ -443,6 +445,16 @@ Full migration path, including the one decision to get right before the first de `Component.reset_shared_state()`** in its fixtures; this also clears `shared_registry`, which stays public and is otherwise unaffected. A project that never resets shared state between builds is unaffected. +13. **A scheduler tick runs in one replica, not in every one.** Before, every replica -- and every + worker -- ran its own timer and each ran every tick. Now `scheduler_mode = "event"` delivers the + tick through the queue group to one replica, and `"in_process"` claims each tick in the cache so + one replica runs it. A deployment that relied on every replica running a tick in parallel -- a + per-pod cleanup, say -- now runs it once per tick; register the cache per pod, or do the per-pod + work outside the scheduler. Without a registered cache, `"in_process"` still runs every tick in + every replica, and says so with a WARNING at startup where it used to log an INFO. +14. **A Core NATS event reaches one replica, not every one.** Subscriptions now join a queue group + (`nats_queue_group`, else `app_name`); before, every replica received and processed every event. + A deployment that relied on each replica seeing each event now sees each event once. 15. **`Config()` no longer configures logging.** Constructing a `Config` used to set up the root logger; library code must not, so `AppBuilder` does it now. A script or test that builds only a `Config` and relied on its logging setup has to configure logging itself. diff --git a/CLAUDE.md b/CLAUDE.md index 32a2c36b..f5e7a45d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,6 +5,11 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co See `AGENTS.md` for the architecture, the component patterns, the testing conventions and the **design rules** -- each with the failure it prevents -- shared across all AI assistants and every human working here. +## Language + +This repository is written entirely in English: code, identifiers, comments, docstrings, log and error messages, +documentation, specs, plans, changelogs, commit messages and pull-request descriptions. + ## Dev Commands ```bash diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 76b048a0..d98648e7 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7807,6 +7807,13 @@ Guarded by `test_standalone_log_lines.py` (6 cases, including "building a standa health cache and actuator tests (10 cases); all 16 fail against the previous code. No existing test had pinned any of these lines, which is how they changed unnoticed. +**Kept, decided with the user:** the error lines removed by "log each failure once" stay removed +(each failure is logged once, at the transport edge), and so does the old "Failed to publish handler +event" WARNING, which belonged to acknowledging an event whose result was lost. The rule behind it +is now stated in `concepts/event-processing.md`: a delivery is acknowledged only when its work -- +the handler chain and publishing every result -- is complete; otherwise it is a nak or a dead +letter. `CLAUDE.md` now states that the repository is written entirely in English. + **The NATS connection name, decided with the user.** v0.8.1 sent none; the feature named every connection `f"{namespace}.{group}.{pod}"`, so a standalone agent appeared in `/connz` as `..`. The user chose to keep a name -- more information is good -- but not to @@ -7887,6 +7894,13 @@ this environment. `CHANGELOG.md` gains a Deprecated section and "Upgrading a sta stream, the Core NATS queue group). Two stale comments fixed on the way: `integration_config`'s "the framework default is 300" and `docker-compose.yml`'s "falls back to Core NATS". +**The scheduler's startup line, decided with the user: keep it, and call the behaviour breaking.** +The line changed with the behaviour (#73: a tick is claimed, one replica runs it), so the v0.8.1 +wording would now be wrong. But a deployment that expected every replica to run each tick in +parallel sees that change, so `CHANGELOG.md` [0.9.0] Breaking gains item 13 for it -- and item 14 +for the same shift on Core NATS, where the new queue group means one replica per event instead of +every replica. + **`Config` behaviour, decided with the user.** `get("hostname" / "pod_name" / "blueprint_group")` raised `ValueError` on every configuration since the deployment-identity blocklist (C6). The user asked what those keys have to do with namespaces: nothing directly -- C6 keeps an agent from @@ -7917,6 +7931,12 @@ Tests: `TestTheDeploymentDeclaresTheResource` (4 cases; three fail against the p (2) The global `MeterProvider` stays; its side effect -- a project's own `metrics.get_meter()` metrics are now exported -- is breaking change 17 in `CHANGELOG.md` [0.9.0]. +**A breaking note that did not hold for standalone agents.** `CHANGELOG.md` [0.9.0] breaking change 6 +("Cache keys moved ... sees its old entries as absent") was written as if it applied to every +application. The audit found a standalone agent's default cache unchanged -- same directory, Redis +prefix and key hash. The item now says it applies to named caches and to agents in a group, and +that a standalone agent's default cache keeps its entries. + **Not restored -- listed for the user, not worked around:** the Dapr degraded reason, the behaviour changes of the transport fixes, `Config` behaviour changes, the scheduler line, and the new outputs (metrics, span and resource attributes, new log lines). From 134cc6f999010a2c1711116782b5acfe09d90ef5 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 28 Sep 2026 14:43:26 +0200 Subject: [PATCH 067/133] feat(cli): warn about absolute src imports in asbs validate --group An agent that imports its own code as `from src.x import Y` works standalone and fails in a group, where it is imported by its module path and nothing puts its directory on sys.path. A non-critical agent is then skipped with one ERROR line and its routes vanish from /docs. - validate_group: `_absolute_src_import_warnings` parses (never imports) every .py under an agent's src/ and reports level-0 `import src` / `from src...` with file:line, as a warning. - The migration guide and the blueprint-migration skill gain a Common pitfalls section naming the cause, log line, fix and a grep. - tests/integration/dapr_mock.py: a stdlib-only Dapr sidecar stand-in answering health and publish calls, for demos and integration work. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 6 ++ ...26-08-28-multi-agent-grouping-changelog.md | 64 +++++++++++ .../skills/blueprint-migration/SKILL.md | 11 ++ .../cli/commands/validate_group.py | 52 +++++++++ .../docs/guides/multi-agent-migration.md | 38 +++++++ tests/integration/dapr_mock.py | 100 ++++++++++++++++++ .../cli/commands/test_validate_group.py | 67 ++++++++++++ 7 files changed, 338 insertions(+) create mode 100644 tests/integration/dapr_mock.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b6088e78..45c9563a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -145,6 +145,12 @@ ### Added +- **The migration docs name absolute `src` imports as a pitfall.** `from src.x import Y` works for + an agent served on its own and fails in a group, where a non-critical agent is then skipped with + one ERROR line and its routes are missing from `/docs`. The `blueprint-migration` skill and + `guides/multi-agent-migration.md` now carry the cause, the log line, the fix (relative imports, + which keep working standalone) and a `grep` that finds them. `asbs validate --group` reports + them as a warning, with file and line. - **Handlers see the subject a NATS message was delivered on**, as `context["nats_subject"]` (`NATS_SUBJECT_CONTEXT_KEY`), beside `nats_topic`, which is the subscription and may be a wildcard. It comes from the broker, not the event, so a tenant can be derived from the subject the diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index d98648e7..119e8423 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -7941,6 +7941,70 @@ that a standalone agent's default cache keeps its entries. behaviour changes of the transport fixes, `Config` behaviour changes, the scheduler line, and the new outputs (metrics, span and resource attributes, new log lines). +### A Dapr sidecar mock for demos and integration work + +`tests/integration/dapr_mock.py`, standard library only, run as a script +(`python tests/integration/dapr_mock.py`, port 3500). Written while preparing a demo of the +grouping feature: a Dapr agent without a sidecar reports readiness DOWN, and there was nothing +short of a real `daprd` to make it come up. It answers exactly what the framework calls -- +`GET /v1.0/healthz` (and `/outbound`) with 204, `POST /v1.0/publish//` with 204 and +a log line naming the topic and event id -- and 404s anything else with a warning, so an unmocked +call is visible rather than silently answered. + +Checked by hand against `examples/order_event_pipeline` served standalone: readiness 503 without +it, 200 five seconds after starting it (the client's `event_client_retry_delay`), and an +`order.created` event posted to `/events/orders` shows up in the mock's log as a publish to +`pubsub/orders-validated`. + +It does **not** close the Dapr item under *Infrastructure* in +`docs/plans/2026-09-11-broker-integration-tests.md`: it reads no `/dapr/subscribe` and delivers +nothing to `/events/{topic}`, which is the half that item is about. No test uses it yet; the +obvious next step is a fixture that serves it in-process on a free port and sets `dapr_url`. + +### The migration docs name absolute `src` imports as a pitfall + +Found preparing the same demo: both examples it uses import their own code absolutely +(`from src.services.order_service import OrderService`), and neither the `blueprint-migration` +skill nor `guides/multi-agent-migration.md` said that this breaks in a group. Standalone the +agent's directory is the working directory, so `src` is a top-level package; in a group the agent +is imported by its `module` path (`agents.<...>.src.main`) and nothing puts its directory on +`sys.path`. Confirmed by importing `examples/inventory_api` from a group layout: +`ModuleNotFoundError: No module named 'src'`. + +Worse than a crash for a non-critical agent: `AgentGroup._skip_or_raise` skips it, so the group +starts, logs one ERROR, and the agent's routes are missing from `/docs`. + +Documented as a pitfall rather than a migration step, because relative imports are already common +and a project that uses them has nothing to do. New *Common pitfalls* sections in both the guide +(before *After the move*) and the skill carry the cause, the log line, the fix and a `grep` that +finds the imports; the pattern was checked against both examples (6 hits). The scaffolder already +writes relative imports, so new agents are not affected. `getting-started.md` still shows the +absolute style and was left as it is -- both styles are legitimate for a standalone agent. + +### `asbs validate --group` warns about absolute `src` imports + +The mechanical half of the entry above. `_agent_findings` in +`agent_generator/cli/commands/validate_group.py` now calls `_absolute_src_import_warnings` for +each agent that has a `src/` of its own; it parses (`ast`, never imports) every `.py` under it and +reports `import src...` and level-0 `from src... import` with `file:line`, five listed and the rest +counted, plus the fix. + +Three decisions in it: + +- **A warning, not an issue.** Issues mean "would stop this image starting"; a non-critical agent + with the defect is skipped and the image starts, and a critical one fails loudly on its own. +- **Skipped when the agent's `src` is the image root's `src`.** There `src` really is the agent's + package -- a single agent at the image root, served as a group of one -- and reporting it would + be a false statement about a working image, the failure `test_validate_group.py`'s docstring + exists to prevent. (The `src/order/main.py` layout in `multi-agent-setup.md` is not reached at + all: its agents have no `src/` of their own.) +- **Parsed, not grepped**, so a docstring or comment naming an import is not reported, and + `srcutils` is not `src`. + +Checked against both demo agents in a group layout: 5 hits in `inventory_api`, 1 in +`order_event_pipeline`, the same six the documented `grep` finds. Tests: +`TestAbsoluteSrcImports` (6 cases) in `tests/unit/agent_generator/cli/commands/test_validate_group.py`. + --- ## Open points diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md index 1f08406b..18df78a3 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md @@ -68,6 +68,17 @@ asbs validate --group # where the map is: the map and every agent it names sections and process-wide keys left in an agent. Pass `--agent-map ` if the map is not beside the directory being checked. +## Common pitfalls + +- **Absolute `src` imports.** `from src.services.x import Y` works standalone, where the agent's + directory is the working directory, and breaks in a group, where the agent is imported as + `agents.<...>.src.main` and nothing puts its directory on `sys.path`. Both styles are in use, so + look before assuming: `asbs validate --group` warns with file and line, or before the map + exists, `grep -rnE "^\s*(from|import) src(\.|\s|$)" src/`. Make each hit relative + (`from .x` in `src/main.py`, `from ..x` one package down); that still works standalone. Missed, + a non-critical agent is **skipped** at startup with one ERROR line naming `ModuleNotFoundError: + No module named 'src'`, and its routes are silently missing from `/docs`. + ## Before calling the move invisible It is not. On the first grouped deploy the agent's broker-side identity changes once (new durables, diff --git a/src/blueprint/agent_generator/cli/commands/validate_group.py b/src/blueprint/agent_generator/cli/commands/validate_group.py index d735b688..00756242 100644 --- a/src/blueprint/agent_generator/cli/commands/validate_group.py +++ b/src/blueprint/agent_generator/cli/commands/validate_group.py @@ -11,6 +11,7 @@ passing its probes, which is exactly what makes them expensive to find later. """ +import ast import os import sys import tomllib @@ -25,6 +26,9 @@ AGENT_MAP_FILE = "agents.toml" AGENT_MAP_ENV = "BLUEPRINT_AGENT_MAP" +# How many absolute `src` imports one warning lists before it summarises the rest. +_IMPORTS_SHOWN = 5 + def run(args: Namespace) -> None: """Execute ``asbs validate --group``. @@ -167,6 +171,8 @@ def _agent_findings(image_root: Path, name: str, entry: Any, claimed: dict[Path, if not (root / "src").is_dir(): warnings.append(f"Agent '{name}' has no 'src' directory at {declared_root}. An agent is the same shape alone or in a group.") + elif (root / "src").resolve() != (image_root / "src").resolve(): + warnings.extend(_absolute_src_import_warnings(name, root)) settings = root / "settings.toml" if settings.is_file(): @@ -244,6 +250,52 @@ def _process_key_warnings(name: str, settings: Path) -> list[str]: ] +def _absolute_src_import_warnings(name: str, root: Path) -> list[str]: + """Report an agent that imports its own code as the top-level package ``src``. + + Standalone that works, because the agent's directory is the working directory. In a group the + agent is imported by its ``module`` path and nothing puts its directory on ``sys.path``, so + ``src`` resolves to nothing -- or to the image root's own ``src``, a different package. A + non-critical agent is then skipped at startup with one ERROR line and its routes are missing, + which is why this is reported here rather than left to the log. + + A warning, not an issue: a critical agent fails loudly by itself, and a non-critical one does + not stop the image starting. The caller skips agents whose ``src`` *is* the image root's, + where the absolute import resolves to the agent's own code. + + Parsed rather than grepped, so an import named in a docstring or a comment is not reported, + and parsed rather than imported, like everything else this command checks. + """ + found: list[str] = [] + for path in sorted((root / "src").rglob("*.py")): + if "__pycache__" in path.parts: + continue + try: + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + except (OSError, SyntaxError, UnicodeDecodeError): + continue # not this check's to report: the runtime's import names it precisely + for node in ast.walk(tree): + if isinstance(node, ast.Import): + names = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: + names = [node.module] + else: + continue + if any(imported == "src" or imported.startswith("src.") for imported in names): + found.append(f"{path.relative_to(root).as_posix()}:{node.lineno}") + + if not found: + return [] + shown = ", ".join(found[:_IMPORTS_SHOWN]) + more = f" and {len(found) - _IMPORTS_SHOWN} more" if len(found) > _IMPORTS_SHOWN else "" + return [ + f"Agent '{name}' imports its own code as 'src' ({shown}{more}). That works standalone and fails in a group, " + "where the agent is imported by its module path and 'src' is not its package: a non-critical agent is then " + "skipped at startup and its routes are missing. Make these imports relative -- 'from .x import Y' in " + "src/main.py, 'from ..x import Y' one package down -- which keeps working standalone." + ] + + def _report(issues: list[str], warnings: list[str], notices: list[str]) -> None: """Print the three grades, worst first.""" for label, entries in (("Issues", issues), ("Warnings", warnings), ("Notices", notices)): diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md index 3ced9d14..5586e5a0 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md @@ -242,6 +242,44 @@ hosted in a group, the same directory gains an `/api/` prefix. --- +## Common pitfalls + +### Absolute `src` imports + +Both import styles work for an agent served on its own: + +```python +from src.services.order_service import OrderService # absolute +from ..services.order_service import OrderService # relative +``` + +Only the relative one survives the move. Standalone, the agent's directory is the working directory, +so `src` is a top-level package. In a group the agent is imported by its `module` path -- +`agents.order.src.main` -- and nothing puts its directory on `sys.path`, so `import src` finds +nothing, or finds a different `src` if the image root happens to have one. + +The failure is quiet for an agent that is not critical: it is **skipped**, the group starts without +it, and the only trace is one ERROR line -- + +``` +Agent 'order' could not be loaded and is not critical, so it is skipped: importing +'agents.order.src.main' raised ModuleNotFoundError: No module named 'src' +``` + +-- while the agent's routes are simply absent from `/docs`. A critical agent fails the startup with +the same reason. + +The fix is to make every import of the agent's own code relative -- `from src.x import Y` becomes +`from .x import Y` in `src/main.py`, and `from ..x import Y` one package further down. Relative +imports keep working standalone as well, so the change needs no second copy. `asbs validate +--group` lists them as a warning with file and line; without a map yet, a `grep` finds them: + +```bash +grep -rnE "^\s*(from|import) src(\.|\s|$)" src/ +``` + +--- + ## After the move Your **broker-side identity changes once**, on the first grouped deploy. What that affects -- diff --git a/tests/integration/dapr_mock.py b/tests/integration/dapr_mock.py new file mode 100644 index 00000000..59c8d5c4 --- /dev/null +++ b/tests/integration/dapr_mock.py @@ -0,0 +1,100 @@ +"""A stand-in for the Dapr sidecar, answering the calls a Blueprint app makes to it. + +Standard library only, so it runs from any Python 3.10+ with nothing installed: + + python tests/integration/dapr_mock.py # listens on 127.0.0.1:3500 + python tests/integration/dapr_mock.py --port 3500 --host 0.0.0.0 + +What it answers: + +- ``GET /v1.0/healthz`` and ``/v1.0/healthz/outbound`` -> 204. This is all the framework's + startup ping and readiness check ask for, so starting this process is what turns a Dapr + agent's ``/health/ready`` from DOWN to UP. +- ``POST /v1.0/publish//`` -> 204. The event is accepted and logged, not + delivered anywhere: there is no broker behind it. +- anything else -> 404, logged, so a call the mock does not know about is visible. + +It does not deliver events to the app and does not read the app's ``/dapr/subscribe``. It is +a sidecar that is *there*, not one that routes. +""" + +from __future__ import annotations + +import argparse +import json +import logging +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from logging import getLogger + +_log = getLogger("dapr_mock") + +_HEALTH_PATHS = ("/v1.0/healthz", "/v1.0/healthz/outbound") +_PUBLISH_PREFIX = "/v1.0/publish/" + + +class DaprMockHandler(BaseHTTPRequestHandler): + """Answer the sidecar endpoints a Blueprint app calls.""" + + def do_GET(self) -> None: # noqa: N802 -- name fixed by BaseHTTPRequestHandler + path = self.path.split("?", 1)[0] + if path in _HEALTH_PATHS: + _log.debug("health check %s", path) + self._reply(204) + return + self._unknown() + + def do_POST(self) -> None: # noqa: N802 -- name fixed by BaseHTTPRequestHandler + path = self.path.split("?", 1)[0] + body = self.rfile.read(int(self.headers.get("Content-Length") or 0)) + if path.startswith(_PUBLISH_PREFIX): + parts = path[len(_PUBLISH_PREFIX) :].split("/", 1) + if len(parts) == 2 and all(parts): + pubsub, topic = parts + _log.info("published to %s/%s: event id %s (%d bytes)", pubsub, topic, _event_id(body), len(body)) + self._reply(204) + return + self._unknown() + + def _unknown(self) -> None: + _log.warning("not mocked: %s %s", self.command, self.path) + self._reply(404) + + def _reply(self, status: int) -> None: + self.send_response(status) + self.send_header("Content-Length", "0") + self.end_headers() + + def log_message(self, format: str, *args: object) -> None: # noqa: A002 -- signature fixed by the base class + """Route the base class's access log through logging instead of stderr.""" + _log.debug(format, *args) + + +def _event_id(body: bytes) -> str: + """Return the event's ``id`` if the body is a JSON object carrying one, else ``"?"``.""" + try: + payload = json.loads(body) + except ValueError: + return "?" + return str(payload.get("id", "?")) if isinstance(payload, dict) else "?" + + +def main() -> None: + parser = argparse.ArgumentParser(description="Dapr sidecar mock for Blueprint demos and tests") + parser.add_argument("--host", default="127.0.0.1", help="interface to bind (default: 127.0.0.1)") + parser.add_argument("--port", type=int, default=3500, help="Dapr HTTP port (default: 3500)") + parser.add_argument("--verbose", "-v", action="store_true", help="also log every health check") + args = parser.parse_args() + + logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO, format="%(asctime)s dapr-mock %(message)s") + server = ThreadingHTTPServer((args.host, args.port), DaprMockHandler) + _log.info("Dapr sidecar mock listening on http://%s:%d", args.host, args.port) + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + server.server_close() + + +if __name__ == "__main__": + main() diff --git a/tests/unit/agent_generator/cli/commands/test_validate_group.py b/tests/unit/agent_generator/cli/commands/test_validate_group.py index c3fb2ca7..5b9c3d07 100644 --- a/tests/unit/agent_generator/cli/commands/test_validate_group.py +++ b/tests/unit/agent_generator/cli/commands/test_validate_group.py @@ -98,3 +98,70 @@ def test_the_flag_wins_over_the_environment(self, tmp_path: Path, monkeypatch: p monkeypatch.setenv(MAP_ENV, "from/env.toml") assert _agent_map_path(tmp_path, "from/flag.toml") == tmp_path / "from" / "flag.toml" + + +class TestAbsoluteSrcImports: + """An agent importing its own code as `src` works standalone and is skipped in a group.""" + + @staticmethod + def _image_with(tmp_path: Path, files: dict[str, str]) -> Path: + _agent_dir(tmp_path / "agents" / "orders") + for relative, text in files.items(): + target = tmp_path / "agents" / "orders" / "src" / relative + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(text, encoding="utf-8") + (tmp_path / "agents.toml").write_text(_map_text("agents/orders"), encoding="utf-8") + return tmp_path + + def test_an_absolute_src_import_is_a_warning_naming_file_and_line(self, tmp_path: Path) -> None: + image = self._image_with( + tmp_path, + {"main.py": "from src.services.order_service import OrderService\nagent = None\n", "api/routes.py": "import src.models\n"}, + ) + + issues, warnings, _ = _findings(image, _agent_map_path(image, None)) + + assert issues == [], "Both styles are legitimate standalone; this must not claim the image cannot start." + found = [w for w in warnings if "imports its own code as 'src'" in w] + assert len(found) == 1 + assert "src/main.py:1" in found[0] and "src/api/routes.py:1" in found[0] + assert "from .x import Y" in found[0], "The warning has to carry the fix." + + def test_relative_imports_are_not_reported(self, tmp_path: Path) -> None: + image = self._image_with(tmp_path, {"main.py": "from .services.order_service import OrderService\nagent = None\n"}) + + _, warnings, _ = _findings(image, _agent_map_path(image, None)) + + assert not any("imports its own code as 'src'" in w for w in warnings) + + def test_a_name_in_a_docstring_or_comment_is_not_an_import(self, tmp_path: Path) -> None: + image = self._image_with(tmp_path, {"main.py": '"""Once: from src.x import Y."""\n# import src\nagent = None\n'}) + + _, warnings, _ = _findings(image, _agent_map_path(image, None)) + + assert not any("imports its own code as 'src'" in w for w in warnings) + + def test_a_package_merely_starting_with_src_is_not_reported(self, tmp_path: Path) -> None: + image = self._image_with(tmp_path, {"main.py": "import srcutils\nfrom srclib.x import Y\nagent = None\n"}) + + _, warnings, _ = _findings(image, _agent_map_path(image, None)) + + assert not any("imports its own code as 'src'" in w for w in warnings) + + def test_an_agent_whose_src_is_the_image_roots_is_not_reported(self, tmp_path: Path) -> None: + """A single agent at the image root: there `src` really is its own package.""" + _agent_dir(tmp_path) + (tmp_path / "src" / "main.py").write_text("from src.services import x\nagent = None\n", encoding="utf-8") + (tmp_path / "agents.toml").write_text(_map_text(".", "src.main:agent"), encoding="utf-8") + + _, warnings, _ = _findings(tmp_path, _agent_map_path(tmp_path, None)) + + assert not any("imports its own code as 'src'" in w for w in warnings) + + def test_a_long_list_is_summarised(self, tmp_path: Path) -> None: + image = self._image_with(tmp_path, {"main.py": "".join(f"import src.m{i}\n" for i in range(8)) + "agent = None\n"}) + + _, warnings, _ = _findings(image, _agent_map_path(image, None)) + + found = [w for w in warnings if "imports its own code as 'src'" in w] + assert "and 3 more" in found[0] From 6dd1529817d97d22061180c98dbbeaa05ffcee9d Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 28 Sep 2026 14:43:52 +0200 Subject: [PATCH 068/133] feat(api)!: one Swagger group per grouped agent, with reserved path segments A grouped image's Swagger UI filed most operations under "default" and scattered the rest as . groups interleaved across agents: _mount only rewrote routes that already carried a tag, and nothing ordered the rewritten ones. - RestApiBase.group_segment: a segment folded into route_prefix for a namespaced component only. NatsEventing sets "nats", SchedulerBase "scheduler", so in a group the NATS publish endpoint is /api//nats/events/{topic} and a trigger /api//scheduler//trigger. Standalone paths do not move. - _mount tags every route of a namespaced component with exactly [], replacing declared tags and tagging untagged routes. Root components keep their declared tags. - RestApiBase.path_prefix: optional developer prefix, applied as the router's own prefix in both modes. - _refuse_reserved_segments: in a group, a route starting with nats, cache or scheduler that is not served by that segment's framework owner fails build() with the class, agent, route and owner named. Plan: docs/plans/2026-09-28-grouped-http-surface.md. Spec: new sec. 11.2 and a sec. 10 row. Docs, skill and CHANGELOG updated. BREAKING CHANGE: for grouped agents only, /api//events/{topic} moves to /api//nats/events/{topic}, /api///trigger to /api//scheduler//trigger, every operation's OpenAPI tag becomes the agent's name, and an agent route under /nats, /cache or /scheduler now fails startup. Standalone agents are unaffected. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 18 ++ CLAUDE.md | 3 + ...26-08-28-multi-agent-grouping-changelog.md | 149 +++++++++++ docs/plans/2026-09-28-grouped-http-surface.md | 119 +++++++++ docs/specs/2026-08-28-multi-agent-grouping.md | 36 +++ .../agent_generator/claude_docs/CLAUDE.md | 3 +- .../skills/blueprint-migration/SKILL.md | 13 + .../docs/components/rest-apis.md | 27 +- .../docs/components/schedulers.md | 4 + .../docs/guides/multi-agent-migration.md | 23 ++ .../docs/guides/multi-agent-setup.md | 32 ++- .../agent_generator/docs/reference/api.md | 10 +- src/blueprint/agents/app_builder.py | 84 ++++++- src/blueprint/agents/component/namespace.py | 5 +- src/blueprint/agents/io/api/eventing/nats.py | 5 + src/blueprint/agents/io/api/rest_api_base.py | 44 +++- .../agents/io/api/scheduling/scheduler.py | 5 +- .../app_builder/test_route_namespacing.py | 231 +++++++++++++++++- 18 files changed, 774 insertions(+), 37 deletions(-) create mode 100644 docs/plans/2026-09-28-grouped-http-surface.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 45c9563a..ae8fdd82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -145,6 +145,9 @@ ### Added +- **`RestApiBase.path_prefix`**, an optional class attribute putting every route of an API under + one segment -- `/api/reports/...` standalone, `/api//reports/...` in a group. Default `""`, + so no existing path moves. - **The migration docs name absolute `src` imports as a pitfall.** `from src.x import Y` works for an agent served on its own and fails in a group, where a non-critical agent is then skipped with one ERROR line and its routes are missing from `/docs`. The `blueprint-migration` skill and @@ -205,6 +208,21 @@ ### Breaking +- **In a group, the NATS publish endpoint and scheduler triggers move, and each agent is one + Swagger group.** Grouped agents only; a standalone agent's paths and tags do not change. + - `/api//events/{topic}` becomes `/api//nats/events/{topic}`. + - `/api///trigger` becomes `/api//scheduler//trigger`. + - Cache endpoints stay at `/api//cache/*`. + - Every operation of a grouped agent is tagged with exactly the agent's name, replacing declared + tags and tagging untagged ones. In 0.9.0 an agent was split into `.` groups + interleaved with other agents', and its untagged routes sat under "default" beside everyone + else's. + - `nats`, `cache` and `scheduler` under `/api//` are reserved: a grouped agent's own route + starting with one now fails startup, naming the class and the route. Rename it or set + `path_prefix`. + + Clients and scripts calling a grouped agent's NATS publish endpoint or scheduler trigger need the + new paths. Nothing broker-side changes. - **Removed unused internals:** the empty module `blueprint.agents.models.event_routing`, and the example-domain models `AnalysisRequest` and `AnalysisResponse` in `blueprint.agents.models.result`, which nothing in the framework used and the package did not export. diff --git a/CLAUDE.md b/CLAUDE.md index f5e7a45d..945e9ebe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -86,6 +86,9 @@ uv pip install --no-cache-dir --find-links file:///home/pajoma/pypi/ avs-bluepri spec, the spec wins. - **Implementation plan:** `docs/plans/2026-08-28-multi-agent-grouping.md` -- prerequisites P0-P6 (blocking defects) and phases 0-10. +- **Follow-up plan -- grouped HTTP surface:** `docs/plans/2026-09-28-grouped-http-surface.md` -- + one Swagger tag per agent, reserved path segments (`nats`, `cache`, `scheduler`), steps 0-4. + Spec sec. 11.2. Standalone tags and paths never change. **Work this feature in reviewable steps.** Make one change, then stop and report what changed and why before starting the next. Do not chain phases together, and do not chain the work items within diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 119e8423..639a0f69 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8005,10 +8005,159 @@ Checked against both demo agents in a group layout: 5 hits in `inventory_api`, 1 `order_event_pipeline`, the same six the documented `grep` finds. Tests: `TestAbsoluteSrcImports` (6 cases) in `tests/unit/agent_generator/cli/commands/test_validate_group.py`. +### A grouped agent's HTTP surface: plan and spec amendment (step 0) + +Found setting up a group in a consuming repository: the image's Swagger UI filed most operations +under "default" and scattered the rest as `.nats`, `.cache` among them. Two causes +in `AppBuilder._mount`: it rewrites only routes that already carry a tag (`and route.tags`), so a +developer's untagged route keeps `[]` and lands in "default"; and nothing orders the rewritten +tags, so Swagger UI lists them in first-seen order across agents. + +New plan `docs/plans/2026-09-28-grouped-http-surface.md` (steps 0-4) and a new spec sec. 11.2, +plus a sec. 10 row. What they decide: + +- **One Swagger group per agent**: every operation of a grouped agent carries exactly the tag + ``, replacing declared tags; none is untagged. +- **The second level is the path**: `nats`, `cache` and `scheduler` are reserved segments under + `/api//`. NATS publish moves to `/api//nats/events/{topic}` and the scheduler trigger + to `/api//scheduler//trigger`; cache already had its segment. +- **Standalone is untouched**: every rule applies to namespaced components only, so a + standalone agent keeps its declared tags, "default" included, and its paths. +- **A developer prefix is optional**, applies in both modes, and a grouped agent's route may + not start with a reserved segment -- refused at `build()`. + +Rejected, with reasons in the plan: ReDoc's `x-tagGroups` (invisible in Swagger UI, and ReDoc +hides every ungrouped tag once it is present) and ` / ` sub-tags (Swagger UI has one +tag level). The grouped path changes are breaking for grouped 0.9.0 deployments -- grouping +shipped in 0.9.0 -- and are release-noted under *Breaking* (step 4). This entry first said +nothing released was affected, which was wrong. + +### Reserved path segments for a grouped agent's framework endpoints (step 1) + +Step 1 of `docs/plans/2026-09-28-grouped-http-surface.md`. `RestApiBase` gains a class attribute +`group_segment` (default `""`), and `route_prefix` folds it in for a namespaced component only: +`/api//` when it is set, `/api/` otherwise, `""` at the root whatever it says. +`NatsEventing.group_segment = "nats"` and `SchedulerBase.group_segment = "scheduler"`, so in a +group the NATS publish endpoint moves from `/api//events/{topic}` to +`/api//nats/events/{topic}` and a scheduler's trigger from `/api///trigger` to +`/api//scheduler//trigger`. Cache endpoints already had `cache/` in their declared +paths and are unchanged. + +In `route_prefix` rather than in `_mount` because `DaprEventing.subscribe` also reads it to tell +the sidecar where to post; one property keeps the two agreeing. `DaprEventing` declares no segment +and is always root, so the subscription document is unchanged. Standalone paths do not move: +`/events/{topic}` and `/api//trigger` stay where they were, and the frozen compatibility +suite passes unedited. + +Tests in `tests/unit/agents/app_builder/test_route_namespacing.py`: segment follows the prefix, +a root component ignores it, the framework's segment values, grouped NATS and scheduler paths, +standalone NATS and scheduler paths unchanged; the two-agent NATS test now expects the `nats/` +paths. + +### One Swagger group per grouped agent (step 2) + +Step 2 of `docs/plans/2026-09-28-grouped-http-surface.md`, and the fix for what the consuming +repository saw. In `AppBuilder._mount` the rewrite of a namespaced component's routes was + +```python +if isinstance(route, APIRoute) and route.tags: + route.tags = [qualified_entry_name(component.namespace, str(tag)) for tag in route.tags] +``` + +and is now + +```python +if isinstance(route, APIRoute): + route.tags = [component.namespace] +``` + +Dropping `and route.tags` is what empties "default": an untagged route of a grouped agent used to +keep `[]`. Replacing instead of qualifying is what makes one group per agent: `orders.Items`, +`orders.nats`, `orders.cache` and `orders.Scheduler` were separate Swagger groups, interleaved with +other agents' in first-seen order, and a route with two tags sat in two of them. The second level +is now the path (step 1). Root components are not touched, so a standalone agent keeps its +declared tags and its untagged routes still fall under "default". + +`qualified_entry_name` is no longer imported by `app_builder.py`; it still renders readiness +entries (`health_base.py`), whose `orders.cache` keys are a payload contract and do not change. +Docstrings of `_mount`, `with_rest_api` and `qualified_entry_name`, and the comment in +`_build_rest_endpoints`, updated to match. + +Tests: `TestTags` in `tests/unit/agents/app_builder/test_route_namespacing.py` rewritten around a +new `ItemApi` with a tagged, an untagged and a two-tag route -- each gets exactly `[]` in a +group; the NATS endpoint joins its agent's group; no `/api//...` operation carries anything but +`[]` across two agents; standalone keeps `["Items"]`, `[]` and `["Items", "Reports"]`. The old +tests asserted `orders.orders`, which is the behaviour removed. + +### A developer path prefix, and reserved segments refused in a group (step 3) + +Step 3 of `docs/plans/2026-09-28-grouped-http-surface.md`. + +**`RestApiBase.path_prefix`** (class attribute, default `""`). Passed through a module-private +`_normalise_path_prefix` (surrounding slashes and whitespace ignored, `""` or `/segment` out -- +the form FastAPI asserts) into `APIRouter(prefix=...)` in `RestApiBase.__init__`. Being the +router's prefix, it is part of every route's path -- decorated or added to `self.router` directly +-- and so applies in both modes: `path_prefix = "reports"` serves `/api/reports/daily` standalone +and `/api/orders/reports/daily` in a group. Independent of `group_segment`, which belongs to the +mount and applies in a group only. Optional, so no existing API moves. + +**`AppBuilder._refuse_reserved_segments`**, called from `_mount` for namespaced components only, +before the tag rewrite. For every route with a path it takes the path relative to `/api/` +(the component's `route_prefix` minus the agent prefix, plus the route path) and looks its first +segment up in the new module constant `_RESERVED_SEGMENTS` = `{"nats": NatsEventing, "cache": +CacheManagementApi, "scheduler": SchedulerBase}`. A hit on a component that is not an instance of +the owner raises `ValueError` naming the class, the agent, the route, the segment and the owner. +Keyed on the owner's class rather than on "declares a `group_segment`" because the cache API +reserves `cache` through its route paths and declares no segment, while a developer's scheduler +subclass is a legitimate owner of `scheduler`. Matched on the whole segment, so `/caches/...` is +fine. Not checked standalone: a route an existing agent serves at `/api/cache/...` keeps working. + +It raises out of `build()` and therefore out of `AgentGroup.assemble`, taking the image down +rather than one agent: the collision is deterministic and visible in the first local run +(`asbs dev` runs a group of one), and serving it would answer one of the two routes with the +other's handler, depending on mount order. `_RESERVED_SEGMENTS` is typed `dict[str, type]` since +mypy rejects abstract classes as `type[RestApiBase]`. + +Tests in `tests/unit/agents/app_builder/test_route_namespacing.py`: `TestPathPrefix` (standalone, +grouped, slashes, no prefix) and `TestReservedSegments` (a `/cache/...` route and a `nats` prefix +refused in a group, the same route served standalone, `caches` allowed, a developer's scheduler +allowed its segment). + +### Documentation for the grouped HTTP surface (step 4) + +Step 4 of `docs/plans/2026-09-28-grouped-http-surface.md`; documentation only, plus one docstring. + +- `guides/multi-agent-setup.md`: both identity tables gain the NATS publish and scheduler trigger + rows, and the OpenAPI tag row now reads `order` (grouped, whatever was declared) against + `Orders` (standalone, as declared). New section *An agent's Swagger group and its reserved + paths*. +- `guides/multi-agent-migration.md`: a pitfall *Routes under `/nats`, `/cache` or `/scheduler`* + with the error text, and a paragraph in *After the move* on the HTTP surface moving. +- `components/rest-apis.md`: the `tags` parameter row says it is replaced in a group; new section + *Path Prefix*. +- `components/schedulers.md`, `reference/api.md`, `claude_docs/CLAUDE.md`: the grouped trigger + path. `reference/api.md` also lists `path_prefix` and `group_segment` as class attributes, the + latter marked framework-internal. +- `blueprint-migration` skill: a reserved-segment pitfall and a *Swagger in a group* section. +- `AppBuilder.with_scheduler` docstring: the trigger moves under `/api//scheduler`. +- `CHANGELOG.md`: `path_prefix` under *Added*; the grouped path and tag changes under **Breaking**. + +**Correction.** The step 0 entry and the plan said the grouped path changes broke nothing released +because grouping was not on `main`. Grouping shipped in 0.9.0 (`CHANGELOG.md`, 2026-09-14), so a +grouped 0.9 deployment's clients of `/api//events/{topic}` and `/api///trigger` +do break. Found writing the `CHANGELOG.md` entry, which is why it is under *Breaking* and not +*Added*; both earlier statements are corrected in place. + --- ## Open points +- **A grouped scheduler's trigger path repeats the agent.** `register_trigger_route` builds the + path from `self.name`, the registry name, which a group qualifies: agent `orders` serves + `/api/orders/scheduler/orders_nightly_scheduler/trigger`. Standalone the name is unqualified, so + using the base name would change grouped paths only. Found in step 1 of the grouped-HTTP-surface + plan (it predates that step); deferred by decision on 2026-09-28. + - **`test_three_replicas_run_one_tick` is flaky in a full run.** Seen once on 2026-09-24 (two of three replicas ran one tick), passing alone. Likely `DiskCacheService.claim`'s documented non-atomic takeover of an expired claim, or a run straddling a minute boundary; not investigated. diff --git a/docs/plans/2026-09-28-grouped-http-surface.md b/docs/plans/2026-09-28-grouped-http-surface.md new file mode 100644 index 00000000..a283e1ae --- /dev/null +++ b/docs/plans/2026-09-28-grouped-http-surface.md @@ -0,0 +1,119 @@ +# Plan -- A Grouped Agent's HTTP Surface + +| | | +|---|---| +| **Amends** | `docs/specs/2026-08-28-multi-agent-grouping.md` -- sec. 11.2 (added in step 0) | +| **Changelog** | `docs/plans/2026-08-28-multi-agent-grouping-changelog.md` | +| **Branch** | `feature/multi-agent-namespaces` | +| **Decided** | 2026-09-28 | + +Worked in reviewable steps like the rest of the grouping feature: one step, then a report, then +the next. + +--- + +## Problem + +A grouped image's Swagger UI is unusable for the question every reader starts with -- *which +agent do I want to look at?* + +- **Most operations sit under "default".** `AppBuilder._mount` rewrites the tags of a namespaced + component's routes, but only of routes that already carry one (`if isinstance(route, APIRoute) + and route.tags`). A developer's untagged route keeps `[]`, and FastAPI files it under "default", + mixed with every other agent's untagged routes. +- **An agent's tagged groups are scattered.** Tags are rendered `.` (`orders.nats`, + `orders.cache`), and Swagger UI lists tags in the order it first meets them, so one agent's + groups interleave with another's and with "default". +- **Paths have no consistent second level.** Cache routes already carry `cache/`, the scheduler + trigger carries the scheduler's name, NATS publish carries nothing (`/api//events/{topic}`), + and a developer's routes carry whatever they declare. + +## Decisions + +1. **One Swagger group per agent.** In a group, every operation of agent `orders` carries exactly + the tag `orders`, replacing whatever was declared -- the framework's tags and the developer's + alike. No grouped agent's operation is ever untagged. +2. **The second level is the path, not the tag.** Swagger UI renders tags on one level only, so a + sub-grouping is expressed as `/api///...`. Within one agent's group Swagger lists + operations in registration order, which clusters them by segment without a sorter setting. +3. **Framework segments are reserved.** `nats`, `cache` and `scheduler` belong to the framework + inside an agent's prefix: + - NATS publish: `/api//nats/events/{topic}` + - Scheduler trigger: `/api//scheduler//trigger` + - Cache: `/api//cache/*` (unchanged -- its routes already carry `cache/`) +4. **Standalone apps are untouched.** Every rule above applies only to a component with a + namespace. A standalone agent (root namespace) keeps the tags the framework and the developer + declare today -- including "default" for untagged routes -- and every path it serves. + Root components of a grouped app (`root`, `actuators`, `dapr`) are process-wide and keep theirs. +5. **A developer's own prefix is optional.** A developer may declare a path prefix on their API + class; it applies in both modes, so an agent's code is identical standalone and grouped. It is + not required: an existing agent joins a group without a code change. What *is* enforced, in a + group only, is that no developer route starts with a reserved segment. +6. **Rejected: `x-tagGroups`.** A ReDoc vendor extension that Swagger UI ignores; once present, + ReDoc hides every tag not placed in a group. Revisit only as OpenAPI 3.2 `parent` tags, and + only once Swagger UI renders them. +7. **Rejected: ` / ` sub-tags.** Superseded by decision 1 -- one group per agent, with + the path carrying the second level. + +The grouped paths change (`/events` -> `/nats/events`, `//trigger` -> +`/scheduler//trigger`). Grouping shipped in 0.9.0, so this is a **breaking change for +grouped 0.9 deployments** and is release-noted under *Breaking*. (An earlier draft of this plan +said grouping had not been released; it had.) + +## Steps + +### Step 0 -- Spec amendment + +Add sec. 11.2 *An agent's HTTP surface* to the grouping spec, carrying decisions 1-5 as +requirements, and a row to sec. 10's compatibility table. No code. + +### Step 1 -- Framework segments through `route_prefix` + +`RestApiBase` gains a class attribute naming a segment that applies only when the component +belongs to an agent, folded into `route_prefix`: + +```python +group_segment: str = "" # "nats" on NatsEventing, "scheduler" on SchedulerBase + +@property +def route_prefix(self) -> str: + if not self.namespace: + return "" + return f"/api/{self.namespace}/{self.group_segment}" if self.group_segment else f"/api/{self.namespace}" +``` + +In `route_prefix` because two places must agree on it: the builder, which mounts the router, and +`DaprEventing.subscribe`, which tells the sidecar where to post (`dapr.py:199`). `DaprEventing` is +always root and so unaffected, but it must stay reading the same property. + +Tests: grouped NATS and scheduler paths; standalone paths unchanged; the frozen compatibility suite +unchanged. + +### Step 2 -- One tag per agent + +`AppBuilder._mount`: for a namespaced component, every `APIRoute`'s tags become +`[component.namespace]`, whether or not it had tags. Root components are left alone. + +Tests: an untagged grouped route is tagged with its agent; a tagged one loses its own tag; two +agents never share a tag; root and standalone tags unchanged. The expectations in +`test_route_namespacing.py` (`orders.orders`, `billing.orders`) change accordingly. + +### Step 3 -- Developer prefix and reserved segments + +- An optional class attribute on `RestApiBase` for a developer's own path prefix, applied in both + modes. The attribute's name and its interaction with `group_segment` are settled in this step. +- `build()` fails with a message naming the component, the route and the segment when a grouped + agent's developer route starts with `nats`, `cache` or `scheduler`. Framework components are + exempt, since they are the owners. + +### Step 4 -- Documentation + +`guides/multi-agent-migration.md` and the `blueprint-migration` skill (tags and paths in a group; +the reserved segments; the optional prefix), the `with_rest_api` / `with_scheduler` docstrings +that describe the grouped paths and tags, `CHANGELOG.md`, and the feature changelog. + +## Out of scope + +Routes added directly to the `FastAPI` application in `main.py` (`@app.get`, +`app.include_router`) never pass through `_mount` and can still land in "default". A check after +`build()` could catch them; not planned unless asked for. diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md index eac4c16c..0368f686 100644 --- a/docs/specs/2026-08-28-multi-agent-grouping.md +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -7,6 +7,7 @@ | **Unblocks** | #32 (100 agents in 4 GB), #35 (shared interpreter), #20 (worker scaling) | | **Related** | #33 (lazy heavy imports), #34 / #74 (dependency slimming), #36 (concurrency bounds + benchmark), #43 (scheduler double-start), #6 (config service) | | **Amended by** | `docs/plans/2026-09-10-builder-unification.md` -- decided 2026-09-10, folded into sec. 2, 4, 5.3, 8, 9, 10 and 11 below. | +| **Amended by** | `docs/plans/2026-09-28-grouped-http-surface.md` -- decided 2026-09-28, folded into sec. 10 and 11.2 below. | | **Deferred out of** | `docs/plans/2026-09-10-config-validation-unification.md` -- configuration validation is not part of this feature. | Requirement keywords (**MUST**, **MUST NOT**, **SHOULD**, **MAY**) are used in the RFC 2119 sense. @@ -815,6 +816,7 @@ change, and `uvicorn src.main:app` as its entrypoint. Specifically: | Passing a constructed instance to `with_*` | Unchanged standalone; refused only when the builder is collected into a group (sec. 4.2). | | Component construction timing | Deferred to `build()`. Reading a component out of the registry between `with_*` calls was never supported -- collaborators resolve in `on_startup` -- and now breaks. | | `with_health_checker` keys | Bare name at the root, so an existing readiness payload is unchanged; qualified per agent in a group. | +| OpenAPI tags and paths | Unchanged at the root: tags as the framework and the developer declare them, untagged routes under "default", every path as served today. Rewritten only per agent in a group (sec. 11.2). | | `with_cache(False)` / `with_cache(True, False)` | Unchanged (sec. 4.2). | | `Component` subclasses | No constructor change (sec. 4.3). | | `registry.cache_service` | Retained as alias. | @@ -895,6 +897,40 @@ mechanically, because a rule that cannot be violated locally will not be followe Two things an author still needs to know: their agent's name, and that handlers must not block. +### 11.2 An agent's HTTP surface + +The first question a reader of a grouped image's Swagger UI asks is *which agent*, so an agent's +operations **MUST** form one group, and nothing an agent serves may fall outside it. Swagger UI +renders tags on one level only; the second level is therefore carried by the path, never by a +sub-tag. + +Every requirement below applies to a component **with a namespace**. A root component -- every +component of a standalone agent, and the process-wide `root`, `actuators` and Dapr endpoints of a +grouped app -- keeps its declared tags and its paths (sec. 10). + +- **Tags.** Every operation of agent `` **MUST** carry exactly the tag ``, replacing any + tag the framework or the developer declared. An operation **MUST NOT** be untagged, which is what + would file it under Swagger UI's "default" group. +- **Paths.** Every path of agent `` lives under `/api//` (sec. 11). Within it, the + segments `nats`, `cache` and `scheduler` are **reserved** for the framework: + + | Endpoint | Grouped path | Standalone path (unchanged) | + |---|---|---| + | NATS publish | `/api//nats/events/{topic}` | `/events/{topic}` | + | Scheduler trigger | `/api//scheduler//trigger` | `/api//trigger` | + | Cache management | `/api//cache/...` | `/api/cache/...` | + + The Dapr endpoints are not an agent's: one process-wide pair at the root, fixed by Dapr's + protocol (sec. 6). +- **Developer paths.** A developer **MAY** declare a path prefix on their REST API class. It + applies standalone and grouped alike, so the agent's code does not depend on its grouping (C6); + it is not required, so an existing agent joins a group without a source change. `build()` + **MUST** refuse a grouped agent whose developer-declared route starts with a reserved segment, + naming the component, the route and the segment -- otherwise it would silently collide with the + framework's route of the same path. +- **Not covered.** Routes added to the `FastAPI` application directly in `main.py` do not belong + to any agent and are not subject to these rules. + --- ## 12. Acceptance criteria diff --git a/src/blueprint/agent_generator/claude_docs/CLAUDE.md b/src/blueprint/agent_generator/claude_docs/CLAUDE.md index c12f2774..dbb67e1d 100644 --- a/src/blueprint/agent_generator/claude_docs/CLAUDE.md +++ b/src/blueprint/agent_generator/claude_docs/CLAUDE.md @@ -167,7 +167,8 @@ class CleanupScheduler(SchedulerBase): ``` - **Override `on_startup` only if you also call `super().on_startup()`.** The base class is - what starts the timer, wires the tick handler and registers `POST /api//trigger`. + what starts the timer, wires the tick handler and registers `POST /api//trigger` + (`/api//scheduler//trigger` in a group). - **`scheduler_mode` decides what calls `tick()`, and it is required.** It has no default: registering a scheduler without setting it fails at startup, because neither value is safe to inherit silently. `"event"` starts no timer in the process -- the tick arrives as an ordinary diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md index 18df78a3..74d8be7a 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md @@ -78,6 +78,19 @@ beside the directory being checked. (`from .x` in `src/main.py`, `from ..x` one package down); that still works standalone. Missed, a non-critical agent is **skipped** at startup with one ERROR line naming `ModuleNotFoundError: No module named 'src'`, and its routes are silently missing from `/docs`. +- **Routes under a reserved segment.** In a group, `/api//nats/`, `/cache/` and + `/scheduler/` belong to the framework. An agent route starting with one of them (a + `@RestApiBase.get("/cache/...")`, or `path_prefix = "cache"`) raises `ValueError` at startup and + the **whole image** does not start. Standalone the same route is served, so it only shows on the + move. Rename it, or set `path_prefix` on the API class - that works standalone too. + +## Swagger in a group + +Every operation of a grouped agent is tagged with the agent's name, replacing declared tags and +tagging untagged routes, so each agent is exactly one Swagger group and nothing is under +"default". Do not add tags to "fix" grouping - they are replaced. The second level is the path: +`/api//nats/...`, `/cache/...`, `/scheduler/...`, and the developer's own paths, optionally +under a `path_prefix`. A standalone agent keeps its declared tags and paths. ## Before calling the move invisible diff --git a/src/blueprint/agent_generator/docs/components/rest-apis.md b/src/blueprint/agent_generator/docs/components/rest-apis.md index 85af6655..64618f8b 100644 --- a/src/blueprint/agent_generator/docs/components/rest-apis.md +++ b/src/blueprint/agent_generator/docs/components/rest-apis.md @@ -80,9 +80,34 @@ Each decorator accepts the following keyword arguments: |---|---|---| | `path` | `str` | The URL path (positional). Supports path parameters like `{id}`. | | `response_model` | `type` | Pydantic model for response serialization and OpenAPI documentation. | -| `tags` | `list[str]` | OpenAPI grouping tags. | +| `tags` | `list[str]` | OpenAPI grouping tags. Used as declared standalone; in a group every operation is tagged with the agent's name instead (see [Multi-Agent Setup](../guides/multi-agent-setup.md#an-agents-swagger-group-and-its-reserved-paths)). | | `summary` | `str` | Short description for OpenAPI documentation. | +## Path Prefix + +Set `path_prefix` on the class to put every route of the API under one segment: + +```python +class ReportApi(RestApiBase): + path_prefix = "reports" + + @RestApiBase.get("/daily", tags=["Reports"]) + async def daily(self) -> list[Report]: + ... +``` + +| Mode | Path | +|---|---| +| Standalone | `/api/reports/daily` | +| Agent `order` in a group | `/api/order/reports/daily` | + +The prefix is the same in both modes, so the class does not change when the agent joins a group. +It is optional -- the default `""` adds nothing -- and surrounding slashes are ignored (`"reports"` +and `"/reports/"` are the same). It also applies to routes added to `self.router` directly. + +In a group, `nats`, `cache` and `scheduler` are reserved for the framework: a route of a grouped +agent that starts with one of them, through its path or its prefix, fails startup. + ## Auto-Wiring Routes are registered automatically in `__init__`. There is no need to create a router, call `add_api_route`, or perform any manual wiring. Simply decorate your methods and they will be available when the application starts. diff --git a/src/blueprint/agent_generator/docs/components/schedulers.md b/src/blueprint/agent_generator/docs/components/schedulers.md index 8392232b..831dd8fd 100644 --- a/src/blueprint/agent_generator/docs/components/schedulers.md +++ b/src/blueprint/agent_generator/docs/components/schedulers.md @@ -111,6 +111,10 @@ The `scheduler_name` is derived from the class name. For a class named `DataSync POST /api/data_sync_scheduler/trigger ``` +In a group, the trigger moves under the agent's reserved `scheduler` segment: +`POST /api//scheduler//trigger`. The name there is the scheduler's registry name, +which a group qualifies with the agent -- `/api/order/scheduler/order_data_sync_scheduler/trigger`. + This is useful for testing, debugging, and on-demand execution without waiting for the next cron interval. ## Accessing Registry and Config diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md index 5586e5a0..6996bf56 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md @@ -278,6 +278,23 @@ imports keep working standalone as well, so the change needs no second copy. `as grep -rnE "^\s*(from|import) src(\.|\s|$)" src/ ``` +### Routes under `/nats`, `/cache` or `/scheduler` + +In a group, `nats`, `cache` and `scheduler` directly under `/api//` belong to the framework: +the agent's NATS publish endpoint, its cache management and its scheduler triggers live there. A +route of your own that starts with one of them -- `@RestApiBase.get("/cache/warmup")`, or a +`path_prefix = "cache"` -- is refused and **the image does not start**: + +``` +ValueError: WarmupApi in agent 'order' serves '/cache/warmup', which starts with the reserved +segment 'cache': in a group, /api/order/cache/ belongs to the framework's CacheManagementApi. +Rename the route, or set a path_prefix on the class. +``` + +Standalone the same route is served at `/api/cache/warmup` as before, so this only appears on the +move. Rename the route, or give the class a `path_prefix` (see +[REST APIs](../components/rest-apis.md#path-prefix)) -- both work standalone too. + --- ## After the move @@ -287,6 +304,12 @@ durables, queue groups, cache directories, telemetry -- is set out in [What changes, and what does not](multi-agent-setup.md#what-changes-and-what-does-not), and the cold-cache consequence in [The cache is cold after the move](multi-agent-setup.md#the-cache-is-cold-after-the-move). +Your **HTTP surface moves** too. Every route gains the `/api/` prefix, the NATS publish +endpoint becomes `/api//nats/events/{topic}`, a scheduler trigger becomes +`/api//scheduler//trigger`, and in Swagger UI all of the agent's operations form one +group named after it, whatever tags they declared. Clients calling the agent directly need the new +paths; see [An agent's Swagger group and its reserved paths](multi-agent-setup.md#an-agents-swagger-group-and-its-reserved-paths). + --- ## See also diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md index ff5d5c9a..a8aa3921 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md @@ -229,7 +229,9 @@ rather than asserted in prose: | NATS queue group | `nats_queue_group`, else `app_name` | | JetStream durable | `-durable` | | REST routes | `/api/orders/{id}` | -| OpenAPI tag | `Orders` | +| NATS publish endpoint | `/events/{topic}` | +| Scheduler trigger | `/api//trigger` | +| OpenAPI tag | `Orders` -- as declared; an untagged route stays under "default" | | Telemetry `service.name` | `otel_service_name` | | Disk cache directory | `cache.cache_dir` | | Redis key prefix | `cache.key_prefix` | @@ -248,7 +250,9 @@ from its own name. That is one consumer migration, and then it is over: | NATS queue group | `order` | | JetStream durable | `order--durable` | | REST routes | `/api/order/orders/{id}` | -| OpenAPI tag | `order.Orders` | +| NATS publish endpoint | `/api/order/nats/events/{topic}` | +| Scheduler trigger | `/api/order/scheduler//trigger` | +| OpenAPI tag | `order` -- on every operation of the agent, whatever it declared | | Telemetry `service.name` | `order` | | Disk cache directory | `/order.default` | | Redis key prefix | `:order.default` | @@ -265,6 +269,30 @@ wherever the agents are. `/cache/*` does move -- it becomes `/api//cache/ per agent that declared a cache, because a cache belongs to the agent that declared it and to no other. +### An agent's Swagger group and its reserved paths + +In a group, Swagger UI shows **one group per agent**, named after it, and every operation the agent +serves is in it -- its own routes, its NATS publish endpoint, its cache endpoints and its scheduler +triggers. Tags your routes declare are replaced, and an untagged route is tagged too, so nothing an +agent serves ever lands under "default". Swagger UI has only one tag level, so the second level is +the path: + +``` +/api/order/nats/... the agent's NATS publish endpoint +/api/order/cache/... the agent's cache management +/api/order/scheduler/... the agent's scheduler triggers +/api/order/ everything else the agent declares +``` + +`nats`, `cache` and `scheduler` are **reserved**: a grouped agent whose own route starts with one of +them fails the image at startup, naming the class, the route and the segment. To put your routes +under a segment of their own, set `path_prefix` on the API class (see +[REST APIs](../components/rest-apis.md#path-prefix)); it applies standalone too, so the code is the +same either way. The process-wide endpoints (`/`, `/health/*`, `/info`, `/status/*`, Dapr's +`/dapr/subscribe` and `/events/{topic}`) keep their own tags. + +A standalone agent keeps its declared tags and all of its paths -- none of this applies to it. + ### The cache is cold after the move The cache key layout has changed twice during this work, so an application upgrading with a diff --git a/src/blueprint/agent_generator/docs/reference/api.md b/src/blueprint/agent_generator/docs/reference/api.md index 1fd5e1d5..0a4baf1d 100644 --- a/src/blueprint/agent_generator/docs/reference/api.md +++ b/src/blueprint/agent_generator/docs/reference/api.md @@ -262,6 +262,13 @@ Use these to decorate methods on your subclass: |----------|------|-------------| | `router` | `APIRouter` | The FastAPI router containing all declared routes. | +### Class Attributes + +| Attribute | Type | Default | Description | +|-----------|------|---------|-------------| +| `path_prefix` | `str` | `""` | Prefix for every route of the class, applied standalone and in a group alike (`"reports"` -> `/api/reports/...`, or `/api//reports/...` in a group). Surrounding slashes are ignored. | +| `group_segment` | `str` | `""` | Framework-internal: the reserved segment (`"nats"`, `"scheduler"`) a framework component's routes sit under in a group. Not for application code. | + ### Inherited Members | Member | Type | Description | @@ -314,7 +321,8 @@ Each registered scheduler exposes: POST /{name}/trigger ``` -This endpoint allows manual invocation of the `tick()` method outside the cron schedule. +This endpoint allows manual invocation of the `tick()` method outside the cron schedule. It is +served at `/api/{name}/trigger` standalone and at `/api//scheduler/{name}/trigger` in a group. --- diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index f8fd2584..38c3860a 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -23,7 +23,6 @@ construction_scope, current_namespace, namespace_of, - qualified_entry_name, validate_namespace, ) from .component.registry import DEFAULT_CACHE_NAME, Registry @@ -66,6 +65,19 @@ checker is not a ``Component`` at all -- the object declared is the object used. """ +_RESERVED_SEGMENTS: dict[str, type] = { # `type`, not `type[RestApiBase]`: mypy rejects abstract classes there + "nats": NatsEventing, + "cache": CacheManagementApi, + "scheduler": SchedulerBase, +} +"""The first path segments under ``/api//`` the framework owns, each with its owner (spec sec. 11.2). + +Keyed on the owner's class rather than on "has a ``group_segment``": the cache API reserves +``cache`` through its own route paths, which have always read ``/cache/...``, and declares no +segment -- while a developer's scheduler subclass *is* the owner of ``scheduler``, because the +segment is inherited from ``SchedulerBase``. +""" + HandlerT = TypeVar("HandlerT", bound=EventHandlerBase) ServiceT = TypeVar("ServiceT", bound=ServiceBase) AgentT = TypeVar("AgentT", bound=AgentRuntime) @@ -523,7 +535,8 @@ def with_scheduler( Both modes need something of this agent's own -- ``"in_process"`` claims each tick in a cache **this** agent declared (:meth:`with_cache`), and ``"event"`` needs ``event_bus``, which is the group's to set. The scheduler's own REST routes move under - ``/api/`` with every other route of this agent. + ``/api//scheduler`` -- a segment reserved for schedulers -- and join the agent's + one Swagger group (spec sec. 11.2). """ return self._record("scheduler", scheduler, kwargs, name=name, method="with_scheduler") @@ -534,8 +547,9 @@ def with_rest_api( **In a group:** the routes move. A root component keeps the paths it always served under ``/api``; a component belonging to an agent serves them under ``/api/``, - and its OpenAPI tags are prefixed with the agent, so two agents that declare the same - path do not collide and each agent's operations group together in Swagger UI. Nothing in + and every operation's OpenAPI tag is replaced by the agent's name, so two agents that + declare the same path do not collide and each agent's operations form one group in + Swagger UI (spec sec. 11.2). Standalone, the declared tags are kept. Nothing in the component changes -- the prefix comes from ``RestApiBase.route_prefix``, which the namespace decides -- but a client of a grouped agent addresses the prefixed path. """ @@ -1182,8 +1196,9 @@ def _build_rest_endpoints(self, app: FastAPI, registry: Registry) -> None: # No blanket `tags=["rest"]`: it stamps every operation with a redundant "rest" tag on # top of its own resource tag, so the whole business API collapses into one "rest" group # in Swagger UI. Routes carry their per-operation tags (set via the RestApiBase decorators) - # and group correctly; untagged routes fall under FastAPI's "default", which is the nudge - # for services to tag their routes rather than hide behind a catch-all. + # and group correctly; standalone, untagged routes fall under FastAPI's "default", which + # is the nudge for services to tag their routes rather than hide behind a catch-all. In + # a group `_mount` replaces every tag with the agent's name, so nothing lands there. self._mount(app, rest_api, root_prefix="/api") for eventing_component in self._eventing_components: @@ -1255,11 +1270,17 @@ def _mount(app: FastAPI, component: RestApiBase, *, root_prefix: str) -> None: A namespaced component ignores it and takes ``route_prefix`` instead, so both kinds end up under one prefix per agent. - The tags are rewritten rather than added to, so an agent's operations form their own - group in Swagger UI instead of appearing twice -- once under the agent and once under - the bare resource name. ``include_router(tags=...)`` appends, which is why this is done - on the routes. Mutating them is safe because a router belongs to exactly one component - and ``build()`` runs once per process (``Component.configure`` refuses a second call). + A namespaced component's operations are all tagged with exactly the agent's name, replacing + whatever the framework or the developer declared, and untagged ones included (spec sec. + 11.2). A reader of a grouped image's Swagger UI starts from *which agent*, and Swagger UI + has one tag level: a declared tag kept beside the agent's would list the operation in two + groups, and an untagged one would land in "default", mixed with every other agent's. The + second level is the path (``RestApiBase.group_segment``), not a tag. + + ``include_router(tags=...)`` appends, which is why this is done on the routes. Mutating + them is safe because a router belongs to exactly one component and ``build()`` runs once + per process (``Component.configure`` refuses a second call). A root component's tags are + left exactly as declared. Args: app: The application to mount on. @@ -1268,13 +1289,50 @@ def _mount(app: FastAPI, component: RestApiBase, *, root_prefix: str) -> None: """ prefix = component.route_prefix or root_prefix if component.namespace: + AppBuilder._refuse_reserved_segments(component) for route in component.router.routes: # A Starlette BaseRoute has no tags; an APIRoute does, and those are the # ones the decorators produce. Anything else is left alone. - if isinstance(route, APIRoute) and route.tags: - route.tags = [qualified_entry_name(component.namespace, str(tag)) for tag in route.tags] + if isinstance(route, APIRoute): + route.tags = [component.namespace] app.include_router(component.router, prefix=prefix) + @staticmethod + def _refuse_reserved_segments(component: RestApiBase) -> None: + """Raise if a grouped agent's route claims a path segment the framework owns. + + Inside ``/api//`` the segments ``nats``, ``cache`` and ``scheduler`` belong to the + framework (spec sec. 11.2). FastAPI does not detect duplicate routes -- it serves the + first match -- so a developer's ``/cache/stats`` beside the framework's would silently + answer for one of them, depending on mount order. Refused here, in ``build()``, because + that is the first point at which both the routes and the agent are known. + + Only called for a namespaced component: a standalone agent's paths are its own, and a + route it has always served at ``/api/cache/...`` must keep working (spec sec. 10). + + The segment is read from the path *relative to the agent's prefix*, so a component with a + :attr:`~RestApiBase.group_segment` is judged by that segment, and a :attr:`~RestApiBase.path_prefix` + is judged as part of the route. Every route kind with a path is checked, not only + ``APIRoute``: a websocket at ``/cache/live`` collides just the same. + + Raises: + ValueError: naming the component, the agent, the route and the owner of the segment. + """ + agent_prefix = f"/api/{component.namespace}" + for route in component.router.routes: + path = getattr(route, "path", None) + if not isinstance(path, str): + continue + relative = component.route_prefix.removeprefix(agent_prefix) + path + segment = relative.lstrip("/").split("/", 1)[0] + owner = _RESERVED_SEGMENTS.get(segment) + if owner is not None and not isinstance(component, owner): + raise ValueError( + f"{type(component).__name__} in agent {component.namespace!r} serves {path!r}, which starts with " + f"the reserved segment {segment!r}: in a group, {agent_prefix}/{segment}/ belongs to the framework's " + f"{owner.__name__}. Rename the route, or set a path_prefix on the class." + ) + # ------------------------------------------------------------------ # Lifespan # ------------------------------------------------------------------ diff --git a/src/blueprint/agents/component/namespace.py b/src/blueprint/agents/component/namespace.py index f4c9e15d..bdad4e45 100644 --- a/src/blueprint/agents/component/namespace.py +++ b/src/blueprint/agents/component/namespace.py @@ -252,8 +252,9 @@ def qualified_entry_name(namespace: str, name: str) -> str: """Return the name ``name`` is *displayed* under inside ``namespace``. For the names that identify something in a payload or a document rather than in the - registry: a readiness entry, an OpenAPI tag. The root keeps the bare name, so a - single-agent application's readiness payload and Swagger groups do not change. + registry, such as a readiness entry. The root keeps the bare name, so a single-agent + application's readiness payload does not change. (OpenAPI tags used to be rendered this + way too; a grouped agent's are now its bare name, spec sec. 11.2.) ``.`` rather than the ``_`` of :func:`qualified_component_name`, and the two are not interchangeable. A registry name is an identifier that other code *looks up*, and ``_`` is diff --git a/src/blueprint/agents/io/api/eventing/nats.py b/src/blueprint/agents/io/api/eventing/nats.py index dade87f8..d2983938 100644 --- a/src/blueprint/agents/io/api/eventing/nats.py +++ b/src/blueprint/agents/io/api/eventing/nats.py @@ -47,8 +47,13 @@ class NatsEventing(EventHandlingBase): which would silently disable one agent's subscription, and could not be observed by its author running it alone. Deduplication happens inside one of these components, so it cannot reach across namespaces by construction. + + In a group its publish endpoint is ``/api//nats/events/{topic}``; standalone it + stays ``/events/{topic}`` (spec sec. 11.2). """ + group_segment = "nats" + def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: """Initialize the NATS endpoint for one agent. diff --git a/src/blueprint/agents/io/api/rest_api_base.py b/src/blueprint/agents/io/api/rest_api_base.py index 1f1a142a..69030517 100644 --- a/src/blueprint/agents/io/api/rest_api_base.py +++ b/src/blueprint/agents/io/api/rest_api_base.py @@ -44,6 +44,16 @@ async def create_item(self, payload: ItemRequest) -> Item: logger = logging.getLogger(__name__) +def _normalise_path_prefix(value: str) -> str: + """Return ``value`` in the form ``APIRouter(prefix=...)`` requires: ``""`` or ``/segment``. + + FastAPI asserts a prefix starts with ``/`` and does not end with one; a developer writing + ``"reports"`` or ``"/reports/"`` means the same thing, so both are accepted. + """ + stripped = value.strip().strip("/") + return f"/{stripped}" if stripped else "" + + class RestApiBase(IOBase, ABC): """Base class for REST API components. @@ -63,6 +73,29 @@ class RestApiBase(IOBase, ABC): which routes it is allowed to answer for. """ + group_segment: str = "" + """Path segment this component's routes sit under inside an agent's prefix, in a group only. + + Set by the framework's own components that belong to an agent (``"nats"``, ``"scheduler"``) + so an agent's paths read ``/api///...`` and those segments stay reserved + for the framework (spec sec. 11.2). A root component ignores it: a standalone agent's paths + are a contract with its existing clients and do not move. ``""`` adds no segment. + """ + + path_prefix: str = "" + """Path prefix a developer puts in front of every route of this API, in both modes. + + ``path_prefix = "reports"`` serves ``@RestApiBase.get("/daily")`` at ``/api/reports/daily`` + standalone and at ``/api//reports/daily`` in a group -- the same code either way + (spec sec. 11.2, C6). Optional: ``""``, the default, adds nothing, so an existing API's paths + do not move. Surrounding slashes are ignored, so ``"reports"`` and ``"/reports/"`` are the + same prefix. + + Applied as the router's own prefix, so it reaches routes added to :attr:`router` directly as + well as decorated ones. Unlike :attr:`group_segment` it is part of each route's path, not of + the mount, which is why it applies at the root too. + """ + def __init__(self, should_register: bool = True, *, namespace: str = ROOT_NAMESPACE) -> None: """Initialize the REST API and wire its declared routes. @@ -74,7 +107,7 @@ def __init__(self, should_register: bool = True, *, namespace: str = ROOT_NAMESP per-agent endpoints are built outside any scope and name it. """ super().__init__(should_register, namespace=namespace) - self._router = APIRouter(route_class=type(self).route_class) + self._router = APIRouter(prefix=_normalise_path_prefix(type(self).path_prefix), route_class=type(self).route_class) self._wire_routes() @property @@ -82,7 +115,8 @@ def route_prefix(self) -> str: """The path prefix this component's routes are mounted under. ``""`` for the root, so every path an existing application serves is unchanged, and - ``/api/`` for a component that belongs to one. An agent's whole HTTP surface + ``/api/`` for a component that belongs to one -- ``/api//`` when + the component declares a :attr:`group_segment`. An agent's whole HTTP surface therefore lives under one prefix, and two agents in a group cannot collide on a path -- which they otherwise would, since a group applies the same registration twice and both copies declare the same routes. @@ -93,7 +127,11 @@ def route_prefix(self) -> str: two disagreed the sidecar would post to a path FastAPI does not serve, and every delivery would 404 -- with the application otherwise healthy. """ - return f"/api/{self.namespace}" if self.namespace else "" + if not self.namespace: + return "" + if self.group_segment: + return f"/api/{self.namespace}/{self.group_segment}" + return f"/api/{self.namespace}" @property def router(self) -> APIRouter: diff --git a/src/blueprint/agents/io/api/scheduling/scheduler.py b/src/blueprint/agents/io/api/scheduling/scheduler.py index e50f3f16..c3a59d38 100644 --- a/src/blueprint/agents/io/api/scheduling/scheduler.py +++ b/src/blueprint/agents/io/api/scheduling/scheduler.py @@ -23,7 +23,8 @@ than on the code -- see :meth:`SchedulerBase._resolve_mode`. A REST endpoint for manual triggering is registered under ``/{name}/trigger`` in -both modes. +both modes: ``/api/{name}/trigger`` standalone, ``/api//scheduler/{name}/trigger`` +in a group (spec sec. 11.2). Example:: @@ -228,6 +229,8 @@ class SchedulerBase(RestApiBase): already published on a subject someone else owns. """ + group_segment = "scheduler" + def __init__(self, crontab: str, *, topic: str | None = None) -> None: super().__init__() self._crontab = crontab diff --git a/tests/unit/agents/app_builder/test_route_namespacing.py b/tests/unit/agents/app_builder/test_route_namespacing.py index 8a7341fe..38cf8dd8 100644 --- a/tests/unit/agents/app_builder/test_route_namespacing.py +++ b/tests/unit/agents/app_builder/test_route_namespacing.py @@ -24,7 +24,9 @@ from blueprint.agents.config import Config from blueprint.agents.handler.event_handler_base import EventHandlerBase from blueprint.agents.io.api.eventing.dapr import DaprEventing +from blueprint.agents.io.api.eventing.nats import NatsEventing from blueprint.agents.io.api.rest_api_base import RestApiBase +from blueprint.agents.io.api.scheduling import SchedulerBase from blueprint.agents.models.events import GenericCloudEvent @@ -40,6 +42,18 @@ async def list_orders(self) -> list[str]: return [] +class SegmentedApi(OrderApi): + group_segment = "reports" + + +class NightlyScheduler(SchedulerBase): + def __init__(self) -> None: + super().__init__(crontab="0 3 * * *") + + async def tick(self) -> None: + pass + + class OrderHandler(EventHandlerBase): async def on_startup(self) -> None: pass @@ -122,6 +136,22 @@ def test_an_agents_component_is_prefixed_with_its_name(self, dapr_config: Config api = OrderApi() assert api.route_prefix == "/api/orders" + def test_an_agents_segment_follows_its_prefix(self, dapr_config: Config) -> None: + Component.configure(dapr_config) + with namespace_scope("orders"): + api = SegmentedApi() + assert api.route_prefix == "/api/orders/reports" + + def test_a_root_component_ignores_its_segment(self, dapr_config: Config) -> None: + """A standalone agent's paths are a contract with its clients; a segment must not move them.""" + Component.configure(dapr_config) + assert SegmentedApi().route_prefix == "" + + def test_the_framework_reserves_its_segments(self) -> None: + assert NatsEventing.group_segment == "nats" + assert SchedulerBase.group_segment == "scheduler" + assert DaprEventing.group_segment == "" + def test_the_dapr_endpoint_is_always_the_root_one(self, dapr_config: Config) -> None: """It takes no namespace at all: Dapr's paths are fixed, so there is one endpoint.""" Component.configure(dapr_config) @@ -148,30 +178,172 @@ def test_two_agents_declaring_one_route_do_not_collide(self, dapr_config: Config assert {"/api/orders/orders", "/api/billing/orders"} <= set(paths(app)) +class ItemApi(RestApiBase): + """One route per tagging shape a developer can write.""" + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + @RestApiBase.get("/items", tags=["Items"]) + async def list_items(self) -> list[str]: + return [] + + @RestApiBase.get("/untagged") + async def untagged(self) -> list[str]: + return [] + + @RestApiBase.get("/multi", tags=["Items", "Reports"]) + async def multi(self) -> list[str]: + return [] + + class TestTags: - def test_an_agents_tags_are_prefixed(self, dapr_config: Config) -> None: - app = AgentGroup("g", {"orders": AppBuilder().with_rest_api(OrderApi)}).assemble(dapr_config) + """In a group an agent's operations form exactly one Swagger group, named after the agent (spec sec. 11.2).""" - assert tags_for(app, "/api/orders/orders") == ["orders.orders"] + def test_a_declared_tag_is_replaced_by_the_agent(self, dapr_config: Config) -> None: + """Kept beside the agent's tag, it would list the operation in two Swagger groups.""" + app = AgentGroup("g", {"orders": AppBuilder().with_rest_api(ItemApi)}).assemble(dapr_config) - def test_the_bare_tag_is_replaced_rather_than_added_to(self, dapr_config: Config) -> None: - """Appending would put the operation in two Swagger groups instead of one.""" - app = AgentGroup("g", {"orders": AppBuilder().with_rest_api(OrderApi)}).assemble(dapr_config) + assert tags_for(app, "/api/orders/items") == ["orders"] + + def test_an_untagged_route_is_tagged_with_the_agent(self, dapr_config: Config) -> None: + """The defect this replaces: untagged, it landed in "default" with every other agent's.""" + app = AgentGroup("g", {"orders": AppBuilder().with_rest_api(ItemApi)}).assemble(dapr_config) + + assert tags_for(app, "/api/orders/untagged") == ["orders"] + + def test_several_declared_tags_collapse_into_one(self, dapr_config: Config) -> None: + app = AgentGroup("g", {"orders": AppBuilder().with_rest_api(ItemApi)}).assemble(dapr_config) + + assert tags_for(app, "/api/orders/multi") == ["orders"] + + def test_the_framework_endpoints_join_the_agents_group(self, nats_config: Config) -> None: + app = AgentGroup("g", {"orders": AppBuilder().with_handler(OrderHandler)}).assemble(nats_config) + + assert tags_for(app, "/api/orders/nats/events/{topic}") == ["orders"] + + def test_no_agent_operation_is_left_in_default(self, dapr_config: Config) -> None: + declaration = AppBuilder().with_rest_api(ItemApi) + + app = AgentGroup("g", {"orders": declaration, "billing": declaration}).assemble(dapr_config) - assert "orders" not in tags_for(app, "/api/orders/orders") + for path, operations in app.openapi()["paths"].items(): + if path.startswith("/api/"): + for operation in operations.values(): + assert operation.get("tags") == [path.split("/")[2]], path def test_two_agents_tags_do_not_merge(self, dapr_config: Config) -> None: - declaration = AppBuilder().with_rest_api(OrderApi) + declaration = AppBuilder().with_rest_api(ItemApi) app = AgentGroup("g", {"orders": declaration, "billing": declaration}).assemble(dapr_config) - assert tags_for(app, "/api/orders/orders") == ["orders.orders"] - assert tags_for(app, "/api/billing/orders") == ["billing.orders"] + assert tags_for(app, "/api/orders/items") == ["orders"] + assert tags_for(app, "/api/billing/items") == ["billing"] def test_a_root_components_tags_are_untouched(self, dapr_config: Config) -> None: - app = AppBuilder(dapr_config).with_rest_api(OrderApi).build() + """Standalone keeps what was declared -- including no tag at all, which is "default".""" + app = AppBuilder(dapr_config).with_rest_api(ItemApi).build() + + assert tags_for(app, "/api/items") == ["Items"] + assert tags_for(app, "/api/untagged") == [] + assert tags_for(app, "/api/multi") == ["Items", "Reports"] + + +class ReportApi(RestApiBase): + path_prefix = "reports" + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass - assert tags_for(app, "/api/orders") == ["orders"] + @RestApiBase.get("/daily") + async def daily(self) -> list[str]: + return [] + + +class SlashedReportApi(ReportApi): + path_prefix = "/reports/" + + +class CacheLookalikeApi(OrderApi): + """A developer route in a segment the framework owns.""" + + @RestApiBase.get("/cache/stats") + async def stats(self) -> dict[str, int]: + return {} + + +class NatsPrefixedApi(ReportApi): + path_prefix = "nats" + + +class CachesApi(OrderApi): + """``caches`` is not ``cache``: the segment is matched whole.""" + + @RestApiBase.get("/caches/stats") + async def stats(self) -> dict[str, int]: + return {} + + +class TestPathPrefix: + """A developer's optional prefix, applied the same in both modes (spec sec. 11.2).""" + + def test_standalone_it_follows_api(self, dapr_config: Config) -> None: + app = AppBuilder(dapr_config).with_rest_api(ReportApi).build() + + assert "/api/reports/daily" in paths(app) + + def test_in_a_group_it_follows_the_agent(self, dapr_config: Config) -> None: + app = AgentGroup("g", {"orders": AppBuilder().with_rest_api(ReportApi)}).assemble(dapr_config) + + assert "/api/orders/reports/daily" in paths(app) + + def test_surrounding_slashes_are_ignored(self, dapr_config: Config) -> None: + app = AppBuilder(dapr_config).with_rest_api(SlashedReportApi).build() + + assert "/api/reports/daily" in paths(app) + + def test_no_prefix_moves_nothing(self, dapr_config: Config) -> None: + assert OrderApi.path_prefix == "" + assert OrderApi().router.prefix == "" + + +class TestReservedSegments: + """In a group, ``nats``, ``cache`` and ``scheduler`` under ``/api//`` are the framework's.""" + + def test_a_grouped_route_in_a_reserved_segment_is_refused(self, dapr_config: Config) -> None: + declaration = AppBuilder().with_rest_api(CacheLookalikeApi) + + with pytest.raises(ValueError, match=r"CacheLookalikeApi in agent 'orders' serves '/cache/stats'.*'cache'.*CacheManagementApi"): + AgentGroup("g", {"orders": declaration}).assemble(dapr_config) + + def test_a_reserved_path_prefix_is_refused(self, dapr_config: Config) -> None: + declaration = AppBuilder().with_rest_api(NatsPrefixedApi) + + with pytest.raises(ValueError, match=r"'nats'.*NatsEventing"): + AgentGroup("g", {"orders": declaration}).assemble(dapr_config) + + def test_standalone_the_same_route_is_served(self, dapr_config: Config) -> None: + """Standalone paths are the agent's own; ``/api/cache/stats`` may have clients (spec sec. 10).""" + app = AppBuilder(dapr_config).with_rest_api(CacheLookalikeApi).build() + + assert "/api/cache/stats" in paths(app) + + def test_the_segment_is_matched_whole(self, dapr_config: Config) -> None: + app = AgentGroup("g", {"orders": AppBuilder().with_rest_api(CachesApi)}).assemble(dapr_config) + + assert "/api/orders/caches/stats" in paths(app) + + def test_a_developers_scheduler_owns_the_scheduler_segment(self, scheduler_config: Config) -> None: + """It inherits ``SchedulerBase``, the owner. NATS and cache are covered by their own route tests.""" + app = AgentGroup("g", {"orders": AppBuilder().with_scheduler(NightlyScheduler)}).assemble(scheduler_config) + + assert [path for path in paths(app) if path.startswith("/api/orders/scheduler/")] class TestEventingRoutes: @@ -187,6 +359,7 @@ def test_the_dapr_delivery_path_never_moves(self, dapr_config: Config) -> None: assert {"/events/{topic}", "/dapr/subscribe"} <= set(paths(app)) assert "/api/orders/events/{topic}" not in paths(app) + assert "/api/orders/nats/events/{topic}" not in paths(app) def test_two_agents_get_their_own_nats_delivery_paths(self, nats_config: Config) -> None: """Unprefixed, FastAPI would serve one agent's endpoint for both agents' deliveries.""" @@ -194,7 +367,14 @@ def test_two_agents_get_their_own_nats_delivery_paths(self, nats_config: Config) app = AgentGroup("g", {"orders": declaration, "billing": declaration}).assemble(nats_config) - assert {"/api/orders/events/{topic}", "/api/billing/events/{topic}"} <= set(paths(app)) + assert {"/api/orders/nats/events/{topic}", "/api/billing/nats/events/{topic}"} <= set(paths(app)) + assert not [path for path in paths(app) if path.startswith("/api/orders/events")] + + def test_a_standalone_nats_path_is_unchanged(self, nats_config: Config) -> None: + app = AppBuilder(nats_config).with_handler(OrderHandler).build() + + assert "/events/{topic}" in paths(app) + assert not [path for path in paths(app) if "/nats/" in path] async def test_a_root_document_is_unchanged(self, dapr_config: Config) -> None: Component.configure(dapr_config) @@ -205,6 +385,31 @@ async def test_a_root_document_is_unchanged(self, dapr_config: Config) -> None: assert document == [{"pubsubname": "pubsub", "topic": "orders.created", "route": "/events/orders.created"}] +@pytest.fixture +def scheduler_config(tmp_path: Path) -> Config: + settings = tmp_path / "settings.toml" + settings.write_text( + '[development]\napp_name = "root-app"\napp_port = 8000\nevent_bus = "nats"\nscheduler_mode = "in_process"\n\n' + '[development.orders]\napp_name = "orders"\n' + ) + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + +class TestSchedulerRoutes: + def test_an_agents_trigger_lives_under_the_scheduler_segment(self, scheduler_config: Config) -> None: + app = AgentGroup("g", {"orders": AppBuilder().with_scheduler(NightlyScheduler)}).assemble(scheduler_config) + + triggers = [path for path in paths(app) if path.endswith("/trigger")] + assert len(triggers) == 1 + assert triggers[0].startswith("/api/orders/scheduler/") + + def test_a_standalone_trigger_path_is_unchanged(self, scheduler_config: Config) -> None: + scheduler = NightlyScheduler() + app = AppBuilder(scheduler_config).with_scheduler(scheduler).build() + + assert f"/api/{scheduler.name}/trigger" in paths(app) + + class TestCacheEndpointsPerAgent: """``/cache/*`` is per agent, because one process-wide endpoint reports one agent's keys to another. From afa2ce7f2e6a572b87628c410a4273536e6cf58d Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Fri, 9 Oct 2026 18:14:41 +0200 Subject: [PATCH 069/133] fix(logging): leave successful health probes out of the access log HealthCheckFilter searched uvicorn's access line for " 200 ", but uvicorn logs '%s - "%s %s HTTP/%s" %d' -- the status code ends the line -- so the filter never matched and every /health/live and /health/ready probe was logged. It shows in the grouped image: the entrypoint builds the app before uvicorn.run(app, log_level=...), which resets uvicorn.access to INFO after suppress_noisy_loggers had set it to WARNING. The filter now parses the line, matches the path (query string excluded) against /health/live and /health/ready as a suffix, and drops 2xx only. A failed or redirected probe, and a line it cannot parse, is still logged. The tests built records in an invented format the old check happened to match; they now use uvicorn's format string and arguments. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 8 +++ ...26-08-28-multi-agent-grouping-changelog.md | 22 +++++++ src/blueprint/agents/config/custom_logging.py | 38 +++++++---- .../agents/config/test_health_check_filter.py | 65 +++++++++++-------- 4 files changed, 95 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ae8fdd82..5b6c6afc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,14 @@ ### Fixed +- **Successful health probes are left out of the access log, as documented.** `HealthCheckFilter` + looked for `" 200 "` in uvicorn's access line, but uvicorn ends that line with the status code, + so the filter never matched and every `/health/live` and `/health/ready` probe was logged. It now + parses the line, drops 2xx responses on those two paths (with or without a query string), and + keeps everything else -- a failed or redirected probe is still logged. Visible wherever + `uvicorn.access` logs at INFO: the grouped image's `python -m blueprint.agents.entrypoint`, which + calls `uvicorn.run(app, log_level=...)` after the app is built and so resets that logger's level, + and any deployment with `suppress_noisy_loggers = false`. - **A standalone agent's `Config` reads `hostname`, `pod_name` and `blueprint_group` again.** Since the 0.9 alphas, `get()` raised for these keys everywhere. The refusal exists so that an agent in a group cannot depend on where it runs; it now applies only to an agent's view in a group. diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 639a0f69..7474b36a 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8148,6 +8148,28 @@ grouped 0.9 deployment's clients of `/api//events/{topic}` and `/api/ + `uvicorn.run(app, log_level=...)`, which sets `uvicorn.access` back to the uvicorn level -- and + from there only the filter stood between the probes and the log. +- `test_health_check_filter.py` built records in an invented format (`GET /health/live HTTP/1.1 + 200 0`) that the old check happened to match. The records are now built from uvicorn's format + string and arguments, and a test pins how they render. Checked against a real uvicorn server in + the entrypoint's order: before, `/health/live` 200 was logged; after, only the 503 probe and the + ordinary route are. + --- ## Open points diff --git a/src/blueprint/agents/config/custom_logging.py b/src/blueprint/agents/config/custom_logging.py index c8950129..a2a58029 100644 --- a/src/blueprint/agents/config/custom_logging.py +++ b/src/blueprint/agents/config/custom_logging.py @@ -4,28 +4,44 @@ import contextvars import logging +import re import sys +HEALTH_PROBE_PATHS = ("/health/live", "/health/ready") +"""Paths whose successful requests are left out of the access log. + +Matched as suffixes of the request path, so a probe served under a route prefix is caught too. +""" + +_ACCESS_LINE = re.compile(r'"[A-Z]+ (?P[^ ?"]*)\S* HTTP/[^"]*" (?P\d{3})') +"""The request line and status of a uvicorn access record. + +uvicorn logs ``'%s - "%s %s HTTP/%s" %d'``, which renders as +``10.0.0.1:5000 - "GET /health/ready?probe=1 HTTP/1.1" 200``. ``path`` excludes the query string. +""" + class HealthCheckFilter(logging.Filter): """Filter to suppress successful health check requests from logs.""" def filter(self, record: logging.LogRecord) -> bool: - """Filter out successful health check requests. + """Drop a successful (2xx) health probe from uvicorn's access log; keep everything else. + + The record is parsed in uvicorn's own line format. The previous version searched the line + for ``" 200 "``, but uvicorn ends the line with the status code -- there is no space after + it -- so the filter never matched and every Kubernetes and Docker probe was logged. - Only logs health checks if they fail (status >= 400). + A line that does not parse is kept: a changed format then costs log volume, not a lost + failure. """ - message = record.getMessage() + if record.name != "uvicorn.access": + return True - # Check if this is a uvicorn access log for health endpoints - if hasattr(record, "name") and record.name == "uvicorn.access": - # Filter out successful health check requests (status 200) - if "/health/live" in message or "/health/ready" in message: - # Only log if it's an error (status >= 400) - if " 200 " in message or " 204 " in message: - return False + match = _ACCESS_LINE.search(record.getMessage()) + if match is None or not match["path"].endswith(HEALTH_PROBE_PATHS): + return True - return True + return not 200 <= int(match["status"]) < 300 class CorrelationContext: diff --git a/tests/unit/agents/config/test_health_check_filter.py b/tests/unit/agents/config/test_health_check_filter.py index 77a9467d..d050cc9d 100644 --- a/tests/unit/agents/config/test_health_check_filter.py +++ b/tests/unit/agents/config/test_health_check_filter.py @@ -6,15 +6,23 @@ from blueprint.agents.config.custom_logging import HealthCheckFilter +UVICORN_ACCESS_FORMAT = '%s - "%s %s HTTP/%s" %d' +"""The format string uvicorn's h11 and httptools protocols pass to ``uvicorn.access``. -def _make_record(name: str, message: str) -> logging.LogRecord: +The records below are built the way uvicorn builds them. The previous tests used an invented +format (``GET /health/live HTTP/1.1 200 0``) that the old substring check happened to match, +while uvicorn's real line -- which ends with the status code -- never did. +""" + + +def _access_record(path: str, status: int, method: str = "GET", name: str = "uvicorn.access") -> logging.LogRecord: return logging.LogRecord( name=name, level=logging.INFO, pathname="", lineno=0, - msg=message, - args=(), + msg=UVICORN_ACCESS_FORMAT, + args=("10.0.0.1:51234", method, path, "1.1", status), exc_info=None, ) @@ -24,36 +32,39 @@ class TestHealthCheckFilter: def health_filter(self) -> HealthCheckFilter: return HealthCheckFilter() - def test_filters_live_200(self, health_filter: HealthCheckFilter) -> None: - record = _make_record("uvicorn.access", "GET /health/live HTTP/1.1 200 0") - assert health_filter.filter(record) is False + def test_record_renders_as_uvicorn_does(self) -> None: + """Guards the fixture: the status code ends the line, with nothing after it.""" + assert _access_record("/health/ready", 200).getMessage() == '10.0.0.1:51234 - "GET /health/ready HTTP/1.1" 200' - def test_filters_ready_200(self, health_filter: HealthCheckFilter) -> None: - record = _make_record("uvicorn.access", "GET /health/ready HTTP/1.1 200 0") - assert health_filter.filter(record) is False + @pytest.mark.parametrize("path", ["/health/live", "/health/ready"]) + @pytest.mark.parametrize("status", [200, 204]) + def test_drops_successful_probe(self, health_filter: HealthCheckFilter, path: str, status: int) -> None: + assert health_filter.filter(_access_record(path, status)) is False - def test_filters_ready_204(self, health_filter: HealthCheckFilter) -> None: - record = _make_record("uvicorn.access", "GET /health/ready HTTP/1.1 204 0") - assert health_filter.filter(record) is False + def test_drops_successful_probe_with_query_string(self, health_filter: HealthCheckFilter) -> None: + assert health_filter.filter(_access_record("/health/ready?probe=k8s", 200)) is False - def test_passes_live_500_error(self, health_filter: HealthCheckFilter) -> None: - """Failed health checks should still be logged.""" - record = _make_record("uvicorn.access", "GET /health/live HTTP/1.1 500 0") - assert health_filter.filter(record) is True + def test_drops_successful_probe_under_route_prefix(self, health_filter: HealthCheckFilter) -> None: + assert health_filter.filter(_access_record("/svc/health/live", 200)) is False - def test_passes_ready_404_error(self, health_filter: HealthCheckFilter) -> None: - record = _make_record("uvicorn.access", "GET /health/ready HTTP/1.1 404 0") - assert health_filter.filter(record) is True + @pytest.mark.parametrize("status", [307, 404, 500, 503]) + def test_keeps_unsuccessful_probe(self, health_filter: HealthCheckFilter, status: int) -> None: + """A probe that did not succeed is exactly what the access log is read for.""" + assert health_filter.filter(_access_record("/health/ready", status)) is True - def test_passes_non_health_route_200(self, health_filter: HealthCheckFilter) -> None: - record = _make_record("uvicorn.access", "GET /api/v1/agents HTTP/1.1 200 42") - assert health_filter.filter(record) is True + @pytest.mark.parametrize("path", ["/api/v1/agents", "/health", "/health/live/extra", "/status/env"]) + def test_keeps_other_routes(self, health_filter: HealthCheckFilter, path: str) -> None: + assert health_filter.filter(_access_record(path, 200)) is True + + def test_keeps_health_path_only_in_query_string(self, health_filter: HealthCheckFilter) -> None: + assert health_filter.filter(_access_record("/api/v1/redirect?to=/health/live", 200)) is True - def test_passes_non_uvicorn_access_logger(self, health_filter: HealthCheckFilter) -> None: + @pytest.mark.parametrize("name", ["myapp.server", "root", "uvicorn.error"]) + def test_keeps_records_of_other_loggers(self, health_filter: HealthCheckFilter, name: str) -> None: """Health-check filtering only applies to the uvicorn.access logger.""" - record = _make_record("myapp.server", "GET /health/live HTTP/1.1 200 0") - assert health_filter.filter(record) is True + assert health_filter.filter(_access_record("/health/live", 200, name=name)) is True - def test_passes_root_logger_record(self, health_filter: HealthCheckFilter) -> None: - record = _make_record("root", "GET /health/live HTTP/1.1 200 0") + def test_keeps_unparseable_access_line(self, health_filter: HealthCheckFilter) -> None: + """A format uvicorn might change to costs log volume, never a lost failure line.""" + record = logging.LogRecord("uvicorn.access", logging.INFO, "", 0, "GET /health/live 200", (), None) assert health_filter.filter(record) is True From a20a2b70b3f86d0d1b03618d272589519af29cee Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 14 Oct 2026 10:54:38 +0200 Subject: [PATCH 070/133] fix(nats): run deliveries concurrently and keep long runs alive nats-py gives each subscription one task that awaits its callback, and the callback ran the whole handler chain, so an agent handled one event per subscription and process at a time however much of the run was spent waiting on a model. message_handler now only waits for a slot of nats_max_concurrent_runs (default 1, the previous behaviour) and starts the delivery as its own task; _run_finished frees the slot and keeps the in-flight count that shutdown and pause wait on. While a JetStream run is in progress its delivery is reported in_progress every third of the bound consumer's ack_wait, so a run longer than ack_wait is no longer redelivered while it still runs (handler-time-bounds spec sec. 4.1/4.2). Measured against nats:2.10 with 2 s handlers: 5 events 10.1 s -> 4.0 s at 4 runs; a 7 s run under a 3 s ack_wait ran three times before, once after. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 13 ++ ...26-08-28-multi-agent-grouping-changelog.md | 43 +++++ .../docs/concepts/event-processing.md | 18 +- .../agent_generator/docs/guides/deployment.md | 10 +- .../docs/reference/configuration-keys.md | 4 +- .../agents/clients/io/nats_client.py | 159 +++++++++++++++--- .../agents/clients/io/test_nats_client.py | 28 ++- 7 files changed, 238 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b6c6afc..3e111a4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,16 @@ ### Fixed +- **NATS deliveries are no longer handled strictly one at a time.** nats-py gives each subscription + one task that awaits its callback, and the callback ran the whole handler -- so an agent handled + one event per subscription and process at a time, however much of the run was spent waiting on a + model. Each delivery now runs as its own task, up to the new `nats_max_concurrent_runs` per agent + (default `1`, the previous behaviour). Measured against a real broker with 2 s handlers: 5 events + took 10 s before and 4 s with the key at 4. +- **A long JetStream run is no longer redelivered while it still runs.** The delivery is reported + `in_progress` every third of the bound consumer's `ack_wait` until it is settled. Measured: one + 7 s run under a 3 s `ack_wait` ran three times before, once now. + - **Successful health probes are left out of the access log, as documented.** `HealthCheckFilter` looked for `" 200 "` in uvicorn's access line, but uvicorn ends that line with the status code, so the filter never matched and every `/health/live` and `/health/ready` probe was logged. It now @@ -153,6 +163,9 @@ ### Added +- **`nats_max_concurrent_runs`** (int, default `1`): how many deliveries an agent handles at once per + process, across all of its subscriptions. With every slot taken the subscription stops taking + messages; keep `nats_max_ack_pending` near replicas x this value. - **`RestApiBase.path_prefix`**, an optional class attribute putting every route of an API under one segment -- `/api/reports/...` standalone, `/api//reports/...` in a group. Default `""`, so no existing path moves. diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 7474b36a..33a47039 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8170,6 +8170,49 @@ this feature -- the filter never worked -- but the group entrypoint is where it the entrypoint's order: before, `/health/live` 200 was logged; after, only the 503 probe and the ordinary route are. +### Deliveries run concurrently, and long runs send heartbeats + +Found while measuring an agent group against a real broker (2026-10-14): every agent handled +one NATS event per subscription and process at a time. nats-py gives a subscription one task, which +awaits the callback before taking the next message (`nats/aio/subscription.py`, `_wait_for_msgs`), +and `message_handler` ran the whole handler chain inside that callback. An agent spending minutes +per run waiting on a model therefore queued every further event behind it, on an idle event loop. +The behaviour dates from the first NATS commit (`c347f30`); P1/P3 contained it with +`max_ack_pending` 16, which `604bebb` made opt-in again. + +- `_subscribe_one.message_handler` now only acquires a slot of `_run_slots` (an + `asyncio.Semaphore` of `nats_max_concurrent_runs`, created in `subscribe()`), counts the delivery + in with `_enter_handler()`, and starts `_run_delivery` as a task kept in `_runs`. Waiting for the + slot inside the callback is the back-pressure: with every slot taken the subscription's task stops + taking messages. +- `_run_delivery` is the former callback body -- decode, dispatch, settle with the sec. 7.2 table -- + plus a heartbeat around the dispatch, stopped before settling. A cancelled run is not settled. +- `_run_finished` (done-callback) frees the slot and calls `_exit_handler()`, so `close()` and + `pause_consumption()` still wait for running deliveries through `_await_inflight`, although the + callback has already returned. It logs a run that failed outside its handler. +- `_start_heartbeat` / `_keep_alive` / `_heartbeat_finished`: JetStream only, `in_progress()` every + `ack_wait / 3` of the bound consumer's config (stored per topic in `_ack_waits` from + `_ensure_consumer`'s result; `SERVER_DEFAULT_ACK_WAIT` if the config has none) -- Part A sec. 4.1 + and 4.2 of `docs/specs/2026-09-24-handler-time-bounds.md`, without its `nats_heartbeat_enabled` + switch and hard limit. A failed heartbeat is logged at DEBUG and never fails the run. +- `nats_max_concurrent_runs` (`_resolve_max_concurrent_runs`): int >= 1, default 1, which keeps one + run at a time per agent. Per agent across all of its subscriptions, not per subscription. + +Tests: `_until_settled` in `test_nats_client.py` awaits the started run, because the callback +returns before the delivery is settled; the 26 tests that assert a settlement use it. Docs: +`reference/configuration-keys.md` (the key, `nats_max_ack_pending` sized against it, the example), +`concepts/event-processing.md`, `guides/deployment.md`; `CHANGELOG.md` Fixed and Added. + +Measured against `nats:2.10-alpine` with a group built by `AgentGroup.assemble`, 2 s handlers: +5 events of one subject 10.1 s -> 4.0 s at 4 runs; 6 events of two tenants' subjects on one +subscription 12.1 s -> 4.0 s; one 7 s run under `nats_ack_wait = 3` ran three times before (redelivered +while running, then queued behind itself) and once after. + +Not changed: spec sec. 5.2 still lists 300 s / 16 as the defaults of `nats_ack_wait` / +`nats_max_ack_pending`, which `604bebb` made server defaults; and handler-time-bounds sec. 4.5 +assumes running handlers are bounded by `nats_max_ack_pending`, while they were bounded by one per +subscription and now by `nats_max_concurrent_runs`. Both are for the spec owner. + --- ## Open points diff --git a/src/blueprint/agent_generator/docs/concepts/event-processing.md b/src/blueprint/agent_generator/docs/concepts/event-processing.md index 8b51675a..88deba2e 100644 --- a/src/blueprint/agent_generator/docs/concepts/event-processing.md +++ b/src/blueprint/agent_generator/docs/concepts/event-processing.md @@ -294,9 +294,21 @@ unset, each is the server's default: client's: when it expires the message is redelivered to another replica while the first one is still working, so a model call that occasionally takes four minutes needs an `ack_wait` above four minutes, not the NATS default of thirty seconds. -- **`nats_max_ack_pending` should stay close to the replica count.** A push subscription processes - its callbacks one at a time, so anything larger parks messages in the client's queue -- where - their `ack_wait` is already counting down, unhandled. +- **`nats_max_ack_pending` should stay close to replicas x `nats_max_concurrent_runs`.** A pod + starts at most `nats_max_concurrent_runs` runs; anything the broker pushes beyond that waits in + the client's queue -- where its `ack_wait` is already counting down, unhandled and without a + heartbeat. + +**How many deliveries run at once.** Each delivery runs as its own task, up to +`nats_max_concurrent_runs` per agent and process (default `1`: one at a time). The subscription +waits for a free slot before it takes the next message, so a full agent stops taking work rather +than starting more. Order within a subject is not kept beyond one run at a time. + +**Long runs are kept alive.** While a JetStream run is in progress, its delivery is reported +`in_progress` every third of the consumer's `ack_wait` -- the value the broker has, not +`nats_ack_wait`, since an existing consumer keeps its own. A run longer than `ack_wait` is +therefore not redelivered while it still runs. A message still waiting for a slot gets no +heartbeat. An existing consumer is never rewritten. Its filter subject and deliver group are broker-side state that the stream's redelivery bookkeeping hangs off, so changing them is a migration: the diff --git a/src/blueprint/agent_generator/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md index aeece582..63a08942 100644 --- a/src/blueprint/agent_generator/docs/guides/deployment.md +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -348,6 +348,10 @@ Unset, each is the server's default: the framework sets no consumer setting on i at once. - **`nats_max_deliver`** bounds retries. Unset it is unlimited, so a message that keeps failing is retried forever and never dead-lettered. +- **`nats_max_concurrent_runs`** (default 1) is how many deliveries one pod runs at once per agent. + An agent that waits on models most of the time can run many at once on one event loop; set + `nats_max_ack_pending` to about replicas x this value, so pods do not hoard messages they cannot + start yet. ### 3. Deduplication, if your handlers need it @@ -420,8 +424,10 @@ spec: CPU is a poor signal for an event-driven agent that spends its time waiting on an LLM. Consumer lag or in-flight count is the metric you actually want to scale on, and reaching it needs a metrics -adapter. Check `nats_max_ack_pending` before adding replicas: it limits the in-flight messages of all -pods together, so more pods under the same limit do not process more at once. +adapter. Check `nats_max_ack_pending` and `nats_max_concurrent_runs` before adding replicas: the +first limits the in-flight messages of all pods together, so more pods under the same limit do not +process more at once; the second is often the cheaper lever, since a pod waiting on models has +event-loop time to spare. --- diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 23541664..ef882925 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -44,7 +44,8 @@ Settings for the event bus transport layer. | `nats_stream_name` | `str` | `"EVENTS"` | Stream the durable consumers are created on. The framework creates it if it is missing, and widens an existing one to cover every subscribed subject plus the dead-letter subject; it never removes a subject. | | `nats_durable_name` | `str` | `"-durable"` | Name of the durable consumer. Derived from the topic by default, with `.`, `*`, `>` and whitespace replaced by `_` because NATS rejects them in a consumer name. A client that belongs to a namespace prefixes it (`"--durable"`), so two agents subscribing to the same topic get a consumer each. Setting it explicitly is only valid with a single subscribed topic: a durable filters one subject, and under a namespace it must be scoped per namespace or every namespace binds to the same consumer. | | `nats_ack_wait` | `float` | unset -- the server's default (NATS: 30 s) | Seconds the broker waits for an acknowledgement before redelivering. **Must exceed the p99 duration of your slowest handler**, or long inference is redelivered to another replica while the first is still working. Handlers that call models usually need more than the NATS default, so set it. | -| `nats_max_ack_pending` | `int` | unset -- the server's default (NATS: 1000) | Unacknowledged messages the consumer may have outstanding at once, counted across every replica sharing it. `-1` is unlimited. Keep it close to the number of replicas: a push subscription runs its callbacks one at a time, so anything much larger queues messages inside the client while their `nats_ack_wait` is already running down. | +| `nats_max_ack_pending` | `int` | unset -- the server's default (NATS: 1000) | Unacknowledged messages the consumer may have outstanding at once, counted across every replica sharing it. `-1` is unlimited. Keep it close to replicas x `nats_max_concurrent_runs`: whatever a pod receives beyond the runs it has started waits in the client's queue, unheartbeated, while its `nats_ack_wait` is already running down. | +| `nats_max_concurrent_runs` | `int` | `1` | Deliveries this agent handles at once, per process, across all of its subscriptions. `1` is one at a time, as before the key existed. An agent that spends its runs waiting on a model or an API gains the most from raising it; every run shares the process's one event loop, so CPU-heavy handlers gain little. Applies to Core NATS and JetStream alike. | | `nats_max_deliver` | `int` | unset -- the server's default (NATS: unlimited) | Delivery attempts before the message is dead-lettered. Unlimited -- the default, or `-1` -- means a permanently failing message is retried forever and never dead-lettered; the client logs a warning at startup if you set `-1` explicitly. Set a positive limit to bound retries. | | `nats_dead_letter_subject` | `str` | `".dead-letter"` | Subject a message is republished to when the framework gives up on it -- either a terminal failure (`InvalidEventError`, `CriticalHandlerError`, or a payload that is not a CloudEvent) or `nats_max_deliver` attempts spent. The original bytes are republished unchanged, with `Blueprint-Dead-Letter-Reason`, `Blueprint-Original-Subject`, `Blueprint-Delivery-Count` and `Blueprint-Event-Id` headers. Set to `""` to disable, which drops those messages and loses their payloads. Startup fails if the subject is a wildcard or is itself one of the subscribed subjects, since that would loop. | @@ -251,6 +252,7 @@ nats_stream_name = "EVENTS" nats_ack_wait = 300.0 # must exceed the p99 handler duration nats_max_ack_pending = 16 # outstanding messages across all replicas nats_max_deliver = 5 # attempts before the message is dead-lettered +nats_max_concurrent_runs = 8 # deliveries one process handles at once (default 1) # nats_dead_letter_subject = "my_agent_service.dead-letter" # defaults to .dead-letter # Event deduplication (off by default; both keys are needed to turn it on) diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 075044da..66d44534 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -50,6 +50,14 @@ class JetStreamUnavailableError(RuntimeError): """ +SERVER_DEFAULT_ACK_WAIT = 30.0 +"""Seconds: the ``ack_wait`` NATS gives a consumer created without one. + +Only a fallback for a bound consumer whose config reports no ``ack_wait``; the heartbeat interval +is otherwise derived from the consumer's own value (handler-time-bounds spec sec. 4.2). +""" + + FatalHandler = Callable[[str, BaseException], Awaitable[None]] """Called once when a client finds, after startup, that its agent cannot run at all: namespace, error.""" @@ -177,6 +185,24 @@ class NATSClient(IOClientBase): message is dead-lettered; unlimited disables dead-lettering on exhaustion. ``nats_dead_letter_subject`` (str, default ``".dead-letter"``): where a message goes when the framework gives up on it; ``""`` disables it and loses the payload. + ``nats_max_concurrent_runs`` (int, default 1): deliveries this agent handles at once, across + all of its subscriptions. ``1`` is the behaviour before the key existed: one run at a time. + + Concurrent runs + ~~~~~~~~~~~~~~~ + nats-py gives each subscription one task, and that task awaits its callback before it takes + the next message. A callback that ran the handler itself therefore handled one delivery per + subscription at a time, however much of the handler was spent waiting on I/O. The callback now + only waits for a free run slot and starts the run as a task of its own, so up to + ``nats_max_concurrent_runs`` runs of this agent are in progress at once. Waiting for the slot + *inside* the callback is the back-pressure: with every slot taken, the subscription's task + stops taking messages and they wait in the client's buffer (bounded by ``max_ack_pending``) + rather than starting. Order within a subscription is not kept beyond one run at a time. + + While a JetStream run is in progress its delivery is reported ``in_progress`` every third of + the bound consumer's ``ack_wait``, so a run longer than ``ack_wait`` is not redelivered while it + still runs (handler-time-bounds spec sec. 4.1). Messages still waiting in the buffer get no + heartbeat; their ``ack_wait`` keeps running. """ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: @@ -204,6 +230,10 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: self._inflight: int = 0 self._idle: asyncio.Event = asyncio.Event() self._idle.set() + self._max_concurrent_runs: int = 1 + self._run_slots: asyncio.Semaphore = asyncio.Semaphore(1) + self._runs: set[asyncio.Task[None]] = set() + self._ack_waits: dict[str, float] = {} # ------------------------------------------------------------------ # Public state @@ -267,6 +297,8 @@ async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: """ self._topic_callbacks = topic_callbacks self._queue_group = self._resolve_queue_group() + self._max_concurrent_runs = self._resolve_max_concurrent_runs() + self._run_slots = asyncio.Semaphore(self._max_concurrent_runs) if self.config.get("nats_use_jetstream", False): self._durables = self._resolve_durables(list(topic_callbacks)) self._tuning = self._resolve_consumer_tuning(list(topic_callbacks)) @@ -589,6 +621,15 @@ def _read_optional_float(self, key: str) -> float | None: return None return self._read_float(key, 0.0) + def _resolve_max_concurrent_runs(self) -> int: + """Return ``nats_max_concurrent_runs``: at least 1, and 1 when it is not configured.""" + value = self._read_optional_int("nats_max_concurrent_runs") + if value is None: + return 1 + if value < 1: + raise ValueError(f"'nats_max_concurrent_runs' must be at least 1, got {value}. It is how many deliveries run at once.") + return value + def _read_optional_int(self, key: str) -> int | None: """Read ``key`` as an integer, or ``None`` when it is not configured.""" if self.config.get(key, None) is None: @@ -1331,31 +1372,14 @@ async def _subscribe_one(self, topic: str, callback: DeliveryCallback) -> None: client = await self.client async def message_handler(msg: Any) -> None: + # Runs on the subscription's one nats-py task. It waits for a run slot -- the + # back-pressure -- and returns as soon as the run is started, so the task can take the + # next message while this one is still running. + await self._run_slots.acquire() self._enter_handler() - try: - cloud_event = self._decode_message(msg, topic) - if cloud_event is None: - # A payload that will not parse now will not parse on redelivery either. - await self._settle(msg, DeliveryDisposition.TERM, topic, None) - return - - try: - await callback(cloud_event, msg.subject) - except Exception as ex: - disposition = disposition_for(ex) - logger.error( - "Handler failed for event %s on topic '%s', will %s: %s", - cloud_event.id, - topic, - disposition.value, - ex, - exc_info=True, - ) - await self._settle(msg, disposition, topic, cloud_event.id) - else: - await self._settle(msg, DeliveryDisposition.ACK, topic, cloud_event.id) - finally: - self._exit_handler() + run = asyncio.create_task(self._run_delivery(msg, topic, callback), name=f"nats-run-{self.namespace or ROOT_LABEL}") + self._runs.add(run) + run.add_done_callback(self._run_finished) try: if self._use_jetstream and client.jetstream(): @@ -1368,6 +1392,8 @@ async def message_handler(msg: Any) -> None: # is per agent. Binding to a consumer we create ourselves also puts ack_wait, # max_ack_pending and max_deliver where the broker can enforce them. consumer_config = await self._ensure_consumer(topic, durable_name) + # The broker's value, not nats_ack_wait: an existing consumer keeps its own. + self._ack_waits[topic] = consumer_config.ack_wait or SERVER_DEFAULT_ACK_WAIT sub = await client.jetstream().subscribe_bind( stream=stream_name, config=consumer_config, @@ -1397,6 +1423,91 @@ async def message_handler(msg: Any) -> None: logger.error("Failed to subscribe to topic '%s': %s", topic, str(e)) raise + # ------------------------------------------------------------------ + # Internal -- one run + # ------------------------------------------------------------------ + + async def _run_delivery(self, msg: Any, topic: str, callback: DeliveryCallback) -> None: + """Decode, dispatch and settle one delivery; runs as its own task, beside its heartbeat. + + The heartbeat is stopped before the delivery is settled, whatever ended the run. A + cancelled run (shutdown past its deadline) is not settled: the broker redelivers it. + """ + cloud_event = self._decode_message(msg, topic) + if cloud_event is None: + # A payload that will not parse now will not parse on redelivery either. + await self._settle(msg, DeliveryDisposition.TERM, topic, None) + return + + heartbeat = self._start_heartbeat(msg, topic) + disposition = DeliveryDisposition.ACK + try: + await callback(cloud_event, msg.subject) + except Exception as ex: + disposition = disposition_for(ex) + logger.error( + "Handler failed for event %s on topic '%s', will %s: %s", + cloud_event.id, + topic, + disposition.value, + ex, + exc_info=True, + ) + finally: + if heartbeat is not None: + heartbeat.cancel() + # A heartbeat never fails the run (handler-time-bounds spec sec. 4.1). + with contextlib.suppress(asyncio.CancelledError, Exception): + await heartbeat + await self._settle(msg, disposition, topic, cloud_event.id) + + def _run_finished(self, run: asyncio.Task[None]) -> None: + """Free the run's slot and count it out of the in-flight handlers shutdown waits for.""" + self._runs.discard(run) + self._run_slots.release() + self._exit_handler() + if not run.cancelled() and run.exception() is not None: + # _run_delivery settles every handler failure itself; this is a fault in the run's own code. + logger.error( + "A NATS delivery run of agent '%s' failed outside its handler: %s", + self.namespace or ROOT_LABEL, + run.exception(), + exc_info=run.exception(), + ) + + def _start_heartbeat(self, msg: Any, topic: str) -> asyncio.Task[None] | None: + """Start reporting ``in_progress`` for a JetStream delivery; ``None`` on Core NATS.""" + ack_wait = self._ack_waits.get(topic) + if not self._use_jetstream or ack_wait is None: + return None + heartbeat = asyncio.create_task(self._keep_alive(msg, ack_wait / 3), name=f"nats-heartbeat-{self.namespace or ROOT_LABEL}") + heartbeat.add_done_callback(self._heartbeat_finished) + return heartbeat + + def _heartbeat_finished(self, heartbeat: asyncio.Task[None]) -> None: + """Log a heartbeat that died of anything but its cancellation; the run goes on without it.""" + if not heartbeat.cancelled() and heartbeat.exception() is not None: + logger.error( + "The heartbeat of a NATS delivery of agent '%s' failed; the delivery may be redelivered while it runs: %s", + self.namespace or ROOT_LABEL, + heartbeat.exception(), + exc_info=heartbeat.exception(), + ) + + @staticmethod + async def _keep_alive(msg: Any, interval: float) -> None: + """Report ``in_progress`` every ``interval`` seconds until cancelled; the first after one interval. + + A failed report (connection lost) is logged and retried at the next interval. It never + fails the run: the settlement would fail the same way, and that already ends in a redelivery. + """ + while True: + await asyncio.sleep(interval) + try: + await msg.in_progress() + except Exception as exc: + logger.debug("Heartbeat for the message on %s failed: %s", msg.subject, exc) + # ------------------------------------------------------------------ # Internal — acknowledgement # ------------------------------------------------------------------ diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index 8db6aff3..10f46946 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -24,6 +24,20 @@ from blueprint.agents.models.events import CloudEvent +def _until_settled(nats_client: NATSClient, handler): + """The broker callback, awaited until the run it started has settled. + + The callback only starts the run as a task of its own (concurrent runs); these tests assert + on what the run did, so they wait for it. + """ + + async def deliver(msg) -> None: + await handler(msg) + await asyncio.gather(*list(nats_client._runs), return_exceptions=True) + + return deliver + + class TestNATSClientInit: def test_nats_client_initialises_as_none(self, nats_client: NATSClient) -> None: assert nats_client._nats_client is None @@ -358,7 +372,7 @@ async def _handler_for(nats_client: NATSClient, mock_nats_core: MagicMock, callb nats_client._nats_client = mock_nats_core nats_client._client = mock_nats_core await nats_client._subscribe_one("orders.created", callback) - return mock_nats_core.subscribe.await_args.kwargs["cb"] + return _until_settled(nats_client, mock_nats_core.subscribe.await_args.kwargs["cb"]) async def test_undecodable_payload_is_not_dispatched( self, nats_client: NATSClient, mock_nats_core: MagicMock, caplog: pytest.LogCaptureFixture @@ -387,7 +401,7 @@ async def _callback(event: CloudEvent, subject: str) -> None: nats_client._nats_client = mock_nats_core nats_client._client = mock_nats_core await nats_client._subscribe_one("t.*.risk.>", _callback) - handler = mock_nats_core.subscribe.await_args.kwargs["cb"] + handler = _until_settled(nats_client, mock_nats_core.subscribe.await_args.kwargs["cb"]) await handler(MagicMock(subject="t.T1.risk.created", data=json.dumps(dict(cloud_event)).encode())) assert received == ["t.T1.risk.created"] @@ -457,7 +471,7 @@ async def _js_handler(nats_client: NATSClient, mock_nats_jetstream: tuple, callb nats_client._client = mock_nc nats_client._use_jetstream = True await nats_client._subscribe_one("orders.created", callback) - return mock_nc.jetstream().subscribe_bind.await_args.kwargs["cb"] + return _until_settled(nats_client, mock_nc.jetstream().subscribe_bind.await_args.kwargs["cb"]) @staticmethod def _msg(cloud_event: CloudEvent) -> MagicMock: @@ -538,7 +552,7 @@ async def test_core_nats_settles_nothing(self, nats_client: NATSClient, mock_nat nats_client._nats_client = mock_nats_core nats_client._client = mock_nats_core await nats_client._subscribe_one("orders.created", AsyncMock()) - handler = mock_nats_core.subscribe.await_args.kwargs["cb"] + handler = _until_settled(nats_client, mock_nats_core.subscribe.await_args.kwargs["cb"]) msg = self._msg(cloud_event) await handler(msg) msg.ack.assert_not_awaited() @@ -628,7 +642,7 @@ async def _callback(event: CloudEvent, subject: str) -> None: nats_client._nats_client = mock_nats_core nats_client._client = mock_nats_core await nats_client._subscribe_one("orders.created", _callback) - message_handler = mock_nats_core.subscribe.await_args.kwargs["cb"] + message_handler = _until_settled(nats_client, mock_nats_core.subscribe.await_args.kwargs["cb"]) msg = MagicMock(data=json.dumps(dict(cloud_event)).encode()) await message_handler(msg) @@ -645,7 +659,7 @@ async def _callback(event: CloudEvent, subject: str) -> None: nats_client._nats_client = mock_nats_core nats_client._client = mock_nats_core await nats_client._subscribe_one("orders.created", _callback) - message_handler = mock_nats_core.subscribe.await_args.kwargs["cb"] + message_handler = _until_settled(nats_client, mock_nats_core.subscribe.await_args.kwargs["cb"]) await message_handler(MagicMock(data=json.dumps(dict(cloud_event)).encode())) @@ -1302,7 +1316,7 @@ async def _handler(nats_client: NATSClient, mock_config: MagicMock, mock_nats_je await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"], **overrides) await nats_client._subscribe_one("orders.created", callback) mock_nc, _ = mock_nats_jetstream - return mock_nc.jetstream().subscribe_bind.await_args.kwargs["cb"] + return _until_settled(nats_client, mock_nc.jetstream().subscribe_bind.await_args.kwargs["cb"]) async def test_terminal_failure_is_dead_lettered_then_termed( self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent From 5dd995948790486613fdf22f437aeec7cf4a232b Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 14 Oct 2026 12:48:24 +0200 Subject: [PATCH 071/133] docs(plans): named NATS connections with concurrent runs Plan for letting an agent consume from several named connections that the deployment supplies through a connection source (own account and JetStream binding each), with concurrent runs per connection and no state shared between (agent, connection) pairs. The framework stays free of tenancy: it sees names, credentials, bindings and hooks. Decisions D1-D10 taken with the owner; six reviewable steps; acceptance runs in WSL against a broker with real accounts. Co-Authored-By: Claude Opus 5 (1M context) --- docs/plans/2026-10-14-named-connections.md | 335 +++++++++++++++++++++ 1 file changed, 335 insertions(+) create mode 100644 docs/plans/2026-10-14-named-connections.md diff --git a/docs/plans/2026-10-14-named-connections.md b/docs/plans/2026-10-14-named-connections.md new file mode 100644 index 00000000..77621ec2 --- /dev/null +++ b/docs/plans/2026-10-14-named-connections.md @@ -0,0 +1,335 @@ +# Plan -- Named NATS connections with concurrent runs + +**Status:** 2026-10-14, decisions D1-D10 taken with the owner (sec. 4); ready for step 1. Supersedes +`docs/plans/2026-10-09-tenancy.md` (discarded: the framework does not take on tenancy). + +**Goal in one sentence:** an agent consumes from several *named connections* that the deployment +supplies at runtime -- each with its own broker account and its own JetStream binding -- with +concurrent runs per connection, and nothing of one connection's runs ever reaches another's. + +**What the framework does not know:** what a connection stands for. A deployment may map one +connection to one tenant, one region or one customer; the framework sees a name, credentials, a +binding and a validation hook. No tenant document, registry, tenant scope, tenant id or +tenant-specific key enters the framework. + +**First consumer:** a multi-tenant agent application, which today does all of this beside the +framework, in a connection pool and an ingress of its own. No deployment uses the framework's NATS path +yet, so nothing has to be migrated. + +--- + +## 1. Why + +- **The framework has one connection per agent.** One credential, one stream (`nats_stream_name`, + process scope, provisioned and widened by the client), durables, deliver subjects and deliver + groups derived by the client. A deployment whose streams and accounts are owned by someone else + -- one account and one stream per tenant, created by provisioning, consumers possibly created by + an operator -- cannot be served. The broker refuses the framework's stream over subjects that + already belong to another stream (`err_code=10065`). +- **So the first consumer built its own transport**, and with it lost every delivery guarantee the + framework has (dispositions, dead letter, drain budget, telemetry) and had to re-implement the + rest (settlement, heartbeat, run limit, degraded pause). +- **Concurrency.** Measured 2026-10-14: runs were strictly one at a time per subscription and + process in both implementations. `19c4c48` fixed the framework's path + (`nats_max_concurrent_runs`, heartbeat); this plan carries it over to every connection. + +--- + +## 2. Invariants + +- **N1 -- Isolation between (agent, connection).** A run started from a delivery on connection C for + agent A shares no mutable state with any run of another (agent, connection): + - each run starts in an **empty `contextvars.Context`** -- nothing is inherited from the + dispatcher, the subscription task or another run; + - each (agent, connection) has its own broker connection, subscription, run slots and in-flight + accounting; the only thing shared is the per-process run cap, a counter; + - a delivery is settled (ack / nak / term / in_progress) on the connection that delivered it; + - the handler learns its connection from the context key `nats_connection`, set by the framework + from the connection the message arrived on -- never from the payload. +- **N2 -- Validation before dispatch.** A deployment-supplied hook sees (connection name, subject, + CloudEvent) before any handler runs. A rejection is terminated (`term`), logged, never processed, + never retried. +- **N3 -- Bind, never provision, on a named connection.** The stream belongs to the binding. The + client never creates or widens it. Consumers are created or updated only when the binding says + so; otherwise the client binds to what exists and sends no `$JS.API` request at all. +- **N4 -- Wire values come from the deployment, byte for byte.** Durable name, deliver subject, + deliver group and filter subjects of a named connection are taken from its binding, not derived. + Moving that application onto the framework is then a redeploy: every `consumer_info` + identical before and after. +- **N5 -- Composition independence.** Behaviour does not depend on how many agents or connections a + process hosts. One slow connection does not slow another beyond the shared per-process cap. +- **N6 -- Existing agents unchanged.** Without a connection source, an agent runs exactly as today + on its one configured connection. +- **N7 -- The same delivery semantics everywhere.** Named connections use the existing delivery + path: run slots, `_run_delivery`, dispositions (spec sec. 7.2), heartbeat, drain, telemetry. There + is one implementation of settling a message. + +--- + +## 3. Shape + +``` +ConnectionSource (deployment code, process-wide) + connections() -> {name: ConnectionSpec}; notifies on add / change / remove + binding(agent, subjects, spec) -> JetStreamBinding + validate(name, subject, event) -> None | reason + | + v +NATSClient (one per agent, as today) + default connection -- from nats_url etc., as today (N6) + named connection "c1" -- own nats.Client, own subscription(s), own slots + named connection "c2" -- ... + | + v per delivery: validate -> run task in empty Context -> handler chain -> settle on "cX" +``` + +- **One `NATSClient` per agent stays.** The registry name, `NatsEventing`'s lookup, publishing and + the supervisor's pause/resume all assume it (`component.py:153`, `nats.py:69`, + `event_publishing_service.py:65`, `namespace_supervisor.py:222`). The client grows an internal + set of connections instead of the registry growing several clients. +- **`ConnectionSpec`:** name, URL, credentials (secrets as `SecretStr`, never logged), connect + options. **`JetStreamBinding`:** the declared subjects it serves on this connection (D10), its + `subject_prefix` (filter subject = prefix + declared subject), stream, durable, deliver subject, + deliver group, `manage_consumer`, optional dead-letter subject (D6). +- **Subjects:** an agent declares its subjects as today (`get_subscribed_topics()`, + `nats_subscriptions`), without any prefix. The source maps them to a connection's filter subjects + in `binding()` -- that is where a deployment adds a prefix such as `t..`. The framework never + rewrites a subject. Example: agent `risk` declares `risk.>`; for connection `A` the source returns + filter `t.A.risk.>`, durable `acme-agent-risk`, deliver subject + `acme.agent.A.risk`, deliver group `risk`. +- **Context keys of a delivery on a named connection** (D10): `nats_topic` = the subscription *as + the agent declared it* (`risk.>`), so everything that matches on the declared topic keeps working + -- e.g. `SchedulerTickHandler` compares `nats_topic` with its own topic (`scheduler.py:195`); + `nats_subject` = the delivered subject with the binding's prefix stripped (`risk.created`), so + `can_handle_event` sees what the agent knows; `nats_connection` = `A`, an opaque name for logs. + The wire subject (`t.A.risk.created`) is not in the handler context. +- **Without a source nothing changes (N6):** no `nats_connection_source`, no named connections; the + agent's subjects are subscribed on its one connection exactly as today, durables and stream + derived as today. +- **Runtime changes:** a connection added, changed (credentials, binding) or removed is opened, + replaced or drained while the agent runs. Draining follows `close()`: stop deliveries, let runs + finish within the budget, settle, close. A consumer the framework did not create is never deleted. + +--- + +## 4. Decisions + +All taken on 2026-10-14; each entry starts with the decision, followed by the analysis that led to it. + +- **D1 -- Connection granularity. Decided 2026-10-14: (a), one broker connection per (agent, + connection).** Step 1 separates a *link* (the `nats.Client`, connecting, callbacks) from a + *binding* (subscription, run slots, settlement), one link per binding for now, so a shared link + -- option (b) -- can be added later as its own step without reshaping the rest. Triggers for + building (b): pod memory gets tight, or the operator sets `max_connections` per account. What (b) + would add: a process-wide link pool with reference counting and shutdown ordering, fanning + connection events out to every agent on the link, readiness that tells "link down" from "agent + paused", an exception to C2's connection naming and to grouping spec sec. 6, and every acceptance + test in both modes. The analysis that led here: + One broker connection per (agent, connection) **(recommended)**: + confines a dropped connection (stranded acks) and a slow-consumer kick to one agent and one + connection, as the grouping spec does per agent (sec. 6). Cost: agents x connections connections + per pod (19 x 10 = 190). Alternative: one per named connection shared by the agents of a process + (what the first consumer's own pool does today) -- fewer connections, but one agent's flood or blip hits all. + *Measured 2026-10-14* (nats-py 2.15 in `python:3.13-slim-bookworm` containers, NATS 2.10 with TLS + (RSA 2048) and user/password, all in WSL): an idle connection costs ~313 KB in the client with TLS + (~89 KB without) and ~80 KB in the broker; no measurable idle CPU; 400 connections open in 2.1 s. + Broker restart under 3 pods x 400: all 1200 back within 0.7 s; 3 x 800: all 2400 within 1.6 s, broker + CPU ~3 cores for about a second, ~2 s client CPU per pod, none given up even with the framework's + `nats_max_reconnect_attempts = 5`. The cost of this option is memory: 300 connections ~ 95 MB per + pod. Not covered: real network latency, a clustered broker, per-account `max_connections` set by + the operator (agents x replicas per account under this option). +- **D2 -- Registering the source. Decided 2026-10-14: (a), the process-scope config key.** The + builders are each agent's own declaration, and an agent must not know about the deployment's + connections; a builder call would put the source into agent code. The key goes into + `PROCESS_SCOPE_KEYS`; `asbs validate` checks that it imports. The analysis that led here: + A process-scope key naming a factory, + `nats_connection_source = "package.module:factory"` **(recommended)**: works in a group without + any agent code, like the group file. Alternative: a builder call -- needs a process-scope + registration a group does not have today. +- **D3 -- Run scope hook. Decided 2026-10-14: (a), the source may supply `run_scope(name)`.** + Agents open no deployment scope themselves and cannot forget it. The analysis that led here: + The source may supply `run_scope(name)`, a context manager the framework + enters *inside* the run task, around the handler chain **(recommended)**. It is how a deployment + applies per-connection settings that live in ContextVars (today: per-tenant model override) without + agent code. Without it, every agent service has to open such scopes itself. +- **D4 -- `HandlerResult` publishing for a run from a named connection. Decided 2026-10-14: (a), + refused for now.** A result without a topic mapping is skipped as today; an agent that has named + connections *and* a topic mapping fails startup, so no connection's result can reach the default + connection's subjects. Found: the first consumer's handlers return `HandlerResult`s but the + repository has no topic mapping, so nothing is published today. **Later, when needed -- option + (b):** publish on the delivering connection, the source mapping the target subject as it maps + bindings (e.g. `t.A.`); needs publish rights on the connection's account. The analysis + that led here: Today it goes out on the + agent's default connection. Options: keep that **(recommended for this step; documented as "leaves + the connection")**, publish on the delivering connection (needs publish rights on that account), + or refuse. Isolation-relevant: the event leaves the connection's account. +- **D5 -- Readiness. Decided 2026-10-14:** new key `nats_connections_readiness = "never" | "any" | + "all"`, default `never`. `never`: named connections show in the readiness payload and metrics but + never make the agent not ready (= today's behaviour of the only user: tenant connections are + invisible to readiness); `any` (OR): ready while at least one named connection is up; `all` (AND): + ready only while every one is up. The **default connection keeps today's behaviour unchanged** + (`health_check`, `nats_client.py:1106`: not connected -> unhealthy). **Required regardless of the + mode:** a named connection's state feeds readiness only, never the supervisor's pause decision -- + one agent health bit drives both today (`namespace_supervisor.py:131`), and a pause on one dead + connection would stop the agent on every connection. Acceptance in WSL: one account with a wrong + password, nothing paused, readiness as the mode says. The analysis that led here: + A named connection that is down degrades that (agent, connection) only and + shows in the readiness payload; the agent stays ready **(recommended)**, so one broken account + does not take every other connection's work off the pod. **Open:** whether an agent with named + connections but none of them up should report not ready. +- **D6 -- Dead letters on a named connection. Decided 2026-10-14: (a).** Dead-lettered on the + delivering connection only when the binding carries a dead-letter subject; otherwise term + ERROR + log (event id, reason, delivery count) -- what the first consumer does today. Never via the + default connection: a connection's payload must not reach another account. The analysis that led + here: Use the binding's dead-letter subject if it has one; + none -> term + ERROR log, payload lost **(recommended)** -- a deployment's account may not be + allowed to publish. +- **D7 -- Run limits. Decided 2026-10-14.** Event rates differ by orders of magnitude between agents + (once an hour to several times a minute), so a busy (agent, connection) may take many runs while + an idle one never waits: + - **One run per (agent, connection) is always allowed** and counts against no limit. + - **Every further run** needs both: the (agent, connection) is below `nats_max_concurrent_runs` + (K, the same for every connection of the agent, settable per agent), **and** a slot of the + process-wide pool `nats_extra_runs_per_process` is free. + - Both keys take an absolute number or a percentage of the current number of (agent, connection) + pairs in the process (`"33%"`), recomputed when connections are added or removed. The owner's + sizing: K up to about a third of the pairs. + - Defaults keep today's behaviour: K = 1 (so no further runs at all), pool unset (unlimited). + - Order of acquisition is fixed (the pair's slot, then the pool), so there is no deadlock; waiters + are served first come, first served, so no pair starves. + - Consequence to measure: guaranteed first runs are uncapped, so in the worst case every pair + runs at once plus the whole pool. The step-3 stress scenario includes "every pair busy at once". + - Per-connection K from the binding (a large tenant gets more) is not built; it can be added later + without reshaping anything. + The analysis that led here: `nats_max_concurrent_runs` becomes per (agent, connection) -- it was per agent + in `19c4c48`, which is unpushed and unused -- plus a new process-scope cap + `nats_max_concurrent_runs_per_process` across every agent and connection. Defaults: 1 and unset + (no cap) to keep N6; the deployment sets both. +- **D8 -- Core NATS on named connections. Decided 2026-10-14: (a), JetStream only.** A binding + without stream and consumer fails that connection's start with a clear message. Core NATS on the + default connection is unchanged. **Later, when needed -- option (b):** Core NATS on a named + connection, subscribing the filter subjects in the queue group with no acknowledgement, heartbeat, + redelivery or dead letter; events published during a pause or restart are lost; every acceptance + test then runs in both modes. The analysis that led here: JetStream only **(recommended)**: a named connection + exists to bind an existing durable consumer. +- **D9 -- Handler timeout. Decided 2026-10-14: in this plan.** `nats_handler_timeout` (seconds, + agent-scoped, every connection including the default one), **default unset = no limit**. At the + limit the run is cancelled and nak'd for immediate redelivery; a `TimeoutError` the handler raises + itself is an ordinary failure (the run's own timer is checked, not the exception type). The run's + slot is freed only when its task has actually ended -- a handler that swallows the cancellation + keeps holding its slot, logged, instead of running unseen beside its redelivery. The heartbeat + (`19c4c48`) already exists and stops before the nak. The analysis that led here: + Part A's hard limit (`nats_handler_timeout`, cancel + nak) is in + the first consumer today and in the handler-time-bounds draft spec. Include it in this plan + **(recommended)** -- "everything works as it does now" requires it. + +- **D10 -- Which subjects go where. Decided 2026-10-14: (a), the source decides per connection.** + Agents know their events (`risk.>`), never how connections are built (prefixes, accounts, + streams): `can_handle_event` must be able to look at the event's subject *as the agent declared + it* and decide whether there is work. Hence the binding expresses its mapping as a plain + `subject_prefix` (a generic concept, not a tenant one): filter subject = prefix + declared subject, + and the framework strips the prefix again on delivery, so `nats_subject` is always the subject the + agent knows (`risk.created`) -- on the default connection exactly as today. The wire subject + (`t.A.risk.created`) reaches the validation hook and the framework's logs, not the handler + context. The analysis that led here: An agent may declare subjects that + belong to the named connections (tenant events) and subjects that do not (a scheduler tick, a + process-level event). Recommended: `binding()` returns, per connection, which of the declared + subjects it serves; a subject no connection serves stays on the default connection, as today. + The default connection then subscribes only what is left -- possibly nothing, which matters where + the process account may not subscribe at all (the first consumer). + +--- + +## 5. Steps + +One step, one reviewable commit. Each step names its acceptance. + +1. **Refactor: connections inside `NATSClient`.** The client's connection state (nats client, + JetStream context, subscriptions, slots, in-flight, ack-wait map) moves into a `_Connection` + object; the client holds a default one. No behaviour change, with one addition decided + 2026-10-14: `nats_heartbeat_enabled` (bool, agent-scoped, default `true`) switches the heartbeat + of `19c4c48` off per agent, as in handler-time-bounds sec. 4.1. + *Acceptance:* unit and integration suites unchanged; the 2026-10-14 probe (B1-B5, K1-K3) gives + the same results. +2. **Binding mode.** A `_Connection` can bind with a `JetStreamBinding`: no stream provisioning, + consumer created only with `manage_consumer`, wire values verbatim (N3, N4). + *Acceptance:* broker test -- an operator-made consumer is bound with `consumer_info` identical + before and after; with `manage_consumer` the consumer equals what the first consumer's pool + creates for the same input. +3. **Connection source, static.** `nats_connection_source` (D2), connections opened at startup, + validation hook (N2), empty Context per run, `nats_connection` context key, run scope hook (D3), + per-connection slots and per-process cap (D7), handler timeout (D9). + *Acceptance:* isolation test below; mismatch -> term; limits respected (measured overlap). +4. **Connection source, dynamic.** Add, change, remove at runtime; drain on remove; never delete a + foreign consumer. +5. **Readiness and telemetry per connection** (D5): connection state in the readiness payload, + metrics labelled with the connection name. +6. **Everything that describes the framework agrees with it -- no contradiction left anywhere.** + Not only the new feature: every statement about NATS delivery, consumers, concurrency, heartbeat, + run limits and connections is checked against the code after steps 1-5, and corrected or + removed. Covered: + - **Specs and plans:** `docs/specs/2026-08-28-multi-agent-grouping.md` (sec. 5.2 still lists + 300 s / 16 as defaults; sec. 6 and 7 against named connections), + `docs/specs/2026-09-24-handler-time-bounds.md` (sec. 4.5 assumes running handlers are bounded by + `nats_max_ack_pending`; what part A is now implemented), `docs/specs/2026-09-23-dynamic-subscriptions.md` + (overlap with step 4), the feature changelog, `CHANGELOG.md`, `README.md`, `AGENTS.md`. + ADRs (`docs/adr/`) are owned outside this repository: contradictions there are listed for their + owner, not edited. + - **Shipped docs:** `src/blueprint/agent_generator/docs/` -- concepts, guides (deployment, event + processing, scaling), reference (configuration keys, every new key with type, default and + scope), getting started. + - **Agent generator:** the templates in `base_files/` (e.g. `settings.txt`, the handler template + whose docstring and idempotency comment still put business logic in the handler), the + generator, `asbs validate` checks for the new keys (a source that cannot be imported, a binding + without a stream, limits below 1), `asbs docs` output. + - **Skills and assistant docs:** `claude_docs/CLAUDE.md`, `claude_docs/agents/` + (`blueprint-builder.md`, `blueprint-architect.md`), every skill under `claude_docs/skills/` + (`blueprint-events`, `blueprint-config`, `blueprint-deployment`, `blueprint-multi-agent`, + `blueprint-troubleshooting`, `blueprint-testing`, ...), and the assistant integrations -- the + `main.py` patterns they show are known to disagree with each other and with the template. + - **Examples:** every project under `examples/` builds and starts against the changed framework; + `order_event_pipeline` (or a new example) shows a connection source with two named connections. + *Acceptance:* a written inventory of every place checked, with what was changed or why nothing + was; the repository's reference and design-rule guards green; every example started once in WSL + against a real broker; a grep for removed or renamed keys and APIs over the whole repository + finds nothing outside the changelogs. + +Afterwards, outside this repository: the first consumer implements the source over its tenant +documents and drops its own connection pool and the receiving half of its ingress. + +--- + +## 6. Acceptance in WSL (every step from 3 on) + +Run against a broker with **real accounts** (a `nats-server` config with one account per +connection, permissions as the operator grants them: subscribe to the deliver subject, publish acks, +nothing else), not an open broker. + +- **Isolation:** 2 connections x 3 agents, `nats_max_concurrent_runs` > 1, bursts on every + (agent, connection). Every run records the connection it sees in its context, the value of a + ContextVar set by the run scope hook, and the subject of its delivery; the test fails on any + mismatch. A ContextVar set inside one run is never visible in another. +- **Rejection:** a delivery whose payload disagrees with its connection (validation hook) is termed, + never reaches a handler, is not redelivered. +- **Stress scenario** from the discarded plan (sec. 9): 15 events per lane -- 9 short, 3 longer than + twice `ack_wait`, 2 failing, 1 hanging -- `ack_wait` 3 s, limit 10 s. Nothing stuck, no live run + redelivered, hung runs cut at the limit, failing ones dead-lettered or termed after `max_deliver`. +- **Limits:** measured maximum overlap per (agent, connection) and per process equals the configured + values; every pair always gets its first run, even with the pool exhausted. +- **Every pair busy at once:** all (agent, connection) pairs receive a burst at the same moment; + measured event-loop lag, heartbeat punctuality (no live run redelivered) and run times against an + idle baseline. +- **Later, after all three steps (framework, SDK, deployment):** a mock LLM that answers only after a + configurable number of minutes, to diagnose how a group with many tenants behaves under sustained + high load (loop lag, memory per run, limits, redeliveries) and to size K and the pool. +- **Runtime change** (step 4): a connection added and removed while the others run; no delivery of + the others lost or duplicated. +- **Control runs** against the code before the step, for every claim of the form "this fixes X". + +--- + +## 7. Not in scope + +Tenant documents, a tenant registry, tenant ids, `current_tenant()`, per-tenant model settings, +REST token verification, outbound backend credentials: all stay with the deployment. The framework +offers the seams (source, binding, validation hook, run scope hook) and nothing that names a tenant. From c2054aedecd3b9cfb58fefbd920d128dd387d07b Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 14 Oct 2026 13:35:43 +0200 Subject: [PATCH 072/133] refactor(nats): links and bindings inside NATSClient; one run per subscription when unset Step 1 of the named-connections plan. The client's per-connection state moves into _Link (the broker connection) and _Binding (subscriptions, run slots, running tasks, ack_wait per topic, in-flight count); the delivery path takes the binding a message arrived on, and a dead letter is published on that binding's own link. The former private names are transitional properties over the default link and binding. nats_heartbeat_enabled (bool, default true) switches the heartbeat off per agent; a non-boolean is refused. Fixes a regression of a20a2b7: one semaphore per agent across all of its subscriptions made an agent with two subscriptions run one delivery in total instead of one per subscription. Unset, nats_max_concurrent_runs keeps one slot per subscription again; set, the subscriptions share K. Measured: two topics x 3 events 6.0 s before a20a2b7, 12.1 s after it, 6.0 s now. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 10 +- ...26-08-28-multi-agent-grouping-changelog.md | 39 ++ docs/plans/2026-10-14-named-connections.md | 4 +- .../docs/concepts/event-processing.md | 5 +- .../agent_generator/docs/guides/deployment.md | 3 +- .../docs/reference/configuration-keys.md | 5 +- .../agents/clients/io/nats_client.py | 338 ++++++++++++++---- .../agents/clients/io/test_nats_client.py | 152 ++++++++ 8 files changed, 474 insertions(+), 82 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e111a4b..a7fc75df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,9 @@ - **NATS deliveries are no longer handled strictly one at a time.** nats-py gives each subscription one task that awaits its callback, and the callback ran the whole handler -- so an agent handled one event per subscription and process at a time, however much of the run was spent waiting on a - model. Each delivery now runs as its own task, up to the new `nats_max_concurrent_runs` per agent - (default `1`, the previous behaviour). Measured against a real broker with 2 s handlers: 5 events + model. Each delivery now runs as its own task, up to the new `nats_max_concurrent_runs` per agent, + shared by its subscriptions; unset, each subscription still runs one delivery at a time, the + previous behaviour. Measured against a real broker with 2 s handlers: 5 events took 10 s before and 4 s with the key at 4. - **A long JetStream run is no longer redelivered while it still runs.** The delivery is reported `in_progress` every third of the bound consumer's `ack_wait` until it is settled. Measured: one @@ -163,9 +164,10 @@ ### Added -- **`nats_max_concurrent_runs`** (int, default `1`): how many deliveries an agent handles at once per - process, across all of its subscriptions. With every slot taken the subscription stops taking +- **`nats_max_concurrent_runs`** (int, unset by default): how many deliveries an agent handles at once + per process, shared by all of its subscriptions; unset keeps one run per subscription. With every slot taken the subscription stops taking messages; keep `nats_max_ack_pending` near replicas x this value. +- **`nats_heartbeat_enabled`** (bool, default `true`): switches the delivery heartbeat off for an agent. - **`RestApiBase.path_prefix`**, an optional class attribute putting every route of an API under one segment -- `/api/reports/...` standalone, `/api//reports/...` in a group. Default `""`, so no existing path moves. diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 33a47039..803fd29b 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8213,6 +8213,45 @@ Not changed: spec sec. 5.2 still lists 300 s / 16 as the defaults of `nats_ack_w assumes running handlers are bounded by `nats_max_ack_pending`, while they were bounded by one per subscription and now by `nats_max_concurrent_runs`. Both are for the spec owner. +### Links and bindings inside `NATSClient`; one run per subscription restored (named connections, step 1) + +Step 1 of `docs/plans/2026-10-14-named-connections.md`: the client's per-connection state moves into +two objects, so later steps can give an agent several connections without reshaping the delivery +path. No behaviour change, with one deliberate addition and one correction. + +- `_Link` (module-private dataclass): the broker connection -- URL, connect options, connection + name, `nats.Client`, JetStream context, JetStream mismatch. `_Binding`: what one agent consumes + over one link -- topic callbacks, durables, consumer tuning, subscriptions, readiness flag, run + slots, running tasks, per-topic `ack_wait`, in-flight count and idle event, with `enter_run()` / + `exit_run()` / `slots_for(topic)`. The client holds one of each, `_link` and `_binding`. +- The delivery path takes the binding the message arrived on: `_subscribe_one(..., binding=None)` + captures it in `message_handler`; `_run_delivery`, `_start_heartbeat`, `_run_finished`, `_settle`, + `_deliveries_exhausted`, `_dead_letter`, `_drain_subscriptions` and `_await_inflight` act on it + (default: the client's own). A dead letter is published on the binding's own link. +- Transitional: the client's former private names (`_nats_client`, `_subscriptions`, `_tuning`, + ...) are properties over the default link and binding, because 237 unit-test lines reach them by + name. They go when the tests address links and bindings directly (plan step 3). +- **Addition:** `nats_heartbeat_enabled` (bool, default `true`, `_resolve_heartbeat_enabled`); + `_start_heartbeat` returns `None` when it is off. A non-boolean is refused: `"false"` as a string + would read as true. +- **Correction of the previous entry:** `19c4c48` gave an agent one semaphore across all of its + subscriptions, default 1 -- so an agent with two subscriptions, which ran one delivery per + subscription at once before, ran one in total. Measured: two topics, 3 events each, 6.0 s before, + 12.1 s after `19c4c48`, 6.0 s now. Unset, `nats_max_concurrent_runs` now keeps one slot per + subscription (`_Binding.subscription_slots`); set, the subscriptions share K (`run_slots`). + +Tests: `TestConcurrentRuns` (K at once, one at a time unset, one per subscription unset, shared when +set, slot freed after a failure, values below 1 refused) and `TestHeartbeat` (progress reported and +stopped before the ack, none for a short run, switched off, a string refused) -- the concurrency and +heartbeat of `19c4c48` had no unit test of their own. Docs: the key rows, event processing, +deployment guide; `CHANGELOG.md`. + +Acceptance against `nats:2.10-alpine` in WSL, same probe as `19c4c48`: one topic 5 events 10.1 s, +two tenants on one subscription 12.1 s, two topics 6.0 s / 2 at once, two agents 6.0 s / 2 at once, +`nats_max_concurrent_runs = 4` 4.0 s / 4 at once, a 7 s run under a 3 s `ack_wait` once. Integration +suite: 41 passed, 2 failed -- `test_the_broker_counts_it_as_a_redelivery` and +`test_two_processes_share_cache`, both failing identically without these changes (control run). + --- ## Open points diff --git a/docs/plans/2026-10-14-named-connections.md b/docs/plans/2026-10-14-named-connections.md index 77621ec2..de9968f0 100644 --- a/docs/plans/2026-10-14-named-connections.md +++ b/docs/plans/2026-10-14-named-connections.md @@ -194,7 +194,9 @@ All taken on 2026-10-14; each entry starts with the decision, followed by the an - Both keys take an absolute number or a percentage of the current number of (agent, connection) pairs in the process (`"33%"`), recomputed when connections are added or removed. The owner's sizing: K up to about a third of the pairs. - - Defaults keep today's behaviour: K = 1 (so no further runs at all), pool unset (unlimited). + - Defaults keep today's behaviour: K unset = one run at a time *per subscription* (what every + agent did before; corrected in step 1 -- `19c4c48` had made it one per agent), pool unset + (unlimited). With K set, the subscriptions of a pair share its K runs. - Order of acquisition is fixed (the pair's slot, then the pool), so there is no deadlock; waiters are served first come, first served, so no pair starves. - Consequence to measure: guaranteed first runs are uncapped, so in the worst case every pair diff --git a/src/blueprint/agent_generator/docs/concepts/event-processing.md b/src/blueprint/agent_generator/docs/concepts/event-processing.md index 88deba2e..956df1f6 100644 --- a/src/blueprint/agent_generator/docs/concepts/event-processing.md +++ b/src/blueprint/agent_generator/docs/concepts/event-processing.md @@ -300,7 +300,8 @@ unset, each is the server's default: heartbeat. **How many deliveries run at once.** Each delivery runs as its own task, up to -`nats_max_concurrent_runs` per agent and process (default `1`: one at a time). The subscription +`nats_max_concurrent_runs` per agent and process, shared by its subscriptions (unset: one at a time +per subscription, as before the key existed). The subscription waits for a free slot before it takes the next message, so a full agent stops taking work rather than starting more. Order within a subject is not kept beyond one run at a time. @@ -308,7 +309,7 @@ than starting more. Order within a subject is not kept beyond one run at a time. `in_progress` every third of the consumer's `ack_wait` -- the value the broker has, not `nats_ack_wait`, since an existing consumer keeps its own. A run longer than `ack_wait` is therefore not redelivered while it still runs. A message still waiting for a slot gets no -heartbeat. +heartbeat. `nats_heartbeat_enabled = false` switches the heartbeat off for an agent. An existing consumer is never rewritten. Its filter subject and deliver group are broker-side state that the stream's redelivery bookkeeping hangs off, so changing them is a migration: the diff --git a/src/blueprint/agent_generator/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md index 63a08942..7a34a713 100644 --- a/src/blueprint/agent_generator/docs/guides/deployment.md +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -348,7 +348,8 @@ Unset, each is the server's default: the framework sets no consumer setting on i at once. - **`nats_max_deliver`** bounds retries. Unset it is unlimited, so a message that keeps failing is retried forever and never dead-lettered. -- **`nats_max_concurrent_runs`** (default 1) is how many deliveries one pod runs at once per agent. +- **`nats_max_concurrent_runs`** (unset: one per subscription) is how many deliveries one pod runs at + once per agent. An agent that waits on models most of the time can run many at once on one event loop; set `nats_max_ack_pending` to about replicas x this value, so pods do not hoard messages they cannot start yet. diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index ef882925..48441533 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -45,7 +45,8 @@ Settings for the event bus transport layer. | `nats_durable_name` | `str` | `"-durable"` | Name of the durable consumer. Derived from the topic by default, with `.`, `*`, `>` and whitespace replaced by `_` because NATS rejects them in a consumer name. A client that belongs to a namespace prefixes it (`"--durable"`), so two agents subscribing to the same topic get a consumer each. Setting it explicitly is only valid with a single subscribed topic: a durable filters one subject, and under a namespace it must be scoped per namespace or every namespace binds to the same consumer. | | `nats_ack_wait` | `float` | unset -- the server's default (NATS: 30 s) | Seconds the broker waits for an acknowledgement before redelivering. **Must exceed the p99 duration of your slowest handler**, or long inference is redelivered to another replica while the first is still working. Handlers that call models usually need more than the NATS default, so set it. | | `nats_max_ack_pending` | `int` | unset -- the server's default (NATS: 1000) | Unacknowledged messages the consumer may have outstanding at once, counted across every replica sharing it. `-1` is unlimited. Keep it close to replicas x `nats_max_concurrent_runs`: whatever a pod receives beyond the runs it has started waits in the client's queue, unheartbeated, while its `nats_ack_wait` is already running down. | -| `nats_max_concurrent_runs` | `int` | `1` | Deliveries this agent handles at once, per process, across all of its subscriptions. `1` is one at a time, as before the key existed. An agent that spends its runs waiting on a model or an API gains the most from raising it; every run shares the process's one event loop, so CPU-heavy handlers gain little. Applies to Core NATS and JetStream alike. | +| `nats_max_concurrent_runs` | `int` | unset -- one run at a time per subscription, as before the key existed | Deliveries this agent handles at once, per process, shared by all of its subscriptions. Unset, each subscription runs one delivery at a time on its own, so an agent with two subscriptions runs two at once. An agent that spends its runs waiting on a model or an API gains the most from raising it; every run shares the process's one event loop, so CPU-heavy handlers gain little. Applies to Core NATS and JetStream alike. | +| `nats_heartbeat_enabled` | `bool` | `true` | Whether a running JetStream delivery reports `in_progress` every third of its consumer's `ack_wait`, so a run longer than `ack_wait` is not redelivered while it still runs. Switch it off only for an agent whose runs always finish well inside `ack_wait`; off, a long run is delivered again to another replica. Must be a boolean -- the string `"false"` is refused, because it would read as true. | | `nats_max_deliver` | `int` | unset -- the server's default (NATS: unlimited) | Delivery attempts before the message is dead-lettered. Unlimited -- the default, or `-1` -- means a permanently failing message is retried forever and never dead-lettered; the client logs a warning at startup if you set `-1` explicitly. Set a positive limit to bound retries. | | `nats_dead_letter_subject` | `str` | `".dead-letter"` | Subject a message is republished to when the framework gives up on it -- either a terminal failure (`InvalidEventError`, `CriticalHandlerError`, or a payload that is not a CloudEvent) or `nats_max_deliver` attempts spent. The original bytes are republished unchanged, with `Blueprint-Dead-Letter-Reason`, `Blueprint-Original-Subject`, `Blueprint-Delivery-Count` and `Blueprint-Event-Id` headers. Set to `""` to disable, which drops those messages and loses their payloads. Startup fails if the subject is a wildcard or is itself one of the subscribed subjects, since that would loop. | @@ -252,7 +253,7 @@ nats_stream_name = "EVENTS" nats_ack_wait = 300.0 # must exceed the p99 handler duration nats_max_ack_pending = 16 # outstanding messages across all replicas nats_max_deliver = 5 # attempts before the message is dead-lettered -nats_max_concurrent_runs = 8 # deliveries one process handles at once (default 1) +nats_max_concurrent_runs = 8 # deliveries one process handles at once (unset: one per subscription) # nats_dead_letter_subject = "my_agent_service.dead-letter" # defaults to .dead-letter # Event deduplication (off by default; both keys are needed to turn it on) diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 66d44534..58bc0685 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -2,12 +2,13 @@ import asyncio import contextlib +import functools import importlib.util import json import logging import re from collections.abc import Awaitable, Callable -from dataclasses import dataclass +from dataclasses import dataclass, field from functools import cached_property from pathlib import Path from typing import Any @@ -110,6 +111,72 @@ class ConsumerTuning: dead_letter_subject: str +@dataclass(eq=False) +class _Link: + """One broker connection and what it was opened with. + + Held apart from :class:`_Binding` so that what a connection *is* (URL, credentials, the + ``nats.Client``) and what is consumed *over* it (subscriptions, runs) can vary + independently: today every binding has a link of its own, and a link shared by several + bindings stays possible without reshaping either (named-connections plan, D1). + """ + + name: str = "" + """``""`` for the agent's default connection, configured through ``nats_url`` and friends.""" + url: str = "" + connect_options: dict[str, Any] = field(default_factory=dict) + connection_name: str = "" + nats_client: NatsClient | None = None + js: JetStreamContext | None = None + jetstream_mismatch: JetStreamUnavailableError | None = None + + +@dataclass(eq=False) +class _Binding: + """What one agent consumes over one link, and the runs it has in flight there. + + Every delivery is decoded, run, heartbeated and settled against the binding it arrived + on, so nothing of one binding's runs -- slots, in-flight count, acknowledgement -- is + shared with another's. + """ + + link: _Link + topic_callbacks: dict[str, DeliveryCallback] = field(default_factory=dict) + durables: dict[str, str] = field(default_factory=dict) + tuning: ConsumerTuning | None = None + subscriptions: list[Any] = field(default_factory=list) + subscriptions_ready: bool = False + run_slots: asyncio.Semaphore | None = None + """Shared by every subscription of the binding when ``nats_max_concurrent_runs`` is set.""" + subscription_slots: dict[str, asyncio.Semaphore] = field(default_factory=dict) + """One slot per subscription when it is not set -- one run at a time per subscription.""" + runs: set[asyncio.Task[None]] = field(default_factory=set) + ack_waits: dict[str, float] = field(default_factory=dict) + """Per topic, the bound consumer's own ``ack_wait`` -- what the heartbeat interval derives from.""" + inflight: int = 0 + idle: asyncio.Event = field(default_factory=asyncio.Event) + + def __post_init__(self) -> None: + self.idle.set() + + def slots_for(self, topic: str) -> asyncio.Semaphore: + """The slots a delivery on ``topic`` waits for: the binding's shared ones, else its subscription's own.""" + if self.run_slots is not None: + return self.run_slots + return self.subscription_slots.setdefault(topic, asyncio.Semaphore(1)) + + def enter_run(self) -> None: + """Count one delivery in; shutdown and pause wait until the count is back to zero.""" + self.inflight += 1 + self.idle.clear() + + def exit_run(self) -> None: + """Count one delivery out.""" + self.inflight = max(0, self.inflight - 1) + if self.inflight == 0: + self.idle.set() + + class NATSClient(IOClientBase): """NATS client for subscribing to and publishing CloudEvents. @@ -185,8 +252,11 @@ class NATSClient(IOClientBase): message is dead-lettered; unlimited disables dead-lettering on exhaustion. ``nats_dead_letter_subject`` (str, default ``".dead-letter"``): where a message goes when the framework gives up on it; ``""`` disables it and loses the payload. - ``nats_max_concurrent_runs`` (int, default 1): deliveries this agent handles at once, across - all of its subscriptions. ``1`` is the behaviour before the key existed: one run at a time. + ``nats_max_concurrent_runs`` (int, unset by default): deliveries this agent handles at once, + shared by all of its subscriptions. Unset is the behaviour before the key existed: one run at a + time *per subscription*, so an agent with two subscriptions runs two at once. + ``nats_heartbeat_enabled`` (bool, default true): whether running JetStream deliveries report + ``in_progress``; off, a run longer than the consumer's ``ack_wait`` is redelivered while it runs. Concurrent runs ~~~~~~~~~~~~~~~ @@ -194,7 +264,8 @@ class NATSClient(IOClientBase): the next message. A callback that ran the handler itself therefore handled one delivery per subscription at a time, however much of the handler was spent waiting on I/O. The callback now only waits for a free run slot and starts the run as a task of its own, so up to - ``nats_max_concurrent_runs`` runs of this agent are in progress at once. Waiting for the slot + ``nats_max_concurrent_runs`` runs of this agent are in progress at once. Unset, each + subscription keeps one slot of its own, exactly the old behaviour. Waiting for the slot *inside* the callback is the back-pressure: with every slot taken, the subscription's task stops taking messages and they wait in the client's buffer (bounded by ``max_ack_pending``) rather than starting. Order within a subscription is not kept beyond one run at a time. @@ -202,38 +273,137 @@ class NATSClient(IOClientBase): While a JetStream run is in progress its delivery is reported ``in_progress`` every third of the bound consumer's ``ack_wait``, so a run longer than ``ack_wait`` is not redelivered while it still runs (handler-time-bounds spec sec. 4.1). Messages still waiting in the buffer get no - heartbeat; their ``ack_wait`` keeps running. + heartbeat; their ``ack_wait`` keeps running. ``nats_heartbeat_enabled = false`` switches it off. + + Links and bindings + ~~~~~~~~~~~~~~~~~~ + The broker connection is a :class:`_Link`; what this agent consumes over it, with its run + slots and in-flight runs, is a :class:`_Binding`. Today the client has exactly one of each, + the *default* ones configured by ``nats_url`` and friends, and the delivery path takes the + binding a message arrived on as a parameter (named-connections plan, step 1). """ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: super().__init__(namespace=namespace) - self._connection_name: str = "" - self._nats_url: str = "" - self._connect_options: dict[str, Any] = {} - self._jetstream_mismatch: JetStreamUnavailableError | None = None + self._link = _Link() + self._binding = _Binding(link=self._link) self._started = False self._fatal_handler: FatalHandler | None = None self._fatal_reported = False - self._nats_client: NatsClient | None = None - self._js: JetStreamContext | None = None self._use_jetstream: bool = False self._publish_via_jetstream: bool = False self._publish_subjects: set[str] = set() - self._subscriptions: list[Any] = [] - self._topic_callbacks: dict[str, DeliveryCallback] = {} self._queue_group: str = "" - self._tuning: ConsumerTuning | None = None - self._durables: dict[str, str] = {} - self._subscriptions_ready: bool = False self._subscriptions_managed: bool = False self._retry_task: asyncio.Task[None] | None = None - self._inflight: int = 0 - self._idle: asyncio.Event = asyncio.Event() - self._idle.set() - self._max_concurrent_runs: int = 1 - self._run_slots: asyncio.Semaphore = asyncio.Semaphore(1) - self._runs: set[asyncio.Task[None]] = set() - self._ack_waits: dict[str, float] = {} + self._max_concurrent_runs: int | None = None + self._heartbeat_enabled: bool = True + + # ------------------------------------------------------------------ + # The default link and binding, under the names the client used before it had them + # ------------------------------------------------------------------ + # Transitional: unit tests reach these by name. They go once the tests address links and + # bindings directly (named-connections plan, step 3). + + @property + def _connection_name(self) -> str: + return self._link.connection_name + + @_connection_name.setter + def _connection_name(self, value: str) -> None: + self._link.connection_name = value + + @property + def _nats_url(self) -> str: + return self._link.url + + @_nats_url.setter + def _nats_url(self, value: str) -> None: + self._link.url = value + + @property + def _connect_options(self) -> dict[str, Any]: + return self._link.connect_options + + @_connect_options.setter + def _connect_options(self, value: dict[str, Any]) -> None: + self._link.connect_options = value + + @property + def _jetstream_mismatch(self) -> JetStreamUnavailableError | None: + return self._link.jetstream_mismatch + + @_jetstream_mismatch.setter + def _jetstream_mismatch(self, value: JetStreamUnavailableError | None) -> None: + self._link.jetstream_mismatch = value + + @property + def _nats_client(self) -> NatsClient | None: + return self._link.nats_client + + @_nats_client.setter + def _nats_client(self, value: NatsClient | None) -> None: + self._link.nats_client = value + + @property + def _js(self) -> JetStreamContext | None: + return self._link.js + + @_js.setter + def _js(self, value: JetStreamContext | None) -> None: + self._link.js = value + + @property + def _subscriptions(self) -> list[Any]: + return self._binding.subscriptions + + @_subscriptions.setter + def _subscriptions(self, value: list[Any]) -> None: + self._binding.subscriptions = value + + @property + def _topic_callbacks(self) -> dict[str, DeliveryCallback]: + return self._binding.topic_callbacks + + @_topic_callbacks.setter + def _topic_callbacks(self, value: dict[str, DeliveryCallback]) -> None: + self._binding.topic_callbacks = value + + @property + def _tuning(self) -> ConsumerTuning | None: + return self._binding.tuning + + @_tuning.setter + def _tuning(self, value: ConsumerTuning | None) -> None: + self._binding.tuning = value + + @property + def _durables(self) -> dict[str, str]: + return self._binding.durables + + @_durables.setter + def _durables(self, value: dict[str, str]) -> None: + self._binding.durables = value + + @property + def _subscriptions_ready(self) -> bool: + return self._binding.subscriptions_ready + + @_subscriptions_ready.setter + def _subscriptions_ready(self, value: bool) -> None: + self._binding.subscriptions_ready = value + + @property + def _inflight(self) -> int: + return self._binding.inflight + + @property + def _runs(self) -> set[asyncio.Task[None]]: + return self._binding.runs + + @property + def _ack_waits(self) -> dict[str, float]: + return self._binding.ack_waits # ------------------------------------------------------------------ # Public state @@ -298,7 +468,9 @@ async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: self._topic_callbacks = topic_callbacks self._queue_group = self._resolve_queue_group() self._max_concurrent_runs = self._resolve_max_concurrent_runs() - self._run_slots = asyncio.Semaphore(self._max_concurrent_runs) + # Unset keeps one run per subscription (subscription_slots); set, the subscriptions share K. + self._binding.run_slots = asyncio.Semaphore(self._max_concurrent_runs) if self._max_concurrent_runs else None + self._heartbeat_enabled = self._resolve_heartbeat_enabled() if self.config.get("nats_use_jetstream", False): self._durables = self._resolve_durables(list(topic_callbacks)) self._tuning = self._resolve_consumer_tuning(list(topic_callbacks)) @@ -621,15 +793,27 @@ def _read_optional_float(self, key: str) -> float | None: return None return self._read_float(key, 0.0) - def _resolve_max_concurrent_runs(self) -> int: - """Return ``nats_max_concurrent_runs``: at least 1, and 1 when it is not configured.""" + def _resolve_max_concurrent_runs(self) -> int | None: + """Return ``nats_max_concurrent_runs``: at least 1, or ``None`` when it is not configured.""" value = self._read_optional_int("nats_max_concurrent_runs") if value is None: - return 1 + return None if value < 1: raise ValueError(f"'nats_max_concurrent_runs' must be at least 1, got {value}. It is how many deliveries run at once.") return value + def _resolve_heartbeat_enabled(self) -> bool: + """Return ``nats_heartbeat_enabled``: whether running JetStream deliveries report ``in_progress``. + + Raises: + ValueError: if the value is not a boolean -- a string such as ``"false"`` would + otherwise read as true and keep the heartbeat the operator meant to switch off. + """ + value = self.config.get("nats_heartbeat_enabled", True) + if not isinstance(value, bool): + raise ValueError(f"'nats_heartbeat_enabled' must be true or false, got {value!r}.") + return value + def _read_optional_int(self, key: str) -> int | None: """Read ``key`` as an integer, or ``None`` when it is not configured.""" if self.config.get(key, None) is None: @@ -1008,13 +1192,14 @@ async def close(self) -> None: # Internal -- shutdown # ------------------------------------------------------------------ - async def _drain_subscriptions(self, deadline: float) -> None: + async def _drain_subscriptions(self, deadline: float, binding: _Binding | None = None) -> None: """Stop new deliveries while letting already-queued messages reach their handler. Falls back to an immediate unsubscribe if a drain fails or outlives the deadline, so one stuck subscription cannot hold up shutdown. """ - for sub in self._subscriptions: + binding = binding or self._binding + for sub in binding.subscriptions: remaining = max(0.0, deadline - asyncio.get_running_loop().time()) try: await asyncio.wait_for(sub.drain(), timeout=remaining) @@ -1024,7 +1209,7 @@ async def _drain_subscriptions(self, deadline: float) -> None: except Exception as e: logger.warning("Failed to drain a NATS subscription (%s); unsubscribing instead", e) await self._force_unsubscribe(sub) - self._subscriptions.clear() + binding.subscriptions.clear() @staticmethod def _decode_message(msg: Any, topic: str) -> CloudEvent[Any] | None: @@ -1047,29 +1232,27 @@ async def _force_unsubscribe(sub: Any) -> None: with contextlib.suppress(Exception): await sub.unsubscribe() - async def _await_inflight(self, deadline: float) -> None: + async def _await_inflight(self, deadline: float, binding: _Binding | None = None) -> None: """Give handlers that are still running a bounded chance to finish.""" - if self._inflight == 0: + binding = binding or self._binding + if binding.inflight == 0: return remaining = max(0.0, deadline - asyncio.get_running_loop().time()) - logger.debug("Waiting up to %.1fs for %d in-flight NATS handler(s)", remaining, self._inflight) + logger.debug("Waiting up to %.1fs for %d in-flight NATS handler(s)", remaining, binding.inflight) try: - await asyncio.wait_for(self._idle.wait(), timeout=remaining) + await asyncio.wait_for(binding.idle.wait(), timeout=remaining) except TimeoutError: logger.error( "Shutdown deadline reached with %d NATS handler(s) still running; their messages will be redelivered", - self._inflight, + binding.inflight, ) def _enter_handler(self) -> None: - self._inflight += 1 - self._idle.clear() + self._binding.enter_run() def _exit_handler(self) -> None: - self._inflight = max(0, self._inflight - 1) - if self._inflight == 0: - self._idle.set() + self._binding.exit_run() # ------------------------------------------------------------------ # Publish @@ -1368,18 +1551,20 @@ def _consumer_drift(actual: js_api.ConsumerConfig, desired: js_api.ConsumerConfi # Internal — per-topic subscription # ------------------------------------------------------------------ - async def _subscribe_one(self, topic: str, callback: DeliveryCallback) -> None: + async def _subscribe_one(self, topic: str, callback: DeliveryCallback, binding: _Binding | None = None) -> None: + binding = binding or self._binding client = await self.client async def message_handler(msg: Any) -> None: - # Runs on the subscription's one nats-py task. It waits for a run slot -- the - # back-pressure -- and returns as soon as the run is started, so the task can take the - # next message while this one is still running. - await self._run_slots.acquire() - self._enter_handler() - run = asyncio.create_task(self._run_delivery(msg, topic, callback), name=f"nats-run-{self.namespace or ROOT_LABEL}") - self._runs.add(run) - run.add_done_callback(self._run_finished) + # Runs on the subscription's one nats-py task. It waits for a run slot of the binding the + # message arrived on -- the back-pressure -- and returns as soon as the run is started, so + # the task can take the next message while this one is still running. + slots = binding.slots_for(topic) + await slots.acquire() + binding.enter_run() + run = asyncio.create_task(self._run_delivery(msg, topic, callback, binding), name=f"nats-run-{self.namespace or ROOT_LABEL}") + binding.runs.add(run) + run.add_done_callback(functools.partial(self._run_finished, binding, slots)) try: if self._use_jetstream and client.jetstream(): @@ -1393,7 +1578,7 @@ async def message_handler(msg: Any) -> None: # max_ack_pending and max_deliver where the broker can enforce them. consumer_config = await self._ensure_consumer(topic, durable_name) # The broker's value, not nats_ack_wait: an existing consumer keeps its own. - self._ack_waits[topic] = consumer_config.ack_wait or SERVER_DEFAULT_ACK_WAIT + binding.ack_waits[topic] = consumer_config.ack_wait or SERVER_DEFAULT_ACK_WAIT sub = await client.jetstream().subscribe_bind( stream=stream_name, config=consumer_config, @@ -1417,7 +1602,7 @@ async def message_handler(msg: Any) -> None: else: logger.info("Subscribed to Core NATS topic '%s'", topic) - self._subscriptions.append(sub) + binding.subscriptions.append(sub) except Exception as e: logger.error("Failed to subscribe to topic '%s': %s", topic, str(e)) @@ -1427,19 +1612,20 @@ async def message_handler(msg: Any) -> None: # Internal -- one run # ------------------------------------------------------------------ - async def _run_delivery(self, msg: Any, topic: str, callback: DeliveryCallback) -> None: + async def _run_delivery(self, msg: Any, topic: str, callback: DeliveryCallback, binding: _Binding) -> None: """Decode, dispatch and settle one delivery; runs as its own task, beside its heartbeat. The heartbeat is stopped before the delivery is settled, whatever ended the run. A cancelled run (shutdown past its deadline) is not settled: the broker redelivers it. + Everything is settled against ``binding``, the one the message arrived on. """ cloud_event = self._decode_message(msg, topic) if cloud_event is None: # A payload that will not parse now will not parse on redelivery either. - await self._settle(msg, DeliveryDisposition.TERM, topic, None) + await self._settle(msg, DeliveryDisposition.TERM, topic, None, binding) return - heartbeat = self._start_heartbeat(msg, topic) + heartbeat = self._start_heartbeat(msg, topic, binding) disposition = DeliveryDisposition.ACK try: await callback(cloud_event, msg.subject) @@ -1459,13 +1645,13 @@ async def _run_delivery(self, msg: Any, topic: str, callback: DeliveryCallback) # A heartbeat never fails the run (handler-time-bounds spec sec. 4.1). with contextlib.suppress(asyncio.CancelledError, Exception): await heartbeat - await self._settle(msg, disposition, topic, cloud_event.id) + await self._settle(msg, disposition, topic, cloud_event.id, binding) - def _run_finished(self, run: asyncio.Task[None]) -> None: - """Free the run's slot and count it out of the in-flight handlers shutdown waits for.""" - self._runs.discard(run) - self._run_slots.release() - self._exit_handler() + def _run_finished(self, binding: _Binding, slots: asyncio.Semaphore, run: asyncio.Task[None]) -> None: + """Free the run's slot and count it out of the in-flight runs shutdown waits for.""" + binding.runs.discard(run) + slots.release() + binding.exit_run() if not run.cancelled() and run.exception() is not None: # _run_delivery settles every handler failure itself; this is a fault in the run's own code. logger.error( @@ -1475,10 +1661,10 @@ def _run_finished(self, run: asyncio.Task[None]) -> None: exc_info=run.exception(), ) - def _start_heartbeat(self, msg: Any, topic: str) -> asyncio.Task[None] | None: - """Start reporting ``in_progress`` for a JetStream delivery; ``None`` on Core NATS.""" - ack_wait = self._ack_waits.get(topic) - if not self._use_jetstream or ack_wait is None: + def _start_heartbeat(self, msg: Any, topic: str, binding: _Binding) -> asyncio.Task[None] | None: + """Start reporting ``in_progress`` for a JetStream delivery; ``None`` on Core NATS or when switched off.""" + ack_wait = binding.ack_waits.get(topic) + if not self._heartbeat_enabled or not self._use_jetstream or ack_wait is None: return None heartbeat = asyncio.create_task(self._keep_alive(msg, ack_wait / 3), name=f"nats-heartbeat-{self.namespace or ROOT_LABEL}") heartbeat.add_done_callback(self._heartbeat_finished) @@ -1512,7 +1698,9 @@ async def _keep_alive(msg: Any, interval: float) -> None: # Internal — acknowledgement # ------------------------------------------------------------------ - async def _settle(self, msg: Any, disposition: DeliveryDisposition, topic: str, event_id: str | None) -> None: + async def _settle( + self, msg: Any, disposition: DeliveryDisposition, topic: str, event_id: str | None, binding: _Binding | None = None + ) -> None: """Tell the broker what became of a delivery (spec sec. 7.2). Only JetStream deliveries can be settled. Core NATS is fire-and-forget and @@ -1536,13 +1724,14 @@ async def _settle(self, msg: Any, disposition: DeliveryDisposition, topic: str, if not self._use_jetstream: return + binding = binding or self._binding try: if disposition is DeliveryDisposition.ACK: await msg.ack() - elif disposition is DeliveryDisposition.NAK and not self._deliveries_exhausted(msg): + elif disposition is DeliveryDisposition.NAK and not self._deliveries_exhausted(msg, binding): await msg.nak() else: - await self._dead_letter(msg, disposition, topic, event_id) + await self._dead_letter(msg, disposition, topic, event_id, binding) await msg.term() except Exception as exc: logger.error( @@ -1553,7 +1742,7 @@ async def _settle(self, msg: Any, disposition: DeliveryDisposition, topic: str, exc, ) - def _deliveries_exhausted(self, msg: Any) -> bool: + def _deliveries_exhausted(self, msg: Any, binding: _Binding | None = None) -> bool: """Whether the broker has no redelivery left for this message. ``max_deliver`` counts attempts, so the last one the broker makes is attempt @@ -1562,7 +1751,8 @@ def _deliveries_exhausted(self, msg: Any) -> bool: as not exhausted, so an unreadable header can only cost a retry, never a payload. """ # Not configured means the server's default, which is unlimited. - max_deliver = self._tuning.max_deliver if self._tuning else None + tuning = (binding or self._binding).tuning + max_deliver = tuning.max_deliver if tuning else None if max_deliver is None or max_deliver < 0: return False delivered = self._delivery_count(msg) @@ -1576,7 +1766,9 @@ def _delivery_count(msg: Any) -> int | None: except Exception: return None - async def _dead_letter(self, msg: Any, disposition: DeliveryDisposition, topic: str, event_id: str | None) -> None: + async def _dead_letter( + self, msg: Any, disposition: DeliveryDisposition, topic: str, event_id: str | None, binding: _Binding | None = None + ) -> None: """Republish a message the framework has given up on, before the delivery is termed. Both terminal outcomes arrive here: a payload rejected as unprocessable, and one @@ -1586,7 +1778,8 @@ async def _dead_letter(self, msg: Any, disposition: DeliveryDisposition, topic: CloudEvent. What went wrong travels in headers instead, where it cannot corrupt a body a dead-letter consumer will try to read. """ - subject = self._tuning.dead_letter_subject if self._tuning else "" + binding = binding or self._binding + subject = binding.tuning.dead_letter_subject if binding.tuning else "" delivered = self._delivery_count(msg) reason = "deliveries-exhausted" if disposition is DeliveryDisposition.NAK else "terminal-failure" @@ -1611,7 +1804,8 @@ async def _dead_letter(self, msg: Any, disposition: DeliveryDisposition, topic: headers["Blueprint-Event-Id"] = event_id try: - await self._nats_client.jetstream().publish(subject, msg.data, headers=headers) # type: ignore[union-attr] + # On the binding's own link: a dead letter never leaves the connection it arrived on. + await binding.link.nats_client.jetstream().publish(subject, msg.data, headers=headers) # type: ignore[union-attr] except Exception as exc: self._count_dead_letter(reason, kept=False) logger.error( diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index 10f46946..fe21843e 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -2311,3 +2311,155 @@ async def test_the_subscribe_line(self, connected_nats_client: NATSClient, caplo with caplog.at_level("INFO", logger="blueprint.agents.clients.io.nats_client"): await connected_nats_client._subscribe_one("orders.created", AsyncMock()) assert caplog.messages == ["Subscribed to Core NATS topic 'orders.created'"] + + +def _delivery(cloud_event: CloudEvent) -> MagicMock: + """A JetStream delivery whose settlement and heartbeat calls are recorded in one order.""" + msg = MagicMock(data=json.dumps(dict(cloud_event)).encode(), reply="$JS.ACK.x", subject="orders.created") + for name in ("ack", "nak", "term", "in_progress"): + setattr(msg, name, AsyncMock()) + msg.metadata.num_delivered = 1 + return msg + + +async def _js_delivery_handler(nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, callback, **overrides: object): + """The raw broker callback of one JetStream subscription, with the given config overrides.""" + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"], **overrides) + await nats_client._subscribe_one("orders.created", callback) + mock_nc, _ = mock_nats_jetstream + return mock_nc.jetstream().subscribe_bind.await_args.kwargs["cb"] + + +class TestConcurrentRuns: + """Deliveries run as tasks of their own, up to nats_max_concurrent_runs per binding.""" + + @staticmethod + async def _started_while_blocked( + handler, nats_client: NATSClient, cloud_event: CloudEvent, deliveries: int, gate: asyncio.Event, started: list + ): + callers = [asyncio.create_task(handler(_delivery(cloud_event))) for _ in range(deliveries)] + for _ in range(20): + await asyncio.sleep(0) + running = len(started) + gate.set() + await asyncio.gather(*callers) + await asyncio.gather(*list(nats_client._runs), return_exceptions=True) + return running + + @staticmethod + def _blocking_callback(gate: asyncio.Event, started: list): + async def callback(event: CloudEvent, subject: str) -> None: + started.append(event.id) + await gate.wait() + + return callback + + async def test_runs_up_to_the_configured_number_at_once( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + gate, started = asyncio.Event(), [] + handler = await _js_delivery_handler( + nats_client, mock_config, mock_nats_jetstream, self._blocking_callback(gate, started), nats_max_concurrent_runs=2 + ) + running = await self._started_while_blocked(handler, nats_client, cloud_event, 3, gate, started) + assert running == 2 + assert len(started) == 3, "the third delivery runs once a slot is free" + + async def test_one_at_a_time_when_not_configured( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + gate, started = asyncio.Event(), [] + handler = await _js_delivery_handler(nats_client, mock_config, mock_nats_jetstream, self._blocking_callback(gate, started)) + assert await self._started_while_blocked(handler, nats_client, cloud_event, 3, gate, started) == 1 + + async def test_the_slot_is_freed_and_the_run_counted_out( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + handler = await _js_delivery_handler(nats_client, mock_config, mock_nats_jetstream, AsyncMock(side_effect=RuntimeError("boom"))) + await _until_settled(nats_client, handler)(_delivery(cloud_event)) + assert nats_client.inflight_handlers == 0 + assert nats_client._binding.slots_for("orders.created").locked() is False + + async def test_unset_keeps_one_run_per_subscription( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + """Before the key existed each subscription ran one delivery at a time, independently of the others.""" + assert await self._two_topics_at_once(nats_client, mock_config, mock_nats_jetstream, cloud_event) == 2 + + async def test_set_the_subscriptions_share_the_runs( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + assert await self._two_topics_at_once(nats_client, mock_config, mock_nats_jetstream, cloud_event, nats_max_concurrent_runs=1) == 1 + + async def _two_topics_at_once(self, nats_client, mock_config, mock_nats_jetstream, cloud_event, **overrides) -> int: + gate, started = asyncio.Event(), [] + callback = self._blocking_callback(gate, started) + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created", "orders.cancelled"], **overrides) + mock_nc, _ = mock_nats_jetstream + handlers = [] + for topic in ("orders.created", "orders.cancelled"): + await nats_client._subscribe_one(topic, callback) + handlers.append(mock_nc.jetstream().subscribe_bind.await_args.kwargs["cb"]) + callers = [asyncio.create_task(handler(_delivery(cloud_event))) for handler in handlers] + for _ in range(20): + await asyncio.sleep(0) + running = len(started) + gate.set() + await asyncio.gather(*callers) + await asyncio.gather(*list(nats_client._runs), return_exceptions=True) + return running + + @pytest.mark.parametrize("value", [0, -1]) + async def test_fewer_than_one_run_is_refused( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, value: int + ) -> None: + with pytest.raises(ValueError, match="nats_max_concurrent_runs"): + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"], nats_max_concurrent_runs=value) + + +class TestHeartbeat: + """A running JetStream delivery reports in_progress every third of the consumer's ack_wait.""" + + async def test_a_long_run_reports_progress_and_stops_before_settling( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + async def slow(event: CloudEvent, subject: str) -> None: + await asyncio.sleep(0.1) + + handler = await _js_delivery_handler(nats_client, mock_config, mock_nats_jetstream, slow, nats_ack_wait=0.03) + msg = _delivery(cloud_event) + order = MagicMock() + order.attach_mock(msg.in_progress, "in_progress") + order.attach_mock(msg.ack, "ack") + await _until_settled(nats_client, handler)(msg) + + calls = [name for name, _, _ in order.mock_calls] + assert calls.count("in_progress") >= 2 + assert calls[-1] == "ack", "no heartbeat after the delivery is settled" + + async def test_a_short_run_sends_none( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + handler = await _js_delivery_handler(nats_client, mock_config, mock_nats_jetstream, AsyncMock(), nats_ack_wait=30.0) + msg = _delivery(cloud_event) + await _until_settled(nats_client, handler)(msg) + msg.in_progress.assert_not_awaited() + + async def test_it_can_be_switched_off( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + async def slow(event: CloudEvent, subject: str) -> None: + await asyncio.sleep(0.1) + + handler = await _js_delivery_handler( + nats_client, mock_config, mock_nats_jetstream, slow, nats_ack_wait=0.03, nats_heartbeat_enabled=False + ) + msg = _delivery(cloud_event) + await _until_settled(nats_client, handler)(msg) + msg.in_progress.assert_not_awaited() + msg.ack.assert_awaited_once() + + async def test_a_string_is_not_a_switch(self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple) -> None: + """'false' as a string would read as true and keep the heartbeat the operator meant to switch off.""" + with pytest.raises(ValueError, match="nats_heartbeat_enabled"): + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"], nats_heartbeat_enabled="false") From fa2e6096a5e4d8e98b38dddd4a6c710fa5292ed3 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 14 Oct 2026 14:53:47 +0200 Subject: [PATCH 073/133] feat(nats): binding mode -- consume through a consumer the deployment defines Step 2 of the named-connections plan. A JetStreamBinding carries every wire value of a deployment's consumer verbatim: the declared subjects it serves, the subject prefix, stream, durable, deliver subject and group, and the contract values ack_wait and max_deliver. A binding in this mode makes one plain subscription on the deliver subject in the deliver group, sends no JetStream API request unless it manages its consumer, never creates a stream, hands handlers the subject without the prefix, and settles, heartbeats and dead-letters on its own link. Verified against a broker with a restricted account: bound and acked with zero permission violations; the operator's consumer unchanged; a managed consumer identical to the one the first consumer creates. Co-Authored-By: Claude Opus 5 (1M context) --- ...26-08-28-multi-agent-grouping-changelog.md | 45 ++++ .../agents/clients/io/nats_client.py | 180 +++++++++++++-- .../agents/clients/io/nats_connections.py | 81 +++++++ .../clients/io/test_nats_binding_mode.py | 208 ++++++++++++++++++ 4 files changed, 491 insertions(+), 23 deletions(-) create mode 100644 src/blueprint/agents/clients/io/nats_connections.py create mode 100644 tests/unit/agents/clients/io/test_nats_binding_mode.py diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 803fd29b..7c589c00 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8252,6 +8252,51 @@ two tenants on one subscription 12.1 s, two topics 6.0 s / 2 at once, two agents suite: 41 passed, 2 failed -- `test_the_broker_counts_it_as_a_redelivery` and `test_two_processes_share_cache`, both failing identically without these changes (control run). +### Binding mode: consuming through a consumer the deployment defines (named connections, step 2) + +Step 2 of `docs/plans/2026-10-14-named-connections.md`. Not reachable from configuration yet -- the +connection source that creates such bindings is step 3. + +- New module `clients/io/nats_connections.py`, `JetStreamBinding` (frozen dataclass): the declared + subjects a connection serves, `subject_prefix`, stream, durable, deliver subject, deliver group, + the contract values `ack_wait` and `max_deliver`, optional `max_ack_pending`, `deliver_policy`, + `manage_consumer`, optional `dead_letter_subject`. `filter_subjects` = prefix + declared subject; + `consumer_config()` builds the consumer from those values verbatim; `local_subject()` strips the + prefix; `topic_for()` finds the declared subject covering a delivery. +- `_Binding.jetstream`: set, `_subscribe_all` calls `_bind` instead of provisioning a stream and + subscribing per topic. `_bind` makes **one plain subscription** on the deliver subject in the + deliver group -- as the first consumer's own pool does -- so receiving needs no JetStream + API request; with `manage_consumer` unset it sends none at all. With it set, + `_ensure_bound_consumer` checks the stream exists (missing: `JetStreamBindingError`, never created) + and creates or updates the consumer, deleting and recreating it when the broker refuses the + update (WARNING: its unacknowledged messages are lost) -- the deployment's behaviour today, and + unlike the agent's own consumers, which are never rewritten. +- `_message_handler(binding, slot_key, topic, callback)` replaces the closure in `_subscribe_one` + and serves both modes; in binding mode the topic is found per delivery (`_bound_topic`), and a + delivery no declared subject covers is termed without running. `_run_delivery` hands the handler + the subject without the prefix (plan D10). `_settles(binding)` makes a binding-mode delivery + settle and heartbeat whatever `nats_use_jetstream` says; the heartbeat interval comes from the + binding's `ack_wait`, exhaustion from its `max_deliver`, the dead-letter subject from the binding + (none: term + log, plan D6), published on the binding's own link. + +Tests: `test_nats_binding_mode.py`, 15 cases (the binding's values, no JetStream request when +unmanaged, create / recreate / missing stream when managed, prefix stripped, uncovered delivery +termed, heartbeat interval, nak below and dead letter or term at exhaustion). + +Acceptance against `nats:2.10-alpine` in WSL with a **restricted account** -- the agent user may +subscribe to its deliver subject and publish `$JS.ACK.>`, nothing else: an operator-made consumer +was bound, three `t..risk.created` events reached the handler as `risk.created`, one +`issue.created` was filtered out, all acked (ack pending 0, redelivered 0), the consumer's config +unchanged, **0 permission violations** in the broker log. Control: a managed binding with the same +user fails on `$JS.API.STREAM.INFO` with a publish violation, so the check is real. A consumer +created by the binding (`manage_consumer`) and one created by the first consumer's own pool for the +same tenant document are **identical** as the broker reports them. Unit suite 3391 passed; +integration 41 passed, the same 2 failing as without the change. + +Open for step 3: reconnect handling exists for the default link only (`_on_reconnected`); a named +link needs its own. A plain subscription is restored by nats-py on reconnect; whether the push +consumer delivers again without a JetStream request is to be shown against a broker restart. + --- ## Open points diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 58bc0685..10685a78 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -30,6 +30,7 @@ from ...models.events import CloudEvent from ..client_base import DeliveryCallback from .io_client_base import IOClientBase, subject_is_covered_by, validate_publish_subject, validate_subject_segment +from .nats_connections import JetStreamBinding logger = logging.getLogger(__name__) @@ -42,6 +43,13 @@ """ +class JetStreamBindingError(RuntimeError): + """A binding-mode binding cannot be bound as the deployment describes it (e.g. its stream is missing). + + Raised into the connection's retry loop, which retries it: provisioning may create the stream later. + """ + + class JetStreamUnavailableError(RuntimeError): """The agent declared ``nats_use_jetstream = true`` and the server does not offer JetStream to it. @@ -141,6 +149,9 @@ class _Binding: """ link: _Link + jetstream: JetStreamBinding | None = None + """Set: *binding mode* -- bind to the deployment's consumer with its wire values verbatim, + never provision (plan N3, N4). Unset: the agent's own consumers, derived as before.""" topic_callbacks: dict[str, DeliveryCallback] = field(default_factory=dict) durables: dict[str, str] = field(default_factory=dict) tuning: ConsumerTuning | None = None @@ -1368,17 +1379,25 @@ async def _connect_and_subscribe(self) -> None: return await self._subscribe_all() - async def _subscribe_all(self) -> None: - """Provision the stream once, then subscribe every topic. + async def _subscribe_all(self, binding: _Binding | None = None) -> None: + """Provision the stream once, then subscribe every topic -- or, in binding mode, bind. Shared by first connect and by reconnect, so a stream that was recreated while the client was away -- or a failover to a cluster peer that never had it -- is restored - before any consumer tries to bind to it. + before any consumer tries to bind to it. A binding-mode binding provisions nothing. """ + binding = binding or self._binding + if binding.jetstream is not None: + await self._bind(binding) + return if self._use_jetstream: await self._provision_stream() - for topic, callback in self._topic_callbacks.items(): - await self._subscribe_one(topic, callback) + for topic, callback in binding.topic_callbacks.items(): + await self._subscribe_one(topic, callback, binding) + + def _settles(self, binding: _Binding) -> bool: + """Whether deliveries on ``binding`` are JetStream deliveries that can be settled.""" + return binding.jetstream is not None or self._use_jetstream # ------------------------------------------------------------------ # Internal -- JetStream stream and consumer @@ -1554,17 +1573,7 @@ def _consumer_drift(actual: js_api.ConsumerConfig, desired: js_api.ConsumerConfi async def _subscribe_one(self, topic: str, callback: DeliveryCallback, binding: _Binding | None = None) -> None: binding = binding or self._binding client = await self.client - - async def message_handler(msg: Any) -> None: - # Runs on the subscription's one nats-py task. It waits for a run slot of the binding the - # message arrived on -- the back-pressure -- and returns as soon as the run is started, so - # the task can take the next message while this one is still running. - slots = binding.slots_for(topic) - await slots.acquire() - binding.enter_run() - run = asyncio.create_task(self._run_delivery(msg, topic, callback, binding), name=f"nats-run-{self.namespace or ROOT_LABEL}") - binding.runs.add(run) - run.add_done_callback(functools.partial(self._run_finished, binding, slots)) + message_handler = self._message_handler(binding, topic, topic, callback) try: if self._use_jetstream and client.jetstream(): @@ -1608,6 +1617,124 @@ async def message_handler(msg: Any) -> None: logger.error("Failed to subscribe to topic '%s': %s", topic, str(e)) raise + # ------------------------------------------------------------------ + # Internal -- binding mode (named-connections plan, step 2) + # ------------------------------------------------------------------ + + async def _bind(self, binding: _Binding) -> None: + """Consume through the deployment's consumer, exactly as its binding describes it. + + One consumer carries every subject the binding serves, delivered to its deliver subject + in its deliver group. The subscription is a plain one on that subject: the messages are + JetStream deliveries all the same (their reply subject is the ``$JS.ACK`` one), so they + are settled and heartbeated as usual, and no JetStream API request is needed to receive + them. With ``manage_consumer`` unset the client sends none at all -- the account may + only be allowed to receive and acknowledge. + + Raises: + JetStreamBindingError: the binding manages its consumer and its stream does not + exist. The stream belongs to whoever provisions the deployment; it is never + created here. + """ + spec = binding.jetstream + if spec is None: + raise RuntimeError("_bind needs a binding-mode binding") + client = binding.link.nats_client + if client is None: + raise RuntimeError("binding mode needs a connected link") + if spec.manage_consumer: + await self._ensure_bound_consumer(client, spec) + for topic in spec.subjects: + binding.ack_waits[topic] = spec.ack_wait + handler = self._message_handler(binding, spec.deliver_subject, None) + sub = await client.subscribe(spec.deliver_subject, queue=spec.deliver_group, cb=handler) + binding.subscriptions.append(sub) + logger.info( + "Agent '%s' bound to consumer '%s' on stream '%s' (deliver subject '%s', group '%s', subjects %s)", + self.namespace or ROOT_LABEL, + spec.durable, + spec.stream, + spec.deliver_subject, + spec.deliver_group, + ", ".join(spec.filter_subjects), + ) + + async def _ensure_bound_consumer(self, client: NatsClient, spec: JetStreamBinding) -> None: + """Create or update a binding's consumer; recreate it when the broker refuses the update. + + Unlike the agent's own consumers, which are never rewritten, a managed binding's consumer + follows its binding: the deployment that owns the values changed them. A consumer whose + immutable fields differ cannot be updated in place, so it is deleted and created again -- + and its unacknowledged messages are lost with it, which is why that is a WARNING. + """ + jsm = client.jsm() + try: + await jsm.stream_info(spec.stream) + except NotFoundError: + raise JetStreamBindingError( + f"Agent '{self.namespace or ROOT_LABEL}': stream '{spec.stream}' of consumer '{spec.durable}' does not " + "exist. It is provisioned by the deployment, never by the framework." + ) from None + config = spec.consumer_config() + try: + await jsm.add_consumer(spec.stream, config=config) + except APIError as exc: + logger.warning( + "Agent '%s': consumer '%s' on stream '%s' cannot be updated (%s); recreating it -- its unacknowledged " + "messages are lost with it", + self.namespace or ROOT_LABEL, + spec.durable, + spec.stream, + exc.description or exc, + ) + with contextlib.suppress(NotFoundError): + await jsm.delete_consumer(spec.stream, spec.durable) + await jsm.add_consumer(spec.stream, config=config) + + def _message_handler( + self, binding: _Binding, slot_key: str, topic: str | None, callback: DeliveryCallback | None = None + ) -> Callable[[Any], Awaitable[None]]: + """The callback a subscription on ``binding`` delivers to. + + It runs on the subscription's one nats-py task: it waits for a run slot -- the + back-pressure -- and returns as soon as the run is started, so the task can take the next + message while this one is still running. ``topic`` is the declared subject of a + per-topic subscription; ``None`` means one subscription for the whole binding, where the + topic is found per message from its subject. + """ + + async def message_handler(msg: Any) -> None: + resolved = topic if topic is not None else self._bound_topic(binding, msg) + if resolved is None: + await self._settle(msg, DeliveryDisposition.TERM, msg.subject, None, binding) + return + slots = binding.slots_for(slot_key) + await slots.acquire() + binding.enter_run() + dispatch = callback if callback is not None else binding.topic_callbacks[resolved] + run = asyncio.create_task(self._run_delivery(msg, resolved, dispatch, binding), name=f"nats-run-{self.namespace or ROOT_LABEL}") + binding.runs.add(run) + run.add_done_callback(functools.partial(self._run_finished, binding, slots)) + + return message_handler + + def _bound_topic(self, binding: _Binding, msg: Any) -> str | None: + """The declared subject a binding-mode delivery belongs to, or ``None`` (logged) if none covers it.""" + spec = binding.jetstream + if spec is None: + return None + topic = spec.topic_for(spec.local_subject(msg.subject)) + if topic is not None and topic in binding.topic_callbacks: + return topic + logger.error( + "Agent '%s': delivery on '%s' from consumer '%s' matches none of its subjects %s; terminating it", + self.namespace or ROOT_LABEL, + msg.subject, + spec.durable, + ", ".join(spec.subjects), + ) + return None + # ------------------------------------------------------------------ # Internal -- one run # ------------------------------------------------------------------ @@ -1628,7 +1755,8 @@ async def _run_delivery(self, msg: Any, topic: str, callback: DeliveryCallback, heartbeat = self._start_heartbeat(msg, topic, binding) disposition = DeliveryDisposition.ACK try: - await callback(cloud_event, msg.subject) + subject = binding.jetstream.local_subject(msg.subject) if binding.jetstream is not None else msg.subject + await callback(cloud_event, subject) except Exception as ex: disposition = disposition_for(ex) logger.error( @@ -1664,7 +1792,7 @@ def _run_finished(self, binding: _Binding, slots: asyncio.Semaphore, run: asynci def _start_heartbeat(self, msg: Any, topic: str, binding: _Binding) -> asyncio.Task[None] | None: """Start reporting ``in_progress`` for a JetStream delivery; ``None`` on Core NATS or when switched off.""" ack_wait = binding.ack_waits.get(topic) - if not self._heartbeat_enabled or not self._use_jetstream or ack_wait is None: + if not self._heartbeat_enabled or not self._settles(binding) or ack_wait is None: return None heartbeat = asyncio.create_task(self._keep_alive(msg, ack_wait / 3), name=f"nats-heartbeat-{self.namespace or ROOT_LABEL}") heartbeat.add_done_callback(self._heartbeat_finished) @@ -1721,10 +1849,10 @@ async def _settle( keeps the payload, on the dead-letter subject, and releases the consumer's pending slot immediately instead of one more ``ack_wait`` later. """ - if not self._use_jetstream: + binding = binding or self._binding + if not self._settles(binding): return - binding = binding or self._binding try: if disposition is DeliveryDisposition.ACK: await msg.ack() @@ -1751,8 +1879,11 @@ def _deliveries_exhausted(self, msg: Any, binding: _Binding | None = None) -> bo as not exhausted, so an unreadable header can only cost a retry, never a payload. """ # Not configured means the server's default, which is unlimited. - tuning = (binding or self._binding).tuning - max_deliver = tuning.max_deliver if tuning else None + binding = binding or self._binding + if binding.jetstream is not None: + max_deliver = binding.jetstream.max_deliver + else: + max_deliver = binding.tuning.max_deliver if binding.tuning else None if max_deliver is None or max_deliver < 0: return False delivered = self._delivery_count(msg) @@ -1779,7 +1910,10 @@ async def _dead_letter( body a dead-letter consumer will try to read. """ binding = binding or self._binding - subject = binding.tuning.dead_letter_subject if binding.tuning else "" + if binding.jetstream is not None: + subject = binding.jetstream.dead_letter_subject or "" + else: + subject = binding.tuning.dead_letter_subject if binding.tuning else "" delivered = self._delivery_count(msg) reason = "deliveries-exhausted" if disposition is DeliveryDisposition.NAK else "terminal-failure" diff --git a/src/blueprint/agents/clients/io/nats_connections.py b/src/blueprint/agents/clients/io/nats_connections.py new file mode 100644 index 00000000..0081e64d --- /dev/null +++ b/src/blueprint/agents/clients/io/nats_connections.py @@ -0,0 +1,81 @@ +"""What a deployment tells the framework about a connection it supplies (named-connections plan). + +The framework does not know what a named connection stands for. It receives, per agent and +connection, a :class:`JetStreamBinding`: which of the agent's declared subjects the connection +serves, the prefix that turns a declared subject into the subject on the wire, and the durable +consumer that carries them -- every wire value verbatim, never derived (N4). +""" + +from dataclasses import dataclass, field + +from nats.js import api as js_api + +from .io_client_base import subject_is_covered_by + + +@dataclass(frozen=True) +class JetStreamBinding: + """One agent's durable push consumer on one connection, as the deployment defines it. + + ``ack_wait`` and ``max_deliver`` are the consumer's contract values. They are carried here + rather than read from the broker because a binding with ``manage_consumer = False`` sends no + JetStream API request at all -- its account may not be allowed to -- so the client could not + ask. The heartbeat interval derives from ``ack_wait``; dead-lettering on exhaustion from + ``max_deliver``. + """ + + subjects: tuple[str, ...] + """The agent's declared subjects this connection serves, as the agent declared them.""" + stream: str + durable: str + deliver_subject: str + deliver_group: str + ack_wait: float + """Seconds; the consumer's own value, for the heartbeat interval (and for creating it).""" + subject_prefix: str = "" + """Filter subject = prefix + declared subject; stripped again before a handler sees the subject.""" + max_deliver: int | None = None + """``None`` or ``-1``: unlimited, so exhaustion never dead-letters.""" + max_ack_pending: int | None = None + deliver_policy: js_api.DeliverPolicy = js_api.DeliverPolicy.ALL + manage_consumer: bool = False + """``True``: create or update the consumer and check the stream exists. ``False``: bind only.""" + dead_letter_subject: str | None = None + """Where a given-up-on message goes, on this connection; ``None``: term and log (plan D6).""" + filter_subjects: tuple[str, ...] = field(init=False) + + def __post_init__(self) -> None: + if not self.subjects: + raise ValueError(f"Binding of durable '{self.durable}' serves no subject.") + if self.ack_wait <= 0: + raise ValueError(f"Binding of durable '{self.durable}': ack_wait must be greater than 0, got {self.ack_wait}.") + object.__setattr__(self, "filter_subjects", tuple(f"{self.subject_prefix}{subject}" for subject in self.subjects)) + + def consumer_config(self) -> js_api.ConsumerConfig: + """The consumer this binding creates when it manages its consumer.""" + return js_api.ConsumerConfig( + name=self.durable, + durable_name=self.durable, + deliver_subject=self.deliver_subject, + deliver_group=self.deliver_group, + filter_subjects=list(self.filter_subjects), + ack_policy=js_api.AckPolicy.EXPLICIT, + ack_wait=self.ack_wait, + max_deliver=self.max_deliver, + max_ack_pending=self.max_ack_pending, + deliver_policy=self.deliver_policy, + ) + + def local_subject(self, wire_subject: str) -> str: + """The subject as the agent knows it: ``wire_subject`` without this binding's prefix. + + A subject that does not carry the prefix is returned unchanged; the consumer's filter + makes that impossible for a delivery, and the topic match that follows rejects it. + """ + if self.subject_prefix and wire_subject.startswith(self.subject_prefix): + return wire_subject[len(self.subject_prefix) :] + return wire_subject + + def topic_for(self, local_subject: str) -> str | None: + """The declared subject that covers ``local_subject``, first in declaration order, or ``None``.""" + return next((subject for subject in self.subjects if subject_is_covered_by(local_subject, subject)), None) diff --git a/tests/unit/agents/clients/io/test_nats_binding_mode.py b/tests/unit/agents/clients/io/test_nats_binding_mode.py new file mode 100644 index 00000000..18d4b829 --- /dev/null +++ b/tests/unit/agents/clients/io/test_nats_binding_mode.py @@ -0,0 +1,208 @@ +"""Binding mode: an agent consumes through a consumer the deployment defines (named-connections plan, step 2).""" + +import asyncio +import json +from unittest.mock import AsyncMock, MagicMock + +import pytest +from nats.js import api as js_api +from nats.js.errors import APIError, NotFoundError + +from blueprint.agents.clients.io.nats_client import JetStreamBindingError, NATSClient, _Binding +from blueprint.agents.clients.io.nats_connections import JetStreamBinding +from blueprint.agents.models.errors import RetryableHandlerError +from blueprint.agents.models.events import CloudEvent + +PREFIX = "t.01900000-0000-7000-8000-0000000000a1." + + +def _spec(**overrides: object) -> JetStreamBinding: + values: dict = { + "subjects": ("risk.>",), + "stream": "NOTIFICATIONS_A", + "durable": "acme-agent-risk", + "deliver_subject": "acme.agent.A.risk", + "deliver_group": "risk", + "ack_wait": 600.0, + "subject_prefix": PREFIX, + "max_deliver": 5, + "deliver_policy": js_api.DeliverPolicy.NEW, + } + values.update(overrides) + return JetStreamBinding(**values) + + +def _delivery(cloud_event: CloudEvent, subject: str = f"{PREFIX}risk.created", delivered: int = 1) -> MagicMock: + msg = MagicMock(data=json.dumps(dict(cloud_event)).encode(), reply="$JS.ACK.x", subject=subject) + for name in ("ack", "nak", "term", "in_progress"): + setattr(msg, name, AsyncMock()) + msg.metadata.num_delivered = delivered + return msg + + +@pytest.fixture +def jsm() -> MagicMock: + manager = MagicMock() + manager.stream_info = AsyncMock() + manager.add_consumer = AsyncMock() + manager.delete_consumer = AsyncMock() + return manager + + +async def _bound( + nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock, callback, **overrides: object +) -> tuple[_Binding, object]: + """Bind a binding-mode binding on the client's link and return it with its broker callback.""" + mock_nats_core.jsm = MagicMock(return_value=jsm) + nats_client._link.nats_client = mock_nats_core + spec = _spec(**overrides) + binding = _Binding(link=nats_client._link, jetstream=spec, topic_callbacks=dict.fromkeys(spec.subjects, callback)) + await nats_client._subscribe_all(binding) + return binding, mock_nats_core.subscribe.await_args.kwargs["cb"] + + +async def _settled(binding: _Binding, handler, msg: MagicMock) -> None: + await handler(msg) + await asyncio.gather(*list(binding.runs), return_exceptions=True) + + +class TestTheBindingItself: + def test_filter_subjects_are_prefix_plus_declared(self) -> None: + assert _spec(subjects=("risk.>", "issue.created")).filter_subjects == (f"{PREFIX}risk.>", f"{PREFIX}issue.created") + + def test_the_consumer_carries_the_wire_values_verbatim(self) -> None: + """What the first consumer's own connection pool creates for the same input.""" + assert _spec().consumer_config() == js_api.ConsumerConfig( + name="acme-agent-risk", + durable_name="acme-agent-risk", + deliver_subject="acme.agent.A.risk", + deliver_group="risk", + filter_subjects=[f"{PREFIX}risk.>"], + ack_policy=js_api.AckPolicy.EXPLICIT, + ack_wait=600.0, + max_deliver=5, + deliver_policy=js_api.DeliverPolicy.NEW, + ) + + def test_the_agent_sees_its_own_subject(self) -> None: + spec = _spec() + assert spec.local_subject(f"{PREFIX}risk.created") == "risk.created" + assert spec.topic_for("risk.created") == "risk.>" + assert spec.topic_for("issue.created") is None + + @pytest.mark.parametrize("overrides", [{"subjects": ()}, {"ack_wait": 0}], ids=["no-subject", "no-ack-wait"]) + def test_an_unusable_binding_is_refused(self, overrides: dict) -> None: + with pytest.raises(ValueError): + _spec(**overrides) + + +class TestBinding: + async def test_an_unmanaged_binding_sends_no_jetstream_request( + self, nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock + ) -> None: + """The account may only be allowed to receive and acknowledge.""" + await _bound(nats_client, mock_nats_core, jsm, AsyncMock()) + mock_nats_core.jsm.assert_not_called() + mock_nats_core.subscribe.assert_awaited_once() + assert mock_nats_core.subscribe.await_args.args == ("acme.agent.A.risk",) + assert mock_nats_core.subscribe.await_args.kwargs["queue"] == "risk" + + async def test_a_managed_binding_creates_its_consumer(self, nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock) -> None: + await _bound(nats_client, mock_nats_core, jsm, AsyncMock(), manage_consumer=True) + jsm.stream_info.assert_awaited_once_with("NOTIFICATIONS_A") + jsm.add_consumer.assert_awaited_once_with("NOTIFICATIONS_A", config=_spec(manage_consumer=True).consumer_config()) + + async def test_a_consumer_that_cannot_be_updated_is_recreated( + self, nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock + ) -> None: + jsm.add_consumer.side_effect = [APIError(description="consumer already exists"), None] + await _bound(nats_client, mock_nats_core, jsm, AsyncMock(), manage_consumer=True) + jsm.delete_consumer.assert_awaited_once_with("NOTIFICATIONS_A", "acme-agent-risk") + assert jsm.add_consumer.await_count == 2 + + async def test_a_missing_stream_is_never_created(self, nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock) -> None: + jsm.stream_info.side_effect = NotFoundError() + with pytest.raises(JetStreamBindingError, match="NOTIFICATIONS_A"): + await _bound(nats_client, mock_nats_core, jsm, AsyncMock(), manage_consumer=True) + jsm.add_consumer.assert_not_awaited() + mock_nats_core.subscribe.assert_not_awaited() + + +class TestDelivery: + async def test_the_handler_sees_the_subject_without_the_prefix_and_it_is_acked( + self, nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock, cloud_event: CloudEvent + ) -> None: + """Settled although the agent's own nats_use_jetstream is off: a binding is always JetStream.""" + seen: list[str] = [] + + async def callback(event: CloudEvent, subject: str) -> None: + seen.append(subject) + + binding, handler = await _bound(nats_client, mock_nats_core, jsm, callback) + msg = _delivery(cloud_event) + await _settled(binding, handler, msg) + assert seen == ["risk.created"] + msg.ack.assert_awaited_once() + + async def test_a_delivery_no_subject_covers_is_termed_unprocessed( + self, nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock, cloud_event: CloudEvent + ) -> None: + callback = AsyncMock() + binding, handler = await _bound(nats_client, mock_nats_core, jsm, callback) + msg = _delivery(cloud_event, subject=f"{PREFIX}issue.created") + await _settled(binding, handler, msg) + callback.assert_not_awaited() + msg.term.assert_awaited_once() + + async def test_the_heartbeat_follows_the_bindings_ack_wait( + self, nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock, cloud_event: CloudEvent + ) -> None: + async def slow(event: CloudEvent, subject: str) -> None: + await asyncio.sleep(0.1) + + binding, handler = await _bound(nats_client, mock_nats_core, jsm, slow, ack_wait=0.03) + msg = _delivery(cloud_event) + await _settled(binding, handler, msg) + assert msg.in_progress.await_count >= 2 + + async def test_exhausted_without_a_dead_letter_subject_is_termed( + self, nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock, cloud_event: CloudEvent + ) -> None: + mock_nats_core.jetstream = MagicMock() + binding, handler = await _bound( + nats_client, mock_nats_core, jsm, AsyncMock(side_effect=RetryableHandlerError(status="failed", reason="not yet")), max_deliver=2 + ) + msg = _delivery(cloud_event, delivered=2) + await _settled(binding, handler, msg) + msg.term.assert_awaited_once() + msg.nak.assert_not_awaited() + mock_nats_core.jetstream.return_value.publish.assert_not_called() + + async def test_exhausted_with_a_dead_letter_subject_stays_on_its_connection( + self, nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock, cloud_event: CloudEvent + ) -> None: + js = MagicMock(publish=AsyncMock()) + mock_nats_core.jetstream = MagicMock(return_value=js) + binding, handler = await _bound( + nats_client, + mock_nats_core, + jsm, + AsyncMock(side_effect=RetryableHandlerError(status="failed", reason="not yet")), + max_deliver=2, + dead_letter_subject=f"{PREFIX}dead-letter", + ) + msg = _delivery(cloud_event, delivered=2) + await _settled(binding, handler, msg) + js.publish.assert_awaited_once() + assert js.publish.await_args.args[0] == f"{PREFIX}dead-letter" + msg.term.assert_awaited_once() + + async def test_below_the_limit_a_failure_is_nakd( + self, nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock, cloud_event: CloudEvent + ) -> None: + binding, handler = await _bound( + nats_client, mock_nats_core, jsm, AsyncMock(side_effect=RetryableHandlerError(status="failed", reason="not yet")), max_deliver=5 + ) + msg = _delivery(cloud_event, delivered=1) + await _settled(binding, handler, msg) + msg.nak.assert_awaited_once() From 45809536253cc7643c15a47c444527664c72c728 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 14 Oct 2026 15:25:32 +0200 Subject: [PATCH 074/133] feat(nats): named connections from a connection source Step 3a of the named-connections plan. A process-scope key, nats_connection_source, names a factory returning a ConnectionSource; AppBuilder loads it once per process and hands it to every agent's client. The source lists named connections and, per agent and connection, a JetStreamBinding; the subjects a connection serves leave the agent's default connection. Each named binding connects and binds in its own loop with its own link, retried and reconnected forever, independent of the others. A run from a named connection starts in an empty context, is checked by the source's validate hook before anything runs (a reason terms it), runs inside the source's run_scope, and knows its connection through the nats_connection context key. An agent with named connections may not map handler results to topics. Pause, resume and close cover every connection. Verified in WSL with restricted per-tenant accounts and a real group of three agents on two connections: no run saw another connection's tenant, a mismatched event never ran, deliveries resumed after a broker restart without any JetStream request, zero permission violations. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 1 + ...26-08-28-multi-agent-grouping-changelog.md | 45 +++ .../docs/reference/configuration-keys.md | 1 + src/blueprint/agents/app_builder.py | 16 +- .../agents/clients/io/nats_client.py | 291 ++++++++++++++++- .../agents/clients/io/nats_connections.py | 162 +++++++++- src/blueprint/agents/config/config.py | 1 + src/blueprint/agents/io/api/eventing/nats.py | 5 + .../agents/app_builder/test_app_builder.py | 44 +++ .../clients/io/test_nats_connection_source.py | 303 ++++++++++++++++++ 10 files changed, 847 insertions(+), 22 deletions(-) create mode 100644 tests/unit/agents/clients/io/test_nats_connection_source.py diff --git a/CHANGELOG.md b/CHANGELOG.md index a7fc75df..3c2329cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -164,6 +164,7 @@ ### Added +- **Named NATS connections (`nats_connection_source`).** A deployment can give its agents further NATS connections -- one account and one existing JetStream consumer each -- through a connection source named by a process-scope key. The framework binds to the deployment's consumers verbatim and never provisions on them, checks each delivery with the source's validation hook before it runs, runs it in an empty context inside the source's scope, and settles, heartbeats and dead-letters it on its own connection. Agents keep declaring their subjects as before and see them without the connection's prefix; `nats_connection` names the connection in the handler context. Unset, nothing changes. - **`nats_max_concurrent_runs`** (int, unset by default): how many deliveries an agent handles at once per process, shared by all of its subscriptions; unset keeps one run per subscription. With every slot taken the subscription stops taking messages; keep `nats_max_ack_pending` near replicas x this value. diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 7c589c00..5de49550 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8297,6 +8297,51 @@ Open for step 3: reconnect handling exists for the default link only (`_on_recon link needs its own. A plain subscription is restored by nats-py on reconnect; whether the push consumer delivers again without a JetStream request is to be shown against a broker restart. +### Named connections from a connection source (named connections, step 3a) + +Step 3a of `docs/plans/2026-10-14-named-connections.md` (decisions D1-D4, D8, D10). + +- `clients/io/nats_connections.py` gains the deployment-facing API: `ConnectionSpec` (name, URL, + credentials -- secrets kept out of `repr` -- and `connect_options()`), the `ConnectionSource` + protocol (`connections()`, `binding(agent, subjects, connection)`, `validate(connection, subject, + event)`, `run_scope(connection)`), `load_connection_source()` for the process-scope key + `nats_connection_source` (added to `PROCESS_SCOPE_KEYS`), and `current_connection()` / + `mark_connection()` over a ContextVar that is only ever set inside a run's own task. +- `AppBuilder.build` loads the source once per process (NATS only) and `_wire_transport` hands it to + every agent's client (`NATSClient.set_connection_source`) -- no global state; a wrong path fails + the build. +- `NATSClient.subscribe` asks the source per connection (`_plan_named_bindings`): each binding gets a + `_Link` of its own (D1) and its own run slots; the subjects it serves leave the default binding + (D10); a binding claiming an undeclared subject, or named connections together with + `event_publishing.topic_mapping` (D4, `_refuse_result_publishing`), fail startup. +- Each named binding connects and binds in a loop of its own (`_start_named_links`, + `_run_named_link`, `_open_named_link`): retried forever, reconnecting forever once open, one + failing never holding up another or the default connection. On reconnect nothing is re-bound: the + plain subscription is restored by nats-py and the push consumer delivers to it again. +- Pause drains every binding, resume restarts the named loops (re-binding over the open link), + `close` drains all, waits for every run within the one `event_client_drain_timeout`, then closes + every link. `inflight_handlers` counts every connection; `named_connections` lists them. +- A run from a named connection starts in an empty `contextvars.Context` (N1; the default + connection keeps its copied context, N6), marks its connection, is checked by `_accepted` + (validation hook: a reason terms it, an exception naks it) and runs inside `_run_scope` (the + source's sync or async context manager). `NatsEventing` adds `nats_connection` to the handler + context only when a run has one. + +Tests: `test_nats_connection_source.py` (22: loading the source, the spec, planning the bindings, +D4, scope and connection inside the run, an ambient ContextVar not inherited, two connections never +sharing a run context, rejection, a raising validator, the default connection unchanged, the +context key, shutdown of every link) and `TestConnectionSourceWiring` in `test_app_builder.py` (3). + +Acceptance in WSL against `nats:2.10-alpine` with three accounts -- a process account allowed +nothing, and per tenant an admin (provisioning, operator) and an agent user allowed only its deliver +subjects and `$JS.ACK.>` -- and a real group of three agents on two named connections, the source +binding them as the first consumer does and validating as W17.2 does: 32 of 32 runs, none whose +connection, scope tenant (also after awaiting) and event tenant disagreed; handlers saw +`risk.created` / `issue.created` and their declared topics; at most 2 runs per (agent, connection) +with `nats_max_concurrent_runs = 2`, 12 at once overall; every consumer acked, none redelivered; an +event in tenant A's stream claiming tenant B ran nowhere and was termed; after a broker restart all +named connections were back and delivering without a JetStream request; 0 permission violations. + --- ## Open points diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 48441533..e9bc6952 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -46,6 +46,7 @@ Settings for the event bus transport layer. | `nats_ack_wait` | `float` | unset -- the server's default (NATS: 30 s) | Seconds the broker waits for an acknowledgement before redelivering. **Must exceed the p99 duration of your slowest handler**, or long inference is redelivered to another replica while the first is still working. Handlers that call models usually need more than the NATS default, so set it. | | `nats_max_ack_pending` | `int` | unset -- the server's default (NATS: 1000) | Unacknowledged messages the consumer may have outstanding at once, counted across every replica sharing it. `-1` is unlimited. Keep it close to replicas x `nats_max_concurrent_runs`: whatever a pod receives beyond the runs it has started waits in the client's queue, unheartbeated, while its `nats_ack_wait` is already running down. | | `nats_max_concurrent_runs` | `int` | unset -- one run at a time per subscription, as before the key existed | Deliveries this agent handles at once, per process, shared by all of its subscriptions. Unset, each subscription runs one delivery at a time on its own, so an agent with two subscriptions runs two at once. An agent that spends its runs waiting on a model or an API gains the most from raising it; every run shares the process's one event loop, so CPU-heavy handlers gain little. Applies to Core NATS and JetStream alike. | +| `nats_connection_source` | `str` | unset -- the agent consumes on its one connection, as before | **Process scope.** `"package.module:attribute"` naming a factory that is called with the process `Config` and returns a `ConnectionSource` (`blueprint.agents.clients.io.nats_connections`). The source lists named connections -- each with its own URL and account -- and, per agent and connection, a `JetStreamBinding`: which declared subjects the connection serves, the subject prefix, and the deployment's durable consumer with its wire values verbatim. Those subjects leave the agent's default connection. Each delivery from a named connection is checked by the source's `validate` before anything runs (a reason terminates it), runs in an empty context inside the source's `run_scope`, and is settled on the connection it arrived on; the handler sees the subject without the prefix and the connection's name under the context key `nats_connection`. JetStream only. An agent with named connections may not map handler results to topics. A wrong path fails startup. | | `nats_heartbeat_enabled` | `bool` | `true` | Whether a running JetStream delivery reports `in_progress` every third of its consumer's `ack_wait`, so a run longer than `ack_wait` is not redelivered while it still runs. Switch it off only for an agent whose runs always finish well inside `ack_wait`; off, a long run is delivered again to another replica. Must be a boolean -- the string `"false"` is refused, because it would read as true. | | `nats_max_deliver` | `int` | unset -- the server's default (NATS: unlimited) | Delivery attempts before the message is dead-lettered. Unlimited -- the default, or `-1` -- means a permanently failing message is retried forever and never dead-lettered; the client logs a warning at startup if you set `-1` explicitly. Set a positive limit to bound retries. | | `nats_dead_letter_subject` | `str` | `".dead-letter"` | Subject a message is republished to when the framework gives up on it -- either a terminal failure (`InvalidEventError`, `CriticalHandlerError`, or a payload that is not a CloudEvent) or `nats_max_deliver` attempts spent. The original bytes are republished unchanged, with `Blueprint-Dead-Letter-Reason`, `Blueprint-Original-Subject`, `Blueprint-Delivery-Count` and `Blueprint-Event-Id` headers. Set to `""` to disable, which drops those messages and loses their payloads. Startup fails if the subject is a wildcard or is itself one of the subscribed subjects, since that would loop. | diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index 38c3860a..19ba8aa1 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -41,6 +41,7 @@ from .clients.io.dapr_client import DaprClient from .clients.io.io_client_base import TOPIC_TRANSPORTS from .clients.io.nats_client import NATSClient +from .clients.io.nats_connections import CONNECTION_SOURCE_KEY, ConnectionSource, load_connection_source from .services.service_base import ServiceBase from .services.eventing.event_processing_service import EventProcessingService from .services.eventing.event_publishing_service import EventPublishingService @@ -1003,8 +1004,12 @@ def build(self, config: Config | None = None) -> FastAPI: # is out of scope for this plan -- but which agents get a client, and which of them # get an endpoint, is decided per agent below. event_bus_type = str(resolved_config.get("event_bus", "") or "").strip().lower() + # One connection source per process, shared by every agent's client (named-connections plan, D2). + connection_source = ( + load_connection_source(resolved_config.get(CONNECTION_SOURCE_KEY), resolved_config) if event_bus_type == "nats" else None + ) for namespace in self.hosted_namespaces: - self._wire_transport(registry, namespace, event_bus_type) + self._wire_transport(registry, namespace, event_bus_type, connection_source) self._wire_dapr_endpoint(registry, event_bus_type) # 4. Create internal services (auto-register) @@ -1071,7 +1076,9 @@ def build(self, config: Config | None = None) -> FastAPI: self._build_rest_endpoints(app, registry) return app - def _wire_transport(self, registry: Registry, namespace: str, event_bus_type: str) -> None: + def _wire_transport( + self, registry: Registry, namespace: str, event_bus_type: str, connection_source: ConnectionSource | None = None + ) -> None: """Give ``namespace`` a transport client, and an endpoint if it consumes. Publishing and consuming are decided separately, per agent. An agent that only emits @@ -1091,6 +1098,7 @@ def _wire_transport(self, registry: Registry, namespace: str, event_bus_type: st registry: The application's registry, queried per namespace. namespace: The agent to wire. event_bus_type: The resolved ``event_bus`` value, shared by the whole process. + connection_source: The process's ``nats_connection_source``, if one is configured. Raises: ValueError: if this agent opted into publishing and there is no topic transport @@ -1119,7 +1127,9 @@ def _wire_transport(self, registry: Registry, namespace: str, event_bus_type: st # The client is per agent; the endpoint is not. See _wire_dapr_endpoint. DaprClient(namespace=namespace) # auto-registers elif event_bus_type == "nats": - NATSClient(namespace=namespace).set_fatal_handler(self._on_transport_fatal) # auto-registers + client = NATSClient(namespace=namespace) # auto-registers + client.set_fatal_handler(self._on_transport_fatal) + client.set_connection_source(connection_source) if consumes: self._eventing_components.append(NatsEventing(namespace=namespace)) elif event_bus_type == "sessions": diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 10685a78..252db012 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -2,12 +2,13 @@ import asyncio import contextlib +import contextvars import functools import importlib.util import json import logging import re -from collections.abc import Awaitable, Callable +from collections.abc import AsyncIterator, Awaitable, Callable from dataclasses import dataclass, field from functools import cached_property from pathlib import Path @@ -30,7 +31,7 @@ from ...models.events import CloudEvent from ..client_base import DeliveryCallback from .io_client_base import IOClientBase, subject_is_covered_by, validate_publish_subject, validate_subject_segment -from .nats_connections import JetStreamBinding +from .nats_connections import ConnectionSource, JetStreamBinding, mark_connection logger = logging.getLogger(__name__) @@ -309,6 +310,9 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: self._retry_task: asyncio.Task[None] | None = None self._max_concurrent_runs: int | None = None self._heartbeat_enabled: bool = True + self._source: ConnectionSource | None = None + self._named: list[_Binding] = [] + self._named_tasks: dict[str, asyncio.Task[None]] = {} # ------------------------------------------------------------------ # The default link and binding, under the names the client used before it had them @@ -447,8 +451,13 @@ def queue_group(self) -> str: @property def inflight_handlers(self) -> int: - """Number of message handlers currently executing.""" - return self._inflight + """Number of message handlers currently executing, on every connection of this agent.""" + return self._inflight + sum(binding.inflight for binding in self._named) + + @property + def named_connections(self) -> tuple[str, ...]: + """Names of the connections the source gave this agent a binding on, in the source's order.""" + return tuple(binding.link.name for binding in self._named) @property def consumer_tuning(self) -> ConsumerTuning | None: @@ -476,15 +485,17 @@ async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: after subscribing. The loop is started by :meth:`resume_consumption` instead, if the agent is ever released. """ - self._topic_callbacks = topic_callbacks self._queue_group = self._resolve_queue_group() self._max_concurrent_runs = self._resolve_max_concurrent_runs() # Unset keeps one run per subscription (subscription_slots); set, the subscriptions share K. self._binding.run_slots = asyncio.Semaphore(self._max_concurrent_runs) if self._max_concurrent_runs else None self._heartbeat_enabled = self._resolve_heartbeat_enabled() + # What a named connection serves leaves the default connection (plan D10). + default_topics = self._plan_named_bindings(topic_callbacks) + self._topic_callbacks = default_topics if self.config.get("nats_use_jetstream", False): - self._durables = self._resolve_durables(list(topic_callbacks)) - self._tuning = self._resolve_consumer_tuning(list(topic_callbacks)) + self._durables = self._resolve_durables(list(default_topics)) + self._tuning = self._resolve_consumer_tuning(list(default_topics)) self._subscriptions_managed = True self._subscriptions_ready = False if self._consumption_paused: @@ -495,6 +506,161 @@ async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: ) return self._start_retry_task() + self._start_named_links() + + def set_connection_source(self, source: ConnectionSource | None) -> None: + """Install the process's connection source, before ``subscribe()``; ``None`` keeps one connection (N6).""" + self._source = source + + def _plan_named_bindings(self, topic_callbacks: dict[str, DeliveryCallback]) -> dict[str, DeliveryCallback]: + """Ask the source which connections serve which of this agent's subjects; return what stays on the default one. + + Each binding gets a link of its own (plan D1) and its own run slots. A subject several + connections serve is consumed on each of them, from each connection's own consumer. + + Raises: + ValueError: a binding claims a subject this agent did not declare, or the agent both + has named connections and maps handler results to topics (plan D4). + """ + self._named = [] + if self._source is None: + return dict(topic_callbacks) + declared = tuple(topic_callbacks) + served: set[str] = set() + for spec in self._source.connections().values(): + jetstream = self._source.binding(self._queue_group, declared, spec) + if jetstream is None: + continue + unknown = [subject for subject in jetstream.subjects if subject not in topic_callbacks] + if unknown: + raise ValueError( + f"Agent '{self.namespace or ROOT_LABEL}': the binding for connection '{spec.name}' claims " + f"{', '.join(unknown)}, which the agent does not declare. A binding serves declared subjects only." + ) + binding = _Binding( + link=_Link(name=spec.name, url=spec.url, connect_options=spec.connect_options()), + jetstream=jetstream, + topic_callbacks={subject: topic_callbacks[subject] for subject in jetstream.subjects}, + ) + binding.run_slots = asyncio.Semaphore(self._max_concurrent_runs) if self._max_concurrent_runs else None + self._named.append(binding) + served.update(jetstream.subjects) + if self._named: + self._refuse_result_publishing() + logger.info( + "Agent '%s' consumes on %d named connection(s) %s; %d subject(s) stay on its default connection", + self.namespace or ROOT_LABEL, + len(self._named), + ", ".join(binding.link.name for binding in self._named) or "-", + len(declared) - len(served), + ) + return {topic: callback for topic, callback in topic_callbacks.items() if topic not in served} + + def _refuse_result_publishing(self) -> None: + """Fail startup when an agent with named connections maps handler results to topics (plan D4). + + A result would go out on the default connection, so what a run on one connection + produced would reach subjects outside that connection's account. + """ + mapping = self.config.get("event_publishing.topic_mapping", {}) or {} + if mapping: + raise ValueError( + f"Agent '{self.namespace or ROOT_LABEL}' consumes on named connections and maps handler results to " + "topics ('event_publishing.topic_mapping'). A result would leave the connection its event arrived on, " + "through the default connection, so this is refused. Remove the mapping." + ) + + def _start_named_links(self) -> None: + """Connect and bind every named connection in a loop of its own; one failing never holds up another.""" + for binding in self._named: + running = self._named_tasks.get(binding.link.name) + if running is not None and not running.done(): + continue + task = asyncio.ensure_future(self._run_named_link(binding)) + task.add_done_callback(functools.partial(self._on_named_link_done, binding)) + self._named_tasks[binding.link.name] = task + + async def _run_named_link(self, binding: _Binding) -> None: + """Connect ``binding``'s link and bind, retrying until it works. + + Never gives up: a named connection's stream or account may appear later (provisioning), and + unlike the default connection its absence does not make the agent unready (plan D5). + """ + delay = float(self.config.get("event_client_retry_delay", 5.0)) + attempt = 0 + while True: + try: + await self._open_named_link(binding.link) + if self._consumption_paused: + return + binding.subscriptions.clear() + await self._bind(binding) + binding.subscriptions_ready = True + return + except asyncio.CancelledError: + raise + except Exception as exc: + attempt += 1 + binding.subscriptions_ready = False + logger.warning( + "Agent '%s': named connection '%s' attempt %d failed, retrying in %.1fs: %s", + self.namespace or ROOT_LABEL, + binding.link.name, + attempt, + delay, + exc, + ) + await asyncio.sleep(delay) + + def _on_named_link_done(self, binding: _Binding, task: asyncio.Task[None]) -> None: + """Report a named-connection loop that died of anything but its cancellation, naming agent and connection.""" + if not task.cancelled() and task.exception() is not None: + logger.error( + "Agent '%s': the loop of named connection '%s' failed: %s", + self.namespace or ROOT_LABEL, + binding.link.name, + task.exception(), + exc_info=task.exception(), + ) + + async def _open_named_link(self, link: _Link) -> None: + """Open a named link, reconnecting forever once open, as the deployment's own pool did.""" + if link.nats_client is not None and not link.nats_client.is_closed: + return + base = self._resolve_connection_name() + link.connection_name = ".".join(part for part in (base, link.name) if part) + agent = self.namespace or ROOT_LABEL + + async def on_disconnected() -> None: + for binding in self._named: + if binding.link is link: + binding.subscriptions_ready = False + logger.warning("Agent '%s': named connection '%s' lost its broker", agent, link.name) + + async def on_reconnected() -> None: + # A plain subscription is restored by nats-py itself, and a push consumer delivers to + # it again as soon as there is interest: nothing to re-bind, no JetStream request. + for binding in self._named: + if binding.link is link and not self._consumption_paused: + binding.subscriptions_ready = True + logger.info("Agent '%s': named connection '%s' is back", agent, link.name) + + async def on_error(error: Exception) -> None: + # Permission violations land here: a subject the deployment did not grant this account. + logger.error("Agent '%s': error on named connection '%s': %s", agent, link.name, error) + + link.nats_client = await nats.connect( + link.url, + name=link.connection_name or None, + max_reconnect_attempts=-1, + reconnect_time_wait=self.config.get("nats_reconnect_time_wait", 2), + connect_timeout=10, + disconnected_cb=on_disconnected, + reconnected_cb=on_reconnected, + error_cb=on_error, + **link.connect_options, + ) + logger.info("Agent '%s' connected named connection '%s' as '%s'", agent, link.name, link.connection_name) def _start_retry_task(self) -> None: """Start the background connect-and-subscribe loop, unless one is already running.""" @@ -1133,10 +1299,16 @@ async def pause_consumption(self) -> None: return self._consumption_paused = True self._subscriptions_ready = False + timeout = float(self.config.get("event_client_drain_timeout", 30.0)) + deadline = asyncio.get_running_loop().time() + timeout + for binding in self._named: + binding.subscriptions_ready = False + await self._drain_subscriptions(deadline, binding) if self._nats_client is not None: - timeout = float(self.config.get("event_client_drain_timeout", 30.0)) - deadline = asyncio.get_running_loop().time() + timeout await self._drain_subscriptions(deadline) + for binding in self._named: + await self._await_inflight(deadline, binding) + if self._nats_client is not None: await self._await_inflight(deadline) logger.error( "Agent '%s' stopped consuming: its subscriptions are drained while it is degraded, so its events " @@ -1156,6 +1328,8 @@ async def resume_consumption(self) -> None: self._consumption_paused = False if not self._subscriptions_managed: return + # Each named connection re-binds in its own loop, over its still-open link. + self._start_named_links() if self._nats_client is None: # Paused before it ever connected -- subscribe() registered the topics and waited. # The retry loop is what connects and subscribes; a loop still running picks up the @@ -1187,13 +1361,34 @@ async def close(self) -> None: self._retry_task.cancel() with contextlib.suppress(asyncio.CancelledError): await self._retry_task - + for task in list(self._named_tasks.values()): + if not task.done(): + task.cancel() + with contextlib.suppress(asyncio.CancelledError, Exception): + await task + self._named_tasks.clear() + + # One budget for every connection: stop all deliveries, then wait for every run, then close. + timeout = float(self.config.get("event_client_drain_timeout", 30.0)) + deadline = asyncio.get_running_loop().time() + timeout + for binding in self._named: + binding.subscriptions_ready = False + if binding.link.nats_client is not None: + await self._drain_subscriptions(deadline, binding) if self._nats_client is not None: - timeout = float(self.config.get("event_client_drain_timeout", 30.0)) - deadline = asyncio.get_running_loop().time() + timeout await self._drain_subscriptions(deadline) + for binding in self._named: + await self._await_inflight(deadline, binding) + if self._nats_client is not None: await self._await_inflight(deadline) + for binding in self._named: + client = binding.link.nats_client + if client is not None: + with contextlib.suppress(Exception): + await client.close() + binding.link.nats_client = None + if self._nats_client is not None: await self._nats_client.close() self._nats_client = None self._js = None @@ -1712,7 +1907,15 @@ async def message_handler(msg: Any) -> None: await slots.acquire() binding.enter_run() dispatch = callback if callback is not None else binding.topic_callbacks[resolved] - run = asyncio.create_task(self._run_delivery(msg, resolved, dispatch, binding), name=f"nats-run-{self.namespace or ROOT_LABEL}") + # A run from a named connection starts in an empty context: nothing of the subscription + # task or of another run reaches it (plan N1). The default connection keeps the copied + # context it always had (N6). + context = contextvars.Context() if binding.link.name else None + run = asyncio.create_task( + self._run_delivery(msg, resolved, dispatch, binding), + name=f"nats-run-{self.namespace or ROOT_LABEL}{'-' + binding.link.name if binding.link.name else ''}", + context=context, + ) binding.runs.add(run) run.add_done_callback(functools.partial(self._run_finished, binding, slots)) @@ -1752,11 +1955,18 @@ async def _run_delivery(self, msg: Any, topic: str, callback: DeliveryCallback, await self._settle(msg, DeliveryDisposition.TERM, topic, None, binding) return + connection = binding.link.name + if connection and self._source is not None: + mark_connection(connection) + if not await self._accepted(msg, topic, cloud_event, binding): + return + heartbeat = self._start_heartbeat(msg, topic, binding) disposition = DeliveryDisposition.ACK try: subject = binding.jetstream.local_subject(msg.subject) if binding.jetstream is not None else msg.subject - await callback(cloud_event, subject) + async with self._run_scope(connection): + await callback(cloud_event, subject) except Exception as ex: disposition = disposition_for(ex) logger.error( @@ -1775,6 +1985,59 @@ async def _run_delivery(self, msg: Any, topic: str, callback: DeliveryCallback, await heartbeat await self._settle(msg, disposition, topic, cloud_event.id, binding) + async def _accepted(self, msg: Any, topic: str, cloud_event: CloudEvent[Any], binding: _Binding) -> bool: + """Ask the source whether a named-connection delivery may run (plan N2); settle it if not. + + A reason terminates the delivery -- never processed, never retried. A hook that raises + is a fault of the deployment's code, not of the event: the delivery is left for + redelivery (nak) rather than lost. + """ + source = self._source + if source is None: + return True + connection = binding.link.name + try: + reason = source.validate(connection, msg.subject, cloud_event) + except Exception as exc: + logger.error( + "Agent '%s': validating event %s on '%s' from connection '%s' raised; left for redelivery: %s", + self.namespace or ROOT_LABEL, + cloud_event.id, + msg.subject, + connection, + exc, + exc_info=True, + ) + await self._settle(msg, DeliveryDisposition.NAK, topic, cloud_event.id, binding) + return False + if reason is None: + return True + logger.error( + "Agent '%s': rejecting event %s (type %s) on '%s' from connection '%s': %s", + self.namespace or ROOT_LABEL, + cloud_event.id, + cloud_event.type, + msg.subject, + connection, + reason, + ) + await self._settle(msg, DeliveryDisposition.TERM, topic, cloud_event.id, binding) + return False + + @contextlib.asynccontextmanager + async def _run_scope(self, connection: str) -> AsyncIterator[None]: + """Enter the source's scope for ``connection`` around a run (plan D3); nothing for the default connection.""" + if not connection or self._source is None: + yield + return + scope = self._source.run_scope(connection) + if isinstance(scope, contextlib.AbstractAsyncContextManager): + async with scope: + yield + else: + with scope: + yield + def _run_finished(self, binding: _Binding, slots: asyncio.Semaphore, run: asyncio.Task[None]) -> None: """Free the run's slot and count it out of the in-flight runs shutdown waits for.""" binding.runs.discard(run) diff --git a/src/blueprint/agents/clients/io/nats_connections.py b/src/blueprint/agents/clients/io/nats_connections.py index 0081e64d..9046b09c 100644 --- a/src/blueprint/agents/clients/io/nats_connections.py +++ b/src/blueprint/agents/clients/io/nats_connections.py @@ -1,17 +1,131 @@ -"""What a deployment tells the framework about a connection it supplies (named-connections plan). +"""What a deployment tells the framework about the connections it supplies (named-connections plan). -The framework does not know what a named connection stands for. It receives, per agent and -connection, a :class:`JetStreamBinding`: which of the agent's declared subjects the connection -serves, the prefix that turns a declared subject into the subject on the wire, and the durable -consumer that carries them -- every wire value verbatim, never derived (N4). +The framework does not know what a named connection stands for. A deployment names a +:class:`ConnectionSource` factory in the process-scope key ``nats_connection_source``; the source +lists :class:`ConnectionSpec` s and answers, per agent and connection, with a +:class:`JetStreamBinding` -- which of the agent's declared subjects the connection serves, the +prefix that turns a declared subject into the subject on the wire, and the durable consumer that +carries them, every wire value verbatim (N4). Before a delivery runs, the source may reject it +(:meth:`ConnectionSource.validate`, N2), and it may wrap every run in a scope of its own +(:meth:`ConnectionSource.run_scope`, D3). + +Agents never see any of this. A handler learns at most an opaque connection name, from the +``nats_connection`` context key. """ +import importlib +from collections.abc import Mapping +from contextlib import AbstractAsyncContextManager, AbstractContextManager +from contextvars import ContextVar from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable from nats.js import api as js_api from .io_client_base import subject_is_covered_by +if TYPE_CHECKING: + from ...models.events import CloudEvent + + +CONNECTION_SOURCE_KEY = "nats_connection_source" +"""Process-scope key naming the factory, ``"package.module:attribute"``; unset, nothing changes (N6).""" + +NATS_CONNECTION_CONTEXT_KEY = "nats_connection" +"""Handler context key holding the name of the named connection a delivery arrived on.""" + +_CURRENT_CONNECTION: ContextVar[str | None] = ContextVar("blueprint_nats_connection", default=None) +"""Set inside a run that started from a named connection, and only there: each such run starts in an +empty context, so the value can never be another run's.""" + + +def current_connection() -> str | None: + """The named connection the current run's delivery arrived on; ``None`` outside such a run.""" + return _CURRENT_CONNECTION.get() + + +@dataclass(frozen=True) +class ConnectionSpec: + """One connection a deployment supplies: a name and how to log in. Secrets are never logged.""" + + name: str + """Opaque to the framework; shows in logs, task names and the ``nats_connection`` context key.""" + url: str + user: str | None = None + password: str | None = field(default=None, repr=False) + token: str | None = field(default=None, repr=False) + creds_file: str | None = None + nkey_seed: str | None = field(default=None, repr=False) + inbox_prefix: str | None = None + tls: Any = field(default=None, repr=False) + """An ``ssl.SSLContext`` for ``tls://`` brokers with a private CA; ``None`` uses the default.""" + + def __post_init__(self) -> None: + if not self.name or any(char.isspace() for char in self.name): + raise ValueError(f"A connection name must be non-empty and contain no whitespace, got {self.name!r}.") + if not self.url.startswith(("nats://", "tls://")): + raise ValueError(f"Connection '{self.name}': url must be a nats:// or tls:// URL.") + if bool(self.user) != bool(self.password): + raise ValueError(f"Connection '{self.name}': user and password go together.") + + def connect_options(self) -> dict[str, Any]: + """The credential and inbox arguments for ``nats.connect()``.""" + options: dict[str, Any] = {} + if self.user: + options.update(user=self.user, password=self.password) + if self.token: + options["token"] = self.token + if self.creds_file: + options["user_credentials"] = self.creds_file + if self.nkey_seed: + options["nkeys_seed_str"] = self.nkey_seed + if self.inbox_prefix: + options["inbox_prefix"] = self.inbox_prefix + if self.tls is not None: + options["tls"] = self.tls + return options + + +@runtime_checkable +class ConnectionSource(Protocol): + """What a deployment implements to supply named connections. Built once per process. + + The factory named by ``nats_connection_source`` is called with the process ``Config`` and + returns the source. Every agent of the process shares it, so it must hold no per-run state. + """ + + def connections(self) -> Mapping[str, ConnectionSpec]: + """The connections to open, by name. Read at startup.""" + ... + + def binding(self, agent: str, subjects: tuple[str, ...], connection: ConnectionSpec) -> "JetStreamBinding | None": + """How ``agent`` consumes over ``connection``, or ``None`` if the connection serves none of its subjects. + + Args: + agent: The agent's name (its namespace, or the queue group of a standalone agent). + subjects: Every subject the agent declared, as it declared them. The binding's + ``subjects`` must be a subset; the rest stay on the agent's default connection. + connection: The connection, as :meth:`connections` returned it. + """ + ... + + def validate(self, connection: str, subject: str, event: "CloudEvent[Any]") -> str | None: + """Why a delivery must not run, or ``None`` to let it run (N2). + + Called before any handler sees the delivery, with the subject as it arrived on the wire. + A reason terminates the delivery: logged, never processed, never retried. + """ + ... + + def run_scope(self, connection: str) -> AbstractContextManager[Any] | AbstractAsyncContextManager[Any]: + """A context the framework enters inside each run from ``connection``, around the handler chain (D3). + + Entered in the run's own task, which started from an empty context, so whatever it sets + in ContextVars is visible to this run and no other. A synchronous or an asynchronous context + manager; a source with nothing to enter returns ``contextlib.nullcontext()``. + """ + ... + @dataclass(frozen=True) class JetStreamBinding: @@ -79,3 +193,41 @@ def local_subject(self, wire_subject: str) -> str: def topic_for(self, local_subject: str) -> str | None: """The declared subject that covers ``local_subject``, first in declaration order, or ``None``.""" return next((subject for subject in self.subjects if subject_is_covered_by(local_subject, subject)), None) + + +def mark_connection(name: str) -> None: + """Record ``name`` as the current run's connection. Called by the client inside a run's own task only.""" + _CURRENT_CONNECTION.set(name) + + +def load_connection_source(path: object, config: Any) -> ConnectionSource | None: + """Import and call the factory named by ``nats_connection_source``; ``None`` when the key is unset. + + Resolved once per process, when the application is built, so a wrong path fails startup + rather than the first delivery. + + Raises: + ValueError: the value is not ``"package.module:attribute"``, the module cannot be + imported, the attribute is missing or not callable, or what it returns is not a + :class:`ConnectionSource`. The message names the key and the value. + """ + text = str(path or "").strip() + if not text: + return None + module_path, _, attribute = text.partition(":") + if not module_path or not attribute: + raise ValueError(f"'{CONNECTION_SOURCE_KEY}' is {text!r}; write it as 'package.module:attribute', naming the factory.") + try: + module = importlib.import_module(module_path) + except Exception as exc: + raise ValueError(f"'{CONNECTION_SOURCE_KEY}': importing '{module_path}' raised {type(exc).__name__}: {exc}") from exc + factory = getattr(module, attribute, None) + if not callable(factory): + raise ValueError(f"'{CONNECTION_SOURCE_KEY}': '{module_path}' has no callable '{attribute}'.") + source = factory(config) + if not isinstance(source, ConnectionSource): + raise ValueError( + f"'{CONNECTION_SOURCE_KEY}': '{text}' returned a {type(source).__name__}, which is not a ConnectionSource " + "(connections, binding, validate, run_scope)." + ) + return source diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index d5d41719..f8c31ef7 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -78,6 +78,7 @@ class ConfigError(Exception): "readiness_policy", "dot_placeholder", "nats_stream_name", + "nats_connection_source", } ) """Keys that describe the *process*, and that an agent's own settings file therefore cannot set. diff --git a/src/blueprint/agents/io/api/eventing/nats.py b/src/blueprint/agents/io/api/eventing/nats.py index d2983938..586e4fa8 100644 --- a/src/blueprint/agents/io/api/eventing/nats.py +++ b/src/blueprint/agents/io/api/eventing/nats.py @@ -5,6 +5,7 @@ from ....clients.client_base import DeliveryCallback from ....clients.io.nats_client import NATSClient +from ....clients.io.nats_connections import NATS_CONNECTION_CONTEXT_KEY, current_connection from ....component.namespace import ROOT_NAMESPACE from ....models.events import CloudEvent from ..rest_api_base import RestApiBase @@ -119,6 +120,10 @@ def _make_event_callback(self, topic: str) -> DeliveryCallback: async def _process_event(event: CloudEvent[Any], subject: str) -> None: context = {"nats_topic": topic, NATS_SUBJECT_CONTEXT_KEY: subject} + connection = current_connection() + if connection is not None: + # Only a run from a named connection has one; the default connection adds no key (N6). + context[NATS_CONNECTION_CONTEXT_KEY] = connection processing_result = await self._process_cloud_event(event, context, topic) logger.debug( "Processed CloudEvent %s on topic %s with status %s", diff --git a/tests/unit/agents/app_builder/test_app_builder.py b/tests/unit/agents/app_builder/test_app_builder.py index 9a297687..d12b59f4 100644 --- a/tests/unit/agents/app_builder/test_app_builder.py +++ b/tests/unit/agents/app_builder/test_app_builder.py @@ -771,3 +771,47 @@ def test_consuming_still_publishes_without_the_opt_in( all_build_mocks.nats_eventing.assert_called_once() all_build_mocks.eps.assert_called_once() all_build_mocks.epubs.assert_called_once() + + +class TestConnectionSourceWiring: + """Named-connections plan D2: one source per process, handed to every agent's NATS client.""" + + @staticmethod + def _config(build_config: MagicMock, source_path: str | None) -> None: + values = {"event_bus": "nats", "nats_connection_source": source_path} + build_config.get.side_effect = lambda key, default="": values.get(key, default) if values.get(key) is not None else default + + def test_the_source_reaches_the_client( + self, builder_for_build: AppBuilder, mock_registry: MagicMock, all_build_mocks: types.SimpleNamespace, build_config: MagicMock + ) -> None: + from tests.unit.agents.clients.io.test_nats_connection_source import FakeSource + + wire_empty_registry(mock_registry) + mock_registry.get_event_handler.return_value = [MagicMock()] + self._config(build_config, "tests.unit.agents.clients.io.test_nats_connection_source:make_source") + + builder_for_build.build() + + (source,) = all_build_mocks.nats_client.return_value.set_connection_source.call_args.args + assert isinstance(source, FakeSource) + + def test_without_the_key_the_client_gets_none( + self, builder_for_build: AppBuilder, mock_registry: MagicMock, all_build_mocks: types.SimpleNamespace, build_config: MagicMock + ) -> None: + wire_empty_registry(mock_registry) + mock_registry.get_event_handler.return_value = [MagicMock()] + self._config(build_config, None) + + builder_for_build.build() + + all_build_mocks.nats_client.return_value.set_connection_source.assert_called_once_with(None) + + def test_a_wrong_path_fails_the_build( + self, builder_for_build: AppBuilder, mock_registry: MagicMock, all_build_mocks: types.SimpleNamespace, build_config: MagicMock + ) -> None: + wire_empty_registry(mock_registry) + mock_registry.get_event_handler.return_value = [MagicMock()] + self._config(build_config, "no.such.module:factory") + + with pytest.raises(ValueError, match="nats_connection_source"): + builder_for_build.build() diff --git a/tests/unit/agents/clients/io/test_nats_connection_source.py b/tests/unit/agents/clients/io/test_nats_connection_source.py new file mode 100644 index 00000000..923f1526 --- /dev/null +++ b/tests/unit/agents/clients/io/test_nats_connection_source.py @@ -0,0 +1,303 @@ +"""Named connections from a connection source (named-connections plan, step 3a).""" + +import asyncio +import contextvars +import json +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from nats.js import api as js_api + +from blueprint.agents.clients.io.nats_client import NATSClient +from blueprint.agents.clients.io.nats_connections import ( + ConnectionSpec, + JetStreamBinding, + current_connection, + load_connection_source, + mark_connection, +) +from blueprint.agents.io.api.eventing.nats import NatsEventing +from blueprint.agents.models.events import CloudEvent + +SCOPED: contextvars.ContextVar[str | None] = contextvars.ContextVar("test_scoped", default=None) +AMBIENT: contextvars.ContextVar[str | None] = contextvars.ContextVar("test_ambient", default=None) + + +def _binding(prefix: str, *subjects: str) -> JetStreamBinding: + return JetStreamBinding( + subjects=subjects, + stream=f"S_{prefix}", + durable=f"d-{prefix}", + deliver_subject=f"deliver.{prefix}", + deliver_group="g", + ack_wait=600.0, + subject_prefix=f"t.{prefix}.", + max_deliver=5, + deliver_policy=js_api.DeliverPolicy.NEW, + ) + + +class FakeSource: + """A deployment's source: two connections, and a scope that sets a ContextVar per connection.""" + + def __init__(self, bindings: dict[str, JetStreamBinding | None], reject: Any = None) -> None: + self.bindings = bindings + self.reject = reject + self.asked: list[tuple[str, tuple[str, ...], str]] = [] + + def connections(self) -> dict[str, ConnectionSpec]: + return {name: ConnectionSpec(name=name, url="nats://localhost:4222") for name in self.bindings} + + def binding(self, agent: str, subjects: tuple[str, ...], connection: ConnectionSpec) -> JetStreamBinding | None: + self.asked.append((agent, subjects, connection.name)) + return self.bindings[connection.name] + + def validate(self, connection: str, subject: str, event: CloudEvent[Any]) -> str | None: + return self.reject(connection, subject, event) if self.reject else None + + def run_scope(self, connection: str) -> Any: + @contextmanager + def scope() -> Iterator[None]: + token = SCOPED.set(connection) + try: + yield + finally: + SCOPED.reset(token) + + return scope() + + +def make_source(config: Any) -> FakeSource: + """Factory for load_connection_source, as a deployment would write one.""" + return FakeSource({"A": _binding("A", "risk.>")}) + + +def not_a_source(config: Any) -> object: + return object() + + +async def _subscribed(nats_client: NATSClient, source: FakeSource, topics: tuple[str, ...]) -> dict[str, AsyncMock]: + """subscribe() with the source, without starting any connection loop.""" + nats_client.set_connection_source(source) + callbacks = {topic: AsyncMock() for topic in topics} + with patch.object(nats_client, "_start_retry_task"), patch.object(nats_client, "_start_named_links"): + await nats_client.subscribe(callbacks) + return callbacks + + +def _delivery(cloud_event: CloudEvent, subject: str) -> MagicMock: + msg = MagicMock(data=json.dumps(dict(cloud_event)).encode(), reply="$JS.ACK.x", subject=subject) + for name in ("ack", "nak", "term", "in_progress"): + setattr(msg, name, AsyncMock()) + msg.metadata.num_delivered = 1 + return msg + + +async def _bound_handler(nats_client: NATSClient, mock_nats_core: MagicMock, name: str) -> tuple[Any, Any]: + """Bind the named binding ``name`` on a mocked link and return it with its broker callback.""" + binding = next(binding for binding in nats_client._named if binding.link.name == name) + core = MagicMock( + subscribe=AsyncMock(return_value=MagicMock(drain=AsyncMock(), unsubscribe=AsyncMock())), close=AsyncMock(), is_closed=False + ) + binding.link.nats_client = core + await nats_client._bind(binding) + return binding, core.subscribe.await_args.kwargs["cb"] + + +async def _deliver(binding: Any, handler: Any, msg: MagicMock) -> None: + await handler(msg) + await asyncio.gather(*list(binding.runs), return_exceptions=True) + + +class TestLoadingTheSource: + def test_unset_is_no_source(self) -> None: + assert load_connection_source(None, MagicMock()) is None + assert load_connection_source(" ", MagicMock()) is None + + def test_the_factory_is_called_with_the_config(self) -> None: + source = load_connection_source(f"{__name__}:make_source", MagicMock()) + assert isinstance(source, FakeSource) + + @pytest.mark.parametrize( + "path", + ["no_colon_here", "no.such.module:factory", f"{__name__}:missing", f"{__name__}:not_a_source"], + ids=["format", "import", "attribute", "not-a-source"], + ) + def test_a_wrong_path_fails_naming_the_key(self, path: str) -> None: + with pytest.raises(ValueError, match="nats_connection_source"): + load_connection_source(path, MagicMock()) + + +class TestConnectionSpec: + def test_secrets_stay_out_of_its_repr(self) -> None: + spec = ConnectionSpec(name="A", url="nats://h:4222", user="u", password="PLACEHOLDER") + assert "PLACEHOLDER" not in repr(spec) + assert spec.connect_options() == {"user": "u", "password": "PLACEHOLDER"} + + @pytest.mark.parametrize( + "kwargs", + [{"name": ""}, {"name": "a b"}, {"url": "http://h"}, {"user": "u"}], + ids=["empty-name", "space-in-name", "not-nats", "user-without-password"], + ) + def test_an_unusable_spec_is_refused(self, kwargs: dict) -> None: + with pytest.raises(ValueError): + ConnectionSpec(**{"name": "A", "url": "nats://h:4222", **kwargs}) + + +class TestPlanningTheBindings: + async def test_served_subjects_leave_the_default_connection(self, nats_client: NATSClient) -> None: + source = FakeSource({"A": _binding("A", "risk.>", "issue.>"), "B": _binding("B", "risk.>"), "C": None}) + await _subscribed(nats_client, source, ("risk.>", "issue.>", "scheduler.tick")) + + assert nats_client.named_connections == ("A", "B") + assert list(nats_client._topic_callbacks) == ["scheduler.tick"] + assert source.asked == [("test-agent", ("risk.>", "issue.>", "scheduler.tick"), name) for name in ("A", "B", "C")] + + async def test_a_binding_may_not_claim_an_undeclared_subject(self, nats_client: NATSClient) -> None: + with pytest.raises(ValueError, match="does not declare"): + await _subscribed(nats_client, FakeSource({"A": _binding("A", "invented.>")}), ("risk.>",)) + + async def test_without_a_source_nothing_changes(self, nats_client: NATSClient) -> None: + with patch.object(nats_client, "_start_retry_task"), patch.object(nats_client, "_start_named_links"): + await nats_client.subscribe({"risk.>": AsyncMock()}) + assert nats_client.named_connections == () + assert list(nats_client._topic_callbacks) == ["risk.>"] + + async def test_result_publishing_is_refused_with_named_connections(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """Plan D4: a result would leave the connection its event arrived on.""" + base = mock_config.get.side_effect + mock_config.get.side_effect = lambda key, default=None: ( + {"x.done": {"topic": "out.done"}} if key == "event_publishing.topic_mapping" else base(key, default) + ) + with pytest.raises(ValueError, match="topic_mapping"): + await _subscribed(nats_client, FakeSource({"A": _binding("A", "risk.>")}), ("risk.>",)) + + +class TestARunFromANamedConnection: + async def test_it_runs_in_the_sources_scope_and_knows_its_connection( + self, nats_client: NATSClient, mock_nats_core: MagicMock, cloud_event: CloudEvent + ) -> None: + seen: dict[str, Any] = {} + + async def callback(event: CloudEvent, subject: str) -> None: + seen.update(scoped=SCOPED.get(), connection=current_connection(), ambient=AMBIENT.get(), subject=subject) + + source = FakeSource({"A": _binding("A", "risk.>")}) + await _subscribed(nats_client, source, ("risk.>",)) + nats_client._named[0].topic_callbacks["risk.>"] = callback + binding, handler = await _bound_handler(nats_client, mock_nats_core, "A") + + AMBIENT.set("leaked") # set in the context the delivery arrives from + msg = _delivery(cloud_event, "t.A.risk.created") + await _deliver(binding, handler, msg) + + assert seen == {"scoped": "A", "connection": "A", "ambient": None, "subject": "risk.created"} + assert SCOPED.get() is None, "the scope does not outlive the run" + msg.ack.assert_awaited_once() + + async def test_a_rejected_delivery_is_termed_and_never_runs( + self, nats_client: NATSClient, mock_nats_core: MagicMock, cloud_event: CloudEvent + ) -> None: + source = FakeSource({"A": _binding("A", "risk.>")}, reject=lambda connection, subject, event: "tenant mismatch") + callbacks = await _subscribed(nats_client, source, ("risk.>",)) + binding, handler = await _bound_handler(nats_client, mock_nats_core, "A") + msg = _delivery(cloud_event, "t.A.risk.created") + await _deliver(binding, handler, msg) + callbacks["risk.>"].assert_not_awaited() + msg.term.assert_awaited_once() + msg.ack.assert_not_awaited() + + async def test_a_validator_that_raises_leaves_the_delivery_for_redelivery( + self, nats_client: NATSClient, mock_nats_core: MagicMock, cloud_event: CloudEvent + ) -> None: + def broken(connection: str, subject: str, event: CloudEvent) -> str | None: + raise RuntimeError("bug in the deployment's hook") + + callbacks = await _subscribed(nats_client, FakeSource({"A": _binding("A", "risk.>")}, reject=broken), ("risk.>",)) + binding, handler = await _bound_handler(nats_client, mock_nats_core, "A") + msg = _delivery(cloud_event, "t.A.risk.created") + await _deliver(binding, handler, msg) + callbacks["risk.>"].assert_not_awaited() + msg.nak.assert_awaited_once() + + async def test_two_connections_never_share_a_run_context( + self, nats_client: NATSClient, mock_nats_core: MagicMock, cloud_event: CloudEvent + ) -> None: + seen: list[tuple[str | None, str | None]] = [] + gate = asyncio.Event() + + async def callback(event: CloudEvent, subject: str) -> None: + await gate.wait() # both runs are in flight at once + seen.append((SCOPED.get(), current_connection())) + + await _subscribed(nats_client, FakeSource({"A": _binding("A", "risk.>"), "B": _binding("B", "risk.>")}), ("risk.>",)) + for binding in nats_client._named: + binding.topic_callbacks["risk.>"] = callback + a, handler_a = await _bound_handler(nats_client, mock_nats_core, "A") + b, handler_b = await _bound_handler(nats_client, mock_nats_core, "B") + await handler_a(_delivery(cloud_event, "t.A.risk.created")) + await handler_b(_delivery(cloud_event, "t.B.risk.created")) + await asyncio.sleep(0) + gate.set() + await asyncio.gather(*list(a.runs), *list(b.runs)) + assert sorted(seen) == [("A", "A"), ("B", "B")] + + async def test_the_default_connection_keeps_its_inherited_context( + self, nats_client: NATSClient, mock_nats_core: MagicMock, cloud_event: CloudEvent + ) -> None: + """N6: a run on the default connection is started exactly as before.""" + seen: dict[str, Any] = {} + + async def callback(event: CloudEvent, subject: str) -> None: + seen.update(ambient=AMBIENT.get(), connection=current_connection()) + + nats_client._nats_client = mock_nats_core + nats_client._client = mock_nats_core + await nats_client._subscribe_one("risk.>", callback) + handler = mock_nats_core.subscribe.await_args.kwargs["cb"] + AMBIENT.set("inherited") + await handler(_delivery(cloud_event, "risk.created")) + await asyncio.gather(*list(nats_client._runs)) + assert seen == {"ambient": "inherited", "connection": None} + + +class TestTheHandlerContext: + async def test_the_connection_reaches_the_handler_context_only_from_a_named_one(self) -> None: + eventing = NatsEventing.__new__(NatsEventing) + captured: list[dict] = [] + + async def process(event: Any, context: dict, topic: str) -> Any: + captured.append(dict(context)) + return MagicMock() + + eventing._process_cloud_event = process # type: ignore[method-assign] + callback = eventing._make_event_callback("risk.>") + event = MagicMock() + + await callback(event, "risk.created") + + async def from_named() -> None: + mark_connection("A") + await callback(event, "risk.created") + + await asyncio.create_task(from_named(), context=contextvars.Context()) + assert "nats_connection" not in captured[0] + assert captured[1]["nats_connection"] == "A" + assert captured[1]["nats_topic"] == "risk.>" + + +class TestShutdown: + async def test_close_drains_and_closes_every_named_link(self, nats_client: NATSClient, mock_nats_core: MagicMock) -> None: + await _subscribed(nats_client, FakeSource({"A": _binding("A", "risk.>"), "B": _binding("B", "risk.>")}), ("risk.>",)) + links = [] + for name in ("A", "B"): + binding, _ = await _bound_handler(nats_client, mock_nats_core, name) + links.append((binding, binding.link.nats_client, binding.subscriptions[0])) + await nats_client.close() + for binding, client, sub in links: + sub.drain.assert_awaited_once() + client.close.assert_awaited_once() + assert binding.link.nats_client is None From 567d1f589b53e2cf247e61c8f17ab8c43697db09 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 14 Oct 2026 15:41:29 +0200 Subject: [PATCH 075/133] feat(nats): a guaranteed run per (agent, connection), a process pool for the rest Step 3b of the named-connections plan (D7). Event rates differ by orders of magnitude between agents, so every (agent, connection) pair may always start one run, and every further run needs both its pair below nats_max_concurrent_runs and a slot of the process-wide pool nats_extra_runs_per_process. Both take a number or a percentage of the pairs the process consumes on, resolved at every request; waiters are served in arrival order. Unset K keeps one run per subscription. Verified in WSL with six pairs, K = 3 and a pool of 2: every pair's first run started at once, at most 8 runs overall (six guaranteed plus two). Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 6 +- ...26-08-28-multi-agent-grouping-changelog.md | 29 +++ .../docs/reference/configuration-keys.md | 3 +- src/blueprint/agents/app_builder.py | 15 +- .../agents/clients/io/nats_client.py | 71 +++++--- .../agents/clients/io/nats_run_pool.py | 171 ++++++++++++++++++ src/blueprint/agents/config/config.py | 1 + .../agents/clients/io/test_nats_run_pool.py | 162 +++++++++++++++++ 8 files changed, 431 insertions(+), 27 deletions(-) create mode 100644 src/blueprint/agents/clients/io/nats_run_pool.py create mode 100644 tests/unit/agents/clients/io/test_nats_run_pool.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c2329cc..b2a89921 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -165,8 +165,10 @@ ### Added - **Named NATS connections (`nats_connection_source`).** A deployment can give its agents further NATS connections -- one account and one existing JetStream consumer each -- through a connection source named by a process-scope key. The framework binds to the deployment's consumers verbatim and never provisions on them, checks each delivery with the source's validation hook before it runs, runs it in an empty context inside the source's scope, and settles, heartbeats and dead-letters it on its own connection. Agents keep declaring their subjects as before and see them without the connection's prefix; `nats_connection` names the connection in the handler context. Unset, nothing changes. -- **`nats_max_concurrent_runs`** (int, unset by default): how many deliveries an agent handles at once - per process, shared by all of its subscriptions; unset keeps one run per subscription. With every slot taken the subscription stops taking +- **`nats_max_concurrent_runs`** (number or `"N%"`, unset by default): how many deliveries an (agent, + connection) pair runs at once per process; unset keeps one run per subscription. The pair's first run + is always allowed; further runs also need a slot of **`nats_extra_runs_per_process`** (process scope, + number or percentage of the process's pairs, unset unlimited). With every slot taken the subscription stops taking messages; keep `nats_max_ack_pending` near replicas x this value. - **`nats_heartbeat_enabled`** (bool, default `true`): switches the delivery heartbeat off for an agent. - **`RestApiBase.path_prefix`**, an optional class attribute putting every route of an API under diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 5de49550..249ec3a3 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8342,6 +8342,35 @@ with `nats_max_concurrent_runs = 2`, 12 at once overall; every consumer acked, n event in tenant A's stream claiming tenant B ran nowhere and was termed; after a broker restart all named connections were back and delivering without a JetStream request; 0 permission violations. +### Run limits: a guaranteed run per pair, a process pool for the rest (named connections, step 3b) + +Step 3b of `docs/plans/2026-10-14-named-connections.md` (decision D7). + +- New module `clients/io/nats_run_pool.py`. `RunLimit.parse` reads a number or `"N%"` (refusing + anything else, naming the key); `resolve(pairs)` turns a percentage into runs of the process's + current (agent, connection) pairs, never below its minimum. `PairRuns` holds whether a pair's + guaranteed run is busy and how many it runs. `RunPool.acquire(pair, limit)` grants the guaranteed + run whenever it is free and a further run only while the pair is below K and the pool below its + size; waiters are woken in arrival order, a cancelled waiter returns what it was granted, and + `add_pair` / `remove_pair` re-resolve percentages. +- `AppBuilder.build` creates one `RunPool` per process from `nats_extra_runs_per_process` (added to + `PROCESS_SCOPE_KEYS`) and hands it to every client (`NATSClient.set_run_pool`). +- `NATSClient`: `nats_max_concurrent_runs` now accepts a percentage (`_resolve_max_concurrent_runs` + returns a `RunLimit`); `_Binding.limit` / `_Binding.pair` replace the shared semaphore; the + delivery path waits in `_acquire_run` -- unset K: the subscription's one slot as before; set: the + pool -- and the run's done-callback calls the returned release. `_register_pairs` counts each + client's pairs into the pool at `subscribe()` and out at `close()`. + +Tests: `test_nats_run_pool.py`, 21 (parsing, percentages, guaranteed run with an exhausted pool, K and +pool together, arrival order, cancellation, a percentage following the pairs, and through the client +an idle connection running while a busy one has exhausted the pool). + +Acceptance in WSL, the 3a set-up (three agents on two restricted connections, six pairs) with +`nats_max_concurrent_runs = 3`, `nats_extra_runs_per_process = 2`, a burst on every pair at once, 1 s +runs: all 40 runs, the first run of every pair started within 0.16 s, at most 2 per pair and **8 at +once overall -- six guaranteed plus the pool of two**, no run whose tenants disagreed, 0 permission +violations. + --- ## Open points diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index e9bc6952..7afd274a 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -45,7 +45,8 @@ Settings for the event bus transport layer. | `nats_durable_name` | `str` | `"-durable"` | Name of the durable consumer. Derived from the topic by default, with `.`, `*`, `>` and whitespace replaced by `_` because NATS rejects them in a consumer name. A client that belongs to a namespace prefixes it (`"--durable"`), so two agents subscribing to the same topic get a consumer each. Setting it explicitly is only valid with a single subscribed topic: a durable filters one subject, and under a namespace it must be scoped per namespace or every namespace binds to the same consumer. | | `nats_ack_wait` | `float` | unset -- the server's default (NATS: 30 s) | Seconds the broker waits for an acknowledgement before redelivering. **Must exceed the p99 duration of your slowest handler**, or long inference is redelivered to another replica while the first is still working. Handlers that call models usually need more than the NATS default, so set it. | | `nats_max_ack_pending` | `int` | unset -- the server's default (NATS: 1000) | Unacknowledged messages the consumer may have outstanding at once, counted across every replica sharing it. `-1` is unlimited. Keep it close to replicas x `nats_max_concurrent_runs`: whatever a pod receives beyond the runs it has started waits in the client's queue, unheartbeated, while its `nats_ack_wait` is already running down. | -| `nats_max_concurrent_runs` | `int` | unset -- one run at a time per subscription, as before the key existed | Deliveries this agent handles at once, per process, shared by all of its subscriptions. Unset, each subscription runs one delivery at a time on its own, so an agent with two subscriptions runs two at once. An agent that spends its runs waiting on a model or an API gains the most from raising it; every run shares the process's one event loop, so CPU-heavy handlers gain little. Applies to Core NATS and JetStream alike. | +| `nats_max_concurrent_runs` | `int` or `"N%"` | unset -- one run at a time per subscription, as before the key existed | How many deliveries one (agent, connection) pair runs at once, per process. The pair's **first** run is always allowed and counts against no limit; every further run also needs a free slot of `nats_extra_runs_per_process`. A percentage is taken of the (agent, connection) pairs the process consumes on, at least 1. An agent that waits on a model or an API gains the most from raising it; every run shares the process's one event loop, so CPU-heavy handlers gain little. | +| `nats_extra_runs_per_process` | `int` or `"N%"` | unset -- unlimited | **Process scope.** The pool of runs beyond each pair's guaranteed one, shared by every agent and connection of the process; a percentage is taken of the current number of pairs. It is what keeps a burst on many pairs from overloading the event loop while an idle pair still never waits. `0` allows no runs beyond the guaranteed ones. | | `nats_connection_source` | `str` | unset -- the agent consumes on its one connection, as before | **Process scope.** `"package.module:attribute"` naming a factory that is called with the process `Config` and returns a `ConnectionSource` (`blueprint.agents.clients.io.nats_connections`). The source lists named connections -- each with its own URL and account -- and, per agent and connection, a `JetStreamBinding`: which declared subjects the connection serves, the subject prefix, and the deployment's durable consumer with its wire values verbatim. Those subjects leave the agent's default connection. Each delivery from a named connection is checked by the source's `validate` before anything runs (a reason terminates it), runs in an empty context inside the source's `run_scope`, and is settled on the connection it arrived on; the handler sees the subject without the prefix and the connection's name under the context key `nats_connection`. JetStream only. An agent with named connections may not map handler results to topics. A wrong path fails startup. | | `nats_heartbeat_enabled` | `bool` | `true` | Whether a running JetStream delivery reports `in_progress` every third of its consumer's `ack_wait`, so a run longer than `ack_wait` is not redelivered while it still runs. Switch it off only for an agent whose runs always finish well inside `ack_wait`; off, a long run is delivered again to another replica. Must be a boolean -- the string `"false"` is refused, because it would read as true. | | `nats_max_deliver` | `int` | unset -- the server's default (NATS: unlimited) | Delivery attempts before the message is dead-lettered. Unlimited -- the default, or `-1` -- means a permanently failing message is retried forever and never dead-lettered; the client logs a warning at startup if you set `-1` explicitly. Set a positive limit to bound retries. | diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index 19ba8aa1..86064413 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -42,6 +42,7 @@ from .clients.io.io_client_base import TOPIC_TRANSPORTS from .clients.io.nats_client import NATSClient from .clients.io.nats_connections import CONNECTION_SOURCE_KEY, ConnectionSource, load_connection_source +from .clients.io.nats_run_pool import RunLimit, RunPool from .services.service_base import ServiceBase from .services.eventing.event_processing_service import EventProcessingService from .services.eventing.event_publishing_service import EventPublishingService @@ -1008,8 +1009,10 @@ def build(self, config: Config | None = None) -> FastAPI: connection_source = ( load_connection_source(resolved_config.get(CONNECTION_SOURCE_KEY), resolved_config) if event_bus_type == "nats" else None ) + # One pool of runs beyond each pair's guaranteed one, shared by the whole process (plan D7). + run_pool = RunPool(RunLimit.parse("nats_extra_runs_per_process", resolved_config.get("nats_extra_runs_per_process"), minimum=0)) for namespace in self.hosted_namespaces: - self._wire_transport(registry, namespace, event_bus_type, connection_source) + self._wire_transport(registry, namespace, event_bus_type, connection_source, run_pool) self._wire_dapr_endpoint(registry, event_bus_type) # 4. Create internal services (auto-register) @@ -1077,7 +1080,12 @@ def build(self, config: Config | None = None) -> FastAPI: return app def _wire_transport( - self, registry: Registry, namespace: str, event_bus_type: str, connection_source: ConnectionSource | None = None + self, + registry: Registry, + namespace: str, + event_bus_type: str, + connection_source: ConnectionSource | None = None, + run_pool: RunPool | None = None, ) -> None: """Give ``namespace`` a transport client, and an endpoint if it consumes. @@ -1099,6 +1107,7 @@ def _wire_transport( namespace: The agent to wire. event_bus_type: The resolved ``event_bus`` value, shared by the whole process. connection_source: The process's ``nats_connection_source``, if one is configured. + run_pool: The process's pool of runs beyond each pair's guaranteed one. Raises: ValueError: if this agent opted into publishing and there is no topic transport @@ -1130,6 +1139,8 @@ def _wire_transport( client = NATSClient(namespace=namespace) # auto-registers client.set_fatal_handler(self._on_transport_fatal) client.set_connection_source(connection_source) + if run_pool is not None: + client.set_run_pool(run_pool) if consumes: self._eventing_components.append(NatsEventing(namespace=namespace)) elif event_bus_type == "sessions": diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 252db012..fed38bb3 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -32,6 +32,7 @@ from ..client_base import DeliveryCallback from .io_client_base import IOClientBase, subject_is_covered_by, validate_publish_subject, validate_subject_segment from .nats_connections import ConnectionSource, JetStreamBinding, mark_connection +from .nats_run_pool import PairRuns, Release, RunLimit, RunPool logger = logging.getLogger(__name__) @@ -158,8 +159,9 @@ class _Binding: tuning: ConsumerTuning | None = None subscriptions: list[Any] = field(default_factory=list) subscriptions_ready: bool = False - run_slots: asyncio.Semaphore | None = None - """Shared by every subscription of the binding when ``nats_max_concurrent_runs`` is set.""" + limit: RunLimit | None = None + """``nats_max_concurrent_runs`` when it is set: the pair's guaranteed run plus pool runs up to K.""" + pair: PairRuns = field(default_factory=PairRuns) subscription_slots: dict[str, asyncio.Semaphore] = field(default_factory=dict) """One slot per subscription when it is not set -- one run at a time per subscription.""" runs: set[asyncio.Task[None]] = field(default_factory=set) @@ -172,9 +174,7 @@ def __post_init__(self) -> None: self.idle.set() def slots_for(self, topic: str) -> asyncio.Semaphore: - """The slots a delivery on ``topic`` waits for: the binding's shared ones, else its subscription's own.""" - if self.run_slots is not None: - return self.run_slots + """With ``nats_max_concurrent_runs`` unset: the one slot of the subscription on ``topic``, as before it existed.""" return self.subscription_slots.setdefault(topic, asyncio.Semaphore(1)) def enter_run(self) -> None: @@ -308,7 +308,9 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: self._queue_group: str = "" self._subscriptions_managed: bool = False self._retry_task: asyncio.Task[None] | None = None - self._max_concurrent_runs: int | None = None + self._max_concurrent_runs: RunLimit | None = None + self._pool = RunPool() + self._pairs_registered = 0 self._heartbeat_enabled: bool = True self._source: ConnectionSource | None = None self._named: list[_Binding] = [] @@ -487,8 +489,9 @@ async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: """ self._queue_group = self._resolve_queue_group() self._max_concurrent_runs = self._resolve_max_concurrent_runs() - # Unset keeps one run per subscription (subscription_slots); set, the subscriptions share K. - self._binding.run_slots = asyncio.Semaphore(self._max_concurrent_runs) if self._max_concurrent_runs else None + # Unset keeps one run per subscription (subscription_slots); set, the pair's guaranteed run + # plus pool runs up to K (plan D7). + self._binding.limit = self._max_concurrent_runs self._heartbeat_enabled = self._resolve_heartbeat_enabled() # What a named connection serves leaves the default connection (plan D10). default_topics = self._plan_named_bindings(topic_callbacks) @@ -498,6 +501,7 @@ async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: self._tuning = self._resolve_consumer_tuning(list(default_topics)) self._subscriptions_managed = True self._subscriptions_ready = False + self._register_pairs((1 if default_topics else 0) + len(self._named)) if self._consumption_paused: logger.info( "Agent '%s' is degraded, so its %d subscription(s) are registered but not started", @@ -508,6 +512,18 @@ async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: self._start_retry_task() self._start_named_links() + def set_run_pool(self, pool: RunPool) -> None: + """Install the process's pool of runs beyond each pair's guaranteed one, before ``subscribe()`` (plan D7).""" + self._pool = pool + + def _register_pairs(self, wanted: int) -> None: + """Hold ``wanted`` of this agent's (agent, connection) pairs in the pool; percentages are taken of the total.""" + for _ in range(wanted - self._pairs_registered): + self._pool.add_pair() + for _ in range(self._pairs_registered - wanted): + self._pool.remove_pair() + self._pairs_registered = wanted + def set_connection_source(self, source: ConnectionSource | None) -> None: """Install the process's connection source, before ``subscribe()``; ``None`` keeps one connection (N6).""" self._source = source @@ -542,7 +558,7 @@ def _plan_named_bindings(self, topic_callbacks: dict[str, DeliveryCallback]) -> jetstream=jetstream, topic_callbacks={subject: topic_callbacks[subject] for subject in jetstream.subjects}, ) - binding.run_slots = asyncio.Semaphore(self._max_concurrent_runs) if self._max_concurrent_runs else None + binding.limit = self._max_concurrent_runs self._named.append(binding) served.update(jetstream.subjects) if self._named: @@ -970,14 +986,13 @@ def _read_optional_float(self, key: str) -> float | None: return None return self._read_float(key, 0.0) - def _resolve_max_concurrent_runs(self) -> int | None: - """Return ``nats_max_concurrent_runs``: at least 1, or ``None`` when it is not configured.""" - value = self._read_optional_int("nats_max_concurrent_runs") - if value is None: - return None - if value < 1: - raise ValueError(f"'nats_max_concurrent_runs' must be at least 1, got {value}. It is how many deliveries run at once.") - return value + def _resolve_max_concurrent_runs(self) -> RunLimit | None: + """Return ``nats_max_concurrent_runs`` -- a number of at least 1 or ``"N%"`` of the process's pairs -- or ``None``. + + Raises: + ValueError: anything else, or a number below 1. It is how many deliveries a pair runs at once. + """ + return RunLimit.parse("nats_max_concurrent_runs", self.config.get("nats_max_concurrent_runs", None), minimum=1) def _resolve_heartbeat_enabled(self) -> bool: """Return ``nats_heartbeat_enabled``: whether running JetStream deliveries report ``in_progress``. @@ -1368,6 +1383,7 @@ async def close(self) -> None: await task self._named_tasks.clear() + self._register_pairs(0) # One budget for every connection: stop all deliveries, then wait for every run, then close. timeout = float(self.config.get("event_client_drain_timeout", 30.0)) deadline = asyncio.get_running_loop().time() + timeout @@ -1903,8 +1919,7 @@ async def message_handler(msg: Any) -> None: if resolved is None: await self._settle(msg, DeliveryDisposition.TERM, msg.subject, None, binding) return - slots = binding.slots_for(slot_key) - await slots.acquire() + release = await self._acquire_run(binding, slot_key) binding.enter_run() dispatch = callback if callback is not None else binding.topic_callbacks[resolved] # A run from a named connection starts in an empty context: nothing of the subscription @@ -1917,10 +1932,22 @@ async def message_handler(msg: Any) -> None: context=context, ) binding.runs.add(run) - run.add_done_callback(functools.partial(self._run_finished, binding, slots)) + run.add_done_callback(functools.partial(self._run_finished, binding, release)) return message_handler + async def _acquire_run(self, binding: _Binding, slot_key: str) -> Release: + """Wait until ``binding`` may start a run; return what frees it. + + Unset ``nats_max_concurrent_runs``: the subscription's one slot, as before the key existed. + Set: the pair's guaranteed run, or a pool run within K (plan D7). + """ + if binding.limit is None: + slots = binding.slots_for(slot_key) + await slots.acquire() + return slots.release + return await self._pool.acquire(binding.pair, binding.limit) + def _bound_topic(self, binding: _Binding, msg: Any) -> str | None: """The declared subject a binding-mode delivery belongs to, or ``None`` (logged) if none covers it.""" spec = binding.jetstream @@ -2038,10 +2065,10 @@ async def _run_scope(self, connection: str) -> AsyncIterator[None]: with scope: yield - def _run_finished(self, binding: _Binding, slots: asyncio.Semaphore, run: asyncio.Task[None]) -> None: + def _run_finished(self, binding: _Binding, release: Release, run: asyncio.Task[None]) -> None: """Free the run's slot and count it out of the in-flight runs shutdown waits for.""" binding.runs.discard(run) - slots.release() + release() binding.exit_run() if not run.cancelled() and run.exception() is not None: # _run_delivery settles every handler failure itself; this is a fault in the run's own code. diff --git a/src/blueprint/agents/clients/io/nats_run_pool.py b/src/blueprint/agents/clients/io/nats_run_pool.py new file mode 100644 index 00000000..b86edf97 --- /dev/null +++ b/src/blueprint/agents/clients/io/nats_run_pool.py @@ -0,0 +1,171 @@ +"""How many deliveries run at once: one guaranteed per (agent, connection), the rest from a process pool. + +Named-connections plan, decision D7. Event rates differ by orders of magnitude between agents -- once +an hour for one, several times a minute for another -- so a busy pair may take many runs while an +idle one must never wait: + +- **One run per (agent, connection) is always allowed** and counts against no limit. +- **Every further run** needs both: its pair is below ``nats_max_concurrent_runs`` (K), and a slot + of the process-wide pool ``nats_extra_runs_per_process`` is free. + +Both limits take an absolute number or a percentage of the pairs the process currently consumes on +(``"33%"``), resolved at every request, so they follow pairs being added or removed. Waiters are +served first come, first served among those that may run, so no pair starves another. +""" + +import asyncio +import math +from collections import deque +from collections.abc import Callable +from dataclasses import dataclass + +Release = Callable[[], None] + + +@dataclass(frozen=True) +class RunLimit: + """A configured amount: ``absolute`` runs, or ``percent`` of the process's pairs (at least ``minimum``).""" + + absolute: int | None = None + percent: float | None = None + minimum: int = 0 + + @classmethod + def parse(cls, key: str, raw: object, *, minimum: int) -> "RunLimit | None": + """Read ``raw`` as a number or ``"N%"``; ``None`` when it is unset. + + Raises: + ValueError: anything else, a number below ``minimum``, or a percentage outside + (0, 100]. The message names the key. + """ + if raw is None or raw == "": + return None + if isinstance(raw, bool): + raise ValueError(f"'{key}' must be a number or a percentage such as \"33%\", got {raw!r}.") + if isinstance(raw, int): + return cls._absolute(key, raw, minimum) + text = str(raw).strip() + if text.endswith("%"): + try: + percent = float(text[:-1]) + except ValueError: + raise ValueError(f"'{key}' is {raw!r}, which is not a percentage such as \"33%\".") from None + if not 0 < percent <= 100: + raise ValueError(f"'{key}' must be a percentage above 0 and at most 100, got {raw!r}.") + return cls(percent=percent, minimum=minimum) + try: + return cls._absolute(key, int(text), minimum) + except ValueError as exc: + if "must be" in str(exc): + raise + raise ValueError(f"'{key}' must be a number or a percentage such as \"33%\", got {raw!r}.") from None + + @classmethod + def _absolute(cls, key: str, value: int, minimum: int) -> "RunLimit": + if value < minimum: + raise ValueError(f"'{key}' must be at least {minimum}, got {value}.") + return cls(absolute=value, minimum=minimum) + + def resolve(self, pairs: int) -> int: + """The amount for a process that currently consumes on ``pairs`` (agent, connection) pairs.""" + if self.absolute is not None: + return self.absolute + return max(self.minimum, math.ceil(pairs * (self.percent or 0) / 100)) + + +@dataclass +class PairRuns: + """What one (agent, connection) pair has running: its guaranteed run, and how many in total.""" + + guaranteed_busy: bool = False + running: int = 0 + + +class RunPool: + """The process-wide pool of runs beyond each pair's guaranteed one. One per process, shared by every client.""" + + def __init__(self, extra: RunLimit | None = None) -> None: + self._extra = extra + self._extras_running = 0 + self._pairs = 0 + self._waiters: deque[tuple[PairRuns, RunLimit, asyncio.Future[Release]]] = deque() + + @property + def pairs(self) -> int: + """The (agent, connection) pairs the process consumes on, which percentages are taken of.""" + return self._pairs + + @property + def extras_running(self) -> int: + """Runs currently holding a slot of the pool.""" + return self._extras_running + + def add_pair(self) -> None: + self._pairs += 1 + self._wake() + + def remove_pair(self) -> None: + self._pairs = max(0, self._pairs - 1) + + async def acquire(self, pair: PairRuns, limit: RunLimit) -> Release: + """Wait until ``pair`` may start a run; return what frees it again. + + The pair's guaranteed run is granted at once whenever it is free; a further run waits for + both the pair's limit and the pool. + """ + granted = self._try(pair, limit) + if granted is not None: + return granted + waiter: asyncio.Future[Release] = asyncio.get_running_loop().create_future() + entry = (pair, limit, waiter) + self._waiters.append(entry) + try: + return await waiter + except asyncio.CancelledError: + if entry in self._waiters: + self._waiters.remove(entry) + elif waiter.done() and not waiter.cancelled(): + waiter.result()() # granted while being cancelled: hand the slot back + raise + + def _try(self, pair: PairRuns, limit: RunLimit) -> Release | None: + if not pair.guaranteed_busy: + pair.guaranteed_busy = True + pair.running += 1 + return self._releaser(pair, guaranteed=True) + if pair.running >= limit.resolve(self._pairs): + return None + if self._extra is not None and self._extras_running >= self._extra.resolve(self._pairs): + return None + self._extras_running += 1 + pair.running += 1 + return self._releaser(pair, guaranteed=False) + + def _releaser(self, pair: PairRuns, *, guaranteed: bool) -> Release: + released = False + + def release() -> None: + nonlocal released + if released: + return + released = True + pair.running -= 1 + if guaranteed: + pair.guaranteed_busy = False + else: + self._extras_running -= 1 + self._wake() + + return release + + def _wake(self) -> None: + """Grant every waiter that may run now, in arrival order.""" + for entry in list(self._waiters): + pair, limit, waiter = entry + if waiter.done(): + self._waiters.remove(entry) + continue + granted = self._try(pair, limit) + if granted is not None: + self._waiters.remove(entry) + waiter.set_result(granted) diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index f8c31ef7..b47a7a6e 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -79,6 +79,7 @@ class ConfigError(Exception): "dot_placeholder", "nats_stream_name", "nats_connection_source", + "nats_extra_runs_per_process", } ) """Keys that describe the *process*, and that an agent's own settings file therefore cannot set. diff --git a/tests/unit/agents/clients/io/test_nats_run_pool.py b/tests/unit/agents/clients/io/test_nats_run_pool.py new file mode 100644 index 00000000..6d20a786 --- /dev/null +++ b/tests/unit/agents/clients/io/test_nats_run_pool.py @@ -0,0 +1,162 @@ +"""Run limits: one guaranteed run per (agent, connection), the rest from a process pool (plan D7, step 3b).""" + +import asyncio +from typing import Any +from unittest.mock import MagicMock + +import pytest + +from blueprint.agents.clients.io.nats_client import NATSClient +from blueprint.agents.clients.io.nats_run_pool import PairRuns, RunLimit, RunPool +from blueprint.agents.models.events import CloudEvent +from tests.unit.agents.clients.io.test_nats_connection_source import FakeSource, _binding, _bound_handler, _delivery, _subscribed + + +class TestRunLimit: + @pytest.mark.parametrize("raw", [None, ""]) + def test_unset(self, raw: object) -> None: + assert RunLimit.parse("k", raw, minimum=1) is None + + @pytest.mark.parametrize("raw", [4, "4", " 4 "]) + def test_a_number(self, raw: object) -> None: + assert RunLimit.parse("k", raw, minimum=1) == RunLimit(absolute=4, minimum=1) + + def test_a_percentage_of_the_pairs(self) -> None: + limit = RunLimit.parse("k", "33%", minimum=1) + assert limit is not None + assert limit.resolve(300) == 99 + assert limit.resolve(6) == 2 + assert limit.resolve(0) == 1, "never below the minimum" + + @pytest.mark.parametrize("raw", ["x", "0%", "101%", "%", True, 0, -1], ids=["text", "0%", "101%", "bare-%", "bool", "zero", "negative"]) + def test_anything_else_is_refused_naming_the_key(self, raw: object) -> None: + with pytest.raises(ValueError, match="nats_max_concurrent_runs"): + RunLimit.parse("nats_max_concurrent_runs", raw, minimum=1) + + def test_the_pool_may_be_zero(self) -> None: + assert RunLimit.parse("nats_extra_runs_per_process", 0, minimum=0) == RunLimit(absolute=0, minimum=0) + + +class TestRunPool: + async def test_the_guaranteed_run_needs_no_pool(self) -> None: + pool = RunPool(RunLimit(absolute=0)) + pool.add_pair() + release = await pool.acquire(PairRuns(), RunLimit(absolute=5, minimum=1)) + assert pool.extras_running == 0 + release() + + async def test_further_runs_need_both_the_pairs_limit_and_the_pool(self) -> None: + pool = RunPool(RunLimit(absolute=1)) + busy, idle = PairRuns(), PairRuns() + pool.add_pair() + pool.add_pair() + k = RunLimit(absolute=3, minimum=1) + + first = await pool.acquire(busy, k) # guaranteed + second = await pool.acquire(busy, k) # the one pool slot + third = asyncio.create_task(pool.acquire(busy, k)) + await asyncio.sleep(0) + assert not third.done(), "the pool is exhausted" + + idle_first = await pool.acquire(idle, k) # an idle pair never waits for the pool + assert idle.guaranteed_busy + + second() # the pool slot comes back + await asyncio.sleep(0) + assert third.done() + assert busy.running == 2 + for release in (first, third.result(), idle_first): + release() + assert pool.extras_running == 0 and busy.running == 0 + + async def test_a_pair_never_exceeds_its_limit(self) -> None: + pool = RunPool(None) + pair, k = PairRuns(), RunLimit(absolute=2, minimum=1) + pool.add_pair() + await pool.acquire(pair, k) + await pool.acquire(pair, k) + waiting = asyncio.create_task(pool.acquire(pair, k)) + await asyncio.sleep(0) + assert not waiting.done() + waiting.cancel() + + async def test_waiters_are_served_in_arrival_order(self) -> None: + pool = RunPool(RunLimit(absolute=1)) + a, b = PairRuns(), PairRuns() + for _ in range(2): + pool.add_pair() + k = RunLimit(absolute=5, minimum=1) + await pool.acquire(a, k) + await pool.acquire(b, k) + holder = await pool.acquire(a, k) + order: list[str] = [] + + async def wait(name: str, pair: PairRuns) -> None: + (await pool.acquire(pair, k))() + order.append(name) + + tasks = [asyncio.create_task(wait("b", b)), asyncio.create_task(wait("a", a))] + await asyncio.sleep(0) + holder() + await asyncio.gather(*tasks) + assert order == ["b", "a"] + + async def test_a_cancelled_waiter_leaves_nothing_behind(self) -> None: + pool = RunPool(RunLimit(absolute=0)) + pair, k = PairRuns(), RunLimit(absolute=5, minimum=1) + pool.add_pair() + guaranteed = await pool.acquire(pair, k) + waiting = asyncio.create_task(pool.acquire(pair, k)) + await asyncio.sleep(0) + waiting.cancel() + with pytest.raises(asyncio.CancelledError): + await waiting + guaranteed() + assert pair.running == 0 and not pair.guaranteed_busy + + async def test_a_percentage_follows_the_pairs(self) -> None: + """Resolved at every request: a pair added later raises the pool, and a waiter is woken by it.""" + pool = RunPool(RunLimit(percent=50)) + pair, k = PairRuns(), RunLimit(absolute=10, minimum=1) + await pool.acquire(pair, k) # guaranteed + waiting = asyncio.create_task(pool.acquire(pair, k)) + await asyncio.sleep(0) + assert not waiting.done(), "50% of no pairs is no pool slot" + pool.add_pair() # 50% of 1 pair rounds up to 1 + await asyncio.sleep(0) + assert waiting.done() + + +class TestTheClientUsesThePool: + async def test_an_idle_connection_runs_while_a_busy_one_has_exhausted_the_pool( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_core: MagicMock, cloud_event: CloudEvent + ) -> None: + base = mock_config.get.side_effect + mock_config.get.side_effect = lambda key, default=None: 3 if key == "nats_max_concurrent_runs" else base(key, default) + nats_client.set_run_pool(RunPool(RunLimit(absolute=1))) + gate = asyncio.Event() + started: list[str] = [] + + async def callback(event: Any, subject: str) -> None: + started.append(subject) + await gate.wait() + + await _subscribed(nats_client, FakeSource({"A": _binding("A", "risk.>"), "B": _binding("B", "risk.>")}), ("risk.>",)) + for binding in nats_client._named: + binding.topic_callbacks["risk.>"] = callback + a, handler_a = await _bound_handler(nats_client, mock_nats_core, "A") + b, handler_b = await _bound_handler(nats_client, mock_nats_core, "B") + + callers = [asyncio.create_task(handler_a(_delivery(cloud_event, "t.A.risk.created"))) for _ in range(3)] + for _ in range(20): + await asyncio.sleep(0) + assert len(started) == 2, "A: its guaranteed run plus the one pool slot; the third waits" + await handler_b(_delivery(cloud_event, "t.B.risk.created")) + for _ in range(20): + await asyncio.sleep(0) + assert len(started) == 3, "B's guaranteed run starts although the pool is exhausted" + + gate.set() + await asyncio.gather(*callers) + await asyncio.gather(*list(a.runs), *list(b.runs)) + assert len(started) == 4 From c30737c542390704c8e0b5ddbd359391a60da061 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 14 Oct 2026 15:45:01 +0200 Subject: [PATCH 076/133] test(integration): wait for a run to be counted out instead of expecting it at once Since deliveries run as tasks of their own (a20a2b7), a run is counted out after it has settled, which is after the handler returned. The harness test asserted inflight_handlers == 0 the moment the handler had recorded the event and failed when the settlement had not finished yet. Co-Authored-By: Claude Opus 5 (1M context) --- tests/integration/test_harness.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/integration/test_harness.py b/tests/integration/test_harness.py index 44db84ae..0ff32723 100644 --- a/tests/integration/test_harness.py +++ b/tests/integration/test_harness.py @@ -208,6 +208,8 @@ async def test_a_subscribed_agent_receives_what_is_published_to_its_topic( timeout=10, description=f"the handler subscribed to '{recorder.topic}' to be called", ) - assert client.inflight_handlers == 0 + # A run is its own task and is counted out after it has settled, which is after the + # handler returned -- so wait for it rather than expect it at the handler's last line. + await wait_until(lambda: client.inflight_handlers == 0, timeout=5, description="the run to be counted out") assert [received.id for received in recorder.received] == [event.id] From 29dfb77a216d3c99b6687a370505d3a75a76dd31 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 14 Oct 2026 15:54:31 +0200 Subject: [PATCH 077/133] feat(nats): bound a run with nats_handler_timeout Step 3c of the named-connections plan (D9). With nats_handler_timeout set, a run that reaches the limit is cancelled and nak'd for immediate redelivery, on every connection; after max_deliver attempts it is given up as usual. Whether the limit was hit is read from the run's own timer, so a TimeoutError the handler raises itself stays an ordinary failure. A handler that swallows the cancellation keeps its slot until it returns, which is logged, and is nak'd all the same. Unset, nothing is cut. Verified in WSL with restricted per-tenant accounts: a hanging handler was cut at 2 s five times (max_deliver) and given up while its pair's other events and every other pair ran; without the key it held its pair. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 3 + ...26-08-28-multi-agent-grouping-changelog.md | 31 ++++ .../docs/concepts/event-processing.md | 6 + .../docs/reference/configuration-keys.md | 1 + .../agents/clients/io/nats_client.py | 80 ++++++++-- .../clients/io/test_nats_handler_timeout.py | 151 ++++++++++++++++++ 6 files changed, 261 insertions(+), 11 deletions(-) create mode 100644 tests/unit/agents/clients/io/test_nats_handler_timeout.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b2a89921..744cac78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -171,6 +171,9 @@ number or percentage of the process's pairs, unset unlimited). With every slot taken the subscription stops taking messages; keep `nats_max_ack_pending` near replicas x this value. - **`nats_heartbeat_enabled`** (bool, default `true`): switches the delivery heartbeat off for an agent. +- **`nats_handler_timeout`** (seconds, unset by default): the longest one run may take. At the limit the + run is cancelled and nak'd for immediate redelivery; a `TimeoutError` of the handler's own is an + ordinary failure. Unset, a run is never cut. - **`RestApiBase.path_prefix`**, an optional class attribute putting every route of an API under one segment -- `/api/reports/...` standalone, `/api//reports/...` in a group. Default `""`, so no existing path moves. diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 249ec3a3..b94355c9 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8371,6 +8371,37 @@ runs: all 40 runs, the first run of every pair started within 0.16 s, at most 2 once overall -- six guaranteed plus the pool of two**, no run whose tenants disagreed, 0 permission violations. +### A run can be bounded: `nats_handler_timeout` (named connections, step 3c) + +Step 3c of `docs/plans/2026-10-14-named-connections.md` (decision D9; part A's hard limit of +`docs/specs/2026-09-24-handler-time-bounds.md`, without its shutdown part). + +- `_resolve_handler_timeout` reads `nats_handler_timeout` in `subscribe()`: unset -> `None` (no + limit), a number or numeric text > 0 -> seconds; zero, negative, other text and booleans are + refused naming the key. +- `_run_delivery` runs the handler chain (and the source's run scope) inside + `asyncio.timeout(self._handler_timeout)` -- in the run's own task, so its ContextVars stay + visible. A `TimeoutError` with `limit.expired()` -> `NAK` and an ERROR naming agent, event, topic + and the connection if named; any other exception, a handler's own `TimeoutError` included, keeps + `disposition_for`. A handler that swallows the cancellation and returns -> `limit.expired()` on a + normal exit -> `NAK` and an ERROR saying it held its slot until it returned. The slot is released + by the run's done-callback, so only when the task has really ended. The heartbeat is still stopped + in the `finally` before the delivery is settled. A nak on the last allowed delivery becomes the + usual dead letter / term. + +Tests: `test_nats_handler_timeout.py`, 11 (cut and nak'd without the handler continuing, heartbeat +stopped before the nak, the handler's own `TimeoutError` an ordinary failure, unset never cut, a +swallowed cancellation holding the slot and nak'd, invalid values refused, numeric text read, the +limit on a named connection naming it). + +Acceptance in WSL, the multi-account set-up (two agents on two restricted connections), one event +on agent1@A whose handler hangs forever, three further events on agent1@A, events on every other +pair, `nats_handler_timeout = 2`: the hung event ran on agent1@A five times (starts at 0.0, 2.7, 4.7, +6.7, 8.7 s -- `max_deliver` 5) and was then given up (consumer: ack pending 0), agent1@A's other +three events ran in between, agent2@A 4 of 4 and tenant B 6 of 6 finished. Control without the key: +the hung run held agent1@A for the whole window -- its other three events never ran (ack pending +4) -- while every other pair finished. 0 permission violations in both runs. + --- ## Open points diff --git a/src/blueprint/agent_generator/docs/concepts/event-processing.md b/src/blueprint/agent_generator/docs/concepts/event-processing.md index 956df1f6..76e580f8 100644 --- a/src/blueprint/agent_generator/docs/concepts/event-processing.md +++ b/src/blueprint/agent_generator/docs/concepts/event-processing.md @@ -311,6 +311,12 @@ than starting more. Order within a subject is not kept beyond one run at a time. therefore not redelivered while it still runs. A message still waiting for a slot gets no heartbeat. `nats_heartbeat_enabled = false` switches the heartbeat off for an agent. +**A run can be bounded.** The heartbeat proves the process is alive, not that the run makes progress: +a hung model request would hold its slot -- and, with one run per subscription, every later event of +that subscription -- forever. `nats_handler_timeout` cancels a run at the limit and naks its delivery +for immediate redelivery, up to `nats_max_deliver` attempts. Whether the limit was hit is read from +the run's own timer: a `TimeoutError` raised by the handler is an ordinary failure. + An existing consumer is never rewritten. Its filter subject and deliver group are broker-side state that the stream's redelivery bookkeeping hangs off, so changing them is a migration: the client logs which settings differ and keeps consuming with the ones the broker already has. Apply diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 7afd274a..7c66c2f1 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -48,6 +48,7 @@ Settings for the event bus transport layer. | `nats_max_concurrent_runs` | `int` or `"N%"` | unset -- one run at a time per subscription, as before the key existed | How many deliveries one (agent, connection) pair runs at once, per process. The pair's **first** run is always allowed and counts against no limit; every further run also needs a free slot of `nats_extra_runs_per_process`. A percentage is taken of the (agent, connection) pairs the process consumes on, at least 1. An agent that waits on a model or an API gains the most from raising it; every run shares the process's one event loop, so CPU-heavy handlers gain little. | | `nats_extra_runs_per_process` | `int` or `"N%"` | unset -- unlimited | **Process scope.** The pool of runs beyond each pair's guaranteed one, shared by every agent and connection of the process; a percentage is taken of the current number of pairs. It is what keeps a burst on many pairs from overloading the event loop while an idle pair still never waits. `0` allows no runs beyond the guaranteed ones. | | `nats_connection_source` | `str` | unset -- the agent consumes on its one connection, as before | **Process scope.** `"package.module:attribute"` naming a factory that is called with the process `Config` and returns a `ConnectionSource` (`blueprint.agents.clients.io.nats_connections`). The source lists named connections -- each with its own URL and account -- and, per agent and connection, a `JetStreamBinding`: which declared subjects the connection serves, the subject prefix, and the deployment's durable consumer with its wire values verbatim. Those subjects leave the agent's default connection. Each delivery from a named connection is checked by the source's `validate` before anything runs (a reason terminates it), runs in an empty context inside the source's `run_scope`, and is settled on the connection it arrived on; the handler sees the subject without the prefix and the connection's name under the context key `nats_connection`. JetStream only. An agent with named connections may not map handler results to topics. A wrong path fails startup. | +| `nats_handler_timeout` | `float` | unset -- no limit | Seconds one run may take, on every connection of the agent. At the limit the run is cancelled and its delivery nak'd for immediate redelivery, so a hung model request no longer holds its slot forever; after `nats_max_deliver` attempts the delivery is given up as usual. A `TimeoutError` the handler raises itself is an ordinary failure. A handler that catches the cancellation and carries on keeps its slot until it returns, which is logged, and its delivery is nak'd all the same. Set it above the longest legitimate run. | | `nats_heartbeat_enabled` | `bool` | `true` | Whether a running JetStream delivery reports `in_progress` every third of its consumer's `ack_wait`, so a run longer than `ack_wait` is not redelivered while it still runs. Switch it off only for an agent whose runs always finish well inside `ack_wait`; off, a long run is delivered again to another replica. Must be a boolean -- the string `"false"` is refused, because it would read as true. | | `nats_max_deliver` | `int` | unset -- the server's default (NATS: unlimited) | Delivery attempts before the message is dead-lettered. Unlimited -- the default, or `-1` -- means a permanently failing message is retried forever and never dead-lettered; the client logs a warning at startup if you set `-1` explicitly. Set a positive limit to bound retries. | | `nats_dead_letter_subject` | `str` | `".dead-letter"` | Subject a message is republished to when the framework gives up on it -- either a terminal failure (`InvalidEventError`, `CriticalHandlerError`, or a payload that is not a CloudEvent) or `nats_max_deliver` attempts spent. The original bytes are republished unchanged, with `Blueprint-Dead-Letter-Reason`, `Blueprint-Original-Subject`, `Blueprint-Delivery-Count` and `Blueprint-Event-Id` headers. Set to `""` to disable, which drops those messages and loses their payloads. Startup fails if the subject is a wildcard or is itself one of the subscribed subjects, since that would loop. | diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index fed38bb3..1e19b4fa 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -269,6 +269,9 @@ class NATSClient(IOClientBase): time *per subscription*, so an agent with two subscriptions runs two at once. ``nats_heartbeat_enabled`` (bool, default true): whether running JetStream deliveries report ``in_progress``; off, a run longer than the consumer's ``ack_wait`` is redelivered while it runs. + ``nats_handler_timeout`` (float seconds, unset by default): the longest one run may take, on + every connection. At the limit the run is cancelled and nak'd for immediate redelivery; unset, + a run is never cut. Concurrent runs ~~~~~~~~~~~~~~~ @@ -312,6 +315,7 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: self._pool = RunPool() self._pairs_registered = 0 self._heartbeat_enabled: bool = True + self._handler_timeout: float | None = None self._source: ConnectionSource | None = None self._named: list[_Binding] = [] self._named_tasks: dict[str, asyncio.Task[None]] = {} @@ -493,6 +497,7 @@ async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: # plus pool runs up to K (plan D7). self._binding.limit = self._max_concurrent_runs self._heartbeat_enabled = self._resolve_heartbeat_enabled() + self._handler_timeout = self._resolve_handler_timeout() # What a named connection serves leaves the default connection (plan D10). default_topics = self._plan_named_bindings(topic_callbacks) self._topic_callbacks = default_topics @@ -1006,6 +1011,25 @@ def _resolve_heartbeat_enabled(self) -> bool: raise ValueError(f"'nats_heartbeat_enabled' must be true or false, got {value!r}.") return value + def _resolve_handler_timeout(self) -> float | None: + """Return ``nats_handler_timeout``: seconds one run may take, or ``None`` for no limit (plan D9). + + Raises: + ValueError: anything but a number greater than 0. A boolean is refused rather than read as 1. + """ + raw = self.config.get("nats_handler_timeout", None) + if raw is None or raw == "": + return None + if isinstance(raw, bool): + raise ValueError(f"'nats_handler_timeout' must be a number of seconds, got {raw!r}.") + try: + value = float(raw) + except (TypeError, ValueError): + raise ValueError(f"'nats_handler_timeout' must be a number of seconds, got {raw!r}.") from None + if value <= 0: + raise ValueError(f"'nats_handler_timeout' must be greater than 0, got {value}. Unset it for no limit.") + return value + def _read_optional_int(self, key: str) -> int | None: """Read ``key`` as an integer, or ``None`` when it is not configured.""" if self.config.get(key, None) is None: @@ -1975,6 +1999,12 @@ async def _run_delivery(self, msg: Any, topic: str, callback: DeliveryCallback, The heartbeat is stopped before the delivery is settled, whatever ended the run. A cancelled run (shutdown past its deadline) is not settled: the broker redelivers it. Everything is settled against ``binding``, the one the message arrived on. + + With ``nats_handler_timeout`` set, a run that reaches the limit is cancelled and nak'd for + immediate redelivery (plan D9). Whether the limit was hit is read from the run's own timer, + not from the exception: a ``TimeoutError`` the handler raises itself is an ordinary failure. + A handler that swallows the cancellation runs on and holds its slot until it returns; that + is logged, and its delivery is nak'd all the same. """ cloud_event = self._decode_message(msg, topic) if cloud_event is None: @@ -1990,20 +2020,48 @@ async def _run_delivery(self, msg: Any, topic: str, callback: DeliveryCallback, heartbeat = self._start_heartbeat(msg, topic, binding) disposition = DeliveryDisposition.ACK + # The run stays in this task (asyncio.timeout, not a new task): the run scope and the + # connection marker are ContextVars of this task. None means no limit. + limit = asyncio.timeout(self._handler_timeout) try: subject = binding.jetstream.local_subject(msg.subject) if binding.jetstream is not None else msg.subject - async with self._run_scope(connection): - await callback(cloud_event, subject) + async with limit: + async with self._run_scope(connection): + await callback(cloud_event, subject) except Exception as ex: - disposition = disposition_for(ex) - logger.error( - "Handler failed for event %s on topic '%s', will %s: %s", - cloud_event.id, - topic, - disposition.value, - ex, - exc_info=True, - ) + if isinstance(ex, TimeoutError) and limit.expired(): + disposition = DeliveryDisposition.NAK + logger.error( + "Agent '%s': event %s on topic '%s'%s exceeded nats_handler_timeout (%.1fs); cancelled and nak'd for redelivery", + self.namespace or ROOT_LABEL, + cloud_event.id, + topic, + f" from connection '{connection}'" if connection else "", + self._handler_timeout, + ) + else: + disposition = disposition_for(ex) + logger.error( + "Handler failed for event %s on topic '%s', will %s: %s", + cloud_event.id, + topic, + disposition.value, + ex, + exc_info=True, + ) + else: + if limit.expired(): + # The handler caught the cancellation and returned on its own, after the limit. + disposition = DeliveryDisposition.NAK + logger.error( + "Agent '%s': the handler for event %s on topic '%s'%s swallowed the cancellation at " + "nats_handler_timeout (%.1fs) and held its run slot until it returned; nak'd for redelivery", + self.namespace or ROOT_LABEL, + cloud_event.id, + topic, + f" from connection '{connection}'" if connection else "", + self._handler_timeout, + ) finally: if heartbeat is not None: heartbeat.cancel() diff --git a/tests/unit/agents/clients/io/test_nats_handler_timeout.py b/tests/unit/agents/clients/io/test_nats_handler_timeout.py new file mode 100644 index 00000000..aacaa508 --- /dev/null +++ b/tests/unit/agents/clients/io/test_nats_handler_timeout.py @@ -0,0 +1,151 @@ +"""nats_handler_timeout: a run that reaches the limit is cancelled and nak'd (named-connections plan D9, step 3c).""" + +import asyncio +import logging +from typing import Any +from unittest.mock import MagicMock + +import pytest + +from blueprint.agents.clients.io.nats_client import NATSClient +from blueprint.agents.models.events import CloudEvent +from tests.unit.agents.clients.io.test_nats_client import _delivery, _js_delivery_handler, _prepare_js_client, _until_settled +from tests.unit.agents.clients.io.test_nats_connection_source import FakeSource, _binding, _bound_handler, _deliver, _subscribed +from tests.unit.agents.clients.io.test_nats_connection_source import _delivery as _named_delivery + +LOGGER = "blueprint.agents.clients.io.nats_client" + + +class TestTheLimit: + async def test_a_run_at_the_limit_is_cancelled_and_nakd( + self, + nats_client: NATSClient, + mock_config: MagicMock, + mock_nats_jetstream: tuple, + cloud_event: CloudEvent, + caplog: pytest.LogCaptureFixture, + ) -> None: + finished: list[bool] = [] + + async def hangs(event: CloudEvent, subject: str) -> None: + await asyncio.sleep(10) + finished.append(True) + + handler = await _js_delivery_handler(nats_client, mock_config, mock_nats_jetstream, hangs, nats_handler_timeout=0.05) + msg = _delivery(cloud_event) + with caplog.at_level(logging.ERROR, logger=LOGGER): + await asyncio.wait_for(_until_settled(nats_client, handler)(msg), timeout=5) + msg.nak.assert_awaited_once() + msg.ack.assert_not_awaited() + assert finished == [], "the handler does not continue past the limit" + assert any("exceeded nats_handler_timeout" in message for message in caplog.messages) + assert nats_client.inflight_handlers == 0 + + async def test_the_heartbeat_stops_before_the_nak( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + async def hangs(event: CloudEvent, subject: str) -> None: + await asyncio.sleep(10) + + handler = await _js_delivery_handler( + nats_client, mock_config, mock_nats_jetstream, hangs, nats_ack_wait=0.03, nats_handler_timeout=0.1 + ) + msg = _delivery(cloud_event) + order = MagicMock() + order.attach_mock(msg.in_progress, "in_progress") + order.attach_mock(msg.nak, "nak") + await _until_settled(nats_client, handler)(msg) + calls = [name for name, _, _ in order.mock_calls] + assert calls.count("in_progress") >= 1 + assert calls[-1] == "nak" + + async def test_a_timeout_error_of_the_handlers_own_is_an_ordinary_failure( + self, + nats_client: NATSClient, + mock_config: MagicMock, + mock_nats_jetstream: tuple, + cloud_event: CloudEvent, + caplog: pytest.LogCaptureFixture, + ) -> None: + async def own_timeout(event: CloudEvent, subject: str) -> None: + raise TimeoutError("the backend did not answer") + + handler = await _js_delivery_handler(nats_client, mock_config, mock_nats_jetstream, own_timeout, nats_handler_timeout=10) + msg = _delivery(cloud_event) + with caplog.at_level(logging.ERROR, logger=LOGGER): + await _until_settled(nats_client, handler)(msg) + assert not any("exceeded nats_handler_timeout" in message for message in caplog.messages) + assert any("Handler failed for event" in message for message in caplog.messages) + + async def test_unset_a_run_is_never_cut( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + async def slow(event: CloudEvent, subject: str) -> None: + await asyncio.sleep(0.2) + + handler = await _js_delivery_handler(nats_client, mock_config, mock_nats_jetstream, slow) + msg = _delivery(cloud_event) + await _until_settled(nats_client, handler)(msg) + msg.ack.assert_awaited_once() + msg.nak.assert_not_awaited() + + async def test_a_handler_that_swallows_the_cancellation_holds_its_slot_and_is_nakd( + self, + nats_client: NATSClient, + mock_config: MagicMock, + mock_nats_jetstream: tuple, + cloud_event: CloudEvent, + caplog: pytest.LogCaptureFixture, + ) -> None: + held: list[int] = [] + + async def stubborn(event: CloudEvent, subject: str) -> None: + try: + await asyncio.sleep(10) + except asyncio.CancelledError: + await asyncio.sleep(0.1) # carries on after being cancelled + held.append(nats_client.inflight_handlers) + + handler = await _js_delivery_handler(nats_client, mock_config, mock_nats_jetstream, stubborn, nats_handler_timeout=0.05) + msg = _delivery(cloud_event) + with caplog.at_level(logging.ERROR, logger=LOGGER): + await _until_settled(nats_client, handler)(msg) + assert held == [1], "the slot stays taken while the handler runs on" + msg.nak.assert_awaited_once() + assert any("swallowed the cancellation" in message for message in caplog.messages) + + @pytest.mark.parametrize("value", [0, -1, "x", True], ids=["zero", "negative", "text", "bool"]) + async def test_anything_but_a_positive_number_is_refused( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, value: Any + ) -> None: + with pytest.raises(ValueError, match="nats_handler_timeout"): + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"], nats_handler_timeout=value) + + async def test_a_number_as_text_is_read(self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple) -> None: + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"], nats_handler_timeout="2.5") + assert nats_client._handler_timeout == 2.5 + + +class TestOnANamedConnection: + async def test_the_limit_applies_and_the_connection_is_named( + self, + nats_client: NATSClient, + mock_config: MagicMock, + mock_nats_core: MagicMock, + cloud_event: CloudEvent, + caplog: pytest.LogCaptureFixture, + ) -> None: + base = mock_config.get.side_effect + mock_config.get.side_effect = lambda key, default=None: 0.05 if key == "nats_handler_timeout" else base(key, default) + + async def hangs(event: CloudEvent, subject: str) -> None: + await asyncio.sleep(10) + + await _subscribed(nats_client, FakeSource({"A": _binding("A", "risk.>")}), ("risk.>",)) + nats_client._named[0].topic_callbacks["risk.>"] = hangs + binding, handler = await _bound_handler(nats_client, mock_nats_core, "A") + msg = _named_delivery(cloud_event, "t.A.risk.created") + with caplog.at_level(logging.ERROR, logger=LOGGER): + await asyncio.wait_for(_deliver(binding, handler, msg), timeout=5) + msg.nak.assert_awaited_once() + assert any("from connection 'A'" in message and "exceeded nats_handler_timeout" in message for message in caplog.messages) From 4aa166f3c2f0d6dbd633ab255ef2b45d79b331b7 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 14 Oct 2026 16:07:34 +0200 Subject: [PATCH 078/133] feat(cli): asbs validate warns about a swallowed asyncio.CancelledError When a run exceeds nats_handler_timeout it is cancelled. Code that catches the cancellation without re-raising it -- a bare except, except BaseException, except asyncio.CancelledError, or contextlib.suppress of one of them -- keeps working past the limit, holding its slot, and when it returns the delivery is nak'd and redelivered anyway, so its work may run twice. asbs validate (and --group, per agent) now names each such place with file and line. The blueprint-events skill and the validate guide say why. Checked against the first consumer: no finding in any agent; a copy with an injected swallow was reported. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 3 + ...26-08-28-multi-agent-grouping-changelog.md | 20 ++++ .../skills/blueprint-events/SKILL.md | 6 ++ .../agent_generator/cli/commands/validate.py | 7 ++ .../cli/commands/validate_group.py | 6 ++ .../cli/utils/cancellation_check.py | 95 +++++++++++++++++++ .../docs/guides/cli/validate.md | 7 ++ .../commands/test_validate_cancellation.py | 75 +++++++++++++++ 8 files changed, 219 insertions(+) create mode 100644 src/blueprint/agent_generator/cli/utils/cancellation_check.py create mode 100644 tests/unit/agent_generator/cli/commands/test_validate_cancellation.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 744cac78..756965f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -164,6 +164,9 @@ ### Added +- **`asbs validate` warns about a swallowed `asyncio.CancelledError`** in an agent's `src/` (and for + every agent with `--group`), with file and line: such code keeps a run going past + `nats_handler_timeout`, and the delivery is nak'd and redelivered anyway. - **Named NATS connections (`nats_connection_source`).** A deployment can give its agents further NATS connections -- one account and one existing JetStream consumer each -- through a connection source named by a process-scope key. The framework binds to the deployment's consumers verbatim and never provisions on them, checks each delivery with the source's validation hook before it runs, runs it in an empty context inside the source's scope, and settles, heartbeats and dead-letters it on its own connection. Agents keep declaring their subjects as before and see them without the connection's prefix; `nats_connection` names the connection in the handler context. Unset, nothing changes. - **`nats_max_concurrent_runs`** (number or `"N%"`, unset by default): how many deliveries an (agent, connection) pair runs at once per process; unset keeps one run per subscription. The pair's first run diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index b94355c9..af7f745f 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8402,6 +8402,26 @@ three events ran in between, agent2@A 4 of 4 and tenant B 6 of 6 finished. Contr the hung run held agent1@A for the whole window -- its other three events never ran (ack pending 4) -- while every other pair finished. 0 permission violations in both runs. +### `asbs validate` warns about a swallowed cancellation + +Decided with the owner after step 3c: a handler that catches the cancellation and returns normally +is nak'd (the limit was exceeded), and the validator says so before it happens. + +- New `agent_generator/cli/utils/cancellation_check.py`: `swallowed_cancellations(src_dir)` parses + every module under `src/` and reports `path:line` for an `except` that catches a cancellation -- + bare, `BaseException`, `CancelledError` (by name or attribute, alone or in a tuple) -- whose body + contains no `raise` outside nested functions, and for `contextlib.suppress(...)` naming one of + them. `swallowed_cancellation_warning(agent, found)` words the consequence. +- `validate.run` adds the warning for the project's `src/`; `validate_group._agent_findings` for every + agent root. A warning, not an issue: the agent still runs. + +Docs: `guides/cli/validate.md`, the `blueprint-events` skill (rule: never swallow +`asyncio.CancelledError`; `asbs validate` warns), `CHANGELOG.md`. Tests: +`test_validate_cancellation.py`, 15. Checked against the first consumer (`--group --agent-map +deploy/agents.toml`): valid, no finding in any agent; control -- a copy of `business_case` with an +injected `except asyncio.CancelledError: return None` -- reported with file and line, validation +passing with the warning. + --- ## Open points diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md index 7bc86b10..7b116ea4 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md @@ -28,6 +28,12 @@ pod restart, a rolling deploy. Either make the method safe to repeat, or set **b whose id and source it has already dispatched, within that window. It is off by default on purpose - only you know whether replaying your side effects is acceptable. +**Never swallow `asyncio.CancelledError`** in a handler or anything it calls. A run that exceeds +`nats_handler_timeout` is cancelled; code that catches the cancellation (`except BaseException`, a +bare `except:`, `except asyncio.CancelledError` without `raise`) keeps working past the limit and is +nak'd and redelivered anyway, so its work may run twice. Catch `Exception` instead, or re-raise. +`asbs validate` warns with file and line. + ## Shape ```python diff --git a/src/blueprint/agent_generator/cli/commands/validate.py b/src/blueprint/agent_generator/cli/commands/validate.py index cf0b6a2f..3cf78c98 100644 --- a/src/blueprint/agent_generator/cli/commands/validate.py +++ b/src/blueprint/agent_generator/cli/commands/validate.py @@ -12,6 +12,7 @@ from blueprint.agents.config import PROCESS_SCOPE_KEYS from . import validate_group +from ..utils.cancellation_check import swallowed_cancellation_warning, swallowed_cancellations from blueprint.agents.io.api.scheduling.scheduler import SCHEDULER_MODE_EVENT, SCHEDULER_MODE_IN_PROCESS, SCHEDULER_MODES logger = logging.getLogger(__name__) @@ -145,6 +146,12 @@ def run(args: Namespace) -> None: if notice: notices.append(notice) + # A swallowed cancellation defeats nats_handler_timeout: the run goes on and is nak'd anyway. + if src_dir.is_dir(): + swallowed = swallowed_cancellations(src_dir) + if swallowed: + warnings.append(swallowed_cancellation_warning(project_dir.name, swallowed)) + # Group readiness: what this project must state before it can be hosted beside another # agent, and what would otherwise stay silent. group_issues, group_warnings, group_notices = _group_findings(project_dir) diff --git a/src/blueprint/agent_generator/cli/commands/validate_group.py b/src/blueprint/agent_generator/cli/commands/validate_group.py index 00756242..a2066a8f 100644 --- a/src/blueprint/agent_generator/cli/commands/validate_group.py +++ b/src/blueprint/agent_generator/cli/commands/validate_group.py @@ -23,6 +23,8 @@ from blueprint.agents.config import PROCESS_SCOPE_KEYS from blueprint.agents.layout import check_agent_layout +from ..utils.cancellation_check import swallowed_cancellation_warning, swallowed_cancellations + AGENT_MAP_FILE = "agents.toml" AGENT_MAP_ENV = "BLUEPRINT_AGENT_MAP" @@ -173,6 +175,10 @@ def _agent_findings(image_root: Path, name: str, entry: Any, claimed: dict[Path, warnings.append(f"Agent '{name}' has no 'src' directory at {declared_root}. An agent is the same shape alone or in a group.") elif (root / "src").resolve() != (image_root / "src").resolve(): warnings.extend(_absolute_src_import_warnings(name, root)) + if (root / "src").is_dir(): + swallowed = swallowed_cancellations(root / "src") + if swallowed: + warnings.append(swallowed_cancellation_warning(name, swallowed)) settings = root / "settings.toml" if settings.is_file(): diff --git a/src/blueprint/agent_generator/cli/utils/cancellation_check.py b/src/blueprint/agent_generator/cli/utils/cancellation_check.py new file mode 100644 index 00000000..8416b544 --- /dev/null +++ b/src/blueprint/agent_generator/cli/utils/cancellation_check.py @@ -0,0 +1,95 @@ +"""Find agent code that swallows a cancellation -- what ``nats_handler_timeout`` relies on. + +When a run exceeds ``nats_handler_timeout`` the framework cancels it: an +``asyncio.CancelledError`` is raised wherever the run is awaiting. Code that catches it without +re-raising keeps the run going past the limit. The run then still holds its slot, and when it +finally returns the delivery is nak'd and redelivered anyway, because the limit was exceeded -- so +whatever it went on to finish may be done a second time. + +Parsed rather than imported, like everything ``asbs validate`` checks. +""" + +import ast +from pathlib import Path + +CANCELLATION_NAMES = frozenset({"CancelledError", "BaseException"}) +"""Exception names whose ``except`` catches a cancellation. ``Exception`` does not (Python 3.8+).""" + +SHOWN = 5 +"""How many places one warning lists before it summarises the rest.""" + + +def swallowed_cancellations(src_dir: Path) -> list[str]: + """Return ``"path:line"`` for every place under ``src_dir`` that catches a cancellation and does not re-raise. + + Reported: a bare ``except:``, ``except BaseException``, ``except (asyncio.)CancelledError`` -- alone + or in a tuple -- whose body contains no ``raise``, and ``contextlib.suppress(...)`` naming one of + them. A handler that re-raises (``except asyncio.CancelledError: ...; raise``) is fine. + """ + found: list[str] = [] + root = src_dir.parent + for path in sorted(src_dir.rglob("*.py")): + if "__pycache__" in path.parts: + continue + try: + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + except (OSError, SyntaxError, UnicodeDecodeError): + continue # not this check's to report + for node in ast.walk(tree): + if isinstance(node, ast.ExceptHandler) and _catches_cancellation(node.type) and not _reraises(node): + found.append(f"{path.relative_to(root).as_posix()}:{node.lineno}") + elif isinstance(node, ast.With | ast.AsyncWith): + for item in node.items: + if _suppresses_cancellation(item.context_expr): + found.append(f"{path.relative_to(root).as_posix()}:{node.lineno}") + return found + + +def swallowed_cancellation_warning(agent: str, found: list[str]) -> str: + """The warning for ``found``, naming the agent and what follows from it.""" + shown = ", ".join(found[:SHOWN]) + more = f" and {len(found) - SHOWN} more" if len(found) > SHOWN else "" + return ( + f"Agent '{agent}' catches asyncio.CancelledError without re-raising it ({shown}{more}). When a run exceeds " + "'nats_handler_timeout' it is cancelled; code that swallows the cancellation keeps working past the limit, " + "holding its slot, and when it returns the delivery is nak'd and redelivered anyway -- so what it finished may " + "run twice. Re-raise it ('except asyncio.CancelledError: raise' before a broader handler), or catch 'Exception', " + "which does not include it." + ) + + +def _name(node: ast.expr) -> str | None: + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + return node.attr + return None + + +def _catches_cancellation(caught: ast.expr | None) -> bool: + if caught is None: + return True # bare except + if isinstance(caught, ast.Tuple): + return any(_name(element) in CANCELLATION_NAMES for element in caught.elts) + return _name(caught) in CANCELLATION_NAMES + + +def _reraises(handler: ast.ExceptHandler) -> bool: + """Whether the handler raises anything, not counting functions defined inside it.""" + stack: list[ast.AST] = list(handler.body) + while stack: + node = stack.pop() + if isinstance(node, ast.Raise): + return True + if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda | ast.ClassDef): + continue + stack.extend(ast.iter_child_nodes(node)) + return False + + +def _suppresses_cancellation(expr: ast.expr) -> bool: + return ( + isinstance(expr, ast.Call) + and _name(expr.func) == "suppress" + and any(_name(argument) in CANCELLATION_NAMES for argument in expr.args) + ) diff --git a/src/blueprint/agent_generator/docs/guides/cli/validate.md b/src/blueprint/agent_generator/docs/guides/cli/validate.md index 230cfaae..13b94053 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/validate.md +++ b/src/blueprint/agent_generator/docs/guides/cli/validate.md @@ -44,6 +44,13 @@ Delivery: - A notice when handlers exist and `idempotency_enabled` is not declared either way. Delivery is at-least-once, so the decision is the author's to make and the framework will not make it +- A warning, with file and line, for code under `src/` that catches `asyncio.CancelledError` without + re-raising it: a bare `except:`, `except BaseException`, `except asyncio.CancelledError` (alone or + in a tuple) whose body raises nothing, or `contextlib.suppress(...)` naming one of them. When a run + exceeds `nats_handler_timeout` it is cancelled; code that swallows that keeps working past the + limit, holding its slot, and when it returns the delivery is nak'd and redelivered anyway -- what + it finished may run twice. `except Exception` does not catch a cancellation and is fine. Checked + for every agent with `--group` too. ## Example diff --git a/tests/unit/agent_generator/cli/commands/test_validate_cancellation.py b/tests/unit/agent_generator/cli/commands/test_validate_cancellation.py new file mode 100644 index 00000000..7c9d5cb7 --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_validate_cancellation.py @@ -0,0 +1,75 @@ +"""asbs validate warns about agent code that swallows asyncio.CancelledError (nats_handler_timeout).""" + +from argparse import Namespace +from pathlib import Path + +import pytest + +from blueprint.agent_generator.cli.commands import validate +from blueprint.agent_generator.cli.utils.cancellation_check import swallowed_cancellation_warning, swallowed_cancellations + + +def _src(tmp_path: Path, code: str, name: str = "handler.py") -> Path: + src = tmp_path / "src" + (src / "handlers").mkdir(parents=True, exist_ok=True) + (src / "handlers" / name).write_text(code, encoding="utf-8") + return src + + +SWALLOWING = { + "bare-except": "try:\n pass\nexcept:\n pass\n", + "base-exception": "try:\n pass\nexcept BaseException:\n return_value = None\n", + "cancelled-error": "import asyncio\ntry:\n pass\nexcept asyncio.CancelledError:\n pass\n", + "imported-name": "from asyncio import CancelledError\ntry:\n pass\nexcept CancelledError:\n pass\n", + "in-a-tuple": "import asyncio\ntry:\n pass\nexcept (ValueError, asyncio.CancelledError):\n pass\n", + "suppress": "import asyncio, contextlib\nwith contextlib.suppress(asyncio.CancelledError):\n pass\n", + "raise-only-in-nested-def": "try:\n pass\nexcept BaseException:\n def later():\n raise RuntimeError()\n", +} + +FINE = { + "exception": "try:\n pass\nexcept Exception:\n pass\n", + "re-raised": "import asyncio\ntry:\n pass\nexcept asyncio.CancelledError:\n cleanup = 1\n raise\n", + "re-raised-base": "try:\n pass\nexcept BaseException as exc:\n raise RuntimeError() from exc\n", + "suppress-other": "import contextlib\nwith contextlib.suppress(KeyError):\n pass\n", + "only-mentioned": '"""except asyncio.CancelledError: pass -- in a docstring"""\n# except BaseException:\n', +} + + +class TestTheCheck: + @pytest.mark.parametrize("code", SWALLOWING.values(), ids=SWALLOWING.keys()) + def test_a_swallowed_cancellation_is_found_with_its_line(self, tmp_path: Path, code: str) -> None: + found = swallowed_cancellations(_src(tmp_path, code)) + assert len(found) == 1 + assert found[0].startswith("src/handlers/handler.py:") + + @pytest.mark.parametrize("code", FINE.values(), ids=FINE.keys()) + def test_code_that_lets_it_through_is_not_reported(self, tmp_path: Path, code: str) -> None: + assert swallowed_cancellations(_src(tmp_path, code)) == [] + + def test_a_file_that_does_not_parse_is_not_this_checks_to_report(self, tmp_path: Path) -> None: + assert swallowed_cancellations(_src(tmp_path, "def broken(:\n")) == [] + + def test_the_warning_says_what_follows(self) -> None: + warning = swallowed_cancellation_warning("orders", [f"src/x.py:{line}" for line in range(1, 8)]) + assert "Agent 'orders'" in warning + assert "nats_handler_timeout" in warning and "nak'd" in warning + assert "src/x.py:1" in warning and "and 2 more" in warning + + +class TestValidateReportsIt: + def test_validate_warns_and_still_passes(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + _src( + tmp_path, + "import asyncio\nasync def handle():\n try:\n pass\n except asyncio.CancelledError:\n return None\n", + ) + (tmp_path / "tests").mkdir() + (tmp_path / "settings.toml").write_text("[default]\nidempotency_enabled = true\n", encoding="utf-8") + (tmp_path / "pyproject.toml").write_text("", encoding="utf-8") + (tmp_path / "src" / "main.py").write_text("from blueprint.agents.app_builder import AppBuilder\n", encoding="utf-8") + + with pytest.raises(SystemExit) as exit_info: + validate.run(Namespace(project_dir=str(tmp_path), group=False)) + + assert exit_info.value.code == 0, "a warning, not an issue" + out = capsys.readouterr().out + assert "catches asyncio.CancelledError without re-raising it (src/handlers/handler.py:5)" in out From f99b37d067831069c31001ba49d03c07541cc98b Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 14 Oct 2026 16:36:44 +0200 Subject: [PATCH 079/133] docs(plans): step 4 follows the dynamic-subscriptions rules and takes review finding #10 Co-Authored-By: Claude Opus 5 (1M context) --- docs/plans/2026-10-14-named-connections.md | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/docs/plans/2026-10-14-named-connections.md b/docs/plans/2026-10-14-named-connections.md index de9968f0..1575ae18 100644 --- a/docs/plans/2026-10-14-named-connections.md +++ b/docs/plans/2026-10-14-named-connections.md @@ -263,9 +263,27 @@ One step, one reviewable commit. Each step names its acceptance. per-connection slots and per-process cap (D7), handler timeout (D9). *Acceptance:* isolation test below; mismatch -> term; limits respected (measured overlap). 4. **Connection source, dynamic.** Add, change, remove at runtime; drain on remove; never delete a - foreign consumer. + foreign consumer. Built on the rules of `docs/specs/2026-09-23-dynamic-subscriptions.md`, for whole + connections only (no selectors, no REST API), with building blocks that spec can reuse later: + - a change and a reconnect never interleave (one lock per agent, spec 7.2); + - a changed connection: open and bind the new link first, then drain and close the old (spec 7.4); + - a removed connection: drain, give running runs a grace period, then **revoke** what is left -- + no ack, no nak, heartbeat stopped, not cancelled, `publish` refused (spec 7.5); the link closes + only after that, so no acknowledgement of a finished run is lost; + - a consumer the operator made is never deleted, and neither is a managed one on removal (a tenant + that drops out of the directory briefly must not lose messages; the first consumer's pool behaves so today); + - permission violations arrive through `error_cb`, not as the call's error: a JetStream request + that times out while one arrived is permanent, not retried as a slow broker (spec 7.9); + - a shutdown during a change cancels it, nothing is half applied (spec 7.10); readiness does not + change during a change (D7); nothing depends on group composition (D0). + **Also in this step (owner's review finding #10, decided 2026-10-14):** `nats_max_reconnect_attempts` + defaults to `-1` (unlimited) instead of 5 -- after about 10 s of outage the default connection + closed for good while readiness reported healthy -- and a client that did close reconnects **and + resubscribes** instead of only reconnecting in the health check. Core NATS's 128 MB client buffer + (also #10) is not part of this feature; a configurable limit is left for later. 5. **Readiness and telemetry per connection** (D5): connection state in the readiness payload, - metrics labelled with the connection name. + metrics labelled with the connection name. Take review finding #6 (the readiness probe waits on a + lock held during slow health checks) into account here. 6. **Everything that describes the framework agrees with it -- no contradiction left anywhere.** Not only the new feature: every statement about NATS delivery, consumers, concurrency, heartbeat, run limits and connections is checked against the code after steps 1-5, and corrected or From c8ec35a7ac196ecbd4ae052605d11d8c1c10c43d Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 14 Oct 2026 17:24:09 +0200 Subject: [PATCH 080/133] fix(nats): a closed connection reconnects and resubscribes; unlimited reconnects by default Step 4a of the named-connections plan, review finding #10. nats_max_reconnect_attempts defaults to -1 (was 5, about 10 s of outage). A connection that closes anyway restarts the retry loop, which connects and resubscribes (or, while paused, connects and leaves the subscribing to resume_consumption). Once subscriptions are managed, a connect() from the health checker only starts that loop instead of opening a bare connection that subscribes to nothing. Measured in WSL with 45-75 s broker outages and a control run on the old code: both recover; time to the first handled event is bounded by the next health poll in both (C4 resumes on a healthy poll). Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 4 ++ ...26-08-28-multi-agent-grouping-changelog.md | 16 ++++++ .../docs/reference/configuration-keys.md | 1 + .../agents/clients/io/nats_client.py | 36 +++++++++++++- .../agents/clients/io/test_nats_client.py | 49 +++++++++++++++++++ 5 files changed, 104 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a84f927d..10feebe2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,10 @@ ### Fixed +- **A NATS connection that gave up reconnecting comes back, with its subscriptions.** + `nats_max_reconnect_attempts` now defaults to unlimited (was 5, about 10 s of outage), and a + connection that closes anyway restarts the client's retry loop, which connects and resubscribes; + a health check no longer opens a bare connection that subscribes to nothing. - **NATS deliveries are no longer handled strictly one at a time.** nats-py gives each subscription one task that awaits its callback, and the callback ran the whole handler -- so an agent handled one event per subscription and process at a time, however much of the run was spent waiting on a diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index af7f745f..b781414d 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8422,6 +8422,22 @@ deploy/agents.toml`): valid, no finding in any agent; control -- a copy of `busi injected `except asyncio.CancelledError: return None` -- reported with file and line, validation passing with the warning. +### A closed NATS connection comes back with its subscriptions (named connections, step 4a; review finding #10) + +- `connect()`: `nats_max_reconnect_attempts` defaults to `-1`; `closed_cb=_on_closed`. Once + subscriptions are managed, a `connect()` from outside the retry loop (the health checker polls it) + only starts the loop, which connects and subscribes -- or, while the agent is paused, connects and + subscribes nothing until `resume_consumption`. `_on_closed` restarts the loop unless we closed it + ourselves (`_closing`, set in `close()`). +- Tests: `TestAClosedConnectionComesBack` (7). +- Measured in WSL, JetStream, broker stopped for 45/60/75 s, control on the code before: both recover; + the code before only because the health checker reconnected bare and pause/resume (C4) resubscribed. + A first version of this change refused that bare connect also while paused and so never recovered + (caught by the control run, fixed). Time from broker start to the first event handled is bounded by + the next health poll in both versions (C4 resumes only on a healthy poll): 3.0-14.2 s before, + 14.2-29.3 s after, by phase of the 30 s poll. **Open:** resume on reconnect without waiting for the + next poll would cut up to one `health_check_interval_seconds` from every recovery. + --- ## Open points diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 7c66c2f1..9b224b30 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -40,6 +40,7 @@ Settings for the event bus transport layer. | `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. | | `event_client_drain_timeout` | `float` | `30.0` | Seconds allowed at shutdown for in-flight message handlers to finish before the broker connection is closed. Bounds the whole shutdown sequence, so keep it below the pod's termination grace period. | +| `nats_max_reconnect_attempts` | `int` | `-1` -- unlimited | Reconnect attempts after the broker drops the connection, `nats_reconnect_time_wait` seconds apart. A finite value closes the connection after that many; the client then starts over (connect, then resubscribe). | | `nats_use_jetstream` | `bool` | `false` | Consume through a durable JetStream consumer instead of Core NATS. The keys below apply only when this is `true`. **A declaration, enforced:** with `true`, a server that does not offer JetStream to the account fails the agent -- at startup through the startup failure policy, or, if the broker was unreachable then, when it first connects: the root or a critical agent shuts the process down, a non-critical agent is marked down. There is no fallback to Core NATS. With `false`, the server is not asked; Core NATS works on a JetStream-enabled server too. | | `nats_stream_name` | `str` | `"EVENTS"` | Stream the durable consumers are created on. The framework creates it if it is missing, and widens an existing one to cover every subscribed subject plus the dead-letter subject; it never removes a subject. | | `nats_durable_name` | `str` | `"-durable"` | Name of the durable consumer. Derived from the topic by default, with `.`, `*`, `>` and whitespace replaced by `_` because NATS rejects them in a consumer name. A client that belongs to a namespace prefixes it (`"--durable"`), so two agents subscribing to the same topic get a consumer each. Setting it explicitly is only valid with a single subscribed topic: a durable filters one subject, and under a namespace it must be scoped per namespace or every namespace binds to the same consumer. | diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 1e19b4fa..bb2f8993 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -303,6 +303,7 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: self._link = _Link() self._binding = _Binding(link=self._link) self._started = False + self._closing = False self._fatal_handler: FatalHandler | None = None self._fatal_reported = False self._use_jetstream: bool = False @@ -1225,9 +1226,19 @@ def _is_connected(self) -> bool: return self._nats_client is not None and not self._nats_client.is_closed and self._nats_client.is_connected async def connect(self) -> None: - """Connect to the NATS server, registering disconnect/reconnect callbacks.""" + """Connect to the NATS server, registering disconnect/reconnect callbacks. + + Once ``subscribe()`` has registered the agent's subscriptions, the retry loop owns the + connection: a call from anywhere else -- the health checker polls this -- only makes sure + the loop runs. The loop connects and subscribes; while the agent is paused it connects and + subscribes nothing, and ``resume_consumption`` subscribes once the agent is healthy again -- + which needs the connection, so a paused agent is connected too. + """ if self._nats_client is not None and not self._nats_client.is_closed: return + if self._subscriptions_managed and not self._closing and asyncio.current_task() is not self._retry_task: + self._start_retry_task() + return if not self._nats_url: self._nats_url = self._resolve_nats_url() @@ -1238,11 +1249,14 @@ async def connect(self) -> None: self._nats_client = await nats.connect( self._nats_url, name=self._connection_name or None, - max_reconnect_attempts=self.config.get("nats_max_reconnect_attempts", 5), + # Unlimited by default: with 5 attempts 2 s apart, an outage of about 10 s closed the + # connection for good (review finding #10). _on_closed restarts it either way. + max_reconnect_attempts=self.config.get("nats_max_reconnect_attempts", -1), reconnect_time_wait=self.config.get("nats_reconnect_time_wait", 2), connect_timeout=10, disconnected_cb=self._on_disconnected, reconnected_cb=self._on_reconnected, + closed_cb=self._on_closed, **self._connect_options, ) self._client = self._nats_client @@ -1395,6 +1409,7 @@ async def close(self) -> None: sequence, so shutdown stays inside a pod's termination grace period. """ self._subscriptions_ready = False + self._closing = True if self._retry_task and not self._retry_task.done(): self._retry_task.cancel() @@ -2331,6 +2346,23 @@ async def _on_disconnected(self) -> None: self._subscriptions_ready = False logger.warning("NATSClient disconnected") + async def _on_closed(self) -> None: + """The client gave up reconnecting: connect again and resubscribe, in the retry loop. + + Only with a finite ``nats_max_reconnect_attempts``, or a closed connection we did not close + ourselves. Our own ``close()`` is not reconnected. + """ + if self._closing or not self._subscriptions_managed: + return + self._subscriptions_ready = False + self._subscriptions.clear() + logger.error( + "Agent '%s': the NATS connection closed after its reconnect attempts; connecting again and resubscribing", + self.namespace or ROOT_LABEL, + ) + # Paused or not: the loop connects either way and subscribes only an agent that is not paused. + self._start_retry_task() + async def _on_reconnected(self) -> None: logger.info("NATSClient reconnected") if not self._subscriptions_managed: diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index fe21843e..bbbe9869 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -2463,3 +2463,52 @@ async def test_a_string_is_not_a_switch(self, nats_client: NATSClient, mock_conf """'false' as a string would read as true and keep the heartbeat the operator meant to switch off.""" with pytest.raises(ValueError, match="nats_heartbeat_enabled"): await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"], nats_heartbeat_enabled="false") + + +class TestAClosedConnectionComesBack: + """Review finding #10: after its reconnect attempts the client closed for good and never resubscribed.""" + + async def test_reconnect_attempts_are_unlimited_by_default(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + base = mock_config.get.side_effect + mock_config.get.side_effect = lambda key, default=None: default if key == "nats_max_reconnect_attempts" else base(key, default) + with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock) as mock_connect: + await nats_client.connect() + assert mock_connect.await_args.kwargs["max_reconnect_attempts"] == -1 + assert mock_connect.await_args.kwargs["closed_cb"] == nats_client._on_closed + + async def test_a_closed_connection_restarts_the_retry_loop(self, nats_client: NATSClient) -> None: + nats_client._subscriptions_managed = True + nats_client._subscriptions_ready = True + with patch.object(nats_client, "_start_retry_task") as start: + await nats_client._on_closed() + start.assert_called_once() + assert nats_client.subscriptions_ready is False + + async def test_a_paused_agent_is_reconnected_too(self, nats_client: NATSClient) -> None: + """Resume needs a healthy, connected client; the loop connects and subscribes nothing while paused.""" + nats_client._subscriptions_managed = True + nats_client._consumption_paused = True + with patch.object(nats_client, "_start_retry_task") as start: + await nats_client._on_closed() + await nats_client.connect() + assert start.call_count == 2 + + @pytest.mark.parametrize("state", ["closing", "unmanaged"]) + async def test_not_restarted_when_it_should_not_consume(self, nats_client: NATSClient, state: str) -> None: + nats_client._subscriptions_managed = state != "unmanaged" + nats_client._closing = state == "closing" + nats_client._consumption_paused = state == "paused" + with patch.object(nats_client, "_start_retry_task") as start: + await nats_client._on_closed() + start.assert_not_called() + + async def test_the_health_check_never_opens_a_connection_that_subscribes_to_nothing(self, nats_client: NATSClient) -> None: + """Once subscriptions are managed, connect() from outside only makes sure the retry loop runs.""" + nats_client._subscriptions_managed = True + with ( + patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock) as mock_connect, + patch.object(nats_client, "_start_retry_task") as start, + ): + await nats_client.connect() + mock_connect.assert_not_awaited() + start.assert_called_once() From ca1a8eb43502a9f993d8cf01d620dc1a9682caae Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 08:38:04 +0200 Subject: [PATCH 081/133] feat(nats): named connections change at runtime through ConnectionSource.watch Step 4b of the named-connections plan. A source may define watch(notify); every agent's client registers a notify that hops onto its loop and coalesces, and reconciles the named bindings under a lock that pause and resume also take: a new connection is bound, a changed one gets a new link that is bound before the old one is retired, and a removed one is drained, its runs given subscription_change_grace, and what still runs is revoked -- never acked or nak'd, its heartbeat stopped, publish refused with the new DeliveryRevokedError, not cancelled. No consumer is deleted. Permission violations reported through error_cb back the retry off to 60 s with an ERROR. Verified in WSL with restricted per-tenant accounts while events kept flowing: a tenant added, one's credentials switched (none lost or duplicated, ack pending 0; control with the old link closed first left 2 acks lost per consumer), one removed with a run in flight (revoked, not settled); 0 permission violations. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 6 + ...26-08-28-multi-agent-grouping-changelog.md | 52 +++ docs/plans/2026-10-14-named-connections.md | 2 +- .../docs/reference/configuration-keys.md | 3 +- .../agents/clients/io/nats_client.py | 346 +++++++++++++-- .../agents/clients/io/nats_connections.py | 13 +- src/blueprint/agents/models/errors.py | 14 + .../clients/io/test_nats_runtime_changes.py | 401 ++++++++++++++++++ 8 files changed, 806 insertions(+), 31 deletions(-) create mode 100644 tests/unit/agents/clients/io/test_nats_runtime_changes.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 10feebe2..f80c0dc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -168,6 +168,12 @@ ### Added +- **Named connections change at runtime.** A connection source that defines `watch(notify)` tells every + agent's client when its connections change; the client binds a new connection, replaces a changed one + (new link bound before the old one is retired) and retires a removed one: drained, its runs given + `subscription_change_grace` seconds, the rest revoked -- never settled, `publish` refused with the new + `DeliveryRevokedError`, not cancelled. A change never interleaves with a pause, and no consumer is + deleted. A permission the broker refuses is retried every 60 s with an ERROR instead of at full pace. - **`asbs validate` warns about a swallowed `asyncio.CancelledError`** in an agent's `src/` (and for every agent with `--group`), with file and line: such code keeps a run going past `nats_handler_timeout`, and the delivery is nak'd and redelivered anyway. diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index b781414d..1bee93ee 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8438,6 +8438,58 @@ passing with the warning. 14.2-29.3 s after, by phase of the 30 s poll. **Open:** resume on reconnect without waiting for the next poll would cut up to one `health_check_interval_seconds` from every recovery. +### Named connections change at runtime (named connections, step 4b) + +Step 4b of `docs/plans/2026-10-14-named-connections.md`, following the rules of the +dynamic-subscriptions draft spec (7.2, 7.4, 7.5, 7.7, 7.9, 7.10) for whole connections. + +- `ConnectionSource.watch(notify)` is optional (looked up with `getattr`; not part of the protocol's + `isinstance` check). `subscribe()` registers `_connections_changed`, which hops onto the client's + loop with `call_soon_threadsafe`; `_schedule_reconcile` runs one `_reconcile_loop` at a time and a + notify during a pass makes it run once more. +- `_reconcile` (under `_change_lock`, which `pause_consumption` and `resume_consumption` also take) + re-reads `connections()`/`binding()` for the declared subjects and diffs by name against the + bindings that are not `superseded`: **added** -> `_new_named_binding` + `_start_named_link`; **changed** + (`ConnectionSpec` or `JetStreamBinding` differs) -> a new binding with `replaces` = the old one, which + is marked `superseded` and keeps serving; `_run_named_link` retires it only once the new one is bound + (`_start_retirement`); **removed** -> `_retire`. A binding claiming undeclared subjects is skipped with + an ERROR; an agent mapping results to topics gains no connection (D4). The default connection's + subjects stay as computed at startup. +- `_retire`: cancels the binding's loop, drains its subscriptions, waits `subscription_change_grace` + (agent scope, default `event_client_drain_timeout`) for its runs, then sets `revoked`, cancels their + heartbeats (`_Binding.heartbeats`), closes the link (`_Link.closing`, so the disconnect is not logged + as a lost broker) and removes the pair from the pool. A revoked run is never settled + (`_run_delivery` returns before `_settle`), and `publish` from it raises the new + `models.errors.DeliveryRevokedError` (the run's binding is in the ContextVar `_CURRENT_BINDING`). No + consumer is deleted. +- Permission violations reported through a named link's `error_cb` are kept on `_Link.permission_errors`; + an attempt that failed while one arrived is logged at ERROR and retried every + `PERMISSION_RETRY_SECONDS` (60) instead of at the normal pace. +- `close()` cancels a running reconcile and pending retirements first; the normal close then drains + and closes every binding still listed. +- Found by the unit tests while building it: `_reconcile` first called `_start_named_links()`, which + restarted the loop of every already bound connection -- each would have bound a second subscription. + It now starts only the bindings it created (`_start_named_link`). + +Tests: `test_nats_runtime_changes.py`, 19 (watch optional and registered; added, removed, changed with +new-before-old order and the old link serving while the new one cannot bind; unchanged left alone; +undeclared subjects and D4 skipped; revocation -- never settled, publish refused, heartbeat stopped, +settled normally within the grace; coalescing; notify from another thread; pause waits for a change; +close during a change; permission back-off and error_cb recording). Unit suite 3509 passed. + +Acceptance in WSL against `nats:2.10-alpine` with accounts PROC (nothing allowed) and TA/TB/TC (admin +plus two agent users each, allowed only their deliver subjects and `$JS.ACK.>`), a group of two +agents, a source changed through `watch` while A and B received an event every 0.1 s: +(1) C added -> 10 of 10 runs, A and B undisturbed; (2) A's credentials switched to its second user -> +114 events, none missing, none duplicated, longest gap 0.14 s, consumers of A ack pending 0; +(3) B removed while a 5 s run was in flight, grace 1 s -> revoked after 1 s, the run finished 4.5 s +later and was not settled (each B consumer: ack pending 1, the delivery stays with the broker); every +B event before the removal handled. 360 runs, none whose connection, scope tenant and event tenant +disagreed; 0 permission violations. **Control for (2):** the old link closed abruptly before the change +-> still none missing and no visible gap, but each A consumer ended with **ack pending 2**: acks lost +with the link, redelivered after `ack_wait` as duplicates. That is what binding first and draining +then prevents. + --- ## Open points diff --git a/docs/plans/2026-10-14-named-connections.md b/docs/plans/2026-10-14-named-connections.md index 1575ae18..a045b0e7 100644 --- a/docs/plans/2026-10-14-named-connections.md +++ b/docs/plans/2026-10-14-named-connections.md @@ -262,7 +262,7 @@ One step, one reviewable commit. Each step names its acceptance. validation hook (N2), empty Context per run, `nats_connection` context key, run scope hook (D3), per-connection slots and per-process cap (D7), handler timeout (D9). *Acceptance:* isolation test below; mismatch -> term; limits respected (measured overlap). -4. **Connection source, dynamic.** Add, change, remove at runtime; drain on remove; never delete a +4. **Connection source, dynamic. Done 2026-10-15 (4a `3c16c10`, 4b).** Add, change, remove at runtime; drain on remove; never delete a foreign consumer. Built on the rules of `docs/specs/2026-09-23-dynamic-subscriptions.md`, for whole connections only (no selectors, no REST API), with building blocks that spec can reuse later: - a change and a reconnect never interleave (one lock per agent, spec 7.2); diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 9b224b30..22a64fe9 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -48,8 +48,9 @@ Settings for the event bus transport layer. | `nats_max_ack_pending` | `int` | unset -- the server's default (NATS: 1000) | Unacknowledged messages the consumer may have outstanding at once, counted across every replica sharing it. `-1` is unlimited. Keep it close to replicas x `nats_max_concurrent_runs`: whatever a pod receives beyond the runs it has started waits in the client's queue, unheartbeated, while its `nats_ack_wait` is already running down. | | `nats_max_concurrent_runs` | `int` or `"N%"` | unset -- one run at a time per subscription, as before the key existed | How many deliveries one (agent, connection) pair runs at once, per process. The pair's **first** run is always allowed and counts against no limit; every further run also needs a free slot of `nats_extra_runs_per_process`. A percentage is taken of the (agent, connection) pairs the process consumes on, at least 1. An agent that waits on a model or an API gains the most from raising it; every run shares the process's one event loop, so CPU-heavy handlers gain little. | | `nats_extra_runs_per_process` | `int` or `"N%"` | unset -- unlimited | **Process scope.** The pool of runs beyond each pair's guaranteed one, shared by every agent and connection of the process; a percentage is taken of the current number of pairs. It is what keeps a burst on many pairs from overloading the event loop while an idle pair still never waits. `0` allows no runs beyond the guaranteed ones. | -| `nats_connection_source` | `str` | unset -- the agent consumes on its one connection, as before | **Process scope.** `"package.module:attribute"` naming a factory that is called with the process `Config` and returns a `ConnectionSource` (`blueprint.agents.clients.io.nats_connections`). The source lists named connections -- each with its own URL and account -- and, per agent and connection, a `JetStreamBinding`: which declared subjects the connection serves, the subject prefix, and the deployment's durable consumer with its wire values verbatim. Those subjects leave the agent's default connection. Each delivery from a named connection is checked by the source's `validate` before anything runs (a reason terminates it), runs in an empty context inside the source's `run_scope`, and is settled on the connection it arrived on; the handler sees the subject without the prefix and the connection's name under the context key `nats_connection`. JetStream only. An agent with named connections may not map handler results to topics. A wrong path fails startup. | +| `nats_connection_source` | `str` | unset -- the agent consumes on its one connection, as before | **Process scope.** `"package.module:attribute"` naming a factory that is called with the process `Config` and returns a `ConnectionSource` (`blueprint.agents.clients.io.nats_connections`). The source lists named connections -- each with its own URL and account -- and, per agent and connection, a `JetStreamBinding`: which declared subjects the connection serves, the subject prefix, and the deployment's durable consumer with its wire values verbatim. Those subjects leave the agent's default connection. Each delivery from a named connection is checked by the source's `validate` before anything runs (a reason terminates it), runs in an empty context inside the source's `run_scope`, and is settled on the connection it arrived on; the handler sees the subject without the prefix and the connection's name under the context key `nats_connection`. JetStream only. An agent with named connections may not map handler results to topics. A source that also defines `watch(notify)` is followed at runtime: connections added, changed or removed are applied while the agent runs (`subscription_change_grace`). A wrong path fails startup. | | `nats_handler_timeout` | `float` | unset -- no limit | Seconds one run may take, on every connection of the agent. At the limit the run is cancelled and its delivery nak'd for immediate redelivery, so a hung model request no longer holds its slot forever; after `nats_max_deliver` attempts the delivery is given up as usual. A `TimeoutError` the handler raises itself is an ordinary failure. A handler that catches the cancellation and carries on keeps its slot until it returns, which is logged, and its delivery is nak'd all the same. Set it above the longest legitimate run. | +| `subscription_change_grace` | `float` | `event_client_drain_timeout` | Seconds the runs of a named connection that is removed or replaced at runtime get to finish. A run still going after that is revoked: it is never acked or nak'd -- the delivery stays with the broker and returns after `ack_wait` -- its heartbeat stops, and a `publish` from it raises `DeliveryRevokedError`; it is not cancelled. | | `nats_heartbeat_enabled` | `bool` | `true` | Whether a running JetStream delivery reports `in_progress` every third of its consumer's `ack_wait`, so a run longer than `ack_wait` is not redelivered while it still runs. Switch it off only for an agent whose runs always finish well inside `ack_wait`; off, a long run is delivered again to another replica. Must be a boolean -- the string `"false"` is refused, because it would read as true. | | `nats_max_deliver` | `int` | unset -- the server's default (NATS: unlimited) | Delivery attempts before the message is dead-lettered. Unlimited -- the default, or `-1` -- means a permanently failing message is retried forever and never dead-lettered; the client logs a warning at startup if you set `-1` explicitly. Set a positive limit to bound retries. | | `nats_dead_letter_subject` | `str` | `".dead-letter"` | Subject a message is republished to when the framework gives up on it -- either a terminal failure (`InvalidEventError`, `CriticalHandlerError`, or a payload that is not a CloudEvent) or `nats_max_deliver` attempts spent. The original bytes are republished unchanged, with `Blueprint-Dead-Letter-Reason`, `Blueprint-Original-Subject`, `Blueprint-Delivery-Count` and `Blueprint-Event-Id` headers. Set to `""` to disable, which drops those messages and loses their payloads. Startup fails if the subject is a wildcard or is itself one of the subscribed subjects, since that would loop. | diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index bb2f8993..20155000 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -27,11 +27,11 @@ from ...deployment import UNGROUPED_LABEL, UNKNOWN_POD_LABEL, deployment_group, pod_identity from ...io.telemetry.providers import agent_meter from ...models.api import ComponentHealth -from ...models.errors import DeliveryDisposition, disposition_for +from ...models.errors import DeliveryDisposition, DeliveryRevokedError, disposition_for from ...models.events import CloudEvent from ..client_base import DeliveryCallback from .io_client_base import IOClientBase, subject_is_covered_by, validate_publish_subject, validate_subject_segment -from .nats_connections import ConnectionSource, JetStreamBinding, mark_connection +from .nats_connections import ConnectionSource, ConnectionSpec, JetStreamBinding, mark_connection from .nats_run_pool import PairRuns, Release, RunLimit, RunPool logger = logging.getLogger(__name__) @@ -69,6 +69,15 @@ class JetStreamUnavailableError(RuntimeError): """ +PERMISSION_RETRY_SECONDS = 60.0 +"""How often a named connection retries after the broker refused it a permission: a missing grant does +not heal in seconds, so retrying at the normal pace would only fill the log (spec 7.9).""" + +_CURRENT_BINDING: contextvars.ContextVar["_Binding | None"] = contextvars.ContextVar("blueprint_nats_binding", default=None) +"""The named binding a run's delivery arrived on; set inside that run's own task only, so ``publish`` +can refuse a revoked run (dynamic-subscriptions spec 7.5).""" + + FatalHandler = Callable[[str, BaseException], Awaitable[None]] """Called once when a client finds, after startup, that its agent cannot run at all: namespace, error.""" @@ -139,6 +148,10 @@ class _Link: nats_client: NatsClient | None = None js: JetStreamContext | None = None jetstream_mismatch: JetStreamUnavailableError | None = None + permission_errors: list[str] = field(default_factory=list) + """Permission violations the broker reported through ``error_cb`` since the last attempt.""" + closing: bool = False + """We are closing this link ourselves: its disconnect is not a lost broker.""" @dataclass(eq=False) @@ -169,6 +182,15 @@ class _Binding: """Per topic, the bound consumer's own ``ack_wait`` -- what the heartbeat interval derives from.""" inflight: int = 0 idle: asyncio.Event = field(default_factory=asyncio.Event) + spec: ConnectionSpec | None = None + """The connection as the source last described it; a named binding is replaced when it differs.""" + replaces: "_Binding | None" = None + """The binding this one replaces; retired as soon as this one is bound (new before old, spec 7.4).""" + superseded: bool = False + """A newer binding of the same connection exists; this one serves until that one is bound.""" + revoked: bool = False + """Retired with runs still in flight after the grace period: those runs are never settled (spec 7.5).""" + heartbeats: set[asyncio.Task[None]] = field(default_factory=set) def __post_init__(self) -> None: self.idle.set() @@ -319,7 +341,15 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: self._handler_timeout: float | None = None self._source: ConnectionSource | None = None self._named: list[_Binding] = [] - self._named_tasks: dict[str, asyncio.Task[None]] = {} + self._named_tasks: dict[_Binding, asyncio.Task[None]] = {} + self._declared: dict[str, DeliveryCallback] = {} + self._default_pairs = 0 + self._change_grace = 30.0 + self._change_lock = asyncio.Lock() + self._loop: asyncio.AbstractEventLoop | None = None + self._reconcile_task: asyncio.Task[None] | None = None + self._reconcile_dirty = False + self._retirements: set[asyncio.Task[None]] = set() # ------------------------------------------------------------------ # The default link and binding, under the names the client used before it had them @@ -499,6 +529,8 @@ async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: self._binding.limit = self._max_concurrent_runs self._heartbeat_enabled = self._resolve_heartbeat_enabled() self._handler_timeout = self._resolve_handler_timeout() + self._change_grace = self._resolve_change_grace() + self._declared = dict(topic_callbacks) # What a named connection serves leaves the default connection (plan D10). default_topics = self._plan_named_bindings(topic_callbacks) self._topic_callbacks = default_topics @@ -507,7 +539,9 @@ async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: self._tuning = self._resolve_consumer_tuning(list(default_topics)) self._subscriptions_managed = True self._subscriptions_ready = False - self._register_pairs((1 if default_topics else 0) + len(self._named)) + self._default_pairs = 1 if default_topics else 0 + self._register_pairs(self._default_pairs + len(self._named)) + self._watch_source() if self._consumption_paused: logger.info( "Agent '%s' is degraded, so its %d subscription(s) are registered but not started", @@ -559,12 +593,7 @@ def _plan_named_bindings(self, topic_callbacks: dict[str, DeliveryCallback]) -> f"Agent '{self.namespace or ROOT_LABEL}': the binding for connection '{spec.name}' claims " f"{', '.join(unknown)}, which the agent does not declare. A binding serves declared subjects only." ) - binding = _Binding( - link=_Link(name=spec.name, url=spec.url, connect_options=spec.connect_options()), - jetstream=jetstream, - topic_callbacks={subject: topic_callbacks[subject] for subject in jetstream.subjects}, - ) - binding.limit = self._max_concurrent_runs + binding = self._new_named_binding(spec, jetstream) self._named.append(binding) served.update(jetstream.subjects) if self._named: @@ -595,12 +624,16 @@ def _refuse_result_publishing(self) -> None: def _start_named_links(self) -> None: """Connect and bind every named connection in a loop of its own; one failing never holds up another.""" for binding in self._named: - running = self._named_tasks.get(binding.link.name) - if running is not None and not running.done(): - continue - task = asyncio.ensure_future(self._run_named_link(binding)) - task.add_done_callback(functools.partial(self._on_named_link_done, binding)) - self._named_tasks[binding.link.name] = task + self._start_named_link(binding) + + def _start_named_link(self, binding: _Binding) -> None: + """Start ``binding``'s connect-and-bind loop, unless one is running.""" + running = self._named_tasks.get(binding) + if running is not None and not running.done(): + return + task = asyncio.ensure_future(self._run_named_link(binding)) + task.add_done_callback(functools.partial(self._on_named_link_done, binding)) + self._named_tasks[binding] = task async def _run_named_link(self, binding: _Binding) -> None: """Connect ``binding``'s link and bind, retrying until it works. @@ -611,6 +644,7 @@ async def _run_named_link(self, binding: _Binding) -> None: delay = float(self.config.get("event_client_retry_delay", 5.0)) attempt = 0 while True: + binding.link.permission_errors.clear() try: await self._open_named_link(binding.link) if self._consumption_paused: @@ -618,12 +652,30 @@ async def _run_named_link(self, binding: _Binding) -> None: binding.subscriptions.clear() await self._bind(binding) binding.subscriptions_ready = True + if binding.replaces is not None: + # New before old (spec 7.4): only now that this one delivers is the old one retired. + old, binding.replaces = binding.replaces, None + self._start_retirement(old, "replaced") return except asyncio.CancelledError: raise except Exception as exc: attempt += 1 binding.subscriptions_ready = False + denied = list(binding.link.permission_errors) + if denied: + # The broker reports a missing grant through error_cb and lets the request time + # out: that is permanent, not a slow broker (spec 7.9). + logger.error( + "Agent '%s': named connection '%s' was refused a permission (%s); retrying every %.0fs until " + "the deployment grants it", + self.namespace or ROOT_LABEL, + binding.link.name, + "; ".join(denied), + PERMISSION_RETRY_SECONDS, + ) + await asyncio.sleep(PERMISSION_RETRY_SECONDS) + continue logger.warning( "Agent '%s': named connection '%s' attempt %d failed, retrying in %.1fs: %s", self.namespace or ROOT_LABEL, @@ -654,6 +706,8 @@ async def _open_named_link(self, link: _Link) -> None: agent = self.namespace or ROOT_LABEL async def on_disconnected() -> None: + if link.closing or self._closing: + return for binding in self._named: if binding.link is link: binding.subscriptions_ready = False @@ -669,6 +723,8 @@ async def on_reconnected() -> None: async def on_error(error: Exception) -> None: # Permission violations land here: a subject the deployment did not grant this account. + if "permissions violation" in str(error).lower(): + link.permission_errors.append(str(error)) logger.error("Agent '%s': error on named connection '%s': %s", agent, link.name, error) link.nats_client = await nats.connect( @@ -684,6 +740,203 @@ async def on_error(error: Exception) -> None: ) logger.info("Agent '%s' connected named connection '%s' as '%s'", agent, link.name, link.connection_name) + # ------------------------------------------------------------------ + # Named connections at runtime (named-connections plan, step 4) + # ------------------------------------------------------------------ + + def _new_named_binding(self, spec: ConnectionSpec, jetstream: JetStreamBinding) -> _Binding: + """A binding for ``spec``: a link of its own (plan D1), the declared callbacks, the agent's run limit.""" + binding = _Binding( + link=_Link(name=spec.name, url=spec.url, connect_options=spec.connect_options()), + jetstream=jetstream, + topic_callbacks={subject: self._declared[subject] for subject in jetstream.subjects}, + spec=spec, + ) + binding.limit = self._max_concurrent_runs + return binding + + def _resolve_change_grace(self) -> float: + """Return ``subscription_change_grace``: seconds a removed connection's runs get before revocation.""" + raw = self.config.get("subscription_change_grace", None) + value = ( + float(self.config.get("event_client_drain_timeout", 30.0)) + if raw is None + else self._read_float("subscription_change_grace", 0.0) + ) + if value <= 0: + raise ValueError(f"'subscription_change_grace' must be greater than 0, got {value}.") + return value + + def _watch_source(self) -> None: + """Ask the source to tell this client when its connections change, if the source can (``watch`` is optional).""" + self._loop = asyncio.get_running_loop() + watch = getattr(self._source, "watch", None) if self._source is not None else None + if callable(watch): + watch(self._connections_changed) + + def _connections_changed(self) -> None: + """The source's notify: callable from any thread; hops onto this client's loop and coalesces.""" + loop = self._loop + if loop is None or loop.is_closed() or self._closing: + return + loop.call_soon_threadsafe(self._schedule_reconcile) + + def _schedule_reconcile(self) -> None: + """Run one reconcile at a time; a change notified while one runs makes it run once more.""" + if self._closing: + return + if self._reconcile_task is not None and not self._reconcile_task.done(): + self._reconcile_dirty = True + return + self._reconcile_task = asyncio.ensure_future(self._reconcile_loop()) + self._reconcile_task.add_done_callback(self._on_reconcile_done) + + def _on_reconcile_done(self, task: asyncio.Task[None]) -> None: + """Report a reconcile that died of anything but its cancellation, naming the agent.""" + if not task.cancelled() and task.exception() is not None: + logger.error( + "Agent '%s': applying a change of its named connections failed: %s", + self.namespace or ROOT_LABEL, + task.exception(), + exc_info=task.exception(), + ) + + async def _reconcile_loop(self) -> None: + while True: + self._reconcile_dirty = False + async with self._change_lock: + await self._reconcile() + if not self._reconcile_dirty: + return + + async def _reconcile(self) -> None: + """Bring the named bindings in line with what the source says now: add, replace, retire. + + Runs under the agent's change lock, so it never interleaves with a pause or a resume. The + default connection's subjects stay as computed at startup: a subject a connection stops + serving is not moved back to it, and a connection added later takes only what it claims. + """ + source = self._source + if source is None or self._closing: + return + agent = self.namespace or ROOT_LABEL + declared = tuple(self._declared) + wanted: dict[str, tuple[ConnectionSpec, JetStreamBinding]] = {} + for spec in source.connections().values(): + jetstream = source.binding(self._queue_group, declared, spec) + if jetstream is None: + continue + unknown = [subject for subject in jetstream.subjects if subject not in self._declared] + if unknown: + logger.error( + "Agent '%s': connection '%s' skipped -- its binding claims %s, which the agent does not declare", + agent, + spec.name, + ", ".join(unknown), + ) + continue + wanted[spec.name] = (spec, jetstream) + + current = {binding.link.name: binding for binding in self._named if not binding.superseded} + created: list[_Binding] = [] + maps_results = bool(self.config.get("event_publishing.topic_mapping", {}) or {}) + for name, (spec, jetstream) in wanted.items(): + existing = current.get(name) + if existing is not None and existing.spec == spec and existing.jetstream == jetstream: + continue + if existing is None and maps_results: + logger.error( + "Agent '%s': connection '%s' not added -- the agent maps handler results to topics, and a result " + "would leave the connection its event arrived on (plan D4)", + agent, + name, + ) + continue + binding = self._new_named_binding(spec, jetstream) + if existing is not None: + existing.superseded = True + binding.replaces = existing + self._named.append(binding) + created.append(binding) + logger.info("Agent '%s': connection '%s' %s", agent, name, "changed; binding the new one" if existing else "added") + self._register_pairs(self._default_pairs + len(self._named)) + if not self._consumption_paused: + # Only the new ones: a binding that is already bound must not bind a second time. + for binding in created: + self._start_named_link(binding) + + for name, binding in current.items(): + if name not in wanted: + await self._retire(binding, "removed") + + def _start_retirement(self, binding: _Binding, reason: str) -> None: + """Retire ``binding`` in the background, under the change lock (a replacement that just bound).""" + + async def retire() -> None: + async with self._change_lock: + await self._retire(binding, reason) + + task = asyncio.ensure_future(retire()) + self._retirements.add(task) + task.add_done_callback(self._retirement_done) + + def _retirement_done(self, task: asyncio.Task[None]) -> None: + self._retirements.discard(task) + if not task.cancelled() and task.exception() is not None: + logger.error( + "Agent '%s': retiring a named connection failed: %s", + self.namespace or ROOT_LABEL, + task.exception(), + exc_info=task.exception(), + ) + + async def _retire(self, binding: _Binding, reason: str) -> None: + """Stop consuming on ``binding``, give its runs the grace period, revoke the rest, close its link. + + Drained, not unsubscribed: what the client already holds still reaches a handler and is + settled over this link. A run still going when the grace period ends is revoked -- never + acked or nak'd (the delivery stays with the broker), its heartbeat stopped, its ``publish`` + refused, but not cancelled (spec 7.5). No consumer is deleted: it is the deployment's. + """ + if binding not in self._named: + return + agent = self.namespace or ROOT_LABEL + task = self._named_tasks.pop(binding, None) + if task is not None and not task.done(): + task.cancel() + with contextlib.suppress(asyncio.CancelledError, Exception): + await task + binding.subscriptions_ready = False + loop = asyncio.get_running_loop() + deadline = loop.time() + self._change_grace + await self._drain_subscriptions(deadline, binding) + if binding.inflight: + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(binding.idle.wait(), timeout=max(0.0, deadline - loop.time())) + revoked = binding.inflight + if revoked: + binding.revoked = True + for heartbeat in list(binding.heartbeats): + heartbeat.cancel() + logger.warning( + "Agent '%s': connection '%s' %s with %d run(s) still in flight after %.1fs; revoked -- they are not " + "settled and stay with the broker", + agent, + binding.link.name, + reason, + revoked, + self._change_grace, + ) + client = binding.link.nats_client + if client is not None: + binding.link.closing = True + with contextlib.suppress(Exception): + await client.close() + binding.link.nats_client = None + self._named.remove(binding) + self._register_pairs(self._default_pairs + len(self._named)) + logger.info("Agent '%s': connection '%s' %s and closed (%d run(s) revoked)", agent, binding.link.name, reason, revoked) + def _start_retry_task(self) -> None: """Start the background connect-and-subscribe loop, unless one is already running.""" if self._retry_task is not None and not self._retry_task.done(): @@ -1352,17 +1605,18 @@ async def pause_consumption(self) -> None: return self._consumption_paused = True self._subscriptions_ready = False - timeout = float(self.config.get("event_client_drain_timeout", 30.0)) - deadline = asyncio.get_running_loop().time() + timeout - for binding in self._named: - binding.subscriptions_ready = False - await self._drain_subscriptions(deadline, binding) - if self._nats_client is not None: - await self._drain_subscriptions(deadline) - for binding in self._named: - await self._await_inflight(deadline, binding) - if self._nats_client is not None: - await self._await_inflight(deadline) + async with self._change_lock: # never interleaved with a connection change (spec 7.2) + timeout = float(self.config.get("event_client_drain_timeout", 30.0)) + deadline = asyncio.get_running_loop().time() + timeout + for binding in self._named: + binding.subscriptions_ready = False + await self._drain_subscriptions(deadline, binding) + if self._nats_client is not None: + await self._drain_subscriptions(deadline) + for binding in self._named: + await self._await_inflight(deadline, binding) + if self._nats_client is not None: + await self._await_inflight(deadline) logger.error( "Agent '%s' stopped consuming: its subscriptions are drained while it is degraded, so its events " "redeliver to a healthy replica", @@ -1382,7 +1636,8 @@ async def resume_consumption(self) -> None: if not self._subscriptions_managed: return # Each named connection re-binds in its own loop, over its still-open link. - self._start_named_links() + async with self._change_lock: + self._start_named_links() if self._nats_client is None: # Paused before it ever connected -- subscribe() registered the topics and waited. # The retry loop is what connects and subscribes; a loop still running picks up the @@ -1411,6 +1666,13 @@ async def close(self) -> None: self._subscriptions_ready = False self._closing = True + # A change in progress is cancelled, not finished: everything it left is cleaned up below. + for change in [self._reconcile_task, *self._retirements]: + if change is not None and not change.done(): + change.cancel() + with contextlib.suppress(asyncio.CancelledError, Exception): + await change + if self._retry_task and not self._retry_task.done(): self._retry_task.cancel() with contextlib.suppress(asyncio.CancelledError): @@ -1526,7 +1788,13 @@ async def publish(self, topic: str, event: CloudEvent[Any], routing_key: str | N topic: The topic, used for event routing. event: The CloudEvent to publish. routing_key: Ignored — NATS does not use routing keys. + + Raises: + DeliveryRevokedError: called from a run whose connection was removed under it. """ + running_on = _CURRENT_BINDING.get() + if running_on is not None and running_on.revoked: + raise DeliveryRevokedError() client = await self.client try: @@ -2030,6 +2298,7 @@ async def _run_delivery(self, msg: Any, topic: str, callback: DeliveryCallback, connection = binding.link.name if connection and self._source is not None: mark_connection(connection) + _CURRENT_BINDING.set(binding) if not await self._accepted(msg, topic, cloud_event, binding): return @@ -2043,6 +2312,15 @@ async def _run_delivery(self, msg: Any, topic: str, callback: DeliveryCallback, async with limit: async with self._run_scope(connection): await callback(cloud_event, subject) + except DeliveryRevokedError: + disposition = DeliveryDisposition.NAK # never sent: a revoked delivery is not settled + logger.warning( + "Agent '%s': event %s on topic '%s' from connection '%s' was revoked; its result is discarded", + self.namespace or ROOT_LABEL, + cloud_event.id, + topic, + connection, + ) except Exception as ex: if isinstance(ex, TimeoutError) and limit.expired(): disposition = DeliveryDisposition.NAK @@ -2083,6 +2361,16 @@ async def _run_delivery(self, msg: Any, topic: str, callback: DeliveryCallback, # A heartbeat never fails the run (handler-time-bounds spec sec. 4.1). with contextlib.suppress(asyncio.CancelledError, Exception): await heartbeat + if binding.revoked: + # Its connection was removed and the grace period ran out (spec 7.5): no ack, no nak. + logger.warning( + "Agent '%s': event %s on topic '%s' finished after its connection '%s' was retired; not settled", + self.namespace or ROOT_LABEL, + cloud_event.id, + topic, + connection, + ) + return await self._settle(msg, disposition, topic, cloud_event.id, binding) async def _accepted(self, msg: Any, topic: str, cloud_event: CloudEvent[Any], binding: _Binding) -> bool: @@ -2159,6 +2447,8 @@ def _start_heartbeat(self, msg: Any, topic: str, binding: _Binding) -> asyncio.T return None heartbeat = asyncio.create_task(self._keep_alive(msg, ack_wait / 3), name=f"nats-heartbeat-{self.namespace or ROOT_LABEL}") heartbeat.add_done_callback(self._heartbeat_finished) + binding.heartbeats.add(heartbeat) + heartbeat.add_done_callback(binding.heartbeats.discard) return heartbeat def _heartbeat_finished(self, heartbeat: asyncio.Task[None]) -> None: diff --git a/src/blueprint/agents/clients/io/nats_connections.py b/src/blueprint/agents/clients/io/nats_connections.py index 9046b09c..c3dc6ff5 100644 --- a/src/blueprint/agents/clients/io/nats_connections.py +++ b/src/blueprint/agents/clients/io/nats_connections.py @@ -92,10 +92,21 @@ class ConnectionSource(Protocol): The factory named by ``nats_connection_source`` is called with the process ``Config`` and returns the source. Every agent of the process shares it, so it must hold no per-run state. + + **Runtime changes (optional).** A source may also define ``watch(notify)``: every agent's client + calls it once with a ``notify`` callable, and the source calls ``notify()`` -- from any thread -- + whenever its connections may have changed. The client then reads :meth:`connections` and + :meth:`binding` again and applies the difference: a new connection is bound; a changed one + (another :class:`ConnectionSpec` or :class:`JetStreamBinding`) gets a new link, bound before the + old one is retired; a removed one is drained, its runs get ``subscription_change_grace`` seconds, + and what still runs then is revoked -- never acked or nak'd, ``publish`` refused with + ``DeliveryRevokedError``, not cancelled. No consumer is ever deleted. A source without ``watch`` + is read once, at startup. ``watch`` is not part of this protocol's ``isinstance`` check, so such + a source still qualifies. The agent's default connection keeps the subjects it had at startup. """ def connections(self) -> Mapping[str, ConnectionSpec]: - """The connections to open, by name. Read at startup.""" + """The connections to open, by name. Read at startup, and again after each ``notify()``.""" ... def binding(self, agent: str, subjects: tuple[str, ...], connection: ConnectionSpec) -> "JetStreamBinding | None": diff --git a/src/blueprint/agents/models/errors.py b/src/blueprint/agents/models/errors.py index d51def5c..5ed55ce9 100644 --- a/src/blueprint/agents/models/errors.py +++ b/src/blueprint/agents/models/errors.py @@ -35,6 +35,20 @@ def __init__(self, *, status: str, reason: str, code: str | None = None): super().__init__(status=status, reason=reason, code=code) +class DeliveryRevokedError(Exception): + """The connection this event arrived on was removed while it was being handled. + + Raised by framework calls made on behalf of a revoked delivery -- ``publish`` from within + its run -- after the grace period of a connection change ran out (dynamic-subscriptions + spec sec. 7.5). Deliberately not a :class:`HandlerError`: every ``HandlerError`` maps to a + settlement, and a revoked delivery is never settled. A handler may catch it to store or + compensate its work its own way; if it escapes, the framework logs it and sends nothing. + """ + + def __init__(self) -> None: + super().__init__("the subscription this event arrived on was removed while it was being handled; its result cannot be delivered") + + class DeliveryDisposition(Enum): """What a transport does with a delivery once dispatch has finished. diff --git a/tests/unit/agents/clients/io/test_nats_runtime_changes.py b/tests/unit/agents/clients/io/test_nats_runtime_changes.py new file mode 100644 index 00000000..8d30a438 --- /dev/null +++ b/tests/unit/agents/clients/io/test_nats_runtime_changes.py @@ -0,0 +1,401 @@ +"""Named connections changed at runtime through ConnectionSource.watch (named-connections plan, step 4b).""" + +import asyncio +import json +import logging +import threading +from contextlib import nullcontext +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from nats.js import api as js_api + +from blueprint.agents.clients.io import nats_client as nats_client_module +from blueprint.agents.clients.io.nats_client import NATSClient +from blueprint.agents.clients.io.nats_connections import ConnectionSource, ConnectionSpec, JetStreamBinding +from blueprint.agents.models.errors import DeliveryRevokedError +from blueprint.agents.models.events import CloudEvent + + +def _binding(name: str, *subjects: str, ack_wait: float = 600.0) -> JetStreamBinding: + return JetStreamBinding( + subjects=subjects or ("risk.>",), + stream=f"S_{name}", + durable=f"d-{name}", + deliver_subject=f"deliver.{name}", + deliver_group="g", + ack_wait=ack_wait, + subject_prefix=f"t.{name}.", + max_deliver=5, + deliver_policy=js_api.DeliverPolicy.NEW, + ) + + +class WatchedSource: + """A source whose connections the test changes, telling the client through watch().""" + + def __init__(self, **connections: JetStreamBinding) -> None: + self.bindings = dict(connections) + self.passwords: dict[str, str] = {} + self.notifiers: list[Any] = [] + self.reads = 0 + + def watch(self, notify: Any) -> None: + self.notifiers.append(notify) + + def change(self, **connections: JetStreamBinding) -> None: + self.bindings = dict(connections) + self.notify() + + def notify(self) -> None: + for notify in self.notifiers: + notify() + + def connections(self) -> dict[str, ConnectionSpec]: + self.reads += 1 + return { + name: ConnectionSpec(name=name, url="nats://h:4222", user="u", password=self.passwords.get(name, "PLACEHOLDER-1")) + for name in self.bindings + } + + def binding(self, agent: str, subjects: tuple[str, ...], connection: ConnectionSpec) -> JetStreamBinding | None: + return self.bindings.get(connection.name) + + def validate(self, connection: str, subject: str, event: CloudEvent[Any]) -> str | None: + return None + + def run_scope(self, connection: str) -> Any: + return nullcontext() + + +class Broker: + """Stands in for nats.connect: one mocked core client per opened link, in the order they were opened.""" + + def __init__(self) -> None: + self.events: list[str] = [] + self.links: dict[str, list[MagicMock]] = {} + self.fail_next: dict[str, int] = {} + + async def open(self, link: Any) -> None: + if self.fail_next.get(link.name, 0): + self.fail_next[link.name] -= 1 + raise ConnectionError(f"{link.name} not reachable yet") + core = MagicMock(is_closed=False) + sub = MagicMock(drain=AsyncMock(), unsubscribe=AsyncMock()) + + async def subscribe(*args: Any, **kwargs: Any) -> MagicMock: + self.events.append(f"bind {link.name}#{len(self.links[link.name])}") + return sub + + async def close() -> None: + self.events.append(f"close {link.name}#{self.links[link.name].index(core) + 1}") + + core.subscribe = AsyncMock(side_effect=subscribe) + core.close = AsyncMock(side_effect=close) + core.sub = sub + self.links.setdefault(link.name, []).append(core) + link.nats_client = core + + +@pytest.fixture +def broker() -> Broker: + return Broker() + + +@pytest.fixture +def configured(nats_client: NATSClient, mock_config: MagicMock) -> Any: + """Override config keys of the nats_client fixture: configured(**{key: value}).""" + base = mock_config.get.side_effect + + def apply(**values: Any) -> None: + mock_config.get.side_effect = lambda key, default=None: values[key] if key in values else base(key, default) + + apply(event_client_retry_delay=0.01, subscription_change_grace=0.05) + return apply + + +async def _started(nats_client: NATSClient, source: WatchedSource, broker: Broker, topics: tuple[str, ...] = ("risk.>",)) -> None: + nats_client.set_connection_source(source) # type: ignore[arg-type] + with patch.object(nats_client, "_start_retry_task"): + await nats_client.subscribe({topic: AsyncMock() for topic in topics}) + await _settled(nats_client) + + +async def _settled(nats_client: NATSClient) -> None: + for _ in range(50): + await asyncio.sleep(0.01) + busy = [t for t in nats_client._named_tasks.values() if not t.done()] + reconcile = nats_client._reconcile_task + if not busy and (reconcile is None or reconcile.done()) and not nats_client._retirements: + return + + +def _delivery(name: str) -> MagicMock: + event = CloudEvent(id=f"ev-{name}", type="risk.created", source="t") + msg = MagicMock(data=json.dumps(dict(event)).encode(), reply="$JS.ACK.x", subject=f"t.{name}.risk.created") + for verb in ("ack", "nak", "term", "in_progress"): + setattr(msg, verb, AsyncMock()) + msg.metadata.num_delivered = 1 + return msg + + +@pytest.fixture(autouse=True) +def fake_broker(nats_client: NATSClient, broker: Broker, configured: Any) -> Any: + with patch.object(nats_client, "_open_named_link", side_effect=broker.open): + yield + + +class TestTheSourceStaysOptional: + def test_a_source_without_watch_is_still_a_connection_source(self) -> None: + class Static: + def connections(self) -> dict: + return {} + + def binding(self, agent: str, subjects: tuple, connection: Any) -> None: + return None + + def validate(self, connection: str, subject: str, event: Any) -> None: + return None + + def run_scope(self, connection: str) -> Any: + return nullcontext() + + assert isinstance(Static(), ConnectionSource) + + async def test_watch_is_registered_at_subscribe(self, nats_client: NATSClient, broker: Broker) -> None: + source = WatchedSource(A=_binding("A")) + await _started(nats_client, source, broker) + assert source.notifiers == [nats_client._connections_changed] + + +class TestAddRemoveChange: + async def test_an_added_connection_is_bound_and_counted(self, nats_client: NATSClient, broker: Broker) -> None: + source = WatchedSource(A=_binding("A")) + await _started(nats_client, source, broker) + pairs = nats_client._pool.pairs + + source.change(A=_binding("A"), C=_binding("C")) + await _settled(nats_client) + + assert nats_client.named_connections == ("A", "C") + assert "bind C#1" in broker.events + assert nats_client._pool.pairs == pairs + 1 + + async def test_a_removed_connection_is_drained_and_closed(self, nats_client: NATSClient, broker: Broker) -> None: + source = WatchedSource(A=_binding("A"), B=_binding("B")) + await _started(nats_client, source, broker) + pairs = nats_client._pool.pairs + + source.change(A=_binding("A")) + await _settled(nats_client) + + assert nats_client.named_connections == ("A",) + broker.links["B"][0].sub.drain.assert_awaited_once() + assert "close B#1" in broker.events + assert nats_client._pool.pairs == pairs - 1 + + async def test_a_changed_connection_binds_the_new_link_before_closing_the_old(self, nats_client: NATSClient, broker: Broker) -> None: + source = WatchedSource(A=_binding("A")) + await _started(nats_client, source, broker) + + source.passwords["A"] = "PLACEHOLDER-2" + source.notify() + await _settled(nats_client) + + assert broker.events == ["bind A#1", "bind A#2", "close A#1"] + assert nats_client.named_connections == ("A",) + assert nats_client._named[0].link.nats_client is broker.links["A"][1] + + async def test_the_old_link_keeps_serving_until_the_new_one_binds(self, nats_client: NATSClient, broker: Broker) -> None: + source = WatchedSource(A=_binding("A")) + await _started(nats_client, source, broker) + broker.fail_next["A"] = 3 + + source.passwords["A"] = "PLACEHOLDER-2" + source.notify() + await asyncio.sleep(0.015) + assert "close A#1" not in broker.events, "nothing closed while the new link cannot bind" + await _settled(nats_client) + assert broker.events[-2:] == ["bind A#2", "close A#1"] + + async def test_an_unchanged_connection_is_left_alone(self, nats_client: NATSClient, broker: Broker) -> None: + source = WatchedSource(A=_binding("A")) + await _started(nats_client, source, broker) + source.notify() + await _settled(nats_client) + assert broker.events == ["bind A#1"] + + +class TestSkipped: + async def test_an_undeclared_subject_skips_that_connection_only( + self, nats_client: NATSClient, broker: Broker, caplog: pytest.LogCaptureFixture + ) -> None: + source = WatchedSource(A=_binding("A")) + await _started(nats_client, source, broker) + with caplog.at_level(logging.ERROR): + source.change(A=_binding("A"), C=_binding("C", "invented.>")) + await _settled(nats_client) + assert nats_client.named_connections == ("A",) + assert any("connection 'C' skipped" in message for message in caplog.messages) + + async def test_an_agent_mapping_results_gains_no_connection( + self, nats_client: NATSClient, broker: Broker, configured: Any, caplog: pytest.LogCaptureFixture + ) -> None: + """Plan D4 at runtime: a result would leave the connection its event arrived on.""" + configured(event_client_retry_delay=0.01, **{"event_publishing.topic_mapping": {"x": {"topic": "out"}}}) + source = WatchedSource() + await _started(nats_client, source, broker) + with caplog.at_level(logging.ERROR): + source.change(A=_binding("A")) + await _settled(nats_client) + assert nats_client.named_connections == () + assert any("plan D4" in message for message in caplog.messages) + + +class TestRevocation: + async def _in_flight( + self, nats_client: NATSClient, broker: Broker, ack_wait: float = 600.0, publish: bool = True + ) -> tuple[Any, MagicMock, asyncio.Event, list]: + source = WatchedSource(A=_binding("A"), B=_binding("B", ack_wait=ack_wait)) + await _started(nats_client, source, broker) + gate, outcome = asyncio.Event(), [] + + async def handler(event: CloudEvent, subject: str) -> None: + await gate.wait() + if not publish: + return + try: + await nats_client.publish("out.done", event) + except DeliveryRevokedError as exc: + outcome.append(exc) + raise + + b = next(binding for binding in nats_client._named if binding.link.name == "B") + b.topic_callbacks["risk.>"] = handler + msg = _delivery("B") + await broker.links["B"][0].subscribe.await_args.kwargs["cb"](msg) + await asyncio.sleep(0) + source.change(A=_binding("A")) + return b, msg, gate, outcome + + async def test_a_run_outliving_the_grace_is_never_settled(self, nats_client: NATSClient, broker: Broker) -> None: + b, msg, gate, outcome = await self._in_flight(nats_client, broker) + await _settled(nats_client) + assert b.revoked and b not in nats_client._named + gate.set() + await asyncio.gather(*list(b.runs), return_exceptions=True) + for verb in ("ack", "nak", "term"): + getattr(msg, verb).assert_not_awaited() + + async def test_publishing_from_a_revoked_run_is_refused(self, nats_client: NATSClient, broker: Broker) -> None: + b, msg, gate, outcome = await self._in_flight(nats_client, broker) + await _settled(nats_client) + gate.set() + await asyncio.gather(*list(b.runs), return_exceptions=True) + assert len(outcome) == 1 and isinstance(outcome[0], DeliveryRevokedError) + + async def test_its_heartbeat_stops_at_revocation(self, nats_client: NATSClient, broker: Broker) -> None: + b, msg, gate, outcome = await self._in_flight(nats_client, broker, ack_wait=0.03) + await _settled(nats_client) + beats = msg.in_progress.await_count + await asyncio.sleep(0.05) + assert msg.in_progress.await_count == beats, "no in_progress after revocation" + gate.set() + await asyncio.gather(*list(b.runs), return_exceptions=True) + + async def test_a_run_finishing_within_the_grace_is_settled_normally( + self, nats_client: NATSClient, broker: Broker, configured: Any + ) -> None: + configured(event_client_retry_delay=0.01, subscription_change_grace=5.0) + b, msg, gate, outcome = await self._in_flight(nats_client, broker, publish=False) + await asyncio.sleep(0.02) + gate.set() + await _settled(nats_client) + assert not b.revoked + msg.ack.assert_awaited_once() + + +class TestScheduling: + async def test_notifications_during_a_change_coalesce_into_one_more_pass(self, nats_client: NATSClient, broker: Broker) -> None: + source = WatchedSource(A=_binding("A")) + await _started(nats_client, source, broker) + reads = source.reads + for _ in range(5): + source.notify() + await _settled(nats_client) + assert source.reads - reads <= 2 + + async def test_a_notify_from_another_thread_is_applied_on_the_loop(self, nats_client: NATSClient, broker: Broker) -> None: + source = WatchedSource(A=_binding("A")) + await _started(nats_client, source, broker) + source.bindings["C"] = _binding("C") + thread = threading.Thread(target=source.notify) + thread.start() + thread.join() + await _settled(nats_client) + assert nats_client.named_connections == ("A", "C") + + async def test_a_pause_waits_for_a_change_in_progress(self, nats_client: NATSClient, broker: Broker, configured: Any) -> None: + configured(event_client_retry_delay=0.01, subscription_change_grace=0.2) + source = WatchedSource(A=_binding("A"), B=_binding("B")) + await _started(nats_client, source, broker) + b = next(binding for binding in nats_client._named if binding.link.name == "B") + b.enter_run() # a run in flight keeps the retirement in its grace period + source.change(A=_binding("A")) + await asyncio.sleep(0.02) + order: list[str] = [] + pause = asyncio.create_task(nats_client.pause_consumption()) + await asyncio.sleep(0.05) + order.append("pause still waiting" if not pause.done() else "pause done") + await pause + order.append("pause done") + assert order == ["pause still waiting", "pause done"] + assert b not in nats_client._named + + async def test_close_during_a_change_cancels_it_and_cleans_up(self, nats_client: NATSClient, broker: Broker, configured: Any) -> None: + configured(event_client_retry_delay=0.01, subscription_change_grace=10.0, event_client_drain_timeout=0.05) + source = WatchedSource(A=_binding("A"), B=_binding("B")) + await _started(nats_client, source, broker) + b = next(binding for binding in nats_client._named if binding.link.name == "B") + b.enter_run() + source.change(A=_binding("A")) + await asyncio.sleep(0.02) + await asyncio.wait_for(nats_client.close(), timeout=2) + assert nats_client._reconcile_task is not None and nats_client._reconcile_task.done() + assert {"close A#1", "close B#1"} <= set(broker.events) + + +class TestPermissionViolations: + async def test_a_refused_permission_backs_off_and_says_so( + self, nats_client: NATSClient, broker: Broker, caplog: pytest.LogCaptureFixture + ) -> None: + source = WatchedSource(A=_binding("A")) + calls = 0 + + async def denied(link: Any) -> None: + nonlocal calls + calls += 1 + if calls == 1: + link.permission_errors.append("nats: permissions violation for subscription to deliver.A") + raise TimeoutError() + await broker.open(link) + + with ( + patch.object(nats_client, "_open_named_link", side_effect=denied), + patch.object(nats_client_module, "PERMISSION_RETRY_SECONDS", 0.01), + caplog.at_level(logging.ERROR), + ): + await _started(nats_client, source, broker) + assert any("refused a permission" in message and "deliver.A" in message for message in caplog.messages) + assert calls == 2 + + async def test_the_error_callback_records_permission_violations(self, nats_client: NATSClient) -> None: + from blueprint.agents.clients.io.nats_client import _Link + + link = _Link(name="A", url="nats://h:4222") + with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock) as connect: + await NATSClient._open_named_link(nats_client, link) + await connect.await_args.kwargs["error_cb"](Exception("nats: permissions violation for publish to $JS.API.X")) + await connect.await_args.kwargs["error_cb"](Exception("nats: unexpected EOF")) + assert link.permission_errors == ["nats: permissions violation for publish to $JS.API.X"] From 44e903845e39e235caafbe298c122a817fca0dcd Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 09:33:50 +0200 Subject: [PATCH 082/133] feat(nats): ConnectionSource.claims keeps tenant subjects off the default connection Step 4c of the named-connections plan. The source says which subjects belong to named connections, independently of the connections that exist now; those never go to the agent's default connection. A fresh deployment without any connection therefore subscribes nothing there (before, every subject landed on the default connection for good). A declared subject the source does not claim fails startup unless nats_unclaimed_subjects = "default_connection" allows the hybrid. Verified in WSL with a process account allowed nothing: 3 permission violations before, 0 after; a tenant added at runtime is served. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 4 ++ ...26-08-28-multi-agent-grouping-changelog.md | 22 ++++++++ .../docs/reference/configuration-keys.md | 1 + .../agents/clients/io/nats_client.py | 51 ++++++++++++++++--- .../agents/clients/io/nats_connections.py | 12 +++++ .../clients/io/test_nats_connection_source.py | 49 +++++++++++++++--- .../clients/io/test_nats_runtime_changes.py | 6 +++ 7 files changed, 130 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f80c0dc8..a336ad98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -177,6 +177,10 @@ - **`asbs validate` warns about a swallowed `asyncio.CancelledError`** in an agent's `src/` (and for every agent with `--group`), with file and line: such code keeps a run going past `nats_handler_timeout`, and the delivery is nak'd and redelivered anyway. +- **`ConnectionSource.claims(agent, subjects)` and `nats_unclaimed_subjects`.** The source says which + subjects belong to named connections, independently of which connections exist; those never go to + the agent's default connection, so a fresh deployment without a tenant subscribes nothing there. A + subject not claimed fails startup unless `nats_unclaimed_subjects = "default_connection"` allows it. - **Named NATS connections (`nats_connection_source`).** A deployment can give its agents further NATS connections -- one account and one existing JetStream consumer each -- through a connection source named by a process-scope key. The framework binds to the deployment's consumers verbatim and never provisions on them, checks each delivery with the source's validation hook before it runs, runs it in an empty context inside the source's scope, and settles, heartbeats and dead-letters it on its own connection. Agents keep declaring their subjects as before and see them without the connection's prefix; `nats_connection` names the connection in the handler context. Unset, nothing changes. - **`nats_max_concurrent_runs`** (number or `"N%"`, unset by default): how many deliveries an (agent, connection) pair runs at once per process; unset keeps one run per subscription. The pair's first run diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 1bee93ee..c6d2dfc1 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8490,6 +8490,28 @@ disagreed; 0 permission violations. **Control for (2):** the old link closed abr with the link, redelivered after `ack_wait` as duplicates. That is what binding first and draining then prevents. +### Claimed subjects never reach the default connection (named connections, step 4c) + +Decided with the owner after 4b: the hybrid of named and default connection is allowed only +explicitly, and an undeclared mapping fails startup. + +- `ConnectionSource.claims(agent, subjects)` (required): the subjects that belong to named + connections, from the deployment's scheme, independent of the connections that exist now. +- `NATSClient._plan_named_bindings`: `_claimed_subjects` (a claim must name declared subjects); + unclaimed subjects fail startup unless `_resolve_unclaimed_policy` reads `nats_unclaimed_subjects = + "default_connection"`; a binding may serve claimed subjects only; the default binding gets the + unclaimed subjects only. `_reconcile` skips a connection whose binding serves an unclaimed subject. +- Before this, a start without any connection put every subject on the default connection for good, + and a tenant added later was served in addition. + +Tests: 8 new cases in `test_nats_connection_source.py`; the fakes implement `claims`. Live, three +accounts with a process account allowed nothing: before 4c a fresh start subscribed `risk.>` / +`issue.>` on the default connection -- 3 permission violations -- and kept them after tenant A +arrived; with 4c nothing on the default connection, 0 violations, tenant A's 3 events handled; an +unclaimed `scheduler.tick` fails startup with the message; with `"default_connection"` it is +subscribed there (1 violation, because that test's process account may subscribe nothing -- the +deployment must allow it). + --- ## Open points diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 22a64fe9..7b555e05 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -51,6 +51,7 @@ Settings for the event bus transport layer. | `nats_connection_source` | `str` | unset -- the agent consumes on its one connection, as before | **Process scope.** `"package.module:attribute"` naming a factory that is called with the process `Config` and returns a `ConnectionSource` (`blueprint.agents.clients.io.nats_connections`). The source lists named connections -- each with its own URL and account -- and, per agent and connection, a `JetStreamBinding`: which declared subjects the connection serves, the subject prefix, and the deployment's durable consumer with its wire values verbatim. Those subjects leave the agent's default connection. Each delivery from a named connection is checked by the source's `validate` before anything runs (a reason terminates it), runs in an empty context inside the source's `run_scope`, and is settled on the connection it arrived on; the handler sees the subject without the prefix and the connection's name under the context key `nats_connection`. JetStream only. An agent with named connections may not map handler results to topics. A source that also defines `watch(notify)` is followed at runtime: connections added, changed or removed are applied while the agent runs (`subscription_change_grace`). A wrong path fails startup. | | `nats_handler_timeout` | `float` | unset -- no limit | Seconds one run may take, on every connection of the agent. At the limit the run is cancelled and its delivery nak'd for immediate redelivery, so a hung model request no longer holds its slot forever; after `nats_max_deliver` attempts the delivery is given up as usual. A `TimeoutError` the handler raises itself is an ordinary failure. A handler that catches the cancellation and carries on keeps its slot until it returns, which is logged, and its delivery is nak'd all the same. Set it above the longest legitimate run. | | `subscription_change_grace` | `float` | `event_client_drain_timeout` | Seconds the runs of a named connection that is removed or replaced at runtime get to finish. A run still going after that is revoked: it is never acked or nak'd -- the delivery stays with the broker and returns after `ack_wait` -- its heartbeat stops, and a `publish` from it raises `DeliveryRevokedError`; it is not cancelled. | +| `nats_unclaimed_subjects` | `str` | `"fail"` | Only with a `nats_connection_source`. What happens to a declared subject the source does not `claims()` for the agent: `"fail"` -- the agent's startup fails, naming the subjects; `"default_connection"` -- consumed on the agent's own connection (the explicit hybrid mode; the process account must then be allowed to subscribe them). A claimed subject never goes to the default connection, even while no named connection serves it yet. | | `nats_heartbeat_enabled` | `bool` | `true` | Whether a running JetStream delivery reports `in_progress` every third of its consumer's `ack_wait`, so a run longer than `ack_wait` is not redelivered while it still runs. Switch it off only for an agent whose runs always finish well inside `ack_wait`; off, a long run is delivered again to another replica. Must be a boolean -- the string `"false"` is refused, because it would read as true. | | `nats_max_deliver` | `int` | unset -- the server's default (NATS: unlimited) | Delivery attempts before the message is dead-lettered. Unlimited -- the default, or `-1` -- means a permanently failing message is retried forever and never dead-lettered; the client logs a warning at startup if you set `-1` explicitly. Set a positive limit to bound retries. | | `nats_dead_letter_subject` | `str` | `".dead-letter"` | Subject a message is republished to when the framework gives up on it -- either a terminal failure (`InvalidEventError`, `CriticalHandlerError`, or a payload that is not a CloudEvent) or `nats_max_deliver` attempts spent. The original bytes are republished unchanged, with `Blueprint-Dead-Letter-Reason`, `Blueprint-Original-Subject`, `Blueprint-Delivery-Count` and `Blueprint-Event-Id` headers. Set to `""` to disable, which drops those messages and loses their payloads. Startup fails if the subject is a wildcard or is itself one of the subscribed subjects, since that would loop. | diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 20155000..978028a7 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -343,6 +343,7 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: self._named: list[_Binding] = [] self._named_tasks: dict[_Binding, asyncio.Task[None]] = {} self._declared: dict[str, DeliveryCallback] = {} + self._claimed: frozenset[str] = frozenset() self._default_pairs = 0 self._change_grace = 30.0 self._change_lock = asyncio.Lock() @@ -582,16 +583,26 @@ def _plan_named_bindings(self, topic_callbacks: dict[str, DeliveryCallback]) -> if self._source is None: return dict(topic_callbacks) declared = tuple(topic_callbacks) + self._claimed = self._claimed_subjects(declared) + unclaimed = [subject for subject in declared if subject not in self._claimed] + if unclaimed and self._resolve_unclaimed_policy() == "fail": + raise ValueError( + f"Agent '{self.namespace or ROOT_LABEL}' declares {', '.join(unclaimed)}, which the connection source does " + "not claim, so no named connection will ever serve it. Declare only subjects the deployment's " + "connections carry, or set 'nats_unclaimed_subjects = \"default_connection\"' to consume these on the " + "agent's own connection." + ) served: set[str] = set() for spec in self._source.connections().values(): jetstream = self._source.binding(self._queue_group, declared, spec) if jetstream is None: continue - unknown = [subject for subject in jetstream.subjects if subject not in topic_callbacks] + unknown = [subject for subject in jetstream.subjects if subject not in self._claimed] if unknown: raise ValueError( - f"Agent '{self.namespace or ROOT_LABEL}': the binding for connection '{spec.name}' claims " - f"{', '.join(unknown)}, which the agent does not declare. A binding serves declared subjects only." + f"Agent '{self.namespace or ROOT_LABEL}': the binding for connection '{spec.name}' serves " + f"{', '.join(unknown)}, which the source does not claim for this agent. A binding serves claimed " + "subjects only." ) binding = self._new_named_binding(spec, jetstream) self._named.append(binding) @@ -599,13 +610,37 @@ def _plan_named_bindings(self, topic_callbacks: dict[str, DeliveryCallback]) -> if self._named: self._refuse_result_publishing() logger.info( - "Agent '%s' consumes on %d named connection(s) %s; %d subject(s) stay on its default connection", + "Agent '%s' consumes on %d named connection(s) %s; %d claimed subject(s) served by none yet; %d unclaimed " + "subject(s) on its default connection", self.namespace or ROOT_LABEL, len(self._named), ", ".join(binding.link.name for binding in self._named) or "-", - len(declared) - len(served), + len(self._claimed - served), + len(unclaimed), ) - return {topic: callback for topic, callback in topic_callbacks.items() if topic not in served} + # Claimed subjects never go to the default connection, served now or not (plan D10). + return {topic: callback for topic, callback in topic_callbacks.items() if topic not in self._claimed} + + def _claimed_subjects(self, declared: tuple[str, ...]) -> frozenset[str]: + """The source's claim on this agent's subjects; refused unless it names declared subjects only.""" + if self._source is None: + return frozenset() + claimed = frozenset(self._source.claims(self._queue_group, declared)) + foreign = sorted(claimed - set(declared)) + if foreign: + raise ValueError( + f"Agent '{self.namespace or ROOT_LABEL}': the connection source claims {', '.join(foreign)}, which the " + "agent does not declare. A claim names declared subjects only." + ) + return claimed + + def _resolve_unclaimed_policy(self) -> str: + """``nats_unclaimed_subjects``: ``"fail"`` (default) or ``"default_connection"`` (the explicit hybrid mode).""" + raw = self.config.get("nats_unclaimed_subjects", None) + policy = str(raw or "fail").strip().lower() + if policy not in ("fail", "default_connection"): + raise ValueError(f"'nats_unclaimed_subjects' must be 'fail' or 'default_connection', got {raw!r}.") + return policy def _refuse_result_publishing(self) -> None: """Fail startup when an agent with named connections maps handler results to topics (plan D4). @@ -826,10 +861,10 @@ async def _reconcile(self) -> None: jetstream = source.binding(self._queue_group, declared, spec) if jetstream is None: continue - unknown = [subject for subject in jetstream.subjects if subject not in self._declared] + unknown = [subject for subject in jetstream.subjects if subject not in self._claimed] if unknown: logger.error( - "Agent '%s': connection '%s' skipped -- its binding claims %s, which the agent does not declare", + "Agent '%s': connection '%s' skipped -- its binding serves %s, which the source does not claim", agent, spec.name, ", ".join(unknown), diff --git a/src/blueprint/agents/clients/io/nats_connections.py b/src/blueprint/agents/clients/io/nats_connections.py index c3dc6ff5..2db6bdf9 100644 --- a/src/blueprint/agents/clients/io/nats_connections.py +++ b/src/blueprint/agents/clients/io/nats_connections.py @@ -105,6 +105,18 @@ class ConnectionSource(Protocol): a source still qualifies. The agent's default connection keeps the subjects it had at startup. """ + def claims(self, agent: str, subjects: tuple[str, ...]) -> tuple[str, ...]: + """Which of ``agent``'s declared subjects belong to named connections -- whatever connections exist now. + + Answered from the deployment's subject scheme, not from the current connections: with no + connection yet (a fresh environment, no tenant yet) a claimed subject is still claimed, so it + is consumed nowhere until a connection serves it, and never on the agent's default connection. + A subject not claimed goes to the default connection only where ``nats_unclaimed_subjects = + "default_connection"`` allows it; by default (``"fail"``) it fails the agent's startup. + Must be a subset of ``subjects``. A binding may serve claimed subjects only. + """ + ... + def connections(self) -> Mapping[str, ConnectionSpec]: """The connections to open, by name. Read at startup, and again after each ``notify()``.""" ... diff --git a/tests/unit/agents/clients/io/test_nats_connection_source.py b/tests/unit/agents/clients/io/test_nats_connection_source.py index 923f1526..4e89ebf4 100644 --- a/tests/unit/agents/clients/io/test_nats_connection_source.py +++ b/tests/unit/agents/clients/io/test_nats_connection_source.py @@ -43,11 +43,15 @@ def _binding(prefix: str, *subjects: str) -> JetStreamBinding: class FakeSource: """A deployment's source: two connections, and a scope that sets a ContextVar per connection.""" - def __init__(self, bindings: dict[str, JetStreamBinding | None], reject: Any = None) -> None: + def __init__(self, bindings: dict[str, JetStreamBinding | None], reject: Any = None, claimed: tuple[str, ...] | None = None) -> None: self.bindings = bindings self.reject = reject + self.claimed = claimed # None: every declared subject, as in the first consumer of named connections self.asked: list[tuple[str, tuple[str, ...], str]] = [] + def claims(self, agent: str, subjects: tuple[str, ...]) -> tuple[str, ...]: + return subjects if self.claimed is None else self.claimed + def connections(self) -> dict[str, ConnectionSpec]: return {name: ConnectionSpec(name=name, url="nats://localhost:4222") for name in self.bindings} @@ -148,17 +152,48 @@ def test_an_unusable_spec_is_refused(self, kwargs: dict) -> None: class TestPlanningTheBindings: - async def test_served_subjects_leave_the_default_connection(self, nats_client: NATSClient) -> None: + async def test_claimed_subjects_never_go_to_the_default_connection(self, nats_client: NATSClient) -> None: source = FakeSource({"A": _binding("A", "risk.>", "issue.>"), "B": _binding("B", "risk.>"), "C": None}) - await _subscribed(nats_client, source, ("risk.>", "issue.>", "scheduler.tick")) + await _subscribed(nats_client, source, ("risk.>", "issue.>", "audit.>")) assert nats_client.named_connections == ("A", "B") + assert list(nats_client._topic_callbacks) == [], "audit.> is claimed: served by no connection yet, but never by the default one" + assert source.asked == [("test-agent", ("risk.>", "issue.>", "audit.>"), name) for name in ("A", "B", "C")] + + async def test_no_connection_yet_is_no_error_and_subscribes_nothing(self, nats_client: NATSClient) -> None: + """A fresh environment without tenants: nothing to consume yet, nothing on the default connection.""" + await _subscribed(nats_client, FakeSource({}), ("risk.>", "issue.>")) + assert nats_client.named_connections == () + assert list(nats_client._topic_callbacks) == [] + + async def test_an_unclaimed_subject_fails_startup_by_default(self, nats_client: NATSClient) -> None: + source = FakeSource({"A": _binding("A", "risk.>")}, claimed=("risk.>",)) + with pytest.raises(ValueError, match="scheduler.tick.*does not claim.*nats_unclaimed_subjects"): + await _subscribed(nats_client, source, ("risk.>", "scheduler.tick")) + + async def test_the_hybrid_mode_must_be_asked_for(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + base = mock_config.get.side_effect + mock_config.get.side_effect = lambda key, default=None: ( + "default_connection" if key == "nats_unclaimed_subjects" else base(key, default) + ) + source = FakeSource({"A": _binding("A", "risk.>")}, claimed=("risk.>",)) + await _subscribed(nats_client, source, ("risk.>", "scheduler.tick")) assert list(nats_client._topic_callbacks) == ["scheduler.tick"] - assert source.asked == [("test-agent", ("risk.>", "issue.>", "scheduler.tick"), name) for name in ("A", "B", "C")] - async def test_a_binding_may_not_claim_an_undeclared_subject(self, nats_client: NATSClient) -> None: - with pytest.raises(ValueError, match="does not declare"): - await _subscribed(nats_client, FakeSource({"A": _binding("A", "invented.>")}), ("risk.>",)) + async def test_an_unknown_policy_is_refused(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + base = mock_config.get.side_effect + mock_config.get.side_effect = lambda key, default=None: "hybrid" if key == "nats_unclaimed_subjects" else base(key, default) + with pytest.raises(ValueError, match="nats_unclaimed_subjects"): + await _subscribed(nats_client, FakeSource({}, claimed=("risk.>",)), ("risk.>", "x.>")) + + async def test_a_claim_names_declared_subjects_only(self, nats_client: NATSClient) -> None: + with pytest.raises(ValueError, match="claims invented.>, which the agent does not declare"): + await _subscribed(nats_client, FakeSource({}, claimed=("risk.>", "invented.>")), ("risk.>",)) + + async def test_a_binding_serves_claimed_subjects_only(self, nats_client: NATSClient) -> None: + source = FakeSource({"A": _binding("A", "invented.>")}, claimed=("risk.>",)) + with pytest.raises(ValueError, match="serves invented.>, which the source does not claim"): + await _subscribed(nats_client, source, ("risk.>",)) async def test_without_a_source_nothing_changes(self, nats_client: NATSClient) -> None: with patch.object(nats_client, "_start_retry_task"), patch.object(nats_client, "_start_named_links"): diff --git a/tests/unit/agents/clients/io/test_nats_runtime_changes.py b/tests/unit/agents/clients/io/test_nats_runtime_changes.py index 8d30a438..097c5fa4 100644 --- a/tests/unit/agents/clients/io/test_nats_runtime_changes.py +++ b/tests/unit/agents/clients/io/test_nats_runtime_changes.py @@ -52,6 +52,9 @@ def notify(self) -> None: for notify in self.notifiers: notify() + def claims(self, agent: str, subjects: tuple[str, ...]) -> tuple[str, ...]: + return subjects # every declared subject is a tenant subject, as in the first consumer of named connections + def connections(self) -> dict[str, ConnectionSpec]: self.reads += 1 return { @@ -149,6 +152,9 @@ def fake_broker(nats_client: NATSClient, broker: Broker, configured: Any) -> Any class TestTheSourceStaysOptional: def test_a_source_without_watch_is_still_a_connection_source(self) -> None: class Static: + def claims(self, agent: str, subjects: tuple) -> tuple: + return subjects + def connections(self) -> dict: return {} From 108ee0195f133624904aa9f6c022330b8b15b6b6 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 10:06:23 +0200 Subject: [PATCH 083/133] test(integration): delivery features and named connections against a real broker Concurrent runs (K and one run per subscription), heartbeat on and off, the hard handler limit, the run pool's guaranteed first run, and named connections against a second broker with one account per tenant: isolation, validate rejection, unclaimed subjects, the explicit hybrid, and runtime add/switch/remove without loss or duplicates. Co-Authored-By: Claude Opus 5.5 (1M context) --- ...26-08-28-multi-agent-grouping-changelog.md | 31 ++ tests/integration/conftest.py | 92 ++++++ tests/integration/connection_source.py | 108 +++++++ tests/integration/docker-compose.yml | 18 ++ tests/integration/nats-accounts.conf | 48 +++ .../integration/test_delivery_concurrency.py | 170 +++++++++++ tests/integration/test_named_connections.py | 273 ++++++++++++++++++ 7 files changed, 740 insertions(+) create mode 100644 tests/integration/connection_source.py create mode 100644 tests/integration/nats-accounts.conf create mode 100644 tests/integration/test_delivery_concurrency.py create mode 100644 tests/integration/test_named_connections.py diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index c6d2dfc1..d52b1b9f 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8512,6 +8512,31 @@ unclaimed `scheduler.tick` fails startup with the message; with `"default_connec subscribed there (1 violation, because that test's process account may subscribe nothing -- the deployment must allow it). +### Broker integration tests for the delivery features and named connections + +The acceptance runs of steps 1 to 4c, as repeatable tests in `tests/integration`. + +- `test_delivery_concurrency.py`: up to K runs at once on one subscription; unset, one run per + subscription with subscriptions in parallel; heartbeat keeps a run longer than `ack_wait` from + being redelivered, and switched off it is redelivered while it runs; `nats_handler_timeout` cuts a + hung run, which comes back at once (`nak`) while the others flow; an exhausted run pool never holds + back a pair's first run. +- `test_named_connections.py`: two tenants on their own accounts, 16 runs, no run whose connection, + scope tenant and event tenant disagree, consumer config unchanged, 0 permission violations; an + event `validate` rejects never runs and is `term`ed; an unclaimed subject fails startup; with + `nats_unclaimed_subjects = "default_connection"` it is served there; a connection added, its + credentials switched and removed at runtime, none lost, none duplicated. +- `docker-compose.yml` gains `nats-accounts` (4223) with `nats-accounts.conf`: process account + allowed nothing (and a hybrid user allowed `hybrid.>`), one account per tenant with an admin and + agent users allowed only their deliver subjects and `$JS.ACK.>`. Test-only placeholder passwords. +- `conftest.py`: `settings_group` (a group from settings the test writes, waiting for named + bindings), `base_settings`, `accounts_url`; `connection_source.py` is the test `ConnectionSource`. + +11 new tests, about 15 s together. Two full integration runs on fresh brokers: 52 passed, 2 failed +each, both failures pre-existing and failing at HEAD as well (`test_two_processes_share_cache`: +the subprocess does not find `blueprint`; `test_the_broker_counts_it_as_a_redelivery`: now +deterministic, see Open points). + --- ## Open points @@ -8526,6 +8551,12 @@ deployment must allow it). replicas ran one tick), passing alone. Likely `DiskCacheService.claim`'s documented non-atomic takeover of an expired claim, or a run straddling a minute boundary; not investigated. +- **`test_the_broker_counts_it_as_a_redelivery` now fails every time** (2026-10-15, also with the + test changes stashed). The consumer info it reads shows `num_pending=0, num_redelivered=0`: the + retryable failure is `nak`ed at once, so all `max_deliver` attempts are used up within + milliseconds and the message has left the pending set before the test reads the count, which + then no longer includes it. Likely the assertion, not the client; not fixed here. + - ~~**A startup-failure latch is never released.**~~ **Closed** -- see *A latched agent recovers, and readiness shows it* above. A non-critical agent whose `on_startup` raised is latched by `AppBuilder._mark_agent_down` -> `NamespaceSupervisor.mark_down`, and nothing in diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index ffca9ae8..fda35b69 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -19,6 +19,10 @@ docker compose -f tests/integration/docker-compose.yml up -d pytest tests/ -m integration + +``nats`` (4222) is a plain JetStream broker, ``redis`` (6379) the shared cache, and +``nats-accounts`` (4223) a second broker with one account per tenant and per-user permissions +(``nats-accounts.conf``) -- the named-connection tests need a broker that can refuse. """ import asyncio @@ -352,3 +356,91 @@ async def factory(agents: dict[str, type], *, ready_timeout: float = 20.0) -> As Component.reset_shared_state() return factory + + +# --------------------------------------------------------------------------- +# A group built from settings the test writes (the NATS delivery features) +# --------------------------------------------------------------------------- + + +GroupFactory = Callable[..., Any] + + +def _ready(client: NATSClient, named: int) -> bool: + """Default subscriptions up and, if asked, bound on that many named connections.""" + return client.subscriptions_ready and len([binding for binding in client._named if binding.subscriptions_ready]) >= named + + +@pytest.fixture +def settings_group(tmp_path: Path) -> GroupFactory: + """Return a context manager yielding the clients of a group built from the given settings lines. + + Used as:: + + async with settings_group(settings, {"orders_x": OrdersHandler}) as clients: + ... + + The test writes every key itself, because the features under test are configured per test + (run limits, heartbeat, timeouts, a connection source). Waits until every agent's default + subscriptions are ready and, when ``named`` is set, until each agent is bound on that many + named connections. + """ + + @asynccontextmanager + async def factory( + settings: str, agents: dict[str, type], *, named: int = 0, ready_timeout: float = 20.0 + ) -> AsyncIterator[dict[str, NATSClient]]: + (tmp_path / "settings.toml").write_text(settings, encoding="utf-8") + config = Config(settings_files=["settings.toml"], root_path=str(tmp_path)) + group = AgentGroup("integration", {name: AppBuilder().with_handler(handler) for name, handler in agents.items()}) + try: + app = group.assemble(config) + async with app.router.lifespan_context(app): + registry = Component.shared_registry + assert registry is not None + clients = {name: registry.get_component(NATSClient, namespace=name) for name in agents} + for name, client in clients.items(): + await wait_until( + lambda client=client: _ready(client, named), # type: ignore[misc] + timeout=ready_timeout, + description=f"agent '{name}' to subscribe (and bind {named} named connection(s))", + ) + yield clients + finally: + Component.reset_shared_state() + + return factory + + +def base_settings(nats_url: str, stream: str, extra: str = "") -> str: + """The settings every delivery test starts from: one stream for the test, JetStream on.""" + return ( + "[default]\n" + 'app_name = "blueprint-it"\n' + 'app_environment = "development"\n' + "app_port = 8000\n" + 'model_provider = "openai"\n' + 'event_bus = "nats"\n' + f'nats_url = "{nats_url}"\n' + f'nats_stream_name = "{stream}"\n' + "nats_use_jetstream = true\n" + "event_client_max_retries = 2\n" + "event_client_retry_delay = 0.5\n" + extra + ) + + +# --------------------------------------------------------------------------- +# The broker with accounts (named connections) +# --------------------------------------------------------------------------- + + +NATS_ACCOUNTS_URL = os.environ.get("BLUEPRINT_TEST_NATS_ACCOUNTS_URL", "nats://127.0.0.1:4223") +"""The broker with one account per tenant (``nats-accounts`` in docker-compose.yml).""" + + +@pytest.fixture(scope="session") +def accounts_url() -> str: + """The accounts broker's URL, or skip: the named-connection tests need its permissions.""" + if not server_is_listening(NATS_ACCOUNTS_URL): + pytest.skip(f"No NATS server with accounts at {NATS_ACCOUNTS_URL}. Start it with: {COMPOSE_HINT}") + return NATS_ACCOUNTS_URL diff --git a/tests/integration/connection_source.py b/tests/integration/connection_source.py new file mode 100644 index 00000000..fe29c26e --- /dev/null +++ b/tests/integration/connection_source.py @@ -0,0 +1,108 @@ +"""A connection source as a tenant deployment writes one, for test_named_connections.py. + +One named connection per tenant, each logging in as that tenant's agent user on the accounts broker +(nats-accounts.conf). Everything per test comes from the process config the factory is called with, +because that is all the framework hands it: ``test_source_url``, ``test_source_prefix`` (keeps +streams and subjects apart between tests), ``test_source_tenants`` and ``test_source_unclaimed``. +""" + +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from contextvars import ContextVar +from typing import Any + +from nats.js import api as js_api + +from blueprint.agents.clients.io.nats_connections import ConnectionSpec, JetStreamBinding + +SCOPE: ContextVar[str | None] = ContextVar("integration_tenant_scope", default=None) +"""Set by run_scope inside each run: what a deployment would set for its tenant.""" + +SOURCES: list["TenantSource"] = [] +"""Every source built in this process, so a test can change its connections at runtime.""" + +PASSWORDS = { + "agent-a": "agent-a-test-only", + "agent-a2": "agent-a2-test-only", + "agent-b": "agent-b-test-only", +} + + +def stream_for(prefix: str, tenant: str) -> str: + return f"S_{prefix.upper()}_{tenant}" + + +def subject_prefix_for(prefix: str, tenant: str) -> str: + return f"t.{tenant}.{prefix}." + + +def binding_for(prefix: str, agent: str, subjects: tuple[str, ...], tenant: str) -> JetStreamBinding: + """The binding of one agent on one tenant: also what the operator creates the consumer from.""" + return JetStreamBinding( + subjects=subjects, + stream=stream_for(prefix, tenant), + durable=f"d-{agent}", + deliver_subject=f"acme.agent.{tenant}.{agent}", + deliver_group=agent, + ack_wait=10.0, + subject_prefix=subject_prefix_for(prefix, tenant), + max_deliver=3, + deliver_policy=js_api.DeliverPolicy.NEW, + ) + + +class TenantSource: + """Tenants from the config; the users can be changed at runtime and announced through watch().""" + + def __init__(self, config: Any) -> None: + self.url = str(config.get("test_source_url")) + self.prefix = str(config.get("test_source_prefix")) + self.users = {tenant: f"agent-{tenant.lower()}" for tenant in config.get("test_source_tenants") or []} + self.unclaimed = tuple(config.get("test_source_unclaimed") or ()) + self.notifiers: list[Callable[[], None]] = [] + SOURCES.append(self) + + def claims(self, agent: str, subjects: tuple[str, ...]) -> tuple[str, ...]: + return tuple(subject for subject in subjects if subject not in self.unclaimed) + + def watch(self, notify: Callable[[], None]) -> None: + self.notifiers.append(notify) + + def set_users(self, users: dict[str, str]) -> None: + """Replace the tenants and their users, and tell every client.""" + self.users = dict(users) + for notify in self.notifiers: + notify() + + def connections(self) -> dict[str, ConnectionSpec]: + return { + tenant: ConnectionSpec(name=tenant, url=self.url, user=user, password=PASSWORDS[user]) for tenant, user in self.users.items() + } + + def binding(self, agent: str, subjects: tuple[str, ...], connection: ConnectionSpec) -> JetStreamBinding: + return binding_for(self.prefix, agent, self.claims(agent, subjects), connection.name) + + def validate(self, connection: str, subject: str, event: Any) -> str | None: + """W17.2 in miniature: connection, subject token and the event's tenantid must agree.""" + token = subject.split(".")[1] if subject.count(".") >= 2 else None + if token != connection: + return f"subject tenant {token} is not the connection's" + claimed = (event.model_extra or {}).get("tenantid") + if claimed != connection: + return f"event tenantid {claimed} is not the connection's" + return None + + def run_scope(self, connection: str) -> Any: + @contextmanager + def scope() -> Iterator[None]: + token = SCOPE.set(connection) + try: + yield + finally: + SCOPE.reset(token) + + return scope() + + +def create_source(config: Any) -> TenantSource: + return TenantSource(config) diff --git a/tests/integration/docker-compose.yml b/tests/integration/docker-compose.yml index cc73c059..0fc6a3ad 100644 --- a/tests/integration/docker-compose.yml +++ b/tests/integration/docker-compose.yml @@ -33,6 +33,24 @@ services: retries: 5 start_period: 5s + nats-accounts: + # A second broker, with accounts and permissions: what a deployment with one account per tenant + # looks like. The named-connection tests run against it; see nats-accounts.conf. + image: nats:2.10-alpine + container_name: blueprint-test-nats-accounts + command: ["-c", "/etc/nats/accounts.conf"] + volumes: + - ./nats-accounts.conf:/etc/nats/accounts.conf:ro + ports: + - "4223:4222" + - "8223:8222" + healthcheck: + test: ["CMD", "wget", "--spider", "-q", "http://localhost:8222/healthz"] + interval: 5s + timeout: 3s + retries: 5 + start_period: 5s + redis: image: redis:7-alpine container_name: blueprint-test-redis diff --git a/tests/integration/nats-accounts.conf b/tests/integration/nats-accounts.conf new file mode 100644 index 00000000..c6530cbf --- /dev/null +++ b/tests/integration/nats-accounts.conf @@ -0,0 +1,48 @@ +# A broker with accounts, for the named-connection tests (tests/integration/test_named_connections.py). +# +# It stands for a deployment whose tenants own their accounts: one account per tenant, provisioned +# by someone else, and an agent user in it that may receive from its deliver subjects and +# acknowledge, nothing else. The process account is allowed nothing at all, so any subscription the +# framework made on an agent's default connection shows up as a permissions violation. +# +# Test-only credentials: every password here is a placeholder, never used anywhere else. + +port: 4222 +http_port: 8222 +jetstream: { store_dir: "/tmp/nats-accounts" } + +accounts: { + PROC: { + users: [ + { user: proc, password: proc-test-only, permissions: { publish: { deny: [">"] }, subscribe: { deny: [">"] } } } + # The explicit hybrid mode (nats_unclaimed_subjects = "default_connection") needs a process + # connection that may receive its own, unclaimed subjects over Core NATS. + { user: proc-hybrid, password: proc-hybrid-test-only, permissions: { publish: { allow: ["hybrid.>"] }, subscribe: { allow: ["hybrid.>"] } } } + ] + } + TA: { + jetstream: enabled + users: [ + { user: admin-a, password: admin-a-test-only } + { user: agent-a, password: agent-a-test-only, permissions: { + publish: { allow: ["$JS.ACK.>"] } + subscribe: { allow: ["acme.agent.A.>"] } + } } + # A second agent user of the same account: rotated credentials, for the runtime change test. + { user: agent-a2, password: agent-a2-test-only, permissions: { + publish: { allow: ["$JS.ACK.>"] } + subscribe: { allow: ["acme.agent.A.>"] } + } } + ] + } + TB: { + jetstream: enabled + users: [ + { user: admin-b, password: admin-b-test-only } + { user: agent-b, password: agent-b-test-only, permissions: { + publish: { allow: ["$JS.ACK.>"] } + subscribe: { allow: ["acme.agent.B.>"] } + } } + ] + } +} diff --git a/tests/integration/test_delivery_concurrency.py b/tests/integration/test_delivery_concurrency.py new file mode 100644 index 00000000..1c433853 --- /dev/null +++ b/tests/integration/test_delivery_concurrency.py @@ -0,0 +1,170 @@ +"""Concurrent runs, the heartbeat, the hard limit and the run pool, against a real broker. + +The unit tests assert what the client decides; these assert what a broker then does with it: +that runs really overlap, that a long run is not redelivered while it still runs, that a hung run is +cut and comes back, and that a pair's first run is never held back by the process pool. Every case +here runs in seconds: ack waits and limits are scaled down, and the waits are on observed state. +""" + +import asyncio +import uuid +from dataclasses import dataclass, field +from typing import Any + +from nats.aio.client import Client as NatsClient + +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.events import GenericCloudEvent + +from .conftest import base_settings +from .helpers import wait_until + + +@dataclass +class Runs: + """What a recording handler saw: which events started and finished, and a gate it waits on.""" + + started: list[str] = field(default_factory=list) + finished: list[str] = field(default_factory=list) + gate: asyncio.Event = field(default_factory=asyncio.Event) + + +def recording_handler(topics: list[str], runs: Runs, *, duration: float = 0.0, gated: bool = False, hang: str | None = None) -> type: + """A handler that records its runs; it may wait on the gate, sleep, or hang on one label.""" + + class Recording(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return topics + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> None: + label = str((event.data or {}).get("label")) + runs.started.append(label) + if label == hang: + await asyncio.Event().wait() # never set: only the hard limit ends this run + if gated: + await runs.gate.wait() + if duration: + await asyncio.sleep(duration) + runs.finished.append(label) + return None + + return Recording + + +async def publish(connection: NatsClient, subject: str, label: str) -> None: + event = GenericCloudEvent(id=str(uuid.uuid4()), source="integration-test", type="thing.happened", data={"label": label}) + await connection.jetstream().publish(subject, event.model_dump_json().encode()) + + +async def stays(predicate: Any, seconds: float = 0.3) -> bool: + """Whether ``predicate`` holds for ``seconds`` -- a limit must not merely be reached, it must hold.""" + loop = asyncio.get_running_loop() + end = loop.time() + seconds + while loop.time() < end: + if not predicate(): + return False + await asyncio.sleep(0.05) + return True + + +class TestConcurrentRuns: + async def test_up_to_k_runs_at_once_on_one_subscription( + self, settings_group: Any, nats_url: str, jetstream_stream: str, subject_prefix: str, nats_connection: NatsClient + ) -> None: + runs, topic = Runs(), f"{subject_prefix}.orders.created" + agent = f"orders_{subject_prefix}" + settings = base_settings(nats_url, jetstream_stream, "nats_max_concurrent_runs = 3\n") + async with settings_group(settings, {agent: recording_handler([topic], runs, gated=True)}): + for n in range(5): + await publish(nats_connection, topic, f"e{n}") + await wait_until(lambda: len(runs.started) == 3, timeout=10, description="three runs to start") + assert await stays(lambda: len(runs.started) == 3), "never more than K runs at once" + runs.gate.set() + await wait_until(lambda: len(runs.finished) == 5, timeout=10, description="all five runs to finish") + + async def test_unset_one_run_per_subscription_and_subscriptions_in_parallel( + self, settings_group: Any, nats_url: str, jetstream_stream: str, subject_prefix: str, nats_connection: NatsClient + ) -> None: + runs = Runs() + created, cancelled = f"{subject_prefix}.orders.created", f"{subject_prefix}.orders.cancelled" + agent = f"orders_{subject_prefix}" + async with settings_group( + base_settings(nats_url, jetstream_stream), {agent: recording_handler([created, cancelled], runs, gated=True)} + ): + for subject in (created, created, cancelled, cancelled): + await publish(nats_connection, subject, subject.rsplit(".", 1)[1]) + await wait_until(lambda: len(runs.started) == 2, timeout=10, description="one run per subscription to start") + assert await stays(lambda: len(runs.started) == 2) + assert sorted(runs.started) == ["cancelled", "created"], "the two subscriptions run in parallel, one run each" + runs.gate.set() + await wait_until(lambda: len(runs.finished) == 4, timeout=10, description="all four runs to finish") + + +class TestHeartbeat: + async def test_a_run_longer_than_ack_wait_is_delivered_once( + self, settings_group: Any, nats_url: str, jetstream_stream: str, subject_prefix: str, nats_connection: NatsClient + ) -> None: + runs, topic = Runs(), f"{subject_prefix}.orders.created" + settings = base_settings(nats_url, jetstream_stream, "nats_ack_wait = 1.0\n") + async with settings_group(settings, {f"orders_{subject_prefix}": recording_handler([topic], runs, duration=2.5)}): + await publish(nats_connection, topic, "long") + await wait_until(lambda: runs.finished == ["long"], timeout=10, description="the long run to finish") + assert await stays(lambda: runs.started == ["long"], 1.5), "a live run is never redelivered" + + async def test_switched_off_a_long_run_is_redelivered_while_it_runs( + self, settings_group: Any, nats_url: str, jetstream_stream: str, subject_prefix: str, nats_connection: NatsClient + ) -> None: + runs, topic = Runs(), f"{subject_prefix}.orders.created" + settings = base_settings( + nats_url, jetstream_stream, "nats_ack_wait = 1.0\nnats_heartbeat_enabled = false\nnats_max_concurrent_runs = 2\n" + ) + async with settings_group(settings, {f"orders_{subject_prefix}": recording_handler([topic], runs, duration=2.5)}): + await publish(nats_connection, topic, "long") + await wait_until(lambda: runs.started.count("long") >= 2, timeout=6, description="the redelivery of the live run") + + +class TestHardLimit: + async def test_a_hung_run_is_cut_and_redelivered_and_the_others_flow( + self, settings_group: Any, nats_url: str, jetstream_stream: str, subject_prefix: str, nats_connection: NatsClient + ) -> None: + runs, topic = Runs(), f"{subject_prefix}.orders.created" + settings = base_settings(nats_url, jetstream_stream, "nats_handler_timeout = 0.5\nnats_ack_wait = 10.0\nnats_max_deliver = 3\n") + async with settings_group(settings, {f"orders_{subject_prefix}": recording_handler([topic], runs, hang="hung")}): + await publish(nats_connection, topic, "hung") + for n in range(3): + await publish(nats_connection, topic, f"ok{n}") + await wait_until(lambda: sorted(runs.finished) == ["ok0", "ok1", "ok2"], timeout=10, description="the other events to run") + await wait_until(lambda: runs.started.count("hung") >= 2, timeout=10, description="the cut run to be redelivered at once (nak)") + assert "hung" not in runs.finished + + +class TestRunPool: + async def test_a_pairs_first_run_is_never_held_back_by_an_exhausted_pool( + self, settings_group: Any, nats_url: str, jetstream_stream: str, subject_prefix: str, nats_connection: NatsClient + ) -> None: + busy, idle = Runs(), Runs() + busy_topic, idle_topic = f"{subject_prefix}.busy.created", f"{subject_prefix}.idle.created" + settings = base_settings(nats_url, jetstream_stream, "nats_max_concurrent_runs = 3\nnats_extra_runs_per_process = 1\n") + agents = { + f"busy_{subject_prefix}": recording_handler([busy_topic], busy, gated=True), + f"idle_{subject_prefix}": recording_handler([idle_topic], idle, gated=True), + } + async with settings_group(settings, agents): + for n in range(3): + await publish(nats_connection, busy_topic, f"b{n}") + await wait_until(lambda: len(busy.started) == 2, timeout=10, description="the busy pair's guaranteed run plus the pool's one") + assert await stays(lambda: len(busy.started) == 2), "the pool of one is exhausted" + await publish(nats_connection, idle_topic, "i0") + await wait_until(lambda: idle.started == ["i0"], timeout=10, description="the idle pair's first run, despite the pool") + busy.gate.set() + idle.gate.set() + await wait_until(lambda: len(busy.finished) == 3 and idle.finished == ["i0"], timeout=10, description="everything to finish") diff --git a/tests/integration/test_named_connections.py b/tests/integration/test_named_connections.py new file mode 100644 index 00000000..90460991 --- /dev/null +++ b/tests/integration/test_named_connections.py @@ -0,0 +1,273 @@ +"""Named connections against a broker with one account per tenant (nats-accounts in docker-compose.yml). + +What a tenant deployment depends on, observed rather than asserted on the client's own state: + +- the framework binds to consumers the operator made, sends no JetStream API request, and its + process connection subscribes nothing -- so the restricted accounts report no permission violation; +- a run sees one tenant only: its connection, the source's run scope and the event's tenant agree; +- a delivery the source rejects never runs and is termed; +- a subject the source does not claim fails startup unless the hybrid mode is asked for; +- connections added, changed and removed at runtime lose and duplicate nothing. +""" + +import json +import logging +import uuid +from collections.abc import AsyncIterator, Awaitable, Callable +from typing import Any + +import nats +import pytest + +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.events import GenericCloudEvent + +from .connection_source import SCOPE, SOURCES, binding_for, stream_for, subject_prefix_for +from .helpers import poll_until, wait_until + +ADMINS = {"A": ("admin-a", "admin-a-test-only"), "B": ("admin-b", "admin-b-test-only")} + + +def recording_handler(topics: list[str], runs: list[dict[str, Any]]) -> type: + class Recording(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return topics + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> None: + runs.append( + { + "id": event.id, + "connection": context.get("nats_connection"), + "scope": SCOPE.get(), + "tenant": (event.model_extra or {}).get("tenantid"), + "subject": context.get("nats_subject"), + } + ) + return None + + return Recording + + +Operator = Callable[[list[str], dict[str, list[str]]], Awaitable[None]] + + +@pytest.fixture +async def operator(accounts_url: str, subject_prefix: str) -> AsyncIterator[Operator]: + """Provision what the deployment owns: a stream per tenant and the agents' consumers. Removed after the test.""" + made: set[str] = set() + + async def provision(tenants: list[str], agents: dict[str, list[str]]) -> None: + for tenant in tenants: + user, password = ADMINS[tenant] + admin = await nats.connect(accounts_url, user=user, password=password) + jsm = admin.jsm() + stream = stream_for(subject_prefix, tenant) + if tenant not in made: + await jsm.add_stream(name=stream, subjects=[f"{subject_prefix_for(subject_prefix, tenant)}>"]) + made.add(tenant) + for agent, subjects in agents.items(): + await jsm.add_consumer(stream, config=binding_for(subject_prefix, agent, tuple(subjects), tenant).consumer_config()) + await admin.close() + + yield provision + + for tenant in made: + user, password = ADMINS[tenant] + admin = await nats.connect(accounts_url, user=user, password=password) + try: + await admin.jsm().delete_stream(stream_for(subject_prefix, tenant)) + finally: + await admin.close() + + +async def publish(accounts_url: str, prefix: str, tenant: str, subject: str, *, claimed_tenant: str | None = None) -> str: + user, password = ADMINS[tenant] + admin = await nats.connect(accounts_url, user=user, password=password) + event_id = str(uuid.uuid4()) + body = {"specversion": "1.0", "id": event_id, "type": subject, "source": "integration-test", "tenantid": claimed_tenant or tenant} + await admin.jetstream().publish(f"{subject_prefix_for(prefix, tenant)}{subject}", json.dumps(body).encode()) + await admin.close() + return event_id + + +async def consumer_info(accounts_url: str, prefix: str, tenant: str, agent: str) -> Any: + user, password = ADMINS[tenant] + admin = await nats.connect(accounts_url, user=user, password=password) + try: + return await admin.jsm().consumer_info(stream_for(prefix, tenant), f"d-{agent}") + finally: + await admin.close() + + +def settings( + accounts_url: str, prefix: str, tenants: list[str], extra: str = "", *, user: str = "proc", password: str = "proc-test-only" +) -> str: + return ( + "[default]\n" + 'app_name = "blueprint-it"\n' + 'app_environment = "development"\n' + "app_port = 8000\n" + 'model_provider = "openai"\n' + 'event_bus = "nats"\n' + f'nats_url = "{accounts_url}"\n' + f'nats_user = "{user}"\n' + f'nats_password = "{password}"\n' + "event_client_max_retries = 2\n" + "event_client_retry_delay = 0.5\n" + 'nats_connection_source = "tests.integration.connection_source:create_source"\n' + f'test_source_url = "{accounts_url}"\n' + f'test_source_prefix = "{prefix}"\n' + f"test_source_tenants = {json.dumps(tenants)}\n" + extra + ) + + +def permission_violations(caplog: pytest.LogCaptureFixture) -> list[str]: + """Permission violations the broker reported to any connection of the process, as logged.""" + found = [] + for record in caplog.records: + text = record.getMessage() + (str(record.exc_info[1]) if record.exc_info and record.exc_info[1] else "") + if "ermission" in text: + found.append(text[:200]) + return found + + +class TestTenantsAreKeptApart: + async def test_each_run_sees_one_tenant_on_consumers_the_operator_made( + self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str, caplog: pytest.LogCaptureFixture + ) -> None: + caplog.set_level(logging.WARNING) + risk, both = f"risk_{subject_prefix}", f"both_{subject_prefix}" + agents_subjects = {risk: ["risk.>"], both: ["risk.>", "issue.>"]} + await operator(["A", "B"], agents_subjects) + before = (await consumer_info(accounts_url, subject_prefix, "A", both)).config.as_dict() + runs: list[dict[str, Any]] = [] + agents = {name: recording_handler(subjects, runs) for name, subjects in agents_subjects.items()} + + async with settings_group( + settings(accounts_url, subject_prefix, ["A", "B"], "nats_max_concurrent_runs = 2\n"), agents, named=2 + ) as clients: + assert all(list(client._topic_callbacks) == [] for client in clients.values()), "nothing on the process connection" + for tenant in ("A", "B"): + for _ in range(3): + await publish(accounts_url, subject_prefix, tenant, "risk.created") + for _ in range(2): + await publish(accounts_url, subject_prefix, tenant, "issue.created") + await wait_until(lambda: len(runs) == 16, timeout=15, description="16 runs (risk agent 6, both agent 10)") + + async def settled() -> bool: + infos = [await consumer_info(accounts_url, subject_prefix, t, a) for t in ("A", "B") for a in agents_subjects] + return all(info.num_ack_pending == 0 and info.num_redelivered == 0 for info in infos) + + await poll_until(settled, timeout=10, description="every delivery acked, none redelivered") + + assert [run for run in runs if not run["connection"] == run["scope"] == run["tenant"]] == [] + assert {run["subject"] for run in runs} == {"risk.created", "issue.created"}, "the handler sees the subject without the prefix" + after = (await consumer_info(accounts_url, subject_prefix, "A", both)).config.as_dict() + assert after == before, "the operator's consumer is bound, never rewritten" + assert permission_violations(caplog) == [] + + async def test_a_delivery_the_source_rejects_never_runs_and_is_termed( + self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str + ) -> None: + agent = f"risk_{subject_prefix}" + await operator(["A"], {agent: ["risk.>"]}) + runs: list[dict[str, Any]] = [] + async with settings_group(settings(accounts_url, subject_prefix, ["A"]), {agent: recording_handler(["risk.>"], runs)}, named=1): + await publish(accounts_url, subject_prefix, "A", "risk.created", claimed_tenant="B") + good = await publish(accounts_url, subject_prefix, "A", "risk.created") + await wait_until(lambda: [run["id"] for run in runs] == [good], timeout=10, description="only the matching event to run") + + async def termed() -> bool: + info = await consumer_info(accounts_url, subject_prefix, "A", agent) + return info.delivered.stream_seq == 2 and info.num_ack_pending == 0 and info.num_redelivered == 0 + + await poll_until(termed, timeout=10, description="the rejected delivery to be settled for good") + + +class TestClaims: + async def test_an_unclaimed_subject_fails_startup( + self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str + ) -> None: + agent = f"risk_{subject_prefix}" + await operator(["A"], {agent: ["risk.>"]}) + extra = 'test_source_unclaimed = ["hybrid.tick"]\n' + with pytest.raises(Exception, match="does not claim"): + async with settings_group( + settings(accounts_url, subject_prefix, ["A"], extra), {agent: recording_handler(["risk.>", "hybrid.tick"], [])} + ): + pass + + async def test_the_hybrid_mode_serves_it_on_the_process_connection_when_asked_for( + self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str, caplog: pytest.LogCaptureFixture + ) -> None: + caplog.set_level(logging.WARNING) + agent, tick = f"risk_{subject_prefix}", f"hybrid.{subject_prefix}.tick" + await operator(["A"], {agent: ["risk.>"]}) + extra = f'test_source_unclaimed = ["{tick}"]\nnats_unclaimed_subjects = "default_connection"\n' + runs: list[dict[str, Any]] = [] + handler = recording_handler(["risk.>", tick], runs) + config = settings(accounts_url, subject_prefix, ["A"], extra, user="proc-hybrid", password="proc-hybrid-test-only") + async with settings_group(config, {agent: handler}, named=1) as clients: + assert list(clients[agent]._topic_callbacks) == [tick] + publisher = await nats.connect(accounts_url, user="proc-hybrid", password="proc-hybrid-test-only") + event = {"specversion": "1.0", "id": str(uuid.uuid4()), "type": "tick", "source": "integration-test"} + await publisher.publish(tick, json.dumps(event).encode()) + await publisher.close() + await publish(accounts_url, subject_prefix, "A", "risk.created") + await wait_until(lambda: len(runs) == 2, timeout=10, description="the tick (process connection) and the tenant event") + assert sorted(str(run["connection"]) for run in runs) == ["A", "None"] + assert permission_violations(caplog) == [] + + +class TestConnectionsChangeAtRuntime: + async def test_added_changed_and_removed_without_loss_or_duplicate( + self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str, caplog: pytest.LogCaptureFixture + ) -> None: + caplog.set_level(logging.WARNING) + agent = f"risk_{subject_prefix}" + await operator(["A", "B"], {agent: ["risk.>"]}) + runs: list[dict[str, Any]] = [] + async with settings_group( + settings(accounts_url, subject_prefix, ["A"]), {agent: recording_handler(["risk.>"], runs)}, named=1 + ) as clients: + client, source = clients[agent], SOURCES[-1] + + source.set_users({"A": "agent-a", "B": "agent-b"}) # added + await wait_until( + lambda: client.named_connections == ("A", "B") and all(b.subscriptions_ready for b in client._named), + timeout=10, + description="B to be bound", + ) + on_b = await publish(accounts_url, subject_prefix, "B", "risk.created") + await wait_until(lambda: on_b in [run["id"] for run in runs], timeout=10, description="B's event to run") + + sent = [await publish(accounts_url, subject_prefix, "A", "risk.created") for _ in range(5)] + source.set_users({"A": "agent-a2", "B": "agent-b"}) # changed: the same account, rotated user + sent += [await publish(accounts_url, subject_prefix, "A", "risk.created") for _ in range(10)] + await wait_until( + lambda: all(event_id in [run["id"] for run in runs] for event_id in sent), + timeout=15, + description="every event on A across the change", + ) + await wait_until( + lambda: len([b for b in client._named if b.link.name == "A"]) == 1, + timeout=10, + description="the old link of A to be retired", + ) + handled = [run["id"] for run in runs if run["connection"] == "A"] + assert sorted(handled) == sorted(sent), "nothing lost, nothing twice" + + source.set_users({"A": "agent-a2"}) # removed + await wait_until(lambda: client.named_connections == ("A",), timeout=10, description="B to be removed") + info = await consumer_info(accounts_url, subject_prefix, "A", agent) + assert info.num_ack_pending == 0 and info.num_redelivered == 0 + assert permission_violations(caplog) == [] From d90ca5fa73f17276bfc496586b3bcf8c21627129 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 10:58:34 +0200 Subject: [PATCH 084/133] feat(nats): per-connection readiness state and nats_connections_readiness (named connections, step 5) - HealthCheckEntry.affects_consumption: HealthCheckCache computes a readiness verdict from every entry and a consumption verdict from the entries that may pause; the supervisor gets the latter. - .nats_client:connections (NamedConnectionsHealthChecker), readiness-only: a named connection that is down never pauses the agent on its other connections (D5). - nats_connections_readiness = never (default) | any | all, validated at subscribe(). - NATSClient.named_connection_states(): bound / connecting / reconnecting / retrying with the redacted last error / paused, plus permission violations; a refused login is recorded from error_cb, since nats.connect() retries it itself and never returns. - Gauge blueprint.nats.connection.bound, counter blueprint.nats.connection.permission_violations. - /health/ready reads the cached answer without the poll lock (review finding #6). - A paused agent whose default connection comes back re-evaluates readiness at once; under any/all so does a named connection becoming bound or unbound. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 13 + ...26-08-28-multi-agent-grouping-changelog.md | 31 ++ docs/plans/2026-10-14-named-connections.md | 6 +- .../docs/concepts/observability.md | 31 +- .../docs/reference/configuration-keys.md | 1 + src/blueprint/agents/app_builder.py | 24 +- .../agents/clients/io/nats_client.py | 193 ++++++++++- .../io/api/actuators/health/__init__.py | 2 + .../io/api/actuators/health/health_base.py | 4 + .../io/api/actuators/health/health_cache.py | 33 +- .../health/named_connections_health.py | 40 +++ tests/integration/conftest.py | 6 +- tests/integration/connection_source.py | 9 +- tests/integration/test_named_connections.py | 47 ++- .../agents/app_builder/test_app_builder.py | 42 +++ .../io/test_nats_connection_readiness.py | 305 ++++++++++++++++++ .../api/actuators/health/test_health_cache.py | 78 +++++ 17 files changed, 847 insertions(+), 18 deletions(-) create mode 100644 src/blueprint/agents/io/api/actuators/health/named_connections_health.py create mode 100644 tests/unit/agents/clients/io/test_nats_connection_readiness.py diff --git a/CHANGELOG.md b/CHANGELOG.md index a336ad98..6c4f5ce4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,10 @@ ### Fixed +- **`/health/ready` no longer waits for a running health poll.** The cached answer was read under the + lock the poll holds while it awaits every check, so a slow check -- a NATS connect up to its 10 s + timeout -- delayed every readiness probe with it. Measured with a 4 s check: up to 3.9 s per probe + before, under 0.1 s now. - **A NATS connection that gave up reconnecting comes back, with its subscriptions.** `nats_max_reconnect_attempts` now defaults to unlimited (was 5, about 10 s of outage), and a connection that closes anyway restarts the client's retry loop, which connects and resubscribes; @@ -168,6 +172,15 @@ ### Added +- **Per-connection state and `nats_connections_readiness`.** Each agent with named connections gets a + readiness entry `.nats_client:connections` listing every connection as `bound`, `connecting`, + `reconnecting`, `retrying` (with the last error, redacted) or `paused`, and any permission violation, + plus the gauge `blueprint.nats.connection.bound` and the counter + `blueprint.nats.connection.permission_violations` (attributes `agent`, `connection`). The new agent-scope + key decides whether the entry can fail: `"never"` (default), `"any"` (one bound) or `"all"` (every one + bound); another value fails startup. In every mode a named connection feeds readiness only and never + pauses the agent, so its other connections keep delivering. A paused agent whose default connection + comes back re-evaluates readiness at once instead of at the next health interval. - **Named connections change at runtime.** A connection source that defines `watch(notify)` tells every agent's client when its connections change; the client binds a new connection, replaces a changed one (new link bound before the old one is retired) and retires a removed one: drained, its runs given diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index d52b1b9f..21892932 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8537,6 +8537,37 @@ each, both failures pre-existing and failing at HEAD as well (`test_two_processe the subprocess does not find `blueprint`; `test_the_broker_counts_it_as_a_redelivery`: now deterministic, see Open points). +### Named connections, step 5: readiness and telemetry per connection (D5, review finding #6) + +- **Readiness only, never a pause.** `HealthCheckEntry` gains `affects_consumption` (default `True`). + `HealthCheckCache` computes two verdicts per agent: readiness from every entry (payload, policy) and + consumption from the entries that may pause (what `NamespaceSupervisor.observe` gets). The new + entry `.nats_client:connections` (`NamedConnectionsHealthChecker`, registered by `build()` + for each NATS client given a connection source) is readiness-only: a tenant connection that is down + never pauses the agent on its other connections, in any mode. +- **`nats_connections_readiness`** (agent scope): `"never"` (default, the entry always healthy and + only reports), `"any"` (fails while none is bound; zero connections count as none), `"all"` (fails + while one is not bound). Another value fails `subscribe()`, naming the key. The default + connection's entry is unchanged. +- **Per-connection state** (`NATSClient.named_connection_states()`): `bound`, `connecting`, + `reconnecting`, `retrying` with the last error (URL and the link's credentials redacted, 200 + characters), `paused`, and whether a permission violation was seen. A refused login never surfaces + as an exception -- with `max_reconnect_attempts=-1` `nats.connect()` retries it itself and never + returns -- so `error_cb` records it as the last error, and the state reads `retrying`. +- **Metrics** on the agent's meter: gauge `blueprint.nats.connection.bound` and counter + `blueprint.nats.connection.permission_violations`, both with `agent` and `connection`. +- **#6:** `get_health_status()` no longer takes the lock the poll holds while it awaits the checks; + the lock now only serialises polls. Live over HTTP with a 4 s check: max 3928 ms and 5 of 25 probes + over 0.5 s on the old code, max 82 ms and none over 0.5 s now. +- **Immediate re-evaluation:** `NATSClient.set_health_refresh()` (wired by `build()` to + `ActuatorApi.refresh_health`). The default connection coming back while the agent is paused runs + the checks at once, so a pause its own disconnect caused ends on the reconnect; under `any`/`all` + a named connection becoming bound or unbound does the same. The refresh runs in a watched task. +- Tests: unit (states, redaction, modes, checker, two verdicts, lock-free read, serialised polls, + refresh, gauge, counter, wiring); integration `TestADeadConnectionCountsForReadinessOnly` on the + accounts broker -- tenant B with a wrong password, per mode: A bound and B `retrying`, `/health/ready` + 200/200/503 for never/any/all, the agent not paused, A still delivering, no password in the payload. + --- ## Open points diff --git a/docs/plans/2026-10-14-named-connections.md b/docs/plans/2026-10-14-named-connections.md index a045b0e7..5bc2fa06 100644 --- a/docs/plans/2026-10-14-named-connections.md +++ b/docs/plans/2026-10-14-named-connections.md @@ -283,7 +283,11 @@ One step, one reviewable commit. Each step names its acceptance. (also #10) is not part of this feature; a configurable limit is left for later. 5. **Readiness and telemetry per connection** (D5): connection state in the readiness payload, metrics labelled with the connection name. Take review finding #6 (the readiness probe waits on a - lock held during slow health checks) into account here. + lock held during slow health checks) into account here. **Done 2026-10-15:** readiness entry + `.nats_client:connections` registered with `affects_consumption=False` (feeds the verdict, + never the supervisor), `nats_connections_readiness`, gauge `blueprint.nats.connection.bound`, + counter `blueprint.nats.connection.permission_violations`; `/health/ready` reads the cache without + the poll lock (#6); a paused agent whose default connection comes back re-evaluates at once. 6. **Everything that describes the framework agrees with it -- no contradiction left anywhere.** Not only the new feature: every statement about NATS delivery, consumers, concurrency, heartbeat, run limits and connections is checked against the code after steps 1-5, and corrected or diff --git a/src/blueprint/agent_generator/docs/concepts/observability.md b/src/blueprint/agent_generator/docs/concepts/observability.md index 3f45fae6..26e36a55 100644 --- a/src/blueprint/agent_generator/docs/concepts/observability.md +++ b/src/blueprint/agent_generator/docs/concepts/observability.md @@ -111,6 +111,8 @@ An exception propagating out of the method sets the span status to `ERROR` befor | `blueprint.namespace.inflight` | gauge | Dispatches that agent has in progress. Carries `agent`. | | `blueprint.events.unhandled` | counter | Events an agent received and found nothing to do with. Carries `agent` and `topic`. | | `blueprint.events.duplicate` | counter | Events an agent recognised as already processed. Carries `agent` and `topic`. | +| `blueprint.nats.connection.bound` | gauge | `1` while a named NATS connection is bound and delivering, `0` otherwise. Carries `agent` and `connection`. | +| `blueprint.nats.connection.permission_violations` | counter | Permission violations the broker reported on a named connection. Carries `agent` and `connection`. | | `llm.tokens.count` | counter | Tokens consumed, by an agent's model calls. | | `llm.response.latency` | histogram | Model call duration. | @@ -131,7 +133,7 @@ the only attribution available is what was emitted *before* the process died. | Endpoint | Answers | |---|---| | `GET /health/live` | `200` while the process is running. Never namespace-dependent (C3). | -| `GET /health/ready` | `200` when the pod should receive traffic, `503` otherwise. | +| `GET /health/ready` | `200` when the pod should receive traffic, `503` otherwise. Answered from the last poll's result at once, also while a poll is still waiting on a slow check. | | `GET /info`, `/status/env`, `/status/llm`, `/status/build` | Service, configuration, AI-provider and build metadata. | **Liveness is never namespace-dependent, and that is a rule rather than an accident.** A failing @@ -237,6 +239,33 @@ registration rather than silently reduced to one. The framework registers checks of its own: one per transport client, and one per declared cache (`cache`, or `cache:` for a named one). +### Named NATS connections + +With a `nats_connection_source`, each agent's client gets one more entry, +`.nats_client:connections`. Its message lists every named connection and how it stands -- +`bound`, `connecting`, `reconnecting`, `retrying` (with the last error, credentials redacted) or +`paused` -- and whether the broker reported a permission violation: + +```json +"orders.nats_client:connections": { + "status": "unhealthy", + "message": "1/2 named connection(s) bound, readiness 'all': A=bound, B=retrying (Error: nats: 'Authorization Violation')" +} +``` + +Whether it can fail is the agent's `nats_connections_readiness`: `never` (default) -- it is always +healthy and only reports; `any` -- it fails while no named connection is bound; `all` -- it fails +while any one is not bound. + +**It counts for readiness only, never for consumption.** A failing entry makes the agent `DOWN` in +the payload and under the readiness policy, but the agent is not paused: a tenant whose connection +is down must not stop the agent on every other tenant's connection. The default connection's +entry keeps pausing the agent as described below. + +When the mode is `any` or `all`, a named connection becoming bound or unbound re-runs the checks at +once rather than at the next interval. So does the default connection coming back while the agent +is paused, so a pause its own disconnect caused ends on the reconnect. + --- ## What happens when an agent stops serving diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 7b555e05..adcc4fbc 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -51,6 +51,7 @@ Settings for the event bus transport layer. | `nats_connection_source` | `str` | unset -- the agent consumes on its one connection, as before | **Process scope.** `"package.module:attribute"` naming a factory that is called with the process `Config` and returns a `ConnectionSource` (`blueprint.agents.clients.io.nats_connections`). The source lists named connections -- each with its own URL and account -- and, per agent and connection, a `JetStreamBinding`: which declared subjects the connection serves, the subject prefix, and the deployment's durable consumer with its wire values verbatim. Those subjects leave the agent's default connection. Each delivery from a named connection is checked by the source's `validate` before anything runs (a reason terminates it), runs in an empty context inside the source's `run_scope`, and is settled on the connection it arrived on; the handler sees the subject without the prefix and the connection's name under the context key `nats_connection`. JetStream only. An agent with named connections may not map handler results to topics. A source that also defines `watch(notify)` is followed at runtime: connections added, changed or removed are applied while the agent runs (`subscription_change_grace`). A wrong path fails startup. | | `nats_handler_timeout` | `float` | unset -- no limit | Seconds one run may take, on every connection of the agent. At the limit the run is cancelled and its delivery nak'd for immediate redelivery, so a hung model request no longer holds its slot forever; after `nats_max_deliver` attempts the delivery is given up as usual. A `TimeoutError` the handler raises itself is an ordinary failure. A handler that catches the cancellation and carries on keeps its slot until it returns, which is logged, and its delivery is nak'd all the same. Set it above the longest legitimate run. | | `subscription_change_grace` | `float` | `event_client_drain_timeout` | Seconds the runs of a named connection that is removed or replaced at runtime get to finish. A run still going after that is revoked: it is never acked or nak'd -- the delivery stays with the broker and returns after `ack_wait` -- its heartbeat stops, and a `publish` from it raises `DeliveryRevokedError`; it is not cancelled. | +| `nats_connections_readiness` | `str` | `"never"` | Only with a `nats_connection_source`; agent scope. Whether the agent's named connections count for its readiness: `"never"` -- they never make it not ready; `"any"` -- ready while at least one named connection is bound (none at all counts as not ready); `"all"` -- ready only while every named connection is bound. Any other value fails startup, naming the key. **Readiness only, in every mode:** a named connection that is down never pauses the agent, so its other connections keep delivering. Each connection's state (`bound`, `connecting`, `reconnecting`, `retrying` with the last error, `paused`, and a permission violation if one was seen) is listed in the readiness entry `.nats_client:connections` in every mode, and the gauge `blueprint.nats.connection.bound` reports it. The agent's default connection keeps its behaviour. | | `nats_unclaimed_subjects` | `str` | `"fail"` | Only with a `nats_connection_source`. What happens to a declared subject the source does not `claims()` for the agent: `"fail"` -- the agent's startup fails, naming the subjects; `"default_connection"` -- consumed on the agent's own connection (the explicit hybrid mode; the process account must then be allowed to subscribe them). A claimed subject never goes to the default connection, even while no named connection serves it yet. | | `nats_heartbeat_enabled` | `bool` | `true` | Whether a running JetStream delivery reports `in_progress` every third of its consumer's `ack_wait`, so a run longer than `ack_wait` is not redelivered while it still runs. Switch it off only for an agent whose runs always finish well inside `ack_wait`; off, a long run is delivered again to another replica. Must be a boolean -- the string `"false"` is refused, because it would read as true. | | `nats_max_deliver` | `int` | unset -- the server's default (NATS: unlimited) | Delivery attempts before the message is dead-lettered. Unlimited -- the default, or `-1` -- means a permanently failing message is retried forever and never dead-lettered; the client logs a warning at startup if you set `-1` explicitly. Set a positive limit to bound retries. | diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index 86064413..393cdc3e 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -32,7 +32,7 @@ from .io.api.rest_api_base import RestApiBase from .io.api.scheduling.scheduler import SchedulerBase from .io.api.actuators.actuator_api import ActuatorApi -from .io.api.actuators.health import CacheHealthChecker, ClientHealthChecker, HealthCheckEntry +from .io.api.actuators.health import CacheHealthChecker, ClientHealthChecker, HealthCheckEntry, NamedConnectionsHealthChecker from .io.api.eventing.dapr import DaprEventing from .io.api.eventing.nats import NatsEventing from .io.api.eventing.sessions_bus import SessionsBus @@ -265,6 +265,8 @@ def __init__(self, config: Config | None = None) -> None: # because a group's agents each subscribe on their own behalf (spec sec. 7.6); it holds # exactly one element for every application that declares no namespace. self._eventing_components: list[DaprEventing | NatsEventing] = [] + # The NATS clients given a connection source, for their named connections' readiness entries. + self._sourced_nats_clients: list[NATSClient] = [] # Components that need lifespan (on_startup / on_shutdown) but do not expose # a FastAPI router. SessionsBus lives here because it is SSE-driven, not # HTTP-driven; keeping it out of _eventing_component avoids the routerless @@ -1011,6 +1013,7 @@ def build(self, config: Config | None = None) -> FastAPI: ) # One pool of runs beyond each pair's guaranteed one, shared by the whole process (plan D7). run_pool = RunPool(RunLimit.parse("nats_extra_runs_per_process", resolved_config.get("nats_extra_runs_per_process"), minimum=0)) + self._sourced_nats_clients = [] for namespace in self.hosted_namespaces: self._wire_transport(registry, namespace, event_bus_type, connection_source, run_pool) self._wire_dapr_endpoint(registry, event_bus_type) @@ -1053,6 +1056,17 @@ def build(self, config: Config | None = None) -> FastAPI: # The agent is carried on the entry, so two agents' default caches are two entries # rather than one that silently reports whichever was registered last. health_providers.append(HealthCheckEntry(name=name, namespace=namespace, checker=CacheHealthChecker(cache))) + # Each agent's named connections: one entry for readiness only. Never one that pauses the + # agent -- a dead tenant connection must not stop it on its other connections (plan D5). + health_providers.extend( + HealthCheckEntry( + name=f"{client.base_name}:connections", + namespace=client.namespace, + checker=NamedConnectionsHealthChecker(client), + affects_consumption=False, + ) + for client in self._sourced_nats_clients + ) health_providers.extend(self._health_checkers) if health_providers: self._actuator_api.add_health_providers(health_providers) @@ -1138,7 +1152,10 @@ def _wire_transport( elif event_bus_type == "nats": client = NATSClient(namespace=namespace) # auto-registers client.set_fatal_handler(self._on_transport_fatal) + client.set_health_refresh(self._refresh_health) client.set_connection_source(connection_source) + if connection_source is not None: + self._sourced_nats_clients.append(client) if run_pool is not None: client.set_run_pool(run_pool) if consumes: @@ -1573,6 +1590,11 @@ async def _start_loop_diagnostics(self, config: Config) -> None: ) await self._loop_watchdog.start() + async def _refresh_health(self) -> None: + """Recompute readiness now; what a transport client calls for a change it saw before a poll would.""" + if self._actuator_api is not None: + await self._actuator_api.refresh_health() + async def _mark_agent_down(self, namespace: str, reason: str) -> None: """Take one agent out of service for a failure no health check can see. diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 978028a7..cd0e8b0a 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -8,7 +8,7 @@ import json import logging import re -from collections.abc import AsyncIterator, Awaitable, Callable +from collections.abc import AsyncIterator, Awaitable, Callable, Iterable from dataclasses import dataclass, field from functools import cached_property from pathlib import Path @@ -21,7 +21,7 @@ from nats.js.client import JetStreamContext from nats.errors import NoRespondersError from nats.js.errors import APIError, NotFoundError -from opentelemetry.metrics import Counter +from opentelemetry.metrics import CallbackOptions, Counter, Observation from ...component.namespace import ROOT_LABEL, ROOT_NAMESPACE from ...deployment import UNGROUPED_LABEL, UNKNOWN_POD_LABEL, deployment_group, pod_identity @@ -69,6 +69,20 @@ class JetStreamUnavailableError(RuntimeError): """ +CONNECTIONS_READINESS_KEY = "nats_connections_readiness" +"""Agent-scoped: whether the agent's named connections count for its readiness -- ``"never"`` (default), +``"any"`` (one bound is enough) or ``"all"`` (every one bound). Readiness only, in every mode: a named +connection never pauses the agent (named-connections plan, D5).""" + +CONNECTIONS_READINESS_MODES = ("never", "any", "all") + +CONNECTION_BOUND_GAUGE = "blueprint.nats.connection.bound" +"""``1`` while a named connection is bound and delivering, ``0`` otherwise; attributes ``agent`` and +``connection``. Recorded on the agent's own meter provider (C2).""" + +PERMISSION_VIOLATIONS_COUNTER = "blueprint.nats.connection.permission_violations" +"""Permission violations a named connection's broker reported; attributes ``agent`` and ``connection``.""" + PERMISSION_RETRY_SECONDS = 60.0 """How often a named connection retries after the broker refused it a permission: a missing grant does not heal in seconds, so retrying at the normal pace would only fill the log (spec 7.9).""" @@ -130,6 +144,37 @@ class ConsumerTuning: dead_letter_subject: str +@dataclass(frozen=True) +class NamedConnectionState: + """How one named connection of an agent stands, for readiness and diagnostics. Never carries a secret. + + ``state`` is ``"bound"`` (delivering), ``"connecting"`` (first attempt in progress), + ``"reconnecting"`` (the broker was lost; the client reconnects by itself), ``"retrying"`` (an + attempt failed; ``last_error`` says why) or ``"paused"`` (the agent is degraded and consumes + nowhere, C4). + """ + + name: str + state: str + last_error: str = "" + permission_denied: bool = False + """The broker reported a permission violation since the connection's last attempt.""" + + @property + def bound(self) -> bool: + """Whether the connection is bound and delivering.""" + return self.state == "bound" + + def describe(self) -> str: + """One line for the readiness payload: name, state, and why when it is not bound.""" + details = [] + if self.permission_denied: + details.append("permission violation") + if self.last_error and not self.bound: + details.append(self.last_error) + return f"{self.name}={self.state}" + (f" ({'; '.join(details)})" if details else "") + + @dataclass(eq=False) class _Link: """One broker connection and what it was opened with. @@ -191,6 +236,10 @@ class _Binding: revoked: bool = False """Retired with runs still in flight after the grace period: those runs are never settled (spec 7.5).""" heartbeats: set[asyncio.Task[None]] = field(default_factory=set) + last_error: str = "" + """Why the last connect-and-bind attempt failed, redacted; ``""`` once it is bound.""" + permission_denied: bool = False + """The last failed attempt was refused a permission by the broker.""" def __post_init__(self) -> None: self.idle.set() @@ -348,6 +397,9 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: self._change_grace = 30.0 self._change_lock = asyncio.Lock() self._loop: asyncio.AbstractEventLoop | None = None + self._connections_readiness: str | None = None + self._connection_gauge_registered = False + self._health_refresh: Callable[[], Awaitable[None]] | None = None self._reconcile_task: asyncio.Task[None] | None = None self._reconcile_dirty = False self._retirements: set[asyncio.Task[None]] = set() @@ -497,6 +549,123 @@ def named_connections(self) -> tuple[str, ...]: """Names of the connections the source gave this agent a binding on, in the source's order.""" return tuple(binding.link.name for binding in self._named) + @property + def connections_readiness(self) -> str: + """``nats_connections_readiness`` for this agent: ``"never"``, ``"any"`` or ``"all"``. + + Raises: + ValueError: the key holds anything else. ``subscribe()`` resolves it first, so a wrong + value fails the agent's startup rather than a health poll. + """ + if self._connections_readiness is None: + self._connections_readiness = self._resolve_connections_readiness() + return self._connections_readiness + + def named_connection_states(self) -> tuple[NamedConnectionState, ...]: + """How each current named connection stands, in the source's order; one being replaced is left out.""" + return tuple(self._state_of(binding) for binding in self._named if not binding.superseded) + + def _state_of(self, binding: _Binding) -> NamedConnectionState: + """``binding``'s state, from what its link and its connect loop last recorded.""" + client = binding.link.nats_client + if binding.subscriptions_ready: + state = "bound" + elif self._consumption_paused: + state = "paused" + elif client is not None and client.is_reconnecting: + state = "reconnecting" + elif binding.last_error: + state = "retrying" + else: + state = "connecting" + denied = binding.permission_denied or bool(binding.link.permission_errors) + return NamedConnectionState(binding.link.name, state, binding.last_error, denied) + + def _resolve_connections_readiness(self) -> str: + """Read ``nats_connections_readiness``; refuse anything but the three modes, naming the key.""" + raw = self.config.get(CONNECTIONS_READINESS_KEY, None) + mode = str(raw or "never").strip().lower() + if mode not in CONNECTIONS_READINESS_MODES: + raise ValueError( + f"'{CONNECTIONS_READINESS_KEY}' must be one of {', '.join(CONNECTIONS_READINESS_MODES)}, got {raw!r} " + f"(agent '{self.namespace or ROOT_LABEL}')." + ) + return mode + + def set_health_refresh(self, refresh: Callable[[], Awaitable[None]] | None) -> None: + """Install what re-evaluates readiness at once, for a change a health poll would otherwise see late. + + Called after the default connection comes back while the agent is paused -- the pause its own + disconnect caused ends on that re-evaluation rather than up to ``health_check_interval_seconds`` + later -- and, unless ``nats_connections_readiness`` is ``"never"``, whenever a named connection + becomes bound or unbound. + """ + self._health_refresh = refresh + + def _request_health_refresh(self, reason: str) -> None: + """Run the installed refresh in a task of its own; a callback of nats-py must not wait for a poll.""" + if self._health_refresh is None or self._closing: + return + logger.debug("Agent '%s': readiness re-evaluated now: %s", self.namespace or ROOT_LABEL, reason) + task = asyncio.ensure_future(self._health_refresh()) + task.add_done_callback(self._on_health_refresh_done) + + def _on_health_refresh_done(self, task: "asyncio.Future[None]") -> None: + """Report a refresh that failed, naming the agent.""" + if not task.cancelled() and task.exception() is not None: + logger.error( + "Agent '%s': re-evaluating readiness failed: %s", + self.namespace or ROOT_LABEL, + task.exception(), + exc_info=task.exception(), + ) + + def _named_bound_changed(self, binding: _Binding) -> None: + """A named connection became bound or unbound: re-evaluate readiness if the mode reads it.""" + if self._source is not None and self.connections_readiness != "never": + self._request_health_refresh(f"named connection '{binding.link.name}' changed state") + + def _register_connection_gauge(self) -> None: + """Create :data:`CONNECTION_BOUND_GAUGE` once, on the agent's meter, after telemetry is configured.""" + if self._connection_gauge_registered: + return + self._connection_gauge_registered = True + agent = self.namespace or ROOT_LABEL + + def observe(_options: CallbackOptions) -> Iterable[Observation]: + # Runs on the metrics reader's thread: reads the bindings, nothing more. + return [ + Observation(1 if state.bound else 0, {"agent": agent, "connection": state.name}) for state in self.named_connection_states() + ] + + agent_meter(self.namespace, __name__).create_observable_gauge( + CONNECTION_BOUND_GAUGE, + callbacks=[observe], + description="1 while this named connection is bound and delivering, 0 otherwise", + unit="1", + ) + + @cached_property + def _permission_violations(self) -> Counter: + """Counter of :data:`PERMISSION_VIOLATIONS_COUNTER`, created on first use (see ``_dead_lettered``).""" + return agent_meter(self.namespace, __name__).create_counter( + name=PERMISSION_VIOLATIONS_COUNTER, + description="Permission violations the broker reported on this agent's named connections", + unit="{violation}", + ) + + @staticmethod + def _describe_error(link: _Link, exc: BaseException) -> str: + """``exc`` as one short line for the readiness payload: the URL redacted, no credential of the link in it.""" + text = f"{type(exc).__name__}: {exc}" + if link.url: + text = text.replace(link.url, redact_url(link.url)) + for key in ("password", "token", "nkeys_seed_str"): + secret = link.connect_options.get(key) + if isinstance(secret, str) and secret: + text = text.replace(secret, "***") + return text[:200] + @property def consumer_tuning(self) -> ConsumerTuning | None: """JetStream consumer settings resolved by ``subscribe()``; ``None`` on Core NATS.""" @@ -531,6 +700,7 @@ async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: self._heartbeat_enabled = self._resolve_heartbeat_enabled() self._handler_timeout = self._resolve_handler_timeout() self._change_grace = self._resolve_change_grace() + self._connections_readiness = self._resolve_connections_readiness() self._declared = dict(topic_callbacks) # What a named connection serves leaves the default connection (plan D10). default_topics = self._plan_named_bindings(topic_callbacks) @@ -542,6 +712,8 @@ async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: self._subscriptions_ready = False self._default_pairs = 1 if default_topics else 0 self._register_pairs(self._default_pairs + len(self._named)) + if self._source is not None: + self._register_connection_gauge() self._watch_source() if self._consumption_paused: logger.info( @@ -687,6 +859,9 @@ async def _run_named_link(self, binding: _Binding) -> None: binding.subscriptions.clear() await self._bind(binding) binding.subscriptions_ready = True + binding.last_error = "" + binding.permission_denied = False + self._named_bound_changed(binding) if binding.replaces is not None: # New before old (spec 7.4): only now that this one delivers is the old one retired. old, binding.replaces = binding.replaces, None @@ -698,6 +873,8 @@ async def _run_named_link(self, binding: _Binding) -> None: attempt += 1 binding.subscriptions_ready = False denied = list(binding.link.permission_errors) + binding.last_error = self._describe_error(binding.link, exc) + binding.permission_denied = bool(denied) if denied: # The broker reports a missing grant through error_cb and lets the request time # out: that is permanent, not a slow broker (spec 7.9). @@ -746,6 +923,7 @@ async def on_disconnected() -> None: for binding in self._named: if binding.link is link: binding.subscriptions_ready = False + self._named_bound_changed(binding) logger.warning("Agent '%s': named connection '%s' lost its broker", agent, link.name) async def on_reconnected() -> None: @@ -754,12 +932,20 @@ async def on_reconnected() -> None: for binding in self._named: if binding.link is link and not self._consumption_paused: binding.subscriptions_ready = True + self._named_bound_changed(binding) logger.info("Agent '%s': named connection '%s' is back", agent, link.name) async def on_error(error: Exception) -> None: # Permission violations land here: a subject the deployment did not grant this account. if "permissions violation" in str(error).lower(): link.permission_errors.append(str(error)) + self._permission_violations.add(1, {"agent": agent, "connection": link.name}) + # A refused login lands here too, and only here: with max_reconnect_attempts=-1, + # nats.connect() retries it by itself and never returns, so the connect loop sees no + # exception. Recorded so the state reads "retrying" with the reason, not "connecting". + for binding in self._named: + if binding.link is link and not binding.subscriptions_ready: + binding.last_error = self._describe_error(link, error) logger.error("Agent '%s': error on named connection '%s': %s", agent, link.name, error) link.nats_client = await nats.connect( @@ -2697,6 +2883,9 @@ async def _on_reconnected(self) -> None: # restoring the connection would silently resubscribe a degraded agent, and C4 # would hold only until the next network blip. logger.info("Agent '%s' stays paused after the reconnect; it is still degraded", self.namespace or ROOT_LABEL) + # The pause may have been this connection's own loss: re-evaluate now, so the agent + # resumes on this reconnect instead of up to one health interval later. + self._request_health_refresh("the default connection is back while the agent is paused") return if self._use_jetstream and self._topic_callbacks: # JetStream durable consumers do not survive reconnects; re-subscribe manually. diff --git a/src/blueprint/agents/io/api/actuators/health/__init__.py b/src/blueprint/agents/io/api/actuators/health/__init__.py index 13d1d8a7..0ad3c31b 100644 --- a/src/blueprint/agents/io/api/actuators/health/__init__.py +++ b/src/blueprint/agents/io/api/actuators/health/__init__.py @@ -3,6 +3,7 @@ from .health_base import HealthCheckEntry, HealthCheckerBase from .cache_health import CacheHealthChecker from .client_health import ClientHealthChecker +from .named_connections_health import NamedConnectionsHealthChecker from .sessions_health import SessionsServiceHealthChecker __all__ = [ @@ -10,5 +11,6 @@ "HealthCheckerBase", "CacheHealthChecker", "ClientHealthChecker", + "NamedConnectionsHealthChecker", "SessionsServiceHealthChecker", ] diff --git a/src/blueprint/agents/io/api/actuators/health/health_base.py b/src/blueprint/agents/io/api/actuators/health/health_base.py index 67d3e56e..1add8b91 100644 --- a/src/blueprint/agents/io/api/actuators/health/health_base.py +++ b/src/blueprint/agents/io/api/actuators/health/health_base.py @@ -55,11 +55,15 @@ class HealthCheckEntry: name: What this check is called within its agent. namespace: The agent it belongs to; ``""`` for the root. checker: The checker to poll. + affects_consumption: Whether a failure also stops the agent consuming (C4). ``False`` + makes the check count for readiness only: a named NATS connection that is down must + never pause the agent on its other connections (named-connections plan, D5). """ name: str namespace: str checker: HealthCheckerBase + affects_consumption: bool = True @property def key(self) -> str: diff --git a/src/blueprint/agents/io/api/actuators/health/health_cache.py b/src/blueprint/agents/io/api/actuators/health/health_cache.py index c881396c..5c10ccdf 100644 --- a/src/blueprint/agents/io/api/actuators/health/health_cache.py +++ b/src/blueprint/agents/io/api/actuators/health/health_cache.py @@ -72,6 +72,9 @@ def __init__( namespaces={} if self._grouped else None, ) self._last_update: datetime = datetime.now() + # Serialises polls (the schedule and refresh()). Readers never take it: the cached response + # is replaced in one assignment, so a read sees the old one or the new one, never a mix, + # and the readiness probe never waits for a slow check (review finding #6). self._lock = asyncio.Lock() self._entries: tuple[HealthCheckEntry, ...] = () @@ -126,13 +129,16 @@ async def stop(self) -> None: logger.info("Health check cache stopped") async def get_health_status(self) -> ReadinessResponse: - """Get the cached health status. + """Get the cached health status, at once -- also while a poll is running. + + It used to wait for the poll lock, which a poll holds while it awaits every check: a NATS + client connecting against a broker that is down took up to its 10 s connect timeout, and + every readiness probe in that window waited with it (review finding #6). Returns: ReadinessResponse with cached health status """ - async with self._lock: - return self._cached_response + return self._cached_response async def refresh(self) -> None: """Re-run the checks now instead of at the next interval. @@ -177,7 +183,7 @@ async def _run_health_checks(self) -> None: else: components[entry.key] = result - namespace_status, namespaces = self._aggregate_by_agent(components) + namespace_status, consumption_status, namespaces = self._aggregate_by_agent(components) overall_status = "UP" if self._policy.is_ready(namespace_status, self._critical_namespaces()) else "DOWN" # Update cache @@ -200,7 +206,9 @@ async def _run_health_checks(self) -> None: # every probe during a pause wait for it, and a probe that times out is read as a # failure of the pod rather than of the one agent that is actually degraded. if self._supervisor is not None: - await self._supervisor.observe(namespace_status) + # The consumption verdict, not the readiness one: a readiness-only check (a named + # NATS connection) must never pause the agent on its other connections (D5). + await self._supervisor.observe(consumption_status) except Exception as exc: # pragma: no cover logger.error("Unexpected error during health check refresh: %s", exc, exc_info=True) @@ -209,7 +217,9 @@ def _critical_namespaces(self) -> frozenset[str]: """The agents that gate readiness under the ``critical`` policy, or none known.""" return self._supervisor.critical_namespaces if self._supervisor is not None else frozenset() - def _aggregate_by_agent(self, components: dict[str, ComponentHealth]) -> tuple[dict[str, bool], dict[str, NamespaceReadiness]]: + def _aggregate_by_agent( + self, components: dict[str, ComponentHealth] + ) -> tuple[dict[str, bool], dict[str, bool], dict[str, NamespaceReadiness]]: """Reduce the individual check results to one verdict per agent. The agent comes from the entry, not from the key. ``HealthCheckEntry`` carries it as @@ -226,23 +236,30 @@ def _aggregate_by_agent(self, components: dict[str, ComponentHealth]) -> tuple[d components: This poll's results, keyed by entry key. Returns: - Whether each namespace passed, and the per-agent section of the readiness payload. + Whether each namespace passed every check (readiness), whether it passed the checks + that may stop it consuming (what the supervisor acts on), and the per-agent section + of the readiness payload. """ supervised = set(self._supervisor.status) if self._supervisor is not None else set() forced = self._supervisor.forced_down if self._supervisor is not None else {} failing: dict[str, list[str]] = {namespace: [] for namespace in supervised | set(forced)} + consumption_failing: dict[str, list[str]] = {namespace: [] for namespace in failing} for entry in self._entries: result = components.get(entry.key) failing.setdefault(entry.namespace, []) + consumption_failing.setdefault(entry.namespace, []) if result is not None and result.status != "healthy": failing[entry.namespace].append(entry.key) + if entry.affects_consumption: + consumption_failing[entry.namespace].append(entry.key) # A latched agent is down whatever its checks say. That is the point of the latch: a # component that failed to start may answer its health check perfectly while the agent is # unusable, so the checks alone would report it UP -- to the policy and in the payload. critical = self._critical_namespaces() namespace_status = {namespace: not keys and namespace not in forced for namespace, keys in failing.items()} + consumption_status = {namespace: not keys and namespace not in forced for namespace, keys in consumption_failing.items()} namespaces = { (namespace or ROOT_LABEL): NamespaceReadiness( status="UP" if namespace_status[namespace] else "DOWN", @@ -255,7 +272,7 @@ def _aggregate_by_agent(self, components: dict[str, ComponentHealth]) -> tuple[d ) for namespace, keys in failing.items() } - return namespace_status, namespaces + return namespace_status, consumption_status, namespaces def get_cache_age_seconds(self) -> float: """Get the age of the cached health status in seconds. diff --git a/src/blueprint/agents/io/api/actuators/health/named_connections_health.py b/src/blueprint/agents/io/api/actuators/health/named_connections_health.py new file mode 100644 index 00000000..55e54dd1 --- /dev/null +++ b/src/blueprint/agents/io/api/actuators/health/named_connections_health.py @@ -0,0 +1,40 @@ +"""Readiness of an agent's named NATS connections, under ``nats_connections_readiness`` (named-connections plan, D5).""" + +from __future__ import annotations + +from .....clients.io.nats_client import NATSClient +from .....models.api import ComponentHealth +from .health_base import HealthCheckerBase + + +class NamedConnectionsHealthChecker(HealthCheckerBase): + """Reports every named connection of one agent, and fails only as its readiness mode says. + + Registered with ``affects_consumption=False``: a failure takes the agent out of readiness but + never pauses it, so a dead tenant connection cannot stop the agent on its other connections. + + - ``never`` (default): always healthy; the message still lists each connection's state. + - ``any``: healthy while at least one named connection is bound. + - ``all``: healthy only while every named connection is bound. + + Reads what the client recorded and does no I/O, so a poll never waits on a broker. + """ + + def __init__(self, client: NATSClient) -> None: + self._client = client + + async def health_check(self) -> ComponentHealth: + mode = self._client.connections_readiness + states = self._client.named_connection_states() + bound = sum(1 for state in states if state.bound) + if mode == "any": + healthy = bound > 0 + elif mode == "all": + healthy = bound == len(states) + else: + healthy = True + listed = ", ".join(state.describe() for state in states) or "none" + return ComponentHealth( + status="healthy" if healthy else "unhealthy", + message=f"{bound}/{len(states)} named connection(s) bound, readiness '{mode}': {listed}", + ) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index fda35b69..2f9d6f87 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -380,7 +380,7 @@ def settings_group(tmp_path: Path) -> GroupFactory: async with settings_group(settings, {"orders_x": OrdersHandler}) as clients: ... - The test writes every key itself, because the features under test are configured per test + ``apps``, if given, receives the assembled application. The test writes every key itself, because the features under test are configured per test (run limits, heartbeat, timeouts, a connection source). Waits until every agent's default subscriptions are ready and, when ``named`` is set, until each agent is bound on that many named connections. @@ -388,13 +388,15 @@ def settings_group(tmp_path: Path) -> GroupFactory: @asynccontextmanager async def factory( - settings: str, agents: dict[str, type], *, named: int = 0, ready_timeout: float = 20.0 + settings: str, agents: dict[str, type], *, named: int = 0, ready_timeout: float = 20.0, apps: list[Any] | None = None ) -> AsyncIterator[dict[str, NATSClient]]: (tmp_path / "settings.toml").write_text(settings, encoding="utf-8") config = Config(settings_files=["settings.toml"], root_path=str(tmp_path)) group = AgentGroup("integration", {name: AppBuilder().with_handler(handler) for name, handler in agents.items()}) try: app = group.assemble(config) + if apps is not None: + apps.append(app) # for a test that asks the app itself, e.g. its readiness probe async with app.router.lifespan_context(app): registry = Component.shared_registry assert registry is not None diff --git a/tests/integration/connection_source.py b/tests/integration/connection_source.py index fe29c26e..8261ed22 100644 --- a/tests/integration/connection_source.py +++ b/tests/integration/connection_source.py @@ -3,7 +3,8 @@ One named connection per tenant, each logging in as that tenant's agent user on the accounts broker (nats-accounts.conf). Everything per test comes from the process config the factory is called with, because that is all the framework hands it: ``test_source_url``, ``test_source_prefix`` (keeps -streams and subjects apart between tests), ``test_source_tenants`` and ``test_source_unclaimed``. +streams and subjects apart between tests), ``test_source_tenants``, ``test_source_unclaimed`` and +``test_source_wrong_password`` (tenants whose connection logs in with a password the broker refuses). """ from collections.abc import Callable, Iterator @@ -59,6 +60,7 @@ def __init__(self, config: Any) -> None: self.prefix = str(config.get("test_source_prefix")) self.users = {tenant: f"agent-{tenant.lower()}" for tenant in config.get("test_source_tenants") or []} self.unclaimed = tuple(config.get("test_source_unclaimed") or ()) + self.wrong_password = set(config.get("test_source_wrong_password") or ()) self.notifiers: list[Callable[[], None]] = [] SOURCES.append(self) @@ -76,7 +78,10 @@ def set_users(self, users: dict[str, str]) -> None: def connections(self) -> dict[str, ConnectionSpec]: return { - tenant: ConnectionSpec(name=tenant, url=self.url, user=user, password=PASSWORDS[user]) for tenant, user in self.users.items() + tenant: ConnectionSpec( + name=tenant, url=self.url, user=user, password="wrong-test-only" if tenant in self.wrong_password else PASSWORDS[user] + ) + for tenant, user in self.users.items() } def binding(self, agent: str, subjects: tuple[str, ...], connection: ConnectionSpec) -> JetStreamBinding: diff --git a/tests/integration/test_named_connections.py b/tests/integration/test_named_connections.py index 90460991..cf688575 100644 --- a/tests/integration/test_named_connections.py +++ b/tests/integration/test_named_connections.py @@ -7,7 +7,9 @@ - a run sees one tenant only: its connection, the source's run scope and the event's tenant agree; - a delivery the source rejects never runs and is termed; - a subject the source does not claim fails startup unless the hybrid mode is asked for; -- connections added, changed and removed at runtime lose and duplicate nothing. +- connections added, changed and removed at runtime lose and duplicate nothing; +- a tenant connection that cannot log in moves readiness as ``nats_connections_readiness`` says, + and never pauses the agent: its other connection keeps delivering. """ import json @@ -16,6 +18,7 @@ from collections.abc import AsyncIterator, Awaitable, Callable from typing import Any +import httpx import nats import pytest @@ -271,3 +274,45 @@ async def test_added_changed_and_removed_without_loss_or_duplicate( info = await consumer_info(accounts_url, subject_prefix, "A", agent) assert info.num_ack_pending == 0 and info.num_redelivered == 0 assert permission_violations(caplog) == [] + + +class TestADeadConnectionCountsForReadinessOnly: + """Step 5 / D5: a tenant whose connection cannot log in never pauses the agent on its other tenants.""" + + @pytest.mark.parametrize("mode, ready", [("never", True), ("any", True), ("all", False)]) + async def test_readiness_follows_the_mode_and_nothing_is_paused( + self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str, mode: str, ready: bool + ) -> None: + agent = f"risk_{subject_prefix}" + await operator(["A", "B"], {agent: ["risk.>"]}) + runs: list[dict[str, Any]] = [] + extra = f'test_source_wrong_password = ["B"]\nnats_connections_readiness = "{mode}"\nhealth_check_interval_seconds = 1\n' + apps: list[Any] = [] + async with settings_group( + settings(accounts_url, subject_prefix, ["A", "B"], extra), {agent: recording_handler(["risk.>"], runs)}, named=1, apps=apps + ) as clients: + client = clients[agent] + await wait_until( + lambda: {s.name: s.state for s in client.named_connection_states()} == {"A": "bound", "B": "retrying"}, + timeout=15, + description="A bound, B retrying", + ) + (b,) = [s for s in client.named_connection_states() if s.name == "B"] + assert "wrong-test-only" not in b.describe() + + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=apps[0]), base_url="http://it") as http: + + async def probe_settled() -> bool: + response = await http.get("/health/ready") + # The payload of a poll after both connections were tried, not the startup one. + return (response.status_code == 200) is ready and "B=retrying" in response.text + + await poll_until(probe_settled, timeout=10, description=f"readiness {'UP' if ready else 'DOWN'} under '{mode}'") + body = (await http.get("/health/ready")).json() + payload = body if ready else body["detail"] + entry = payload["components"][f"{agent}.nats_client:connections"] + assert "B=retrying" in entry["message"] and "wrong-test-only" not in json.dumps(payload) + + assert not client.consumption_paused, "a dead named connection never pauses the agent" + sent = await publish(accounts_url, subject_prefix, "A", "risk.created") + await wait_until(lambda: sent in [run["id"] for run in runs], timeout=10, description="A to keep delivering") diff --git a/tests/unit/agents/app_builder/test_app_builder.py b/tests/unit/agents/app_builder/test_app_builder.py index d12b59f4..c4378e3e 100644 --- a/tests/unit/agents/app_builder/test_app_builder.py +++ b/tests/unit/agents/app_builder/test_app_builder.py @@ -815,3 +815,45 @@ def test_a_wrong_path_fails_the_build( with pytest.raises(ValueError, match="nats_connection_source"): builder_for_build.build() + + def test_named_connections_get_a_readiness_only_entry( + self, builder_for_build: AppBuilder, mock_registry: MagicMock, all_build_mocks: types.SimpleNamespace, build_config: MagicMock + ) -> None: + """Step 5 / D5: the named connections count for readiness, never for the pause decision.""" + from blueprint.agents.io.api.actuators.health import NamedConnectionsHealthChecker + + wire_empty_registry(mock_registry) + mock_registry.get_event_handler.return_value = [MagicMock()] + client = all_build_mocks.nats_client.return_value + client.base_name, client.namespace = "nats_client", "" + self._config(build_config, "tests.unit.agents.clients.io.test_nats_connection_source:make_source") + + builder_for_build.build() + + (entries,) = all_build_mocks.actuator.return_value.add_health_providers.call_args.args + (entry,) = [entry for entry in entries if entry.name == "nats_client:connections"] + assert entry.affects_consumption is False + assert isinstance(entry.checker, NamedConnectionsHealthChecker) + + def test_without_a_source_there_is_no_such_entry( + self, builder_for_build: AppBuilder, mock_registry: MagicMock, all_build_mocks: types.SimpleNamespace, build_config: MagicMock + ) -> None: + wire_empty_registry(mock_registry) + mock_registry.get_event_handler.return_value = [MagicMock()] + self._config(build_config, None) + + builder_for_build.build() + + calls = all_build_mocks.actuator.return_value.add_health_providers.call_args_list + assert not [entry for call in calls for entry in call.args[0] if entry.name.endswith(":connections")] + + def test_the_client_can_ask_for_a_readiness_refresh( + self, builder_for_build: AppBuilder, mock_registry: MagicMock, all_build_mocks: types.SimpleNamespace, build_config: MagicMock + ) -> None: + wire_empty_registry(mock_registry) + mock_registry.get_event_handler.return_value = [MagicMock()] + self._config(build_config, None) + + builder_for_build.build() + + all_build_mocks.nats_client.return_value.set_health_refresh.assert_called_once_with(builder_for_build._refresh_health) diff --git a/tests/unit/agents/clients/io/test_nats_connection_readiness.py b/tests/unit/agents/clients/io/test_nats_connection_readiness.py new file mode 100644 index 00000000..c0df5739 --- /dev/null +++ b/tests/unit/agents/clients/io/test_nats_connection_readiness.py @@ -0,0 +1,305 @@ +"""Per-connection state, nats_connections_readiness and the readiness refresh (named-connections plan, step 5).""" + +import asyncio +from contextlib import nullcontext +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from nats.js import api as js_api + +from blueprint.agents.clients.io import nats_client as nats_client_module +from blueprint.agents.clients.io.nats_client import ( + CONNECTION_BOUND_GAUGE, + PERMISSION_VIOLATIONS_COUNTER, + NamedConnectionState, + NATSClient, +) +from blueprint.agents.clients.io.nats_connections import ConnectionSpec, JetStreamBinding +from blueprint.agents.io.api.actuators.health import NamedConnectionsHealthChecker +from blueprint.agents.models.events import CloudEvent + +PASSWORD = "PLACEHOLDER-not-a-secret" + + +def _binding(name: str) -> JetStreamBinding: + return JetStreamBinding( + subjects=("risk.>",), + stream=f"S_{name}", + durable=f"d-{name}", + deliver_subject=f"deliver.{name}", + deliver_group="g", + ack_wait=600.0, + subject_prefix=f"t.{name}.", + max_deliver=5, + deliver_policy=js_api.DeliverPolicy.NEW, + ) + + +class Source: + """Every declared subject is a tenant subject; one connection per name given.""" + + def __init__(self, *names: str) -> None: + self.names = names + + def claims(self, agent: str, subjects: tuple[str, ...]) -> tuple[str, ...]: + return subjects + + def connections(self) -> dict[str, ConnectionSpec]: + return {name: ConnectionSpec(name=name, url=f"nats://u:{PASSWORD}@h:4222", user="u", password=PASSWORD) for name in self.names} + + def binding(self, agent: str, subjects: tuple[str, ...], connection: ConnectionSpec) -> JetStreamBinding | None: + return _binding(connection.name) + + def validate(self, connection: str, subject: str, event: CloudEvent[Any]) -> str | None: + return None + + def run_scope(self, connection: str) -> Any: + return nullcontext() + + +class Broker: + """Stands in for opening a named link; a connection listed in ``failing`` raises what is set there.""" + + def __init__(self) -> None: + self.failing: dict[str, BaseException] = {} + self.denied: set[str] = set() + self.cores: dict[str, MagicMock] = {} + + async def open(self, link: Any) -> None: + if link.name in self.denied: + link.permission_errors.append("nats: permissions violation for subscription to x") + error = self.failing.get(link.name) + if error is not None: + raise error + core = MagicMock(is_closed=False, is_reconnecting=False) + core.subscribe = AsyncMock(return_value=MagicMock(drain=AsyncMock(), unsubscribe=AsyncMock())) + core.close = AsyncMock() + self.cores[link.name] = core + link.nats_client = core + + +@pytest.fixture +def broker() -> Broker: + return Broker() + + +@pytest.fixture +def configured(nats_client: NATSClient, mock_config: MagicMock) -> Any: + """Override config keys of the nats_client fixture: configured(**{key: value}).""" + base = mock_config.get.side_effect + + def apply(**values: Any) -> None: + merged = {"event_client_retry_delay": 0.01, **values} + mock_config.get.side_effect = lambda key, default=None: merged[key] if key in merged else base(key, default) + + apply() + return apply + + +@pytest.fixture(autouse=True) +def fake_broker(nats_client: NATSClient, broker: Broker, configured: Any) -> Any: + with patch.object(nats_client, "_open_named_link", side_effect=broker.open): + yield + + +async def _started(nats_client: NATSClient, *names: str) -> None: + nats_client.set_connection_source(Source(*names)) # type: ignore[arg-type] + with patch.object(nats_client, "_start_retry_task"): + await nats_client.subscribe({"risk.>": AsyncMock()}) + for _ in range(20): + await asyncio.sleep(0.01) + + +def _states(nats_client: NATSClient) -> dict[str, NamedConnectionState]: + return {state.name: state for state in nats_client.named_connection_states()} + + +class TestTheStateOfEachConnection: + async def test_a_bound_connection_reads_bound(self, nats_client: NATSClient) -> None: + await _started(nats_client, "A") + assert _states(nats_client)["A"] == NamedConnectionState("A", "bound") + + async def test_a_failing_connection_reads_retrying_with_its_error_redacted(self, nats_client: NATSClient, broker: Broker) -> None: + broker.failing["B"] = ConnectionError(f"nats://u:{PASSWORD}@h:4222 refused: {PASSWORD}") + await _started(nats_client, "A", "B") + + states = _states(nats_client) + assert states["A"].bound + assert states["B"].state == "retrying" + assert states["B"].last_error.startswith("ConnectionError: nats://***@h:4222 refused") + assert PASSWORD not in states["B"].describe() + + async def test_a_refused_permission_is_reported(self, nats_client: NATSClient, broker: Broker) -> None: + broker.failing["B"] = TimeoutError("no response") + broker.denied.add("B") + with patch.object(nats_client_module, "PERMISSION_RETRY_SECONDS", 0.01): + await _started(nats_client, "B") + assert _states(nats_client)["B"].permission_denied + assert "permission violation" in _states(nats_client)["B"].describe() + + async def test_the_error_is_cleared_once_it_binds(self, nats_client: NATSClient, broker: Broker) -> None: + broker.failing["B"] = ConnectionError("down") + await _started(nats_client, "B") + del broker.failing["B"] + for _ in range(20): + await asyncio.sleep(0.01) + assert _states(nats_client)["B"] == NamedConnectionState("B", "bound") + + async def test_a_refused_login_reads_retrying_although_connect_never_returns(self, nats_client: NATSClient) -> None: + """With max_reconnect_attempts=-1 nats.connect() retries a refused login itself; only error_cb hears of it.""" + await _started(nats_client, "B") + binding = nats_client._named[0] + binding.subscriptions_ready = False + link = binding.link + link.nats_client = None + connect = AsyncMock(return_value=MagicMock(is_closed=False, is_reconnecting=False)) + with ( + patch.object(nats_client_module.nats, "connect", connect), + patch.object(nats_client, "_open_named_link", NATSClient._open_named_link.__get__(nats_client)), + ): + await nats_client._open_named_link(link) + await connect.call_args.kwargs["error_cb"](Exception("nats: 'Authorization Violation'")) + + assert _states(nats_client)["B"] == NamedConnectionState("B", "retrying", "Exception: nats: 'Authorization Violation'") + + async def test_a_lost_broker_reads_reconnecting(self, nats_client: NATSClient, broker: Broker) -> None: + await _started(nats_client, "A") + nats_client._named[0].subscriptions_ready = False + broker.cores["A"].is_reconnecting = True + assert _states(nats_client)["A"].state == "reconnecting" + + async def test_a_paused_agent_reads_paused(self, nats_client: NATSClient) -> None: + await _started(nats_client, "A") + await nats_client.pause_consumption() + assert _states(nats_client)["A"].state == "paused" + + +class TestTheReadinessMode: + async def test_it_defaults_to_never(self, nats_client: NATSClient) -> None: + await _started(nats_client, "A") + assert nats_client.connections_readiness == "never" + + @pytest.mark.parametrize("raw, mode", [("any", "any"), ("ALL", "all"), (" never ", "never")]) + async def test_the_three_modes_are_accepted(self, nats_client: NATSClient, configured: Any, raw: str, mode: str) -> None: + configured(nats_connections_readiness=raw) + await _started(nats_client, "A") + assert nats_client.connections_readiness == mode + + async def test_anything_else_fails_subscribe_naming_the_key(self, nats_client: NATSClient, configured: Any) -> None: + configured(nats_connections_readiness="some") + with pytest.raises(ValueError, match="nats_connections_readiness"): + await _started(nats_client, "A") + + +class TestTheCheckerFollowsTheMode: + @staticmethod + def _client(mode: str, *states: NamedConnectionState) -> MagicMock: + client = MagicMock(connections_readiness=mode) + client.named_connection_states.return_value = states + return client + + BOUND = NamedConnectionState("A", "bound") + DOWN = NamedConnectionState("B", "retrying", "ConnectionError: refused") + + @pytest.mark.parametrize( + "mode, states, status", + [ + ("never", (DOWN,), "healthy"), + ("never", (), "healthy"), + ("any", (BOUND, DOWN), "healthy"), + ("any", (DOWN,), "unhealthy"), + ("any", (), "unhealthy"), + ("all", (BOUND, DOWN), "unhealthy"), + ("all", (BOUND,), "healthy"), + ], + ) + async def test_status(self, mode: str, states: tuple[NamedConnectionState, ...], status: str) -> None: + result = await NamedConnectionsHealthChecker(self._client(mode, *states)).health_check() # type: ignore[arg-type] + assert result.status == status + + async def test_the_message_names_each_connection_and_why(self) -> None: + result = await NamedConnectionsHealthChecker(self._client("all", self.BOUND, self.DOWN)).health_check() # type: ignore[arg-type] + assert result.message == "1/2 named connection(s) bound, readiness 'all': A=bound, B=retrying (ConnectionError: refused)" + + +class TestReadinessIsReEvaluatedAtOnce: + async def test_a_reconnect_of_a_paused_agent_refreshes(self, nats_client: NATSClient) -> None: + refresh = AsyncMock() + nats_client.set_health_refresh(refresh) + nats_client._subscriptions_managed = True + nats_client._consumption_paused = True + + await nats_client._on_reconnected() + await asyncio.sleep(0) + + refresh.assert_awaited_once() + + async def test_a_reconnect_of_a_serving_agent_does_not(self, nats_client: NATSClient) -> None: + refresh = AsyncMock() + nats_client.set_health_refresh(refresh) + nats_client._subscriptions_managed = True + + await nats_client._on_reconnected() + await asyncio.sleep(0) + + refresh.assert_not_awaited() + + async def test_a_named_connection_binding_refreshes_when_the_mode_reads_it(self, nats_client: NATSClient, configured: Any) -> None: + configured(nats_connections_readiness="any") + refresh = AsyncMock() + nats_client.set_health_refresh(refresh) + await _started(nats_client, "A") + refresh.assert_awaited_once() + + async def test_under_never_it_does_not(self, nats_client: NATSClient) -> None: + refresh = AsyncMock() + nats_client.set_health_refresh(refresh) + await _started(nats_client, "A") + refresh.assert_not_awaited() + + async def test_a_failing_refresh_is_logged_with_the_agent(self, nats_client: NATSClient, caplog: pytest.LogCaptureFixture) -> None: + nats_client.set_health_refresh(AsyncMock(side_effect=RuntimeError("poll broke"))) + nats_client._subscriptions_managed = True + nats_client._consumption_paused = True + + await nats_client._on_reconnected() + for _ in range(3): + await asyncio.sleep(0) + + assert "re-evaluating readiness failed: poll broke" in caplog.text + + +class TestMetrics: + async def test_the_bound_gauge_reports_each_connection(self, nats_client: NATSClient, broker: Broker) -> None: + meter = MagicMock() + broker.failing["B"] = ConnectionError("down") + with patch.object(nats_client_module, "agent_meter", return_value=meter): + await _started(nats_client, "A", "B") + + (name,), kwargs = meter.create_observable_gauge.call_args + assert name == CONNECTION_BOUND_GAUGE + observations = {o.attributes["connection"]: o.value for o in kwargs["callbacks"][0](MagicMock())} + assert observations == {"A": 1, "B": 0} + + async def test_no_gauge_without_a_source(self, nats_client: NATSClient) -> None: + meter = MagicMock() + with patch.object(nats_client_module, "agent_meter", return_value=meter), patch.object(nats_client, "_start_retry_task"): + await nats_client.subscribe({"risk.>": AsyncMock()}) + meter.create_observable_gauge.assert_not_called() + + async def test_a_permission_violation_is_counted(self, nats_client: NATSClient) -> None: + meter = MagicMock() + link = nats_client_module._Link(name="A", url="nats://h:4222") + connect = AsyncMock(return_value=MagicMock(is_closed=False)) + with ( + patch.object(nats_client_module, "agent_meter", return_value=meter), + patch.object(nats_client_module.nats, "connect", connect), + patch.object(nats_client, "_open_named_link", NATSClient._open_named_link.__get__(nats_client)), + ): + await nats_client._open_named_link(link) + await connect.call_args.kwargs["error_cb"](Exception("nats: Permissions Violation for Subscription to t.A.x")) + + assert meter.create_counter.call_args.kwargs["name"] == PERMISSION_VIOLATIONS_COUNTER + meter.create_counter.return_value.add.assert_called_once_with(1, {"agent": "", "connection": "A"}) + assert link.permission_errors diff --git a/tests/unit/agents/io/api/actuators/health/test_health_cache.py b/tests/unit/agents/io/api/actuators/health/test_health_cache.py index 604a1288..6e8fd9fd 100644 --- a/tests/unit/agents/io/api/actuators/health/test_health_cache.py +++ b/tests/unit/agents/io/api/actuators/health/test_health_cache.py @@ -1,5 +1,6 @@ """Unit tests for HealthCheckCache.""" +import asyncio from unittest.mock import AsyncMock, MagicMock, patch import pytest @@ -316,6 +317,83 @@ async def test_it_is_reported_with_no_checks_registered_at_all(self) -> None: supervisor.observe.assert_awaited_once() +class TestAReadinessOnlyCheck: + """D5: a named connection's state feeds readiness, never the pause decision.""" + + async def test_it_takes_the_agent_out_of_readiness_but_never_pauses_it(self) -> None: + supervisor = TestTheVerdictIsPerAgent._supervisor(["", "orders"], set()) + cache = HealthCheckCache(supervisor=supervisor) + readiness_only = HealthCheckEntry( + name="nats_client:connections", namespace="orders", checker=_make_provider("unhealthy", "B=retrying"), affects_consumption=False + ) + cache.set_health_entries([_entry("nats_client", "healthy", namespace="orders"), readiness_only]) + + await cache._run_health_checks() + + response = await cache.get_health_status() + assert response.status == "DOWN" + assert response.namespaces["orders"].failing == ["orders.nats_client:connections"] + supervisor.observe.assert_awaited_once_with({"": True, "orders": True}) + + async def test_a_failing_consumption_check_still_pauses_beside_it(self) -> None: + supervisor = TestTheVerdictIsPerAgent._supervisor(["", "orders"], set()) + cache = HealthCheckCache(supervisor=supervisor) + readiness_only = HealthCheckEntry( + name="nats_client:connections", namespace="orders", checker=_make_provider("healthy"), affects_consumption=False + ) + cache.set_health_entries([_entry("nats_client", "unhealthy", "broker gone", namespace="orders"), readiness_only]) + + await cache._run_health_checks() + + supervisor.observe.assert_awaited_once_with({"": True, "orders": False}) + + +class TestTheProbeNeverWaitsForAPoll: + """Review finding #6: a slow check held the lock the readiness read waited for.""" + + async def test_the_cached_answer_comes_at_once_while_a_check_hangs(self) -> None: + cache = HealthCheckCache() + release = asyncio.Event() + + async def slow() -> ComponentHealth: + await release.wait() + return ComponentHealth(status="unhealthy", message="late") + + checker = MagicMock() + checker.health_check = slow + cache.set_health_entries([HealthCheckEntry(name="nats", namespace="", checker=checker)]) + poll = asyncio.ensure_future(cache._run_health_checks()) + await asyncio.sleep(0) + + before = await asyncio.wait_for(cache.get_health_status(), timeout=0.1) + release.set() + await poll + + assert before.status == "UP" + assert (await cache.get_health_status()).status == "DOWN" + + async def test_polls_are_still_serialised(self) -> None: + cache = HealthCheckCache() + running = 0 + overlap = 0 + + async def check() -> ComponentHealth: + nonlocal running, overlap + running += 1 + overlap = max(overlap, running) + await asyncio.sleep(0.01) + running -= 1 + return ComponentHealth(status="healthy", message="ok") + + checker = MagicMock() + checker.health_check = check + cache.set_health_entries([HealthCheckEntry(name="nats", namespace="", checker=checker)]) + + await asyncio.gather(cache._run_health_checks(), cache.refresh()) + + assert overlap == 1 + + # --------------------------------------------------------------------------- # A standalone agent logs what v0.8.1 logged # --------------------------------------------------------------------------- From 47a71c1b34672b1cf2a764e23a96a2b98d22f5be Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 16:17:30 +0200 Subject: [PATCH 085/133] feat(handler): HandlerResult.skipped for a responsible handler with nothing to do (D11) A handler that is selected for an event but finds this event needs nothing returns HandlerResult.skipped(reason): the chain stops (no later handler is asked, unlike None), the run reports ProcessingStatus.SKIPPED, nothing is published, the reason is logged at INFO and counted as blueprint.events.skipped instead of unhandled, and the delivery is acknowledged as for any return. A REST caller gets success=true with the reason. Live against nats:2.10-alpine: acked once, no redelivery after ack_wait, nothing published, second handler not called; control on the unchanged code (None from the only handler) logged the "No handler processed event" WARNING. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 5 + ...26-08-28-multi-agent-grouping-changelog.md | 20 +++ docs/plans/2026-10-14-named-connections.md | 8 + docs/specs/2026-08-28-multi-agent-grouping.md | 9 ++ src/blueprint/agents/handler/handler_chain.py | 6 + .../io/api/eventing/event_handling_base.py | 11 ++ src/blueprint/agents/io/api/rest_api_base.py | 3 +- src/blueprint/agents/models/events.py | 38 +++++ src/blueprint/agents/models/result.py | 4 +- .../eventing/event_processing_service.py | 16 +- tests/integration/test_skipped_result.py | 138 ++++++++++++++++++ tests/unit/agents/handler/TESTS.md | 2 +- .../unit/agents/handler/test_handler_chain.py | 36 +++++ tests/unit/agents/io/TESTS.md | 4 +- .../api/eventing/test_event_handling_base.py | 32 +++- .../unit/agents/io/api/test_rest_api_base.py | 25 ++++ tests/unit/agents/models/TESTS.md | 2 +- tests/unit/agents/models/test_events.py | 39 +++++ tests/unit/agents/services/TESTS.md | 2 +- .../eventing/test_event_processing_service.py | 37 +++++ 20 files changed, 426 insertions(+), 11 deletions(-) create mode 100644 tests/integration/test_skipped_result.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c4f5ce4..8008b3ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -172,6 +172,11 @@ ### Added +- **`HandlerResult.skipped(reason)`.** A handler that is responsible for an event but finds it needs + nothing returns it: the chain stops (no later handler is asked, unlike `None`), the delivery is + acknowledged, nothing is published, the reason is logged at INFO and the event is counted as + `blueprint.events.skipped` rather than as unhandled. The run reports the new + `ProcessingStatus.SKIPPED`; a REST caller gets `success = true` with the reason as message. - **Per-connection state and `nats_connections_readiness`.** Each agent with named connections gets a readiness entry `.nats_client:connections` listing every connection as `bound`, `connecting`, `reconnecting`, `retrying` (with the last error, redacted) or `paused`, and any permission violation, diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 21892932..b3e44f50 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8568,6 +8568,26 @@ deterministic, see Open points). accounts broker -- tenant B with a wrong password, per mode: A bound and B `retrying`, `/health/ready` 200/200/503 for never/any/all, the agent not paused, A still delivering, no password in the payload. +### A responsible handler can skip an event: `HandlerResult.skipped` (named connections, D11) + +- **`HandlerResult.skipped(reason, *, metadata=None)`** (`models/events.py`): a new field + `skip_reason`, a validator that refuses an empty reason and a skip that would also carry + `event_type`, `subject` or `data`, and the property `is_skipped`. +- **`HandlerChain._dispatch`**: a skipped result is returned like any non-`None` result -- so the + chain stops and no later handler is asked -- and is logged at INFO with the reason, with the span + attributes `handler.skipped` and `handler.skip_reason`. +- **`ProcessingStatus.SKIPPED`**: `EventProcessingService.process_event` reports it when every result + of the run is a skip (a list mixing a skip with real results stays `PROCESSED`; the skip publishes + nothing either way, because it has no `event_type`). Message: `Skipped: `. +- **`EventHandlingBase._process_cloud_event`** counts it as `blueprint.events.skipped` (`agent`, + `topic`), apart from `blueprint.events.unhandled`. Acknowledgement is unchanged: a return acks. +- **`RestApiBase._process_resource`**: `success` is true for `PROCESSED` and `SKIPPED`. +- Live in WSL against `nats:2.10-alpine` (`tests/integration/test_skipped_result.py`): a skipped event + acked once, ack floor 1, 0 redeliveries after `nats_ack_wait`, nothing on the outbound subject, the + second handler never called, INFO line with the reason and no "No handler processed event". Control + on the unchanged code (the only handler returning `None`, the way an agent had to say "nothing to + do"): acked, but WARNING `No handler processed event 'orders.created'` and counted as unhandled. + --- ## Open points diff --git a/docs/plans/2026-10-14-named-connections.md b/docs/plans/2026-10-14-named-connections.md index 5bc2fa06..aeac2495 100644 --- a/docs/plans/2026-10-14-named-connections.md +++ b/docs/plans/2026-10-14-named-connections.md @@ -239,6 +239,14 @@ All taken on 2026-10-14; each entry starts with the decision, followed by the an subjects it serves; a subject no connection serves stays on the default connection, as today. The default connection then subscribes only what is left -- possibly nothing, which matters where the process account may not subscribe at all (the first consumer). +- **D11 -- "Responsible, but nothing to do" is a result, not a decline. Decided 2026-10-15: (B), + `HandlerResult.skipped(reason)`.** `can_handle_event` routes on the envelope only; whether a + particular event needs work is decided by the service the handler calls, and the handler reports + "no" as `HandlerResult.skipped(reason)`: the chain stops, the delivery is acknowledged, the reason + is logged at INFO and counted as `blueprint.events.skipped`, nothing is published. Rejected: (A) a + second hook (`is_relevant`) beside `can_handle_event` -- the relevance check usually needs the same + reads as the work, so it would split one service call into two. `None` keeps meaning "offer the + event to the next handler"; an event no handler is selected for is unchanged. Done in step 6. --- diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md index 0368f686..bb227658 100644 --- a/docs/specs/2026-08-28-multi-agent-grouping.md +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -516,6 +516,15 @@ It **MUST** be counted per namespace and topic, for one purpose: the *proportion events a namespace declines is how a too-broad subscription shows up (sec. 7.7). A high count is a question about the subject filter, not about the handler. +**A skip is the selected handler's own "nothing to do" (added 2026-10-15).** A handler that is +responsible for an event -- `can_handle_event` routed it there -- and finds that this particular +event needs nothing returns `HandlerResult.skipped(reason)`. The chain stops (no later handler is +asked, unlike `None`), the run reports `ProcessingStatus.SKIPPED`, nothing is published, the reason +is logged at INFO, and the transport acknowledges as for any return. It is counted apart from +unmatched events, as `blueprint.events.skipped` per agent and topic: a skip is the agent's relevance +rule at work, not a sign that the subscription is too broad. A REST caller gets `success = true` +with the reason as message. + **Both transports MUST map the same outcome to the same disposition.** Dapr's response dict *is* its acknowledgement, so the table above is normative for `dapr.py` and `event_handling_base.handle_event` exactly as it is for `nats_client.py`. They disagree in two diff --git a/src/blueprint/agents/handler/handler_chain.py b/src/blueprint/agents/handler/handler_chain.py index c18ce674..3b5d8116 100644 --- a/src/blueprint/agents/handler/handler_chain.py +++ b/src/blueprint/agents/handler/handler_chain.py @@ -357,6 +357,12 @@ async def _dispatch(self, event: CloudEvent[Any], context: dict[str, Any]) -> An result = await handler.handle(event, context) if result is not None: span.set_attribute("handler.processed_by", handler.name) + if isinstance(result, HandlerResult) and result.is_skipped: + # The selected handler's own answer that the event needs nothing: an + # ordinary outcome, so INFO and no WARNING, and the chain stops here. + span.set_attribute("handler.skipped", True) + span.set_attribute("handler.skip_reason", result.skip_reason or "") + logger.info("Handler '%s' skipped event '%s': %s", handler.name, event.type, result.skip_reason) return result logger.info("Handler '%s' passed event '%s' to next handler", handler.name, event.type) diff --git a/src/blueprint/agents/io/api/eventing/event_handling_base.py b/src/blueprint/agents/io/api/eventing/event_handling_base.py index 6f39ee09..714c2a22 100644 --- a/src/blueprint/agents/io/api/eventing/event_handling_base.py +++ b/src/blueprint/agents/io/api/eventing/event_handling_base.py @@ -23,10 +23,12 @@ UNHANDLED_EVENTS_COUNTER = "blueprint.events.unhandled" DUPLICATE_EVENTS_COUNTER = "blueprint.events.duplicate" +SKIPPED_EVENTS_COUNTER = "blueprint.events.skipped" _COUNTER_DESCRIPTIONS = { UNHANDLED_EVENTS_COUNTER: "Events an agent received and found nothing to do with", DUPLICATE_EVENTS_COUNTER: "Events an agent recognised as already processed and did not dispatch", + SKIPPED_EVENTS_COUNTER: "Events whose selected handler was responsible but found nothing to do (HandlerResult.skipped)", } @@ -89,6 +91,11 @@ async def _process_cloud_event( URL path under Dapr, and remembering each distinct value would let a caller grow this process's memory. + A dispatch whose selected handler returned ``HandlerResult.skipped`` is counted apart + too. The handler was responsible and decided the event needs nothing; the chain has + already logged the reason at INFO. Counting it as unhandled would blame the + subscription for what is the agent's own relevance rule. + A dispatch the chain skipped as a duplicate is counted apart from both (spec sec. 7.4). It reaches here looking exactly like an unmatched event -- no handler ran, so no result came back -- but the two say opposite things about the @@ -111,6 +118,10 @@ async def _process_cloud_event( elif processing_result.status is ProcessingStatus.NO_HANDLER_FOUND: self._count(UNHANDLED_EVENTS_COUNTER, agent, topic) logger.debug("No handler in '%s' had work for event %s on topic '%s'", agent or ROOT_LABEL, cloud_event.id, topic) + elif processing_result.status is ProcessingStatus.SKIPPED: + # Apart from unhandled: a skip is the responsible handler's decision, so a high count says + # the agent's own relevance rules filter a lot -- not that its subscription is too broad. + self._count(SKIPPED_EVENTS_COUNTER, agent, topic) return processing_result def _count(self, name: str, namespace: str, topic: str) -> None: diff --git a/src/blueprint/agents/io/api/rest_api_base.py b/src/blueprint/agents/io/api/rest_api_base.py index 69030517..08595bc8 100644 --- a/src/blueprint/agents/io/api/rest_api_base.py +++ b/src/blueprint/agents/io/api/rest_api_base.py @@ -242,7 +242,8 @@ async def _process_resource(self, request: Request, payload: Any) -> ProcessReso # another agent's handlers. processing_result = await event_processing_service.process_rest_request(payload, context, namespace=self.namespace) - success = processing_result.status == ProcessingStatus.PROCESSED + # A skip is a success: the responsible handler ran and decided there is nothing to do. + success = processing_result.status in (ProcessingStatus.PROCESSED, ProcessingStatus.SKIPPED) success_message = processing_result.message or "Processing completed successfully" # Extract response data from handler results diff --git a/src/blueprint/agents/models/events.py b/src/blueprint/agents/models/events.py index 03f6d009..5c2a089c 100644 --- a/src/blueprint/agents/models/events.py +++ b/src/blueprint/agents/models/events.py @@ -84,6 +84,8 @@ class HandlerResult(BaseModel): Handlers can return: - A single HandlerResult to publish one event - A list of HandlerResult objects to publish multiple events + - ``HandlerResult.skipped(reason)`` when the handler is responsible for the event but the + event needs nothing: the chain stops, the delivery is acknowledged and the reason is logged - None to pass control to the next handler - Any other value for internal chaining (no event publication) """ @@ -92,6 +94,42 @@ class HandlerResult(BaseModel): subject: str | None = None data: dict[str, Any] | None = None metadata: dict[str, Any] | None = None + skip_reason: str | None = None + + @model_validator(mode="after") + def _skip_carries_nothing_else(self) -> "HandlerResult": + """A skipped result publishes nothing and returns nothing, so it may carry only its reason. + + Without this, ``HandlerResult(event_type="x", skip_reason="y")`` would be both published and + reported as skipped, and nobody could tell from the result which of the two the author meant. + """ + if self.skip_reason is not None: + if not self.skip_reason.strip(): + raise ValueError("HandlerResult.skip_reason must name why the event needs nothing, not be empty") + if self.event_type is not None or self.subject is not None or self.data is not None: + raise ValueError("A skipped HandlerResult carries only its reason (and metadata), never event_type, subject or data") + return self + + @classmethod + def skipped(cls, reason: str, *, metadata: dict[str, Any] | None = None) -> "HandlerResult": + """Return the result of a handler that is responsible for the event but finds it needs nothing. + + This is the answer of the handler that *was* selected: the chain stops here and offers the + event to no other handler, the transport acknowledges it, and the reason is logged at INFO + and counted as ``blueprint.events.skipped``. Return ``None`` instead only when another + handler should get the event; an event no handler is selected for keeps the WARNING. + + Args: + reason: Why the event needs nothing, e.g. ``"status unchanged"``. Logged; keep personal + data and secrets out of it. + metadata: Optional values kept on the processing result for the caller; never published. + """ + return cls(skip_reason=reason, metadata=metadata) + + @property + def is_skipped(self) -> bool: + """Whether this is a :meth:`skipped` result.""" + return self.skip_reason is not None def create_cloud_event( diff --git a/src/blueprint/agents/models/result.py b/src/blueprint/agents/models/result.py index e77e7d3d..43bd566d 100644 --- a/src/blueprint/agents/models/result.py +++ b/src/blueprint/agents/models/result.py @@ -72,13 +72,15 @@ class ProcessingStatus(StrEnum): PROCESSED = "processed" NO_HANDLER_FOUND = "no_handler_found" + # The selected handler was responsible but the event needed nothing (HandlerResult.skipped). + SKIPPED = "skipped" class ProcessingResult(BaseModel): """Structured result emitted by the processing service.""" request_id: str = Field(..., description="Unique identifier for the processing request.") - status: ProcessingStatus = Field(..., description="Processing status (e.g., 'processed', 'no_handler_found').") + status: ProcessingStatus = Field(..., description="Processing status ('processed', 'skipped' or 'no_handler_found').") result: list[HandlerResult] = Field(default_factory=list, description="Handler results produced during processing.") metadata: dict[str, Any] = Field(default_factory=dict, description="Additional metadata about the processing run.") message: str | None = Field(None, description="Optional explanatory message for the processing outcome.") diff --git a/src/blueprint/agents/services/eventing/event_processing_service.py b/src/blueprint/agents/services/eventing/event_processing_service.py index 99662294..c2fea529 100644 --- a/src/blueprint/agents/services/eventing/event_processing_service.py +++ b/src/blueprint/agents/services/eventing/event_processing_service.py @@ -189,7 +189,14 @@ async def process_event( self._chain_for(namespace).release(event) raise - status = ProcessingStatus.NO_HANDLER_FOUND if handler_result is None else ProcessingStatus.PROCESSED + if handler_result is None: + status = ProcessingStatus.NO_HANDLER_FOUND + elif handler_results and all(result.is_skipped for result in handler_results): + # Only a run whose every result is a skip counts as skipped: a list that mixes a + # skip with real results did work, and its skips simply publish nothing. + status = ProcessingStatus.SKIPPED + else: + status = ProcessingStatus.PROCESSED return self._build_result(request_id, handler_results, status) # A failure propagates unlogged: every caller is a transport edge (NATS, Dapr, REST) that @@ -267,7 +274,12 @@ def _build_result( status: ProcessingStatus, ) -> ProcessingResult: """Build a ProcessingResult from handler outputs.""" - message = "No handler processed this event" if status == ProcessingStatus.NO_HANDLER_FOUND else "Message acknowledged" + if status == ProcessingStatus.NO_HANDLER_FOUND: + message = "No handler processed this event" + elif status == ProcessingStatus.SKIPPED: + message = "Skipped: " + "; ".join(result.skip_reason or "" for result in handler_results) + else: + message = "Message acknowledged" return ProcessingResult( request_id=request_id, status=status, diff --git a/tests/integration/test_skipped_result.py b/tests/integration/test_skipped_result.py new file mode 100644 index 00000000..752425d3 --- /dev/null +++ b/tests/integration/test_skipped_result.py @@ -0,0 +1,138 @@ +"""``HandlerResult.skipped`` on a real broker: acknowledged once, nothing published, nobody else asked. + +A handler that is responsible for an event but finds it needs nothing returns +``HandlerResult.skipped(reason)``. Four claims, each read off the broker or the process rather +than off the framework's own account: + +1. the inbound message is acknowledged -- ``num_ack_pending`` 0, ack floor advanced; +2. it is not redelivered once ``nats_ack_wait`` has passed; +3. nothing is published to the subject the outbound event type is mapped to; +4. the chain stops: a second, later handler that would also accept the event is never called. + +The control for claim 4 is the ordinary ``None`` return, which does pass the event on. +""" + +import asyncio +import uuid +from typing import Any + +import pytest +from nats.aio.client import Client as NatsClient +from nats.js import JetStreamContext + +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.events import GenericCloudEvent, HandlerResult + +from .conftest import OUTBOUND_EVENT_TYPE +from .helpers import poll_until, wait_until +from .test_event_path import collect_from, only_consumer + + +def _handlers(topic: str, first_returns: Any, calls: list[str]) -> tuple[type[EventHandlerBase], type[EventHandlerBase]]: + """Two handlers on ``topic``: the first returns ``first_returns``, the second would publish.""" + + class First(EventHandlerBase): + def __init__(self) -> None: + super().__init__(priority=10) + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return [topic] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> Any: + calls.append("first") + return first_returns + + class Second(EventHandlerBase): + def __init__(self) -> None: + super().__init__(priority=20) + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return [topic] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult: + calls.append("second") + return HandlerResult(event_type=OUTBOUND_EVENT_TYPE, data={"from": "second"}) + + return First, Second + + +def _an_order() -> bytes: + event = GenericCloudEvent(id=str(uuid.uuid4()), source="integration-test", type="orders.created", data={"order_id": "o-1"}) + return event.model_dump_json().encode() + + +class TestASkippedEvent: + async def test_it_is_acknowledged_once_publishes_nothing_and_asks_nobody_else( + self, + nats_app: Any, + subject_prefix: str, + jetstream: JetStreamContext, + jetstream_stream: str, + nats_connection: NatsClient, + outbound_subject: str, + caplog: pytest.LogCaptureFixture, + ) -> None: + topic = f"{subject_prefix}.orders.created" + calls: list[str] = [] + first, second = _handlers(topic, HandlerResult.skipped("status unchanged"), calls) + + with caplog.at_level("INFO"): + async with nats_app(first, second): + outbound = await collect_from(nats_connection, outbound_subject) + await jetstream.publish(topic, _an_order()) + await wait_until(lambda: bool(calls), timeout=10, description="the first handler to be called") + + async def acknowledged() -> bool: + consumer = await only_consumer(jetstream, jetstream_stream) + return bool(consumer.num_ack_pending == 0 and consumer.ack_floor.stream_seq == 1) + + await poll_until(acknowledged, timeout=10, description="the broker to record the acknowledgement") + await asyncio.sleep(3.0) # nats_ack_wait is 2.0: an unacknowledged message would be back by now + consumer = await only_consumer(jetstream, jetstream_stream) + + assert calls == ["first"], f"the chain went on after the skip: {calls}" + assert outbound.empty(), "a skipped event published something" + assert consumer.num_ack_pending == 0 + assert consumer.num_redelivered == 0, "the broker redelivered a skipped event" + skipped = [r for r in caplog.records if "skipped event" in r.getMessage()] + assert skipped and skipped[0].levelname == "INFO" and "status unchanged" in skipped[0].getMessage() + assert not [r for r in caplog.records if "No handler processed event" in r.getMessage()] + + async def test_control_a_none_return_passes_the_event_to_the_next_handler( + self, + nats_app: Any, + subject_prefix: str, + jetstream: JetStreamContext, + nats_connection: NatsClient, + outbound_subject: str, + ) -> None: + """The same two handlers with ``None`` instead of a skip: the second one runs and publishes.""" + topic = f"{subject_prefix}.orders.created" + calls: list[str] = [] + first, second = _handlers(topic, None, calls) + + async with nats_app(first, second): + outbound = await collect_from(nats_connection, outbound_subject) + await jetstream.publish(topic, _an_order()) + published = await asyncio.wait_for(outbound.get(), timeout=10) + + assert calls == ["first", "second"] + assert GenericCloudEvent.model_validate_json(published).data == {"from": "second"} diff --git a/tests/unit/agents/handler/TESTS.md b/tests/unit/agents/handler/TESTS.md index 1522a2b4..bfda2242 100644 --- a/tests/unit/agents/handler/TESTS.md +++ b/tests/unit/agents/handler/TESTS.md @@ -9,7 +9,7 @@ Test coverage for `src/blueprint/agents/handler/`. | File | Class under test | What is covered | |---|---|---| | `test_event_handler_base.py` | `EventHandlerBase` | `__init__` stores default and custom priority; `can_handle` delegates to `can_handle_event` (True/False); `handle` passes through `HandlerResult`, `list[HandlerResult]`, dict, and `None` unchanged; `get_published_event_types` default returns `None`; `get_subscribed_topics` default returns `[]`; `__lt__` priority ordering and `sorted()` correctness | -| `test_handler_chain.py` | `HandlerChain` | `on_startup`/`on_shutdown` lifecycle no-ops; `process` with no handlers → `None`; declining handler skipped; accepting handler result returned; handler returning `None` passes to next; chain stops at first non-`None` result; handlers executed in ascending priority order; handler exception re-raised | +| `test_handler_chain.py` | `HandlerChain` | `on_startup`/`on_shutdown` lifecycle no-ops; `process` with no handlers → `None`; declining handler skipped; accepting handler result returned; handler returning `None` passes to next; chain stops at first non-`None` result; a `HandlerResult.skipped` stops the chain without asking the next handler and logs its reason at INFO with no WARNING; handlers executed in ascending priority order; handler exception re-raised | --- diff --git a/tests/unit/agents/handler/test_handler_chain.py b/tests/unit/agents/handler/test_handler_chain.py index d8032b60..cf75449b 100644 --- a/tests/unit/agents/handler/test_handler_chain.py +++ b/tests/unit/agents/handler/test_handler_chain.py @@ -98,6 +98,42 @@ async def test_chain_stops_after_first_non_none_result( result = await chain.process(cloud_event, {}) assert result is first_result + async def test_skipped_result_stops_the_chain_and_offers_the_event_to_nobody_else( + self, chain: HandlerChain, mock_registry: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + """A skip is the selected handler's answer, not a decline: the next handler must not run. + + Regression guard for the difference to ``None``, which does pass the event on. + """ + asked: list[int] = [] + + class Recording(StubHandler): + async def can_handle_event(self, event, context): + asked.append(self._priority) + return True + + skip = HandlerResult.skipped("status unchanged") + _wire_handlers(mock_registry, [Recording(priority=10, result=skip), Recording(priority=20, result=HandlerResult(event_type="x"))]) + result = await chain.process(cloud_event, {}) + assert result is skip + assert asked == [10] + + async def test_skipped_result_logs_its_reason_at_info_and_no_warning( + self, + chain: HandlerChain, + mock_registry: MagicMock, + cloud_event: GenericCloudEvent, + caplog: pytest.LogCaptureFixture, + ) -> None: + """A skip is an ordinary outcome: its reason at INFO, never the no-handler WARNING.""" + _wire_handlers(mock_registry, [StubHandler(result=HandlerResult.skipped("status unchanged"))]) + with caplog.at_level("DEBUG", logger="blueprint.agents.handler.handler_chain"): + await chain.process(cloud_event, {}) + skipped = [r for r in caplog.records if "skipped event" in r.getMessage()] + assert [r.levelname for r in skipped] == ["INFO"] + assert "status unchanged" in skipped[0].getMessage() + assert not [r for r in caplog.records if r.levelname == "WARNING"] + async def test_handlers_executed_in_ascending_priority_order( self, chain: HandlerChain, mock_registry: MagicMock, cloud_event: GenericCloudEvent ) -> None: diff --git a/tests/unit/agents/io/TESTS.md b/tests/unit/agents/io/TESTS.md index e135f528..37b347e2 100644 --- a/tests/unit/agents/io/TESTS.md +++ b/tests/unit/agents/io/TESTS.md @@ -8,12 +8,12 @@ Test coverage for `src/blueprint/agents/io/`. | File | Class under test | What is covered | |---|---|---| -| `api/test_rest_api_base.py` | `RestApiBase` | HTTP verb decorators attach `_route`, `_wire_routes` registers routes, `_build_problem_details` RFC 7807 fields, `_resolve_status_title` | +| `api/test_rest_api_base.py` | `RestApiBase` | HTTP verb decorators attach `_route`, `_wire_routes` registers routes, `_build_problem_details` RFC 7807 fields, `_resolve_status_title`, a skipped run answers a REST caller with `success=True`, the skip reason as message and no data | | `api/actuators/test_actuator_api.py` | `ActuatorApi` | `_sanitize_config` (flat + nested), `liveness_probe` always UP, `on_startup`/`on_shutdown` lifecycle, `env_status` per-namespace breakdown and masking, reported `envvar_prefix`, one audited tree read per request | | `api/actuators/health/test_client_health.py` | `ClientHealthChecker` | `connect()` called before `health_check()`, healthy/unhealthy/mixed aggregation, empty client list | | `api/actuators/health/test_health_cache.py` | `HealthCheckCache` | Initial state, provider updates, all-healthy→UP, one-unhealthy→DOWN, exception→unhealthy component, `get_cache_age_seconds`, `get_cache_info`, start/stop idempotency | | `api/actuators/health/test_sessions_health.py` | `SessionsServiceHealthChecker` | REST API reachable→UP, `RequestError`→DOWN with details, fresh heartbeat→UP, stale heartbeat→DOWN, no heartbeat→UP (unknown), `update_heartbeat` | -| `api/eventing/test_event_handling_base.py` | `EventHandlingBase` | `_unwrap_nested_cloud_event` (via mixin) for non-dapr/dict/JSON-string/malformed-JSON/missing-fields/None data; `handle_event` PROCESSED→SUCCESS / other→RETRY | +| `api/eventing/test_event_handling_base.py` | `EventHandlingBase` | `_unwrap_nested_cloud_event` (via mixin) for non-dapr/dict/JSON-string/malformed-JSON/missing-fields/None data; `handle_event` PROCESSED→SUCCESS / other→RETRY; a `SKIPPED` run counted as `blueprint.events.skipped` and not as unhandled, acknowledged, with no WARNING | | `api/eventing/test_dapr.py` | `DaprEventing` | `publish` PROCESSED→SUCCESS, no-handler→RETRY, `RetryableHandlerError`→RETRY, `InvalidEventError`→DROP, `CriticalHandlerError`→RETRY; `subscribe` returns empty dict | | `api/eventing/test_nats.py` | `NatsEventing` | `subscribe`/`publish` delegate to `_client`, RuntimeError when client is None; `on_startup` fetches client, subscribes to handler-declared and config-declared topics, deduplicates, preserves handler-first order, skips when no topics; `_subscribe_to_topic` RuntimeError when client None, calls `_client.subscribe` with topic and callback | | `api/eventing/test_sessions_bus.py` | `SessionsBus` | `on_startup` validation (no config/base_url/agent_id/api_key, already started, task created); `on_shutdown` (no task, running task cancelled); `_convert_to_cloud_event` (type/id/subject/source/data); `_process_job_notification` (no handler logged, `InvalidEventError`→cancel job, cancel failure swallowed, `RetryableHandlerError`→log, 403→invalidate+retry, 403 retry failure propagates `InvalidEventError`, non-403 propagates) | diff --git a/tests/unit/agents/io/api/eventing/test_event_handling_base.py b/tests/unit/agents/io/api/eventing/test_event_handling_base.py index 73347fd8..bd9435bd 100644 --- a/tests/unit/agents/io/api/eventing/test_event_handling_base.py +++ b/tests/unit/agents/io/api/eventing/test_event_handling_base.py @@ -10,9 +10,9 @@ from blueprint.agents.handler.handler_chain import DUPLICATE_CONTEXT_KEY from blueprint.agents.io.api.eventing.dapr import DaprEventing -from blueprint.agents.io.api.eventing.event_handling_base import DUPLICATE_EVENTS_COUNTER, UNHANDLED_EVENTS_COUNTER +from blueprint.agents.io.api.eventing.event_handling_base import DUPLICATE_EVENTS_COUNTER, SKIPPED_EVENTS_COUNTER, UNHANDLED_EVENTS_COUNTER from blueprint.agents.models.events import CloudEvent -from blueprint.agents.models.result import ProcessingResult +from blueprint.agents.models.result import ProcessingResult, ProcessingStatus @contextmanager @@ -327,3 +327,31 @@ async def test_unmatched_event_is_still_counted_as_unhandled( counters[UNHANDLED_EVENTS_COUNTER].add.assert_called_once_with(1, {"agent": "", "topic": "orders"}) counters[DUPLICATE_EVENTS_COUNTER].add.assert_not_called() + + +class TestSkippedAccounting: + """``HandlerResult.skipped`` -- counted as skipped, never as unhandled, and still acknowledged.""" + + @staticmethod + def _skipped() -> ProcessingResult: + return ProcessingResult(request_id="req-3", status=ProcessingStatus.SKIPPED, message="Skipped: status unchanged") + + async def test_a_skip_is_counted_as_skipped_not_as_unhandled(self, dapr_eventing: DaprEventing, cloud_event: CloudEvent) -> None: + """A skip is the agent's own relevance rule; counting it as unhandled would blame the subscription.""" + dapr_eventing._dispatch_cloud_event = AsyncMock(return_value=self._skipped()) # type: ignore[method-assign] + + with _counters() as counters: + await dapr_eventing._process_cloud_event(cloud_event, {}, "orders") + + counters[SKIPPED_EVENTS_COUNTER].add.assert_called_once_with(1, {"agent": "", "topic": "orders"}) + counters[UNHANDLED_EVENTS_COUNTER].add.assert_not_called() + + async def test_a_skip_acknowledges_and_reports_no_fault( + self, dapr_eventing: DaprEventing, cloud_event: CloudEvent, caplog: pytest.LogCaptureFixture + ) -> None: + dapr_eventing._dispatch_cloud_event = AsyncMock(return_value=self._skipped()) # type: ignore[method-assign] + + with _counters(), caplog.at_level("DEBUG"): + result = await dapr_eventing.handle_event("orders", cloud_event) + assert result == {"status": "SUCCESS"} + assert [r for r in caplog.records if r.levelname in {"WARNING", "ERROR", "CRITICAL"}] == [] 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 78960d57..9d1f60f8 100644 --- a/tests/unit/agents/io/api/test_rest_api_base.py +++ b/tests/unit/agents/io/api/test_rest_api_base.py @@ -286,3 +286,28 @@ async def test_the_request_id_reaches_processing(self, mock_config: MagicMock, m context = service.process_rest_request.await_args.args[1] assert context["request_id"] == request.state.trace_id + + +class TestProcessResourceSkipped: + """``HandlerResult.skipped`` reaches a REST caller as a success with the reason, not as a failure.""" + + async def test_a_skip_is_a_success_and_carries_its_reason(self, mock_config: MagicMock, mock_registry: MagicMock) -> None: + from blueprint.agents.models.events import HandlerResult + from blueprint.agents.models.result import ProcessingResult, ProcessingStatus + + api = _MinimalApi() + service = MagicMock() + skipped = ProcessingResult( + request_id="r", + status=ProcessingStatus.SKIPPED, + message="Skipped: status unchanged", + result=[HandlerResult.skipped("status unchanged")], + ) + service.process_rest_request = AsyncMock(return_value=skipped) + mock_registry.get_service.return_value = service + + response = await api._process_resource(MagicMock(), {}) + + assert response.success is True + assert response.message == "Skipped: status unchanged" + assert response.data is None diff --git a/tests/unit/agents/models/TESTS.md b/tests/unit/agents/models/TESTS.md index d9085cd1..a97c0821 100644 --- a/tests/unit/agents/models/TESTS.md +++ b/tests/unit/agents/models/TESTS.md @@ -9,7 +9,7 @@ Test coverage for `src/blueprint/agents/models/`. | File | Classes under test | What is covered | |---|---|---| | `test_config.py` | `EventPublishingConfig` | `normalize_topic_mapping`: `TopicConfig` / dict / plain-string / invalid-type values, non-dict mapping → error; `_parse_mapping_string`: empty string, quoted-key string, unquoted-key string (auto-quoting regex), non-brace format → error, malformed brace string → error; `_parse_topic_config_value`: plain string, `map[topic:t]`, `map[topic:t routing_key:rk]`, empty `map[]` → error, missing `topic` entry → error, entry without `:` → error | -| `test_events.py` | `CloudEvent` | `validate_time_format`: Z-suffix, `+00:00` offset, missing timezone → error, non-string → error, default factory produces valid timestamp; `validate_data_exclusivity`: data-only, data_base64-only, neither, both → error | +| `test_events.py` | `CloudEvent`, `HandlerResult` | `validate_time_format`: Z-suffix, `+00:00` offset, missing timezone → error, non-string → error, default factory produces valid timestamp; `validate_data_exclusivity`: data-only, data_base64-only, neither, both → error; `HandlerResult.skipped`: carries its reason and metadata and reports `is_skipped`, an ordinary result is not skipped, an empty or blank reason is refused, a skip combined with `event_type`, `subject` or `data` is refused | | `test_result.py` | `Evidence`, `AgentOutput` | `Evidence.confidence` ge/le constraints (0.0/1.0 pass, outside → error); `AgentOutput.sort_evidence_by_confidence`: empty list, single item, multiple items sorted descending, already-sorted input | --- diff --git a/tests/unit/agents/models/test_events.py b/tests/unit/agents/models/test_events.py index a2e2b90f..e29a2a4f 100644 --- a/tests/unit/agents/models/test_events.py +++ b/tests/unit/agents/models/test_events.py @@ -55,3 +55,42 @@ def test_neither_data_nor_data_base64_is_valid(self) -> None: def test_both_data_and_data_base64_raises(self) -> None: with pytest.raises(ValidationError): CloudEvent(id="1", type="t", data={"x": 1}, data_base64="aGVsbG8=") + + +# --------------------------------------------------------------------------- +# HandlerResult.skipped +# --------------------------------------------------------------------------- + + +class TestHandlerResultSkipped: + """``HandlerResult.skipped``: the responsible handler's "this event needs nothing".""" + + def test_skipped_carries_its_reason_and_reports_itself(self) -> None: + from blueprint.agents.models.events import HandlerResult + + result = HandlerResult.skipped("status unchanged", metadata={"field": "status"}) + assert result.is_skipped + assert result.skip_reason == "status unchanged" + assert result.metadata == {"field": "status"} + assert result.event_type is None and result.data is None + + def test_an_ordinary_result_is_not_skipped(self) -> None: + from blueprint.agents.models.events import HandlerResult + + assert not HandlerResult(event_type="x").is_skipped + + @pytest.mark.parametrize("reason", ["", " "]) + def test_an_empty_reason_is_refused(self, reason: str) -> None: + """A skip without a reason leaves the INFO line saying nothing about why the event was dropped.""" + from blueprint.agents.models.events import HandlerResult + + with pytest.raises(ValidationError, match="must name why"): + HandlerResult.skipped(reason) + + @pytest.mark.parametrize("extra", [{"event_type": "x"}, {"subject": "s"}, {"data": {"a": 1}}]) + def test_a_skip_that_would_also_publish_or_return_data_is_refused(self, extra: dict) -> None: + """Both published and skipped would leave nobody able to tell which one the author meant.""" + from blueprint.agents.models.events import HandlerResult + + with pytest.raises(ValidationError, match="carries only its reason"): + HandlerResult(skip_reason="r", **extra) diff --git a/tests/unit/agents/services/TESTS.md b/tests/unit/agents/services/TESTS.md index c70976fa..43815038 100644 --- a/tests/unit/agents/services/TESTS.md +++ b/tests/unit/agents/services/TESTS.md @@ -8,7 +8,7 @@ Test coverage for `src/blueprint/agents/services/`. | File | Class under test | What is covered | |---|---|---| -| `eventing/test_event_processing_service.py` | `EventProcessingService` | `_extract_handler_results` (None/HandlerResult/list/dict variants), `_build_result` (message text, request_id, result list), `_unwrap_dapr_event` (passthrough / CloudEvent inner / dict inner / missing type / unexpected type), lifecycle no-ops, `process_rest_request` delegates to `process_event` with correct event shape | +| `eventing/test_event_processing_service.py` | `EventProcessingService` | `_extract_handler_results` (None/HandlerResult/list/dict variants), `_build_result` (message text incl. `Skipped: `, request_id, result list), a skipped run reported as `SKIPPED` and publishing nothing, a list mixing a skip with a real result reported as `PROCESSED` and publishing only the real one, `_unwrap_dapr_event` (passthrough / CloudEvent inner / dict inner / missing type / unexpected type), lifecycle no-ops, `process_rest_request` delegates to `process_event` with correct event shape | | `eventing/test_event_publishing_service.py` | `EventPublishingService` | `on_startup` wires client and config, `_get_pub_config` raises before startup, `get_topic_for_event_type` / `get_available_event_types`, `publish_event` (topic mapping, explicit topic override, missing mapping raises, sets default source, result shape), `publish_handler_event` (no mapping → skip, loop prevention → skip, normal → publishes), `publish_status_event` type format and delegation | | `infrastructure/test_disk_cache_service.py` | `DiskCacheService` | `set`/`get` (string/dict/list keys, namespace isolation), `delete` (return values), `exists` (before/after set/delete), `clear` (namespace-scoped and full), TTL expiration via mocked `time.time`, `hash` consistency for string/list/dict inputs, `list_namespaces`, `list_values` (content, TTL-entry exclusion, limit), `get_stats` field presence, lifecycle, context-manager protocol, an unwritable cache directory failing with a message that names the path and the options (and keeping the OSError as the cause); `claim` set-if-absent (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, keys and namespaces independent, dict keys hashed consistently, TTL recorded so readers see expiry, a logically expired claim taken over, no TTL never expires, and an unreachable cache failing open) | | `infrastructure/test_redis_cache_service.py` | `RedisCacheService` | Backed by `fakeredis`. `claim` via `SET NX EX` (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, the TTL is applied to the key, namespaces are independent, and an unreachable cache fails open). *The rest of this file's coverage predates this table and is not itemised here.* | 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 4aaf5b83..12e5455c 100644 --- a/tests/unit/agents/services/eventing/test_event_processing_service.py +++ b/tests/unit/agents/services/eventing/test_event_processing_service.py @@ -64,6 +64,10 @@ def test_no_handler_found_message(self) -> None: result = EventProcessingService._build_result("req-2", [], ProcessingStatus.NO_HANDLER_FOUND) assert result.message == "No handler processed this event" + def test_skipped_message_names_the_reason(self) -> None: + result = EventProcessingService._build_result("req-3", [HandlerResult.skipped("status unchanged")], ProcessingStatus.SKIPPED) + assert result.message == "Skipped: status unchanged" + def test_result_contains_request_id(self) -> None: result = EventProcessingService._build_result("req-42", [], ProcessingStatus.PROCESSED) assert result.request_id == "req-42" @@ -242,6 +246,39 @@ 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 TestASkippedRun: + """``HandlerResult.skipped``: acknowledged as SKIPPED, nothing published.""" + + @staticmethod + def _wire(service: EventProcessingService, mock_registry: MagicMock, results: object) -> MagicMock: + chain = MagicMock() + chain.process = AsyncMock(return_value=results) + service._handler_chains[ROOT_NAMESPACE] = chain + publisher = MagicMock() + publisher.publish_handler_event = AsyncMock() + mock_registry.get_component.return_value = publisher + return publisher + + async def test_a_skip_is_reported_as_skipped_and_publishes_nothing( + self, event_processing_service: EventProcessingService, mock_registry: MagicMock + ) -> None: + publisher = self._wire(event_processing_service, mock_registry, HandlerResult.skipped("status unchanged")) + result = await event_processing_service.process_event(GenericCloudEvent(id="e1", type="t", source="s")) + assert result.status is ProcessingStatus.SKIPPED + assert result.message == "Skipped: status unchanged" + publisher.publish_handler_event.assert_not_awaited() + + async def test_a_list_mixing_a_skip_with_real_results_is_processed_and_publishes_the_real_ones( + self, event_processing_service: EventProcessingService, mock_registry: MagicMock + ) -> None: + """Only a run whose every result is a skip counts as skipped; a skip in a list publishes nothing.""" + results = [HandlerResult.skipped("nothing for a"), HandlerResult(event_type="b", data={})] + publisher = self._wire(event_processing_service, mock_registry, results) + result = await event_processing_service.process_event(GenericCloudEvent(id="e1", type="t", source="s")) + assert result.status is ProcessingStatus.PROCESSED + assert [call.kwargs["event_type"] for call in publisher.publish_handler_event.await_args_list] == ["b"] + + class TestTheRequestIdIsKept: """#13 -- process_event replaced the caller's request_id with a new uuid4.""" From e3f179d91645908039ecb66fafa1c3a594a827be Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 16:40:42 +0200 Subject: [PATCH 086/133] docs: one main.py pattern, handlers translate and services decide (named connections, step 6) Shipped docs, the installed CLAUDE.md, the builder/architect agents, the skills and the handler template now agree with the code: the template's declaration pattern everywhere, the chain stops at the first non-None result, HandlerResult.skipped documented, handler rules (routing on the envelope, one service call, no LLM in handlers, no run state on self), spec 5.2 defaults corrected, the deployment banner and the missing NATS keys fixed. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 16 ++ README.md | 6 +- ...26-08-28-multi-agent-grouping-changelog.md | 32 ++++ docs/specs/2026-08-28-multi-agent-grouping.md | 19 +- .../base_files/src/handlers/handler.txt | 44 +++-- .../agent_generator/claude_docs/CLAUDE.md | 111 ++++++++---- .../claude_docs/agents/blueprint-architect.md | 2 + .../claude_docs/agents/blueprint-builder.md | 42 +++-- .../claude_docs/skills/add-component/SKILL.md | 16 +- .../skills/blueprint-events/SKILL.md | 25 ++- .../agent_generator/docs/components/agents.md | 96 +++++----- .../docs/components/event-handlers.md | 115 +++++++----- .../docs/components/rest-apis.md | 24 +-- .../docs/components/schedulers.md | 21 +-- .../docs/components/services.md | 10 +- .../docs/concepts/architecture.md | 161 +++++++++++------ .../agent_generator/docs/concepts/caching.md | 11 +- .../docs/concepts/configuration.md | 7 +- .../docs/concepts/event-processing.md | 171 +++++++++--------- .../docs/concepts/observability.md | 1 + .../agent_generator/docs/getting-started.md | 57 +++--- .../agent_generator/docs/guides/deployment.md | 29 +-- .../agent_generator/docs/reference/api.md | 25 ++- .../docs/reference/configuration-keys.md | 3 + .../agent_generator/docs/reference/models.md | 7 + 25 files changed, 643 insertions(+), 408 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8008b3ac..b37eefe1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -363,6 +363,22 @@ ### Changed +- **One `main.py` pattern in every document, skill and agent prompt: the template's.** `src/main.py` + is a declaration (`agent = AppBuilder()...`, unbuilt `AgentBuilder`, components as classes) with + a `create_app()` for running it alone. The docs showed three patterns, including `.with_config()`, + `.with_api()` and `AgentBuilder().with_name()`, which do not exist, and a built `AgentRuntime` + that a group refuses. +- **Handlers translate, services decide -- in the scaffold and every document.** The handler + template no longer says "this is where the main business logic is implemented": + `can_handle_event` routes on the envelope only, `handle_event` extracts the payload, makes one + service call and returns the answer (`HandlerResult`, `HandlerResult.skipped(reason)` or `None`); + idempotency belongs to the service; handlers never call the LLM. The chain semantics are stated + as the code has them: the first result that is not `None` ends the chain (the docs said a + `HandlerResult` let later handlers run). +- **`asbs validate` checks the NATS delivery keys** that otherwise fail only at startup: + `nats_max_concurrent_runs`, `nats_extra_runs_per_process`, `nats_handler_timeout`, + `nats_connections_readiness`, `nats_unclaimed_subjects`, and the form and module of + `nats_connection_source` (the factory is not called). - **`docs/guides/cli-reference.md` is an index**, with one page per command under `guides/cli/` (`setup`, `create`, `validate`, `dev`, `claude`, plus `naming` and `auto-registration`). It was a single 1,023-line page, which meant reading about one flag cost the whole file. diff --git a/README.md b/README.md index a0cf4c73..ef2c80f3 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Blueprint Agents gives you a component-based toolkit for building intelligent mi ## Key Features - **Component Architecture** -- Five composable base classes (`EventHandlerBase`, `ServiceBase`, `RestApiBase`, `AgentRuntime`, `SchedulerBase`) assembled via a fluent `AppBuilder` -- **Event-Driven Processing** -- CloudEvents v1.0 with chain-of-responsibility handlers, Dapr and NATS pub/sub support +- **Event-Driven Processing** -- CloudEvents v1.0 with chain-of-responsibility handlers, Dapr and NATS pub/sub support; on NATS, concurrent runs per agent with JetStream heartbeats and run timeouts, and named connections (several brokers or accounts per agent, supplied by a connection source) - **LLM Integration** -- AI agents powered by [Pydantic AI](https://ai.pydantic.dev/) with structured outputs, tool calling, and multi-model support (OpenAI, vLLM) - **Built-in Observability** -- OpenTelemetry tracing, metrics, and structured logging out of the box - **Multi-Agent Grouping** -- Run one agent per process, or host several in one process, as a *deployment* choice: the agent's code is identical either way @@ -144,8 +144,8 @@ Two things about that chain are worth knowing up front: | Component | Base Class | Purpose | |-----------|-----------|---------| -| **Event Handler** | `EventHandlerBase` | Process CloudEvents via chain-of-responsibility with priority ordering | -| **Service** | `ServiceBase` | Encapsulate business logic with full registry access | +| **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 | | **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/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index b3e44f50..5da42701 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8588,6 +8588,38 @@ deterministic, see Open points). on the unchanged code (the only handler returning `None`, the way an agent had to say "nothing to do"): acked, but WARNING `No handler processed event 'orders.created'` and counted as unhandled. +### Named connections, step 6: documentation, scaffold and skills agree with the code + +- **One `main.py` pattern** everywhere (W1): the installed `CLAUDE.md`, `blueprint-builder.md`, + `getting-started.md`, `concepts/architecture.md`, `components/agents.md`, `event-handlers.md`, + `rest-apis.md`, `schedulers.md`, `services.md`, `caching.md`, `configuration.md` and + `reference/api.md` now show the template's declaration. `reference/api.md` documents + `AppBuilder(config=None)` and `build(config=None)`. +- **Chain semantics** (W2): `event-handlers.md` and `concepts/event-processing.md` said a + `HandlerResult` (and any other value) let later handlers run; `_dispatch` returns the first + non-`None` result. Both now carry a table per return value, including `skipped`. +- **`concepts/architecture.md`** (W3) used `with_agent(name, Cls)`, a synchronous + `can_handle_event(event)`, `register_routes`, `execute()` and `priority = 10`; rewritten. +- **Scheduler** (W4): `blueprint-builder.md` showed `on_startup` without `super().on_startup()`. +- **W5** was already fixed (`519566f` removed the second `CLAUDE.md`). +- **Handler template** (W7, W8): docstrings and the idempotency comment now put the decision in the + service. **Runtime in `context`** (W9): documented as framework plumbing a handler never runs. + **Models** (W11): `models/` is `dto.py` + `domain_models.py` (+ `mapper.py`) as the templates + already scaffold it. +- **Handler rules** (2026-10-15) in the installed `CLAUDE.md` (rules 7-10), the builder and architect + agents, `blueprint-events` and `add-component`. +- **`event-handlers.md` context keys:** `nats_topic`/`nats_subject` as the agent declared/knows them, + `nats_connection` added; the tenant example is gone (the framework names no tenant). +- **Spec sec. 5.2** listed `nats_ack_wait = 300`, `nats_max_ack_pending = 16`, `nats_max_deliver = 5` + as defaults; the code leaves them unset (server defaults). Corrected, the new keys added; sec. 7.3 + states the default heartbeat. +- **`guides/deployment.md`**: the "never exercised against a real broker" banner is replaced by + what `tests/integration` covers; dispositions for skipped and timed-out runs; the heartbeat. +- **`reference/configuration-keys.md`**: `nats_subscriptions`, `nats_publish_mode` and + `nats_publish_subjects` were read by the code and documented nowhere. +- **`asbs validate`** (`_nats_findings`): the NATS keys parsed with the client's own parsers; the + source's module found via `importlib.util.find_spec`, the factory never called. + --- ## Open points diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md index bb227658..85aa9afc 100644 --- a/docs/specs/2026-08-28-multi-agent-grouping.md +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -341,14 +341,19 @@ changing them triggers a rolling update on their own. ### 5.2 Runtime keys +Defaults corrected 2026-10-15 to what ships: the NATS limits are unset unless configured, and +the server's defaults apply (feature changelog, named connections step 6). + | Key | Default | Meaning | |---|---|---| | `readiness_policy` | `"all"` | See C3. | | `executor_workers` | `os.cpu_count() + 4` | Per-namespace thread pool size. Bounded per #36. | | `nats_queue_group` | `app_name` | Queue group for the root namespace only. | -| `nats_ack_wait` | `300.0` | Seconds. **MUST** exceed p99 handler duration. See sec. 7.3. | -| `nats_max_ack_pending` | `16` | Per-consumer, shared across replicas. `-1` unlimited. A push subscription dispatches its callbacks serially, so a value far above the replica count queues messages client-side while their `ack_wait` runs. | -| `nats_max_deliver` | `5` | Attempts before the message is dead-lettered. `-1` unlimited, and then nothing is ever dead-lettered. | +| `nats_ack_wait` | unset -- the server's (NATS: 30 s) | Seconds. **MUST** exceed p99 handler duration unless the heartbeat is on (it is by default: a running delivery reports `in_progress` every third of `ack_wait`). See sec. 7.3. | +| `nats_max_ack_pending` | unset -- the server's (NATS: 1000) | Per-consumer, shared across replicas. `-1` unlimited. Keep it near replicas x `nats_max_concurrent_runs`: what a pod receives beyond the runs it has started waits in the client's queue while its `ack_wait` runs. | +| `nats_max_deliver` | unset -- the server's (NATS: unlimited) | Attempts before the message is dead-lettered. `-1` unlimited, and then nothing is ever dead-lettered. | +| `nats_max_concurrent_runs`, `nats_extra_runs_per_process`, `nats_handler_timeout`, `nats_heartbeat_enabled` | see the configuration reference | Concurrent runs per (agent, connection), the process pool beyond each pair's guaranteed run, a per-run time limit, the `in_progress` heartbeat. Added by `docs/plans/2026-10-14-named-connections.md`. | +| `nats_connection_source`, `nats_connections_readiness`, `nats_unclaimed_subjects` | see the configuration reference | Named connections. Same plan. | | `nats_dead_letter_subject` | `.dead-letter` | Where a message the framework gives up on is republished. Derived from the agent's identity, as the queue group is (C1). `""` disables it and loses those payloads. **MUST NOT** be a wildcard or a subject the same namespace consumes. | | `idempotency_enabled` | `false` | Opt-in dedup. See sec. 7.4. | | `idempotency_ttl` | -- | Dedup window. | @@ -550,8 +555,12 @@ the server keys pending state on stream sequence. **MUST** be validated against ### 7.3 Long handlers `ack_wait` **MUST** exceed p99 handler duration, or a slow handler is redelivered to another -replica while the first is still working. `in_progress()` heartbeats address slow handlers; they -do **not** address connection loss, since they travel over the same connection. +replica while the first is still working -- unless the delivery is heartbeated. Since the +named-connections work (2026-10-14) a running JetStream delivery reports `in_progress()` every +third of its consumer's `ack_wait` by default (`nats_heartbeat_enabled`), and `nats_handler_timeout` +bounds a run. Heartbeats address slow handlers; they do **not** address connection loss, since +they travel over the same connection, and they do not cover messages still waiting in the client's +queue (bound those with `nats_max_ack_pending`). ### 7.4 Idempotency diff --git a/src/blueprint/agent_generator/base_files/src/handlers/handler.txt b/src/blueprint/agent_generator/base_files/src/handlers/handler.txt index a5d731c4..be56acad 100644 --- a/src/blueprint/agent_generator/base_files/src/handlers/handler.txt +++ b/src/blueprint/agent_generator/base_files/src/handlers/handler.txt @@ -19,43 +19,55 @@ on_startup on_shutdown async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: - """Determine if this handler should process the event. + """Route: is this handler the one for this kind of event? - This method should make all the necessary checks to determine if this handler should process the event. + Decide on the envelope only -- ``event.type``, ``event.source``, ``event.subject`` and the + context keys. No I/O and no service call here: whether *this* event needs work is the + service's decision, reported back through ``handle_event``. Args: event: The CloudEvent to potentially handle. context: Processing context dictionary. Returns: - True if this handler can process the event, False otherwise. + True if this handler is responsible for the event, False otherwise. """ - # Simple example - # if event.type == self._input_event_type: + # Example: + # return event.type == "order.placed" raise NotImplementedError() async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None: - """Handles the event. This is where the main business logic is implemented. This can a part of a chain of - handlers. The chain continues based on the handlers priorities and until a handler returns a result. + """Translate the event into one service call and the service's answer into a result. + + A handler translates, it never decides: three steps, nothing more. + + 1. ``payload = self.extract_payload(event, MyEventDto)`` -- the typed, validated payload. + 2. **One** service call with domain values (ids, domain models; never the CloudEvent or + the DTO). All business logic lives behind it, including whether the event needs work + and the order of the steps; two service calls in a row are business logic already. + 3. The answer as a result: ``HandlerResult(event_type=..., data=...)`` to publish, + ``HandlerResult.skipped("reason")`` when the service found nothing to do, or ``None`` + only when another handler should be offered the event. + + No LLM call here: the service resolves and runs its agent. Args: event: The CloudEvent to process. - context: Dictionary containing information from previous handlers. Can be extended to pass information to - the following handlers. + context: Processing context dictionary (transport keys such as ``nats_subject``). Returns: - HandlerResult: The resulting event to publish, when the handlers work is done. + The result to publish, a skip, or None to pass the event to the next handler. """ - # DECIDE: can this handler run twice on the same event? + # DECIDE: can the service run twice on the same event? # # Delivery is at-least-once. A redelivery arrives whenever an acknowledgement is - # lost -- a pod restart, a rolling deploy, a connection blip mid-handler -- and the - # side effects of the first attempt have already happened by then. Running twice is - # not an edge case; it is the normal behaviour of the transport. + # lost -- a pod restart, a rolling deploy, a connection blip mid-run -- and the side + # effects of the first attempt have already happened by then. Running twice is not an + # edge case; it is the normal behaviour of the transport. # - # Either make this method safe to repeat (upsert instead of insert, key the outbound - # request on event.id, check before you charge), or switch the framework dedup on: + # Make the *service* safe to repeat (upsert instead of insert, key the outbound request + # on event.id -- pass it as a parameter), or switch the framework dedup on: # # settings.toml # idempotency_enabled = true diff --git a/src/blueprint/agent_generator/claude_docs/CLAUDE.md b/src/blueprint/agent_generator/claude_docs/CLAUDE.md index dbb67e1d..7b1072a2 100644 --- a/src/blueprint/agent_generator/claude_docs/CLAUDE.md +++ b/src/blueprint/agent_generator/claude_docs/CLAUDE.md @@ -31,39 +31,59 @@ from blueprint.agents.models import GenericCloudEvent, HandlerResult, CloudEvent 4. **No global state** — no module-level component instances, no singletons. 5. **All components must implement `on_startup()` and `on_shutdown()`** — even if empty. 6. **Services contain ALL business logic** — handlers and APIs are thin delegation layers. +7. **A handler translates, it never decides.** `can_handle_event` routes on the envelope only + (`event.type`, `event.source`, `event.subject`, the context keys) -- no I/O, no service call. + `handle_event` is three steps: `self.extract_payload(event, Dto)` -> **one** service call -> + translate the answer into a `HandlerResult`, `HandlerResult.skipped(reason)` or `None`. + Calling two services in a row is already business logic: give the service one method for it. +8. **Relevance is the service's decision.** Whether *this* event needs work (a field changed, a + status reached) is checked by the service; a handler that was routed the event but has nothing + to do returns `HandlerResult.skipped(reason)`. +9. **Handlers never call the LLM.** No `agent.run()`, no `registry.get_agent()`, no runtime taken + from `context` in a handler -- the service resolves its agent in `on_startup()` and runs it. +10. **No run state on `self`.** Components are shared by every concurrent run; per-event values + live in locals and parameters. `self` holds only what `on_startup()` resolved. ## Wiring (main.py) +`src/main.py` is a **declaration**, exactly as `asbs setup` writes it: no `Config`, no `build()`, +components registered as **classes**. The host builds it -- `create_app()` when the agent runs on +its own, `python -m blueprint.agents.entrypoint` when it is one agent of a group. + ```python from pathlib import Path -from blueprint.agents import AppBuilder, Config, AgentBuilder -config = Config( - settings_files=["settings.toml", ".secrets.toml"], - root_path=Path(__file__).parent.parent, -) +from blueprint.agents import AgentBuilder, AppBuilder, Config + +from .api.order_api import OrderApi +from .handlers.order_handler import OrderHandler +from .services.order_service import OrderService -my_agent = ( - AgentBuilder(config, runtime_name="my_agent") - .with_model_from_config("my_agent") - .with_system_prompt("system") - .with_tools([...]) - .with_result_type(MyResultModel) - .build(name="my_agent") +order_agent = ( + AgentBuilder(runtime_name="order_agent") + .with_model_from_config() + .with_system_prompt("order_agent_system") ) -app = ( - AppBuilder(config) - .with_service(MyService) - .with_agent(my_agent) - .with_handler(MyHandler) - .with_rest_api(MyApi) - .with_scheduler(MyScheduler) - .with_cache() - .build() +agent = ( + AppBuilder() + .with_service(OrderService) + .with_agent(order_agent, name="order_agent") + .with_handler(OrderHandler) + .with_rest_api(OrderApi) ) + + +def create_app(): + """Build this agent as an application of its own (standalone only).""" + return agent.build(Config(settings_files=["settings.toml", ".secrets.toml"], root_path=str(Path(__file__).parent.parent))) ``` +- Never build the `AgentBuilder` yourself and never pass an instance to a `with_*` call: a group + refuses instances, because a component constructed on that line exists before any namespace does. +- Keep one registration per line in dependency order (services, agents, handlers, APIs, + schedulers) -- `asbs create` rewrites the chain line by line. + ## Component Patterns ### EventHandler @@ -80,21 +100,32 @@ class OrderHandler(EventHandlerBase): pass async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: - return event.type == "order.placed" + return event.type == "order.placed" # routing on the envelope only -- no I/O async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None: - order = self.extract_payload(event, OrderModel) # Typed extraction with validation - result = await self._service.process(order) - return HandlerResult(event_type="order.processed", data=result) + payload = self.extract_payload(event, OrderPlacedEvent) # DTO: typed, validated + outcome = await self._service.on_order_placed(payload.order_id, event_id=event.id) # ONE call + if outcome is None: + return HandlerResult.skipped("order needs no processing") + return HandlerResult(event_type="order.processed", data=outcome.model_dump()) ``` -- Return `None` → pass to next handler. Return `HandlerResult` → publish event, stop chain. -- **Delivery is at-least-once.** The same event can reach `handle_event` more than once (lost ack, pod restart, rolling deploy). Either make the method safe to repeat, or set `idempotency_enabled = true` **and** `idempotency_ttl = ` in `settings.toml` -- the framework then skips an event whose id and source it has already dispatched, within that window. Off by default on purpose: only you know whether replaying your side effects is acceptable. +- Results: `HandlerResult` → published (if its `event_type` is mapped), chain stops. + `HandlerResult.skipped(reason)` → this handler is responsible but the event needs nothing: chain + stops, the delivery is acknowledged, the reason is logged at INFO, nothing is published. + `None` → the event is offered to the next handler; if none takes it, the framework logs + "No handler processed event". +- **Delivery is at-least-once.** The same event can reach `handle_event` more than once (lost ack, pod restart, rolling deploy). The *service* must be safe to repeat (check before you act, upsert rather than insert), or set `idempotency_enabled = true` **and** `idempotency_ttl = ` in `settings.toml` -- the framework then skips an event whose id and source it has already dispatched, within that window. Off by default on purpose: only you know whether replaying your side effects is acceptable. - **`self.extract_payload(event, ModelType)`** — validates `event.data` against a Pydantic model and returns a typed instance. Raises `InvalidEventError` if data is missing or invalid (the framework handles this automatically). +- **The service gets no CloudEvent and no DTO.** Translate the payload into domain values (ids, domain models) in the handler; that is what lets a REST API call the same service method. +- **`context["runtime"]`** holds the agent runtime the chain bound for this handler. It is there for + framework plumbing; a handler never runs it (rule 9) -- the service resolves its own agent. ### Service -Services contain ALL business logic. Each responsibility gets its own method. +Services contain ALL business logic, including the decision whether an event needs work at all. +Each responsibility gets its own method; the method a handler calls is the one entry point for that +event (a facade that calls the others in order). ```python class OrderService(ServiceBase): @@ -104,6 +135,18 @@ class OrderService(ServiceBase): async def on_shutdown(self) -> None: pass + async def on_order_placed(self, order_id: str, event_id: str) -> OrderOutcome | None: + """Entry point for an order.placed event. None: the order needs no processing.""" + order = await self.load(order_id) + if not self.is_relevant(order): + return None + await self.validate(order) + return await self.analyze(order) + + def is_relevant(self, order: Order) -> bool: + """Pure check, testable without mocks.""" + ... + async def validate(self, order: OrderModel) -> ValidationResult: """Validate order against business rules.""" ... @@ -183,15 +226,15 @@ class CleanupScheduler(SchedulerBase): ### AgentRuntime (via AgentBuilder) ```python -agent = ( - AgentBuilder(config, runtime_name="analyzer") - .with_model_from_config("analyzer") - .with_system_prompt("system") # Loads prompts/system.prompt (static, no dynamic inputs) +analyzer = ( + AgentBuilder(runtime_name="analyzer") # declared, not built: the host builds it + .with_model_from_config() + .with_system_prompt("analyzer_system") # Loads prompts/analyzer_system.prompt (static) .with_tools([analyze_tool]) .with_result_type(AnalysisResult) .with_metrics() - .build(name="analyzer") ) +# registered in main.py: AppBuilder()...with_agent(analyzer, name="analyzer") ``` **Prompt files** in `src/prompts/`: @@ -302,6 +345,6 @@ src/ ├── services/ # ServiceBase subclasses ├── api/ # RestApiBase subclasses ├── schedulers/ # SchedulerBase subclasses -├── models/ # Pydantic domain models + DTOs +├── models/ # dto.py: event/REST payloads; domain_models.py: what services work with └── prompts/ # .prompt files (system + instruction) ``` diff --git a/src/blueprint/agent_generator/claude_docs/agents/blueprint-architect.md b/src/blueprint/agent_generator/claude_docs/agents/blueprint-architect.md index 7a7b4f72..b07ce84c 100644 --- a/src/blueprint/agent_generator/claude_docs/agents/blueprint-architect.md +++ b/src/blueprint/agent_generator/claude_docs/agents/blueprint-architect.md @@ -111,6 +111,8 @@ asbs create handler --event-type - **Every component must have a clear, single responsibility** - **Services contain ALL business logic** — handlers and APIs are thin wrappers +- **Plan one service entry point per event type** — the handler routes on the envelope, extracts the payload and calls exactly that method; relevance checks ("does this event need work?") are part of it and come back as `HandlerResult.skipped(reason)` +- **LLM calls belong to services** — never to handlers - **One handler per event type** (or closely related group) - **One RestApi per resource** (or closely related group) - **Agent names must be unique** and match their runtime config section diff --git a/src/blueprint/agent_generator/claude_docs/agents/blueprint-builder.md b/src/blueprint/agent_generator/claude_docs/agents/blueprint-builder.md index 4cd05e76..ecc5c5cb 100644 --- a/src/blueprint/agent_generator/claude_docs/agents/blueprint-builder.md +++ b/src/blueprint/agent_generator/claude_docs/agents/blueprint-builder.md @@ -60,16 +60,24 @@ class MyHandler(EventHandlerBase): pass async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: - return event.type == "my.event.type" - - async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | list[HandlerResult] | None: - payload = self.extract_payload(event, MyModel) # Typed extraction with validation - result = await self._service.process(payload) - return HandlerResult(event_type="my.result.type", data=result) + return event.type == "my.event.type" # envelope only: no I/O, no service call + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None: + payload = self.extract_payload(event, MyEventDto) # Typed extraction with validation + outcome = await self._service.on_my_event(payload.item_id, event_id=event.id) # exactly ONE call + if outcome is None: + return HandlerResult.skipped("nothing to do for this item") + return HandlerResult(event_type="my.result.type", data=outcome.model_dump()) ``` **`self.extract_payload(event, ModelType)`** validates `event.data` against a Pydantic model and returns a typed instance. Raises `InvalidEventError` if data is missing or invalid. +A handler translates, it never decides: `extract_payload` -> one service call with domain values +(never the CloudEvent or the DTO) -> result. Whether the event needs work is the service's answer; +`HandlerResult.skipped(reason)` reports "responsible, nothing to do" (chain stops, acked, INFO log), +`None` passes the event to the next handler. No `agent.run()` and no `registry.get_agent()` in a +handler. Make the *service* safe to run twice on the same event (at-least-once delivery). + #### Service Services contain ALL business logic. Each responsibility gets its own method — do not put everything in one big method. @@ -145,29 +153,32 @@ class CleanupScheduler(SchedulerBase): async def on_startup(self) -> None: self._service = self.registry.get_service(CleanupService) + await super().on_startup() # required: the base class starts the timer / tick handler async def on_shutdown(self) -> None: - pass + await super().on_shutdown() async def tick(self) -> None: """Called on each cron interval.""" await self._service.run_cleanup() ``` -#### AgentRuntime (in main.py) +#### AgentRuntime (declared in main.py, built by the host) ```python my_agent = ( - AgentBuilder(config, runtime_name="my_agent") - .with_model_from_config("my_agent") - .with_system_prompt("system") # Loads prompts/system.prompt (static, no dynamic inputs) + AgentBuilder(runtime_name="my_agent") # no Config, no build(): main.py is a declaration + .with_model_from_config() + .with_system_prompt("my_agent_system") # prompts/my_agent_system.prompt (static, no dynamic inputs) .with_tools([tool_one, tool_two]) .with_result_type(MyResultModel) .with_metrics() - .build(name="my_agent") ) +# registered as: AppBuilder()...with_agent(my_agent, name="my_agent") ``` +The service resolves it in `on_startup()` with `self.registry.get_agent("my_agent")` and runs it. + ### Step 3: Create Pydantic Models All models go in `src/models/`: @@ -214,7 +225,9 @@ Analyze the following order and produce a compliance assessment. ### Step 5: Wire in main.py -Read the existing `src/main.py` and add the new component to the `AppBuilder` chain in the correct dependency order: +Read the existing `src/main.py` -- a declaration (`agent = AppBuilder()...` without `Config` or +`build()`, plus `create_app()`) -- and add the new component as a **class**, one registration per +line, in the correct dependency order: 1. Services (independent first) 2. Agents @@ -238,7 +251,8 @@ Add to `settings.toml`: 6. **Pydantic models for all API request/response types** 7. **Every public method needs a docstring** 8. **Services contain ALL business logic** — one method per responsibility, not one giant method -9. **Handlers and APIs are thin delegation layers** — they call service methods +9. **Handlers and APIs are thin delegation layers** — `can_handle_event` routes on the envelope only; `handle_event` makes exactly one service call; relevance checks live in the service and come back as `HandlerResult.skipped(reason)`; handlers never call the LLM +13. **No run state on `self`** — components serve concurrent runs; per-event values stay in locals and parameters 10. **Context managers for HTTP clients, files, DB connections** 11. **Secrets in `.secrets.toml`** — never hardcoded 12. **System prompt is static** (no dynamic inputs) — **instruction prompt has dynamic inputs** 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 2bb61883..1d19cb3c 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 @@ -53,12 +53,12 @@ After scaffolding, implement the component logic: 3. **Implement the component** following these patterns: ### EventHandler -- `can_handle_event()`: Filter by `event.type` or event data -- `handle_event()`: Process event, return `HandlerResult` or `None` -- Resolve service dependencies in `on_startup()` via `self.registry.get_service()` +- `can_handle_event()`: route on the envelope only (`event.type`, `source`, `subject`, context keys) -- no I/O +- `handle_event()`: `extract_payload` -> exactly **one** service call -> `HandlerResult`, `HandlerResult.skipped(reason)` (responsible, nothing to do) or `None` (let the next handler try) +- Resolve the service in `on_startup()` via `self.registry.get_service()`; never call the LLM from a handler ### Service -- Add domain methods with clear input/output types +- Add domain methods with clear input/output types; one entry-point method per event the handler forwards (including the relevance check) - Resolve agent/cache dependencies in `on_startup()` ### RestApi @@ -67,19 +67,19 @@ After scaffolding, implement the component logic: - Resolve services in `on_startup()` ### AgentRuntime -- Configure via `AgentBuilder` in `main.py` (not in a separate file) +- Declare via `AgentBuilder(runtime_name=...)` in `main.py` -- unbuilt, no `Config`; register with `.with_agent(builder, name=...)` - Set system prompt, tools, result type, and model config - Create `.prompt` file in `src/prompts/` if needed ### Scheduler -- Implement `tick()` with the recurring logic -- Resolve dependencies in `on_startup()` +- Implement `tick()` with the recurring logic (delegate to a service) +- Resolve dependencies in `on_startup()` and then call `await super().on_startup()` -- without it the scheduler never runs ## Step 4: Wire into main.py Add the component to the `AppBuilder` chain in `src/main.py`: - Import the new component -- Add the appropriate `.with_*()` call in dependency order +- Add the appropriate `.with_*()` call in dependency order, passing the **class** (never an instance); `main.py` stays a declaration without `Config` or `build()` - For agents: add `AgentBuilder` setup before the `AppBuilder` chain ## Step 5: Update Configuration diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md index 7b116ea4..e49f3544 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md @@ -19,11 +19,14 @@ asbs docs components/event-handlers --cat # writing a handler **Return value is control flow:** -- `return None` - not mine, or nothing to publish. The event passes to the next handler. - `return HandlerResult(...)` - publish that event and **stop the chain**. +- `return HandlerResult.skipped("reason")` - this handler is responsible but the event needs + nothing: **stop the chain**, acknowledge, log the reason at INFO, count `blueprint.events.skipped`. +- `return None` - another handler should get it. The event passes to the next handler; if none + takes it, the framework logs "No handler processed event". **Delivery is at-least-once.** The same event can reach `handle_event` more than once: a lost ack, a -pod restart, a rolling deploy. Either make the method safe to repeat, or set **both** +pod restart, a rolling deploy. Either make the service it calls safe to repeat, or set **both** `idempotency_enabled = true` and `idempotency_ttl = `; the framework then skips an event whose id and source it has already dispatched, within that window. It is off by default on purpose - only you know whether replaying your side effects is acceptable. @@ -45,17 +48,25 @@ class OrderHandler(EventHandlerBase): self._service = self.registry.get_service(OrderService) async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: - return event.type == "order.placed" + return event.type == "order.placed" # envelope only: no I/O, no service call async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None: - order = self.extract_payload(event, OrderModel) - result = await self._service.process(order) - return HandlerResult(event_type="order.processed", data=result) + payload = self.extract_payload(event, OrderPlacedEvent) + outcome = await self._service.on_order_placed(payload.order_id, event_id=event.id) # ONE call + if outcome is None: + return HandlerResult.skipped("order needs no processing") + return HandlerResult(event_type="order.processed", data=outcome.model_dump()) ``` - **`self.extract_payload(event, Model)`** validates `event.data` and returns a typed instance, raising `InvalidEventError` that the framework handles. Do not hand-parse `event.data`. -- Handlers are a **thin delegation layer**. Business logic belongs in a service. +- **A handler translates, it never decides.** `extract_payload` -> exactly one service call with + domain values (never the CloudEvent or the DTO) -> result. Two service calls in a row are + business logic: give the service one entry-point method. +- **Relevance is the service's decision** ("did the status change?"); the handler reports "no" as + `HandlerResult.skipped(reason)`. +- **No LLM in a handler**: no `agent.run()`, no `registry.get_agent()`, no runtime from `context`. +- **No run state on `self`**: runs are concurrent; per-event values stay in locals. - Dependencies resolve in `on_startup()`, never in `__init__`. ## Publishing from elsewhere diff --git a/src/blueprint/agent_generator/docs/components/agents.md b/src/blueprint/agent_generator/docs/components/agents.md index 17ecef71..06da738b 100644 --- a/src/blueprint/agent_generator/docs/components/agents.md +++ b/src/blueprint/agent_generator/docs/components/agents.md @@ -14,11 +14,13 @@ Agents wrap LLM interactions with structured inputs, outputs, tools, and prompt ## AgentBuilder Fluent API -Build an agent using the chainable builder methods: +Declare an agent runtime with the chainable builder methods. The declaration is not built where +it is written: it is registered with `AppBuilder.with_agent(...)` and the host builds it with the +rest of the agent (see [Registration](#registration)). ```python from pydantic import BaseModel -from blueprint.agents import AgentBuilder, Config +from blueprint.agents import AgentBuilder from blueprint.agents.agent.tool import Tool @@ -34,15 +36,12 @@ def search_documents(query: str) -> list[str]: return ["passage 1", "passage 2"] -config = Config() - -agent = ( - AgentBuilder(config, runtime_name="summarizer") +summarizer = ( + AgentBuilder(runtime_name="summarizer") .with_model_from_config() .with_system_prompt("summarizer") .with_tools([Tool(name="search_documents", function=search_documents)]) .with_result_type(SummaryOutput) - .build() ) ``` @@ -110,15 +109,18 @@ Enables or disables metric collection for this agent. ### build() -Finalizes the agent configuration and returns an `AgentRuntime` instance. The agent is automatically registered with the application registry under its `runtime_name`. +Finalizes the agent configuration and returns an `AgentRuntime` instance. In an application you +never call it: `AppBuilder.build()` builds every declared runtime and registers it under the name +given to `with_agent`. Call it yourself only outside an application -- a script or a test: ```python -agent = builder.build() +runtime = builder.build(config) ``` ## Running an Agent -Once built, invoke the agent with a user prompt: +A service resolves the runtime in `on_startup()` (`self.registry.get_agent("summarizer")`) and +invokes it with a user prompt -- handlers never do: ```python result = await agent.run("Summarize the Q4 earnings report") @@ -143,15 +145,15 @@ class SentimentResult(BaseModel): reasoning: str -agent = ( - AgentBuilder(config, runtime_name="sentiment_analyzer") +sentiment_analyzer = ( + AgentBuilder(runtime_name="sentiment_analyzer") .with_model_from_config() .with_system_prompt("sentiment") .with_result_type(SentimentResult) - .build() ) -result = await agent.run("The product exceeded all expectations.") +# in a service, after self._agent = self.registry.get_agent("sentiment_analyzer"): +result = await self._agent.run("The product exceeded all expectations.") print(result.output.sentiment) # "positive" print(result.output.confidence) # 0.95 ``` @@ -282,27 +284,24 @@ This captures token usage, latency, and success/failure status for observability ## Registration -Register agents with the application builder: +Register agents in `src/main.py`, the declaration `asbs setup` writes. Pass the **unbuilt** +`AgentBuilder` and the name services resolve it by: ```python -from blueprint.agents import AppBuilder, Config - -config = Config() +from blueprint.agents import AgentBuilder, AppBuilder summarizer = ( - AgentBuilder(config, runtime_name="summarizer") + AgentBuilder(runtime_name="summarizer") .with_model_from_config() .with_system_prompt("summarizer") .with_result_type(SummaryOutput) - .build() ) -app = ( - AppBuilder(config) - .with_agent(summarizer) +agent = ( + AppBuilder() .with_service(DocumentService) + .with_agent(summarizer, name="summarizer") .with_handler(DocumentHandler) - .build() ) ``` @@ -314,7 +313,7 @@ A complete example showing a handler that uses an agent through a service. ```python from pydantic import BaseModel -from blueprint.agents import AgentBuilder, Config +from blueprint.agents import AgentBuilder from blueprint.agents.agent.tool import Tool @@ -333,16 +332,13 @@ def lookup_category_definitions() -> list[dict]: ] -config = Config() - classifier_agent = ( - AgentBuilder(config, runtime_name="ticket_classifier") + AgentBuilder(runtime_name="ticket_classifier") .with_model_from_config() .with_system_prompt("ticket_classifier") .with_tools([Tool(name="lookup_category_definitions", function=lookup_category_definitions)]) .with_result_type(ClassificationResult) .with_metrics(True) - .build() ) ``` @@ -389,19 +385,29 @@ class TicketService(ServiceBase): ```python from typing import Any from blueprint.agents.handler.event_handler_base import EventHandlerBase -from blueprint.agents.handler.handler_result import HandlerResult -from blueprint.agents.events.generic_cloud_event import GenericCloudEvent +from pydantic import BaseModel + +from blueprint.agents.models.events import GenericCloudEvent, HandlerResult + + +class TicketCreated(BaseModel): + """DTO: the payload of a ticket.created event.""" + + ticket_id: str + text: str class TicketClassificationHandler(EventHandlerBase): def __init__(self) -> None: super().__init__(priority=100) - self._ticket_service = None async def on_startup(self) -> None: self._ticket_service = self.registry.get_service(TicketService) + async def on_shutdown(self) -> None: + pass + async def can_handle_event( self, event: GenericCloudEvent, context: dict[str, Any] ) -> bool: @@ -410,30 +416,24 @@ class TicketClassificationHandler(EventHandlerBase): async def handle_event( self, event: GenericCloudEvent, context: dict[str, Any] ) -> HandlerResult: - if self._ticket_service: - - classification = await self._ticket_service.classify_ticket( - event.data["text"] - ) - return HandlerResult( - data={**event.data, "classification": classification}, - event_type="com.example.ticket.classified", - ) + payload = self.extract_payload(event, TicketCreated) + classification = await self._ticket_service.classify_ticket(payload.text) + return HandlerResult( + data={"ticket_id": payload.ticket_id, "classification": classification}, + event_type="com.example.ticket.classified", + ) ``` ### Application Assembly ```python -from blueprint.agents import AppBuilder, Config +from blueprint.agents import AppBuilder -config = Config() - -app = ( - AppBuilder(config) - .with_agent(classifier_agent) +agent = ( + AppBuilder() .with_service(TicketService) + .with_agent(classifier_agent, name="ticket_classifier") .with_handler(TicketClassificationHandler) - .build() ) ``` diff --git a/src/blueprint/agent_generator/docs/components/event-handlers.md b/src/blueprint/agent_generator/docs/components/event-handlers.md index b8cb2dbd..07a235e7 100644 --- a/src/blueprint/agent_generator/docs/components/event-handlers.md +++ b/src/blueprint/agent_generator/docs/components/event-handlers.md @@ -11,7 +11,7 @@ from blueprint.agents.models.events import GenericCloudEvent, HandlerResult ## Purpose -Event handlers are the primary entry point for asynchronous event processing. When a CloudEvent arrives (via Dapr, NATS, or HTTP), the framework iterates through all registered handlers in priority order. Each handler is asked whether it can process the event via `can_handle_event()`; if it can, `handle_event()` is called. Handlers should be thin — delegate all domain logic to services. +Event handlers are the primary entry point for asynchronous event processing. When a CloudEvent arrives (via Dapr, NATS, or HTTP), the framework iterates through all registered handlers in priority order. Each handler is asked whether it is responsible for the event via `can_handle_event()`; if it is, `handle_event()` is called, and the first result that is not `None` ends the chain. **A handler translates, it never decides:** it routes on the envelope, extracts the payload, makes one service call and turns the answer into a result. All domain logic -- including whether a particular event needs work -- lives in services. ## Base Class @@ -57,7 +57,7 @@ super().__init__(priority=500) # Runs late ### can_handle_event -Determines whether this handler should process the given event. Return `True` to claim the event, `False` to skip it. Even if `False` is returned, the next handler still runs — returning `False` does not stop the chain. +Routes the event: is this handler the one for this kind of event? Return `True` to claim it, `False` to let the next handler be asked. Decide on the envelope only -- `event.type`, `event.source`, `event.subject` and the context keys -- with no I/O and no service call. Whether *this particular* event needs work is the service's decision, reported through `handle_event` (see `HandlerResult.skipped` below). ```python async def can_handle_event( @@ -68,31 +68,46 @@ async def can_handle_event( ### handle_event -Performs the actual processing. Called only when `can_handle_event` returned `True`. +Called only when `can_handle_event` returned `True`. Three steps, nothing more: + +1. `self.extract_payload(event, MyEventDto)` -- the typed, validated payload. +2. **One** service call with domain values (ids, domain models -- never the CloudEvent or the DTO). + Two service calls in a row are business logic already: give the service one entry-point method. +3. The service's answer as a result. ```python async def handle_event( self, event: GenericCloudEvent, context: dict[str, Any] -) -> Any | HandlerResult | list[HandlerResult] | None: - result = await self._order_service.process(event.data) - return HandlerResult(data=result, event_type="order.processed") +) -> HandlerResult | None: + payload = self.extract_payload(event, OrderCreatedEvent) + outcome = await self._order_service.on_order_created(payload.order_id, event_id=event.id) + if outcome is None: + return HandlerResult.skipped("order needs no processing") + return HandlerResult(event_type="order.processed", data=outcome.model_dump()) ``` +A handler never calls the LLM -- no `agent.run()`, no `registry.get_agent()`, and it does not run the +runtime the chain puts into `context["runtime"]`. The service resolves its agent in `on_startup()`. + ## Return Value Semantics The return value of `handle_event` controls what happens next: | Return Value | Behavior | |---|---| -| `None` | Passes control to the next handler in the chain. | -| `HandlerResult` | Publishes a new CloudEvent downstream; passes control to the next handler. | -| `list[HandlerResult]` | Publishes multiple CloudEvents; passes control to the next handler. | -| Any other value | Stored internally for chaining; no event publication; passes to next handler. | +| `None` | Passes control to the next handler in the chain. If no handler returns anything else, the framework logs "No handler processed event" and acknowledges. | +| `HandlerResult` | Publishes a new CloudEvent if its `event_type` is mapped; **the chain stops**. | +| `list[HandlerResult]` | Publishes multiple CloudEvents; **the chain stops**. | +| `HandlerResult.skipped(reason)` | This handler is responsible but the event needs nothing: **the chain stops**, nothing is published, the delivery is acknowledged, the reason is logged at INFO and counted as `blueprint.events.skipped`. The run reports `ProcessingStatus.SKIPPED`; a REST caller gets `success = true` with the reason. | +| Any other value | Returned as the run's result; no event publication; **the chain stops**. | -Note: The handler chain always continues through all handlers that return `True` from `can_handle_event`. Returning a `HandlerResult` does not stop subsequent handlers. +The first handler that returns anything other than `None` ends the chain (`handler_chain.py`, `_dispatch`). Use `None` only when another handler should be offered the event; a handler that owns the event and finds nothing to do returns `HandlerResult.skipped(reason)`. ## Sharing Data Between Handlers via context +Prefer one handler per event type with a service entry point; a chain of handlers that hand data +on through `context` is for cross-cutting steps, not for splitting one piece of domain logic. + The `context` dictionary is shared across all handlers processing the same event. A handler early in the chain (low priority) can write parsed or enriched data into `context`, and a later handler reads it — avoiding redundant work. ```python @@ -137,25 +152,20 @@ delivery: | Key | Transport | Value | |---|---|---| -| `nats_topic` | NATS | The subscription that matched, possibly a wildcard: `t.*.risk.>` | -| `nats_subject` | NATS | The subject the message was delivered on: `t.T1.risk.created` | +| `nats_topic` | NATS | The subscription as the agent declared it, possibly a wildcard: `orders.>` | +| `nats_subject` | NATS | The subject the message was delivered on, as the agent knows it: `orders.created`. On a named connection the binding's `subject_prefix` is stripped again, so a handler sees the same subject on every connection. | +| `nats_connection` | NATS | The name of the named connection the delivery came from; absent on the default connection. An opaque name for logs and for passing on -- the framework attaches no meaning to it. | | `dapr_topic` | Dapr | The topic the sidecar delivered to | -**Derive anything security-relevant from `nats_subject`, not from the event.** Every field of the -event -- `tenantid` and any other extension included -- is whatever the publisher wrote. The subject -is what the broker routed, and under subject-scoped publish permissions it is what the broker checked -the publisher was allowed to use. Nothing in the payload can overwrite a context key. - -```python -from blueprint.agents.io.api.eventing.nats import NATS_SUBJECT_CONTEXT_KEY - -async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> None: - tenant = context[NATS_SUBJECT_CONTEXT_KEY].split(".")[1] # t..risk. -``` +**Derive anything security-relevant from the delivery, not from the event.** Every field of the +event is whatever the publisher wrote. The connection and the subject are what the broker routed -- +under subject-scoped publish permissions, what the broker checked the publisher was allowed to use. +Nothing in the payload can overwrite a context key. Which deployment-level scope a connection stands +for is decided by the connection source (its `validate` and `run_scope` hooks), not by handlers. -The key is present only for events NATS delivered: a test, a direct `process_event` call or another -transport has no subject, so read it with `.get()` where that can happen. Handlers share `context`, -so a handler earlier in the chain could overwrite it -- do not write to transport keys. +The keys are present only for events NATS delivered: a test, a direct `process_event` call or another +transport has none, so read them with `.get()` where that can happen. Handlers share `context`, +so a handler earlier in the chain could overwrite them -- do not write to transport keys. ## Published Event Types @@ -209,17 +219,17 @@ class OrderHandler(EventHandlerBase): ## Registration -Register handlers with `AppBuilder` by passing the **class** or an instance of the class: +Register handlers with `AppBuilder` by passing the **class** -- an instance is refused in a group, +because it would be constructed before any namespace exists. In `src/main.py` (a declaration; see +[agents](agents.md) and the `create_app()` that `asbs setup` writes): ```python -from blueprint.agents import AppBuilder, Config +from blueprint.agents import AppBuilder -config = Config(settings_files=["settings.toml", ".secrets.toml"]) -app = ( - AppBuilder(config) +agent = ( + AppBuilder() .with_service(OrderService) .with_handler(OrderHandler) - .build() ) ``` @@ -229,11 +239,21 @@ Services must be registered before the handlers that depend on them. ```python from typing import Any + +from pydantic import BaseModel + from blueprint.agents.handler.event_handler_base import EventHandlerBase from blueprint.agents.models.events import GenericCloudEvent, HandlerResult from blueprint.agents.services.service_base import ServiceBase +class OrderConfirmedEvent(BaseModel): + """DTO: the payload of an order.confirmed event.""" + + order_id: str + items: list[dict] + + class InvoiceService(ServiceBase): """Domain service for invoice processing.""" @@ -243,7 +263,10 @@ class InvoiceService(ServiceBase): async def on_shutdown(self) -> None: pass - async def generate_invoice(self, order_id: str, items: list[dict]) -> dict: + async def generate_invoice(self, order_id: str, items: list[dict]) -> dict | None: + """None: nothing to invoice.""" + if not items: + return None return {"invoice_id": "INV-001", "order_id": order_id, "total": 99.99} @@ -271,23 +294,17 @@ class InvoiceHandler(EventHandlerBase): async def handle_event( self, event: GenericCloudEvent, context: dict[str, Any] ) -> HandlerResult | None: - if self._invoice_service is None: - return None - - order_data = event.data or {} - order_id = order_data.get("order_id", "") - items = order_data.get("items", []) - - try: - invoice = await self._invoice_service.generate_invoice(order_id, items) - return HandlerResult(data=invoice, event_type="invoice.created") - except Exception as exc: - return HandlerResult( - data={"order_id": order_id, "error": str(exc)}, - event_type="invoice.error", - ) + payload = self.extract_payload(event, OrderConfirmedEvent) # DTO, validated + invoice = await self._invoice_service.generate_invoice(payload.order_id, payload.items) + if invoice is None: + return HandlerResult.skipped("order has nothing to invoice") + return HandlerResult(data=invoice, event_type="invoice.created") ``` +A failure is not turned into a result here: an exception reaches the transport, which settles the +delivery (nak and redeliver, or terminate for `InvalidEventError`). If the domain needs an +`invoice.error` event, the service decides that and returns it as its answer. + ## Testing Use a mock registry to unit test handlers in isolation. diff --git a/src/blueprint/agent_generator/docs/components/rest-apis.md b/src/blueprint/agent_generator/docs/components/rest-apis.md index 64618f8b..50c0d275 100644 --- a/src/blueprint/agent_generator/docs/components/rest-apis.md +++ b/src/blueprint/agent_generator/docs/components/rest-apis.md @@ -169,14 +169,12 @@ async def get_order(self, order_id: str): Register API instances with the application builder. `with_rest_api` receives an instance or the class: ```python -from blueprint.agents import AppBuilder, Config - -config = Config() -app = ( - AppBuilder(config) - .with_rest_api(OrderApi()) - .with_rest_api(CustomerApi()) - .build() +from blueprint.agents import AppBuilder + +agent = ( + AppBuilder() + .with_rest_api(OrderApi) + .with_rest_api(CustomerApi) ) ``` @@ -301,14 +299,12 @@ class OrderApi(RestApiBase): ### Application Assembly ```python -from blueprint.agents import AppBuilder, Config +from blueprint.agents import AppBuilder -config = Config() -app = ( - AppBuilder(config) +agent = ( + AppBuilder() .with_service(OrderService) - .with_rest_api(OrderApi()) - .build() + .with_rest_api(OrderApi) ) ``` diff --git a/src/blueprint/agent_generator/docs/components/schedulers.md b/src/blueprint/agent_generator/docs/components/schedulers.md index 831dd8fd..b12599e7 100644 --- a/src/blueprint/agent_generator/docs/components/schedulers.md +++ b/src/blueprint/agent_generator/docs/components/schedulers.md @@ -133,13 +133,11 @@ async def tick(self) -> None: Register scheduler instances with the application builder. Note that `with_scheduler` receives an instance or a class: ```python -from blueprint.agents import AppBuilder, Config +from blueprint.agents import AppBuilder -config = Config() -app = ( - AppBuilder(config) - .with_scheduler(DataSyncScheduler()) - .build() +agent = ( + AppBuilder() + .with_scheduler(DataSyncScheduler) ) ``` @@ -241,16 +239,13 @@ class CatalogSyncScheduler(SchedulerBase): ### Application Assembly ```python -from blueprint.agents import AppBuilder, Config +from blueprint.agents import AppBuilder -config = Config() - -app = ( - AppBuilder(config) +agent = ( + AppBuilder() .with_service(ExternalApiClient) .with_service(CatalogService) - .with_scheduler(CatalogSyncScheduler()) - .build() + .with_scheduler(CatalogSyncScheduler) ) ``` diff --git a/src/blueprint/agent_generator/docs/components/services.md b/src/blueprint/agent_generator/docs/components/services.md index cffbf664..59b8e5c5 100644 --- a/src/blueprint/agent_generator/docs/components/services.md +++ b/src/blueprint/agent_generator/docs/components/services.md @@ -102,18 +102,16 @@ class NotificationService(ServiceBase): Register services with the application builder: ```python -from blueprint.agents import AppBuilder, Config +from blueprint.agents import AppBuilder -config = Config() -app = ( - AppBuilder(config) +agent = ( + AppBuilder() .with_service(OrderService) .with_service(NotificationService) - .build() ) ``` -Note that `with_service` receives the class or an instance. +Note that `with_service` receives the **class**: a group refuses an instance, because it would be constructed before any namespace exists. ## Best Practices diff --git a/src/blueprint/agent_generator/docs/concepts/architecture.md b/src/blueprint/agent_generator/docs/concepts/architecture.md index 96d46074..2596d3dd 100644 --- a/src/blueprint/agent_generator/docs/concepts/architecture.md +++ b/src/blueprint/agent_generator/docs/concepts/architecture.md @@ -18,42 +18,55 @@ Each base class follows the same lifecycle contract and participates in the comp ## AppBuilder Fluent API -Applications are assembled using `AppBuilder`, which exposes a fluent interface for registering components and producing a configured application instance. +An agent is a **declaration**: `src/main.py` records what the agent is made of, and the host builds +it -- `create_app()` when it runs on its own, `python -m blueprint.agents.entrypoint` when it is one +agent of a group (see [multi-agent setup](../guides/multi-agent-setup.md)). ```python -from blueprint.agents import AppBuilder, Config +from pathlib import Path + +from blueprint.agents import AgentBuilder, AppBuilder, Config -from my_app.handlers import IngestHandler, EnrichHandler -from my_app.services import EmbeddingService, StorageService -from my_app.agents import ResearchAgent from my_app.apis import QueryApi +from my_app.handlers import EnrichHandler, IngestHandler from my_app.schedulers import CleanupScheduler +from my_app.services import EmbeddingService, StorageService -config = Config(settings_files=["settings.toml", ".secrets.toml"]) +research = ( + AgentBuilder(runtime_name="research") + .with_model_from_config() + .with_system_prompt("research_system") +) -app = ( - AppBuilder(config) +agent = ( + AppBuilder() .with_service(EmbeddingService) .with_service(StorageService) + .with_agent(research, name="research") .with_handler(IngestHandler) .with_handler(EnrichHandler) - .with_agent("research", ResearchAgent) .with_rest_api(QueryApi) .with_scheduler(CleanupScheduler) .with_cache() - .build() ) + + +def create_app(): + return agent.build(Config(settings_files=["settings.toml", ".secrets.toml"], root_path=str(Path(__file__).parent.parent))) ``` ### Builder Methods -- `.with_handler(HandlerClass)` -- Register an event handler. Handlers are instantiated in registration order and sorted by priority at runtime. -- `.with_service(ServiceClass)` -- Register a shared service. Services start before handlers and agents, so they are available for dependency resolution. -- `.with_agent(name, AgentClass)` -- Register a named AI agent runtime. The name is used for configuration lookup and registry resolution. +Every `with_*` call records; nothing is constructed until `build()`. Components are passed as +**classes** -- a group refuses an instance, because it would exist before any namespace does. + +- `.with_service(ServiceClass)` -- Register a service. Services start before handlers and agents, so they are available for dependency resolution. +- `.with_agent(agent_builder, name="...")` -- Register an AI agent runtime from an unbuilt `AgentBuilder`. The name is the registry key services resolve it by. +- `.with_handler(HandlerClass)` -- Register an event handler. Handlers are sorted by priority at runtime. - `.with_rest_api(ApiClass)` -- Register a REST API module. Routes are mounted on the shared FastAPI instance. -- `.with_scheduler(SchedulerClass)` -- Register a scheduled task. Schedulers start last and are the first to shut down. -- `.with_cache()` -- Enable the built-in disk cache service. Once enabled, it is accessible through the registry. -- `.build()` -- Validate configuration, instantiate all components, and return the runnable application. +- `.with_scheduler(SchedulerClass)` -- Register a scheduled task. Schedulers start after the APIs and stop before them. +- `.with_cache()` -- Enable the built-in cache service. Once enabled, it is accessible through the registry. +- `.build(config)` -- Validate configuration, instantiate all components, and return the FastAPI application. Single use. ## Component Registry @@ -63,19 +76,20 @@ The component registry is a central service locator that all components share. C ```python from blueprint.agents.handler.event_handler_base import EventHandlerBase -from my_app.services import EmbeddingService +from blueprint.agents.services.service_base import ServiceBase class IngestHandler(EventHandlerBase): async def on_startup(self) -> None: - # Resolve a service by its class - self.embedding = self.registry.get_service(EmbeddingService) + # A handler resolves the one service it delegates to -- nothing else. + self._service = self.registry.get_service(EmbeddingService) - # Resolve an agent by its registered name - self.research_agent = self.registry.get_agent("research") - # Access the cache (if enabled via .with_cache()) - self.cache = self.registry.cache_service +class EmbeddingService(ServiceBase): + async def on_startup(self) -> None: + # Agents and the cache are resolved by services, which hold the business logic. + self._research = self.registry.get_agent("research") + self._cache = self.registry.cache_service # if enabled via .with_cache() ``` ### Registry Methods @@ -150,72 +164,113 @@ This ordering guarantees that a handler's `on_startup()` can safely call `self.r ## Full Wiring Example -The following example shows a complete application with all five component types wired together: +The following example shows all five component types. The handler only translates; the service +decides, including whether an event needs work at all. ```python -from blueprint.agents import AppBuilder, AgentBuilder, AgentRuntime, Config +from pathlib import Path +from typing import Any + +from pydantic import BaseModel + +from blueprint.agents import AgentBuilder, AppBuilder, Config from blueprint.agents.handler.event_handler_base import EventHandlerBase -from blueprint.agents.services.service_base import ServiceBase from blueprint.agents.io.api.rest_api_base import RestApiBase from blueprint.agents.io.api.scheduling.scheduler import SchedulerBase -from blueprint.agents.models.events import CloudEvent, HandlerResult +from blueprint.agents.models.events import GenericCloudEvent, HandlerResult +from blueprint.agents.services.service_base import ServiceBase -# -- Service -- +class DocumentReceived(BaseModel): + """DTO: the payload of a document.received event.""" + + content: str + + +# -- Service: all business logic -- class SummarizationService(ServiceBase): async def on_startup(self) -> None: - self.agent = self.registry.get_agent("summarizer") + self._agent = self.registry.get_agent("summarizer") - async def summarize(self, text: str) -> str: - return await self.agent.run(text) + async def on_shutdown(self) -> None: + pass + async def summarize(self, text: str) -> str | None: + """None: the document is too short to need a summary.""" + if len(text) < 200: + return None + result = await self._agent.run(text) + return str(result.output) -# -- Handler -- + +# -- Handler: extract, one service call, result -- class DocumentHandler(EventHandlerBase): - priority = 10 + def __init__(self) -> None: + super().__init__(priority=10) async def on_startup(self) -> None: - self.svc = self.registry.get_service(SummarizationService) + self._service = self.registry.get_service(SummarizationService) + + async def on_shutdown(self) -> None: + pass - def can_handle_event(self, event: CloudEvent) -> bool: + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: return event.type == "document.received" - async def handle_event(self, event: CloudEvent) -> HandlerResult: - summary = await self.svc.summarize(event.data["content"]) + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult: + payload = self.extract_payload(event, DocumentReceived) + summary = await self._service.summarize(payload.content) + if summary is None: + return HandlerResult.skipped("document too short to summarise") return HandlerResult(event_type="document.summarized", data={"summary": summary}) - def get_published_event_types(self) -> list[str]: - return ["document.summarized", "document.error"] - # -- REST API -- class StatusApi(RestApiBase): - def register_routes(self, router) -> None: - @router.get("/status") - async def get_status(): - return {"status": "operational"} + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + @RestApiBase.get("/status") + async def get_status(self) -> dict[str, str]: + return {"status": "operational"} # -- Scheduler -- class PurgeScheduler(SchedulerBase): + def __init__(self) -> None: + super().__init__(crontab="0 * * * *") + async def on_startup(self) -> None: - self.cache = self.registry.cache_service + self._cache = self.registry.cache_service + await super().on_startup() # required: without it the scheduler never runs + + async def on_shutdown(self) -> None: + await super().on_shutdown() - async def execute(self) -> None: - await self.cache.clear("temp") + async def tick(self) -> None: + self._cache.clear("temp") -# -- Application assembly -- -config = Config(settings_files=["settings.toml", ".secrets.toml"]) +# -- Declaration (src/main.py) -- +summarizer = AgentBuilder(runtime_name="summarizer").with_model_from_config().with_system_prompt("summarizer_system") -app = ( - AppBuilder(config) +agent = ( + AppBuilder() .with_service(SummarizationService) + .with_agent(summarizer, name="summarizer") .with_handler(DocumentHandler) - .with_agent("summarizer", AgentBuilder.from_config(config, "summarizer")) .with_rest_api(StatusApi) .with_scheduler(PurgeScheduler) .with_cache() - .build() ) + + +def create_app(): + return agent.build(Config(settings_files=["settings.toml", ".secrets.toml"], root_path=str(Path(__file__).parent.parent))) ``` + +A scheduler also needs `scheduler_mode` in `settings.toml` (no default; see +[schedulers](../components/schedulers.md)). diff --git a/src/blueprint/agent_generator/docs/concepts/caching.md b/src/blueprint/agent_generator/docs/concepts/caching.md index 523f2d9a..9363cfac 100644 --- a/src/blueprint/agent_generator/docs/concepts/caching.md +++ b/src/blueprint/agent_generator/docs/concepts/caching.md @@ -16,16 +16,13 @@ this file; see the git history for those. `with_cache()` on the builder: ```python -from blueprint.agents import AppBuilder, Config +from blueprint.agents import AppBuilder -config = Config(settings_files=["settings.toml", ".secrets.toml"]) - -app = ( - AppBuilder(config) +agent = ( + AppBuilder() .with_service(MyService) .with_handler(MyHandler) .with_cache() - .build() ) ``` @@ -38,7 +35,7 @@ configuration exists. Call it again with a name: ```python -AppBuilder(config).with_cache().with_cache(name="sessions").build() +AppBuilder().with_cache().with_cache(name="sessions") ``` Each name gets its own store -- its own directory on disk, its own key prefix on Redis -- and a diff --git a/src/blueprint/agent_generator/docs/concepts/configuration.md b/src/blueprint/agent_generator/docs/concepts/configuration.md index 9275c272..49162480 100644 --- a/src/blueprint/agent_generator/docs/concepts/configuration.md +++ b/src/blueprint/agent_generator/docs/concepts/configuration.md @@ -171,12 +171,13 @@ print(cache_config.default_ttl) # 3600 Configuration is validated automatically when `AppBuilder.build()` is called. If required settings are missing or have invalid types, a `ConfigError` is raised with a descriptive message. ```python -from blueprint.agents import AppBuilder, Config +from blueprint.agents import AgentBuilder, AppBuilder, Config -config = Config(settings_files=["settings.toml"]) +summarizer = AgentBuilder(runtime_name="summarizer").with_model_from_config() +agent = AppBuilder().with_agent(summarizer, name="summarizer") try: - app = AppBuilder(config).with_agent("summarizer", SummarizerAgent).build() + app = agent.build(Config(settings_files=["settings.toml"])) except ConfigError as e: # e.g., "Missing required config: default.runtimes.summarizer.model_provider" print(f"Configuration error: {e}") diff --git a/src/blueprint/agent_generator/docs/concepts/event-processing.md b/src/blueprint/agent_generator/docs/concepts/event-processing.md index ef374f30..26ad76e2 100644 --- a/src/blueprint/agent_generator/docs/concepts/event-processing.md +++ b/src/blueprint/agent_generator/docs/concepts/event-processing.md @@ -60,76 +60,79 @@ event: CloudEvent[DocumentPayload] = CloudEvent( ## Handler Chain-of-Responsibility -Event handlers form an ordered processing chain. When an event arrives, the framework iterates through registered handlers, asks each whether it can handle the event, and delegates processing to those that accept it. +Event handlers form an ordered chain. When an event arrives, the framework asks the handlers in +priority order whether they are responsible for it (`can_handle_event`); the first one that is runs +`handle_event`, and **the first result that is not `None` ends the chain**. ### Handler Priority -Handlers are sorted by their `priority` attribute (lower values execute earlier). This determines the order in which handlers are consulted for each incoming event. +Handlers are sorted by their `priority` (lower values are asked earlier), set through the base +class constructor: ```python -from blueprint.agents.handler.event_handler_base import EventHandlerBase -from blueprint.agents.models.events import CloudEvent +from typing import Any +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.events import GenericCloudEvent, HandlerResult -class ValidationHandler(EventHandlerBase): - priority = 1 # Runs first - - def can_handle_event(self, event: CloudEvent) -> bool: - return event.type == "document.received" - async def handle_event(self, event: CloudEvent) -> None: - if not event.data.get("content"): - raise ValueError("Empty document content") - # Return None to pass the event to the next handler - return None +class DocumentHandler(EventHandlerBase): + def __init__(self) -> None: + super().__init__(priority=10) + async def on_startup(self) -> None: + self._service = self.registry.get_service(DocumentService) -class EnrichmentHandler(EventHandlerBase): - priority = 10 # Runs after validation + async def on_shutdown(self) -> None: + pass - def can_handle_event(self, event: CloudEvent) -> bool: + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: return event.type == "document.received" - async def handle_event(self, event: CloudEvent) -> HandlerResult: - enriched = await self.enrich(event.data) - return HandlerResult(event_type="document.enriched", data=enriched) + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult: + payload = self.extract_payload(event, DocumentReceived) + enriched = await self._service.enrich(payload.document_id) + if enriched is None: + return HandlerResult.skipped("document already enriched") + return HandlerResult(event_type="document.enriched", data=enriched.model_dump()) ``` ### Handler Methods -Every handler must implement two methods: +Every handler implements two methods, both `async` and both given the event and the processing +`context`: -- **`can_handle_event(event)`** -- Return `True` if this handler should process the given event. Called for every incoming event. -- **`handle_event(event)`** -- Process the event and return a result that controls downstream behavior. +- **`can_handle_event(event, context)`** -- routing: return `True` if this handler is responsible for + this kind of event. Decide on the envelope only (`type`, `source`, `subject`, context keys) -- + no I/O, no service call. Called for every incoming event until one handler says yes. +- **`handle_event(event, context)`** -- translation: extract the payload, make **one** service call, + and return the answer as a result. Whether this particular event needs work is the service's + decision. ## Return Values from handle_event -The return value of `handle_event()` determines what happens after processing: +The return value of `handle_event()` determines what happens next: -### Return None -- Pass to Next Handler +| Return value | Chain | Published | Delivery | +|---|---|---|---| +| `None` | continues with the next handler | nothing | acked when the chain ends; if no handler returned anything, "No handler processed event" is logged | +| `HandlerResult(event_type=...)` | stops | the event, if `event_type` is in `topic_mapping` | acked after publishing | +| `list[HandlerResult]` | stops | each result | acked after publishing | +| `HandlerResult.skipped(reason)` | stops | nothing | acked; reason logged at INFO; counted as `blueprint.events.skipped` | +| a `dict` | stops | nothing, unless it carries an `event_type` key | acked; the dict is the run's result (e.g. for a REST caller) | +| an exception | stops | nothing | not acked -- redelivered (see the transport sections) | -Returning `None` or not returning signals that the handler has finished its work (or declined to act) and the event should continue to the next handler in the chain. +### Return None -- Offer the Event to the Next Handler -```python -async def handle_event(self, event: CloudEvent) -> None: - await self.log_event(event) - return None # Continue chain -``` +`None` means "not mine after all": the event goes on to the next handler. Use it only when another +handler should get the event. ### Return HandlerResult -- Publish a Downstream Event Returning a `HandlerResult` causes the framework to publish a new event to the configured event bus. ```python -from blueprint.agents.models.events import HandlerResult - - -async def handle_event(self, event: CloudEvent) -> HandlerResult: - summary = await self.summarize(event.data["content"]) - return HandlerResult( - event_type="document.summarized", - data={"summary": summary, "original_id": event.id}, - ) +return HandlerResult(event_type="document.summarized", data={"summary": summary, "original_id": event.id}) ``` ### Return a List of HandlerResult -- Publish Multiple Events @@ -137,15 +140,21 @@ async def handle_event(self, event: CloudEvent) -> HandlerResult: Returning a list publishes multiple downstream events, useful for fan-out patterns. ```python -async def handle_event(self, event: CloudEvent) -> list[HandlerResult]: - chunks = self.split_document(event.data["content"]) - return [ - HandlerResult( - event_type="chunk.created", - data={"chunk": chunk, "index": i}, - ) - for i, chunk in enumerate(chunks) - ] +return [HandlerResult(event_type="chunk.created", data={"chunk": chunk, "index": i}) for i, chunk in enumerate(chunks)] +``` + +### Return HandlerResult.skipped -- Responsible, Nothing to Do + +The handler owns the event, and its service decided that this particular event needs nothing (the +status did not change, the document is already processed). The chain stops, nothing is published, +the delivery is acknowledged, and the reason is logged at INFO and counted as +`blueprint.events.skipped` -- apart from unhandled events, which say something about the +subscription rather than about the agent's rules. The run's status is `ProcessingStatus.SKIPPED`. + +```python +outcome = await self._service.on_project_updated(payload.project_id, event_id=event.id) +if outcome is None: + return HandlerResult.skipped("project not relevant for this agent") ``` ### When publishing a result fails @@ -166,15 +175,10 @@ Two cases are skipped with a WARNING rather than failed, because they are config a failure: an `event_type` with no entry in `topic_mapping`, and a result that would be published to the topic its inbound event came from. -### Return Any Other Value -- Internal Chaining +### Return a dict -Returning any other value passes it along internally within the handler chain without publishing to the event bus. This is useful for in-process data transformation between handlers. - -```python -async def handle_event(self, event: CloudEvent) -> dict: - # This result is available to the next handler but is not published - return {"validated": True, "timestamp": datetime.utcnow().isoformat()} -``` +A `dict` ends the chain like a result: with an `event_type` key it is published like a `HandlerResult`, otherwise it is the run's result (a REST +caller receives it as `data`). It is not handed to another handler. ## Declaring Published Event Types @@ -421,38 +425,43 @@ job_timeout_seconds = 300 ## Complete Handler Example ```python +from typing import Any + +from pydantic import BaseModel + from blueprint.agents.handler.event_handler_base import EventHandlerBase -from blueprint.agents.models.events import CloudEvent, HandlerResult +from blueprint.agents.models.events import GenericCloudEvent, HandlerResult -class IngestionHandler(EventHandlerBase): - priority = 5 +class DocumentChanged(BaseModel): + """DTO: the payload of document.received / document.updated.""" - async def on_startup(self) -> None: - self.storage = self.registry.get_service(StorageService) - self.cache = self.registry.cache_service + document_id: str - def can_handle_event(self, event: CloudEvent) -> bool: - return event.type in ("document.received", "document.updated") - async def handle_event(self, event: CloudEvent) -> HandlerResult | list[HandlerResult]: - doc_id = event.subject +class IngestionHandler(EventHandlerBase): + def __init__(self) -> None: + super().__init__(priority=5) - # Check cache for deduplication - cached = await self.cache.get(doc_id, namespace="ingested") - if cached and event.type == "document.received": - return None # Already processed, skip + async def on_startup(self) -> None: + self._ingestion = self.registry.get_service(IngestionService) - # Store the document - await self.storage.save(doc_id, event.data) - await self.cache.set(doc_id, True, namespace="ingested", ttl=3600) + async def on_shutdown(self) -> None: + pass - # Publish downstream - return HandlerResult( - event_type="document.stored", - data={"doc_id": doc_id, "source": event.source}, - ) + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return event.type in ("document.received", "document.updated") - def get_published_event_types(self) -> list[str]: - return ["document.stored", "document.ingestion_error"] + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult: + payload = self.extract_payload(event, DocumentChanged) + stored = await self._ingestion.ingest(payload.document_id, event_id=event.id) + if stored is None: + return HandlerResult.skipped("document already ingested") + return HandlerResult(event_type="document.stored", data={"doc_id": stored.document_id}) + + def get_published_event_types(self) -> tuple[str, str] | None: + return ("document.stored", "document.ingestion_error") ``` + +The deduplication ("already ingested"), the storage and the cache all live in `IngestionService`; +the handler only translates. diff --git a/src/blueprint/agent_generator/docs/concepts/observability.md b/src/blueprint/agent_generator/docs/concepts/observability.md index 26e36a55..53a0580e 100644 --- a/src/blueprint/agent_generator/docs/concepts/observability.md +++ b/src/blueprint/agent_generator/docs/concepts/observability.md @@ -111,6 +111,7 @@ An exception propagating out of the method sets the span status to `ERROR` befor | `blueprint.namespace.inflight` | gauge | Dispatches that agent has in progress. Carries `agent`. | | `blueprint.events.unhandled` | counter | Events an agent received and found nothing to do with. Carries `agent` and `topic`. | | `blueprint.events.duplicate` | counter | Events an agent recognised as already processed. Carries `agent` and `topic`. | +| `blueprint.events.skipped` | counter | Events whose responsible handler returned `HandlerResult.skipped` -- the agent's own relevance rule, not a too-broad subscription. Carries `agent` and `topic`. | | `blueprint.nats.connection.bound` | gauge | `1` while a named NATS connection is bound and delivering, `0` otherwise. Carries `agent` and `connection`. | | `blueprint.nats.connection.permission_violations` | counter | Permission violations the broker reported on a named connection. Carries `agent` and `connection`. | | `llm.tokens.count` | counter | Tokens consumed, by an agent's model calls. | diff --git a/src/blueprint/agent_generator/docs/getting-started.md b/src/blueprint/agent_generator/docs/getting-started.md index a12f706c..0d53e2e6 100644 --- a/src/blueprint/agent_generator/docs/getting-started.md +++ b/src/blueprint/agent_generator/docs/getting-started.md @@ -148,44 +148,51 @@ Each command scaffolds a new file in the appropriate directory with the correct ## Understanding main.py -The `main.py` file is where you wire all components together using the `AppBuilder` fluent API. Here is a typical example: +`src/main.py` is a **declaration**: it records what the agent is made of with the `AppBuilder` +fluent API, and nothing is constructed until the host calls `build()`. This is what `asbs setup` +writes: ```python -from blueprint.agents import AppBuilder, AgentBuilder, AgentRuntime, Config -from blueprint.agents.handler.event_handler_base import EventHandlerBase -from blueprint.agents.services.service_base import ServiceBase -from blueprint.agents.io.api.rest_api_base import RestApiBase -from blueprint.agents.io.api.scheduling.scheduler import SchedulerBase +from pathlib import Path -from src.handlers.my_handler import MyHandler -from src.services.my_service import MyService -from src.api.my_api import MyApi +from blueprint.agents import AgentBuilder, AppBuilder, Config -app = ( +from .api.my_api import MyApi +from .handlers.my_handler import MyHandler +from .services.my_service import MyService + +my_agent = ( + AgentBuilder(runtime_name="my_agent") + .with_model_from_config() + .with_system_prompt("my_agent_system") +) + +agent = ( AppBuilder() - .with_config(Config()) - .with_handler(MyHandler) .with_service(MyService) - .with_api(MyApi) - .with_agent( - AgentBuilder() - .with_name("my-agent") - .with_prompt_file("src/prompts/system.md") - .build() - ) - .build() + .with_agent(my_agent, name="my_agent") + .with_handler(MyHandler) + .with_rest_api(MyApi) ) + + +def create_app(): + """Build this agent as an application of its own.""" + return agent.build(Config(settings_files=["settings.toml", ".secrets.toml"], root_path=str(Path(__file__).parent.parent))) ``` ### Key points -- **`AppBuilder`** is the central assembly point. It uses a fluent (method-chaining) API to register each component. +- **`AppBuilder`** is the central assembly point. Every `with_*` call records a component, passed as + a **class**; `build()` constructs them in dependency order and returns the FastAPI app. +- **`create_app()`** is how the agent runs on its own (`uvicorn src.main:create_app --factory`). In a + group, `python -m blueprint.agents.entrypoint` builds the same declaration under the agent's + namespace -- nothing in this file changes. - **`Config`** loads values from `settings.toml` and `.secrets.toml` via Dynaconf. Environment variables can override any setting. -- **Handlers** (`EventHandlerBase` subclasses) process incoming events from message queues or other sources. -- **Services** (`ServiceBase` subclasses) encapsulate reusable business logic and are injected into handlers and APIs. +- **Handlers** (`EventHandlerBase` subclasses) translate incoming events into one service call each. +- **Services** (`ServiceBase` subclasses) hold all business logic and are resolved by handlers and APIs. - **APIs** (`RestApiBase` subclasses) define REST endpoints that are automatically mounted on the FastAPI server. -- **Agents** are configured with `AgentBuilder`, which accepts a name, prompt files, and other LLM-specific settings. -- **`AgentRuntime`** manages the lifecycle of all registered components at runtime. +- **Agents** are declared with `AgentBuilder` (unbuilt) and registered with `with_agent(builder, name=...)`; services resolve them by that name. --- diff --git a/src/blueprint/agent_generator/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md index 7a34a713..8cf29e47 100644 --- a/src/blueprint/agent_generator/docs/guides/deployment.md +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -14,11 +14,12 @@ Two things shape everything below, and both are recent: in both scheduler modes, and event deduplication is available. What you have to decide is listed under [Running more than one replica](#running-more-than-one-replica). -> **The delivery behaviour is covered by unit tests against mocked transports and has not been -> exercised against a real broker.** Queue-group distribution across replicas, redelivery after -> `nats_ack_wait`, durable survival across reconnect and the shutdown drain are all specified and -> implemented; none of them has been watched happening on a live NATS server. Treat the first -> multi-replica deployment as the experiment it is. +> **The delivery behaviour is tested against a real NATS server** (`tests/integration`, a +> `nats:2.10` broker with JetStream): acknowledgement exactly once, redelivery after `nats_ack_wait`, +> concurrent runs, the `in_progress` heartbeat, the run timeout, reconnect with resubscription and +> named connections on an account-per-connection broker. Distribution across several *pods* has +> been measured with several clients in one test process, not with real pods; treat the first +> multi-replica deployment accordingly. --- @@ -332,17 +333,21 @@ scaling out and regrouping are independent of each other. | Outcome | Disposition | |---|---| -| Handled, or no handler matched it | **ack** -- an unmatched event is not a failure | +| Handled, skipped (`HandlerResult.skipped`), or no handler matched it | **ack** -- none of them is a failure | | A retryable failure | **nak**, redelivered after `nats_ack_wait` | +| A run that exceeded `nats_handler_timeout` | cancelled and **nak**'d for immediate redelivery | | A poison payload, or a `CriticalHandlerError` | **term**, and dead-lettered | | `nats_max_deliver` attempts exhausted | dead-lettered | -Two keys to set deliberately: +Keys to set deliberately. Unset, each is the server's default: the framework sets no consumer +setting on its own. -Unset, each is the server's default: the framework sets no consumer setting on its own. - -- **`nats_ack_wait`** (server default: 30 s on NATS) must exceed your p99 handler duration. Set it - below that and the broker redelivers work that is still in progress, to a second replica. +- **`nats_ack_wait`** (server default: 30 s on NATS). A running JetStream delivery reports + `in_progress` every third of it (`nats_heartbeat_enabled`, on by default), so a long run is not + redelivered while it runs. What the heartbeat does not cover is a message that is still waiting in + the client's queue -- bound that with `nats_max_ack_pending`. With the heartbeat switched off, + `nats_ack_wait` must exceed your p99 handler duration. +- **`nats_handler_timeout`** bounds a single run; set it above the longest legitimate run. - **`nats_max_ack_pending`** is the in-flight limit **across every replica sharing the consumer**, not per replica. Set it deliberately: it decides how many messages all replicas together work on at once. @@ -360,7 +365,7 @@ Delivery is at-least-once, permanently: a lost acknowledgement, a pod killed mid rolling deploy each produce a redelivery *after* the first attempt has committed its side effects. Two honest answers, and the framework will not choose for you: -- make the handlers safe to repeat (upsert rather than insert, key the outbound call on +- make the services the handlers call safe to repeat (upsert rather than insert, key the outbound call on `event.id`), or - set `idempotency_enabled = true` and `idempotency_ttl`. diff --git a/src/blueprint/agent_generator/docs/reference/api.md b/src/blueprint/agent_generator/docs/reference/api.md index 0a4baf1d..838ae82d 100644 --- a/src/blueprint/agent_generator/docs/reference/api.md +++ b/src/blueprint/agent_generator/docs/reference/api.md @@ -19,12 +19,12 @@ Fluent builder that assembles a FastAPI application from handlers, services, age ### Constructor ```python -AppBuilder(config: Config) +AppBuilder(config: Config | None = None) ``` | Parameter | Type | Description | |-----------|------|-------------| -| `config` | `Config` | Application configuration instance. | +| `config` | `Config \| None` | Optional. A declaration (`src/main.py`) passes none; `build(config)` takes it instead. | ### Methods @@ -32,28 +32,33 @@ AppBuilder(config: Config) |--------|---------|-------------| | `with_handler(handler, *, name=None)` | `AppBuilder` | Register an event handler. | | `with_service(service, *, name=None)` | `AppBuilder` | Register a service component. | -| `with_agent(agent, *, name=None)` | `AppBuilder` | Register an agent component. | +| `with_agent(agent, *, name=None)` | `AppBuilder` | Register an agent runtime: an unbuilt `AgentBuilder` (what `asbs` writes), a class or a factory. | | `with_rest_api(api, *, name=None)` | `AppBuilder` | Register a REST API controller. | | `with_scheduler(scheduler, *, name=None)` | `AppBuilder` | Register a scheduled task. | -| `with_cache(enabled=True, enable_locking=True)` | `AppBuilder` | Enable or configure the disk cache. | +| `with_cache(enabled=True, enable_locking=True, *, name="default")` | `AppBuilder` | Declare a cache; call again with another `name` for several. | | `with_health_checker(name, checker)` | `AppBuilder` | Add a named health-check probe. | -| `build()` | `FastAPI` | Finalize and return the configured FastAPI application. | +| `build(config=None)` | `FastAPI` | Construct everything declared and return the FastAPI application. Single use. | ### Usage ```python -config = Config() -app = ( - AppBuilder(config) +my_agent = AgentBuilder(runtime_name="my_agent").with_model_from_config().with_system_prompt("my_agent_system") + +agent = ( # src/main.py: a declaration + AppBuilder() .with_service(MyService) - .with_agent(MyAgent) + .with_agent(my_agent, name="my_agent") .with_handler(MyHandler) .with_rest_api(MyApi) .with_cache() - .build() ) + +app = agent.build(Config(settings_files=["settings.toml", ".secrets.toml"])) # what create_app() does ``` +Components are registered as **classes**: a group refuses an instance, because it would be +constructed before any namespace exists. + --- ## Config diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index adcc4fbc..939adb5b 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -56,6 +56,9 @@ Settings for the event bus transport layer. | `nats_heartbeat_enabled` | `bool` | `true` | Whether a running JetStream delivery reports `in_progress` every third of its consumer's `ack_wait`, so a run longer than `ack_wait` is not redelivered while it still runs. Switch it off only for an agent whose runs always finish well inside `ack_wait`; off, a long run is delivered again to another replica. Must be a boolean -- the string `"false"` is refused, because it would read as true. | | `nats_max_deliver` | `int` | unset -- the server's default (NATS: unlimited) | Delivery attempts before the message is dead-lettered. Unlimited -- the default, or `-1` -- means a permanently failing message is retried forever and never dead-lettered; the client logs a warning at startup if you set `-1` explicitly. Set a positive limit to bound retries. | | `nats_dead_letter_subject` | `str` | `".dead-letter"` | Subject a message is republished to when the framework gives up on it -- either a terminal failure (`InvalidEventError`, `CriticalHandlerError`, or a payload that is not a CloudEvent) or `nats_max_deliver` attempts spent. The original bytes are republished unchanged, with `Blueprint-Dead-Letter-Reason`, `Blueprint-Original-Subject`, `Blueprint-Delivery-Count` and `Blueprint-Event-Id` headers. Set to `""` to disable, which drops those messages and loses their payloads. Startup fails if the subject is a wildcard or is itself one of the subscribed subjects, since that would loop. | +| `nats_subscriptions` | `list[str]` | `[]` | Subjects the agent subscribes to in addition to the topics its handlers declare (`get_subscribed_topics()`), deduplicated, handler topics first. Agent scope. With a `nats_connection_source`, these are declared subjects like any other: the source decides per connection which it serves (`nats_unclaimed_subjects`). Not a list -- logged and ignored. | +| `nats_publish_mode` | `str` | unset -- follows `nats_use_jetstream` | `"core"` (fire-and-forget: reaches whoever is subscribed at that moment, not stored) or `"jetstream"` (stored in the stream; the subject must be one this client declares, see `nats_publish_subjects`). Separates publishing from durable consumption. Any other value fails startup. | +| `nats_publish_subjects` | `list[str]` | `[]` | Subjects this client may publish to besides those in `event_publishing.topic_mapping` -- for code that passes `topic=` to `publish_event` directly. Added to the stream's subjects so a JetStream publish is stored; wildcards are refused, because a wildcard published to is taken literally. | **NATS authentication:** `nats_user`/`nats_password`, `nats_token`, `nats_creds_file`, `nats_nkey_seed` and credentials inside `nats_url` are alternatives -- configure at most one. Two at once fail startup rather than leaving the choice to the client library. All of them are read per agent, so a group can give each agent its own account with `[default.]` or `DYNACONF___NATS_CREDS_FILE`. `/status/env` masks the secret keys, and the URL's credentials are stripped from logs, `/health` and `/status/env`. diff --git a/src/blueprint/agent_generator/docs/reference/models.md b/src/blueprint/agent_generator/docs/reference/models.md index 96c9fb42..f9d60557 100644 --- a/src/blueprint/agent_generator/docs/reference/models.md +++ b/src/blueprint/agent_generator/docs/reference/models.md @@ -48,6 +48,13 @@ Returned from event handlers to publish follow-up events. | `subject` | `str \| None` | `None` | Subject for the outbound event. | | `data` | `dict \| None` | `None` | Payload data for the outbound event. | | `metadata` | `dict \| None` | `None` | Additional metadata attached to the outbound event. | +| `skip_reason` | `str \| None` | `None` | Set by `HandlerResult.skipped(reason)`; a skipped result carries no `event_type`, `subject` or `data`. | + +`HandlerResult.skipped(reason, *, metadata=None)` is the result of a handler that is responsible for +the event but finds it needs nothing: the chain stops, nothing is published, the delivery is +acknowledged, the reason is logged at INFO and counted as `blueprint.events.skipped`. The run's +`ProcessingStatus` is `SKIPPED` (beside `PROCESSED` and `NO_HANDLER_FOUND`). `is_skipped` tells +the two kinds of result apart. --- From 00f3e5961667e0fad0a09b11b38bf8083aefc845 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 16:40:42 +0200 Subject: [PATCH 087/133] feat(cli): asbs validate checks the NATS delivery keys before startup does nats_max_concurrent_runs, nats_extra_runs_per_process, nats_handler_timeout, nats_connections_readiness, nats_unclaimed_subjects are parsed with the client's own rules; nats_connection_source is checked for its form and its module being found, without calling the factory. Co-Authored-By: Claude Opus 5 (1M context) --- .../agent_generator/cli/commands/validate.py | 65 ++++++++++++++++ .../cli/commands/test_validate_nats.py | 75 +++++++++++++++++++ 2 files changed, 140 insertions(+) create mode 100644 tests/unit/agent_generator/cli/commands/test_validate_nats.py diff --git a/src/blueprint/agent_generator/cli/commands/validate.py b/src/blueprint/agent_generator/cli/commands/validate.py index 3cf78c98..3b2e5bd9 100644 --- a/src/blueprint/agent_generator/cli/commands/validate.py +++ b/src/blueprint/agent_generator/cli/commands/validate.py @@ -1,5 +1,6 @@ """Validate command - check project structure and configuration.""" +import importlib.util import logging import re import sys @@ -8,6 +9,8 @@ from pathlib import Path from typing import Any +from blueprint.agents.clients.io.nats_client import CONNECTIONS_READINESS_MODES +from blueprint.agents.clients.io.nats_run_pool import RunLimit from blueprint.agents.component.namespace import validate_namespace from blueprint.agents.config import PROCESS_SCOPE_KEYS @@ -152,6 +155,9 @@ def run(args: Namespace) -> None: if swallowed: warnings.append(swallowed_cancellation_warning(project_dir.name, swallowed)) + # The NATS delivery keys: each of these fails startup when it is wrong, so say so here first. + issues.extend(_nats_findings(project_dir)) + # Group readiness: what this project must state before it can be hosted beside another # agent, and what would otherwise stay silent. group_issues, group_warnings, group_notices = _group_findings(project_dir) @@ -474,6 +480,65 @@ def _module_file(project_dir: Path, module_path: str) -> Path | None: return None +def _nats_findings(project_dir: Path) -> list[str]: + """Check the NATS delivery keys that would otherwise fail only at startup. + + The same parsers the client uses (``RunLimit.parse``, the readiness modes), so this command and + startup cannot disagree. ``nats_connection_source`` is checked for its form and for its module + being found -- without calling the factory: what the source returns (a binding without a + stream, for example) depends on the deployment's own data and is only known at startup. + """ + settings = _load_settings(project_dir / SETTINGS_FILE) + if settings is None: + return [] + issues: list[str] = [] + for key, minimum in (("nats_max_concurrent_runs", 1), ("nats_extra_runs_per_process", 0)): + try: + RunLimit.parse(key, _value_of(settings, key), minimum=minimum) + except ValueError as exc: + issues.append(str(exc)) + timeout = _value_of(settings, "nats_handler_timeout") + if timeout is not None and timeout != "": + if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or timeout <= 0: + issues.append(f"'nats_handler_timeout' must be a number of seconds above 0, got {timeout!r}. Unset it for no limit.") + readiness = _value_of(settings, "nats_connections_readiness") + if readiness is not None and str(readiness).strip().lower() not in CONNECTIONS_READINESS_MODES: + issues.append(f"'nats_connections_readiness' must be one of {', '.join(CONNECTIONS_READINESS_MODES)}, got {readiness!r}.") + unclaimed = _value_of(settings, "nats_unclaimed_subjects") + if unclaimed is not None and str(unclaimed).strip().lower() not in ("fail", "default_connection"): + issues.append(f"'nats_unclaimed_subjects' must be 'fail' or 'default_connection', got {unclaimed!r}.") + source = _value_of(settings, "nats_connection_source") + if source: + issue = _connection_source_issue(project_dir, str(source)) + if issue: + issues.append(issue) + return issues + + +def _connection_source_issue(project_dir: Path, path: str) -> str | None: + """Report a ``nats_connection_source`` that cannot be right, or ``None``. + + Finding the module imports its parent packages, as the import at startup would; the module + itself is not executed and the factory not called. + """ + module_path, _, attribute = path.strip().partition(":") + if not module_path or not attribute: + return f"'nats_connection_source' is {path!r}; write it as 'package.module:attribute', naming the factory." + added = str(project_dir) not in sys.path + if added: + sys.path.insert(0, str(project_dir)) + try: + found = importlib.util.find_spec(module_path) is not None + except (ImportError, ValueError) as exc: + return f"'nats_connection_source': '{module_path}' cannot be found: {exc}" + finally: + if added: + sys.path.remove(str(project_dir)) + if not found: + return f"'nats_connection_source': no module '{module_path}' on the project's path; startup would fail." + return None + + def _load_settings(settings_file: Path) -> dict[str, Any] | None: """Parse a settings file, or ``None`` when there is nothing readable to parse. diff --git a/tests/unit/agent_generator/cli/commands/test_validate_nats.py b/tests/unit/agent_generator/cli/commands/test_validate_nats.py new file mode 100644 index 00000000..e9da4d5e --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_validate_nats.py @@ -0,0 +1,75 @@ +"""``asbs validate`` reports the NATS delivery keys that would otherwise fail only at startup.""" + +from pathlib import Path + +import pytest + +from blueprint.agent_generator.cli.commands.validate import _nats_findings + + +def _project(tmp_path: Path, settings: str) -> Path: + (tmp_path / "settings.toml").write_text(settings, encoding="utf-8") + return tmp_path + + +class TestNatsFindings: + def test_a_project_without_the_keys_has_no_findings(self, tmp_path: Path) -> None: + assert _nats_findings(_project(tmp_path, '[default]\napp_name = "x"\n')) == [] + + def test_no_settings_file_has_no_findings(self, tmp_path: Path) -> None: + assert _nats_findings(tmp_path) == [] + + @pytest.mark.parametrize( + "line", + [ + "nats_max_concurrent_runs = 4", + 'nats_max_concurrent_runs = "25%"', + "nats_extra_runs_per_process = 0", + "nats_handler_timeout = 30.5", + 'nats_connections_readiness = "any"', + 'nats_unclaimed_subjects = "default_connection"', + ], + ) + def test_valid_values_pass(self, tmp_path: Path, line: str) -> None: + assert _nats_findings(_project(tmp_path, f"[default]\n{line}\n")) == [] + + @pytest.mark.parametrize( + ("line", "named"), + [ + ("nats_max_concurrent_runs = 0", "nats_max_concurrent_runs"), + ('nats_max_concurrent_runs = "150%"', "nats_max_concurrent_runs"), + ("nats_extra_runs_per_process = -1", "nats_extra_runs_per_process"), + ("nats_handler_timeout = 0", "nats_handler_timeout"), + ('nats_handler_timeout = "soon"', "nats_handler_timeout"), + ('nats_connections_readiness = "some"', "nats_connections_readiness"), + ('nats_unclaimed_subjects = "drop"', "nats_unclaimed_subjects"), + ], + ) + def test_a_value_startup_would_refuse_is_an_issue_naming_the_key(self, tmp_path: Path, line: str, named: str) -> None: + """The same rule as the client's parser, so this command and startup cannot disagree.""" + findings = _nats_findings(_project(tmp_path, f"[default]\n{line}\n")) + assert len(findings) == 1 + assert named in findings[0] + + def test_a_key_in_an_agent_section_is_checked_too(self, tmp_path: Path) -> None: + findings = _nats_findings(_project(tmp_path, "[orders]\nnats_max_concurrent_runs = 0\n")) + assert findings and "nats_max_concurrent_runs" in findings[0] + + +class TestConnectionSource: + def test_a_path_without_an_attribute_is_an_issue(self, tmp_path: Path) -> None: + findings = _nats_findings(_project(tmp_path, '[default]\nnats_connection_source = "deploy.sources"\n')) + assert findings and "package.module:attribute" in findings[0] + + def test_a_module_that_does_not_exist_is_an_issue(self, tmp_path: Path) -> None: + findings = _nats_findings(_project(tmp_path, '[default]\nnats_connection_source = "no_such_pkg_x1.sources:make"\n')) + assert findings and "no_such_pkg_x1" in findings[0] + + def test_a_module_in_the_project_is_found_without_being_executed(self, tmp_path: Path) -> None: + """Only found, never run: the factory reads deployment data that may not exist here.""" + package = tmp_path / "deploy_src_y2" + package.mkdir() + (package / "__init__.py").write_text("", encoding="utf-8") + (package / "sources.py").write_text("raise RuntimeError('executed')\n", encoding="utf-8") + findings = _nats_findings(_project(tmp_path, '[default]\nnats_connection_source = "deploy_src_y2.sources:make"\n')) + assert findings == [] From e7496f0c94c2be1fa75872b85cb578d6227d4d68 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 16:48:20 +0200 Subject: [PATCH 088/133] refactor(examples): main.py is a declaration with create_app(), as the template writes it Every example now declares `agent = AppBuilder()...` with components as classes and an unbuilt AgentBuilder, and builds it in create_app(); the READMEs run `uvicorn src.main:create_app --factory`. Started each once: live 200 for all five, ready on inventory_api, health_monitor and webhook_relay (against a real NATS broker); not ready without a Dapr sidecar (order_event_pipeline) or a model key (document_summarizer). Co-Authored-By: Claude Opus 5 (1M context) --- examples/document_summarizer/README.md | 2 +- examples/document_summarizer/src/main.py | 41 +++++++++++++---------- examples/health_monitor/README.md | 2 +- examples/health_monitor/src/main.py | 28 +++++++++++----- examples/inventory_api/README.md | 2 +- examples/inventory_api/src/main.py | 17 ++++++++-- examples/order_event_pipeline/README.md | 4 +-- examples/order_event_pipeline/src/main.py | 26 +++++++++----- examples/webhook_relay/README.md | 4 +-- examples/webhook_relay/src/main.py | 31 ++++++++--------- 10 files changed, 98 insertions(+), 59 deletions(-) diff --git a/examples/document_summarizer/README.md b/examples/document_summarizer/README.md index 575bf8de..d7fa85df 100644 --- a/examples/document_summarizer/README.md +++ b/examples/document_summarizer/README.md @@ -33,7 +33,7 @@ model_api_key = "sk-your-actual-openai-api-key" 3. Run the service: ```bash -uvicorn src.main:app --host 0.0.0.0 --port 8000 +uvicorn src.main:create_app --factory --host 0.0.0.0 --port 8000 ``` ## API Usage diff --git a/examples/document_summarizer/src/main.py b/examples/document_summarizer/src/main.py index b42c4dad..fc81c522 100644 --- a/examples/document_summarizer/src/main.py +++ b/examples/document_summarizer/src/main.py @@ -1,26 +1,23 @@ -"""Application entry point for the document summarizer service.""" +"""Declaration of the document summarizer agent. + +``agent`` records what the agent is made of; nothing is constructed until it is built. +``create_app()`` builds it as an application of its own:: + + uvicorn src.main:create_app --factory +""" from pathlib import Path from pydantic_ai import Tool -from blueprint.agents import AppBuilder, AgentBuilder, Config +from blueprint.agents import AgentBuilder, AppBuilder, Config +from src.api.routes import SummarizerApi from src.models.schemas import DocumentSummary from src.services.summarizer_service import SummarizerService -from src.api.routes import SummarizerApi -from src.tools.text_tools import word_count, extract_metadata - -config = Config( - settings_files=["settings.toml", "secrets.toml"], - root_path=str(Path(__file__).parent.parent), -) +from src.tools.text_tools import extract_metadata, word_count -agent = ( - AgentBuilder( - config, - runtime_name="document_summarizer", - package_root=Path(__file__).parent, - ) +document_summarizer = ( + AgentBuilder(runtime_name="document_summarizer", package_root=Path(__file__).parent) .with_model_from_config() .with_system_prompt("system") .with_tools( @@ -30,7 +27,17 @@ ] ) .with_result_type(DocumentSummary) - .build() ) -app = AppBuilder(config).with_agent(agent).with_service(SummarizerService).with_rest_api(SummarizerApi()).with_cache().build() +agent = ( + AppBuilder() + .with_service(SummarizerService) + .with_agent(document_summarizer, name="document_summarizer") + .with_rest_api(SummarizerApi) + .with_cache() +) + + +def create_app(): + """Build this agent as an application of its own.""" + return agent.build(Config(settings_files=["settings.toml", "secrets.toml"], root_path=str(Path(__file__).parent.parent))) diff --git a/examples/health_monitor/README.md b/examples/health_monitor/README.md index 338ea4c9..43e82ed4 100644 --- a/examples/health_monitor/README.md +++ b/examples/health_monitor/README.md @@ -28,7 +28,7 @@ asbs dev Or directly with uvicorn: ```bash -uvicorn src.main:app --reload +uvicorn src.main:create_app --factory --reload ``` The API will be available at `http://localhost:8000`. Interactive docs at `http://localhost:8000/docs`. diff --git a/examples/health_monitor/src/main.py b/examples/health_monitor/src/main.py index 289309c4..5985c5a5 100644 --- a/examples/health_monitor/src/main.py +++ b/examples/health_monitor/src/main.py @@ -1,4 +1,12 @@ -"""Application entry point for the Health Monitor.""" +"""Declaration of the Health Monitor agent. + +``agent`` records what the agent is made of; nothing is constructed until it is built. +``create_app()`` builds it as an application of its own:: + + uvicorn src.main:create_app --factory +""" + +from pathlib import Path from blueprint.agents import AppBuilder, Config @@ -7,14 +15,16 @@ from src.schedulers.report_scheduler import ReportScheduler from src.services.monitor_service import MonitorService -config = Config(settings_files=["settings.toml"]) - -app = ( - AppBuilder(config) +agent = ( + AppBuilder() .with_service(MonitorService) - .with_rest_api(MonitorApi()) - .with_scheduler(HealthCheckScheduler()) - .with_scheduler(ReportScheduler()) + .with_rest_api(MonitorApi) + .with_scheduler(HealthCheckScheduler) + .with_scheduler(ReportScheduler) .with_cache() - .build() ) + + +def create_app(): + """Build this agent as an application of its own.""" + return agent.build(Config(settings_files=["settings.toml"], root_path=str(Path(__file__).parent.parent))) diff --git a/examples/inventory_api/README.md b/examples/inventory_api/README.md index edbea898..e684c6fe 100644 --- a/examples/inventory_api/README.md +++ b/examples/inventory_api/README.md @@ -27,7 +27,7 @@ asbs dev Or directly with uvicorn: ```bash -uvicorn src.main:app --reload +uvicorn src.main:create_app --factory --reload ``` The API will be available at `http://localhost:8000`. Interactive docs at `http://localhost:8000/docs`. diff --git a/examples/inventory_api/src/main.py b/examples/inventory_api/src/main.py index 4bceca34..cb8ead94 100644 --- a/examples/inventory_api/src/main.py +++ b/examples/inventory_api/src/main.py @@ -1,10 +1,21 @@ -"""Application entry point for the Inventory API.""" +"""Declaration of the Inventory API agent. + +``agent`` records what the agent is made of; nothing is constructed until it is built. +``create_app()`` builds it as an application of its own:: + + uvicorn src.main:create_app --factory +""" + +from pathlib import Path from blueprint.agents import AppBuilder, Config from src.api.routes import InventoryApi from src.services.inventory_service import InventoryService -config = Config(settings_files=["settings.toml"]) +agent = AppBuilder().with_service(InventoryService).with_rest_api(InventoryApi).with_cache() + -app = AppBuilder(config).with_service(InventoryService).with_rest_api(InventoryApi()).with_cache().build() +def create_app(): + """Build this agent as an application of its own.""" + return agent.build(Config(settings_files=["settings.toml"], root_path=str(Path(__file__).parent.parent))) diff --git a/examples/order_event_pipeline/README.md b/examples/order_event_pipeline/README.md index 0cde1d59..15973816 100644 --- a/examples/order_event_pipeline/README.md +++ b/examples/order_event_pipeline/README.md @@ -52,7 +52,7 @@ order_event_pipeline/ ### With Dapr ```bash -dapr run --app-id order-pipeline --app-port 8000 -- uvicorn src.main:app --host 0.0.0.0 --port 8000 +dapr run --app-id order-pipeline --app-port 8000 -- uvicorn src.main:create_app --factory --host 0.0.0.0 --port 8000 ``` ### Without Dapr (development mode) @@ -60,7 +60,7 @@ dapr run --app-id order-pipeline --app-port 8000 -- uvicorn src.main:app --host Set `event_bus = ""` in `settings.toml` to disable Dapr integration, then run: ```bash -uvicorn src.main:app --host 0.0.0.0 --port 8000 --reload +uvicorn src.main:create_app --factory --host 0.0.0.0 --port 8000 --reload ``` The handler chain still processes events submitted via the REST API, but no diff --git a/examples/order_event_pipeline/src/main.py b/examples/order_event_pipeline/src/main.py index c392f2fc..d0940d9d 100644 --- a/examples/order_event_pipeline/src/main.py +++ b/examples/order_event_pipeline/src/main.py @@ -1,20 +1,30 @@ -"""Application entry point for the Order Event Pipeline.""" +"""Declaration of the Order Event Pipeline agent. + +``agent`` records what the agent is made of; nothing is constructed until it is built. +``create_app()`` builds it as an application of its own:: + + uvicorn src.main:create_app --factory +""" + +from pathlib import Path from blueprint.agents import AppBuilder, Config -from .handlers.order_validation_handler import OrderValidationHandler +from .api.routes import OrderApi from .handlers.order_enrichment_handler import OrderEnrichmentHandler +from .handlers.order_validation_handler import OrderValidationHandler from .services.order_service import OrderService -from .api.routes import OrderApi - -config = Config(settings_files=["settings.toml"]) -app = ( - AppBuilder(config) +agent = ( + AppBuilder() .with_service(OrderService) .with_handler(OrderValidationHandler) .with_handler(OrderEnrichmentHandler) .with_rest_api(OrderApi) .with_cache() - .build() ) + + +def create_app(): + """Build this agent as an application of its own.""" + return agent.build(Config(settings_files=["settings.toml"], root_path=str(Path(__file__).parent.parent))) diff --git a/examples/webhook_relay/README.md b/examples/webhook_relay/README.md index 6d0f44e2..1a3f1a0c 100644 --- a/examples/webhook_relay/README.md +++ b/examples/webhook_relay/README.md @@ -69,14 +69,14 @@ nats_url = "nats://localhost:4222" ```bash pip install -e . - uvicorn src.main:app --host 0.0.0.0 --port 8000 --reload + uvicorn src.main:create_app --factory --host 0.0.0.0 --port 8000 --reload ``` ### Without NATS (handlers still execute, publishing is a no-op) ```bash pip install -e . -uvicorn src.main:app --host 0.0.0.0 --port 8000 --reload +uvicorn src.main:create_app --factory --host 0.0.0.0 --port 8000 --reload ``` The handler chain processes events locally. Published events will log a warning diff --git a/examples/webhook_relay/src/main.py b/examples/webhook_relay/src/main.py index 74981b54..7c171126 100644 --- a/examples/webhook_relay/src/main.py +++ b/examples/webhook_relay/src/main.py @@ -1,4 +1,10 @@ -"""Application entry point -- wires all components via AppBuilder.""" +"""Declaration of the webhook relay agent. + +``agent`` records what the agent is made of; nothing is constructed until it is built. +``create_app()`` builds it as an application of its own, with the settings next to ``src/``:: + + uvicorn src.main:create_app --factory +""" from __future__ import annotations @@ -12,26 +18,21 @@ from .handlers.webhook_normalizer import WebhookNormalizer from .services.webhook_service import WebhookService -# Load settings relative to this file so `uvicorn src.main:app` works from -# the example directory. -_HERE = Path(__file__).resolve().parent.parent - -config = Config( - settings_files=["settings.toml"], - root_path=str(_HERE), -) - -app = ( - AppBuilder(config) +agent = ( + AppBuilder() + # Business service + .with_service(WebhookService) # Handler chain -- priority determines execution order (low first) .with_handler(WebhookNormalizer) # priority 5 -- normalize .with_handler(ContentFilter) # priority 10 -- filter .with_handler(MetadataEnricher) # priority 15 -- enrich & publish - # Business service - .with_service(WebhookService) # REST API .with_rest_api(WebhookApi) # Persistent cache for dedup and recent-event tracking .with_cache() - .build() ) + + +def create_app(): + """Build this agent as an application of its own.""" + return agent.build(Config(settings_files=["settings.toml"], root_path=str(Path(__file__).resolve().parent.parent))) From c8aee09a7c16d35af7fc48a3a4908e15f83d98f9 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 16:52:37 +0200 Subject: [PATCH 089/133] docs(plans): step 6 inventory; AgentBuilder reference and the testing guide's router The inventory lists every place step 6 checked, what changed, what ran and what is still open (named-connection example, example handlers, spec 7.2 WARNING, untracked specs). Co-Authored-By: Claude Opus 5 (1M context) --- ...10-15-named-connections-step6-inventory.md | 70 +++++++++++++++++++ .../agent_generator/docs/guides/testing.md | 4 +- .../agent_generator/docs/reference/api.md | 16 +++-- 3 files changed, 81 insertions(+), 9 deletions(-) create mode 100644 docs/plans/2026-10-15-named-connections-step6-inventory.md diff --git a/docs/plans/2026-10-15-named-connections-step6-inventory.md b/docs/plans/2026-10-15-named-connections-step6-inventory.md new file mode 100644 index 00000000..78c164db --- /dev/null +++ b/docs/plans/2026-10-15-named-connections-step6-inventory.md @@ -0,0 +1,70 @@ +# Named connections, step 6 -- inventory + +Acceptance record for step 6 of `2026-10-14-named-connections.md`: every place checked, what was +changed or why nothing was, and what is still open. Checked against the code on +`feature/multi-agent-namespaces` (2026-10-15). "Read" = compared with the code; "run" = executed. + +## Changed + +| Place | Finding | Change | +|---|---|---| +| `agent_generator/claude_docs/CLAUDE.md` | built `AgentRuntime` + `AppBuilder(config).build()` in "Wiring" (W1); handler example with two-step logic; no handler rules | template declaration with `create_app()`; rules 7-10 (routing on the envelope, one service call, relevance in the service, no LLM in handlers, no run state on `self`); `HandlerResult.skipped`; `context["runtime"]` (W9); `models/` split (W11) | +| `claude_docs/agents/blueprint-builder.md` | scheduler without `super().on_startup()` (W4); built `AgentBuilder(config)...build(name=)` (W1) | fixed; handler pattern and rules 9 and 13 | +| `claude_docs/agents/blueprint-architect.md` | no rule on service entry points or LLM placement | two rules added | +| `claude_docs/skills/blueprint-events`, `add-component` | `None` described as "not mine, or nothing to publish"; handler/agent/scheduler guidance | return values incl. `skipped`; handler rules; scheduler `super()` | +| `base_files/src/handlers/handler.txt` | "This is where the main business logic is implemented" (W7); idempotency comment asks for logic in the handler (W8) | docstrings and comment put the decision in the service | +| `docs/components/event-handlers.md` | `HandlerResult` "does not stop subsequent handlers" (W2); tenant example in the context-key section; instance registration | chain semantics table; context keys per D10 incl. `nats_connection`; classes only; full example with DTO and `skipped` | +| `docs/concepts/event-processing.md` | sync `can_handle_event(event)`, `priority = 1`, "any other value is available to the next handler" | rewritten against `_dispatch`; table per return value | +| `docs/concepts/architecture.md` | `with_agent("name", Cls)`, `register_routes`, `execute()`, `priority = 10` (W3) | rewritten; startup order checked against `app_builder.py:1648-1684` (unchanged, correct) | +| `docs/components/agents.md`, `rest-apis.md`, `schedulers.md`, `services.md`, `concepts/caching.md`, `concepts/configuration.md`, `getting-started.md` | `AppBuilder(config)...build()`, instances, `.with_config()`/`.with_api()`/`with_name()` (W1); wrong import paths in `agents.md` | declaration form; imports fixed | +| `docs/reference/api.md` | `AppBuilder(config: Config)`, `AgentBuilder(config, ...)` required | optional config, `build(config=None)` for both | +| `docs/reference/models.md`, `concepts/observability.md` | -- | `skip_reason`, `ProcessingStatus.SKIPPED`, `blueprint.events.skipped` | +| `docs/reference/configuration-keys.md` | `nats_subscriptions`, `nats_publish_mode`, `nats_publish_subjects` read by the code, documented nowhere | rows added; every other `nats_*` key in the code is present (diffed) | +| `docs/guides/deployment.md` | "never exercised against a real broker"; ack_wait rule ignored the heartbeat | banner states what `tests/integration` covers; skipped/timeout dispositions; heartbeat | +| `docs/guides/testing.md` | `api.register_routes(app.router)` -- no such method | `app.include_router(api.router)` | +| `docs/specs/2026-08-28-multi-agent-grouping.md` | sec. 5.2 defaults 300 / 16 / 5 the code does not apply; sec. 7.3 without the heartbeat | corrected; new keys listed; sec. 7.2 gains the skip | +| `README.md` | -- (already the declaration) | feature line for concurrency / named connections; component table | +| `examples/*/src/main.py` + READMEs | module-level `app = AppBuilder(config)...build()`, instances | declaration + `create_app()`; `uvicorn src.main:create_app --factory` | +| `asbs validate` | no check of the new keys | `_nats_findings` (step-6 item "asbs validate checks for the new keys") | + +## Checked, unchanged + +- **W5**: already fixed by `519566f` (the second `CLAUDE.md` was removed). +- `AGENTS.md`, `CLAUDE.md` (repository): no statement about delivery, handlers or `main.py` that + disagrees with the code. +- `docs/guides/multi-agent-setup.md`, `multi-agent-migration.md`: already show the declaration; + the migration guide shows the old form deliberately as "before". +- `claude_docs/skills/blueprint-config`, `-deployment`, `-multi-agent`, `-troubleshooting`, + `-testing`, `-cli`, `-migration`, `new-agent-service`: grepped for main.py patterns, chain + semantics and NATS delivery claims; nothing found that disagrees. Not read line by line. + +## Run + +- Unit suite: 3588 passed, 1 skipped (was 3553 before step 6). +- `tests/integration/test_skipped_result.py` + `test_event_path.py` against `nats:2.10-alpine` + (throwaway container, port 14222): 8 passed. Control on the unchanged code: a `None` from the only + handler logs "No handler processed event" at WARNING. +- `asbs setup` + `asbs create handler` + `asbs validate` on a scratch project: the scaffold carries + the new handler docstrings, validates clean, and `nats_max_concurrent_runs = 0` is reported. +- Every example started once (`uvicorn src.main:create_app --factory`, Windows host, NATS in WSL + Docker): `/health/live` 200 for all five; `/health/ready` 200 for `inventory_api`, + `health_monitor` and `webhook_relay` (connected to the broker); 503 for `order_event_pipeline` + (no Dapr sidecar) and `document_summarizer` (no model key) -- both expected. Each example's own + tests and `tests/unit/examples`: green. +- Grep for removed APIs (`with_config(`, `with_api(`, `with_prompt_file`, `register_routes(`, + `with_agent("name", Cls)`, `AgentBuilder(config` in docs): only plans and changelogs remain. + +## Open + +- **A named-connection example** (`order_event_pipeline` or a new one with a source and two + connections) is not written. +- **The examples' handlers do not follow the new handler rules:** `webhook_relay`'s three handlers + hold the logic themselves, `order_event_pipeline`'s call two service methods each. Only `main.py` + was changed. +- **Spec sec. 7.2 vs code:** the spec says an unmatched event MUST NOT be logged at WARNING; + `HandlerChain._dispatch` logs "No handler processed event" at WARNING. Kept, as decided with D11 + ("no handler at all keeps the WARNING") -- one of the two should change. +- **Not checked:** the untracked specs `2026-09-23-dynamic-subscriptions.md`, + `2026-09-24-handler-time-bounds.md` (sec. 4.5) and `2026-09-25-config-key-registry.md` (not in the + repository); ADRs (owned outside the repository); `asbs docs` output beyond the files above. +- The examples were started on the Windows host against a broker in WSL, not inside WSL. diff --git a/src/blueprint/agent_generator/docs/guides/testing.md b/src/blueprint/agent_generator/docs/guides/testing.md index 71b65bb3..e87728f0 100644 --- a/src/blueprint/agent_generator/docs/guides/testing.md +++ b/src/blueprint/agent_generator/docs/guides/testing.md @@ -196,9 +196,9 @@ class TestProductCatalogApi: def app(self, mock_registry): """Create a FastAPI app with the API routes registered.""" app = FastAPI() - api = ProductCatalogApi() + api = ProductCatalogApi() # wires its decorated routes on construction api.registry = mock_registry - api.register_routes(app.router) + app.include_router(api.router) return app @pytest.fixture diff --git a/src/blueprint/agent_generator/docs/reference/api.md b/src/blueprint/agent_generator/docs/reference/api.md index 838ae82d..8904f7f0 100644 --- a/src/blueprint/agent_generator/docs/reference/api.md +++ b/src/blueprint/agent_generator/docs/reference/api.md @@ -103,12 +103,12 @@ Fluent builder for constructing an `AgentRuntime` instance with a model, prompts ### Constructor ```python -AgentBuilder(config, runtime_name="default", meter=None, package_root=None) +AgentBuilder(config=None, runtime_name="default", meter=None, package_root=None) ``` | Parameter | Type | Default | Description | |-----------|------|---------|-------------| -| `config` | `Config` | -- | Application configuration instance. | +| `config` | `Config \| None` | `None` | Optional. A declaration in `main.py` passes none; the host's `AppBuilder.build()` supplies it. | | `runtime_name` | `str` | `"default"` | Name of the runtime configuration section to use. | | `meter` | `Meter \| None` | `None` | OpenTelemetry meter for recording metrics. | | `package_root` | `Path \| None` | `None` | Root path for locating prompt files. | @@ -124,7 +124,7 @@ AgentBuilder(config, runtime_name="default", meter=None, package_root=None) | `with_result_type(result_type: type[BaseModel])` | `AgentBuilder` | Set the structured result type (Pydantic model). | | `with_deps_type(deps_type)` | `AgentBuilder` | Set the dependency-injection type for the agent. | | `with_metrics(enabled=True)` | `AgentBuilder` | Enable or disable automatic metrics recording. | -| `build(**kwargs)` | `AgentRuntime` | Build and return the configured `AgentRuntime`. | +| `build(config=None, **kwargs)` | `AgentRuntime` | Build and return the `AgentRuntime`. In an application `AppBuilder.build()` calls it; call it yourself only in a script or a test. | ### Static Methods @@ -136,14 +136,16 @@ AgentBuilder(config, runtime_name="default", meter=None, package_root=None) ### Usage ```python -agent = ( - AgentBuilder(config, runtime_name="default") +my_agent = ( # declared in main.py, not built + AgentBuilder(runtime_name="my_agent") .with_model_from_config() - .with_system_prompt() + .with_system_prompt("my_agent_system") .with_tools([my_tool]) .with_metrics() - .build() ) +# AppBuilder()...with_agent(my_agent, name="my_agent") + +runtime = my_agent.build(config) # only outside an application: a script or a test ``` --- From f72c84a5b0ada34f797aa188ff1db165b94d1bb5 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 17:23:24 +0200 Subject: [PATCH 090/133] refactor(examples): webhook_relay -- one handler translates, WebhookService.relay decides The three chained handlers held the logic themselves (dedup, filtering, enrichment, scoring) and passed state through context. Now one WebhookHandler routes webhook.received on the envelope (and declares it via get_handled_event_types), maps the WebhookPayload DTO to an IncomingWebhook domain value and calls WebhookService.relay() once; a duplicate comes back as HandlerResult.skipped. Models split into DTO (schemas.py) and domain (domain.py). The API resolves its services in on_startup and no longer reads a .data the ProcessingResult does not have. Co-Authored-By: Claude Opus 5 (1M context) --- examples/webhook_relay/README.md | 43 ++-- examples/webhook_relay/src/api/routes.py | 19 +- .../src/handlers/content_filter.py | 68 ------ .../src/handlers/metadata_enricher.py | 79 ------ .../src/handlers/webhook_handler.py | 51 ++++ .../src/handlers/webhook_normalizer.py | 63 ----- examples/webhook_relay/src/main.py | 12 +- examples/webhook_relay/src/models/domain.py | 44 ++++ examples/webhook_relay/src/models/schemas.py | 29 +-- .../src/services/webhook_service.py | 81 +++++- examples/webhook_relay/tests/test_handlers.py | 231 ++++-------------- .../tests/test_webhook_service.py | 63 ++++- 12 files changed, 312 insertions(+), 471 deletions(-) delete mode 100644 examples/webhook_relay/src/handlers/content_filter.py delete mode 100644 examples/webhook_relay/src/handlers/metadata_enricher.py create mode 100644 examples/webhook_relay/src/handlers/webhook_handler.py delete mode 100644 examples/webhook_relay/src/handlers/webhook_normalizer.py create mode 100644 examples/webhook_relay/src/models/domain.py diff --git a/examples/webhook_relay/README.md b/examples/webhook_relay/README.md index 1a3f1a0c..955770e7 100644 --- a/examples/webhook_relay/README.md +++ b/examples/webhook_relay/README.md @@ -8,18 +8,18 @@ events over NATS. ## Architecture -The processing pipeline is built as a **handler chain** with three stages: +One handler, one service -- the shape every Blueprint agent follows: -| Priority | Handler | Responsibility | -|----------|----------------------|-----------------------------------------------------| -| 5 | WebhookNormalizer | Parse raw payload, deduplicate, normalize structure | -| 10 | ContentFilter | Drop bot events, test events, and other noise | -| 15 | MetadataEnricher | Add priority scores, timestamps, publish final event | +| Component | Responsibility | +|---|---| +| `WebhookHandler` | Routes `webhook.received` (envelope only), extracts the `WebhookPayload` DTO, turns it into an `IncomingWebhook` domain value and calls `WebhookService.relay()` **once**. Translates the answer into a result. | +| `WebhookService.relay()` | Every decision: duplicate? (cache), normalise per source, content filter (GitHub bots, Stripe test events), enrich (priority score, timestamp), record for dedup and the recent list. | -Lower priority numbers execute first. Each handler can: +The handler's results: -- Return `None` to pass the event to the next handler in the chain. -- Return a `HandlerResult` to publish an event and stop processing. +- `HandlerResult(event_type="webhook.processed", ...)` -- relayed and enriched. +- `HandlerResult(event_type="webhook.filtered", ...)` -- dropped by a content rule, with the reason. +- `HandlerResult.skipped(reason)` -- a duplicate: nothing to do, acknowledged, logged at INFO. ## Event Flow @@ -27,17 +27,11 @@ Lower priority numbers execute first. Each handler can: POST /api/webhooks | v -[webhook.received] --> WebhookNormalizer (5) - | - v (stores normalized_event in context) - ContentFilter (10) - | - v (filters bots / test events) - MetadataEnricher (15) - | - v - [webhook.processed] --> NATS topic: webhooks-processed - [webhook.filtered] --> NATS topic: webhooks-filtered +[webhook.received] --> WebhookHandler --> WebhookService.relay() + | + duplicate <--------------+--> filtered -> [webhook.filtered] -> webhooks-filtered + (skipped) | + +--> processed -> [webhook.processed] -> webhooks-processed ``` ## NATS Configuration @@ -79,7 +73,7 @@ pip install -e . uvicorn src.main:create_app --factory --host 0.0.0.0 --port 8000 --reload ``` -The handler chain processes events locally. Published events will log a warning +The handler and service process events locally. Published events will log a warning if NATS is unreachable but will not crash the service. ### Testing the endpoint @@ -124,11 +118,10 @@ webhook_relay/ src/ main.py # AppBuilder wiring models/ - schemas.py # Pydantic models + schemas.py # DTO: WebhookPayload (REST body and event data) + domain.py # Domain: IncomingWebhook, NormalizedEvent, RelayOutcome handlers/ - webhook_normalizer.py - content_filter.py - metadata_enricher.py + webhook_handler.py # webhook.received -> WebhookService.relay() services/ webhook_service.py # Business logic and caching api/ diff --git a/examples/webhook_relay/src/api/routes.py b/examples/webhook_relay/src/api/routes.py index d0b9514d..98f0d511 100644 --- a/examples/webhook_relay/src/api/routes.py +++ b/examples/webhook_relay/src/api/routes.py @@ -28,7 +28,9 @@ def __init__(self) -> None: super().__init__() async def on_startup(self) -> None: - """No API-specific startup needed.""" + """Resolve the services this API delegates to.""" + self._events = self.registry.get_service(EventProcessingService) + self._webhooks = self.registry.get_service(WebhookService) async def on_shutdown(self) -> None: """No API-specific shutdown needed.""" @@ -52,18 +54,16 @@ async def receive_webhook(self, payload: WebhookPayload, request: Request) -> JS data=payload.model_dump(), ) - event_processing: EventProcessingService = self.registry.get_service( - EventProcessingService, - ) - - result_event = await event_processing.process_event(cloud_event) + processing = await self._events.process_event(cloud_event) + results = [result.data for result in processing.result if result.data is not None] return JSONResponse( status_code=202, content={ - "status": "accepted", + "status": processing.status.value, "webhook_id": webhook_id, - "result": result_event.data if result_event else None, + "message": processing.message, + "result": results[0] if results else None, }, ) @@ -74,8 +74,7 @@ async def receive_webhook(self, payload: WebhookPayload, request: Request) -> JS ) async def list_recent(self) -> JSONResponse: """Return recently processed webhooks from the cache.""" - webhook_service: WebhookService = self.registry.get_service(WebhookService) - recent = webhook_service.get_recent(limit=20) + recent = self._webhooks.get_recent(limit=20) return JSONResponse( status_code=200, content={"count": len(recent), "webhooks": recent}, diff --git a/examples/webhook_relay/src/handlers/content_filter.py b/examples/webhook_relay/src/handlers/content_filter.py deleted file mode 100644 index 3a7c54ef..00000000 --- a/examples/webhook_relay/src/handlers/content_filter.py +++ /dev/null @@ -1,68 +0,0 @@ -"""Handler that filters out unwanted webhook events (priority 10).""" - -from __future__ import annotations - -import logging -from typing import Any - -from blueprint.agents.handler.event_handler_base import EventHandlerBase -from blueprint.agents.models.events import GenericCloudEvent, HandlerResult - -logger = logging.getLogger(__name__) - - -class ContentFilter(EventHandlerBase): - """Drop bot-generated and test events. - - Filtering rules: - - GitHub: actor containing ``[bot]`` is discarded. - - Stripe: event_category starting with ``test_`` is discarded. - - When an event is filtered a ``webhook.filtered`` result is returned so it - can be published to the filtered-events topic. If the event passes, the - handler returns ``None`` to continue the chain. - """ - - def __init__(self) -> None: - super().__init__(priority=10) - - async def on_startup(self) -> None: - """No handler-specific startup needed.""" - - async def on_shutdown(self) -> None: - """No handler-specific shutdown needed.""" - - async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: - return event.type == "webhook.received" - - async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None: - normalized = context.get("normalized_event", event.data) - webhook_id = context.get("webhook_id", event.id) - - actor = normalized.get("actor") or "" - event_category = normalized.get("event_category", "") - original_source = normalized.get("original_source", "") - - # GitHub bot filter - if original_source == "github" and "[bot]" in actor: - reason = f"Filtered GitHub bot event from {actor}" - logger.info(reason) - return HandlerResult( - event_type="webhook.filtered", - data={"reason": reason, "webhook_id": webhook_id}, - ) - - # Stripe test-event filter - if original_source == "stripe" and event_category.startswith("test_"): - reason = f"Filtered Stripe test event: {event_category}" - logger.info(reason) - return HandlerResult( - event_type="webhook.filtered", - data={"reason": reason, "webhook_id": webhook_id}, - ) - - # Event is allowed -- pass to next handler - return None - - def get_published_event_types(self) -> tuple[str, str] | None: - return ("webhook.filtered", "webhook.filtered.error") diff --git a/examples/webhook_relay/src/handlers/metadata_enricher.py b/examples/webhook_relay/src/handlers/metadata_enricher.py deleted file mode 100644 index c186fc3f..00000000 --- a/examples/webhook_relay/src/handlers/metadata_enricher.py +++ /dev/null @@ -1,79 +0,0 @@ -"""Handler that enriches and publishes the final event (priority 15).""" - -from __future__ import annotations - -import logging -from datetime import UTC, datetime -from typing import Any - -from blueprint.agents.handler.event_handler_base import EventHandlerBase -from blueprint.agents.models.events import GenericCloudEvent, HandlerResult - -from ..services.webhook_service import WebhookService - -logger = logging.getLogger(__name__) - -# Simple priority scoring by event category keyword. -_PRIORITY_KEYWORDS: dict[str, int] = { - "security": 90, - "payment": 80, - "deploy": 70, - "release": 60, - "push": 50, - "pull_request": 40, - "issue": 30, -} - - -def _score_priority(event_category: str) -> int: - """Return a numeric priority score (higher = more important).""" - lower = event_category.lower() - for keyword, score in _PRIORITY_KEYWORDS.items(): - if keyword in lower: - return score - return 10 # default low priority - - -class MetadataEnricher(EventHandlerBase): - """Add priority score and processed timestamp, then publish. - - This is the terminal handler in the chain. It always returns a - ``HandlerResult`` with event_type ``webhook.processed``. - """ - - def __init__(self) -> None: - super().__init__(priority=15) - - async def on_startup(self) -> None: - """No handler-specific startup needed.""" - - async def on_shutdown(self) -> None: - """No handler-specific shutdown needed.""" - - async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: - return event.type == "webhook.received" - - async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None: - webhook_service: WebhookService = self.registry.get_service(WebhookService) # type: ignore - normalized = context.get("normalized_event", event.data) - webhook_id = context.get("webhook_id", event.id) - - # Enrich - enriched: dict[str, Any] = {**normalized} - enriched["priority_score"] = _score_priority(normalized.get("event_category", "")) - enriched["processed_at"] = datetime.now(UTC).isoformat() - enriched["webhook_id"] = webhook_id - - # Mark as processed for dedup and store for the recent-list - webhook_service.mark_processed(webhook_id) - webhook_service.store_recent(webhook_id, enriched) - - logger.info("Enriched webhook %s (priority=%s)", webhook_id, enriched["priority_score"]) - - return HandlerResult( - event_type="webhook.processed", - data=enriched, - ) - - def get_published_event_types(self) -> tuple[str, str] | None: - return ("webhook.processed", "webhook.processed.error") diff --git a/examples/webhook_relay/src/handlers/webhook_handler.py b/examples/webhook_relay/src/handlers/webhook_handler.py new file mode 100644 index 00000000..fadf8f9d --- /dev/null +++ b/examples/webhook_relay/src/handlers/webhook_handler.py @@ -0,0 +1,51 @@ +"""The handler for ``webhook.received``: translate the event, call the service once, translate back.""" + +from __future__ import annotations + +from typing import Any + +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.events import GenericCloudEvent, HandlerResult + +from ..models.domain import IncomingWebhook +from ..models.schemas import WebhookPayload +from ..services.webhook_service import WebhookService + +WEBHOOK_RECEIVED = "webhook.received" + + +class WebhookHandler(EventHandlerBase): + """Relays incoming webhooks. All decisions -- duplicate, filtered, enriched -- are the service's.""" + + def __init__(self) -> None: + super().__init__(priority=10) + + async def on_startup(self) -> None: + self._service = self.registry.get_service(WebhookService) + + async def on_shutdown(self) -> None: + """No handler-specific shutdown needed.""" + + def get_handled_event_types(self) -> list[str]: + return [WEBHOOK_RECEIVED] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return event.type == WEBHOOK_RECEIVED + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult: + payload = self.extract_payload(event, WebhookPayload) + webhook = IncomingWebhook( + webhook_id=payload.webhook_id or event.id, + source=payload.source, + event_type=payload.event_type, + payload=payload.payload, + ) + outcome = await self._service.relay(webhook) + if outcome.kind == "duplicate": + return HandlerResult.skipped(outcome.reason) + if outcome.kind == "filtered": + return HandlerResult(event_type="webhook.filtered", data=outcome.data) + return HandlerResult(event_type="webhook.processed", data=outcome.data) + + def get_published_event_types(self) -> tuple[str, str] | None: + return ("webhook.processed", "webhook.filtered") diff --git a/examples/webhook_relay/src/handlers/webhook_normalizer.py b/examples/webhook_relay/src/handlers/webhook_normalizer.py deleted file mode 100644 index 37b5f6dd..00000000 --- a/examples/webhook_relay/src/handlers/webhook_normalizer.py +++ /dev/null @@ -1,63 +0,0 @@ -"""Handler that normalizes raw webhook payloads (priority 5 -- runs first).""" - -from __future__ import annotations - -import logging -from typing import Any - -from blueprint.agents.handler.event_handler_base import EventHandlerBase -from blueprint.agents.models.events import GenericCloudEvent, HandlerResult - -from ..models.schemas import WebhookPayload -from ..services.webhook_service import WebhookService - -logger = logging.getLogger(__name__) - - -class WebhookNormalizer(EventHandlerBase): - """Parse the incoming webhook, deduplicate, and normalize. - - Stores the normalized event in ``context["normalized_event"]`` so - downstream handlers can use it without re-parsing. - - Returns ``None`` to pass control to the next handler. - """ - - def __init__(self) -> None: - super().__init__(priority=5) - - async def on_startup(self) -> None: - """No handler-specific startup needed.""" - - async def on_shutdown(self) -> None: - """No handler-specific shutdown needed.""" - - async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: - return event.type == "webhook.received" - - async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None: - webhook_service: WebhookService = self.registry.get_service(WebhookService) # type: ignore - - # Parse incoming data into the domain model - payload = WebhookPayload.model_validate(event.data) - - # Deduplicate - webhook_id = payload.webhook_id or event.id - if webhook_service.is_duplicate(webhook_id): - logger.info("Duplicate webhook %s -- skipping", webhook_id) - return None - - # Normalize - normalized = webhook_service.normalize_payload(payload) - context["normalized_event"] = normalized.model_dump() - context["webhook_id"] = webhook_id - logger.info( - "Normalized webhook %s from %s (%s/%s)", - webhook_id, - normalized.original_source, - normalized.event_category, - normalized.event_action, - ) - - # Pass to next handler - return None diff --git a/examples/webhook_relay/src/main.py b/examples/webhook_relay/src/main.py index 7c171126..a87958ba 100644 --- a/examples/webhook_relay/src/main.py +++ b/examples/webhook_relay/src/main.py @@ -13,19 +13,15 @@ from blueprint.agents import AppBuilder, Config from .api.routes import WebhookApi -from .handlers.content_filter import ContentFilter -from .handlers.metadata_enricher import MetadataEnricher -from .handlers.webhook_normalizer import WebhookNormalizer +from .handlers.webhook_handler import WebhookHandler from .services.webhook_service import WebhookService agent = ( AppBuilder() - # Business service + # Business service: deduplication, normalisation, filtering, enrichment .with_service(WebhookService) - # Handler chain -- priority determines execution order (low first) - .with_handler(WebhookNormalizer) # priority 5 -- normalize - .with_handler(ContentFilter) # priority 10 -- filter - .with_handler(MetadataEnricher) # priority 15 -- enrich & publish + # One handler for webhook.received: translates, calls WebhookService.relay once + .with_handler(WebhookHandler) # REST API .with_rest_api(WebhookApi) # Persistent cache for dedup and recent-event tracking diff --git a/examples/webhook_relay/src/models/domain.py b/examples/webhook_relay/src/models/domain.py new file mode 100644 index 00000000..683a792f --- /dev/null +++ b/examples/webhook_relay/src/models/domain.py @@ -0,0 +1,44 @@ +"""Domain models: what the service works with. No CloudEvent and no DTO reaches the service.""" + +from __future__ import annotations + +from datetime import UTC, datetime +from typing import Any, Literal + +from pydantic import BaseModel, Field + + +class IncomingWebhook(BaseModel): + """One webhook to relay, identified by ``webhook_id``.""" + + webhook_id: str + source: str + event_type: str + payload: dict[str, Any] + + +class NormalizedEvent(BaseModel): + """Source-agnostic representation of a webhook event.""" + + original_source: str + event_category: str + event_action: str + actor: str | None = None + resource_id: str | None = None + resource_type: str | None = None + metadata: dict[str, Any] = Field(default_factory=dict) + received_at: str = Field( + default_factory=lambda: datetime.now(UTC).isoformat(), + ) + + +class RelayOutcome(BaseModel): + """What the service decided for one webhook. + + ``duplicate``: already relayed, nothing to do. ``filtered``: dropped by a content rule, ``data`` + says why. ``processed``: normalised and enriched, ``data`` is the event to publish. + """ + + kind: Literal["duplicate", "filtered", "processed"] + reason: str = "" + data: dict[str, Any] = Field(default_factory=dict) diff --git a/examples/webhook_relay/src/models/schemas.py b/examples/webhook_relay/src/models/schemas.py index b48f9163..3a4e97a2 100644 --- a/examples/webhook_relay/src/models/schemas.py +++ b/examples/webhook_relay/src/models/schemas.py @@ -1,40 +1,17 @@ -"""Pydantic models for the webhook relay pipeline.""" +"""DTOs: what arrives over HTTP and in the ``webhook.received`` event.""" from __future__ import annotations -from datetime import UTC, datetime from typing import Any, Literal -from pydantic import BaseModel, Field +from pydantic import BaseModel class WebhookPayload(BaseModel): - """Incoming webhook payload from an external source.""" + """Incoming webhook payload from an external source (REST body and event data).""" source: Literal["github", "stripe", "generic"] = "generic" event_type: str payload: dict[str, Any] timestamp: str | None = None webhook_id: str | None = None - - -class NormalizedEvent(BaseModel): - """Source-agnostic representation of a webhook event.""" - - original_source: str - event_category: str - event_action: str - actor: str | None = None - resource_id: str | None = None - resource_type: str | None = None - metadata: dict[str, Any] = Field(default_factory=dict) - received_at: str = Field( - default_factory=lambda: datetime.now(UTC).isoformat(), - ) - - -class FilterDecision(BaseModel): - """Result of the content-filtering stage.""" - - allowed: bool - reason: str diff --git a/examples/webhook_relay/src/services/webhook_service.py b/examples/webhook_relay/src/services/webhook_service.py index 615fd791..2e1f7374 100644 --- a/examples/webhook_relay/src/services/webhook_service.py +++ b/examples/webhook_relay/src/services/webhook_service.py @@ -1,4 +1,4 @@ -"""Business logic for webhook normalisation and deduplication.""" +"""Business logic of the relay: deduplication, normalisation, content filtering and enrichment.""" from __future__ import annotations @@ -9,13 +9,24 @@ from blueprint.agents.services.service_base import ServiceBase from blueprint.agents.services.infrastructure.cache_service import CacheService -from ..models.schemas import NormalizedEvent, WebhookPayload +from ..models.domain import IncomingWebhook, NormalizedEvent, RelayOutcome logger = logging.getLogger(__name__) WEBHOOK_NAMESPACE = "webhooks" RECENT_NAMESPACE = "webhooks_recent" +# Simple priority scoring by event category keyword (higher = more important). +_PRIORITY_KEYWORDS: dict[str, int] = { + "security": 90, + "payment": 80, + "deploy": 70, + "release": 60, + "push": 50, + "pull_request": 40, + "issue": 30, +} + class WebhookService(ServiceBase): """Normalizes webhook payloads and tracks duplicates via the cache.""" @@ -35,11 +46,69 @@ async def on_startup(self) -> None: async def on_shutdown(self) -> None: """Nothing to tear down.""" + # ------------------------------------------------------------------ + # Entry point + # ------------------------------------------------------------------ + + async def relay(self, webhook: IncomingWebhook) -> RelayOutcome: + """Decide what happens to one webhook: the one method the handler calls. + + Duplicate -> nothing to do. A content rule matches -> filtered, with the reason. Otherwise + normalised, enriched, recorded for deduplication and the recent list, and returned for + publishing. + """ + if self.is_duplicate(webhook.webhook_id): + return RelayOutcome(kind="duplicate", reason=f"webhook {webhook.webhook_id} already relayed") + normalized = self.normalize_payload(webhook) + reason = self.filter_reason(normalized) + if reason is not None: + logger.info("Webhook %s filtered: %s", webhook.webhook_id, reason) + return RelayOutcome(kind="filtered", reason=reason, data={"reason": reason, "webhook_id": webhook.webhook_id}) + enriched = self.enrich(normalized, webhook.webhook_id) + self.mark_processed(webhook.webhook_id) + self.store_recent(webhook.webhook_id, enriched) + logger.info("Relayed webhook %s (priority=%s)", webhook.webhook_id, enriched["priority_score"]) + return RelayOutcome(kind="processed", data=enriched) + + # ------------------------------------------------------------------ + # Filtering and enrichment + # ------------------------------------------------------------------ + + @staticmethod + def filter_reason(normalized: NormalizedEvent) -> str | None: + """Why this event is dropped, or ``None`` to relay it. + + GitHub: an actor containing ``[bot]``. Stripe: an event category starting with ``test_``. + """ + actor = normalized.actor or "" + if normalized.original_source == "github" and "[bot]" in actor: + return f"Filtered GitHub bot event from {actor}" + if normalized.original_source == "stripe" and normalized.event_category.startswith("test_"): + return f"Filtered Stripe test event: {normalized.event_category}" + return None + + @staticmethod + def score_priority(event_category: str) -> int: + """Return a numeric priority score (higher = more important).""" + lower = event_category.lower() + for keyword, score in _PRIORITY_KEYWORDS.items(): + if keyword in lower: + return score + return 10 + + def enrich(self, normalized: NormalizedEvent, webhook_id: str) -> dict[str, Any]: + """The event to publish: the normalised fields plus priority score, timestamp and id.""" + enriched: dict[str, Any] = normalized.model_dump() + enriched["priority_score"] = self.score_priority(normalized.event_category) + enriched["processed_at"] = datetime.now(UTC).isoformat() + enriched["webhook_id"] = webhook_id + return enriched + # ------------------------------------------------------------------ # Normalisation # ------------------------------------------------------------------ - def normalize_payload(self, payload: WebhookPayload) -> NormalizedEvent: + def normalize_payload(self, payload: IncomingWebhook) -> NormalizedEvent: """Convert a source-specific webhook into a NormalizedEvent.""" if payload.source == "github": return self._normalize_github(payload) @@ -48,7 +117,7 @@ def normalize_payload(self, payload: WebhookPayload) -> NormalizedEvent: return self._normalize_generic(payload) @staticmethod - def _normalize_github(payload: WebhookPayload) -> NormalizedEvent: + def _normalize_github(payload: IncomingWebhook) -> NormalizedEvent: data = payload.payload action = data.get("action", payload.event_type) sender = data.get("sender", {}) @@ -68,7 +137,7 @@ def _normalize_github(payload: WebhookPayload) -> NormalizedEvent: ) @staticmethod - def _normalize_stripe(payload: WebhookPayload) -> NormalizedEvent: + def _normalize_stripe(payload: IncomingWebhook) -> NormalizedEvent: data = payload.payload event_type_parts = data.get("type", payload.event_type).rsplit(".", 1) category = event_type_parts[0] if len(event_type_parts) > 1 else payload.event_type @@ -87,7 +156,7 @@ def _normalize_stripe(payload: WebhookPayload) -> NormalizedEvent: ) @staticmethod - def _normalize_generic(payload: WebhookPayload) -> NormalizedEvent: + def _normalize_generic(payload: IncomingWebhook) -> NormalizedEvent: return NormalizedEvent( original_source=payload.source, event_category=payload.event_type, diff --git a/examples/webhook_relay/tests/test_handlers.py b/examples/webhook_relay/tests/test_handlers.py index e28425cd..0fbecdea 100644 --- a/examples/webhook_relay/tests/test_handlers.py +++ b/examples/webhook_relay/tests/test_handlers.py @@ -1,18 +1,17 @@ -"""Unit tests for the webhook relay handler chain.""" +"""Unit tests for WebhookHandler: it translates, the service decides.""" from __future__ import annotations from datetime import UTC, datetime from typing import Any -from unittest.mock import MagicMock +from unittest.mock import AsyncMock, MagicMock import pytest from blueprint.agents.models.events import GenericCloudEvent, HandlerResult -from src.handlers.content_filter import ContentFilter -from src.handlers.metadata_enricher import MetadataEnricher -from src.handlers.webhook_normalizer import WebhookNormalizer +from src.handlers.webhook_handler import WebhookHandler +from src.models.domain import IncomingWebhook, RelayOutcome from src.services.webhook_service import WebhookService # --------------------------------------------------------------------------- @@ -79,183 +78,53 @@ def _stripe_test_data() -> dict[str, Any]: @pytest.fixture() -def mock_registry(): - """Return a mock registry with a fake WebhookService.""" +async def handler_and_service(): + """A WebhookHandler holding a WebhookService double, as ``on_startup`` would leave it.""" service = MagicMock(spec=WebhookService) - service.is_duplicate.return_value = False - service.normalize_payload.side_effect = lambda p: WebhookService._normalize_github(p) - service.mark_processed = MagicMock() - service.store_recent = MagicMock() - - registry = MagicMock() - registry.get_service.return_value = service - return registry - - -# --------------------------------------------------------------------------- -# WebhookNormalizer -# --------------------------------------------------------------------------- - - -class TestWebhookNormalizer: - @pytest.mark.asyncio - async def test_can_handle_correct_event_type(self): - handler = WebhookNormalizer.__new__(WebhookNormalizer) - handler._priority = 5 - event = _make_event(_github_push_data()) - assert await handler.can_handle_event(event, {}) is True - - @pytest.mark.asyncio - async def test_ignores_other_event_types(self): - handler = WebhookNormalizer.__new__(WebhookNormalizer) - handler._priority = 5 - event = _make_event(_github_push_data(), event_type="order.placed") - assert await handler.can_handle_event(event, {}) is False - - @pytest.mark.asyncio - async def test_normalizes_and_passes(self, mock_registry): - handler = WebhookNormalizer.__new__(WebhookNormalizer) - handler._priority = 5 - handler._name = "webhook_normalizer" - type(handler).registry = property(lambda self: mock_registry) # type: ignore - - event = _make_event(_github_push_data()) - context: dict[str, Any] = {} - result = await handler.handle_event(event, context) - - assert result is None - assert "normalized_event" in context - assert context["normalized_event"]["original_source"] == "github" - - @pytest.mark.asyncio - async def test_duplicate_skipped(self, mock_registry): - mock_registry.get_service.return_value.is_duplicate.return_value = True - - handler = WebhookNormalizer.__new__(WebhookNormalizer) - handler._priority = 5 - handler._name = "webhook_normalizer" - type(handler).registry = property(lambda self: mock_registry) # type: ignore - - event = _make_event(_github_push_data()) - context: dict[str, Any] = {} - result = await handler.handle_event(event, context) - - assert result is None - assert "normalized_event" not in context - - -# --------------------------------------------------------------------------- -# ContentFilter -# --------------------------------------------------------------------------- - - -class TestContentFilter: - @pytest.mark.asyncio - async def test_allows_normal_event(self): - handler = ContentFilter.__new__(ContentFilter) - handler._priority = 10 - - context = { - "normalized_event": { - "original_source": "github", - "event_category": "push", - "actor": "octocat", - }, - "webhook_id": "wh-1", - } - event = _make_event(_github_push_data()) - result = await handler.handle_event(event, context) - assert result is None - - @pytest.mark.asyncio - async def test_filters_github_bot(self): - handler = ContentFilter.__new__(ContentFilter) - handler._priority = 10 - - context = { - "normalized_event": { - "original_source": "github", - "event_category": "push", - "actor": "dependabot[bot]", - }, - "webhook_id": "wh-2", - } - event = _make_event(_github_bot_data()) - result = await handler.handle_event(event, context) - - assert isinstance(result, HandlerResult) - assert result.event_type == "webhook.filtered" - assert "bot" in result.data["reason"].lower() # type: ignore - - @pytest.mark.asyncio - async def test_filters_stripe_test(self): - handler = ContentFilter.__new__(ContentFilter) - handler._priority = 10 - - context = { - "normalized_event": { - "original_source": "stripe", - "event_category": "test_charge", - "actor": None, - }, - "webhook_id": "wh-3", - } - event = _make_event(_stripe_test_data()) - result = await handler.handle_event(event, context) - - assert isinstance(result, HandlerResult) - assert result.event_type == "webhook.filtered" - assert "test" in result.data["reason"].lower() # type: ignore - - -# --------------------------------------------------------------------------- -# MetadataEnricher -# --------------------------------------------------------------------------- - - -class TestMetadataEnricher: - @pytest.mark.asyncio - async def test_enriches_and_publishes(self, mock_registry): - handler = MetadataEnricher.__new__(MetadataEnricher) - handler._priority = 15 - handler._name = "metadata_enricher" - type(handler).registry = property(lambda self: mock_registry) # type: ignore - - context = { - "normalized_event": { - "original_source": "github", - "event_category": "push", - "event_action": "completed", - "actor": "octocat", - }, - "webhook_id": "wh-4", - } - event = _make_event(_github_push_data()) - result = await handler.handle_event(event, context) - + service.relay = AsyncMock(return_value=RelayOutcome(kind="processed", data={"webhook_id": "evt-test-001"})) + handler = WebhookHandler.__new__(WebhookHandler) + handler._priority = 10 + handler._service = service + return handler, service + + +class TestRouting: + async def test_declares_and_accepts_webhook_received(self, handler_and_service): + handler, _ = handler_and_service + assert handler.get_handled_event_types() == ["webhook.received"] + assert await handler.can_handle_event(_make_event(_github_push_data()), {}) is True + + async def test_declines_other_types_without_calling_the_service(self, handler_and_service): + handler, service = handler_and_service + assert await handler.can_handle_event(_make_event({}, event_type="other.event"), {}) is False + service.relay.assert_not_awaited() + + +class TestTranslation: + async def test_the_payload_reaches_the_service_as_a_domain_value(self, handler_and_service): + handler, service = handler_and_service + await handler.handle_event(_make_event(_github_push_data()), {}) + webhook = service.relay.await_args.args[0] + assert isinstance(webhook, IncomingWebhook) + assert webhook.webhook_id == "evt-test-001" # no webhook_id in the payload -> the event id + assert webhook.source == "github" + + async def test_processed_is_published_as_webhook_processed(self, handler_and_service): + handler, _ = handler_and_service + result = await handler.handle_event(_make_event(_stripe_payment_data()), {}) assert isinstance(result, HandlerResult) assert result.event_type == "webhook.processed" - assert result.data["priority_score"] == 50 # "push" keyword # type: ignore - assert "processed_at" in result.data # type: ignore - mock_registry.get_service.return_value.mark_processed.assert_called_once_with("wh-4") - - @pytest.mark.asyncio - async def test_payment_gets_high_priority(self, mock_registry): - handler = MetadataEnricher.__new__(MetadataEnricher) - handler._priority = 15 - handler._name = "metadata_enricher" - type(handler).registry = property(lambda self: mock_registry) # type: ignore - - context = { - "normalized_event": { - "original_source": "stripe", - "event_category": "payment_intent", - "event_action": "succeeded", - }, - "webhook_id": "wh-5", - } - event = _make_event(_stripe_payment_data()) - result = await handler.handle_event(event, context) - assert isinstance(result, HandlerResult) - assert result.data["priority_score"] == 80 # "payment" keyword # type: ignore + async def test_filtered_is_published_as_webhook_filtered(self, handler_and_service): + handler, service = handler_and_service + service.relay.return_value = RelayOutcome(kind="filtered", reason="bot", data={"reason": "bot"}) + result = await handler.handle_event(_make_event(_github_bot_data()), {}) + assert result.event_type == "webhook.filtered" + assert result.data == {"reason": "bot"} + + async def test_a_duplicate_is_skipped_with_the_services_reason(self, handler_and_service): + handler, service = handler_and_service + service.relay.return_value = RelayOutcome(kind="duplicate", reason="webhook evt-test-001 already relayed") + result = await handler.handle_event(_make_event(_stripe_test_data()), {}) + assert result.is_skipped + assert result.skip_reason == "webhook evt-test-001 already relayed" diff --git a/examples/webhook_relay/tests/test_webhook_service.py b/examples/webhook_relay/tests/test_webhook_service.py index c499435b..1af3d6fb 100644 --- a/examples/webhook_relay/tests/test_webhook_service.py +++ b/examples/webhook_relay/tests/test_webhook_service.py @@ -5,7 +5,7 @@ from unittest.mock import MagicMock -from src.models.schemas import NormalizedEvent, WebhookPayload +from src.models.domain import IncomingWebhook, NormalizedEvent from src.services.webhook_service import WebhookService # --------------------------------------------------------------------------- @@ -35,7 +35,8 @@ def _make_service(*, with_cache: bool = False) -> WebhookService: class TestNormalizePayload: def test_github_push(self): - payload = WebhookPayload( + payload = IncomingWebhook( + webhook_id="wh-test", source="github", event_type="push", payload={ @@ -56,7 +57,8 @@ def test_github_push(self): assert result.resource_type == "repository" def test_stripe_payment_intent(self): - payload = WebhookPayload( + payload = IncomingWebhook( + webhook_id="wh-test", source="stripe", event_type="payment_intent.succeeded", payload={ @@ -75,7 +77,8 @@ def test_stripe_payment_intent(self): assert result.resource_type == "payment_intent" def test_generic_passthrough(self): - payload = WebhookPayload( + payload = IncomingWebhook( + webhook_id="wh-test", source="generic", event_type="alert.fired", payload={ @@ -97,7 +100,8 @@ def test_generic_passthrough(self): assert result.metadata["severity"] == "critical" def test_github_missing_optional_fields(self): - payload = WebhookPayload( + payload = IncomingWebhook( + webhook_id="wh-test", source="github", event_type="ping", payload={}, @@ -163,3 +167,52 @@ def test_store_recent_noop_without_cache(self): def test_get_recent_empty_without_cache(self): svc = _make_service(with_cache=False) assert svc.get_recent() == [] + + +# --------------------------------------------------------------------------- +# relay: the one entry point, and the decisions the handlers used to make +# --------------------------------------------------------------------------- + + +def _webhook(source: str, event_type: str, payload: dict) -> IncomingWebhook: + return IncomingWebhook(webhook_id="wh-r1", source=source, event_type=event_type, payload=payload) + + +class TestRelay: + async def test_a_duplicate_needs_nothing(self): + svc = _make_service(with_cache=True) + svc._cache.exists.return_value = True # type: ignore + outcome = await svc.relay(_webhook("github", "push", {})) + assert outcome.kind == "duplicate" + assert "wh-r1" in outcome.reason + svc._cache.set.assert_not_called() # type: ignore + + async def test_a_github_bot_is_filtered_and_not_recorded(self): + svc = _make_service(with_cache=True) + outcome = await svc.relay(_webhook("github", "push", {"sender": {"login": "dependabot[bot]"}})) + assert outcome.kind == "filtered" + assert outcome.data == {"reason": "Filtered GitHub bot event from dependabot[bot]", "webhook_id": "wh-r1"} + svc._cache.set.assert_not_called() # type: ignore + + async def test_a_stripe_test_event_is_filtered(self): + svc = _make_service() + outcome = await svc.relay(_webhook("stripe", "test_charge.created", {"type": "test_charge.created"})) + assert outcome.kind == "filtered" + assert "test_charge" in outcome.reason + + async def test_a_normal_event_is_enriched_recorded_and_returned(self): + svc = _make_service(with_cache=True) + outcome = await svc.relay(_webhook("stripe", "payment_intent.succeeded", {"type": "payment_intent.succeeded", "id": "pi_1"})) + assert outcome.kind == "processed" + assert outcome.data["priority_score"] == 80 + assert outcome.data["webhook_id"] == "wh-r1" + assert "processed_at" in outcome.data + assert svc._cache.set.call_count == 2 # type: ignore # dedup marker + recent list + + +class TestScoring: + def test_unknown_category_gets_the_default(self): + assert WebhookService.score_priority("something.else") == 10 + + def test_security_outranks_push(self): + assert WebhookService.score_priority("security_advisory") > WebhookService.score_priority("push") From 1d40fdc18b31edfcb3f63e57628649a9f165a078 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 17:25:11 +0200 Subject: [PATCH 091/133] refactor(examples): order_event_pipeline -- one service call per event, OrderService.process_order Two handlers on order.created split one piece of domain logic (validate, then enrich) and made two service calls each. One OrderHandler now routes on the envelope, declares order.created, maps the OrderPayload DTO to an Order domain value and calls OrderService.process_order() once; the facade validates, enriches and caches. Models split into DTO (schemas.py) and domain (domain.py); the API drops its assert. Co-Authored-By: Claude Opus 5 (1M context) --- examples/order_event_pipeline/README.md | 32 ++- .../order_event_pipeline/src/api/routes.py | 7 +- .../src/handlers/order_enrichment_handler.py | 56 ------ .../src/handlers/order_handler.py | 43 +++++ .../src/handlers/order_validation_handler.py | 61 ------ examples/order_event_pipeline/src/main.py | 12 +- .../order_event_pipeline/src/models/domain.py | 38 ++++ .../src/models/schemas.py | 18 +- .../src/services/order_service.py | 23 ++- .../tests/test_handlers.py | 182 +++++------------- .../tests/test_order_service.py | 32 ++- 11 files changed, 193 insertions(+), 311 deletions(-) delete mode 100644 examples/order_event_pipeline/src/handlers/order_enrichment_handler.py create mode 100644 examples/order_event_pipeline/src/handlers/order_handler.py delete mode 100644 examples/order_event_pipeline/src/handlers/order_validation_handler.py create mode 100644 examples/order_event_pipeline/src/models/domain.py diff --git a/examples/order_event_pipeline/README.md b/examples/order_event_pipeline/README.md index 15973816..70664798 100644 --- a/examples/order_event_pipeline/README.md +++ b/examples/order_event_pipeline/README.md @@ -1,28 +1,24 @@ # Order Event Pipeline An e-commerce order processing pipeline built with the Blueprint Agents framework, -demonstrating Dapr pub/sub event processing with a handler chain-of-responsibility pattern. +demonstrating Dapr pub/sub event processing: one handler translates, one service decides. ## Overview This example shows how to build an event-driven order processing system where: 1. An `order.created` CloudEvent arrives via Dapr pub/sub. -2. The **OrderValidationHandler** (priority 10) validates the order payload. If - validation fails it publishes an `order.rejected` event and short-circuits the - chain. If the order is valid it passes control to the next handler. -3. The **OrderEnrichmentHandler** (priority 20) enriches valid orders with tax - calculations, shipping estimates, and timestamps, then publishes an - `order.validated` event. -4. A REST API exposes cached order statuses for querying. +2. The **OrderHandler** routes it (envelope only), extracts the `OrderPayload` DTO, turns it into + an `Order` domain value and calls `OrderService.process_order()` **once**. +3. `process_order()` decides: an invalid order is cached as `rejected` and comes back with its + errors; a valid one is enriched (tax, shipping estimate, timestamp) and cached as `validated`. +4. The handler publishes the answer as `order.rejected` or `order.validated`. +5. A REST API exposes cached order statuses for querying. ``` -order.created --> [ValidationHandler] --invalid--> order.rejected - | - valid - | - v - [EnrichmentHandler] --> order.validated +order.created --> [OrderHandler] --> OrderService.process_order() + |-- invalid --> order.rejected + '-- valid ----> enrich --> order.validated ``` ## Project Structure @@ -34,10 +30,10 @@ order_event_pipeline/ src/ main.py # Application entry point models/ - schemas.py # Pydantic data models + schemas.py # DTO: OrderPayload (event data) + domain.py # Domain: Order, ValidationError, OrderOutcome handlers/ - order_validation_handler.py - order_enrichment_handler.py + order_handler.py # order.created -> OrderService.process_order() services/ order_service.py # Business logic (validation, enrichment) api/ @@ -63,7 +59,7 @@ Set `event_bus = ""` in `settings.toml` to disable Dapr integration, then run: uvicorn src.main:create_app --factory --host 0.0.0.0 --port 8000 --reload ``` -The handler chain still processes events submitted via the REST API, but no +The handler still processes events submitted via the REST API, but no pub/sub publishing occurs. ## Example CloudEvent Payload diff --git a/examples/order_event_pipeline/src/api/routes.py b/examples/order_event_pipeline/src/api/routes.py index 565f634e..c258c7d4 100644 --- a/examples/order_event_pipeline/src/api/routes.py +++ b/examples/order_event_pipeline/src/api/routes.py @@ -15,12 +15,8 @@ class OrderApi(RestApiBase): """Exposes cached order data via REST endpoints.""" - def __init__(self) -> None: - super().__init__() - self._order_service: OrderService | None = None - async def on_startup(self) -> None: - self._order_service = self.registry.get_service(OrderService) # type: ignore[assignment] + self._order_service: OrderService = self.registry.get_service(OrderService) # type: ignore[assignment] logger.info("OrderApi started") async def on_shutdown(self) -> None: @@ -33,7 +29,6 @@ async def on_shutdown(self) -> None: ) async def get_order(self, order_id: str) -> dict[str, Any]: """Return the cached status and data for a single order.""" - assert self._order_service is not None result = self._order_service.get_cached_order(order_id) if result is None: raise HTTPException(status_code=404, detail=f"Order {order_id} not found") diff --git a/examples/order_event_pipeline/src/handlers/order_enrichment_handler.py b/examples/order_event_pipeline/src/handlers/order_enrichment_handler.py deleted file mode 100644 index 159ff66e..00000000 --- a/examples/order_event_pipeline/src/handlers/order_enrichment_handler.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Handler that enriches validated orders (priority 20).""" - -import logging -from typing import Any - -from blueprint.agents.handler.event_handler_base import EventHandlerBase -from blueprint.agents.models.events import GenericCloudEvent, HandlerResult - -from ..models.schemas import OrderPayload -from ..services.order_service import OrderService - -logger = logging.getLogger(__name__) - - -class OrderEnrichmentHandler(EventHandlerBase): - """Enriches valid orders with tax, shipping estimate, and timestamps. - - Runs after ``OrderValidationHandler`` (priority 20 > 10). Only reached - when validation passed (the validation handler returned ``None``). - Publishes an ``order.validated`` event with the enriched data. - """ - - def __init__(self) -> None: - super().__init__(priority=20) - self._order_service: OrderService | None = None - - async def on_startup(self) -> None: - self._order_service = self.registry.get_service(OrderService) - logger.info("OrderEnrichmentHandler started") - - async def on_shutdown(self) -> None: - pass - - async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: - return event.type == "order.created" - - async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult: - assert self._order_service is not None - payload = OrderPayload(**event.data) - - enriched = self._order_service.enrich_order(payload) - logger.info("Order %s enriched successfully", payload.order_id) - - self._order_service.cache_order_status( - payload.order_id, - "validated", - enriched, - ) - - return HandlerResult( - event_type="order.validated", - data=enriched, - ) - - def get_published_event_types(self) -> tuple[str, str]: - return ("order.validated", "order.rejected") diff --git a/examples/order_event_pipeline/src/handlers/order_handler.py b/examples/order_event_pipeline/src/handlers/order_handler.py new file mode 100644 index 00000000..d4eada72 --- /dev/null +++ b/examples/order_event_pipeline/src/handlers/order_handler.py @@ -0,0 +1,43 @@ +"""The handler for ``order.created``: translate the event, call the service once, translate back.""" + +import logging +from typing import Any + +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.events import GenericCloudEvent, HandlerResult + +from ..models.domain import Order +from ..models.schemas import OrderPayload +from ..services.order_service import OrderService + +logger = logging.getLogger(__name__) + +ORDER_CREATED = "order.created" +_EVENT_TYPE_BY_STATUS = {"validated": "order.validated", "rejected": "order.rejected"} + + +class OrderHandler(EventHandlerBase): + """Processes order.created. Validation and enrichment are OrderService.process_order's decisions.""" + + def __init__(self) -> None: + super().__init__(priority=10) + + async def on_startup(self) -> None: + self._order_service = self.registry.get_service(OrderService) + + async def on_shutdown(self) -> None: + pass + + def get_handled_event_types(self) -> list[str]: + return [ORDER_CREATED] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return event.type == ORDER_CREATED + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult: + payload = self.extract_payload(event, OrderPayload) + outcome = await self._order_service.process_order(Order.model_validate(payload.model_dump())) + return HandlerResult(event_type=_EVENT_TYPE_BY_STATUS[outcome.status], data=outcome.data) + + def get_published_event_types(self) -> tuple[str, str]: + return ("order.validated", "order.rejected") diff --git a/examples/order_event_pipeline/src/handlers/order_validation_handler.py b/examples/order_event_pipeline/src/handlers/order_validation_handler.py deleted file mode 100644 index 28820a4c..00000000 --- a/examples/order_event_pipeline/src/handlers/order_validation_handler.py +++ /dev/null @@ -1,61 +0,0 @@ -"""Handler that validates incoming order events (priority 10).""" - -import logging -from typing import Any - -from blueprint.agents.handler.event_handler_base import EventHandlerBase -from blueprint.agents.models.events import GenericCloudEvent, HandlerResult - -from ..models.schemas import OrderPayload -from ..services.order_service import OrderService - -logger = logging.getLogger(__name__) - - -class OrderValidationHandler(EventHandlerBase): - """Validates order.created events. - - If the order is invalid, publishes an ``order.rejected`` event and - short-circuits the handler chain. If valid, returns ``None`` so the - next handler in the chain (enrichment) can process the order. - """ - - def __init__(self) -> None: - super().__init__(priority=10) - self._order_service: OrderService | None = None - - async def on_startup(self) -> None: - self._order_service = self.registry.get_service(OrderService) - logger.info("OrderValidationHandler started") - - async def on_shutdown(self) -> None: - pass - - async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: - return event.type == "order.created" - - async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None: - assert self._order_service is not None - payload = OrderPayload(**event.data) - - is_valid, errors = self._order_service.validate_order(payload) - - if not is_valid: - error_dicts = [e.model_dump() for e in errors] - logger.warning("Order %s rejected: %s", payload.order_id, error_dicts) - self._order_service.cache_order_status( - payload.order_id, - "rejected", - {"errors": error_dicts}, - ) - return HandlerResult( - event_type="order.rejected", - data={"order_id": payload.order_id, "errors": error_dicts}, - ) - - logger.info("Order %s passed validation", payload.order_id) - # Pass to the next handler in the chain - return None - - def get_published_event_types(self) -> tuple[str, str]: - return ("order.validated", "order.rejected") diff --git a/examples/order_event_pipeline/src/main.py b/examples/order_event_pipeline/src/main.py index d0940d9d..bcf76ab4 100644 --- a/examples/order_event_pipeline/src/main.py +++ b/examples/order_event_pipeline/src/main.py @@ -11,18 +11,10 @@ from blueprint.agents import AppBuilder, Config from .api.routes import OrderApi -from .handlers.order_enrichment_handler import OrderEnrichmentHandler -from .handlers.order_validation_handler import OrderValidationHandler +from .handlers.order_handler import OrderHandler from .services.order_service import OrderService -agent = ( - AppBuilder() - .with_service(OrderService) - .with_handler(OrderValidationHandler) - .with_handler(OrderEnrichmentHandler) - .with_rest_api(OrderApi) - .with_cache() -) +agent = AppBuilder().with_service(OrderService).with_handler(OrderHandler).with_rest_api(OrderApi).with_cache() def create_app(): diff --git a/examples/order_event_pipeline/src/models/domain.py b/examples/order_event_pipeline/src/models/domain.py new file mode 100644 index 00000000..67a763eb --- /dev/null +++ b/examples/order_event_pipeline/src/models/domain.py @@ -0,0 +1,38 @@ +"""Domain models: what OrderService works with. No CloudEvent and no DTO reaches the service.""" + +from typing import Any, Literal + +from pydantic import BaseModel, Field + + +class OrderLine(BaseModel): + """One line of an order.""" + + product_id: str + name: str + quantity: int + unit_price: float + + +class Order(BaseModel): + """An order to process.""" + + order_id: str + customer_id: str + items: list[OrderLine] + shipping_address: str + total_amount: float + + +class ValidationError(BaseModel): + """A single validation error (not an exception).""" + + field: str + message: str + + +class OrderOutcome(BaseModel): + """What OrderService decided: ``rejected`` with the errors, or ``validated`` with the enriched order.""" + + status: Literal["validated", "rejected"] + data: dict[str, Any] = Field(default_factory=dict) diff --git a/examples/order_event_pipeline/src/models/schemas.py b/examples/order_event_pipeline/src/models/schemas.py index 48e8bb84..b3f0ae72 100644 --- a/examples/order_event_pipeline/src/models/schemas.py +++ b/examples/order_event_pipeline/src/models/schemas.py @@ -1,4 +1,4 @@ -"""Pydantic models for order event processing.""" +"""DTOs: the payload of an ``order.created`` event.""" from pydantic import BaseModel @@ -20,19 +20,3 @@ class OrderPayload(BaseModel): items: list[OrderItem] shipping_address: str total_amount: float - - -class OrderResult(BaseModel): - """Result of order processing.""" - - order_id: str - status: str # "validated" | "rejected" - reason: str | None = None - enriched_data: dict | None = None - - -class ValidationError(BaseModel): - """A single validation error (not an exception).""" - - field: str - message: str diff --git a/examples/order_event_pipeline/src/services/order_service.py b/examples/order_event_pipeline/src/services/order_service.py index 62427cb9..268bcc7d 100644 --- a/examples/order_event_pipeline/src/services/order_service.py +++ b/examples/order_event_pipeline/src/services/order_service.py @@ -6,7 +6,7 @@ from blueprint.agents.services.service_base import ServiceBase from blueprint.agents.services.infrastructure.cache_service import CacheService -from ..models.schemas import OrderPayload, ValidationError +from ..models.domain import Order, OrderOutcome, ValidationError logger = logging.getLogger(__name__) @@ -26,7 +26,24 @@ async def on_startup(self) -> None: async def on_shutdown(self) -> None: """No-op shutdown.""" - def validate_order(self, payload: OrderPayload) -> tuple[bool, list[ValidationError]]: + async def process_order(self, order: Order) -> OrderOutcome: + """Validate, then enrich: the one method the handler calls for an order.created event. + + An invalid order is cached as ``rejected`` and comes back with its errors; a valid one is + enriched, cached as ``validated`` and comes back with the enriched data. + """ + is_valid, errors = self.validate_order(order) + if not is_valid: + error_dicts = [error.model_dump() for error in errors] + logger.warning("Order %s rejected: %s", order.order_id, error_dicts) + self.cache_order_status(order.order_id, "rejected", {"errors": error_dicts}) + return OrderOutcome(status="rejected", data={"order_id": order.order_id, "errors": error_dicts}) + enriched = self.enrich_order(order) + self.cache_order_status(order.order_id, "validated", enriched) + logger.info("Order %s validated and enriched", order.order_id) + return OrderOutcome(status="validated", data=enriched) + + def validate_order(self, payload: Order) -> tuple[bool, list[ValidationError]]: """Validate an order payload. Checks: @@ -51,7 +68,7 @@ def validate_order(self, payload: OrderPayload) -> tuple[bool, list[ValidationEr is_valid = len(errors) == 0 return is_valid, errors - def enrich_order(self, payload: OrderPayload) -> dict: + def enrich_order(self, payload: Order) -> dict: """Enrich a validated order with computed fields. Adds: diff --git a/examples/order_event_pipeline/tests/test_handlers.py b/examples/order_event_pipeline/tests/test_handlers.py index 158968b7..c5f22e6e 100644 --- a/examples/order_event_pipeline/tests/test_handlers.py +++ b/examples/order_event_pipeline/tests/test_handlers.py @@ -1,23 +1,17 @@ -"""Unit tests for order event handlers.""" +"""Unit tests for OrderHandler: it translates, OrderService.process_order decides.""" -import pytest +from unittest.mock import AsyncMock, MagicMock -from unittest.mock import MagicMock +import pytest -from blueprint.agents.models.events import GenericCloudEvent, HandlerResult +from blueprint.agents.models.events import GenericCloudEvent -from src.handlers.order_validation_handler import OrderValidationHandler -from src.handlers.order_enrichment_handler import OrderEnrichmentHandler -from src.models.schemas import ValidationError as VError +from src.handlers.order_handler import OrderHandler +from src.models.domain import Order, OrderOutcome def _make_event(data: dict, event_type: str = "order.created") -> GenericCloudEvent: - return GenericCloudEvent( - id="evt-test-001", - type=event_type, - source="/tests", - data=data, - ) + return GenericCloudEvent(id="evt-test-001", type=event_type, source="/tests", data=data) VALID_ORDER_DATA = { @@ -28,129 +22,49 @@ def _make_event(data: dict, event_type: str = "order.created") -> GenericCloudEv "total_amount": 25.0, } -INVALID_ORDER_DATA = { - "order_id": "order-101", - "customer_id": "cust-2", - "items": [], - "shipping_address": "", - "total_amount": -10.0, -} +@pytest.fixture +def handler(): + """An OrderHandler holding an OrderService double, as ``on_startup`` would leave it.""" + h = object.__new__(OrderHandler) + h._priority = 10 + h._order_service = MagicMock() + h._order_service.process_order = AsyncMock(return_value=OrderOutcome(status="validated", data={"order_id": "order-100"})) + return h -# --------------------------------------------------------------------------- -# OrderValidationHandler -# --------------------------------------------------------------------------- - - -class TestOrderValidationHandler: - @pytest.fixture - def handler(self): - h = object.__new__(OrderValidationHandler) - h._priority = 10 - h._name = "order_validation_handler" - - mock_service = MagicMock() - mock_service.validate_order.return_value = (True, []) - mock_service.cache_order_status = MagicMock() - h._order_service = mock_service - return h - - @pytest.mark.asyncio - async def test_can_handle_order_created(self, handler): - event = _make_event(VALID_ORDER_DATA) - assert await handler.can_handle_event(event, {}) is True - - @pytest.mark.asyncio - async def test_ignores_other_events(self, handler): - event = _make_event(VALID_ORDER_DATA, event_type="order.shipped") - assert await handler.can_handle_event(event, {}) is False - - @pytest.mark.asyncio - async def test_valid_order_returns_none(self, handler): - handler._order_service.validate_order.return_value = (True, []) - event = _make_event(VALID_ORDER_DATA) - result = await handler.handle_event(event, {}) - assert result is None - - @pytest.mark.asyncio - async def test_invalid_order_returns_rejected(self, handler): - errors = [ - VError(field="items", message="Order must contain at least one item"), - VError(field="shipping_address", message="Shipping address is required"), - ] - handler._order_service.validate_order.return_value = (False, errors) - event = _make_event(INVALID_ORDER_DATA) - result = await handler.handle_event(event, {}) - - assert isinstance(result, HandlerResult) - assert result.event_type == "order.rejected" - assert result.data["order_id"] == "order-101" - assert len(result.data["errors"]) == 2 - @pytest.mark.asyncio - async def test_rejection_caches_status(self, handler): - errors = [VError(field="items", message="empty")] - handler._order_service.validate_order.return_value = (False, errors) - event = _make_event(INVALID_ORDER_DATA) - await handler.handle_event(event, {}) - handler._order_service.cache_order_status.assert_called_once() +class TestRouting: + async def test_declares_and_accepts_order_created(self, handler): + assert handler.get_handled_event_types() == ["order.created"] + assert await handler.can_handle_event(_make_event(VALID_ORDER_DATA), {}) is True - def test_published_event_types(self, handler): - assert handler.get_published_event_types() == ( - "order.validated", - "order.rejected", - ) - - -# --------------------------------------------------------------------------- -# OrderEnrichmentHandler -# --------------------------------------------------------------------------- - - -class TestOrderEnrichmentHandler: - @pytest.fixture - def handler(self): - h = object.__new__(OrderEnrichmentHandler) - h._priority = 20 - h._name = "order_enrichment_handler" - - mock_service = MagicMock() - mock_service.enrich_order.return_value = { - "order_id": "order-100", - "customer_id": "cust-1", - "items": [{"product_id": "p1", "name": "Widget", "quantity": 1, "unit_price": 25.0}], - "shipping_address": "456 Test Ave", - "total_amount": 25.0, - "tax_amount": 2.5, - "grand_total": 27.5, - "shipping_estimate": "3-5 business days", - "processed_at": "2026-03-30T10:00:00+00:00", - } - mock_service.cache_order_status = MagicMock() - h._order_service = mock_service - return h - - @pytest.mark.asyncio - async def test_can_handle_order_created(self, handler): - event = _make_event(VALID_ORDER_DATA) - assert await handler.can_handle_event(event, {}) is True - - @pytest.mark.asyncio - async def test_returns_validated_result(self, handler): - event = _make_event(VALID_ORDER_DATA) - result = await handler.handle_event(event, {}) - - assert isinstance(result, HandlerResult) + async def test_declines_other_events_without_calling_the_service(self, handler): + assert await handler.can_handle_event(_make_event({}, event_type="order.shipped"), {}) is False + handler._order_service.process_order.assert_not_awaited() + + +class TestTranslation: + async def test_the_payload_reaches_the_service_as_a_domain_order(self, handler): + await handler.handle_event(_make_event(VALID_ORDER_DATA), {}) + order = handler._order_service.process_order.await_args.args[0] + assert isinstance(order, Order) + assert order.order_id == "order-100" + assert order.items[0].product_id == "p1" + + async def test_one_service_call_per_event(self, handler): + await handler.handle_event(_make_event(VALID_ORDER_DATA), {}) + assert handler._order_service.process_order.await_count == 1 + assert [c for c in handler._order_service.method_calls if not c[0].startswith("process_order")] == [] + + async def test_validated_is_published_as_order_validated(self, handler): + result = await handler.handle_event(_make_event(VALID_ORDER_DATA), {}) assert result.event_type == "order.validated" - assert result.data["order_id"] == "order-100" - assert result.data["tax_amount"] == 2.5 - - @pytest.mark.asyncio - async def test_caches_validated_status(self, handler): - event = _make_event(VALID_ORDER_DATA) - await handler.handle_event(event, {}) - handler._order_service.cache_order_status.assert_called_once_with( - "order-100", - "validated", - handler._order_service.enrich_order.return_value, - ) + assert result.data == {"order_id": "order-100"} + + async def test_rejected_is_published_as_order_rejected(self, handler): + handler._order_service.process_order.return_value = OrderOutcome(status="rejected", data={"order_id": "order-101", "errors": []}) + result = await handler.handle_event(_make_event(VALID_ORDER_DATA), {}) + assert result.event_type == "order.rejected" + + def test_published_event_types(self, handler): + assert handler.get_published_event_types() == ("order.validated", "order.rejected") diff --git a/examples/order_event_pipeline/tests/test_order_service.py b/examples/order_event_pipeline/tests/test_order_service.py index 5768c9ad..5eedccee 100644 --- a/examples/order_event_pipeline/tests/test_order_service.py +++ b/examples/order_event_pipeline/tests/test_order_service.py @@ -2,7 +2,9 @@ import pytest -from src.models.schemas import OrderItem, OrderPayload +from unittest.mock import MagicMock + +from src.models.domain import Order, OrderLine from src.services.order_service import OrderService @@ -18,16 +20,16 @@ def service(): return svc -def _make_payload(**overrides) -> OrderPayload: +def _make_payload(**overrides) -> Order: defaults = { "order_id": "order-001", "customer_id": "cust-001", - "items": [OrderItem(product_id="p1", name="Widget", quantity=1, unit_price=10.0)], + "items": [OrderLine(product_id="p1", name="Widget", quantity=1, unit_price=10.0)], "shipping_address": "123 Test St", "total_amount": 10.0, } defaults.update(overrides) - return OrderPayload(**defaults) + return Order(**defaults) class TestValidateOrder: @@ -80,13 +82,13 @@ def test_enrichment_adds_shipping_estimate(self, service: OrderService): assert "shipping_estimate" in result def test_small_order_fast_shipping(self, service: OrderService): - items = [OrderItem(product_id="p1", name="Widget", quantity=2, unit_price=5.0)] + items = [OrderLine(product_id="p1", name="Widget", quantity=2, unit_price=5.0)] payload = _make_payload(items=items, total_amount=10.0) result = service.enrich_order(payload) assert result["shipping_estimate"] == "3-5 business days" def test_large_order_slow_shipping(self, service: OrderService): - items = [OrderItem(product_id="p1", name="Widget", quantity=10, unit_price=5.0)] + items = [OrderLine(product_id="p1", name="Widget", quantity=10, unit_price=5.0)] payload = _make_payload(items=items, total_amount=50.0) result = service.enrich_order(payload) assert result["shipping_estimate"] == "5-7 business days" @@ -95,3 +97,21 @@ def test_enrichment_has_processed_at(self, service: OrderService): payload = _make_payload() result = service.enrich_order(payload) assert "processed_at" in result + + +class TestProcessOrder: + """The facade the handler calls: validate, then enrich, and cache the status either way.""" + + async def test_a_valid_order_is_validated_enriched_and_cached(self, service: OrderService): + service._cache = MagicMock() + outcome = await service.process_order(_make_payload()) + assert outcome.status == "validated" + assert outcome.data["tax_amount"] == 1.0 + assert service._cache.set.call_args.args[1]["status"] == "validated" + + async def test_an_invalid_order_is_rejected_with_its_errors_and_cached(self, service: OrderService): + service._cache = MagicMock() + outcome = await service.process_order(_make_payload(items=[], total_amount=0)) + assert outcome.status == "rejected" + assert {e["field"] for e in outcome.data["errors"]} == {"items", "total_amount"} + assert service._cache.set.call_args.args[1]["status"] == "rejected" From ad771f0f80397319fb3a77ae0e77cae9d15b8870 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 17:25:26 +0200 Subject: [PATCH 092/133] docs(spec): an event no handler takes is logged at WARNING (sec. 7.2) Since HandlerResult.skipped exists, "responsible but nothing to do" has its own INFO outcome, so an event no handler takes means a subscription or routing mistake. The spec said it MUST NOT be a WARNING; the handler chain has always logged one. The spec now matches the code. Kept as its own commit so it can be reverted alone. Co-Authored-By: Claude Opus 5 (1M context) --- docs/specs/2026-08-28-multi-agent-grouping.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md index 85aa9afc..08285a28 100644 --- a/docs/specs/2026-08-28-multi-agent-grouping.md +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -510,12 +510,17 @@ to do, and redelivery cannot make a handler appear: a nak is a pointless loop un and under a queue group a loop that visits every replica in turn. `dapr.py:75` returns `RETRY` for this case today and **MUST** change. -**An unmatched event is normal, and the framework MUST treat it as normal.** Deciding there is -nothing to do is the handler's job and an ordinary outcome of doing it: an agent reads an event, -finds no work in it for whatever domain reason, and says so. Why is the agent's business and not -the framework's. The framework therefore **MUST NOT** log it at WARNING or otherwise present it as -a fault, and **MUST NOT** accumulate per-topic state about it -- under Dapr the topic arrives from a -URL path, so remembering each distinct value lets a caller grow the process's memory. +**An unmatched event is acknowledged, and it is reported as a probable misconfiguration +(changed 2026-10-15).** Deciding there is nothing to do is the handler's job: a handler that is +responsible for the event and finds no work in it returns `HandlerResult.skipped(reason)` (below), +which is an ordinary outcome, logged at INFO. An event that *no* handler takes therefore no longer +stands for "the agent found nothing to do" -- it means the agent is subscribed to something none of +its handlers routes, or a handler declines what it should claim. The framework **MUST** log it at +WARNING ("No handler processed event", from the handler chain) and **MUST** still acknowledge it, +since no redelivery makes a handler appear. It **MUST NOT** accumulate per-topic state about it -- +under Dapr the topic arrives from a URL path, so remembering each distinct value lets a caller grow +the process's memory. (Before 2026-10-15 this paragraph required the opposite -- no WARNING -- +because "nothing to do" could only be said by declining; the chain logged a WARNING regardless.) It **MUST** be counted per namespace and topic, for one purpose: the *proportion* of received events a namespace declines is how a too-broad subscription shows up (sec. 7.7). A high count is a From 30f14e7f2d4894396bd3f9d4ce9d68d2c277467a Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 18:47:19 +0200 Subject: [PATCH 093/133] feat(examples): site_readings -- one agent, two named connections from a ConnectionSource The example the named-connections plan asks for. src/connections.py is a ConnectionSource with two connections (one account each), claims for everything under readings., a binding with a per-connection subject prefix (bind-only, the deployment's consumer), validate (wire subject and event source must name the connection's site) and run_scope (opens the site's settings, read by the service). The agent itself is the usual handler/service split. deploy/ has the example broker (accounts, passwords from the environment), compose and the provisioning script; offline tests cover the source and the handler/service. Live in WSL (throwaway nats:2.10 with accounts, removed afterwards): both connections bound, /health/ready 200, readings below the threshold skipped, above stored as alerts with their own site's threshold, a delivery claiming the other site terminated by validate, every delivery acked once, 0 permission violations. Co-Authored-By: Claude Opus 5 (1M context) --- examples/site_readings/README.md | 71 ++++++++++++ .../site_readings/deploy/docker-compose.yml | 17 +++ .../site_readings/deploy/nats-accounts.conf | 38 ++++++ examples/site_readings/deploy/provision.py | 67 +++++++++++ examples/site_readings/pyproject.toml | 18 +++ examples/site_readings/settings.toml | 31 +++++ examples/site_readings/src/__init__.py | 0 examples/site_readings/src/api/__init__.py | 0 examples/site_readings/src/api/routes.py | 22 ++++ examples/site_readings/src/connections.py | 109 ++++++++++++++++++ .../site_readings/src/handlers/__init__.py | 0 .../src/handlers/reading_handler.py | 42 +++++++ examples/site_readings/src/main.py | 25 ++++ examples/site_readings/src/models/__init__.py | 0 examples/site_readings/src/models/domain.py | 19 +++ examples/site_readings/src/models/schemas.py | 10 ++ .../site_readings/src/services/__init__.py | 0 .../src/services/reading_service.py | 43 +++++++ examples/site_readings/src/sites.py | 42 +++++++ examples/site_readings/tests/__init__.py | 0 .../tests/test_connection_source.py | 96 +++++++++++++++ .../site_readings/tests/test_reading_flow.py | 83 +++++++++++++ 22 files changed, 733 insertions(+) create mode 100644 examples/site_readings/README.md create mode 100644 examples/site_readings/deploy/docker-compose.yml create mode 100644 examples/site_readings/deploy/nats-accounts.conf create mode 100644 examples/site_readings/deploy/provision.py create mode 100644 examples/site_readings/pyproject.toml create mode 100644 examples/site_readings/settings.toml create mode 100644 examples/site_readings/src/__init__.py create mode 100644 examples/site_readings/src/api/__init__.py create mode 100644 examples/site_readings/src/api/routes.py create mode 100644 examples/site_readings/src/connections.py create mode 100644 examples/site_readings/src/handlers/__init__.py create mode 100644 examples/site_readings/src/handlers/reading_handler.py create mode 100644 examples/site_readings/src/main.py create mode 100644 examples/site_readings/src/models/__init__.py create mode 100644 examples/site_readings/src/models/domain.py create mode 100644 examples/site_readings/src/models/schemas.py create mode 100644 examples/site_readings/src/services/__init__.py create mode 100644 examples/site_readings/src/services/reading_service.py create mode 100644 examples/site_readings/src/sites.py create mode 100644 examples/site_readings/tests/__init__.py create mode 100644 examples/site_readings/tests/test_connection_source.py create mode 100644 examples/site_readings/tests/test_reading_flow.py diff --git a/examples/site_readings/README.md b/examples/site_readings/README.md new file mode 100644 index 00000000..308004fd --- /dev/null +++ b/examples/site_readings/README.md @@ -0,0 +1,71 @@ +# Site Readings -- named connections + +One agent consumes the same subject (`readings.>`) from two sites, each with its own NATS account, +over two **named connections** supplied by a **connection source**. The agent's code never learns +that there are sites: the source decides which connections exist, how each one is consumed, which +deliveries may run, and what each run sees. + +A reading above its site's threshold is stored as an alert; one within it is skipped +(`HandlerResult.skipped`). `GET /api/alerts` lists the alerts. + +## What the source does + +`src/connections.py` (named by `nats_connection_source` in `settings.toml`): + +| Hook | Here | +|---|---| +| `claims(agent, subjects)` | Every declared subject under `readings.` belongs to the sites -- so none of them is ever consumed on the agent's default connection, even before a site exists. | +| `connections()` | `site_a` and `site_b`, each logging in as its own account's agent user (`example_sites` in `settings.toml`; the password from `EXAMPLE_NATS_PASSWORD`). | +| `binding(agent, subjects, connection)` | The site's durable consumer: subject prefix `site..` (wire subject `site.site_a.readings.recorded`, the handler sees `readings.recorded`), stream `READINGS_`, deliver subject `deliver..`. Bind-only: the consumer is the deployment's (`deploy/provision.py`). | +| `validate(connection, subject, event)` | A delivery runs only if the wire subject and the event's `source` (`/sites/`) both name the connection's site; anything else is terminated before a handler sees it. | +| `run_scope(connection)` | Opens the site's settings (`src/sites.py`) around the run, so the service applies that site's threshold. Each run starts in an empty context: a run sees its own site only. | + +The agent itself is the usual shape: `ReadingHandler` routes `reading.recorded`, extracts the +`ReadingRecorded` DTO and calls `ReadingService.on_reading()` once; the service decides. + +## Running + +```bash +export EXAMPLE_NATS_PASSWORD= # the broker and the agent read the same variable +export DYNACONF_NATS_PASSWORD="$EXAMPLE_NATS_PASSWORD" +docker compose -f deploy/docker-compose.yml up -d # broker with accounts PROC, SITE_A, SITE_B on :4224 +python deploy/provision.py # streams and consumers, as each site's admin +uvicorn src.main:create_app --factory --port 8000 +python deploy/provision.py --publish # one reading below, one above each threshold +curl localhost:8000/api/alerts # site_a 51.0 (threshold 50), site_b 81.0 (threshold 80) +docker compose -f deploy/docker-compose.yml down +``` + +`/health/ready` stays 503 until both site connections are bound (`nats_connections_readiness = "all"`). +The process account (`proc`) may neither publish nor subscribe: the agent's default connection is +opened but carries no subject, which is what `claims` guarantees. + +## Project structure + +``` +site_readings/ + settings.toml # nats_connection_source, the sites, readiness + src/ + main.py # declaration + create_app() + connections.py # the ConnectionSource (deployment side) + sites.py # per-run site settings, set by run_scope + handlers/reading_handler.py + services/reading_service.py + models/schemas.py # DTO: ReadingRecorded + models/domain.py # Reading, Alert + api/routes.py # GET /api/alerts + deploy/ + nats-accounts.conf # the example broker: one account per site, passwords from the environment + docker-compose.yml + provision.py # what the deployment owns: streams and consumers + tests/ +``` + +## Tests + +```bash +pytest tests +``` + +The tests need no broker: they check the source's answers (connections, claims, bindings, +validation, run scope isolation) and the handler/service split. diff --git a/examples/site_readings/deploy/docker-compose.yml b/examples/site_readings/deploy/docker-compose.yml new file mode 100644 index 00000000..e146e250 --- /dev/null +++ b/examples/site_readings/deploy/docker-compose.yml @@ -0,0 +1,17 @@ +# The example broker with one account per site. Local example only. +# +# export EXAMPLE_NATS_PASSWORD= +# docker compose -f deploy/docker-compose.yml up -d +# python deploy/provision.py # streams and consumers, as each site's admin +services: + nats: + image: nats:2.10-alpine + container_name: site-readings-nats + command: ["-c", "/etc/nats/accounts.conf"] + environment: + EXAMPLE_NATS_PASSWORD: ${EXAMPLE_NATS_PASSWORD:?set EXAMPLE_NATS_PASSWORD} + volumes: + - ./nats-accounts.conf:/etc/nats/accounts.conf:ro + ports: + - "4224:4222" + - "8224:8222" diff --git a/examples/site_readings/deploy/nats-accounts.conf b/examples/site_readings/deploy/nats-accounts.conf new file mode 100644 index 00000000..5b0daf5f --- /dev/null +++ b/examples/site_readings/deploy/nats-accounts.conf @@ -0,0 +1,38 @@ +# The example broker: one account per site, plus the process account. Stands for a deployment +# where each site owns its account and the agent may only receive its deliveries and acknowledge. +# +# No password is written here: every user's password is $EXAMPLE_NATS_PASSWORD, read by the +# server from its environment (see docker-compose.yml). Local example only. + +port: 4222 +http_port: 8222 +jetstream: { store_dir: "/tmp/nats-site-readings" } + +accounts: { + PROC: { + users: [ + # The agent's default connection. It subscribes nothing (every subject is claimed by a site). + { user: proc, password: $EXAMPLE_NATS_PASSWORD, permissions: { publish: { deny: [">"] }, subscribe: { deny: [">"] } } } + ] + } + SITE_A: { + jetstream: enabled + users: [ + { user: admin-site-a, password: $EXAMPLE_NATS_PASSWORD } + { user: agent-site-a, password: $EXAMPLE_NATS_PASSWORD, permissions: { + publish: { allow: ["$JS.ACK.>"] } + subscribe: { allow: ["deliver.site_a.>"] } + } } + ] + } + SITE_B: { + jetstream: enabled + users: [ + { user: admin-site-b, password: $EXAMPLE_NATS_PASSWORD } + { user: agent-site-b, password: $EXAMPLE_NATS_PASSWORD, permissions: { + publish: { allow: ["$JS.ACK.>"] } + subscribe: { allow: ["deliver.site_b.>"] } + } } + ] + } +} diff --git a/examples/site_readings/deploy/provision.py b/examples/site_readings/deploy/provision.py new file mode 100644 index 00000000..29defecf --- /dev/null +++ b/examples/site_readings/deploy/provision.py @@ -0,0 +1,67 @@ +"""What the deployment owns, done once per site: the stream and the agent's consumer. + +The agent never creates either (its users may only receive and acknowledge). Run after the broker +is up; reads EXAMPLE_NATS_PASSWORD and the same settings the source reads:: + + python deploy/provision.py [--publish] + +``--publish`` also sends one reading below and one above each site's threshold. +""" + +import asyncio +import json +import os +import sys +import tomllib +import uuid +from pathlib import Path + +import nats + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) + +from src.connections import SiteSource, stream_name, subject_prefix # noqa: E402 + + +class _Settings: + """The two keys the source reads, from settings.toml, without starting the framework.""" + + def __init__(self) -> None: + self._values = tomllib.loads((ROOT / "settings.toml").read_text(encoding="utf-8"))["default"] + + def get(self, key: str, default: object = None) -> object: + return self._values.get(key, default) + + +async def provision(publish: bool) -> None: + settings = _Settings() + source = SiteSource(settings) + agent = str(settings.get("app_name")) + password = os.environ["EXAMPLE_NATS_PASSWORD"] + for site, spec in source.connections().items(): + admin = await nats.connect(spec.url, user=f"admin-{site.replace('_', '-')}", password=password) + jsm = admin.jsm() + await jsm.add_stream(name=stream_name(site), subjects=[f"{subject_prefix(site)}>"]) + binding = source.binding(agent, ("readings.>",), spec) + if binding is None: + raise SystemExit(f"{site}: the source binds nothing for readings.> -- check src/connections.py") + await jsm.add_consumer(binding.stream, config=binding.consumer_config()) + print(f"{site}: stream {binding.stream}, consumer {binding.durable} -> {binding.deliver_subject}") + if publish: + threshold = float(settings.get("example_sites")[site]["alert_threshold"]) # type: ignore[index] + for value in (threshold - 1, threshold + 1): + event = { + "specversion": "1.0", + "id": str(uuid.uuid4()), + "type": "reading.recorded", + "source": f"/sites/{site}", + "data": {"sensor_id": f"{site}-s1", "value": value}, + } + await admin.jetstream().publish(f"{subject_prefix(site)}readings.recorded", json.dumps(event).encode()) + print(f"{site}: published {threshold - 1} and {threshold + 1}") + await admin.close() + + +if __name__ == "__main__": + asyncio.run(provision("--publish" in sys.argv)) diff --git a/examples/site_readings/pyproject.toml b/examples/site_readings/pyproject.toml new file mode 100644 index 00000000..e8f49fe0 --- /dev/null +++ b/examples/site_readings/pyproject.toml @@ -0,0 +1,18 @@ +[build-system] +requires = ["setuptools>=80.0.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "site-readings" +version = "0.1.0" +requires-python = ">=3.13" +dependencies = ["avs-blueprint-agents>=0.9.0a15"] + +[project.optional-dependencies] +dev = ["pytest>=8.0.0", "pytest-asyncio>=1.0.0"] + +[tool.setuptools] +packages = ["src", "src.api", "src.handlers", "src.services", "src.models"] + +[tool.setuptools.package-dir] +"" = "." diff --git a/examples/site_readings/settings.toml b/examples/site_readings/settings.toml new file mode 100644 index 00000000..36ed17bc --- /dev/null +++ b/examples/site_readings/settings.toml @@ -0,0 +1,31 @@ +[default] +app_name = "site_readings" +app_port = 8000 +app_environment = "development" +log_level = "INFO" + +event_bus = "nats" +# The agent's own (default) connection: the process account. Every subject this agent declares is +# claimed by the source, so it subscribes nothing here. +nats_url = "nats://localhost:4224" +nats_user = "proc" +# nats_password comes from the environment: DYNACONF_NATS_PASSWORD (same value as EXAMPLE_NATS_PASSWORD) + +# Named connections: one per site, supplied by src/connections.py. +nats_connection_source = "src.connections:create_source" +nats_connections_readiness = "all" # ready only while every site's connection is bound +nats_max_concurrent_runs = 4 # per (agent, site) pair + +# Read by the source, not by the framework. +example_broker_url = "nats://localhost:4224" + +[default.example_sites.site_a] +user = "agent-site-a" +alert_threshold = 50.0 + +[default.example_sites.site_b] +user = "agent-site-b" +alert_threshold = 80.0 + +[default.cache] +cache_dir = ".cache/site_readings" diff --git a/examples/site_readings/src/__init__.py b/examples/site_readings/src/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/site_readings/src/api/__init__.py b/examples/site_readings/src/api/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/site_readings/src/api/routes.py b/examples/site_readings/src/api/routes.py new file mode 100644 index 00000000..3102e6ed --- /dev/null +++ b/examples/site_readings/src/api/routes.py @@ -0,0 +1,22 @@ +"""REST endpoint: the alerts the agent has raised, across all sites.""" + +from typing import Any + +from blueprint.agents.io.api.rest_api_base import RestApiBase + +from ..services.reading_service import ReadingService + + +class AlertApi(RestApiBase): + """Read-only view of the stored alerts.""" + + async def on_startup(self) -> None: + self._service = self.registry.get_service(ReadingService) + + async def on_shutdown(self) -> None: + pass + + @RestApiBase.get("/alerts", summary="List recent alerts", tags=["Alerts"]) + async def list_alerts(self) -> dict[str, Any]: + alerts = self._service.recent_alerts() + return {"count": len(alerts), "alerts": alerts} diff --git a/examples/site_readings/src/connections.py b/examples/site_readings/src/connections.py new file mode 100644 index 00000000..813dd7b9 --- /dev/null +++ b/examples/site_readings/src/connections.py @@ -0,0 +1,109 @@ +"""The connection source: two named connections, one per site, each its own broker account. + +Named in ``settings.toml`` as ``nats_connection_source = "src.connections:create_source"``; the +framework calls :func:`create_source` once per process with the process ``Config``. Everything the +source needs comes from there and from the environment (the password, never from a file): + +- ``example_broker_url``: the broker every site's account lives on; +- ``example_sites``: per site, the account user the agent logs in as and its alert threshold. + +The framework never learns what a site is. It opens the connections listed here, consumes each +site's subjects through the binding below, asks :meth:`SiteSource.validate` before a delivery runs, +and enters :meth:`SiteSource.run_scope` around every run. +""" + +import os +from collections.abc import Iterator, Mapping +from contextlib import contextmanager +from typing import Any + +from blueprint.agents.clients.io.nats_connections import ConnectionSpec, JetStreamBinding + +from .sites import SiteSettings, enter_site, leave_site + +PASSWORD_ENV = "EXAMPLE_NATS_PASSWORD" +"""The environment variable holding the example broker's password (the same one ``deploy/`` uses).""" + +CLAIMED_ROOT = "readings." +"""The subject scheme: every subject under ``readings.`` belongs to the sites, never to the default connection.""" + + +def subject_prefix(site: str) -> str: + """What a site's subjects carry on the wire: ``site..readings.recorded``.""" + return f"site.{site}." + + +def stream_name(site: str) -> str: + return f"READINGS_{site.upper()}" + + +def deliver_subject(site: str, agent: str) -> str: + return f"deliver.{site}.{agent}" + + +def durable_name(agent: str) -> str: + return f"{agent}-readings" + + +class SiteSource: + """One named connection per configured site.""" + + def __init__(self, config: Any) -> None: + self._url = str(config.get("example_broker_url")) + self._sites: dict[str, dict[str, Any]] = dict(config.get("example_sites") or {}) + self._password = os.environ.get(PASSWORD_ENV, "") + if not self._password: + raise ValueError(f"Set {PASSWORD_ENV}: the password of the example broker's site users.") + + def claims(self, agent: str, subjects: tuple[str, ...]) -> tuple[str, ...]: + """Every declared subject under ``readings.`` belongs to the sites -- whether a site exists yet or not.""" + return tuple(subject for subject in subjects if subject.startswith(CLAIMED_ROOT)) + + def connections(self) -> Mapping[str, ConnectionSpec]: + return { + site: ConnectionSpec(name=site, url=self._url, user=str(spec["user"]), password=self._password) + for site, spec in self._sites.items() + } + + def binding(self, agent: str, subjects: tuple[str, ...], connection: ConnectionSpec) -> JetStreamBinding | None: + """The consumer ``deploy/provision.py`` creates for ``agent`` in this site's account.""" + claimed = self.claims(agent, subjects) + if not claimed: + return None + return JetStreamBinding( + subjects=claimed, + stream=stream_name(connection.name), + durable=durable_name(agent), + deliver_subject=deliver_subject(connection.name, agent), + deliver_group=agent, + ack_wait=30.0, + subject_prefix=subject_prefix(connection.name), + max_deliver=5, + ) + + def validate(self, connection: str, subject: str, event: Any) -> str | None: + """A delivery runs only if the wire subject and the event's source both name this connection's site.""" + if not subject.startswith(subject_prefix(connection)): + return f"subject {subject!r} is not under {subject_prefix(connection)!r}" + if event.source != f"/sites/{connection}": + return f"event source {event.source!r} is not /sites/{connection}" + return None + + def run_scope(self, connection: str) -> Any: + """Open the site's settings around the run: the threshold the service applies.""" + settings = SiteSettings(name=connection, alert_threshold=float(self._sites[connection]["alert_threshold"])) + + @contextmanager + def scope() -> Iterator[None]: + token = enter_site(settings) + try: + yield + finally: + leave_site(token) + + return scope() + + +def create_source(config: Any) -> SiteSource: + """The factory ``nats_connection_source`` names.""" + return SiteSource(config) diff --git a/examples/site_readings/src/handlers/__init__.py b/examples/site_readings/src/handlers/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/site_readings/src/handlers/reading_handler.py b/examples/site_readings/src/handlers/reading_handler.py new file mode 100644 index 00000000..e73fa9b8 --- /dev/null +++ b/examples/site_readings/src/handlers/reading_handler.py @@ -0,0 +1,42 @@ +"""The handler for ``reading.recorded``: translate the event, call the service once, translate back.""" + +from typing import Any + +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.events import GenericCloudEvent, HandlerResult + +from ..models.domain import Reading +from ..models.schemas import ReadingRecorded +from ..services.reading_service import ReadingService + +READING_RECORDED = "reading.recorded" + + +class ReadingHandler(EventHandlerBase): + """Knows the subject it consumes (``readings.>``), never the connection or the site it came from.""" + + def __init__(self) -> None: + super().__init__(priority=10) + + async def on_startup(self) -> None: + self._service = self.registry.get_service(ReadingService) + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return ["readings.>"] + + def get_handled_event_types(self) -> list[str]: + return [READING_RECORDED] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return event.type == READING_RECORDED + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult: + payload = self.extract_payload(event, ReadingRecorded) + alert = await self._service.on_reading(Reading(sensor_id=payload.sensor_id, value=payload.value), event_id=event.id) + if alert is None: + return HandlerResult.skipped("reading within the site's threshold") + # No event_type: an agent on named connections does not publish results (named-connections plan, D4). + return HandlerResult(data=alert.model_dump()) diff --git a/examples/site_readings/src/main.py b/examples/site_readings/src/main.py new file mode 100644 index 00000000..1f47e9d8 --- /dev/null +++ b/examples/site_readings/src/main.py @@ -0,0 +1,25 @@ +"""Declaration of the site readings agent. + +``agent`` records what the agent is made of; nothing is constructed until it is built. +``create_app()`` builds it as an application of its own:: + + uvicorn src.main:create_app --factory + +Nothing here mentions the sites: the connections come from ``nats_connection_source`` in +``settings.toml``, which the process reads, not the agent. +""" + +from pathlib import Path + +from blueprint.agents import AppBuilder, Config + +from .api.routes import AlertApi +from .handlers.reading_handler import ReadingHandler +from .services.reading_service import ReadingService + +agent = AppBuilder().with_service(ReadingService).with_handler(ReadingHandler).with_rest_api(AlertApi).with_cache() + + +def create_app(): + """Build this agent as an application of its own.""" + return agent.build(Config(settings_files=["settings.toml"], root_path=str(Path(__file__).parent.parent))) diff --git a/examples/site_readings/src/models/__init__.py b/examples/site_readings/src/models/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/site_readings/src/models/domain.py b/examples/site_readings/src/models/domain.py new file mode 100644 index 00000000..08e74f80 --- /dev/null +++ b/examples/site_readings/src/models/domain.py @@ -0,0 +1,19 @@ +"""Domain models: what ReadingService works with.""" + +from pydantic import BaseModel + + +class Reading(BaseModel): + """One sensor reading.""" + + sensor_id: str + value: float + + +class Alert(BaseModel): + """A reading above the threshold that applies to the run.""" + + sensor_id: str + value: float + threshold: float + site: str diff --git a/examples/site_readings/src/models/schemas.py b/examples/site_readings/src/models/schemas.py new file mode 100644 index 00000000..b60069c6 --- /dev/null +++ b/examples/site_readings/src/models/schemas.py @@ -0,0 +1,10 @@ +"""DTO: the payload of a ``reading.recorded`` event.""" + +from pydantic import BaseModel + + +class ReadingRecorded(BaseModel): + """One sensor reading, as a site publishes it.""" + + sensor_id: str + value: float diff --git a/examples/site_readings/src/services/__init__.py b/examples/site_readings/src/services/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/site_readings/src/services/reading_service.py b/examples/site_readings/src/services/reading_service.py new file mode 100644 index 00000000..1ffd1ded --- /dev/null +++ b/examples/site_readings/src/services/reading_service.py @@ -0,0 +1,43 @@ +"""Business logic: decide whether a reading is an alert, and keep the alerts for the API.""" + +import logging +from typing import Any + +from blueprint.agents.services.service_base import ServiceBase + +from ..models.domain import Alert, Reading +from ..sites import current_site + +logger = logging.getLogger(__name__) + +ALERTS_NAMESPACE = "alerts" + + +class ReadingService(ServiceBase): + """Applies the current site's threshold to each reading.""" + + async def on_startup(self) -> None: + self._cache = self.registry.cache_service + + async def on_shutdown(self) -> None: + pass + + async def on_reading(self, reading: Reading, event_id: str) -> Alert | None: + """The one method the handler calls. ``None``: the reading is within its site's threshold. + + Safe to run twice for the same event: the alert is stored under the event id, so a + redelivery overwrites it rather than adding a second one. + """ + site = current_site() + if reading.value <= site.alert_threshold: + return None + alert = Alert(sensor_id=reading.sensor_id, value=reading.value, threshold=site.alert_threshold, site=site.name) + self._cache.set(event_id, alert.model_dump(), namespace=ALERTS_NAMESPACE) + logger.info( + "Alert at site %s: sensor %s reads %s (threshold %s)", site.name, reading.sensor_id, reading.value, site.alert_threshold + ) + return alert + + def recent_alerts(self, limit: int = 50) -> list[dict[str, Any]]: + """The stored alerts, for the REST API.""" + return list(self._cache.list_values(namespace=ALERTS_NAMESPACE, limit=limit)) diff --git a/examples/site_readings/src/sites.py b/examples/site_readings/src/sites.py new file mode 100644 index 00000000..3940900b --- /dev/null +++ b/examples/site_readings/src/sites.py @@ -0,0 +1,42 @@ +"""Per-run site settings, set by the connection source's ``run_scope`` and read by the service. + +This is the one place the agent's code meets the deployment: the source decides which site a run +belongs to (from the connection it arrived on) and opens that site's settings around the run. Each +run starts in an empty context, so a run can only ever see its own site's settings. +""" + +from contextvars import ContextVar, Token +from dataclasses import dataclass + + +@dataclass(frozen=True) +class SiteSettings: + """What differs per site. Here: where an alert starts.""" + + name: str + alert_threshold: float + + +_CURRENT: ContextVar[SiteSettings | None] = ContextVar("site_readings_current_site", default=None) + + +def current_site() -> SiteSettings: + """The settings of the site the current run belongs to. + + Raises: + LookupError: outside a run from a named connection -- a reading without a site has no threshold. + """ + settings = _CURRENT.get() + if settings is None: + raise LookupError("No site in scope: readings are only processed in runs from a site's connection.") + return settings + + +def enter_site(settings: SiteSettings) -> Token[SiteSettings | None]: + """Set the current site; returns the token for :func:`leave_site`. Used by the source only.""" + return _CURRENT.set(settings) + + +def leave_site(token: Token[SiteSettings | None]) -> None: + """Restore what was current before :func:`enter_site`.""" + _CURRENT.reset(token) diff --git a/examples/site_readings/tests/__init__.py b/examples/site_readings/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/site_readings/tests/test_connection_source.py b/examples/site_readings/tests/test_connection_source.py new file mode 100644 index 00000000..26ea1823 --- /dev/null +++ b/examples/site_readings/tests/test_connection_source.py @@ -0,0 +1,96 @@ +"""The connection source: what the framework gets told about the two sites.""" + +import asyncio +from types import SimpleNamespace + +import pytest + +from blueprint.agents.clients.io.nats_connections import ConnectionSource + +from src.connections import PASSWORD_ENV, SiteSource, create_source +from src.sites import current_site + +SETTINGS = { + "example_broker_url": "nats://localhost:4224", + "example_sites": { + "site_a": {"user": "agent-site-a", "alert_threshold": 50.0}, + "site_b": {"user": "agent-site-b", "alert_threshold": 80.0}, + }, +} + + +class _Config: + def get(self, key, default=None): + return SETTINGS.get(key, default) + + +@pytest.fixture +def source(monkeypatch) -> SiteSource: + monkeypatch.setenv(PASSWORD_ENV, "placeholder-for-tests") + return create_source(_Config()) + + +def _event(source: str) -> SimpleNamespace: + return SimpleNamespace(source=source) + + +class TestTheSource: + def test_it_is_a_connection_source(self, source): + assert isinstance(source, ConnectionSource) + + def test_without_the_password_the_factory_refuses(self, monkeypatch): + monkeypatch.delenv(PASSWORD_ENV, raising=False) + with pytest.raises(ValueError, match=PASSWORD_ENV): + create_source(_Config()) + + def test_two_connections_one_per_site_each_with_its_own_user(self, source): + connections = source.connections() + assert sorted(connections) == ["site_a", "site_b"] + assert connections["site_a"].user == "agent-site-a" + assert connections["site_b"].user == "agent-site-b" + assert "placeholder" not in repr(connections["site_a"]), "a password must never appear in a repr" + + def test_claims_every_readings_subject_and_nothing_else(self, source): + assert source.claims("site_readings", ("readings.>", "maintenance.tick")) == ("readings.>",) + + def test_the_binding_prefixes_the_subject_per_site(self, source): + binding = source.binding("site_readings", ("readings.>",), source.connections()["site_b"]) + assert binding.subject_prefix == "site.site_b." + assert binding.filter_subjects == ("site.site_b.readings.>",) + assert binding.deliver_subject == "deliver.site_b.site_readings" + assert binding.stream == "READINGS_SITE_B" + assert binding.local_subject("site.site_b.readings.recorded") == "readings.recorded" + + def test_no_binding_for_an_agent_that_declares_no_readings(self, source): + assert source.binding("other", ("maintenance.tick",), source.connections()["site_a"]) is None + + +class TestValidate: + def test_matching_subject_and_source_run(self, source): + assert source.validate("site_a", "site.site_a.readings.recorded", _event("/sites/site_a")) is None + + def test_a_subject_of_another_site_is_refused(self, source): + assert "not under" in source.validate("site_a", "site.site_b.readings.recorded", _event("/sites/site_a")) + + def test_an_event_claiming_another_site_is_refused(self, source): + assert "event source" in source.validate("site_a", "site.site_a.readings.recorded", _event("/sites/site_b")) + + +class TestRunScope: + def test_the_run_sees_its_sites_settings_and_nothing_after(self, source): + with source.run_scope("site_b"): + assert current_site().name == "site_b" + assert current_site().alert_threshold == 80.0 + with pytest.raises(LookupError): + current_site() + + async def test_concurrent_runs_see_their_own_site(self, source): + seen: dict[str, str] = {} + + async def run(site: str) -> None: + with source.run_scope(site): + await asyncio.sleep(0.01) + seen[site] = current_site().name + + await asyncio.gather(asyncio.create_task(run("site_a")), asyncio.create_task(run("site_b"))) + assert seen == {"site_a": "site_a", "site_b": "site_b"} diff --git a/examples/site_readings/tests/test_reading_flow.py b/examples/site_readings/tests/test_reading_flow.py new file mode 100644 index 00000000..a1309180 --- /dev/null +++ b/examples/site_readings/tests/test_reading_flow.py @@ -0,0 +1,83 @@ +"""ReadingHandler translates; ReadingService decides against the run's site threshold.""" + +from contextlib import contextmanager +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from blueprint.agents.models.events import GenericCloudEvent + +from src.handlers.reading_handler import ReadingHandler +from src.models.domain import Alert, Reading +from src.services.reading_service import ReadingService +from src.sites import SiteSettings, enter_site, leave_site + + +@contextmanager +def site(name: str, threshold: float): + token = enter_site(SiteSettings(name=name, alert_threshold=threshold)) + try: + yield + finally: + leave_site(token) + + +def _event(value: float) -> GenericCloudEvent: + return GenericCloudEvent(id="evt-1", type="reading.recorded", source="/sites/site_a", data={"sensor_id": "s1", "value": value}) + + +@pytest.fixture +def service() -> ReadingService: + svc = object.__new__(ReadingService) + svc._cache = MagicMock() + return svc + + +class TestService: + async def test_within_the_threshold_is_no_alert(self, service): + with site("site_a", 50.0): + assert await service.on_reading(Reading(sensor_id="s1", value=50.0), event_id="e1") is None + service._cache.set.assert_not_called() + + async def test_above_the_threshold_is_an_alert_stored_under_the_event_id(self, service): + with site("site_b", 80.0): + alert = await service.on_reading(Reading(sensor_id="s1", value=81.0), event_id="e2") + assert alert == Alert(sensor_id="s1", value=81.0, threshold=80.0, site="site_b") + assert service._cache.set.call_args.args[0] == "e2" + + async def test_the_same_value_differs_by_site(self, service): + with site("site_a", 50.0): + assert await service.on_reading(Reading(sensor_id="s1", value=60.0), event_id="e3") is not None + with site("site_b", 80.0): + assert await service.on_reading(Reading(sensor_id="s1", value=60.0), event_id="e4") is None + + async def test_outside_a_sites_run_there_is_no_threshold(self, service): + with pytest.raises(LookupError): + await service.on_reading(Reading(sensor_id="s1", value=1.0), event_id="e5") + + +@pytest.fixture +def handler() -> ReadingHandler: + h = object.__new__(ReadingHandler) + h._priority = 10 + h._service = MagicMock() + h._service.on_reading = AsyncMock(return_value=None) + return h + + +class TestHandler: + async def test_routes_on_the_type_and_declares_its_subject(self, handler): + assert handler.get_subscribed_topics() == ["readings.>"] + assert handler.get_handled_event_types() == ["reading.recorded"] + assert await handler.can_handle_event(_event(1.0), {}) is True + + async def test_no_alert_is_a_skip(self, handler): + result = await handler.handle_event(_event(1.0), {}) + assert result.is_skipped + handler._service.on_reading.assert_awaited_once_with(Reading(sensor_id="s1", value=1.0), event_id="evt-1") + + async def test_an_alert_is_returned_unpublished(self, handler): + handler._service.on_reading.return_value = Alert(sensor_id="s1", value=99.0, threshold=50.0, site="site_a") + result = await handler.handle_event(_event(99.0), {}) + assert result.event_type is None + assert result.data["site"] == "site_a" From 4cbc3c20f3d4f791103b9f5947e382058c9fba28 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 18:48:02 +0200 Subject: [PATCH 094/133] fix(examples): document_summarizer -- no assert in production code The API resolves its service in on_startup without an Optional, and the service raises a RuntimeError naming the cause instead of asserting its agent exists. Co-Authored-By: Claude Opus 5 (1M context) --- examples/document_summarizer/src/api/routes.py | 8 +------- .../src/services/summarizer_service.py | 3 ++- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/examples/document_summarizer/src/api/routes.py b/examples/document_summarizer/src/api/routes.py index 40e3f781..3284f7aa 100644 --- a/examples/document_summarizer/src/api/routes.py +++ b/examples/document_summarizer/src/api/routes.py @@ -15,13 +15,9 @@ class SummarizerApi(RestApiBase): """Exposes document summarization endpoints.""" - def __init__(self) -> None: - super().__init__() - self._service: SummarizerService | None = None - async def on_startup(self) -> None: """Resolve the summarizer service from the registry.""" - self._service = self.registry.get_service(SummarizerService) # type: ignore[assignment] + self._service: SummarizerService = self.registry.get_service(SummarizerService) # type: ignore[assignment] logger.info("SummarizerApi started") async def on_shutdown(self) -> None: @@ -39,7 +35,6 @@ async def on_shutdown(self) -> None: ) async def summarize_document(self, request: DocumentRequest) -> SummarizeResponse: """Accept a document and return a structured summary.""" - assert self._service is not None, "Service not initialised" return await self._service.summarize(request) @RestApiBase.get( @@ -50,7 +45,6 @@ async def summarize_document(self, request: DocumentRequest) -> SummarizeRespons ) async def get_summary(self, document_id: str) -> SummarizeResponse: """Return a previously generated summary by its document ID.""" - assert self._service is not None, "Service not initialised" result = await self._service.get_summary(document_id) if result is None: raise HTTPException(status_code=404, detail=f"Summary not found for document_id={document_id}") diff --git a/examples/document_summarizer/src/services/summarizer_service.py b/examples/document_summarizer/src/services/summarizer_service.py index f3ae459b..ade77ac5 100644 --- a/examples/document_summarizer/src/services/summarizer_service.py +++ b/examples/document_summarizer/src/services/summarizer_service.py @@ -64,7 +64,8 @@ async def summarize(self, request: DocumentRequest) -> SummarizeResponse: user_prompt = f"Title: {request.title}\n\n{request.content}" # Run the agent - assert self._agent is not None, "Agent not initialised — was on_startup called?" + if self._agent is None: + raise RuntimeError("SummarizerService used before on_startup resolved its agent") result = await self._agent.run(user_prompt) summary: DocumentSummary = result.data # type: ignore[assignment] From b7586e39426b0ed4eb327955e929c85c6b6ad482 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 18:59:14 +0200 Subject: [PATCH 095/133] feat(nats): nats_delivery_attempt and nats_max_deliver in the handler context Every JetStream delivery, on the default and on named connections, now tells the run which attempt it is: NATSClient._run_delivery records DeliveryAttempt(attempt=num_delivered, max_deliver) in a ContextVar of the run's own task, and NatsEventing copies it into the context as nats_delivery_attempt (1-based) and nats_max_deliver (the binding's max_deliver on a named connection, nats_max_deliver otherwise; None when unlimited or unknown). Equal values mark the last attempt, so a service can close open work instead of leaving it open. Core NATS deliveries carry neither key. _deliveries_exhausted shares the new _max_deliver_of helper. Live against nats:2.10 (default broker and the accounts broker): a nak'd message is seen as (1, 3) then (2, 3) on both connection kinds; the control, a first delivery, is (1, 3) only. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 4 + ...26-08-28-multi-agent-grouping-changelog.md | 12 +++ docs/specs/2026-08-28-multi-agent-grouping.md | 6 ++ .../skills/blueprint-events/SKILL.md | 4 + .../docs/components/event-handlers.md | 7 ++ .../agents/clients/io/nats_client.py | 27 ++++-- .../agents/clients/io/nats_connections.py | 27 ++++++ src/blueprint/agents/io/api/eventing/nats.py | 26 +++++- tests/integration/test_delivery_attempt.py | 62 ++++++++++++++ tests/integration/test_named_connections.py | 34 ++++++++ tests/unit/agents/clients/TESTS.md | 1 + .../clients/io/test_nats_connection_source.py | 84 +++++++++++++++++++ 12 files changed, 286 insertions(+), 8 deletions(-) create mode 100644 tests/integration/test_delivery_attempt.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b37eefe1..c47d085d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -172,6 +172,10 @@ ### Added +- **A JetStream run knows which attempt it is.** The handler context carries `nats_delivery_attempt` + (1-based) and `nats_max_deliver` (`None` when unlimited) on the default and on named connections, + so a service can close open work on the last attempt instead of leaving it open. Core NATS + deliveries carry neither key. - **`HandlerResult.skipped(reason)`.** A handler that is responsible for an event but finds it needs nothing returns it: the chain stops (no later handler is asked, unlike `None`), the delivery is acknowledged, nothing is published, the reason is logged at INFO and the event is counted as diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 5da42701..cc623f47 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -8620,6 +8620,18 @@ deterministic, see Open points). - **`asbs validate`** (`_nats_findings`): the NATS keys parsed with the client's own parsers; the source's module found via `importlib.util.find_spec`, the factory never called. +### The delivery attempt in the handler context + +- `nats_connections.py`: `DeliveryAttempt(attempt, max_deliver)` in a ContextVar, set by + `NATSClient._run_delivery` inside the run's own task from `msg.metadata.num_delivered` and + `_max_deliver_of(binding)` (the binding's `max_deliver` on a named connection, `nats_max_deliver` + on the agent's own consumers; `None` for unset or `-1`). `_deliveries_exhausted` now uses the same + helper. A message without JetStream metadata (Core NATS) sets nothing. +- `NatsEventing._make_event_callback` copies it into the context as `nats_delivery_attempt` and + `nats_max_deliver`. +- Unit tests: named run attempts 1 and 2 with the binding's limit, default connection with unset + `nats_max_deliver` -> `None`, no metadata -> no keys, both keys in the context. + --- ## Open points diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md index 08285a28..bc3bba8a 100644 --- a/docs/specs/2026-08-28-multi-agent-grouping.md +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -567,6 +567,12 @@ bounds a run. Heartbeats address slow handlers; they do **not** address connecti they travel over the same connection, and they do not cover messages still waiting in the client's queue (bound those with `nats_max_ack_pending`). +**A run knows its attempt (added 2026-10-15).** Every JetStream delivery, on the default and on +named connections, puts `nats_delivery_attempt` (1-based, from `num_delivered`) and +`nats_max_deliver` (the consumer's limit; `None` when unlimited or unknown) into the handler +context, beside `nats_topic`, `nats_subject` and `nats_connection`. Equal values mark the last +attempt, after which a failure is dead-lettered or dropped. Core NATS deliveries carry neither key. + ### 7.4 Idempotency At-least-once is unavoidable: rebalance, eviction, node drain and every rolling deploy produce diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md index e49f3544..9b0e8d1e 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md @@ -31,6 +31,10 @@ pod restart, a rolling deploy. Either make the service it calls safe to repeat, whose id and source it has already dispatched, within that window. It is off by default on purpose - only you know whether replaying your side effects is acceptable. +**The handler context tells a JetStream run which attempt it is:** `nats_delivery_attempt` +(1-based) and `nats_max_deliver` (`None` when unlimited). Equal means the last attempt: a failure is +not redelivered. Pass both to the service if it must close open work on the last attempt. + **Never swallow `asyncio.CancelledError`** in a handler or anything it calls. A run that exceeds `nats_handler_timeout` is cancelled; code that catches the cancellation (`except BaseException`, a bare `except:`, `except asyncio.CancelledError` without `raise`) keeps working past the limit and is diff --git a/src/blueprint/agent_generator/docs/components/event-handlers.md b/src/blueprint/agent_generator/docs/components/event-handlers.md index 07a235e7..167bc1f0 100644 --- a/src/blueprint/agent_generator/docs/components/event-handlers.md +++ b/src/blueprint/agent_generator/docs/components/event-handlers.md @@ -155,6 +155,8 @@ delivery: | `nats_topic` | NATS | The subscription as the agent declared it, possibly a wildcard: `orders.>` | | `nats_subject` | NATS | The subject the message was delivered on, as the agent knows it: `orders.created`. On a named connection the binding's `subject_prefix` is stripped again, so a handler sees the same subject on every connection. | | `nats_connection` | NATS | The name of the named connection the delivery came from; absent on the default connection. An opaque name for logs and for passing on -- the framework attaches no meaning to it. | +| `nats_delivery_attempt` | NATS, JetStream | Which attempt this delivery is, 1-based (the broker's `num_delivered`): `1` the first time, `2` after one redelivery. Absent for Core NATS, which does not redeliver. | +| `nats_max_deliver` | NATS, JetStream | The attempts the delivering consumer allows -- the binding's `max_deliver` on a named connection, `nats_max_deliver` otherwise; `None` when unlimited or unknown. Present exactly when `nats_delivery_attempt` is. | | `dapr_topic` | Dapr | The topic the sidecar delivered to | **Derive anything security-relevant from the delivery, not from the event.** Every field of the @@ -163,6 +165,11 @@ under subject-scoped publish permissions, what the broker checked the publisher Nothing in the payload can overwrite a context key. Which deployment-level scope a connection stands for is decided by the connection source (its `validate` and `run_scope` hooks), not by handlers. +**The last attempt.** When `nats_delivery_attempt == nats_max_deliver`, a failure of this run is not +redelivered -- it is dead-lettered or dropped. A service that keeps work open across attempts (a +claimed job, a pending record) can close or hand it off on that attempt instead of leaving it open. +The handler passes the two values to the service as parameters; it does not decide. + The keys are present only for events NATS delivered: a test, a direct `process_event` call or another transport has none, so read them with `.get()` where that can happen. Handlers share `context`, so a handler earlier in the chain could overwrite them -- do not write to transport keys. diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index cd0e8b0a..ce7fc13b 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -31,7 +31,7 @@ from ...models.events import CloudEvent from ..client_base import DeliveryCallback from .io_client_base import IOClientBase, subject_is_covered_by, validate_publish_subject, validate_subject_segment -from .nats_connections import ConnectionSource, ConnectionSpec, JetStreamBinding, mark_connection +from .nats_connections import ConnectionSource, ConnectionSpec, DeliveryAttempt, JetStreamBinding, mark_connection, mark_delivery from .nats_run_pool import PairRuns, Release, RunLimit, RunPool logger = logging.getLogger(__name__) @@ -2516,6 +2516,11 @@ async def _run_delivery(self, msg: Any, topic: str, callback: DeliveryCallback, await self._settle(msg, DeliveryDisposition.TERM, topic, None, binding) return + attempt = self._delivery_count(msg) + if attempt is not None: + # The run's own task: the handler context gets it as nats_delivery_attempt / nats_max_deliver. + mark_delivery(DeliveryAttempt(attempt=attempt, max_deliver=self._max_deliver_of(binding))) + connection = binding.link.name if connection and self._source is not None: mark_connection(connection) @@ -2752,16 +2757,26 @@ def _deliveries_exhausted(self, msg: Any, binding: _Binding | None = None) -> bo and is never exhausted. A message whose JetStream metadata cannot be read is treated as not exhausted, so an unreadable header can only cost a retry, never a payload. """ - # Not configured means the server's default, which is unlimited. - binding = binding or self._binding + max_deliver = self._max_deliver_of(binding or self._binding) + if max_deliver is None: + return False + delivered = self._delivery_count(msg) + return delivered is not None and delivered >= max_deliver + + @staticmethod + def _max_deliver_of(binding: _Binding) -> int | None: + """The attempts ``binding``'s consumer allows; ``None`` for unlimited or unknown. + + A named connection's binding carries the deployment's value; the agent's own consumers + carry ``nats_max_deliver``. Not configured means the server's default, which is unlimited. + """ if binding.jetstream is not None: max_deliver = binding.jetstream.max_deliver else: max_deliver = binding.tuning.max_deliver if binding.tuning else None if max_deliver is None or max_deliver < 0: - return False - delivered = self._delivery_count(msg) - return delivered is not None and delivered >= max_deliver + return None + return max_deliver @staticmethod def _delivery_count(msg: Any) -> int | None: diff --git a/src/blueprint/agents/clients/io/nats_connections.py b/src/blueprint/agents/clients/io/nats_connections.py index 2db6bdf9..3192a6e7 100644 --- a/src/blueprint/agents/clients/io/nats_connections.py +++ b/src/blueprint/agents/clients/io/nats_connections.py @@ -44,6 +44,33 @@ def current_connection() -> str | None: return _CURRENT_CONNECTION.get() +@dataclass(frozen=True) +class DeliveryAttempt: + """Which attempt the current JetStream delivery is, and how many the consumer allows. + + ``attempt`` is 1-based (the broker's ``num_delivered``). ``max_deliver`` is ``None`` when the + consumer allows unlimited attempts or the limit is not known, so ``attempt == max_deliver`` + means: this is the last attempt -- a failure now is not redelivered. + """ + + attempt: int + max_deliver: int | None + + +_CURRENT_DELIVERY: ContextVar[DeliveryAttempt | None] = ContextVar("blueprint_nats_delivery", default=None) +"""Set inside a JetStream run, in the run's own task, so it can never be another run's.""" + + +def current_delivery() -> DeliveryAttempt | None: + """The current run's delivery attempt; ``None`` outside a JetStream run (Core NATS has no redelivery).""" + return _CURRENT_DELIVERY.get() + + +def mark_delivery(attempt: DeliveryAttempt) -> None: + """Record the current run's delivery attempt. Called by the client inside a run's own task only.""" + _CURRENT_DELIVERY.set(attempt) + + @dataclass(frozen=True) class ConnectionSpec: """One connection a deployment supplies: a name and how to log in. Secrets are never logged.""" diff --git a/src/blueprint/agents/io/api/eventing/nats.py b/src/blueprint/agents/io/api/eventing/nats.py index 586e4fa8..e6e3b246 100644 --- a/src/blueprint/agents/io/api/eventing/nats.py +++ b/src/blueprint/agents/io/api/eventing/nats.py @@ -5,7 +5,7 @@ from ....clients.client_base import DeliveryCallback from ....clients.io.nats_client import NATSClient -from ....clients.io.nats_connections import NATS_CONNECTION_CONTEXT_KEY, current_connection +from ....clients.io.nats_connections import NATS_CONNECTION_CONTEXT_KEY, current_connection, current_delivery from ....component.namespace import ROOT_NAMESPACE from ....models.events import CloudEvent from ..rest_api_base import RestApiBase @@ -23,6 +23,23 @@ """ +NATS_DELIVERY_ATTEMPT_CONTEXT_KEY = "nats_delivery_attempt" +"""Handler context key: which attempt this JetStream delivery is, 1-based (the broker's ``num_delivered``). + +Present only on JetStream deliveries -- Core NATS does not redeliver. Read it with +``nats_max_deliver``: when the two are equal this is the last attempt, and a failure now is +dead-lettered or dropped rather than redelivered, so a handler can close or hand off what it +would otherwise leave open. +""" + +NATS_MAX_DELIVER_CONTEXT_KEY = "nats_max_deliver" +"""Handler context key: the attempts the delivering consumer allows; ``None`` when unlimited or unknown. + +Present exactly when ``nats_delivery_attempt`` is. On a named connection the value is the +binding's ``max_deliver``; on the agent's own consumers it is ``nats_max_deliver``. +""" + + class NatsEventing(EventHandlingBase): """Implements event handling using NATS via NATSClient. @@ -119,11 +136,16 @@ def _make_event_callback(self, topic: str) -> DeliveryCallback: """Return an async callback that routes an incoming event through the handler chain.""" async def _process_event(event: CloudEvent[Any], subject: str) -> None: - context = {"nats_topic": topic, NATS_SUBJECT_CONTEXT_KEY: subject} + context: dict[str, Any] = {"nats_topic": topic, NATS_SUBJECT_CONTEXT_KEY: subject} connection = current_connection() if connection is not None: # Only a run from a named connection has one; the default connection adds no key (N6). context[NATS_CONNECTION_CONTEXT_KEY] = connection + delivery = current_delivery() + if delivery is not None: + # JetStream only, on every connection: Core NATS has no redelivery to count. + context[NATS_DELIVERY_ATTEMPT_CONTEXT_KEY] = delivery.attempt + context[NATS_MAX_DELIVER_CONTEXT_KEY] = delivery.max_deliver processing_result = await self._process_cloud_event(event, context, topic) logger.debug( "Processed CloudEvent %s on topic %s with status %s", diff --git a/tests/integration/test_delivery_attempt.py b/tests/integration/test_delivery_attempt.py new file mode 100644 index 00000000..3afac712 --- /dev/null +++ b/tests/integration/test_delivery_attempt.py @@ -0,0 +1,62 @@ +"""A JetStream run sees which attempt it is: ``nats_delivery_attempt`` and ``nats_max_deliver``. + +Against a real broker, so the attempt is the broker's own ``num_delivered``: a handler that fails +once (nak) is redelivered and sees attempt 2; the control -- a handler that succeeds -- sees 1 and +nothing else. ``nats_max_deliver`` is 3 in the integration settings. +""" + +import uuid +from typing import Any + +from nats.js import JetStreamContext + +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.errors import RetryableHandlerError +from blueprint.agents.models.events import GenericCloudEvent + +from .helpers import wait_until + + +def _recording(topic: str, seen: list[tuple[Any, Any]], fail_first: bool) -> type: + class Recording(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return [topic] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> None: + seen.append((context.get("nats_delivery_attempt"), context.get("nats_max_deliver"))) + if fail_first and len(seen) == 1: + raise RetryableHandlerError(status="retry", reason="first attempt fails on purpose") + return None + + return Recording + + +def _event() -> bytes: + return GenericCloudEvent(id=str(uuid.uuid4()), source="integration-test", type="orders.created", data={}).model_dump_json().encode() + + +class TestTheAttemptInTheHandlerContext: + async def test_a_redelivered_message_shows_attempt_2(self, nats_app: Any, jetstream: JetStreamContext, subject_prefix: str) -> None: + topic = f"{subject_prefix}.orders.created" + seen: list[tuple[Any, Any]] = [] + async with nats_app(_recording(topic, seen, fail_first=True)): + await jetstream.publish(topic, _event()) + await wait_until(lambda: len(seen) >= 2, timeout=15, description="the redelivery after the nak") + assert seen == [(1, 3), (2, 3)] + + async def test_control_a_first_delivery_shows_attempt_1(self, nats_app: Any, jetstream: JetStreamContext, subject_prefix: str) -> None: + topic = f"{subject_prefix}.orders.created" + seen: list[tuple[Any, Any]] = [] + async with nats_app(_recording(topic, seen, fail_first=False)): + await jetstream.publish(topic, _event()) + await wait_until(lambda: bool(seen), timeout=10, description="the delivery") + assert seen == [(1, 3)] diff --git a/tests/integration/test_named_connections.py b/tests/integration/test_named_connections.py index cf688575..c70820aa 100644 --- a/tests/integration/test_named_connections.py +++ b/tests/integration/test_named_connections.py @@ -23,6 +23,7 @@ import pytest from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.errors import RetryableHandlerError from blueprint.agents.models.events import GenericCloudEvent from .connection_source import SCOPE, SOURCES, binding_for, stream_for, subject_prefix_for @@ -196,6 +197,39 @@ async def termed() -> bool: await poll_until(termed, timeout=10, description="the rejected delivery to be settled for good") +class TestTheAttemptOnANamedConnection: + async def test_a_redelivery_shows_attempt_2_and_the_bindings_limit( + self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str + ) -> None: + """The binding's max_deliver (3 in connection_source.binding_for), not the agent's own key.""" + agent = f"risk_{subject_prefix}" + await operator(["A"], {agent: ["risk.>"]}) + seen: list[tuple[Any, Any]] = [] + + class FailsOnce(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return ["risk.>"] + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> None: + seen.append((context.get("nats_delivery_attempt"), context.get("nats_max_deliver"))) + if len(seen) == 1: + raise RetryableHandlerError(status="retry", reason="first attempt fails on purpose") + + async with settings_group(settings(accounts_url, subject_prefix, ["A"]), {agent: FailsOnce}, named=1): + await publish(accounts_url, subject_prefix, "A", "risk.created") + await wait_until(lambda: len(seen) >= 2, timeout=15, description="the redelivery after the nak") + assert seen == [(1, 3), (2, 3)] + + class TestClaims: async def test_an_unclaimed_subject_fails_startup( self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str diff --git a/tests/unit/agents/clients/TESTS.md b/tests/unit/agents/clients/TESTS.md index 0f6b6bdd..c4a36d0b 100644 --- a/tests/unit/agents/clients/TESTS.md +++ b/tests/unit/agents/clients/TESTS.md @@ -14,6 +14,7 @@ Test coverage for `src/blueprint/agents/clients/`. | `ai/test_vllm_client.py` | `VLLMClient` | Same shape as OpenAI; additionally verifies `base_url`/`api_key` forwarding to `AsyncOpenAI` | | `io/test_dapr_client.py` | `DaprClient` | `_is_connected`, `connect`/`close`, `subscribe` (no-op), `publish` (URL, headers, routing key, pubsub name), `health_check` | | `io/test_nats_client.py` | `NATSClient` | `__init__` defaults, `_is_connected` variants, `connect` (Core + JetStream), `close`, `publish`, `health_check` | +| `io/test_nats_connection_source.py` | `NATSClient` with a `ConnectionSource` | Loading the source, `ConnectionSpec`, planning bindings (claims, hybrid mode, result publishing refused), runs from named connections (run scope, validation, isolation, default connection unchanged), the handler context (`nats_connection`), the delivery attempt (named run: attempt 1 and 2 with the binding's `max_deliver`; default connection: `nats_max_deliver` unset -> `None`; no JetStream metadata -> no attempt; both keys in the handler context), shutdown. *Earlier coverage was not itemised here.* | `IOClientBase` has no logic and has no test file. diff --git a/tests/unit/agents/clients/io/test_nats_connection_source.py b/tests/unit/agents/clients/io/test_nats_connection_source.py index 4e89ebf4..e7a88304 100644 --- a/tests/unit/agents/clients/io/test_nats_connection_source.py +++ b/tests/unit/agents/clients/io/test_nats_connection_source.py @@ -15,9 +15,12 @@ from blueprint.agents.clients.io.nats_connections import ( ConnectionSpec, JetStreamBinding, + DeliveryAttempt, current_connection, + current_delivery, load_connection_source, mark_connection, + mark_delivery, ) from blueprint.agents.io.api.eventing.nats import NatsEventing from blueprint.agents.models.events import CloudEvent @@ -324,6 +327,87 @@ async def from_named() -> None: assert captured[1]["nats_topic"] == "risk.>" +class TestTheDeliveryAttempt: + """Which attempt a JetStream delivery is, and the consumer's limit -- on every connection.""" + + async def test_a_named_run_knows_its_attempt_and_the_bindings_limit( + self, nats_client: NATSClient, mock_nats_core: MagicMock, cloud_event: CloudEvent + ) -> None: + seen: list[DeliveryAttempt | None] = [] + + async def callback(event: CloudEvent, subject: str) -> None: + seen.append(current_delivery()) + + await _subscribed(nats_client, FakeSource({"A": _binding("A", "risk.>")}), ("risk.>",)) + nats_client._named[0].topic_callbacks["risk.>"] = callback + binding, handler = await _bound_handler(nats_client, mock_nats_core, "A") + first = _delivery(cloud_event, "t.A.risk.created") + again = _delivery(cloud_event, "t.A.risk.created") + again.metadata.num_delivered = 2 + await _deliver(binding, handler, first) + await _deliver(binding, handler, again) + assert seen == [DeliveryAttempt(attempt=1, max_deliver=5), DeliveryAttempt(attempt=2, max_deliver=5)] + + async def test_the_default_connection_carries_nats_max_deliver_or_none( + self, nats_client: NATSClient, mock_nats_core: MagicMock, cloud_event: CloudEvent + ) -> None: + """Unset nats_max_deliver is the server's unlimited default: None, not a number.""" + seen: list[DeliveryAttempt | None] = [] + + async def callback(event: CloudEvent, subject: str) -> None: + seen.append(current_delivery()) + + nats_client._nats_client = mock_nats_core + nats_client._client = mock_nats_core + await nats_client._subscribe_one("risk.>", callback) + handler = mock_nats_core.subscribe.await_args.kwargs["cb"] + msg = _delivery(cloud_event, "risk.created") + msg.metadata.num_delivered = 3 + await handler(msg) + await asyncio.gather(*list(nats_client._runs)) + assert seen == [DeliveryAttempt(attempt=3, max_deliver=None)] + + async def test_a_delivery_without_jetstream_metadata_has_no_attempt( + self, nats_client: NATSClient, mock_nats_core: MagicMock, cloud_event: CloudEvent + ) -> None: + """Core NATS does not redeliver: no attempt to report, rather than a made-up 1.""" + seen: list[DeliveryAttempt | None] = [] + + async def callback(event: CloudEvent, subject: str) -> None: + seen.append(current_delivery()) + + nats_client._nats_client = mock_nats_core + nats_client._client = mock_nats_core + await nats_client._subscribe_one("risk.>", callback) + handler = mock_nats_core.subscribe.await_args.kwargs["cb"] + msg = _delivery(cloud_event, "risk.created") + type(msg).metadata = property(lambda self: (_ for _ in ()).throw(ValueError("not a JetStream message"))) + await handler(msg) + await asyncio.gather(*list(nats_client._runs)) + assert seen == [None] + + async def test_the_attempt_reaches_the_handler_context_as_two_keys(self) -> None: + eventing = NatsEventing.__new__(NatsEventing) + captured: list[dict] = [] + + async def process(event: Any, context: dict, topic: str) -> Any: + captured.append(dict(context)) + return MagicMock() + + eventing._process_cloud_event = process # type: ignore[method-assign] + callback = eventing._make_event_callback("risk.>") + + async def jetstream_run() -> None: + mark_delivery(DeliveryAttempt(attempt=5, max_deliver=5)) + await callback(MagicMock(), "risk.created") + + await asyncio.create_task(callback(MagicMock(), "risk.created"), context=contextvars.Context()) + await asyncio.create_task(jetstream_run(), context=contextvars.Context()) + assert "nats_delivery_attempt" not in captured[0] and "nats_max_deliver" not in captured[0] + assert captured[1]["nats_delivery_attempt"] == 5 + assert captured[1]["nats_max_deliver"] == 5 + + class TestShutdown: async def test_close_drains_and_closes_every_named_link(self, nats_client: NATSClient, mock_nats_core: MagicMock) -> None: await _subscribed(nats_client, FakeSource({"A": _binding("A", "risk.>"), "B": _binding("B", "risk.>")}), ("risk.>",)) From 0b335ae1e3a1dda11721670ca6c067ad4857f58d Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 19:00:59 +0200 Subject: [PATCH 096/133] docs(plans): step 6 inventory -- examples fixed, named-connection example, open points Co-Authored-By: Claude Opus 5 (1M context) --- ...10-15-named-connections-step6-inventory.md | 25 ++++++++++++------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/docs/plans/2026-10-15-named-connections-step6-inventory.md b/docs/plans/2026-10-15-named-connections-step6-inventory.md index 78c164db..502d5526 100644 --- a/docs/plans/2026-10-15-named-connections-step6-inventory.md +++ b/docs/plans/2026-10-15-named-connections-step6-inventory.md @@ -54,17 +54,24 @@ changed or why nothing was, and what is still open. Checked against the code on - Grep for removed APIs (`with_config(`, `with_api(`, `with_prompt_file`, `register_routes(`, `with_agent("name", Cls)`, `AgentBuilder(config` in docs): only plans and changelogs remain. +## Done after the first pass (2026-10-15) + +- `webhook_relay` and `order_event_pipeline`: one handler per event type, one service call + (`46d5db4`, `d698836`); `document_summarizer` without `assert` (`df8c3f3`). +- The named-connection example `examples/site_readings` (`639f2fa`), run live against a broker with + accounts. +- Spec sec. 7.2 now matches the WARNING for an event no handler takes (`b81d5b9`, own commit). +- `nats_delivery_attempt` / `nats_max_deliver` in the handler context (`7e90ab4`). + ## Open -- **A named-connection example** (`order_event_pipeline` or a new one with a source and two - connections) is not written. -- **The examples' handlers do not follow the new handler rules:** `webhook_relay`'s three handlers - hold the logic themselves, `order_event_pipeline`'s call two service methods each. Only `main.py` - was changed. -- **Spec sec. 7.2 vs code:** the spec says an unmatched event MUST NOT be logged at WARNING; - `HandlerChain._dispatch` logs "No handler processed event" at WARNING. Kept, as decided with D11 - ("no handler at all keeps the WARNING") -- one of the two should change. +- **Model file names differ:** the template scaffolds `dto.py` / `domain_models.py` / `mapper.py`; + the examples use `schemas.py` (+ `domain.py` where there are handlers). `document_summarizer`, + `health_monitor` and `inventory_api` have no handlers and keep one `schemas.py`; their APIs pass + request DTOs to the service. +- **Pre-existing integration failure:** `test_acknowledgement_lifecycle.py::TestARetryableFailureComesBack::test_the_broker_counts_it_as_a_redelivery` + fails on the unchanged code too (control run 2026-10-15). - **Not checked:** the untracked specs `2026-09-23-dynamic-subscriptions.md`, `2026-09-24-handler-time-bounds.md` (sec. 4.5) and `2026-09-25-config-key-registry.md` (not in the repository); ADRs (owned outside the repository); `asbs docs` output beyond the files above. -- The examples were started on the Windows host against a broker in WSL, not inside WSL. +- The examples were started on the Windows host against brokers in WSL Docker, not inside WSL. From a9e30559758b9b4a3989e2bcadc820f686ee5f5e Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 19:06:47 +0200 Subject: [PATCH 097/133] refactor(examples): APIs translate DTOs, services see domain models only (SVC-01) document_summarizer: the API maps DocumentRequest to a Document and the service returns a SummaryRecord the API turns into SummarizeResponse. inventory_api: the API maps CreateProductRequest/UpdateProductRequest to NewProduct/ProductChanges and builds the ProductSearchResult; the service returns domain objects. Models split into dto.py and domain_models.py, the template's names. health_monitor: schemas.py -> domain_models.py (no request DTOs) and the scheduler makes one call, MonitorService.run_checks(). Co-Authored-By: Claude Opus 5 (1M context) --- .../document_summarizer/src/api/routes.py | 12 +++-- examples/document_summarizer/src/main.py | 2 +- .../models/{schemas.py => domain_models.py} | 18 +++---- .../document_summarizer/src/models/dto.py | 19 ++++++++ .../src/services/summarizer_service.py | 26 +++++----- .../tests/test_summarizer_service.py | 8 ++-- examples/health_monitor/src/api/routes.py | 2 +- .../models/{schemas.py => domain_models.py} | 0 .../src/schedulers/health_check_scheduler.py | 4 +- .../src/services/monitor_service.py | 9 +++- .../tests/test_monitor_service.py | 14 +++++- .../health_monitor/tests/test_schedulers.py | 14 ++++-- examples/inventory_api/src/api/routes.py | 22 +++------ .../models/{schemas.py => domain_models.py} | 19 +++----- examples/inventory_api/src/models/dto.py | 40 ++++++++++++++++ .../src/services/inventory_service.py | 28 +++++------ .../tests/test_inventory_service.py | 48 +++++++++---------- .../models/{domain.py => domain_models.py} | 0 .../src/models/{schemas.py => dto.py} | 0 .../models/{domain.py => domain_models.py} | 0 .../src/models/{schemas.py => dto.py} | 0 .../models/{domain.py => domain_models.py} | 0 .../src/models/{schemas.py => dto.py} | 0 23 files changed, 173 insertions(+), 112 deletions(-) rename examples/document_summarizer/src/models/{schemas.py => domain_models.py} (54%) create mode 100644 examples/document_summarizer/src/models/dto.py rename examples/health_monitor/src/models/{schemas.py => domain_models.py} (100%) rename examples/inventory_api/src/models/{schemas.py => domain_models.py} (59%) create mode 100644 examples/inventory_api/src/models/dto.py rename examples/order_event_pipeline/src/models/{domain.py => domain_models.py} (100%) rename examples/order_event_pipeline/src/models/{schemas.py => dto.py} (100%) rename examples/site_readings/src/models/{domain.py => domain_models.py} (100%) rename examples/site_readings/src/models/{schemas.py => dto.py} (100%) rename examples/webhook_relay/src/models/{domain.py => domain_models.py} (100%) rename examples/webhook_relay/src/models/{schemas.py => dto.py} (100%) diff --git a/examples/document_summarizer/src/api/routes.py b/examples/document_summarizer/src/api/routes.py index 3284f7aa..20c735af 100644 --- a/examples/document_summarizer/src/api/routes.py +++ b/examples/document_summarizer/src/api/routes.py @@ -6,7 +6,8 @@ from blueprint.agents.io.api.rest_api_base import RestApiBase -from src.models.schemas import DocumentRequest, SummarizeResponse +from src.models.domain_models import Document +from src.models.dto import DocumentRequest, SummarizeResponse from src.services.summarizer_service import SummarizerService logger = logging.getLogger(__name__) @@ -35,7 +36,8 @@ async def on_shutdown(self) -> None: ) async def summarize_document(self, request: DocumentRequest) -> SummarizeResponse: """Accept a document and return a structured summary.""" - return await self._service.summarize(request) + record = await self._service.summarize(Document(content=request.content, title=request.title)) + return SummarizeResponse(document_id=record.document_id, summary=record.summary) @RestApiBase.get( "/summaries/{document_id}", @@ -45,7 +47,7 @@ async def summarize_document(self, request: DocumentRequest) -> SummarizeRespons ) async def get_summary(self, document_id: str) -> SummarizeResponse: """Return a previously generated summary by its document ID.""" - result = await self._service.get_summary(document_id) - if result is None: + record = await self._service.get_summary(document_id) + if record is None: raise HTTPException(status_code=404, detail=f"Summary not found for document_id={document_id}") - return result + return SummarizeResponse(document_id=record.document_id, summary=record.summary) diff --git a/examples/document_summarizer/src/main.py b/examples/document_summarizer/src/main.py index fc81c522..de7c89e8 100644 --- a/examples/document_summarizer/src/main.py +++ b/examples/document_summarizer/src/main.py @@ -12,7 +12,7 @@ from blueprint.agents import AgentBuilder, AppBuilder, Config from src.api.routes import SummarizerApi -from src.models.schemas import DocumentSummary +from src.models.domain_models import DocumentSummary from src.services.summarizer_service import SummarizerService from src.tools.text_tools import extract_metadata, word_count diff --git a/examples/document_summarizer/src/models/schemas.py b/examples/document_summarizer/src/models/domain_models.py similarity index 54% rename from examples/document_summarizer/src/models/schemas.py rename to examples/document_summarizer/src/models/domain_models.py index 4d2cbb67..e831ecbe 100644 --- a/examples/document_summarizer/src/models/schemas.py +++ b/examples/document_summarizer/src/models/domain_models.py @@ -1,13 +1,13 @@ -"""Pydantic models for the document summarizer service.""" +"""Domain models: what SummarizerService works with. No request DTO reaches the service.""" from pydantic import BaseModel, Field -class DocumentRequest(BaseModel): - """Request payload for document summarization.""" +class Document(BaseModel): + """A document to summarize.""" - content: str = Field(..., description="The document text to summarize") - title: str | None = Field(default=None, description="Optional document title") + content: str + title: str | None = None class DocumentSummary(BaseModel): @@ -27,8 +27,8 @@ class DocumentSummary(BaseModel): ) -class SummarizeResponse(BaseModel): - """Response wrapper for a document summarization request.""" +class SummaryRecord(BaseModel): + """A summary and the content-derived id it is stored under.""" - document_id: str = Field(..., description="Unique identifier derived from content hash") - summary: DocumentSummary = Field(..., description="The structured document summary") + document_id: str + summary: DocumentSummary diff --git a/examples/document_summarizer/src/models/dto.py b/examples/document_summarizer/src/models/dto.py new file mode 100644 index 00000000..1898d067 --- /dev/null +++ b/examples/document_summarizer/src/models/dto.py @@ -0,0 +1,19 @@ +"""DTOs: the REST API's wire contract.""" + +from pydantic import BaseModel, Field + +from .domain_models import DocumentSummary + + +class DocumentRequest(BaseModel): + """Request payload for document summarization.""" + + content: str = Field(..., description="The document text to summarize") + title: str | None = Field(default=None, description="Optional document title") + + +class SummarizeResponse(BaseModel): + """Response payload for a summary.""" + + document_id: str = Field(..., description="Unique identifier derived from content hash") + summary: DocumentSummary = Field(..., description="The structured document summary") diff --git a/examples/document_summarizer/src/services/summarizer_service.py b/examples/document_summarizer/src/services/summarizer_service.py index ade77ac5..633ffc9c 100644 --- a/examples/document_summarizer/src/services/summarizer_service.py +++ b/examples/document_summarizer/src/services/summarizer_service.py @@ -8,7 +8,7 @@ from blueprint.agents.agent.agent_runtime import AgentRuntime from blueprint.agents.services.infrastructure.cache_service import CacheService -from src.models.schemas import DocumentRequest, DocumentSummary, SummarizeResponse +from src.models.domain_models import Document, DocumentSummary, SummaryRecord logger = logging.getLogger(__name__) @@ -37,31 +37,31 @@ async def on_shutdown(self) -> None: # Public API # ------------------------------------------------------------------ - async def summarize(self, request: DocumentRequest) -> SummarizeResponse: + async def summarize(self, document: Document) -> SummaryRecord: """Summarize a document, returning a cached result when available. Args: - request: The document to summarize. + document: The document to summarize. Returns: - A SummarizeResponse containing the document_id and structured summary. + The summary and the document_id it is stored under. """ - document_id = self._hash_content(request.content) + document_id = self._hash_content(document.content) # Check cache if self._cache is not None: cached: dict[str, Any] | None = self._cache.get(document_id, namespace=CACHE_NAMESPACE) if cached is not None: logger.info("Cache hit for document_id=%s", document_id) - return SummarizeResponse( + return SummaryRecord( document_id=document_id, summary=DocumentSummary(**cached), ) # Build user prompt - user_prompt = request.content - if request.title: - user_prompt = f"Title: {request.title}\n\n{request.content}" + user_prompt = document.content + if document.title: + user_prompt = f"Title: {document.title}\n\n{document.content}" # Run the agent if self._agent is None: @@ -78,16 +78,16 @@ async def summarize(self, request: DocumentRequest) -> SummarizeResponse: ) logger.info("Cached summary for document_id=%s", document_id) - return SummarizeResponse(document_id=document_id, summary=summary) + return SummaryRecord(document_id=document_id, summary=summary) - async def get_summary(self, document_id: str) -> SummarizeResponse | None: + async def get_summary(self, document_id: str) -> SummaryRecord | None: """Retrieve a previously cached summary by document ID. Args: document_id: The hash-based identifier of the document. Returns: - The cached SummarizeResponse, or None if not found. + The cached summary record, or None if not found. """ if self._cache is None: return None @@ -96,7 +96,7 @@ async def get_summary(self, document_id: str) -> SummarizeResponse | None: if cached is None: return None - return SummarizeResponse( + return SummaryRecord( document_id=document_id, summary=DocumentSummary(**cached), ) diff --git a/examples/document_summarizer/tests/test_summarizer_service.py b/examples/document_summarizer/tests/test_summarizer_service.py index 7c80328c..173a8ce4 100644 --- a/examples/document_summarizer/tests/test_summarizer_service.py +++ b/examples/document_summarizer/tests/test_summarizer_service.py @@ -6,7 +6,7 @@ import pytest -from src.models.schemas import DocumentRequest, DocumentSummary, SummarizeResponse +from src.models.domain_models import Document, DocumentSummary, SummaryRecord from src.services.summarizer_service import SummarizerService, CACHE_NAMESPACE @@ -21,8 +21,8 @@ def _make_summary() -> DocumentSummary: ) -def _make_request(content: str = "Some document content for testing.", title: str | None = None) -> DocumentRequest: - return DocumentRequest(content=content, title=title) +def _make_request(content: str = "Some document content for testing.", title: str | None = None) -> Document: + return Document(content=content, title=title) class TestSummarize: @@ -42,7 +42,7 @@ async def test_returns_summary_from_agent(self) -> None: request = _make_request() response = await service.summarize(request) - assert isinstance(response, SummarizeResponse) + assert isinstance(response, SummaryRecord) assert response.summary == summary assert len(response.document_id) == 16 service._agent.run.assert_awaited_once() diff --git a/examples/health_monitor/src/api/routes.py b/examples/health_monitor/src/api/routes.py index 7a9022d5..ee0fb0a5 100644 --- a/examples/health_monitor/src/api/routes.py +++ b/examples/health_monitor/src/api/routes.py @@ -8,7 +8,7 @@ from blueprint.agents.io.api.rest_api_base import RestApiBase -from src.models.schemas import EndpointStatus, UptimeReport +from src.models.domain_models import EndpointStatus, UptimeReport from src.services.monitor_service import MonitorService logger = logging.getLogger(__name__) diff --git a/examples/health_monitor/src/models/schemas.py b/examples/health_monitor/src/models/domain_models.py similarity index 100% rename from examples/health_monitor/src/models/schemas.py rename to examples/health_monitor/src/models/domain_models.py diff --git a/examples/health_monitor/src/schedulers/health_check_scheduler.py b/examples/health_monitor/src/schedulers/health_check_scheduler.py index c2b0502b..ea166440 100644 --- a/examples/health_monitor/src/schedulers/health_check_scheduler.py +++ b/examples/health_monitor/src/schedulers/health_check_scheduler.py @@ -35,9 +35,7 @@ async def tick(self) -> None: return logger.info("HealthCheckScheduler: running health checks") - results = await self._monitor_service.check_all_endpoints() - for result in results: - await self._monitor_service.store_result(result) + results = await self._monitor_service.run_checks() logger.info( "HealthCheckScheduler: completed %d checks, %d healthy", len(results), diff --git a/examples/health_monitor/src/services/monitor_service.py b/examples/health_monitor/src/services/monitor_service.py index f3de192d..1a31860e 100644 --- a/examples/health_monitor/src/services/monitor_service.py +++ b/examples/health_monitor/src/services/monitor_service.py @@ -11,7 +11,7 @@ from blueprint.agents.services.service_base import ServiceBase from blueprint.agents.services.infrastructure.cache_service import CacheService -from src.models.schemas import EndpointConfig, EndpointStatus, HealthResult, UptimeReport +from src.models.domain_models import EndpointConfig, EndpointStatus, HealthResult, UptimeReport logger = logging.getLogger(__name__) @@ -99,6 +99,13 @@ async def check_all_endpoints(self) -> list[HealthResult]: results.append(result) return results + async def run_checks(self) -> list[HealthResult]: + """Check every endpoint and store each result: the one method the scheduler calls.""" + results = await self.check_all_endpoints() + for result in results: + await self.store_result(result) + return results + async def store_result(self, result: HealthResult) -> None: """Persist a health-check result and update the endpoint status counters.""" if self._cache is None: diff --git a/examples/health_monitor/tests/test_monitor_service.py b/examples/health_monitor/tests/test_monitor_service.py index 88dde920..f7532196 100644 --- a/examples/health_monitor/tests/test_monitor_service.py +++ b/examples/health_monitor/tests/test_monitor_service.py @@ -7,7 +7,7 @@ import pytest -from src.models.schemas import EndpointConfig, HealthResult +from src.models.domain_models import EndpointConfig, HealthResult from src.services.monitor_service import MonitorService @@ -223,3 +223,15 @@ async def test_report_overall_unhealthy(self, service: MonitorService) -> None: report = await service.generate_report() assert report.overall_healthy is False + + +class TestRunChecks: + @pytest.mark.asyncio + async def test_checks_every_endpoint_and_stores_each_result(self) -> None: + """The facade the scheduler calls: check, then store each result.""" + service = MonitorService.__new__(MonitorService) + results = [object(), object()] + service.check_all_endpoints = AsyncMock(return_value=results) # type: ignore[method-assign] + service.store_result = AsyncMock() # type: ignore[method-assign] + assert await service.run_checks() == results + assert service.store_result.await_count == 2 diff --git a/examples/health_monitor/tests/test_schedulers.py b/examples/health_monitor/tests/test_schedulers.py index bae3490a..54d63ac4 100644 --- a/examples/health_monitor/tests/test_schedulers.py +++ b/examples/health_monitor/tests/test_schedulers.py @@ -6,7 +6,7 @@ import pytest -from src.models.schemas import HealthResult, UptimeReport +from src.models.domain_models import HealthResult, UptimeReport from src.schedulers.health_check_scheduler import HealthCheckScheduler from src.schedulers.report_scheduler import ReportScheduler @@ -34,6 +34,12 @@ def mock_monitor_service() -> AsyncMock: ] ) svc.store_result = AsyncMock() + svc.run_checks = AsyncMock( + return_value=[ + _make_health_result("httpbin"), + _make_health_result("jsonplaceholder"), + ] + ) svc.generate_report = AsyncMock( return_value=UptimeReport( generated_at="2026-01-01T00:00:00+00:00", @@ -47,14 +53,14 @@ def mock_monitor_service() -> AsyncMock: class TestHealthCheckScheduler: @pytest.mark.asyncio async def test_tick_calls_check_and_store(self, mock_monitor_service: AsyncMock) -> None: - """tick() should call check_all_endpoints and store each result.""" + """tick() makes one service call: the service checks and stores.""" scheduler = HealthCheckScheduler.__new__(HealthCheckScheduler) scheduler._monitor_service = mock_monitor_service await scheduler.tick() - mock_monitor_service.check_all_endpoints.assert_awaited_once() - assert mock_monitor_service.store_result.await_count == 2 + mock_monitor_service.run_checks.assert_awaited_once() + mock_monitor_service.check_all_endpoints.assert_not_awaited() @pytest.mark.asyncio async def test_tick_skips_when_no_service(self) -> None: diff --git a/examples/inventory_api/src/api/routes.py b/examples/inventory_api/src/api/routes.py index 0add4ab0..1084a641 100644 --- a/examples/inventory_api/src/api/routes.py +++ b/examples/inventory_api/src/api/routes.py @@ -5,27 +5,16 @@ import logging from fastapi import HTTPException -from pydantic import BaseModel from blueprint.agents.io.api.rest_api_base import RestApiBase -from src.models.schemas import ( - CreateProductRequest, - Product, - ProductSearchResult, - UpdateProductRequest, -) +from src.models.domain_models import NewProduct, Product, ProductChanges +from src.models.dto import CreateProductRequest, ProductSearchResult, StockAdjustment, UpdateProductRequest from src.services.inventory_service import InventoryService logger = logging.getLogger(__name__) -class StockAdjustment(BaseModel): - """Request body for stock adjustment.""" - - quantity: int - - class InventoryApi(RestApiBase): """Product inventory CRUD endpoints.""" @@ -66,7 +55,8 @@ async def list_products(self, category: str | None = None) -> list[Product]: ) async def search_products(self, q: str) -> ProductSearchResult: """Search products by name or description.""" - return self.service.search_products(q) + matches = self.service.search_products(q) + return ProductSearchResult(products=matches, total=len(matches)) @RestApiBase.get( "/products/{product_id}", @@ -90,7 +80,7 @@ async def get_product(self, product_id: str) -> Product: ) async def create_product(self, request: CreateProductRequest) -> Product: """Create a new product.""" - return self.service.create_product(request) + return self.service.create_product(NewProduct(**request.model_dump())) @RestApiBase.put( "/products/{product_id}", @@ -100,7 +90,7 @@ async def create_product(self, request: CreateProductRequest) -> Product: ) async def update_product(self, product_id: str, request: UpdateProductRequest) -> Product: """Update an existing product.""" - product = self.service.update_product(product_id, request) + product = self.service.update_product(product_id, ProductChanges(**request.model_dump(exclude_unset=True))) if product is None: raise HTTPException(status_code=404, detail=f"Product {product_id} not found") return product diff --git a/examples/inventory_api/src/models/schemas.py b/examples/inventory_api/src/models/domain_models.py similarity index 59% rename from examples/inventory_api/src/models/schemas.py rename to examples/inventory_api/src/models/domain_models.py index 0f0a2977..1d6a5036 100644 --- a/examples/inventory_api/src/models/schemas.py +++ b/examples/inventory_api/src/models/domain_models.py @@ -1,8 +1,8 @@ -"""Pydantic models for the Inventory API.""" +"""Domain models: what InventoryService works with. No request DTO reaches the service.""" from __future__ import annotations -from datetime import datetime, UTC +from datetime import UTC, datetime from uuid import uuid4 from pydantic import BaseModel, Field @@ -20,8 +20,8 @@ class Product(BaseModel): created_at: datetime = Field(default_factory=lambda: datetime.now(UTC)) -class CreateProductRequest(BaseModel): - """Request body for creating a new product.""" +class NewProduct(BaseModel): + """A product to create: everything but the id and the timestamp, which the service assigns.""" name: str description: str @@ -30,18 +30,11 @@ class CreateProductRequest(BaseModel): category: str -class UpdateProductRequest(BaseModel): - """Request body for updating an existing product. All fields are optional.""" +class ProductChanges(BaseModel): + """The fields to change on a product; only the fields that are set are applied.""" name: str | None = None description: str | None = None price: float | None = None stock: int | None = None category: str | None = None - - -class ProductSearchResult(BaseModel): - """Response for product search queries.""" - - products: list[Product] - total: int diff --git a/examples/inventory_api/src/models/dto.py b/examples/inventory_api/src/models/dto.py new file mode 100644 index 00000000..ca5c7eee --- /dev/null +++ b/examples/inventory_api/src/models/dto.py @@ -0,0 +1,40 @@ +"""DTOs: the REST API's wire contract.""" + +from __future__ import annotations + +from pydantic import BaseModel + +from .domain_models import Product + + +class CreateProductRequest(BaseModel): + """Request body for creating a new product.""" + + name: str + description: str + price: float + stock: int + category: str + + +class UpdateProductRequest(BaseModel): + """Request body for updating an existing product. All fields are optional.""" + + name: str | None = None + description: str | None = None + price: float | None = None + stock: int | None = None + category: str | None = None + + +class StockAdjustment(BaseModel): + """Request body for stock adjustment.""" + + quantity: int + + +class ProductSearchResult(BaseModel): + """Response for product search queries.""" + + products: list[Product] + total: int diff --git a/examples/inventory_api/src/services/inventory_service.py b/examples/inventory_api/src/services/inventory_service.py index 73177117..2c287265 100644 --- a/examples/inventory_api/src/services/inventory_service.py +++ b/examples/inventory_api/src/services/inventory_service.py @@ -9,12 +9,7 @@ from blueprint.agents.services.service_base import ServiceBase from blueprint.agents.services.infrastructure.cache_service import CacheService -from src.models.schemas import ( - CreateProductRequest, - Product, - ProductSearchResult, - UpdateProductRequest, -) +from src.models.domain_models import NewProduct, Product, ProductChanges logger = logging.getLogger(__name__) @@ -65,15 +60,15 @@ def get_product(self, product_id: str) -> Product | None: ) return product - def create_product(self, request: CreateProductRequest) -> Product: + def create_product(self, new: NewProduct) -> Product: """Create a new product with a generated UUID and timestamp.""" product = Product( id=str(uuid4()), - name=request.name, - description=request.description, - price=request.price, - stock=request.stock, - category=request.category, + name=new.name, + description=new.description, + price=new.price, + stock=new.stock, + category=new.category, created_at=datetime.now(UTC), ) self._products[product.id] = product @@ -88,13 +83,13 @@ def create_product(self, request: CreateProductRequest) -> Product: logger.info("Created product %s (%s)", product.id, product.name) return product - def update_product(self, product_id: str, request: UpdateProductRequest) -> Product | None: + def update_product(self, product_id: str, changes: ProductChanges) -> Product | None: """Update an existing product. Returns None if not found.""" product = self._products.get(product_id) if product is None: return None - update_data = request.model_dump(exclude_unset=True) + update_data = changes.model_dump(exclude_unset=True) updated = product.model_copy(update=update_data) self._products[product_id] = updated @@ -121,11 +116,10 @@ def delete_product(self, product_id: str) -> bool: logger.info("Deleted product %s", product_id) return True - def search_products(self, query: str) -> ProductSearchResult: + def search_products(self, query: str) -> list[Product]: """Search products by name or description (case-insensitive).""" q = query.lower() - matches = [p for p in self._products.values() if q in p.name.lower() or q in p.description.lower()] - return ProductSearchResult(products=matches, total=len(matches)) + return [p for p in self._products.values() if q in p.name.lower() or q in p.description.lower()] def update_stock(self, product_id: str, quantity: int) -> Product | None: """Adjust the stock level of a product by the given quantity. diff --git a/examples/inventory_api/tests/test_inventory_service.py b/examples/inventory_api/tests/test_inventory_service.py index 954412d2..67ac135e 100644 --- a/examples/inventory_api/tests/test_inventory_service.py +++ b/examples/inventory_api/tests/test_inventory_service.py @@ -7,7 +7,7 @@ import pytest -from src.models.schemas import CreateProductRequest, UpdateProductRequest +from src.models.domain_models import NewProduct, ProductChanges from src.services.inventory_service import InventoryService @@ -42,8 +42,8 @@ def service(mock_cache: MagicMock) -> InventoryService: @pytest.fixture -def sample_request() -> CreateProductRequest: - return CreateProductRequest( +def sample_request() -> NewProduct: + return NewProduct( name="Widget", description="A useful widget", price=9.99, @@ -53,7 +53,7 @@ def sample_request() -> CreateProductRequest: class TestCreateProduct: - def test_create_returns_product_with_id(self, service: InventoryService, sample_request: CreateProductRequest) -> None: + def test_create_returns_product_with_id(self, service: InventoryService, sample_request: NewProduct) -> None: product = service.create_product(sample_request) assert product.id is not None assert product.name == "Widget" @@ -62,13 +62,13 @@ def test_create_returns_product_with_id(self, service: InventoryService, sample_ assert product.category == "tools" assert product.created_at is not None - def test_create_stores_product(self, service: InventoryService, sample_request: CreateProductRequest) -> None: + def test_create_stores_product(self, service: InventoryService, sample_request: NewProduct) -> None: product = service.create_product(sample_request) assert service.get_product(product.id) is not None class TestGetProduct: - def test_get_existing_product(self, service: InventoryService, sample_request: CreateProductRequest) -> None: + def test_get_existing_product(self, service: InventoryService, sample_request: NewProduct) -> None: product = service.create_product(sample_request) fetched = service.get_product(product.id) assert fetched is not None @@ -79,9 +79,9 @@ def test_get_nonexistent_product(self, service: InventoryService) -> None: class TestUpdateProduct: - def test_update_existing_product(self, service: InventoryService, sample_request: CreateProductRequest) -> None: + def test_update_existing_product(self, service: InventoryService, sample_request: NewProduct) -> None: product = service.create_product(sample_request) - update = UpdateProductRequest(price=19.99, name="Super Widget") + update = ProductChanges(price=19.99, name="Super Widget") updated = service.update_product(product.id, update) assert updated is not None assert updated.price == 19.99 @@ -89,12 +89,12 @@ def test_update_existing_product(self, service: InventoryService, sample_request assert updated.description == "A useful widget" # unchanged def test_update_nonexistent_product(self, service: InventoryService) -> None: - update = UpdateProductRequest(price=5.0) + update = ProductChanges(price=5.0) assert service.update_product("nonexistent-id", update) is None class TestDeleteProduct: - def test_delete_existing_product(self, service: InventoryService, sample_request: CreateProductRequest) -> None: + def test_delete_existing_product(self, service: InventoryService, sample_request: NewProduct) -> None: product = service.create_product(sample_request) assert service.delete_product(product.id) is True assert service.get_product(product.id) is None @@ -104,29 +104,29 @@ def test_delete_nonexistent_product(self, service: InventoryService) -> None: class TestSearchProducts: - def test_search_by_name(self, service: InventoryService, sample_request: CreateProductRequest) -> None: + def test_search_by_name(self, service: InventoryService, sample_request: NewProduct) -> None: service.create_product(sample_request) result = service.search_products("widget") - assert result.total == 1 - assert result.products[0].name == "Widget" + assert len(result) == 1 + assert result[0].name == "Widget" - def test_search_by_description(self, service: InventoryService, sample_request: CreateProductRequest) -> None: + def test_search_by_description(self, service: InventoryService, sample_request: NewProduct) -> None: service.create_product(sample_request) result = service.search_products("useful") - assert result.total == 1 + assert len(result) == 1 - def test_search_no_match(self, service: InventoryService, sample_request: CreateProductRequest) -> None: + def test_search_no_match(self, service: InventoryService, sample_request: NewProduct) -> None: service.create_product(sample_request) result = service.search_products("nonexistent") - assert result.total == 0 - assert result.products == [] + assert len(result) == 0 + assert result == [] class TestListProducts: - def test_list_all(self, service: InventoryService, sample_request: CreateProductRequest) -> None: + def test_list_all(self, service: InventoryService, sample_request: NewProduct) -> None: service.create_product(sample_request) service.create_product( - CreateProductRequest( + NewProduct( name="Gadget", description="A handy gadget", price=14.99, @@ -137,10 +137,10 @@ def test_list_all(self, service: InventoryService, sample_request: CreateProduct products = service.list_products() assert len(products) == 2 - def test_list_filtered_by_category(self, service: InventoryService, sample_request: CreateProductRequest) -> None: + def test_list_filtered_by_category(self, service: InventoryService, sample_request: NewProduct) -> None: service.create_product(sample_request) service.create_product( - CreateProductRequest( + NewProduct( name="Gadget", description="A handy gadget", price=14.99, @@ -154,13 +154,13 @@ def test_list_filtered_by_category(self, service: InventoryService, sample_reque class TestUpdateStock: - def test_increase_stock(self, service: InventoryService, sample_request: CreateProductRequest) -> None: + def test_increase_stock(self, service: InventoryService, sample_request: NewProduct) -> None: product = service.create_product(sample_request) updated = service.update_stock(product.id, 25) assert updated is not None assert updated.stock == 125 - def test_decrease_stock(self, service: InventoryService, sample_request: CreateProductRequest) -> None: + def test_decrease_stock(self, service: InventoryService, sample_request: NewProduct) -> None: product = service.create_product(sample_request) updated = service.update_stock(product.id, -10) assert updated is not None diff --git a/examples/order_event_pipeline/src/models/domain.py b/examples/order_event_pipeline/src/models/domain_models.py similarity index 100% rename from examples/order_event_pipeline/src/models/domain.py rename to examples/order_event_pipeline/src/models/domain_models.py diff --git a/examples/order_event_pipeline/src/models/schemas.py b/examples/order_event_pipeline/src/models/dto.py similarity index 100% rename from examples/order_event_pipeline/src/models/schemas.py rename to examples/order_event_pipeline/src/models/dto.py diff --git a/examples/site_readings/src/models/domain.py b/examples/site_readings/src/models/domain_models.py similarity index 100% rename from examples/site_readings/src/models/domain.py rename to examples/site_readings/src/models/domain_models.py diff --git a/examples/site_readings/src/models/schemas.py b/examples/site_readings/src/models/dto.py similarity index 100% rename from examples/site_readings/src/models/schemas.py rename to examples/site_readings/src/models/dto.py diff --git a/examples/webhook_relay/src/models/domain.py b/examples/webhook_relay/src/models/domain_models.py similarity index 100% rename from examples/webhook_relay/src/models/domain.py rename to examples/webhook_relay/src/models/domain_models.py diff --git a/examples/webhook_relay/src/models/schemas.py b/examples/webhook_relay/src/models/dto.py similarity index 100% rename from examples/webhook_relay/src/models/schemas.py rename to examples/webhook_relay/src/models/dto.py From 85f1ea1fb7139df319653725884d6ad821259f9c Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 19:06:48 +0200 Subject: [PATCH 098/133] refactor(examples): model files use the template's names, dto.py and domain_models.py schemas.py -> dto.py and domain.py -> domain_models.py in order_event_pipeline, webhook_relay and site_readings, imports and READMEs updated -- examples get copied, so they use the names asbs scaffolds. Co-Authored-By: Claude Opus 5 (1M context) --- examples/order_event_pipeline/README.md | 4 ++-- examples/order_event_pipeline/src/handlers/order_handler.py | 4 ++-- examples/order_event_pipeline/src/services/order_service.py | 2 +- examples/order_event_pipeline/tests/test_handlers.py | 2 +- examples/order_event_pipeline/tests/test_order_service.py | 2 +- examples/site_readings/README.md | 4 ++-- examples/site_readings/src/handlers/reading_handler.py | 4 ++-- examples/site_readings/src/services/reading_service.py | 2 +- examples/site_readings/tests/test_reading_flow.py | 2 +- examples/webhook_relay/README.md | 4 ++-- examples/webhook_relay/src/api/routes.py | 2 +- examples/webhook_relay/src/handlers/webhook_handler.py | 4 ++-- examples/webhook_relay/src/services/webhook_service.py | 2 +- examples/webhook_relay/tests/test_handlers.py | 2 +- examples/webhook_relay/tests/test_webhook_service.py | 2 +- 15 files changed, 21 insertions(+), 21 deletions(-) diff --git a/examples/order_event_pipeline/README.md b/examples/order_event_pipeline/README.md index 70664798..eda4106e 100644 --- a/examples/order_event_pipeline/README.md +++ b/examples/order_event_pipeline/README.md @@ -30,8 +30,8 @@ order_event_pipeline/ src/ main.py # Application entry point models/ - schemas.py # DTO: OrderPayload (event data) - domain.py # Domain: Order, ValidationError, OrderOutcome + dto.py # DTO: OrderPayload (event data) + domain_models.py # Domain: Order, ValidationError, OrderOutcome handlers/ order_handler.py # order.created -> OrderService.process_order() services/ diff --git a/examples/order_event_pipeline/src/handlers/order_handler.py b/examples/order_event_pipeline/src/handlers/order_handler.py index d4eada72..aa2abf0a 100644 --- a/examples/order_event_pipeline/src/handlers/order_handler.py +++ b/examples/order_event_pipeline/src/handlers/order_handler.py @@ -6,8 +6,8 @@ from blueprint.agents.handler.event_handler_base import EventHandlerBase from blueprint.agents.models.events import GenericCloudEvent, HandlerResult -from ..models.domain import Order -from ..models.schemas import OrderPayload +from ..models.domain_models import Order +from ..models.dto import OrderPayload from ..services.order_service import OrderService logger = logging.getLogger(__name__) diff --git a/examples/order_event_pipeline/src/services/order_service.py b/examples/order_event_pipeline/src/services/order_service.py index 268bcc7d..a60ea55c 100644 --- a/examples/order_event_pipeline/src/services/order_service.py +++ b/examples/order_event_pipeline/src/services/order_service.py @@ -6,7 +6,7 @@ from blueprint.agents.services.service_base import ServiceBase from blueprint.agents.services.infrastructure.cache_service import CacheService -from ..models.domain import Order, OrderOutcome, ValidationError +from ..models.domain_models import Order, OrderOutcome, ValidationError logger = logging.getLogger(__name__) diff --git a/examples/order_event_pipeline/tests/test_handlers.py b/examples/order_event_pipeline/tests/test_handlers.py index c5f22e6e..3f013e4a 100644 --- a/examples/order_event_pipeline/tests/test_handlers.py +++ b/examples/order_event_pipeline/tests/test_handlers.py @@ -7,7 +7,7 @@ from blueprint.agents.models.events import GenericCloudEvent from src.handlers.order_handler import OrderHandler -from src.models.domain import Order, OrderOutcome +from src.models.domain_models import Order, OrderOutcome def _make_event(data: dict, event_type: str = "order.created") -> GenericCloudEvent: diff --git a/examples/order_event_pipeline/tests/test_order_service.py b/examples/order_event_pipeline/tests/test_order_service.py index 5eedccee..1381ee06 100644 --- a/examples/order_event_pipeline/tests/test_order_service.py +++ b/examples/order_event_pipeline/tests/test_order_service.py @@ -4,7 +4,7 @@ from unittest.mock import MagicMock -from src.models.domain import Order, OrderLine +from src.models.domain_models import Order, OrderLine from src.services.order_service import OrderService diff --git a/examples/site_readings/README.md b/examples/site_readings/README.md index 308004fd..f7d1e2d9 100644 --- a/examples/site_readings/README.md +++ b/examples/site_readings/README.md @@ -51,8 +51,8 @@ site_readings/ sites.py # per-run site settings, set by run_scope handlers/reading_handler.py services/reading_service.py - models/schemas.py # DTO: ReadingRecorded - models/domain.py # Reading, Alert + models/dto.py # DTO: ReadingRecorded + models/domain_models.py # Reading, Alert api/routes.py # GET /api/alerts deploy/ nats-accounts.conf # the example broker: one account per site, passwords from the environment diff --git a/examples/site_readings/src/handlers/reading_handler.py b/examples/site_readings/src/handlers/reading_handler.py index e73fa9b8..e892cb60 100644 --- a/examples/site_readings/src/handlers/reading_handler.py +++ b/examples/site_readings/src/handlers/reading_handler.py @@ -5,8 +5,8 @@ from blueprint.agents.handler.event_handler_base import EventHandlerBase from blueprint.agents.models.events import GenericCloudEvent, HandlerResult -from ..models.domain import Reading -from ..models.schemas import ReadingRecorded +from ..models.domain_models import Reading +from ..models.dto import ReadingRecorded from ..services.reading_service import ReadingService READING_RECORDED = "reading.recorded" diff --git a/examples/site_readings/src/services/reading_service.py b/examples/site_readings/src/services/reading_service.py index 1ffd1ded..3432fae4 100644 --- a/examples/site_readings/src/services/reading_service.py +++ b/examples/site_readings/src/services/reading_service.py @@ -5,7 +5,7 @@ from blueprint.agents.services.service_base import ServiceBase -from ..models.domain import Alert, Reading +from ..models.domain_models import Alert, Reading from ..sites import current_site logger = logging.getLogger(__name__) diff --git a/examples/site_readings/tests/test_reading_flow.py b/examples/site_readings/tests/test_reading_flow.py index a1309180..5af1591d 100644 --- a/examples/site_readings/tests/test_reading_flow.py +++ b/examples/site_readings/tests/test_reading_flow.py @@ -8,7 +8,7 @@ from blueprint.agents.models.events import GenericCloudEvent from src.handlers.reading_handler import ReadingHandler -from src.models.domain import Alert, Reading +from src.models.domain_models import Alert, Reading from src.services.reading_service import ReadingService from src.sites import SiteSettings, enter_site, leave_site diff --git a/examples/webhook_relay/README.md b/examples/webhook_relay/README.md index 955770e7..a6684abb 100644 --- a/examples/webhook_relay/README.md +++ b/examples/webhook_relay/README.md @@ -118,8 +118,8 @@ webhook_relay/ src/ main.py # AppBuilder wiring models/ - schemas.py # DTO: WebhookPayload (REST body and event data) - domain.py # Domain: IncomingWebhook, NormalizedEvent, RelayOutcome + dto.py # DTO: WebhookPayload (REST body and event data) + domain_models.py # Domain: IncomingWebhook, NormalizedEvent, RelayOutcome handlers/ webhook_handler.py # webhook.received -> WebhookService.relay() services/ diff --git a/examples/webhook_relay/src/api/routes.py b/examples/webhook_relay/src/api/routes.py index 98f0d511..84eff0d8 100644 --- a/examples/webhook_relay/src/api/routes.py +++ b/examples/webhook_relay/src/api/routes.py @@ -15,7 +15,7 @@ EventProcessingService, ) -from ..models.schemas import WebhookPayload +from ..models.dto import WebhookPayload from ..services.webhook_service import WebhookService logger = logging.getLogger(__name__) diff --git a/examples/webhook_relay/src/handlers/webhook_handler.py b/examples/webhook_relay/src/handlers/webhook_handler.py index fadf8f9d..ef664b01 100644 --- a/examples/webhook_relay/src/handlers/webhook_handler.py +++ b/examples/webhook_relay/src/handlers/webhook_handler.py @@ -7,8 +7,8 @@ from blueprint.agents.handler.event_handler_base import EventHandlerBase from blueprint.agents.models.events import GenericCloudEvent, HandlerResult -from ..models.domain import IncomingWebhook -from ..models.schemas import WebhookPayload +from ..models.domain_models import IncomingWebhook +from ..models.dto import WebhookPayload from ..services.webhook_service import WebhookService WEBHOOK_RECEIVED = "webhook.received" diff --git a/examples/webhook_relay/src/services/webhook_service.py b/examples/webhook_relay/src/services/webhook_service.py index 2e1f7374..96fc7354 100644 --- a/examples/webhook_relay/src/services/webhook_service.py +++ b/examples/webhook_relay/src/services/webhook_service.py @@ -9,7 +9,7 @@ from blueprint.agents.services.service_base import ServiceBase from blueprint.agents.services.infrastructure.cache_service import CacheService -from ..models.domain import IncomingWebhook, NormalizedEvent, RelayOutcome +from ..models.domain_models import IncomingWebhook, NormalizedEvent, RelayOutcome logger = logging.getLogger(__name__) diff --git a/examples/webhook_relay/tests/test_handlers.py b/examples/webhook_relay/tests/test_handlers.py index 0fbecdea..12e77ea0 100644 --- a/examples/webhook_relay/tests/test_handlers.py +++ b/examples/webhook_relay/tests/test_handlers.py @@ -11,7 +11,7 @@ from blueprint.agents.models.events import GenericCloudEvent, HandlerResult from src.handlers.webhook_handler import WebhookHandler -from src.models.domain import IncomingWebhook, RelayOutcome +from src.models.domain_models import IncomingWebhook, RelayOutcome from src.services.webhook_service import WebhookService # --------------------------------------------------------------------------- diff --git a/examples/webhook_relay/tests/test_webhook_service.py b/examples/webhook_relay/tests/test_webhook_service.py index 1af3d6fb..192d9b8f 100644 --- a/examples/webhook_relay/tests/test_webhook_service.py +++ b/examples/webhook_relay/tests/test_webhook_service.py @@ -5,7 +5,7 @@ from unittest.mock import MagicMock -from src.models.domain import IncomingWebhook, NormalizedEvent +from src.models.domain_models import IncomingWebhook, NormalizedEvent from src.services.webhook_service import WebhookService # --------------------------------------------------------------------------- From fee86fea318a42e706fdce8fcd35e9453daa9ec6 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 19:08:24 +0200 Subject: [PATCH 099/133] style(docs): end-of-file newline in the component naming plan Co-Authored-By: Claude Opus 5 (1M context) --- docs/plans/2026-04-01-component-naming-refactor.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plans/2026-04-01-component-naming-refactor.md b/docs/plans/2026-04-01-component-naming-refactor.md index 97c425dd..dadd4c3f 100644 --- a/docs/plans/2026-04-01-component-naming-refactor.md +++ b/docs/plans/2026-04-01-component-naming-refactor.md @@ -620,4 +620,4 @@ git commit -m "fix: address issues from integration testing" --- -Plan complete. Ready for subagent-driven execution. \ No newline at end of file +Plan complete. Ready for subagent-driven execution. From 851990a2d9d81e72abcdbfb0e13905a50c9e303f Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 19:08:57 +0200 Subject: [PATCH 100/133] docs(changelog): the examples and site_readings under Unreleased Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c47d085d..7e8d997c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -172,6 +172,9 @@ ### Added +- **`examples/site_readings`: named connections end to end.** One agent, two sites, each its own + NATS account, supplied by a `ConnectionSource` (claims, a per-connection subject prefix, `validate`, + `run_scope`), with the example broker, a provisioning script and offline tests. - **A JetStream run knows which attempt it is.** The handler context carries `nats_delivery_attempt` (1-based) and `nats_max_deliver` (`None` when unlimited) on the default and on named connections, so a service can close open work on the last attempt instead of leaving it open. Core NATS @@ -379,6 +382,11 @@ idempotency belongs to the service; handlers never call the LLM. The chain semantics are stated as the code has them: the first result that is not `None` ends the chain (the docs said a `HandlerResult` let later handlers run). +- **The examples follow the handler and service rules.** One handler per event type making one + service call (`webhook_relay`, `order_event_pipeline`), APIs that translate request DTOs into + domain models (`document_summarizer`, `inventory_api`), a scheduler with one service call + (`health_monitor`), no `assert` in production code, and the template's model file names + (`dto.py`, `domain_models.py`). - **`asbs validate` checks the NATS delivery keys** that otherwise fail only at startup: `nats_max_concurrent_runs`, `nats_extra_runs_per_process`, `nats_handler_timeout`, `nats_connections_readiness`, `nats_unclaimed_subjects`, and the form and module of From be1587812ff92cd1141d6542442f16f87f147728 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 15 Oct 2026 19:59:31 +0200 Subject: [PATCH 101/133] docs(plans): condense the feature changelog to decisions and outcomes The running record had grown to 604 KB, past check-added-large-files' 500 KB. It now keeps what each phase decided and produced, the compatibility pointer to CHANGELOG.md's Breaking list, and the open points that are still open (plus the overlapping-subjects broker gap that NATSClient's docstring refers to). The step-by-step history and walkthroughs are in git log. Co-Authored-By: Claude Opus 5 (1M context) --- ...26-08-28-multi-agent-grouping-changelog.md | 9166 +---------------- 1 file changed, 158 insertions(+), 9008 deletions(-) diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index cc623f47..d4e01838 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -4,9028 +4,178 @@ |---|---| | **Spec (normative)** | `docs/specs/2026-08-28-multi-agent-grouping.md` | | **Implementation plan** | `docs/plans/2026-08-28-multi-agent-grouping.md` | +| **Follow-up plans** | `docs/plans/2026-09-28-grouped-http-surface.md`, `docs/plans/2026-10-14-named-connections.md` | | **Branch** | `feature/multi-agent-namespaces` | -Running record of every change on this branch, in the order it landed, with the reasoning behind -it. It doubles as the pull-request description, so it is updated as part of each change rather -than reconstructed at the end. At release time a condensed entry goes into `CHANGELOG.md` under -`[Unreleased]`; this file keeps the detail that would not fit there. +The record of this branch: what each phase decided and what came out of it. It doubles as the +pull-request description. **The step-by-step history -- every change, its code walkthrough and its +measurements -- is in `git log` on this branch**; this file was condensed on 2026-10-15 (it had +grown past 600 KB). User-facing changes and every breaking change are in `CHANGELOG.md` under +`[Unreleased]`, which is the list to read before upgrading. --- ## What this feature does -Today one agent means one process, one port, one broker connection and one container image, so a -platform of 100 agents pays the ~154 MB Python and library baseline 100 times. This feature makes -**which agents share a process a deployment parameter rather than an architectural commitment.** +One agent used to mean one process, one port, one broker connection and one image, so a platform +of 100 agents paid the ~154 MB Python baseline 100 times. **Which agents share a process is now a +deployment parameter, not an architectural commitment.** Components carry an ambient +**namespace** (`""` by default, so nothing existing changes); a namespace owns its handlers, agent +runtimes, REST routes, AI client, thread pool, caches and broker connection, while the port and +the health endpoint stay shared. A group of one gives process isolation, a group of twenty the +shared-interpreter memory profile, and moving an agent between groups changes neither its +broker-side consumer identity nor its telemetry identity. + +--- + +## Decisions and outcomes, by phase + +**Spec and contracts.** Spec and phased plan extracted into the repo's conventions (`4233933`). +Acknowledgement contract: a normal return acks, an exception does not, `NO_HANDLER_FOUND` acks +(`b6ab1c9`). Selection and fan-out rules (spec sec. 7.7) with acceptance criteria (`13e4d28`, +`b94f60c`). + +**P0 -- transport lifecycle.** Managed whole-map `subscribe()`, background retry, resubscription on +reconnect, readiness gated on `subscriptions_ready` (`77af507`); in-flight handlers drain before +the connection closes (`585e58c`); an undecodable payload is told apart from a failed dispatch +(`3843abf`). Dapr declared topics actually subscribe (#81, `fac528b`). + +**P1 -- queue groups.** Core NATS subscriptions join a queue group derived from the agent, so a +second replica no longer processes every message again (`05083c8`). + +**P2 -- acknowledgement.** Both transports render one decision table (ack / nak / term); Dapr's +`NO_HANDLER_FOUND` answers `SUCCESS`, a critical error drops (`ce17f87`). Unmatched events are +counted (`blueprint.events.unhandled`). + +**P3 -- consumers.** `ack_wait`, `max_ack_pending`, `max_deliver` configurable and broker-enforced; +JetStream durables carry a deliver group; given-up messages are dead-lettered to +`.dead-letter` (`8ce9600`). Three stream/durable naming defects fixed on the way. + +**P4 -- deduplication.** Opt-in (`idempotency_enabled` + required `idempotency_ttl`), keyed on event +id and source, released on a failed dispatch; the scaffold and `asbs validate` make the author +decide; duplicates are counted apart (`d127843`). + +**P5 -- scheduling.** `scheduler_mode` is **required** (breaking): `"event"` takes the tick as an +event (the queue group picks one replica), `"in_process"` claims each tick in the cache +(`CacheService.claim`, atomic on both backends) so one replica runs it. Second-timer defect (#43) +and two scaffold defects fixed; publishing no longer requires consuming +(`event_publishing_enabled`) (`662f7b5`). + +**P6 -- one transport per namespace.** Clients belong to a namespace, register under a qualified +name and derive queue group and durable from it; connections are named +`namespace.group.pod` (never used broker-side, C1); one alphabet and one gate for namespace names +(`be5e489`). `/status/env` stopped returning credentials (#91). + +**Config rework.** Logging leaves `Config`; one loaded tree with one view per namespace (C5); the +loader is unreachable from agent code; the env-var prefix is the project's; `/status/env` answers +per agent. + +**Phases 0-7.** The namespace is ambient (`run_app`, one declaration applied alone or per agent); +the registry resolves namespace-then-root without a fallback across agents; caches are looked up +by name and namespace-scoped; one thread pool per agent, lazily; dispatch per agent with +`get_handled_event_types()` as a selection hint; transport endpoints subscribe per agent; `build()` +wires a transport per agent; an agent's HTTP surface lives under `/api/`; grouped Dapr is +routed and fanned out in-process; a handler can name its runtime, and an ambiguous name fails at +startup. + +**Phase 8 / 8b -- the group runs.** `AppBuilder` only records and `build()` is the only thing that +builds; `AgentBuilder` records too and builds against its own agent's configuration; `AgentGroup` +turns named declarations into one application; four declaration surfaces became one; a cache is +private to its agent; health checks carry their agent; an agent's own settings file is its scope; +`AGENTS.md` written and its design rules guarded by `test_design_rules.py`. + +**Phase 9 -- identity and failure survive grouping.** Per-agent telemetry resource and meter, a +degraded agent drives `blueprint.namespace.up = 0` and an attributed ERROR, consumption pauses +(not closes), a latched agent recovers by retry, blocked-loop watchdog. + +**Phase 10 -- setup and migration.** A scaffolded project is a group of one in every environment; +`asbs validate` reports what a project has not decided; migration and deployment guides rewritten +against what ships; scaffolded settings/secrets are the ones the framework reads. + +**Isolation.** The four routes by which an agent could reach a neighbour's data are closed: no root +fallback into another agent, a view names only its own agent or the root, one declaration never +hands two agents the same object, dotted keys stay inside their agent. + +**Review findings and hardening.** Publishing is declared (`nats_publish_mode`, +`nats_publish_subjects`); `nats_url` no longer defaults to localhost outside development; NATS +credentials supported and URL credentials redacted; handlers see `nats_subject`; a failed result +publish fails the delivery (#1); the declared transport mode is enforced (#4); dedup claims +atomically (#6); structured output and deps types reach the agent (#2); one `AgentBuilder` serves +several agents (#10); REST payloads no longer logged (#12, #13); the sessions replay guard is +bounded (#14); a standalone agent's v0.8.1 output restored; a Dapr sidecar mock for demos. + +**Grouped HTTP surface** (`2026-09-28-grouped-http-surface.md`). Reserved path segments for +framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a developer +`path_prefix`; standalone paths and tags never change. + +**Concurrency and named connections** (`2026-10-14-named-connections.md`, D1-D11). +- Deliveries run concurrently (`nats_max_concurrent_runs` per agent and connection, + `nats_extra_runs_per_process` as a process pool), long runs send `in_progress` heartbeats + (`nats_heartbeat_enabled`), a run can be bounded (`nats_handler_timeout`, cancel + nak). +- A `ConnectionSource` (`nats_connection_source`) supplies named connections: bindings with a + subject prefix onto the deployment's consumers, `validate` before a run, `run_scope` around it, + `claims` keep claimed subjects off the default connection (`nats_unclaimed_subjects`), runtime + changes through `watch(notify)`, readiness per connection (`nats_connections_readiness`). +- A closed connection reconnects and resubscribes; reconnects are unlimited by default. +- `HandlerResult.skipped(reason)` (D11): responsible but nothing to do -- chain stops, acked, INFO, + `blueprint.events.skipped`, `ProcessingStatus.SKIPPED`. An event no handler takes keeps its + WARNING (spec sec. 7.2 amended to match). +- `nats_delivery_attempt` / `nats_max_deliver` in the handler context for JetStream deliveries. +- Step 6: docs, scaffold, skills and examples agree with the code (inventory: + `docs/plans/2026-10-15-named-connections-step6-inventory.md`); `asbs validate` checks the NATS + keys; `examples/site_readings` shows two named connections end to end. + +**Measured against a real broker** (`tests/integration`, NATS 2.10 with JetStream, plus an +accounts broker): acknowledgement exactly once, redelivery after `ack_wait`, concurrent runs, +heartbeat, run timeout, reconnect with resubscription, named connections without permission +violations, skipped results, delivery attempts. -Components gain an optional **namespace** (`""` by default, so nothing existing changes). A -namespace owns its own handlers, agent runtime, REST routes, AI client, thread pool, caches and -broker connection, while genuinely shared infrastructure -- the port and the health endpoint -- -stays single. Which namespaces a process hosts is resolved at startup from a group configuration, -and Kubernetes runs one Deployment per group: a group of one gives today's process isolation, a -group of twenty gives the shared-interpreter memory profile, and moving an agent between groups -changes neither its broker-side consumer identity nor its telemetry identity. - -Reaching that requires fixing several defects that block running more than one replica of -*anything* today, which is what the prerequisites (P0-P6) cover and where the work starts. - ---- - -## TL;DR - -Design and specification: - -- Normative spec and phased implementation plan, extracted from `CLAUDE.md` into the repo's - spec/plan convention (`4233933`) -- **Acknowledgement contract**: a normal return acks, a raised exception does not; `NO_HANDLER_FOUND` - acks (`b6ab1c9`) -- **Selection and fan-out rules** (spec sec. 7.7), including the two rules that keep a dispatch - index and broker-side filters non-breaking (`13e4d28`) -- Acceptance criteria for both of the above (`b94f60c`) - -Code: - -- **P6 review follow-up -- namespace identity**: one definition of the root namespace, one - alphabet validated where a namespace enters the framework, an unambiguous durable name and - unforgeable connection-name placeholders (`be5e489`) -- **P0 -- transport lifecycle**: managed whole-map `subscribe()`, background retry, reconnect - re-subscription, `subscriptions_ready` readiness gating (`77af507`) -- **P0 -- shutdown drain**: in-flight handlers finish before the connection closes (`585e58c`) -- **P0 -- message boundary**: an undecodable payload is distinguished from a failed dispatch - (`3843abf`) -- **Dapr subscription discovery fixed** -- declared topics now actually subscribe; `GET - /dapr/subscribe` no longer answers 422 (#81, `fac528b`) -- **P1 -- queue groups**: Core NATS subscriptions join a queue group derived from the agent, so a - second replica no longer processes every message a second time (`05083c8`) -- **P2 (NATS half) -- acknowledgement**: a normal return acks, a raised exception naks or terms per - the spec table; the two layers that swallowed the classification are gone (`ce17f87`) -- **P2 (Dapr half) -- parity**: `NO_HANDLER_FOUND` answers `SUCCESS` instead of looping until - `max_deliver`, a critical error drops instead of retrying, and an unparseable body drops instead - of answering 422; both transports now render one shared decision (`ce17f87`) -- **P2 -- unhandled events are counted, not flagged**: `blueprint.events.unhandled` per - (namespace, topic), read as a ratio; finding no work in an event is normal behaviour -- **P3 -- consumer tuning**: `ack_wait`, `max_ack_pending` and `max_deliver` are configurable and - are enforced by the broker, on a `ConsumerConfig` the client creates itself -- **P3 -- JetStream shares load**: the durable carries a deliver group, so JetStream stops being - single-subscriber; this was P1's other half -- **P3 -- dead letters**: a message the framework gives up on is republished, payload unchanged, - to `.dead-letter` before it is termed -- **P3 -- three defects found on the way**: the stream never covered the subject its consumer - filtered on, only the first topic was ever added to it, and the derived durable name was illegal - for any dotted subject -- **P4 -- opt-in deduplication**: the handler chain skips an event whose id and source it has - already dispatched, keyed in the cache with a required TTL. Off by default, and a failed - dispatch releases its claim so the nak's redelivery still runs -- **P4 -- the author is made to decide**: a `DECIDE:` comment in the scaffolded handler, both - keys in the generated `settings.toml` and `CLAUDE.md`, and an `asbs validate` notice when a - project has handlers and has declared neither -- **P4 -- duplicates are counted apart from unmatched events**: `blueprint.events.duplicate`, - so a redelivery storm does not read as a namespace subscribed too broadly -- **P5 (`662f7b5`) -- the cron timer becomes a stated choice**: `scheduler_mode` is **required** and has no - default. `"event"` starts no in-process timer -- the tick arrives as an ordinary event on the - scheduler's own topic, so the queue group picks a single replica and nothing is elected; - `"in_process"` keeps the timer for local development and plain Docker. Registering a scheduler - without the key, or choosing `"event"` with no usable `event_bus`, fails at startup -- **P5 -- a second `build()` pass no longer starts a second timer** (#43), and the manual trigger - route is registered before `include_router` copies it, so it is actually served -- **P5 -- two defects in the generated scheduler**: the scaffold emitted a file that did not - parse, and its `on_startup` override never called `super()`, so a scaffolded scheduler never ran -- **P5 -- publishing no longer requires consuming**: `event_publishing_enabled` gives an - application that only emits events a transport client and no subscription. Off by default, - because a project that wants only a timer may have no broker access -- **P5 -- #43's other cause**: `SchedulerBase` extends `RestApiBase`, so every scheduler sat in the - REST-API lifespan loop *and* the scheduler loop. A single lifespan started two - `AsyncIOScheduler` instances per scheduler, and `on_shutdown` could reach only one -- **P5 -- an event-mode crontab is validated at startup**: nothing else parses it in that mode, so - a typo used to surface as a tick that never arrives. Manifest generation itself is deliberately - deferred, and the renderer written for it was removed rather than carried as dead code -- **P5 -- `"in_process"` fires a tick once across replicas**: every replica's timer fires and each - tick is claimed in the shared cache, so one replica runs it. Not a leader lease: nothing is held, - so there is no renewal task and no takeover bound -- which answers the open question the spec - left on that mode -- **New cache primitive `CacheService.claim`**: set-if-absent, atomic on both backends (`add` on - disk, `SET NX EX` on Redis). This is the compare-and-set operation P4 flagged as missing -- **P6 -- the transport client belongs to a namespace, not to the process**: clients take a - namespace, register under a namespace-qualified name so two can coexist in one registry, and - derive queue group and durable from the namespace alone -- without that, two co-hosted agents - subscribing to one topic would share a queue group and each see half its events -- **P6 -- connections are no longer anonymous**: `nats.connect()` is called with - `name=f"{namespace}.{group}.{pod}"`, which makes a pod's contents legible in `/connz`. The name - carries the pod, so nothing broker-side may derive from it (C1) -- asserted by test -- **P6 -- `EventPublishingService` publishes on its own namespace's client**, resolved namespace - first then root, raising rather than guessing when that is ambiguous - -Documentation and process: - -- Deployment guide now warns that multi-replica is unsafe, and its examples default to one replica - (`2d80b63`) -- New config keys documented: `event_client_drain_timeout`, `dapr_pubsub_name`, - `dapr_declarative_subscriptions`, `idempotency_enabled`, `idempotency_ttl`, `scheduler_mode`, - `event_publishing_enabled` -- Feature working rules in `CLAUDE.md`: one reviewable change at a time (`4cf2d51`), and a - walkthrough whenever real code is written (`7735251`) - -Issues opened along the way: - -- **#80** -- 28 failing example tests assert on removed examples; the unit/integration split is - unenforced -- **#81** -- Dapr declared topics never subscribe (fixed here) - -**Breaking changes: one, and it is loud.** `scheduler_mode` is required, so an existing project -with a scheduler fails at startup until it states which mode it wants. Nothing changes behaviour -silently. See *Compatibility* at the end. - ---- - -## Changes in detail - -### Spec and plan extracted into the repo's conventions (`4233933`) - -The multi-agent work breakdown lived as a 900-line section inside `CLAUDE.md`. It is now -`docs/specs/2026-08-28-multi-agent-grouping.md` (normative: scope, invariants C1-C7, public API, -configuration, transport topology, event delivery, caches, startup, backwards compatibility, -acceptance criteria, open questions) and -`docs/plans/2026-08-28-multi-agent-grouping.md` (the phased breakdown: prerequisites P0-P6 and -phases 0-10). `CLAUDE.md` keeps pointers plus the list of paths that require reading the spec first. - -**Motivation.** `CLAUDE.md` is loaded into every session, so a 900-line plan costs context on every -task regardless of relevance, and it cannot be reviewed the way a document under `docs/` can. The -repo already separated spec from plan (`docs/specs/2026-07-06-...-design.md` against -`docs/plans/2026-07-06-...md`), so this follows an existing convention rather than inventing one. -Open questions live in the spec alone, so the two documents cannot drift. - -### Acknowledgement contract (`b6ab1c9`) - -Spec sec. 7.2 now states: **a normal return acknowledges, a raised exception does not.** The -transport edge must not inspect `ProcessingResult` to decide delivery, and `NO_HANDLER_FOUND` -acknowledges like any other completed dispatch. Both transports must map the same outcome to the -same disposition, so `CriticalHandlerError` drops on Dapr rather than retrying, and a payload that -fails to parse terms rather than naks. Acknowledging an unmatched event must not hide it: unhandled -events are counted per namespace and topic, with a warning on the first occurrence of each pair. - -**Motivation.** `ProcessingStatus` has exactly two values, `PROCESSED` and `NO_HANDLER_FOUND` -- -there is no failure status, so every real failure already arrives as an exception and inspecting the -result buys nothing. It does actively harm: `dapr.py` mapped `NO_HANDLER_FOUND` to `RETRY`, so an -event no handler wanted was redelivered until `max_deliver`, and under a queue group that loop -visits every replica in turn. The contract removes a check rather than adding one. - -### Selection and fan-out (`13e4d28`) - -Spec sec. 7.7 records that selection happens at two levels and only the subject level is enforced -by the broker: NATS has no content or header predicate, and Dapr's CEL rules are evaluated in the -sidecar after delivery. With one consumer per `(namespace, topic)` pair, a broad subject makes the -broker copy every message once per namespace. - -Two rules are normative, and both exist to keep the optimisation non-breaking: - -1. A handler that declares nothing must still be evaluated for every event its namespace receives. - A dispatch index may key on declared event types, but undeclared handlers must fall into an - always-evaluated wildcard bucket. -2. A broker-side filter must never be narrower than the declared topics unioned with - `nats_subscriptions`, and must never be inferred from handler code. - -Also normative: consumer reconfiguration is a migration, because a durable's name and filter set -are broker-side state and a recreated consumer either replays or gaps. - -**Motivation.** 100 agents each evaluating every event is the wrong shape, and the fix has to go -into the subject rather than into Python. The two rules are load-bearing because **nothing declares -anything today** -- `get_subscribed_topics()` is overridden nowhere in the framework or in any -scaffolded project -- so a design that treats declarations as authoritative describes an empty set -and would silence every existing handler. Combined with the ack contract, the events would then be -acknowledged and discarded rather than accumulating visibly. - -The migration rule surfaced that **Phase 5 was already a consumer migration and was not documented -as one**: renaming durables to `{namespace}-{topic}-durable` makes every pre-existing consumer a new -consumer on first deploy. - -### Acceptance criteria for the above (`b94f60c`) - -Five criteria added to spec sec. 12, covering the ack contract, cross-transport parity, the -undeclared-handler rule, filter derivation, and the two observability counters. - -**Motivation.** Sections 7.2 and 7.7 were normative but had no entry in the acceptance criteria, so -"done" did not include them. - -### P0 -- transport lifecycle (`77af507`) - -Connection, retry and subscription lifecycle moved out of the eventing APIs and into the transport -clients. `ClientBase.subscribe(topic_callbacks)` replaces `subscribe(topic, callback)`: one -non-blocking call carrying the whole `{topic: callback}` map, backed by a background retry task. -Adds `subscriptions_ready` with health-check gating, `disconnected_cb`/`reconnected_cb` with -JetStream durable re-subscription, and the `event_client_max_retries` / `event_client_retry_delay` -keys. The imperative `POST /nats/subscribe/{topic}` endpoint and the `EventHandlingBase.subscribe` -abstract are removed. - -**Motivation.** Previously `NatsEventing.on_startup` subscribed imperatively, so a broker that was -down at startup left the app running with no subscriptions and no record of what it had wanted. -Everything later in the plan depends on this shape: P2's acknowledgement correctness needs the -reconnect path to exist, C4 and C7 read `subscriptions_ready`, and per-namespace clients (P6) need a -single subscribe call carrying the whole map. - -Originally written as PR #27; applied here as one commit without that branch's CI and version -changes, so this update can land first. - -### P0 -- shutdown drain (`585e58c`) - -`close()` now cancels the retry task, drains subscriptions so already-queued messages still reach -their handler, waits for running handlers, and only then closes the connection. One deadline from -`event_client_drain_timeout` (default 30 s) bounds the whole sequence. A drain that fails or -outlives the deadline falls back to an immediate unsubscribe. In-flight work is counted in -`message_handler`'s `try/finally` and exposed as `inflight_handlers`. - -**Motivation.** The order is the fix. An acknowledgement is published to the delivering -connection's reply subject, so closing the connection first strands it and the broker redelivers -- -every deploy guaranteed duplicate work for whatever was in flight, and P2 would have inherited that -as a permanent duplicate source. `inflight_handlers` is public because Phase 9 needs exactly that -number for the per-namespace in-flight gauge (C7). - -### P0 -- message boundary (`3843abf`) - -Decoding moved into `_decode_message`, which returns `None` for a payload that cannot become a -CloudEvent and logs it as discarded, naming the topic. Dispatch keeps its own catch, logging the -event id, the topic and a traceback. - -**Motivation.** One `except Exception` covered both decoding and dispatch and logged a single -message for both -- no topic, no event id, no traceback. Those two failures have opposite -dispositions under spec sec. 7.2 (term versus nak), and P2 cannot act on a distinction that has -already been erased. Each failure is now logged exactly once, by the layer that knows what it means. - -The boundary still catches both: a broker callback that raises into `nats-py` loses our context and -gains nothing while no code yet decides what to do with a failure. In P2 the catch becomes the -disposition. - -### Dapr subscription discovery (#81, `fac528b`) - -`GET /dapr/subscribe` now takes no parameters and returns a subscription array built from -`get_subscribed_topics()` -- one entry per declared topic, routed to `/events/{topic}`, using the -`dapr_pubsub_name` key the publisher already reads. `dapr_declarative_subscriptions` (default -`false`) serves an empty document for deployments that declare subscriptions as Kubernetes -resources. - -**Motivation.** Three defects, found while resolving P0's last gap. The endpoint's signature was -`subscribe(self, topic: str, queue_group: str | None = None)`, and since the path holds no -`{topic}`, that was a **required query parameter** -- so the sidecar's parameter-less GET was -answered 422 by FastAPI before any framework code ran. The body returned `{}` where Dapr expects an -array. And the declarations were collected into a callback map handed to `DaprClient`, which only -pings `/v1.0/healthz` and never reads it, because Dapr delivers over HTTP rather than through a -client-side callback. Net effect: under Dapr, a handler's declared topics subscribed to nothing. - -The callback map is kept deliberately and documented for what it is -- the input that starts the -sidecar-reachability retry and feeds `subscriptions_ready`. Removing it, which "delete the unused -map" invites, would have silently disabled the readiness gating added in P0. - -### P1 -- queue groups on Core NATS subscriptions (`05083c8`) - -Every Core NATS subscription now passes `queue=`, so the server delivers each message to exactly -one member of the group instead of to every subscriber. The name is resolved once, in -`subscribe()`, from `nats_queue_group` falling back to `app_name`, and is exposed as the public -`queue_group` property; the resolved name is logged with each subscription, which is what makes C1 -checkable by diffing two deployments' startup logs. - -Three details carry the invariant: - -- **The name identifies the agent, not the process.** C1 requires the queue group to be a pure - function of the agent's own identity, so that regrouping is invisible to the broker. Only - `nats_queue_group` and `app_name` feed it -- never a pod, container or replica name. When - namespaces land, the namespace supplies the name directly and these keys stay as the root-namespace - fallback. -- **An underivable name raises rather than defaults.** NATS reads `queue=""` as *no queue group*, so - any silent fallback would reintroduce exactly the fan-out being fixed, and would do it invisibly. - `subscribe()` raises `ValueError` instead, naming both keys. -- **It is resolved in `subscribe()`, not at subscription time.** `subscribe()` is called by the - caller's startup path, while the actual subscribing happens inside the background retry task. A - config error raised in that task would be retried indefinitely (`event_client_max_retries` - defaults to `-1`) and would surface only as a readiness probe that never goes green. Raising in - `subscribe()` fails startup where a human is looking. - -**Motivation.** JetStream is off by default, so the default transport path was plain Core NATS with -no queue group: `replicas: 2` meant both replicas received and processed every event -- every side -effect twice, every inference billed twice. This is a defect at any replica count above one, -independent of grouping, and it is what makes the deployment guide's multi-replica warning -removable later. - -**JetStream is deliberately untouched, and still single-subscriber.** nats-py rejects a queue -subscription whose durable name differs from the queue name -(`cannot create queue subscription '' to consumer ''`), so passing the queue group -next to the existing per-topic durable would raise at subscribe time. A durable shared across -replicas needs its deliver group set on an explicitly constructed `ConsumerConfig` and bound with -`subscribe_bind`, which is the same object P3 has to build anyway for `ack_wait` and -`max_ack_pending`. Doing it there is one change instead of two, and the constraint is recorded as a -comment at the call site so it does not read as an oversight. Until then a second replica on -JetStream fails to subscribe loudly (`consumer is already bound to a subscription`) rather than -double-processing silently -- the safer of the two failures, and readiness gating keeps such a pod -out of rotation. - -New config key: `nats_queue_group` (default: `app_name`), documented in -`docs/reference/configuration-keys.md`. - -**What this buys, and what it depends on.** The group key is *(subject, queue name)*, so with the -name set per agent the two properties a multi-agent platform needs hold together: different agents -on one subject are different groups and each receives its own copy (fan-out), while replicas of one -agent share a group and one of them handles each message (round-robin). Adding a replica never adds -a copy; adding an agent always does. Plain non-queue subscribers, such as a monitoring tap, are -unaffected and still receive everything. - -Both properties rest on the names being distinct per agent, and two things can break that: - -- **Default-valued `app_name`.** Scaffolding writes the project name - (`settings_part_generator.py:11`), but the config validator falls back to `agent_blueprint` if the - key is removed, and `asbs create agent` outside a scaffolded project writes `generated-agent` - (`create.py:580`). Two services on either default would join one group and steal each other's - events -- the failure this fixes, moved from replicas to agents. Candidate for an `asbs validate` - notice when `event_bus = "nats"`. -- **JetStream durables are keyed by topic, not by agent** (`nats_durable_name`, default - `f"{topic}-durable"`). Two agents subscribing to the same topic both try to bind one durable and - the second fails. Cross-agent fan-out under JetStream therefore does not work until the Phase 5 - rename to `f"{namespace}-{topic}-durable"`, which is the functional reason that rename is - load-bearing rather than cosmetic. Separately, a project that sets `nats_durable_name` explicitly - collapses all its topics onto one durable name; pre-existing, and worth fixing where Phase 5 - touches that line. - -### P2 -- acknowledgement at the NATS transport edge (`ce17f87`) - -JetStream messages were subscribed with `manual_ack=True` and never acknowledged, so every event -redelivered until `max_deliver` -- a defect at a single replica, not just at scale. The transport -edge now settles every delivery, and the classification needed to settle it correctly survives the -trip from the handler. - -**The disposition table lives in one place.** `models/errors.py` gains `DeliveryDisposition` -(`ACK`/`NAK`/`TERM`) and `disposition_for(exc)`, next to the exceptions it classifies. Spec sec. 7.2 -requires both transports to map the same outcome to the same disposition, so encoding the table once -is what makes that checkable rather than aspirational -- and a new `HandlerError` subclass is now -added in the same file that decides what its failures do to a delivery. Matching is by `isinstance`, -so a project's own subclass inherits its parent's disposition. The function never returns `ACK`: -acknowledgement is what a *normal return* means, and the edge decides that without asking. - -**`NATSClient._settle` applies it.** `message_handler` acks on normal return, terms an undecodable -payload before dispatch, and otherwise settles with whatever `disposition_for` says. Two details: - -- It gates on `_use_jetstream`, not on `msg.reply`. Core NATS is fire-and-forget and `msg.ack()` - raises `NotJSMessageError` there, but a Core NATS *request/reply* message does carry a reply - subject -- gating on the subject would publish `+ACK` to a waiting requester. -- A failure to settle is logged and swallowed. The acknowledgement is published to the delivering - connection's reply subject, so it fails exactly when that connection is gone; raising into the - `nats-py` callback would neither deliver it nor recover it. The message redelivers after - `ack_wait`, which is the at-least-once behaviour sec. 7.4 already requires handlers to tolerate. - -**Two swallowing layers removed.** `NatsEventing._process_event` caught the three classified handler -errors, logged them and returned normally -- which, once the edge acks on normal return, would have -acknowledged every failed event as processed. `EventHandlingBase._process_cloud_event` logged each -exception and re-raised it; the logging is gone and the exception now passes through untouched. Both -transports already log at their own edge, where the topic and the disposition are known, so the -removed logging was duplicate output that knew less than the line beside it. It also brings the -method in line with the repo's log-or-raise rule. - -**Still open in P2**, each its own step: Dapr parity (`NO_HANDLER_FOUND` -> `SUCCESS`, -`CriticalHandlerError` -> `DROP`, and the same in `handle_event`), the unhandled-event counter with -its first-occurrence warning, and `max_deliver` plus a dead-letter destination, which lands with P3 -because a nak on an unexpected exception otherwise redelivers forever. - -### P2 -- Dapr parity (`ce17f87`) - -Dapr acknowledges by response body, so `POST /events/{topic}` is its `_settle`. It disagreed with -the spec table in two places, and both disagreements were live defects: - -- **`NO_HANDLER_FOUND` returned `RETRY`.** An event no handler wanted was redelivered until - `max_deliver`, and now that P1 puts every replica in a queue group, that loop visits each replica - in turn before giving up. It answers `SUCCESS`. -- **`CriticalHandlerError` returned `RETRY`.** A critical error is not made less critical by being - delivered again. It answers `DROP`, matching NATS's `term`. - -An unexpected exception previously raised `HTTPException(500)`. That is a third behaviour rather than -a disposition: the sidecar sees a failed call and applies whatever its own resiliency policy says, -which need not be retry and is not visible from this code. It now answers `RETRY` explicitly, as the -table requires. **The tradeoff is deliberate**: a 500 showed up in HTTP metrics and traces as a -failure, and a 200 with `RETRY` does not, so an unexpected handler exception is now visible only in -the log line and in Dapr's own retry counters until the P2 counters land. - -**One `except`, not four.** The four per-error-type blocks collapsed into a single one that calls -`disposition_for(exc)` and renders the result. The rendering lives in a new -`io/api/eventing/dapr_response.py` -- three lines of mapping from `DeliveryDisposition` to -`SUCCESS`/`RETRY`/`DROP`. It sits there rather than in `models` so Dapr's vocabulary does not leak -into the shared layer, and rather than in `dapr.py` so `EventHandlingBase.handle_event` can render -identically without importing a subclass. What an outcome deserves is decided once; each transport -only says it in its own words, and adding a new error type can no longer update one transport and -miss the other. - -`EventHandlingBase.handle_event` got the same treatment: acknowledge whatever status the chain -returned, warn when nothing matched, and let exceptions through to the edge. - -**Unparseable deliveries now drop, which changes an HTTP response.** A payload that cannot become a -CloudEvent must `DROP` (spec sec. 7.2), but under Dapr the body is parsed by FastAPI before any -framework code runs, so that payload was answered **422** and the sidecar retried it to -`max_deliver` -- the one row of the table where the transports disagreed for a structural reason -rather than a coding one. `DaprDeliveryRoute`, an `APIRoute` subclass, wraps the route handler and -converts `RequestValidationError` into `200 {"status": "DROP"}`. - -*This is a deliberate behaviour change*: `POST /events/{topic}` no longer answers 422 for a malformed -body under Dapr. That is the correct answer to a *REST caller* and the wrong answer to a *sidecar -delivery*, and the same path serves both roles. The wrapper is therefore scoped to the component -that asks for it via a new `RestApiBase.route_class` hook -- an application-wide -`RequestValidationError` handler would have answered `DROP` for ordinary REST endpoints too, where -422 is right. `NatsEventing`, which owns the same path for the outbound direction, keeps the default -route class and still answers 422; there is a test for exactly that. - -### P2 -- unhandled-event accounting, and a spec correction - -An event that matches no handler is acknowledged, and it is also **ordinary**. Deciding there is -nothing to do is the handler's job and an ordinary outcome of doing it: an agent reads an event, -finds no work in it, and says so. Why is the agent's business -- wrong tenant, wrong state, a -condition that is not met -- and none of it is the framework's concern. - -`_process_cloud_event` therefore does exactly two things with such a dispatch: increments -`blueprint.events.unhandled` with `namespace` and `topic` attributes, and logs at DEBUG. - -- **Counted, because the ratio is the signal.** A namespace declining nearly everything it receives - is subscribed too broadly (spec sec. 7.7). That is a question about the subject filter, and it is - only answerable against received volume -- so the count must not be deduplicated. -- **Not flagged, because nothing is wrong.** No WARNING, no error. -- **No state kept.** Under Dapr the topic comes from a URL path, so remembering distinct topics - would let a caller grow this process's memory. - -It lives in `_process_cloud_event`, shared by both transports, because an unmatched dispatch is a -property of the dispatch rather than of the transport carrying it -- and both edges keeping their -own copy of a delivery rule is how they came to disagree about `NO_HANDLER_FOUND` in the first -place. The interim per-event warnings the Dapr work left in `publish` and `handle_event` are gone. - -`_process_cloud_event` gains a `topic` parameter. The topic is already in `context`, but each -transport spells its key differently (`nats_topic`, `dapr_topic`) and those keys reach user -handlers, so they cannot be unified without breaking them. - -`EventHandlingBase.ROOT_NAMESPACE` is the one place the "no namespaces yet" assumption is written -down; phase 2 replaces it and the counter's `namespace` attribute starts varying. - -**The spec was wrong and is corrected.** Sec. 7.2 had required a WARNING on the first -(namespace, topic) pair and called an unmatched event "usually a declaration error"; sec. 7.7 called -it one of "both directions of the same error". That premise is false -- it treats a handler's -domain decision as a framework fault -- and it was implemented before being questioned. Sec. 7.2 now -forbids reporting it as a fault and forbids per-topic state, sec. 7.7 frames both counters as ratios -rather than faults, and the acceptance criterion carries the same conditions. A first -implementation with the tracker, the warning and an accumulating set was replaced rather than -committed. - -### P3 -- consumer tuning, deliver groups and dead letters (`8ce9600`) - -Four settings, one object. `ack_wait`, `max_ack_pending`, `max_deliver` and the deliver group all -live on `ConsumerConfig`, so the client stops letting `js.subscribe` invent a consumer and builds -one itself: `_ensure_consumer` creates the durable through `add_consumer` and `_subscribe_one` binds -to it with `subscribe_bind`. That is the only route by which P1's queue group can reach JetStream -- -`nats-py` refuses a queue subscription whose durable name differs from the queue name, and the -durable is per topic while the queue group is per agent -- so **JetStream stops being -single-subscriber**, which was the half of P1 that had to wait. - -New keys, all defaulting to working behaviour: `nats_ack_wait` (300 s), `nats_max_ack_pending` (16), -`nats_max_deliver` (5), `nats_dead_letter_subject` (`.dead-letter`). They are resolved -and validated in `subscribe()` alongside the queue group, for the same reason: a config error must -fail the caller's startup rather than repeat forever inside the background retry task. - -**Two defaults are opinions, and the reasoning is worth keeping.** `ack_wait` is 300 s against a -NATS default of 30 s, because handlers here call models and a redelivery mid-inference costs the -work twice. `max_ack_pending` is 16 rather than the NATS default of 1000, because a `nats-py` push -subscription runs its callbacks one at a time: everything the broker pushes beyond what is actually -being processed sits in the client's queue with its `ack_wait` already running down. A large window -does not buy throughput here, it manufactures expiries. - -**Dead letters.** `_settle` gained one branch: a nak on the last delivery `max_deliver` permits is -turned into a dead letter plus a term. Naking there is a lie -- the broker will not redeliver it -- -and it differs from a term only in that the message leaves the consumer with no trace of why, one -`ack_wait` later than it needed to. `_dead_letter` republishes the **original bytes**, unchanged, so -a payload that never parsed as a CloudEvent survives; what went wrong travels in -`Blueprint-Dead-Letter-Reason`, `-Original-Subject`, `-Delivery-Count` and `-Event-Id` headers, where -it cannot corrupt a body some dead-letter consumer will try to read. Terminal failures -- -`InvalidEventError`, `CriticalHandlerError`, an unparseable payload -- take the same path. Setting -the subject to `""` disables it, and then each drop is logged as a lost payload rather than passing -silently. - -The dead-letter subject is derived from the queue group, so it follows the agent's identity exactly -as C1 requires, and it is validated at startup: a wildcard is rejected because it is published to, -and a subject the same client subscribes to is rejected because dead-lettering onto a consumed -subject turns one failure into an unbounded loop -- the kind that only shows up under load. - -**Three defects surfaced while building it**, none visible from P3's description, all of which -blocked explicit consumer creation: - -1. **The stream never covered the subject its consumer filtered on.** `add_stream` was called with - `subjects=[f"{topic}.>"]`, which does not match `topic` itself. `js.subscribe` had been papering - over it by letting the server pick; an explicitly created consumer filtering `orders.created` is - simply rejected by a stream that only captures `orders.created.>`. -2. **Only the first topic was ever added to the stream.** `add_stream` ran once per topic with the - same stream name; every call after the first answered "stream name already in use" and was logged - as a warning, leaving the remaining topics uncaptured. Provisioning now happens once per connect, - in `_provision_stream`, with the union of every subscribed subject plus the dead-letter subject, - and widens an existing stream additively rather than replacing it. -3. **The derived durable name was illegal for any dotted subject.** NATS allows no `.`, `*`, `>` or - whitespace in a consumer name, so `f"{topic}-durable"` could not work for `orders.created` -- that - is, for essentially every idiomatic NATS subject. `_durable_for` replaces those characters, and - `_resolve_durables` rejects at startup both the collision that substitution can create and - `nats_durable_name` set while several topics are subscribed, since one durable filters one - subject. - -**An existing consumer is never rewritten.** `_ensure_consumer` reads `consumer_info` first and, when -the durable already exists, binds to the server's config and logs which settings differ. A durable's -filter subject and deliver group are broker-side state that the stream's pending and redelivery -bookkeeping hangs off; rewriting one in place either replays messages it already handled or skips -ones it never saw. The spec already called consumer reconfiguration a migration, and this is that -rule in code -- a rolling restart must not perform one silently. The practical consequence is that -an existing deployment upgrading into this change keeps its old consumer, without a deliver group, -until someone deletes it deliberately; the warning names exactly which settings are not in force. - -The deliver subject is derived from the durable name rather than taken from a fresh inbox, because -every replica has to bind to the same one -- two replicas generating random inboxes would define two -consumers, which is the fan-out P1 removed. - -### P4 -- opt-in deduplication, and the decision forced on the author (`d127843`) - -At-least-once delivery is permanent (spec sec. 7.4). P2 and P3 made acknowledgement correct, which -narrows redelivery to the cases where it is unavoidable -- a lost ack, a pod restart, a rolling -deploy -- but does not remove them: a handler that finishes 60 s of inference and then cannot ack -has already committed its side effects, and the broker sends the event again. Whether replaying -those side effects is *correct* is a property of the product, not of the framework, so P4 provides -the mechanism and refuses to make the choice. - -**The chain claims before it dispatches.** `HandlerChain.process` no longer runs the handler loop -directly; it calls `_claim`, and only then `_dispatch` (the loop, moved verbatim). `_claim` returns -whether to dispatch: with dedup off it always returns `True`, and with dedup on it asks the cache -whether a marker for this event exists, writes one with the configured TTL if it does not, and -returns `False` if it does. A `False` makes `process` set `DUPLICATE_CONTEXT_KEY` in the context, -stamp `event.duplicate` on the span, and return `None` without touching a handler. - -**A failed dispatch releases the claim.** This is the part that is easy to leave out and expensive -to leave out: - -```python -try: - return await self._dispatch(event, context) -except Exception: - self._release(event, policy) - raise -``` - -The claim has to be taken *before* dispatch -- that is the only point at which it can stop a -concurrent duplicate -- which means a dispatch that raises has left a marker behind for an event -that was never processed. The exception it re-raises is what P2 turns into a nak, and the broker -sends the same event back. Without `_release`, that redelivery is swallowed as a duplicate, and so -is the next one, until `max_deliver` is exhausted and the message is dead-lettered having never -reached a handler. The test that pins this asserts the handler is entered on both attempts. - -**The key carries the source as well as the id.** `_idempotency_key` returns -`{"id": ..., "source": ...}`. The spec says "keyed on the CloudEvent `id`", but the CloudEvents -specification requires an id to be unique only *within* a source, so two producers may both legally -emit id `"1"` and keying on the id alone would let one publisher's event suppress another's. It is -sent as a dict because the cache sorts a dict by key before hashing it, which a two-element list -- -which the cache sorts by *value* -- would not preserve. An event missing either field is dispatched -untracked with a warning rather than dropped. - -**`idempotency_ttl` is required, and deliberately has no default.** `_resolve_idempotency_policy` -raises at startup if dedup is enabled without it. The window has to outlast the redelivery window it -exists to cover -- `nats_ack_wait * nats_max_deliver` under JetStream, whatever the component's -retry policy says under Dapr -- and neither number is one the dispatch layer can read without -reaching into a transport it must not know about. A default here would ship a dedup window that -silently expires before the last redelivery arrives, which presents exactly like dedup not working -at all. So enabling dedup is two keys, and the second one is the decision spec sec. 7.4 asks the -author to make. The same method rejects a non-boolean `idempotency_enabled`, a non-positive or -non-numeric TTL, and -- the one that would otherwise fail silently -- dedup enabled with no cache -registered, where there is nowhere to keep the markers. - -**Startup runs, because something now calls it.** `HandlerChain` is created by -`EventProcessingService` with `should_register=False`, so nothing in the lifespan ever called its -lifecycle hooks; its `on_startup` was a no-op and could stay one. It resolves the policy now, so -`EventProcessingService.on_startup`/`on_shutdown` delegate to the chain -- a bad dedup setting has -to fail the pod, not the first event that arrives on it. `process` also resolves the policy on first -use if startup never ran, because a chain constructed outside `AppBuilder` inheriting "dedup is off" -from a missed wiring step is the one failure this feature must not have. - -**A duplicate is counted apart from an unmatched event.** At the transport edge, -`_process_cloud_event` checks the context flag before it looks at the status: - -```python -if context.get(DUPLICATE_CONTEXT_KEY): - _DUPLICATE_EVENTS.add(1, {"namespace": self.ROOT_NAMESPACE, "topic": topic}) -elif processing_result.status is ProcessingStatus.NO_HANDLER_FOUND: - _UNHANDLED_EVENTS.add(1, {"namespace": self.ROOT_NAMESPACE, "topic": topic}) -``` - -A deduplicated event arrives here looking exactly like an unmatched one -- no handler ran, so no -result came back -- but the two say opposite things about the subscription. An unmatched event is -one this namespace had no use for, and `blueprint.events.unhandled` is read as a ratio to spot a -namespace subscribed too broadly (spec sec. 7.7); a duplicate is an event it *did* use, once. -Counting them together would make a redelivery storm read as a bad subscription. The flag travels in -`context` rather than as a third `ProcessingStatus` value because that enum is normative in spec -sec. 7.2 -- it carries two values precisely so that no failure can reach the transport as a returned -value, and adding to it invites exactly that. `context` is already the channel handlers use to pass -information along the chain, and it is mutated in place all the way down. - -**Both dispositions are unchanged.** A duplicate acks, like any completed dispatch. Redelivering it -forever would be the one outcome worse than processing it twice. - -**The claim is not a lock, and this is written into the class docstring.** `exists` then `set` is -not atomic on either cache backend, so two replicas handed the same event at the same instant can -both pass the check; a cache that is unreachable fails open, because both `DiskCacheService` and -`RedisCacheService` swallow their own errors and return `False`/`None`. Dedup narrows the duplicate -window, it does not close it, and a handler whose side effects must never repeat still needs its own -reconciliation. The cache calls are also synchronous inside an async method, like every other cache -call in the framework today; phase 2 moves them onto the namespace executor. - -**Surfacing the requirement (spec sec. 7.4, the second half).** The mechanism is only half of P4 -- -the author has to be told the choice exists: - -- **Scaffolded handler** (`base_files/src/handlers/handler.txt`): a `DECIDE:` comment at the top of - `handle_event` explaining that redelivery is normal behaviour rather than an edge case, naming - both ways out (write a repeatable handler, or set the two keys), and asking to be deleted once the - decision is made. `asbs setup` and `asbs create handler` share this template, so one edit covers - both. -- **Generated `settings.toml`** (`base_files/settings.txt`): both keys, commented, inside `[default]` - -- not after `[default.logging]`, where uncommenting them would silently put them in the wrong - table. -- **Generated project docs** (`claude_docs/CLAUDE.md`): a bullet under EventHandler and the two keys - in the settings example. -- **`asbs validate`**: a new `Notices` section. `_idempotency_notice` reports when a project has - handlers and its `settings.toml` does not declare `idempotency_enabled` -- in any environment - table, since dynaconf environments are top-level tables. Declaring it `false` silences the notice - as much as `true` does: the point is that a decision was made, not which one. A project with no - handlers is not notified, and an unparseable `settings.toml` is left to the check that already - reports it rather than guessed at. - -There is no generated README to put the spec's third line in -- `asbs setup` does not write one -- -so the generated `CLAUDE.md` and `settings.toml` carry it instead. Listed under *Open points*. - -Tests: dedup off by default and repeat deliveries dispatching twice; the same event dispatching once -and the second delivery flagged in context; the claim written with the configured TTL into its own -cache namespace; the same id from a different source not being a duplicate; a failed dispatch -releasing the claim and the retry reaching the handler; an event missing a source dispatching -untracked; six policy-resolution failures and the string form an environment variable delivers; the -duplicate counter firing while the unhandled counter does not, and the reverse; and seven cases for -the `asbs validate` notice. - -### P5 -- the cron timer becomes a stated choice, and the tick becomes an event (`662f7b5`) - -`SchedulerBase.on_startup` created an `AsyncIOScheduler` per process with no leader election -(#73), so every replica fired every cron tick. Grouping widens that: one pod hosting 20 agents -runs 20 timers, and two replicas duplicate all 20 agents' crons at once. The fix spec sec. 7.5 -asks for is not leader election -- it is taking the timer off the path nobody chose. - -**`scheduler_mode` selects what calls `tick()`, and it has no default.** `_resolve_mode` reads the -key, lower-cases and strips it, rejects an absent or empty value, and then accepts only `"event"` -or `"in_process"`: - -```python -raw = self.config.get("scheduler_mode", None) -mode = str(raw or "").strip().lower() -if not mode: - raise ValueError( - f"Scheduler '{self.name}' is registered but 'scheduler_mode' is not set, and it has no default. " - f"Set it to '{SCHEDULER_MODE_EVENT}' to take the tick as an event on '{self.tick_topic}', published " - f"by an external CronJob -- exactly one replica then runs it. Set it to '{SCHEDULER_MODE_IN_PROCESS}' " - "to run an APScheduler timer inside the process, which is correct for local development and plain " - "Docker but fires once per replica." - ) -if mode not in SCHEDULER_MODES: - raise ValueError(f"Config key 'scheduler_mode' must be one of {', '.join(SCHEDULER_MODES)}, got {raw!r}.") -``` - -The error names both values and what each one costs, because it is the only thing an existing -project sees. The result is cached on the instance, so the mode cannot change under a running -scheduler. *Why there is no default* is argued below -- it is a deliberate departure from spec -sec. 7.5, which names `"event"` as the default. - -**Event mode without a transport fails too.** `_require_event_transport`, called from `wire()` -before the handler is created, insists on `event_bus` being one of `EVENT_MODE_TRANSPORTS = -("dapr", "nats")`. `"sessions"` is excluded on purpose: `SessionsBus` consumes SSE job -notifications and never reads `get_subscribed_topics()`, so a tick published to a topic would not -arrive. Without this check, event mode with no broker is the one failure that is pure silence -- -the scheduler starts, subscribes to nothing, and never ticks. - -**In event mode nothing in the process keeps time.** `on_startup` now branches: - -```python -if self._started: - logger.warning("Scheduler '%s' is already started; ignoring the repeated startup", self.name) - return -self._started = True -self.wire() - -if self.scheduler_mode == SCHEDULER_MODE_EVENT: - logger.info(..., self.name, self.tick_topic, self._crontab) - return - -trigger = CronTrigger.from_crontab(self._crontab) -self._scheduler = AsyncIOScheduler() -self._scheduler.add_job(self.tick, trigger, name=self.name) -self._scheduler.start() -``` - -The `AsyncIOScheduler` block is unchanged and now runs only under `"in_process"`. `on_shutdown` -clears `_scheduler` and `_started` after shutting the timer down, so a stop/start cycle in one -process starts one timer again rather than none. - -**`SchedulerTickHandler` is what turns an external tick into a `tick()`.** A new -`EventHandlerBase` subclass in the same module, holding a scheduler and a topic: - -```python -def get_subscribed_topics(self) -> list[str]: - return [self._topic] - -async def can_handle_event(self, event, context) -> bool: - return any(context.get(key) == self._topic for key in _TOPIC_CONTEXT_KEYS) - -async def handle_event(self, event, context) -> dict[str, Any]: - logger.info("Scheduler '%s' ticking from event '%s' on topic '%s'", self._scheduler.name, event.id, self._topic) - await self._scheduler.tick() - return {"status": "ticked", "scheduler": self._scheduler.name} -``` - -That is the entire event mode. Declaring the topic is what makes the transport subscribe -- -`NatsEventing.on_startup` and `DaprEventing._declared_topics` both walk -`registry.get_event_handler()` and call `get_subscribed_topics()` -- so the tick arrives on the -path the framework already has, and the queue group is what guarantees a single replica runs it. -Nothing is elected. Dedup, the unhandled/duplicate counters and the P2 acknowledgement contract -apply to a tick exactly as they do to any other event: a `tick()` that raises reaches the -transport edge and is naked or termed there, which is why `handle_event` does not catch. - -Three details in that class are load-bearing: - -- **It matches the topic, not the event type.** `_TOPIC_CONTEXT_KEYS = ("nats_topic", - "dapr_topic", "topic")` -- every key a transport spells the delivery topic with. Those keys - reach user handlers and were deliberately left un-unified - (`EventHandlingBase._process_cloud_event` says so), so a consumer that wants the topic has to - read all three. Matching the topic rather than a type string also means a hand-published tick - during development works with any body. -- **`PRIORITY = 10`, ahead of the default 100.** A handler that declares nothing is still - evaluated for every event its namespace receives (spec sec. 7.7, rule 1), so a permissive - `can_handle_event` in user code would otherwise claim the tick first. -- **It renames itself in `__init__`.** `Component.__init__` registers under the class-derived - name, and `Registry.add_component` raises on a duplicate, so a second scheduler's handler would - collide with the first on `scheduler_tick_handler`. Assigning `self.name = f"{scheduler.name}_tick"` - immediately pops that key back out of the registry, which is what leaves it free for the next - instance. A test builds two schedulers against a real `Registry` to pin it. - -**The tick topic derives from the agent, not the deployment.** `_resolve_topic` returns -`f"{namespace}.scheduler.{self.name}"`, falling back to `app_name` while `ROOT_NAMESPACE` is still -`""` -- the same identity the queue group derives from, so moving a scheduler between deployment -groups does not change the subject a `CronJob` publishes to (C1). It raises if no identity is -available, and rejects `*` and `>` in either the derived or the `topic=`-overridden form -- a -wildcard would subscribe the scheduler to traffic that is not its tick. Whitespace is treated -asymmetrically: rejected in an explicitly named topic, but rewritten to `_` in a derived one, the -way `NATSClient._durable_for` already rewrites a subject into a legal durable name. -`app_name = "Health Monitor"` is legal and common -- `examples/health_monitor` uses exactly that -- -and since the topic is derived rather than typed there is no author mistake to catch, only a name -to make usable. The `topic=` override exists because the subject taxonomy is still unratified -(spec sec. 13): an agent whose ticks are already published on someone else's subject can name it. - -**`wire()` runs at build time, and that placement is the fix for two silent failures.** - -```python -def wire(self) -> SchedulerTickHandler | None: - self.register_trigger_route() - if self.scheduler_mode != SCHEDULER_MODE_EVENT: - return None - if self._tick_handler is None: - self._tick_handler = SchedulerTickHandler(self, self.tick_topic) - return self._tick_handler -``` - -`AppBuilder.build()` calls it in a new step 2, before the existing `if registry.get_event_handler():` -block that creates the transport and the eventing endpoint: - -```python -for scheduler in registry.get_schedulers(): - tick_handler = scheduler.wire() - if tick_handler is not None: - logger.info( - "Scheduler '%s' is in event mode; its tick arrives on topic '%s' (crontab '%s')", - scheduler.name, tick_handler.topic, scheduler.crontab, - ) -``` - -- **Without that ordering, an application whose only event consumer is a scheduler gets no - transport.** `build()` creates `NATSClient`/`DaprClient` and the eventing component only when a - handler is registered. A tick handler created during `on_startup` would arrive after that - decision, so the scheduler would be registered, subscribed to nothing, and never ticked. -- **The manual trigger route was already broken, and this is where it gets fixed.** - `POST /{name}/trigger` was added to `self.router` inside `on_startup`, but - `_build_rest_endpoints` calls `app.include_router` during `build()`, and `include_router` copies - the routes a router holds *at that moment*. Every route added during startup therefore existed - on the scheduler's own router and was served by nothing. `register_trigger_route` is idempotent - and now runs from `wire()`, before the copy. It stays out of `__init__` because - `with_scheduler(name=...)` can rename the component afterwards and the path carries the name. - -`on_startup` still calls `wire()` itself, so a scheduler driven without `AppBuilder` gets its -handler and its route; both calls are no-ops the second time. - -**#43 -- and it had a second cause, worse than the one on record.** The plan describes two -`build()` passes driving the lifespan hooks twice over the same registry; the `_started` guard -covers that. But it happens in a *single* pass too, and it always has: - -```python -print([x.name for x in registry.get_schedulers()]) # ['nightly_scheduler'] -print([x.name for x in registry.get_rest_apis()]) # ['nightly_scheduler'] -``` - -`SchedulerBase` extends `RestApiBase` -- that is how `POST /{name}/trigger` reaches the app -- so -every scheduler is in `get_rest_apis()` as well as in `get_schedulers()`, and the lifespan iterates -both lists. `on_startup` therefore ran twice on the same object in one startup, and the old -implementation created a fresh `AsyncIOScheduler` each time and overwrote `self._scheduler`. The -first one was already started and stayed started, holding the same job, while the attribute pointed -at the second -- so **every cron job fired twice in a single replica, and `on_shutdown` could only -ever stop one of the two timers.** `on_shutdown` was likewise called twice, which for a subclass -doing anything non-idempotent in either hook is its own problem. - -Two changes, because the two failures are different: - -- `SchedulerBase.on_startup` guards on `_started` and warns on a repeated call. That absorbs both - causes and is the safety net. -- `AppBuilder._lifecycle_rest_apis` removes schedulers from the REST-API lifespan loops, so the - double drive stops happening at all: - - ```python - return [rest_api for rest_api in registry.get_rest_apis() if not isinstance(rest_api, SchedulerBase)] - ``` - - Their routers are still mounted from `get_rest_apis()` in `_build_rest_endpoints`, which is where - that inheritance is wanted. Without this the guard would fire a warning on every startup of every - scheduler, which is a fix that reports itself as a fault forever. - -An integration test asserts a scheduler's hooks run once per lifespan and that no "already started" -warning is emitted. - -**Publishing no longer requires consuming.** Both transport clients were constructed only inside -`build()`'s `if registry.get_event_handler():` branch, and `EventPublishingService` only when an IO -client existed -- so a scheduler-only application could not publish an event at all, whatever its -`event_bus` said. A nightly job that emits `reconciliation.completed` had no way to do it. The two -decisions are now separate: - -```python -consumes = bool(registry.get_event_handler()) -publishes = self._publishing_requested() -event_bus_type = str(self._config.get("event_bus", "") or "").strip().lower() - -if publishes and event_bus_type not in TOPIC_TRANSPORTS: - raise ValueError(...) - -if consumes or publishes: - if event_bus_type == "dapr": - DaprClient() - if consumes: - self._eventing_component = DaprEventing() - elif event_bus_type == "nats": - NATSClient() - if consumes: - self._eventing_component = NatsEventing() - ... -``` - -`event_publishing_enabled` (bool, default `False`) is the opt-in, and it stays opt-in on purpose: a -project that wants only a timer may have no broker access at all, and a client created on its -behalf becomes a readiness dependency on infrastructure it does not run. An absent or empty value -both mean off -- an unset environment override arrives as `""` -- while a non-empty non-boolean -raises, through a new shared `parse_bool` in `utils` that `HandlerChain._read_bool` had implemented -privately for `idempotency_enabled`. - -The publish-only shape gets a client and **nothing else**: no eventing component, so no -`GET /dapr/subscribe`, no `POST /events/{topic}`, no subscription and no consumer. That is the -property that makes it safe for an agent that was never meant to consume -- it cannot accidentally -receive anything, because nothing was subscribed. `EventProcessingService` is still keyed on -`consumes`, and `EventPublishingService` still on the client existing, so a consuming application -keeps the publishing it has always had without touching the new key. - -`TOPIC_TRANSPORTS = ("dapr", "nats")` now lives next to `IOClientBase` -- the class that exists only -for those two -- rather than in the scheduler module, because two callers need the same fact: -publishing needs a client, and an event-mode scheduler needs a subscription. `"sessions"` is -excluded from both; it wires `SessionsApiClient` and `SessionsBus`, which consumes SSE job -notifications and never reads `get_subscribed_topics()`. - -**Two defects in the generated scheduler, found on the way.** - -- **`asbs create scheduler` emitted a file that does not parse.** The template's `tick` body was a - `try:` containing only comments, followed by `except Exception as e:` -- a `SyntaxError`, so the - scaffolded module could not even be imported. The `try` is gone; `tick` is now a documented - TODO that lets its exceptions out, which is also what the acknowledgement contract needs (and - the old body logged *and* re-raised). -- **The scaffolded `on_startup` never called `super().on_startup()`.** It overrode the base method - with a comment-only body, so a scaffolded scheduler that did parse would have started no timer - and registered no trigger route -- in either mode. Both hooks now call `super()`, with a comment - saying what breaks without it. The same omission was in the scheduler example in the generated - `CLAUDE.md` and is fixed there too. - -**Why `scheduler_mode` has no default (a departure from spec sec. 7.5).** The spec names `"event"` -as the default. It is not implemented that way, and the reasoning belongs on the record because it -is the first question a reviewer will ask. - -Neither value is a defensible thing to inherit silently: - -- **`"in_process"` as the default would ship the defect.** It *is* #73 -- a timer in every replica, - so scaling past one fires every tick N times, and a pod hosting 20 grouped agents runs 20 timers. - Defaulting to it means only the projects that read the release notes closely enough to opt in get - the fix, and the ones that do not are precisely the multi-replica production deployments that can - least afford duplicated side effects. -- **`"event"` as the default would ship silence.** It is correct under an orchestrator, but it needs - something outside the process to publish the tick and a transport to receive it. A service whose - only job is periodic work may have neither -- `examples/health_monitor` registers two schedulers - and configures no `event_bus` at all -- and for those, event mode is not a line of config but a - broker they do not have. On upgrade they would simply stop ticking. - -Which value is right depends on facts this layer cannot read: whether a broker is reachable, -whether more than one replica runs, whether an orchestrator exists at all. That is the same shape -as `idempotency_ttl` in sec. 7.4, and it gets the same answer -- the framework provides the -mechanism and the author states the choice. The cost is one line of config per existing project, -paid once, against a startup error that names both options. - -The counter-argument, for the record: `"in_process"` as the default would have made this change -fully backward-compatible, and a required key does break every existing project with a scheduler. -That is accepted deliberately -- the break is loud, one-time and actionable, where the alternative -is a wrong default that stays wrong. It should be an amendment to spec sec. 7.5 rather than an -implementation detail that quietly contradicts it. - -**What is surfaced to the author.** `scheduler_mode = "event"` is written explicitly into the -scaffolded `settings.toml` as `"in_process"` -- the right value for the local `asbs dev` loop a new -project starts in -- with the trade-off and the requirement in a comment, the generated `CLAUDE.md` -gains three bullets on the two modes and the `super()` requirement, and -`docs/reference/configuration-keys.md` gains a `## Scheduling` section. -`examples/health_monitor`, the one project in this repository with schedulers, states -`"in_process"` and says why in a comment. That reference was also missing `idempotency_enabled` and -`idempotency_ttl` from P4 -- documented there now, in a `## Event Deduplication` section, together -with both keys in the example `settings.toml`. - -Tests: both modes read back, case tolerance, an absent/empty/whitespace value and an absent key -each rejected with both values named, rejection of an unknown value, single resolution; topic -derivation from `app_name` and from a renamed scheduler, the `topic=` override, a missing identity, -two wildcards, whitespace rejected in an explicit topic and rewritten in a derived one; `wire()` -creating a handler in event mode only, its idempotency, one trigger route in both modes, event mode -refusing three unusable `event_bus` values and accepting both broker transports, and in-process -mode needing no transport; `parse_bool` accepting a bool, the four true/false strings and rejecting -anything else; `on_startup` starting no timer in event mode, starting and -scheduling one in in-process mode, and starting no second timer or route when called twice (#43); -shutdown allowing a restart; the tick handler's declared topic, priority, name, the three context -keys it accepts, the topics it declines, the tick it runs, the absence of a published event, a -failing tick reaching the transport edge, and two schedulers registering distinct names against a -real `Registry`; `build()` wiring an event-mode scheduler before the transport decision and -creating no transport for an in-process one; and six assertions on the generated scaffold, -including that it parses. - -One offline integration test (`tests/integration/test_scheduler_event_mode.py`) exercises the -whole of event mode with nothing listening anywhere, which the Dapr transport makes possible: a -real `Config`, a real `build()`, the tick topic appearing in `GET /dapr/subscribe`, a CloudEvent -posted to `POST /events/` answering `SUCCESS` and the scheduler's `tick()` having run -once. It also pins the two things a unit test cannot see, both about what `build()` hands to -FastAPI: `POST /api//trigger` answering 200, and an in-process scheduler producing no -subscription document at all. Two more assert the loud failures at `build()`: a scheduler with no -`scheduler_mode`, and `"event"` with no `event_bus`. Three more cover the publish-only shape end to -end -- a pure scheduler that opts in gets a client and a publishing service while -`GET /dapr/subscribe` and `POST /events/...` both answer 404, one that does not opt in gets -neither, and a scheduler's lifecycle hooks run exactly once per lifespan (#43). - -Seven unit tests on `build()` cover the publish/consume split: no client without the opt-in, the -opt-in creating a client but no eventing component and no `EventProcessingService`, the string form -an environment variable delivers, and three rejections -- no transport, `"sessions"`, and a -non-boolean value -- plus the regression that a consuming application still publishes without the -key. - -### P5 -- the event-mode crontab is validated, and the manifest generator was tried and dropped (`662f7b5`) - -Event mode has no publisher yet: the schedule is declared in agent code and something outside the -process has to fire it. A `CronJob` renderer was written for that, reviewed, and then **removed -before it was ever committed** -- the image and entrypoint model is about to change what a manifest -even belongs to (see *Open points*), and an unused module in the framework would only mislead the -next reader. What survives is the one part that was not specific to generating manifests, plus a -record of what the attempt established. - -**`validate_crontab` stays, in `scheduler.py`, called from `wire()`.** In `"in_process"` mode -`CronTrigger.from_crontab` parses the expression, so a typo fails the pod. In `"event"` mode -nothing parsed it at all -- the tick arrives from outside -- so a bad expression surfaced as a -scheduler that reported itself healthy and never ticked: - -```python -if not croniter.is_valid(expression): - raise ValueError(f"The declared crontab '{crontab}' is not a valid cron expression.") - -fields = expression.split() -if len(fields) != 5: - raise ValueError( - f"The declared crontab '{crontab}' has {len(fields)} fields. An external scheduler reads the five standard " - "ones (minute hour day-of-month month day-of-week); seconds and year are apscheduler extensions it will not " - "understand." - ) -``` - -`croniter` rather than apscheduler's parser, because the consumer is an external cron reading the -five standard fields and apscheduler accepts extensions -- a leading seconds field among them -- -that no cron implementation does. That six-field form is rejected explicitly, since it is the -mistake an author familiar with apscheduler would actually make. - -**What the removed renderer established**, kept here because each of these is a trap that will have -to be avoided again wherever the generation ends up living: - -- **A Dapr publisher has to shut its own sidecar down.** The injected sidecar never exits, so the - Job stays `Running` -- and with `concurrencyPolicy: Forbid`, which the spec requires, every later - tick is then suppressed. A nightly job would fire exactly once and afterwards look like a broken - scheduler. `POST /v1.0/shutdown` after the publish is what lets the Job complete. -- **The tick's CloudEvent `id` must vary per run, and the shell quoting is where that breaks.** A - fixed id makes every tick after the first a duplicate once `idempotency_enabled` is on, so the - scheduler runs once and never again. Writing `$TICK_ID` inside a single-quoted JSON body -- the - obvious way to write it -- publishes the literal characters, because a single-quoted shell string - expands nothing. The quote has to be closed, the variable inserted double-quoted, and the quote - reopened. String assertions did not catch this; executing the generated script did. -- **The tick needs a `source`.** The dedup key is `(id, source)` and an event missing either is - dispatched untracked (sec. 7.4). -- **`time` is better left out.** The CloudEvent model defaults it correctly; a shell-formatted - timestamp can fail its ISO-8601-with-timezone validator. -- **A NATS URL can carry credentials, and a manifest is a repository file.** `nats://user:pass@host` - in `settings.toml` would be committed verbatim by any generator that inlines the configured URL. - It has to be detected and replaced with a secret reference. -- **Derived Kubernetes names must fail rather than truncate.** 63 characters minus the job and pod - suffixes leaves 52; truncating lets two schedulers differing only past the cut collapse into one - object, where the second silently overwrites the first. - -### P5 -- `"in_process"` fires once across replicas, and the cache gains a claim primitive (`662f7b5`) - -`"in_process"` mode was still #73 exactly as reported: an `AsyncIOScheduler` per replica, so three -replicas fired every cron job three times. Event mode was fixed by the queue group; this is the -other half, and it is the last thing that stood between the feature and the acceptance criterion -*cron fires once across three replicas in **both** `scheduler_mode` values*. - -**`CacheService.claim` -- set-if-absent, and the reason it had to exist.** P4's dedup and this -tick guard both use the cache to decide *which one of several processes does a piece of work*, and -`exists` followed by `set` cannot do that: two callers racing on one key both pass the check before -either write lands, and both believe they hold it. P4 recorded that as an open point ("a -compare-and-set primitive on `CacheService` (Redis `SET NX`) would close most of it and is not -written yet"). It is written now, as a new abstract method with an implementation per backend. - -Redis is the easy half -- one server-side operation, and expiry is the server's job: - -```python -stored = self._client.set(full_key, json.dumps(value), nx=True, ex=effective_ttl) -return bool(stored) -``` - -The disk backend needed a measurement first. `diskcache_rs.Cache.add` is set-if-absent and atomic -across processes sharing the directory, because the cache is opened with file locking. But its -`expire` argument is **not honoured**: an entry added with `expire=1` was still readable minutes -later. That is presumably why `DiskCacheService` already keeps TTLs in a parallel metadata entry, -and it is what shapes the implementation: - -```python -if not self._cache.add(namespaced_key, value): - if not self._logically_expired(ttl_key): - return False - self._cache.set(namespaced_key, value) - -if effective_ttl is not None: - self._cache.set(ttl_key, str(time.time() + effective_ttl)) -``` - -Had the backend's own expiry been trusted, a claim would never have expired and the scheduler would -have ticked exactly once and then never again -- the same shape of failure as a fixed CloudEvent id -under dedup. The stale branch is the one non-atomic path: `add` refuses a key whose *logical* TTL -has passed because physically it is still there, and taking it over is a read then a write. It is -only reached by a caller that reuses a key beyond its TTL, which the scheduler never does -- see -the key choice below. Both implementations fail **open** on an unreachable cache, matching every -other operation on the service: a cache that cannot answer must not stop the caller from working. - -**The scheduler claims the slot, not a lease.** The timer now runs a wrapper rather than `tick`: - -```python -async def _claimed_tick(self) -> None: - if not self._claim_tick_slot(): - logger.debug("Scheduler '%s' did not win this tick; another replica is running it", self.name) - return - await self.tick() - -def _claim_tick_slot(self) -> bool: - if not self.registry.has_cache(): - return True - slot = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M") - return self.registry.cache_service.claim( - {"scheduler": self.name, "slot": slot}, - {"claimed_at": time.time()}, - namespace=TICK_CACHE_NAMESPACE, - ttl=TICK_CLAIM_TTL_SECONDS, - ) -``` - -`add_job(self._claimed_tick, ...)` replaces `add_job(self.tick, ...)`, so nothing else about the -timer changes. - -**Why a slot claim instead of the leader lease the spec asked for.** This is a deliberate -departure, argued because it *removes* the question rather than answering it. Spec sec. 13 asked -whether that mode needs true failover -- a dead leader taken over within a bound -- or whether "one -designated instance runs it, others no-op" is enough, and noted that the cheap ordinal answer does -not work under a Deployment. With a per-tick claim there is no leader: - -- Nothing is held, so there is **no renewal task** to schedule -- and therefore no framework-created - background task to leak, which C7 exists to prevent -- and no lease left behind by a replica that - dies holding one. -- There is **no takeover bound to specify**, because the next slot is claimed from scratch by - whoever is alive. The failover question dissolves; the spec's open item is deleted rather than - answered. - -**The key is the slot, and that is what keeps set-if-absent sufficient.** `(scheduler, minute)`, -not `scheduler`. Cron granularity is one minute, so every replica firing for the same scheduled -time derives the same key and the next scheduled time derives a different one. Keying on the -scheduler alone would need a compare-*and-swap* on every tick after the first -- read the stored -slot, decide it is stale, write yours -- which is the racy path all over again. With a fresh key -per slot, the atomic `add` path is the normal path and the stale branch is never taken. - -The consequence, stated because it is real: replicas whose clocks differ enough to straddle a -minute boundary derive different slots and both tick. Container clock skew is milliseconds, and -sec. 7.4 covers a repeated tick as it covers every other repeat. - -**No cache means the mode behaves as it did before, loudly.** There is nothing to claim with, so -`_claim_tick_slot` returns `True` and every replica ticks. That is deliberate -- `"in_process"` -exists for local development, and demanding `.with_cache()` there would be gratuitous -- so -`on_startup` warns once, at startup, rather than per tick: - -``` -Scheduler 'x' started an in-process timer with crontab '...' and NO cache is registered, so its -ticks cannot be coordinated: every replica of this process will run every tick. Add '.with_cache()' -to the AppBuilder chain, or use 'scheduler_mode = "event"' where an orchestrator schedules the tick. -``` - -Event mode does **not** claim. The queue group already delivers a published tick to one replica, so -a claim there would be a second mechanism doing the same job; a test pins that the event path -touches the cache not at all. - -**Spec amended** (sec. 7.5): the modes table and the coordination paragraph now describe a per-tick -claim, the set-if-absent requirement and the slot-derived key are normative, the no-cache warning -is required, and the sec. 13 failover question is deleted. Three acceptance criteria were added -- -the three-replica case for both modes, `claim` being set-if-absent on both backends, and the -no-cache warning. - -Tests: the tick claim (winner ticks, loser does not, the key carries scheduler and minute, the -namespace and TTL are passed, **three replicas sharing a real `DiskCacheService` run one tick -between them**, a later slot is claimable again, no cache means every replica ticks, startup warns, -the timer is wired to the wrapper, and event mode claims nothing); and `claim` on both backends -(first wins, second refused, the loser does not overwrite, exactly one of five concurrent callers -wins, TTL behaviour, namespace isolation, stale takeover on disk, and failing open). - -### P6 -- one transport connection per namespace, and named connections (`be5e489`) - -The transport client stops being a process singleton and becomes namespace-owned. Nothing -creates a second one yet -- Phases 5 and 6 do that -- so for every application that exists -today this is a no-op with one visible change: connections are no longer anonymous. - -**`IOClientBase` takes a namespace, and derives the registry name from it.** -`IOClientBase.__init__(namespace="")` stores the namespace, exposes it as a public -`namespace` property, and registers the component as `qualified_component_name(namespace, -camel_to_snake(cls.__name__))` -- `nats_client` at the root, `orders_nats_client` under a -namespace. That last part is what makes the topology possible at all: `Registry.add_component` -raises on a duplicate name, so before this a second transport client of the same class raised -at construction. `NATSClient` and `DaprClient` both forward the parameter. - -Naming had to move *into* the constructor to work. `Component.__init__` registers the instance, -so the pre-existing pattern of renaming afterwards (`AIClientBase` still does it) cannot help: -the collision happens during `super().__init__()`, before any rename could run. `Component` -therefore gained a `name: str | None = None` parameter that overrides the class-derived name, -forwarded through `ClientBase` and `ServiceBase`. Both default to the old behaviour. - -**Connections are named `f"{namespace}.{group}.{pod}"`.** `nats.connect()` was called with no -`name=`, so every connection this framework opened was anonymous in `/connz` and a pod hosting -several agents was unreadable from the broker side. `_resolve_connection_name()` fills the three -positions from the namespace, `BLUEPRINT_GROUP` and `POD_NAME`/`HOSTNAME`/`socket.gethostname()`, -and `connect()` passes the result and records it on a public `connection_name` property. - -The group and pod are read from `os.environ` rather than through `Config`, because group -composition decides which agents get a `Config` at all (spec sec. 5.1) -- the group loader that -will own the variable arrives with the group configuration in Phase 8. Absent segments get a -placeholder (`root`, `ungrouped`, `unknown-pod`) rather than being left empty, so a name cannot -degenerate into `..pod-7` and "no group" stays distinguishable from a group whose name is empty. -The spec was amended to state that rule. - -**Consumer identity follows the namespace, which is the part that had to land with the -ownership change rather than after it.** Once two clients can share a process, the queue group -and the durable name can no longer come from process-wide config: - -- `_resolve_queue_group()` returns the namespace when there is one. Only the root namespace still - falls back to `nats_queue_group` then `app_name` -- which is what `nats_queue_group` is - documented to be, "the queue group for the root namespace only". Without the branch, every - client in a process resolves the same `app_name`, and two co-hosted agents subscribing to one - topic form a single queue group: the broker then hands each event to exactly one of the two - agents, so each silently sees about half of what it subscribed to. -- `_durable_for()` prefixes the namespace, so `orders` on `orders.created` binds - `orders-orders_created-durable`. Same failure otherwise, one layer down: two namespaces - resolving one durable name bind to the same JetStream consumer and consume each other's - events. The whole name is still sanitised, so a dotted namespace stays a legal consumer name. -- A configured `nats_durable_name` under a namespace now warns, naming the consequence. It is - legitimate when the key is scoped per namespace, and fatal when it is not, and the framework - cannot yet tell which -- config scoping (C5) is Phase 1. - -The durable prefix is Phase 5's item in the plan, taken early deliberately: P6 is what makes -co-hosted clients possible, so shipping it without namespace-qualified durables would ship a -latent cross-agent collision. It is dormant until a namespace exists -- the root namespace keeps -`-durable` -- so no deployment of this change is a consumer migration. Phase 5's own -migration note still applies to the filter-set work. - -**Deployment identity must never reach broker identity (C1).** The connection name contains the -pod, so a queue group or durable derived from it would change on every restart and every -regrouping. It is deliberately not stored where either is resolved, and a test asserts that a -junk `BLUEPRINT_GROUP` and `POD_NAME` leave both untouched. - -**`EventPublishingService` becomes per-namespace.** It takes a `namespace`, registers under the -qualified name, and `on_startup` resolves *its own* namespace's client instead of asking the -registry for "the" `IOClientBase`. Publishing another namespace's events down a shared -connection would make outbound traffic unattributable, which is the whole of reason 3. - -Resolution is the spec's rule -- own namespace, then root, raising rather than guessing -- and -lives in the new `component/namespace.py` alongside the naming helper, because the registry has -no namespace dimension yet (Phase 1) and both operations recur wherever a component becomes -namespace-owned. `resolve_for_namespace` raises on ambiguity instead of taking the first match: -picking one of two silently attaches an agent to another agent's transport. A namespace with no -client of its own falls back to the root one, so a namespaced agent in a process with a single -shared transport keeps working. - -**What P6 does not do, on purpose.** `DaprClient` accepts a namespace for health attribution and -C4, and its docstring says plainly that it confines neither ack loss nor slow-consumer -disconnects: it holds no broker connection, the sidecar owns and multiplexes one per pod, and -there is correspondingly nothing to name. Nothing in `app_builder.py` changed -- it still creates -one root-namespace client, which is exactly what a single-agent application should get, and the -rule that a namespace which neither subscribes nor publishes gets no client is already the -process-level behaviour there. `NatsEventing` still resolves the client by type; Phase 5 owns that -call site and reworks it per namespace. - -**Tests.** 50 new unit tests: namespace naming and resolution (`test_namespace.py`), client -ownership and coexistence, queue-group and durable derivation including the two-namespaces-on-one-topic -cases, the connection-name shape and every fallback in it, the C1 assertion that deployment identity -reaches neither, the Dapr namespace parameter, and the publishing service's resolution and its four -failure modes. Two existing publishing-service tests were updated: client resolution moved from -`get_component(IOClientBase)` to `get_io_clients()` plus the namespace filter. - -**Documentation.** `configuration-keys.md` gains a *Deployment Identity (environment only)* -section for `BLUEPRINT_GROUP`, `POD_NAME` and `HOSTNAME`, and the `nats_queue_group` and -`nats_durable_name` rows now say what a namespace does to them. Spec sec. 6 gains the placeholder -rule. - -### P6 review follow-up -- the namespace gets one definition, one alphabet, one gate (`be5e489`) - -Four defects found reviewing P6, all of which turned out to be the same defect: nothing said what -a namespace is allowed to look like, so each consumer of it decided separately. `component/namespace.py` -is now the single answer, and the four symptoms fall out of it. - -**One definition of the root namespace.** `ROOT_NAMESPACE` was declared three times -- in -`component/namespace.py`, as a class attribute on `EventHandlingBase` (`event_handling_base.py:48`) -and at module level in `scheduler.py:66`, the last two predating P6. Both now import the one in -`namespace.py`; the metric labels in `handle_event` read the imported constant instead of -`self.ROOT_NAMESPACE`. The constant's docstring now also says why it is not configurable: three -call sites branch on it being falsy, so a root namespace with a value renames every registry key -and every broker-side consumer, which is what C1 exists to prevent. - -**One alphabet, enforced at the point of entry.** New `validate_namespace()`: a namespace is `""` -or matches `[a-z][a-z0-9_]*`, and is rejected rather than repaired. It is called from -`IOClientBase.__init__` and `EventPublishingService.__init__`, replacing the `.strip()` that used -to silently repair `" orders "` while `"my orders"` blew up much later. Two exclusions carry -their reason in the error message: `-`, because it separates the fields of the durable name, and -`<`/`>`, because they are what make the connection-name placeholders unforgeable. - -The check it replaces was in `_resolve_queue_group()`, which is reached only by a NATS client that -subscribes -- so a publish-only namespace, or a Dapr one, kept an illegal name in its registry key, -its durable and (from C2) its telemetry resource without anything raising. Validation at -construction covers all of them, and the queue group now returns the namespace verbatim. - -**The durable name became unambiguous.** Forbidding `-` in a namespace is what makes -`f"{namespace}-{topic}-durable"` readable back: the first `-` is always the namespace boundary. -Before, namespace `orders-eu` on topic `created` and namespace `orders` on topic `eu-created` -produced the same durable, so two agents would have bound one JetStream consumer and consumed each -other's events -- the exact failure the namespace prefix was added to prevent. `_durable_for` now -rewrites only the topic (`f"{prefix}{re.sub(...)}-durable"` rather than sanitising the whole -string), because the namespace was already validated against an alphabet a consumer name accepts. - -**The connection-name placeholders became unforgeable.** `UNNAMED_NAMESPACE = "root"` collided with -a namespace actually called `root`, which is the ambiguity the placeholders were introduced to -remove. There is now one bracketed spelling -- `ROOT_LABEL` (`""`), reused for messages and -for the connection name -- plus `UNGROUPED_LABEL` and `UNKNOWN_POD_LABEL`. Since `<` and `>` are -outside the namespace alphabet, no namespace can spell one. - -The group and the pod are not ours to validate: they arrive from a pod template, and failing a -rollout over a display string is the wrong trade. New `display_segment()` sanitises them instead -- -`<`, `>`, `.` and whitespace become `_` -- so a group called `eu.west` cannot turn a three-segment -name into four (`.eu_west.pod-1`), an FQDN in `HOSTNAME` stays one segment, and nothing from -the environment can forge a placeholder. Sanitising is acceptable only because C1 forbids anything -deriving from the connection name, so a mangled segment loses no information downstream. - -**The gate moved from the two namespace-owned bases into `Component.__init__`, and `Component` -now owns the namespace.** `Component.__init__(should_register, name, namespace="")` validates the -namespace, then derives the registry name from it through `qualified_component_name`, and exposes a -public `namespace` property. `IOClientBase.__init__` collapsed to `super().__init__(namespace=namespace)` --- its `_namespace` assignment, its `namespace` property and its `_base_component_name` classmethod -are all gone, and `EventPublishingService` lost the same three. `ClientBase` and `ServiceBase` -forward the parameter. - -Two reasons this is not `Registry.add_component`, which was the other candidate. Coverage: eight -components construct with `should_register=False` -- `agent_runtime`, `handler_chain`, -`actuator_api`, `cache`, `root`, `telemetry`, and the `nats.py` and `dapr.py` eventing endpoints, -the last two of which become namespace-owned in phase 2 -- and a gate in the registry never sees -them. Ordering: `Component.__init__` runs before the name is derived and before registration, so -the illegal namespace never becomes a registry key even transiently. Having `Component` own the -namespace outright is what makes the gate sound: reading it back off a subclass attribute would -have left the check dependent on every subclass assigning `_namespace` before calling -`super().__init__()`. - -**Names that cross the process boundary are validated, not repaired.** New -`validate_subject_segment(segment, *, source, subject)` in `io_client_base.py`, applied at three -call sites, replacing two silent rewrites and one partial check: - -- `SchedulerBase.tick_topic` derived the subject as `re.sub(r"\s+", "_", f"{identity}.scheduler.{self.name}")`. - That subject is the contract: a `CronJob`, usually in another repository, publishes to it. An - `app_name` of `"Health Monitor"` silently became `Health_Monitor.scheduler.nightly`, so the - manifest author -- who cannot see the rewrite -- publishes to a subject this scheduler does not - subscribe to, the tick never arrives, and neither side logs anything. Both derived parts are now - validated instead, and the error names the key, the value and the subject it would have produced. - The scheduler's own name is checked too, because `with_scheduler(name=...)` reaches the subject. -- The explicit `topic=` override kept its whitespace check but had a separate wildcard check below - it; both are now the one helper, so the two paths cannot drift apart again. -- `_resolve_queue_group()`'s root fallback checked whitespace only. A queue group is read in - `/connz` *and* seeds the default dead-letter subject `.dead-letter`, so an - `app_name` of `my*service` produced a wildcard subject that the framework then publishes to. - Now rejected with the rest. - -The two rewrites that stay are named in the helper's docstring and in the spec: the topic portion -of a durable name (dots are legal in subjects, illegal in consumer names, so there is no -alternative -- bounded by the existing collision error) and the connection name (attribution only, -and C1 forbids anything deriving from it, so nothing outside can depend on its spelling). - -**One defect introduced and caught during this change:** inserting the `namespace` property between -`Component.name`'s getter and its `@name.setter` silently deleted the setter, which -`with_agent(name=...)`, `with_scheduler(name=...)`, `with_rest_api(name=...)` and `AIClientBase` -all assign through. `mypy` caught it as eight errors across four files; the property now sits below -the setter. - -**Tests.** 1337 unit tests pass (up from 1323). `test_namespace.py` gains `TestValidateNamespace` -and `TestDisplaySegment`, including the assertion that `ROOT_LABEL` cannot be produced by a legal -namespace. Four NATS tests changed to match the new behaviour rather than the old: whitespace and -dotted namespaces are now rejected at construction instead of trimmed or rewritten, and a -hyphenated one is rejected with the collision named. Three new connection-name tests cover the -dotted group, the forged placeholder and the FQDN host name. Five scheduler tests changed or were -added around the tick subject: the spaced `app_name` case inverted from "is rewritten" to "is -rejected", plus a wildcard identity, a spaced scheduler name, and an assertion that the error names -the key, the value and the subject. One NATS test gained the wildcard queue group; another had its -message assertion reordered. - -**Documentation.** Spec sec. 6 gains the unforgeability rule and the sanitise-not-validate rule for -group and pod; C1 gains the namespace alphabet and both exclusions with their reasons. -`configuration-keys.md` gains a *Namespace names* table, a *Names that become subjects are never -rewritten for you* section and the corrected placeholder spellings. C1 also gains the -validate-never-repair rule for boundary-crossing names, the two permitted exceptions, and the -requirement that the namespace gate live in `Component.__init__`. - -### `/status/env` stopped returning credentials (#91) - -Found auditing configuration handling for the config rework, and **pre-existing on `main` and -`develop`** -- introduced in `4e6421b`, unrelated to this feature. Filed as #91 and fixed here -because the grouped-process work makes the same endpoint cross-agent. - -`ActuatorApi._sanitize_config` masked a key only when the whole key equalled one of four words -(`api_key`, `secret`, `token`, `password`), so every compound key this framework actually uses was -returned in clear by `GET /status/env`: `openai_api_key`, `nats_password`, `azure_client_secret`, -any `*_token`. Lists were not walked either, so a list of provider entries was returned verbatim, -and a URL carrying inline credentials passed through because its key names nothing sensitive. - -`_sanitize_config` now delegates per pair to `_sanitize_value`, and the rules are stated in order: - -- `SECRET_KEY_MARKERS` is matched as a **substring** of the lowercased key (`key`, `secret`, - `token`, `password`, `passwd`, `pwd`, `credential`, `auth`, `private`, `salt`). Deliberately - over-broad -- `api_key_header` is masked although it holds nothing -- because a lost diagnostic - line is cheaper than a published credential, and the docstring says so. -- Dicts **and lists** are walked. -- `_strip_url_userinfo` removes `user:password@` from any string that parses as a URL carrying - userinfo, whatever its key, so `redis://admin:pw@cache:6379/0` under `redis_url` becomes - `redis://cache:6379/0` and stays diagnostic instead of becoming `***`. It returns non-URLs - unchanged -- unlike `_sanitize_redis_url`, which is handed a value already known to be a Redis - URL and can safely fall back to a placeholder. The docstring records why the two differ, so they - are not unified wrongly. -- Booleans pass through even under a matching key: a flag cannot carry a credential, and - `auth_enabled` is what someone reads this endpoint for. - -**Tests.** 17 new cases: ten compound keys as a parametrised set, secrets inside a list of dicts -and inside a list of strings, URL userinfo stripped under an innocuous key, a URL without userinfo -left alone, IPv6 brackets preserved, a boolean passing through, and a plain string containing `@` -left alone. 1354 unit tests pass. - -One unrelated formatting fix rode along: the nested conditional in `llm_status` was the one hunk -`black` wanted to rewrite in this file, and `ruff-format` accepts its version, so the file is now -clean under both formatters. - -### Phase 10 added to the plan -- migration and setup documentation, last - -Recorded on the user's prompt so it is not rediscovered later. No code: it adds a phase to -`docs/plans/2026-08-28-multi-agent-grouping.md` after Phase 9, and moves the phase range to 0-10 in -the plan's status line, `CLAUDE.md` and this changelog's header. - -**Why last rather than now.** Everything a migration guide would describe -- `AgentRegistration`, -group configuration, the entry point, the single image -- is built in phases 0, 2 and 8. Written -before them, a guide documents an API that does not exist, and a reader cannot tell which half is -aspiration. The plan already carries the migration *design* (*Migration path for an existing -agent*); what Phase 10 adds is the part a developer can read and run. - -**What it covers:** a new `docs/guides/multi-agent-setup.md` (scaffolding a group; migrating a -single-agent project; the section listing what stays byte-identical and why, which is what decides -whether anyone trusts the migration; and the one decision to make before migrating, since the agent -name becomes the queue group and part of the durable); `asbs setup` / `asbs create agent` / -`asbs validate` support; and the rewrite of `docs/guides/deployment.md`, which ships today and -contradicts this design. - -**One deliberate omission, stated in the phase:** there is no `asbs migrate` command. `main.py` is -the developer's own declaration, so a rewriter either guesses at intent or breaks on hand edits; a -checklist plus a `validate` that names what is missing is the honest shape. - -P6 is what makes the guide's central claim checkable rather than asserted: an existing project -keeps every registry key, queue group and durable name because the root namespace keeps them, and -that is now enforced by tests. - -### Config rework, step 1 -- logging leaves `Config`, and `app_port` leaves the scope - -The two prerequisites for one `Config` per namespace (C5). Neither is a namespace feature; both are -things that only work once, and therefore break the moment a process holds N of them. - -**`Config.__init__` no longer configures logging.** The call at the end of the constructor is gone; -the body it called is now the public `Config.configure_logging()`, and `AppBuilder.__init__` makes -the call before any `with_*()` runs, so components are constructed with the format already set. - -Two reasons, and the second is the one that forced it now. It is the application's decision, not -the loader's -- a library that configures logging on construction takes the root logger from -whatever imported it and cannot be silenced by the caller. And one `Config` per namespace means N -constructions per process: each one built a fresh `LoggingManager`, whose `_configured` flag is -per-instance and therefore never helped, so each re-attached the correlation and health-check -filters, logged "Logging configured" again, and let the last namespace's `log_level` win. Verified -before the change by constructing three scoped `Config`s in one process: three configuration lines. - -Existing projects are unaffected, because they all reach `AppBuilder`. What does change: code that -builds a `Config` and never an `AppBuilder` -- a script, a test -- now gets Python's default -logging until it calls `configure_logging()` itself, which is the correct behaviour for a library -and is why the method is public rather than private. - -**`app_port` is a root key even when a `Config` is scoped.** The scoped validator required -`.app_port` alongside `.app_name`. A group is one process behind one HTTP server, so -only one port can ever be bound: requiring it per agent makes every agent declare a value that all -but one of them cannot have. `app_name` stays scoped -- it is the agent's identity and reaches -telemetry and the queue group -- while the port is validated at root with the same `default=8000` -the unscoped path uses. - -**Tests.** 1361 unit tests pass (up from 1354). `TestLoggingIsTheApplicationsDecision` asserts that -construction configures nothing, that `configure_logging()` does, that it passes the resolved -settings, and that three constructions still configure nothing. `TestLoggingOwnership` asserts -`AppBuilder` makes the call exactly once and that a later `with_*()` does not repeat it. The -`app_port` test inverted from "missing scoped port raises" to two cases: a scoped config reads the -root port, and falls back to 8000 when there is none. - -`config.py` remains on `black`'s pre-existing reformat list: the nested conditional in -`_process_dynabox` is one of the places where `black` and `ruff-format` genuinely disagree -- unlike -the `actuator_api.py` hunk, `ruff-format` rejects `black`'s version here -- so it was left as it is -rather than picking a winner inside an unrelated change. - -### Config rework, step 2 -- one loaded tree, one view per namespace (C5) - -`Config` becomes the loader and the owner of the settings tree; each agent reads through a view of -it. This is C5 ("each namespace **MUST** receive a `Config` with `agent_scope` set"), implemented -without N loads and without giving each agent a window on its neighbours. - -**`Config.for_namespace(namespace)` returns a scoped view sharing the loaded tree.** The view is a -shallow copy differing only in `_agent_scope`, so `for_namespace("orders").get("model_name")` -resolves `orders.model_name` and falls back to the root `model_name`, while `nats_url` and the rest -of the infrastructure keys stay shared. The files are parsed once per process, not once per agent: -a test asserts `view._settings is config._settings`. Views are cached per namespace, so a component -asking twice gets the same object. - -This cost almost nothing because every read already funnelled through one place: the nine typed -getters call `self.get()` 25 times and never touch the tree directly, so scoping `get` scopes all -of them. A test covers that rather than trusting it. - -`for_namespace("")` returns the object itself -- not an optimisation but the definition, since the -root namespace *is* the unscoped configuration. Calling `for_namespace` **on a view raises**: a -view is one agent's window, not a factory for other agents' windows, and allowing it would hand -every namespace an unlogged route to its neighbours' keys. - -**`Component.config` returns the component's own view.** A root-namespace component gets the -configuration object unchanged, so every existing application reads exactly what it read before; -a namespaced one gets `shared_config.for_namespace(self._namespace)`. This is what makes the view -more than an unused abstraction, and it is available now only because P6 put the namespace on -`Component` itself. - -**The raw tree becomes an audited escape hatch.** `self.settings` was a public attribute; it is now -a property over `self._settings` that logs on every access. The user asked for a hatch that logs -rather than a wall, so isolation here is **audited, not enforced** -- and the docstring says so, -because the difference matters to anyone relying on it. Enforcing it would mean making the tree -unreachable, which breaks the actuator environment endpoint and any project reading a key the typed -getters do not model. - -The level distinguishes the two cases, which is what keeps the audit useful rather than noisy: the -loader is the application's own object and owns the tree, so its access is DEBUG; a **namespaced -view** handing out the whole tree is an agent reading past its own subsection, so that is WARNING -and names the namespace. An existing single-agent application therefore logs nothing new. - -**Deployment identity is refused, not returned as `None`.** New `DEPLOYMENT_IDENTITY_KEYS` -(`blueprint_group`, `pod_name`, `hostname`) raises from `get()` with the reason: code that can read -its group or pod can be written to depend on them, and regrouping then breaks it (C6). `None` would -have read as "not configured" and sent the caller hunting for a missing setting. The check sits in -`get()`, the single reader every typed getter funnels through, and it is case-insensitive. This is -also the prerequisite for step 3: with `envvar_prefix` disabled Dynaconf absorbs the entire process -environment -- `BLUEPRINT_GROUP` included -- and this is what keeps it out of reach. - -**Tests.** 1387 unit tests pass (up from 1361). New `test_namespace_views.py`: scoped resolution and -root fallback, two agents disagreeing only where they override, the root being the object itself, -caching, the shared tree, the view-of-a-view refusal, the typed getters being scoped, the C6 -refusals including case and the `default=` argument, and the audit -- a view warns and names itself, -the loader does not, and the hatch still returns the whole tree. `TestConfigIsScopedToTheNamespace` -covers the `Component` side. - -**Two test-fixture changes the production change forced, both worth noting.** Six `mock_config` -fixtures are `MagicMock(spec=Config)`, so `for_namespace()` returned a *different* mock and any test -asserting on `mock_config.get` for a namespaced component broke; they now set -`config.for_namespace.return_value = config`, so the mock stands in for both the loader and its -views. And `tests/unit/agents/agent/conftest.py` builds `AgentRuntime` with `object.__new__`, -bypassing `Component.__init__`, so it now supplies `_namespace` the way it already supplied `_name`. -The alternative -- making `Component.config` tolerate a missing `_namespace` via `getattr` -- was -rejected deliberately: it would hide a real ordering bug in any subclass that reads configuration -before calling `super().__init__()`, which is exactly the failure that should be loud. - -### Config rework, step 2b -- the loader stops being reachable from agent code - -Found by review immediately after step 2: the scoped view and its audit could be walked past. Every -class in this framework is a `Component`, so `Component.shared_config` was in reach of every -handler, service and client -- and it hands out the **unscoped loader**, so a read through it is -neither namespaced nor logged. - -It was worse than a class-level name. `configure()` assigns through `cls`, so the value lands on the -`Component` class itself, which *is* in the instance MRO: `self.shared_config` resolved too, which -is the easiest thing to type and the least likely to look wrong. Probed rather than assumed -- all -four of `self.shared_config`, `Component.shared_config`, `type(self).shared_config` and -`type(self).config` returned the loader. - -**`shared_config` is now `_shared_config`, with no public read path at all.** The only route to -configuration is the instance property `Component.config`, which returns the component's own view -(C5) and logs any raw-tree read. Two small public additions on the metaclass replace what tests -were using the attribute for: `has_config()` reports whether configuration has been injected without -handing over the loader, and `reset_shared_state()` clears the process-wide state, which a suite -building more than one application has to do between cases. 13 assignments and 3 reads across the -suite moved onto them. - -**The metaclass `config` property is deleted, and it was the sharper trap.** It returned -`cls._shared_config` -- the *unscoped loader* -- under the name that means *scoped view* on an -instance, so `MyHandler.config` and `self.config` were two different things one character apart. -Nothing used it: a grep for class-level `.config`/`.registry` access across `src/` and `tests/` -found no hits, so it was dead code as well as a trap. - -**`shared_registry` deliberately stays public.** Hiding it protects nothing: looking up -collaborators is the registry's whole purpose, every component already reaches it through the public -instance property, and `AppBuilder` needs it before any component instance exists. A class-level -property named `registry` was tried and reverted -- it collides with the instance property of the -same name, and mypy resolves the instance one in preference to the metaclass one, so -`Component.registry.cache_service` failed to type-check. The reverted attempt is recorded in the -metaclass docstring so it is not retried. - -**Tests.** 1391 unit tests pass (up from 1387). `TestTheConfigLoaderIsNotReachable` asserts the -class-level accessor is gone, that no instance answers to `shared_config`, and that `has_config()` -and `reset_shared_state()` do their jobs. Three `Component.registry` class-level reads in -`test_component.py` moved to `shared_registry`, since deleting the metaclass property is what made -them resolve to the property object rather than the registry. - -`tests/integration/test_sessions_startup_resilience.py` keeps its pre-existing formatting: `black` -wants to rewrite one assertion there and `ruff-format` rejects the result, so the file stays on the -known-debt list rather than having a winner picked inside an unrelated change. - -### Config rework, step 3a -- the environment-variable prefix becomes the project's to choose - -Until now the only spelling an environment override could have was Dynaconf's own `DYNACONF_`. -That is a library's name in a deployment's interface: a chart for a platform hosting several -Blueprint groups has no way to say which of them a variable is meant for, and an operator reading -`DYNACONF_MODEL_NAME` cannot tell it belongs to this framework at all. - -**`envvar_prefix` is now a top-level key in the settings file, overridable in the environment by -`BLUEPRINT_ENVVAR_PREFIX`.** Precedence is environment, then file, then `DYNACONF` -- so a project -that declares nothing behaves exactly as before, which is the point: every existing chart keeps -working untouched. - -**It is resolved in the first Dynaconf pass, not the second.** `Config.__init__` already had a -bootstrap pass whose only job was to read `app_environment` before the real load. The prefix has to -be known before the tree that uses it exists, so it is resolved there, from the files read through -the default prefix -- the one spelling that is always available. - -**That pass then runs a second time whenever the resolved prefix is not the default.** Without it, -`_APP_ENVIRONMENT` would be invisible to the only read that consumes it: the main pass -would load the `[development]` section while every other key honoured the override, and nothing -would report the mismatch. The repeat is skipped entirely for the default prefix, so the common -case still parses the files twice, not three times. - -**Four declarations are rejected rather than repaired**, each because the alternative is silent: - -- **A lowercase prefix.** Dynaconf does `prefix = prefix.upper()` before matching the environment - (`loaders/env_loader.py`), so a declared `myapp` looks for `MYAPP_`. On Linux the - `myapp_` that was actually exported is then never read, and nothing says so. Windows hides - the bug -- its environment is case-insensitive -- so this is exactly the defect that ships. The - alphabet is `[A-Z][A-Z0-9_]*`; commas are excluded too, because Dynaconf reads a comma-separated - prefix as a *list* of prefixes and one override spelling is enough. -- **`BLUEPRINT` and `POD`.** Dynaconf strips the prefix to form the key, so `envvar_prefix = - "BLUEPRINT"` turns `BLUEPRINT_GROUP` into the readable key `group` -- and the C6 blocklist names - `blueprint_group`, not `group`. A prefix could therefore have quietly reopened the hole - `DEPLOYMENT_IDENTITY_KEYS` exists to close. The rejected set is *derived* from that blocklist - (`_ENVVAR_PREFIX_IDENTITY_COLLISIONS` takes the segment before the first underscore), so a new - identity variable closes its own hole without anyone remembering to. -- **`envvar_prefix = true`**, which names no prefix, and any non-string. -- **A prefix declared inside a section.** This is the mistake a developer will actually make: - putting it under `[default]` next to `app_name`. The resolving pass runs with - `environments=False`, so a section is one opaque value to it and the key inside is invisible -- - and it has to run that way, because the prefix is what decides how `app_environment` is read. - Left there it would name no prefix, so *every* override relying on it would be ignored at once. - `_reject_sectioned_envvar_prefix` walks the bootstrap tree and raises naming the path it found - (`development.envvar_prefix`). - -**`envvar_prefix = false` disables the prefix**, and this is a footgun that ships documented rather -than hidden. Dynaconf then absorbs the entire process environment: probed on this machine, 88 keys -against a 5-key settings file, `PATH`, `BLUEPRINT_GROUP`, `POD_NAME` and every `*_API_KEY` in the -shell among them. It is *safe* only because step 2 put `DEPLOYMENT_IDENTITY_KEYS` in front of -`get()` -- with the prefix off, `BLUEPRINT_GROUP` lands in the tree as `blueprint_group`, which is -the exact spelling the C6 blocklist refuses, and a test asserts that for all three identity keys. -The environment spellings that mean off are `false`, `0`, `no` and the empty string, matching -`parse_bool` rather than inventing a second boolean vocabulary. The guide recommends a short -project prefix and describes what disabling it exposes. - -**One Dynaconf behaviour is worth stating because it is not optional.** `DYNACONF_*` is loaded -whatever the prefix is, and cannot be turned off: - -```python -if global_prefix is False or global_prefix.upper() != "DYNACONF": - load_from_env(obj, "DYNACONF", ...) -``` - -So declaring a prefix **adds** a spelling rather than replacing one, and because the custom prefix -is loaded second it wins for the same key. Verified both ways. This is good for migration -- an old -chart keeps working while a new one moves -- and bad for anyone who declares a prefix believing -they have closed the `DYNACONF_` door. Both directions are tested and both are in the docstring. - -`Config.envvar_prefix` is a public read-only property, because "my variable is ignored" and "my -variable is misspelled" are otherwise indistinguishable; the startup log now names the resolved -prefix (or says the environment is read unprefixed). A namespace view shares it: the prefix is a -property of the process, and `for_namespace` copies it with the rest of the loader. - -**Tests.** 1421 unit tests pass (up from 1391), 30 of them new in -`tests/unit/agents/config/test_envvar_prefix.py`: resolution and precedence, the environment -selected through the resolved prefix, `DYNACONF_` surviving alongside a custom prefix and losing to -it, every rejection above, the four falsy spellings, and C6 still holding with the prefix disabled. -An autouse fixture strips ambient `DYNACONF_*` from the environment, since the developer's own shell -can otherwise satisfy or defeat the very lookup under test. - -`src/blueprint/agents/config/config.py` keeps its pre-existing `black` disagreement in -`_process_dynabox`, which this change does not touch: it is on the known-debt list because -`ruff-format` reverts what `black` wants there. - -### Config rework, step 3b -- the environment endpoint answers per agent, and reads the tree once - -`GET /status/env` flattened the whole settings tree into one dictionary. In a grouped process that -is every co-hosted agent's configuration in one blob, with nothing saying which agent a key belongs -to -- and worse, nothing saying what any agent actually *resolves*, because an agent reads its own -subsection overlaid on the root keys and neither half alone is the answer. - -**`Config.resolved_settings(namespace)` builds the dictionary an agent reads.** Root keys, minus -every other namespace's subsection, with this namespace's own subsection overlaid. `""` returns the -whole tree, which is what the root namespace resolves -- so a single-agent application is -unaffected. The overlay skips `None`, matching `_scoped_get`, where `None` at a scoped key means -"not set" and falls back to the root while `""` and `[]` do not. - -Two bugs in the first version of that overlay, both caught by probing it against `get()` key by key -rather than asserting it looked right: - -- **`as_dict()` upper-cases only the top level of the tree**, leaving a subsection's own keys as - written. So the overlay landed `app_name` *beside* `APP_NAME` instead of on it, and the resolved - dictionary reported the root value while `get()` answered the agent value. Fixed by upper-casing - the overlay key. -- That also silently broke the `None`-versus-empty distinction: `billing`'s `model_name = ""` - resolved to the root `"root-model"` in the flattened dictionary and to `""` through `get()`. The - same fix covers it, and a test now asserts equality with `get()` for both agents key by key. - -**`Config.namespaces` lists the namespaces that have asked for a view**, sorted. That is group -membership as configuration sees it, and it is the only reliable source: a namespace subsection and -an ordinary nested table such as `[default.cache]` are indistinguishable in the tree, so the -endpoint cannot discover agents by inspecting it. - -**Both are root-only, and raise on a view -- this is C6, not tidiness.** A view is what agent code -holds (`Component.config` returns one for a namespaced component), so `namespaces` on a view is an -agent asking who it is grouped with, and `resolved_settings("other")` on a view is an agent reading -a neighbour's configuration. Both raise `RuntimeError` naming the namespace that asked, the same -rule `for_namespace` already applies to itself. C6 is thereby enforced at the two new entry points -rather than being left to the endpoint to respect. - -**`env_status` now returns three things instead of two.** `settings` is what the root resolves, -`namespaces` carries one masked entry per agent, and `envvar_prefix` reports what step 3a resolved -(`null` when the prefix is disabled -- unambiguous for a JSON consumer in a way `""` is not). -`namespaces` is empty for every existing single-agent deployment, so the response is additive. - -**The per-namespace breakdown is masked exactly like the root tree.** It is a second copy of the -same values, so `_sanitize_config` runs over each entry; a test asserts that no marker string from -a secret in either the root or an agent section appears anywhere in the serialised response. - -**The raw tree is read once per request.** `env_status` read `config.settings` three times -(`as_dict`, `current_env` for the log, `current_env` for the response) and `build_status` twice. -`Config.settings` is the *audited* property added in step 2 -- every read logs -- so one operator -request produced three records, and would produce a WARNING per read if the actuator ever holds a -view. Both endpoints now take one reference and read fields off it, and a test asserts the property -is touched exactly once per request. `build_status` also stopped reaching for `current_env` and -`settings_files` as bare attributes, which is what made the endpoint depend on the shape of a -Dynaconf object in two places instead of one. - -**An agent-scoped actuator reports only its own scope.** `ActuatorApi` is a root component by the -plan's sharing table, so this is the branch that should never be taken -- but if it is, the -endpoint must not call the two root-only methods and turn a status request into a 500. It falls back -to the tree it holds and an empty breakdown. - -**Tests.** 1443 unit tests pass (up from 1421). 13 new in `test_namespace_views.py` -(`TestResolvedSettings`, `TestNamespacesIsRootOnly`) and 9 in `test_actuator_api.py` -(`TestEnvStatus`). The endpoint tests use a **real** `Config` rather than a `MagicMock`: what is -under test is how the endpoint uses the real scoping and audit behaviour, and a mock would assert -only which methods were called. - -`src/blueprint/agents/io/api/actuators/actuator_api.py` keeps a pre-existing `ruff-format` -disagreement in `llm_status`, untouched by this change, and `config.py` keeps its pre-existing -`black` one in `_process_dynabox`. The new fixture writes its settings text through a named local -rather than a nested `write_text(textwrap.dedent(...))` call, because the two formatters disagree -about that construct and neither has to win. - -### Phase 0, part 1 -- `run_app`, and the worker count it refuses - -First piece of phase 0. `run_app(app, config)` in `utils/utils.py`, exported from -`blueprint.agents`, is the one line a project needs to become runnable by -`python src/main.py`: host, port and log level come from the same settings tree as everything -else instead of a uvicorn invocation duplicated in a Dockerfile, a compose file and a README. - -Development (`app_environment = "development"`) differs in exactly two ways -- the server logs at -`debug`, and it runs one worker whatever the configuration says. - -**`reload` is never enabled, and that is not an omission.** Auto-reload requires uvicorn to import -the application itself, so it needs an import string; it cannot restart an object that has already -been built. The plan said this; the docstring now says it too, because "why does reload not work" -is otherwise a question that gets answered by adding a broken parameter. - -**`app_workers > 1` raises instead of being passed through**, which is a departure from the plan's -"workers from `app_workers` config (default 1)". Two independent reasons, and either alone settles -it: - -- **uvicorn cannot honour it here.** With an application *object* rather than an import string, - `workers > 1` makes uvicorn log `You must pass the application as an import string to enable - 'reload' or 'workers'` against its own logger and call `sys.exit` (`uvicorn/main.py:603-607`, - verified against uvicorn 0.52.4). So the plan's version produces a process that dies before - binding a port, with a message naming a setting the operator did not touch. -- **It is the wrong shape for this framework even where it works.** Every uvicorn worker is a - separate process that builds the application again: N workers open N transport connections, join - the queue group N times, and start N in-process scheduler timers. Scaling is what replicas are - for, and the queue group (P1) and the per-tick claim (P5) are what make replicas correct. The - error message says this and names the alternative for anyone who wants it anyway. - -**The log level is translated, not validated.** The framework spells levels as `logging` does -(`"INFO"`), uvicorn wants them lower-case and has one level `logging` does not (`"trace"`). An -unrecognised value logs a warning and falls back to `"info"` rather than raising: this level -decides only how uvicorn narrates itself, nothing outside the process can depend on it, and the -application's own logging was already configured from the same key by `Config.configure_logging`. -That is the other side of the P6 rule -- names that cross the process boundary are validated, and -this one does not cross it. - -`DEFAULT_APP_HOST = "0.0.0.0"` carries a `# nosec B104`: bind-all is the only useful default -inside a container, which cannot know the address of the interface its traffic arrives on. **Not -verified locally** -- bandit is not installed in this working copy (see `CLAUDE.local.md`), so -whether the marker satisfies the hook is unconfirmed. - -**No caller in this repository yet, deliberately.** The examples end at `app = builder.build()` and -are served by the Dockerfile's `uvicorn src.main:app`, and phase 8 is what turns `main.py` into a -declaration served by `python -m blueprint.agents.entrypoint` -- which is the caller this exists -for. It is public API from today regardless, so it is usable rather than dormant. - -**Tests.** 1462 unit tests pass (up from 1443), 19 new in `tests/unit/agents/utils/test_run_app.py`: -the arguments uvicorn is handed, the two development differences, the level translation and its -fallback, `reload=False`, and the worker refusal -- including that it happens before `uvicorn.run` -is called at all. - -### Phase 0, part 2 -- the namespace becomes ambient, so a developer never writes one - -The constraint this serves, stated by the user while phase 0 was in progress and now the test the -design is held to: **a developer using the blueprint should not have to care about namespaces at -all**, and a project should read the same whether it runs as a single agent or inside a group -- -with `main.py` the only file that may differ. - -Threading a namespace through constructors fails that immediately: every handler, service and -client would carry a parameter that exists only because of how it is deployed. So the namespace is -**ambient during construction** instead. - -`component/namespace.py` gains three things -- placed there rather than in `component.py` as the -plan said, because that module already declares itself the single definition of what a namespace -is, and the scope validates through `validate_namespace` two functions above it: - -- `_CURRENT_NAMESPACE`, a `ContextVar[str]` defaulting to `ROOT_NAMESPACE`. -- `current_namespace()`, read by `Component.__init__`. -- `namespace_scope(namespace)`, a context manager: validate, set, and reset in `finally`. A - leaked namespace would attach the next agent -- or the framework's own root components -- to the - wrong one, and the registry key, the queue group and the durable name would all be wrong - together, so the reset is not left to a caller to remember. Nested scopes restore the enclosing - namespace rather than the root, and the namespace is validated **on entry**, so an illegal name - is reported against the registration that declared it instead of against whichever component - happened to be built first. - -**`Component.__init__` now resolves `namespace or current_namespace()`**, and the direction of that -`or` is the whole change: - -```python -self._namespace = validate_namespace(namespace or current_namespace()) -``` - -The obvious reading -- an explicit argument wins over the ambient scope -- is wrong here, and -quietly so. `ServiceBase`, `ClientBase`, `IOClientBase` and `EventPublishingService` all declare -`namespace: str = ROOT_NAMESPACE` and forward it **unconditionally**, so a developer writing - -```python -class OrderService(ServiceBase): - def __init__(self) -> None: - super().__init__() -``` - -passes an explicit `""` down to `Component`. Treating that as a decision would pin every -developer-written component to the root and leave the ambient scope applying to nothing that -matters -- the exact components the constraint is about. A *non-empty* argument still wins, which -is what the framework's own namespace-owning components (the transport clients, the publishing -service) rely on. The alternative -- a `None` sentinel threaded through four base classes -- was -rejected: it changes four public signatures to express what one `or` expresses, and it would have -to be repeated by every base class added later. - -**Nothing changes for a single-agent application.** Outside a scope `current_namespace()` is -`ROOT_NAMESPACE`, so `namespace or current_namespace()` is `""` exactly as before, and -`qualified_component_name` keeps the bare registry name. The 1462 tests that passed before this -change still pass unmodified. - -**One limit worth stating.** A `ContextVar` is not inherited by another thread or task, so a -component constructed off the builder's thread does not see the scope. That is the correct shape -rather than a gap: construction happens synchronously inside the builder, and anything built -lazily at request time is a root component by construction, which is what the fallback gives it. - -**Tests.** 1476 unit tests pass (up from 1462), 14 new. `TestAmbientNamespace` in -`test_namespace.py` covers the default, setting, exit, exit **on exception**, nesting, -the root scope as a no-op and validation on entry. `TestNamespaceComesFromTheAmbientScope` in -`test_component.py` covers the part that matters: a `ServiceBase` subclass whose `__init__` takes -no namespace and calls bare `super().__init__()` comes out namespaced, the same class registers -under two different qualified names in two scopes, and an explicit non-empty namespace still wins. - -### Phase 0, part 3 -- one declaration, applied alone or once per agent - -Completes phase 0. `AgentRegistration` collects component *classes* and builds none of them; -`AppBuilder.with_registration(registration, namespace="")` is what builds them, inside -`namespace_scope`. Together with part 2 that satisfies the constraint end to end: a project -declares its components once, and the same object serves both deployment shapes. - -```python -registration = AgentRegistration().with_service(OrderService).with_handler(OrderHandler) - -app = AppBuilder(config).with_registration(registration).with_cache().build() # alone -# a group applies the same object once per agent, under that agent's namespace -``` - -Verified rather than asserted: applying one registration under `orders` and again under -`billing` produces `orders_order_service` and `billing_order_service`, each resolving its own -`app_name` and `model_name` through its own scoped `Config` view -- with the word "namespace" -appearing nowhere in `OrderService` or in the declaration. - -**`with_registration` is new public API that the spec does not list.** Spec sec. 4.2 has only -`with_namespace(..., registration=...)`, which is phase 3. Added now because without a caller -`AgentRegistration` would be a collector nothing could consume for three phases, which is worse -than an extra method: it is a published API that does not work yet. It is also the exact call -phase 8's entry point needs per agent, so phase 3 narrows the gap rather than replacing this. - -**An already-built component is refused, and this is the part that would otherwise bite.** Four -of the five examples pass instances today -- `with_rest_api(MonitorApi())`, -`with_agent(agent)` -- which an `AppBuilder` chain accepts. In a registration that object is -constructed at import time, *before any namespace exists*, so it belongs to the root whichever -agent declared it; two grouped agents each declaring one would collide on its registry name, and -until they collided the misattribution would be silent. `_add` raises `TypeError` on any -`Component` instance, and the message names the class, the method and the fix. - -**Factories are accepted for the case a class cannot express.** `examples/document_summarizer` -builds its agent as `AgentBuilder(config, runtime_name=...).with_model_from_config()...build()` --- a fluent chain, not a class plus keyword arguments. A zero-argument callable is therefore a -legal target, called *inside* the scope, so the model and prompt resolve in the agent's own -namespace instead of at import time. `apply` distinguishes the two: - -```python -target = entry.target if isinstance(entry.target, type) else entry.target() -appliers[entry.kind](target, name=entry.name, **entry.kwargs) -``` - -A class is handed to the builder, which instantiates it -- still inside the scope. A factory has -to be called here, because the builder would otherwise take the callable itself for a built -component. - -**`apply` is public, departing from the plan's `_apply`.** It is called from another class, and -this repo's convention is that a leading underscore means internal to the defining class. - -**There is no `with_cache`,** per spec sec. 4.1: a cache is process-wide and belongs to the -`AppBuilder` hosting the group. An agent that declared its own would duplicate a neighbour's or -quietly take it over. `AttributeError` plus the class docstring is the whole of that story -- a -method existing only to raise seemed worse than one not existing. - -`RegisteredComponent` is a frozen dataclass (`kind`, `target`, `name`, `kwargs`) and -`AgentRegistration.components` exposes the tuple in declaration order. Order is preserved -because it is meaningful -- handler priority and scheduler wiring read it -- and the tuple is -what phase 8 will validate against `agents.toml` and what spec sec. 9.2's startup log needs. - -**Tests.** 1498 unit tests pass (up from 1476), 22 new in -`tests/unit/agents/app_builder/test_agent_registration.py`: nothing is constructed at -declaration time (asserted through `Component.shared_registry` still being `None`), order and -kwargs survive the round trip, the instance and non-callable refusals, root application keeping -the bare registry name, one declaration becoming two independently configured agents, the scope -being left behind afterwards, and a factory both deferred and called inside the namespace. - -**Not done, and the obvious next proof:** no example uses this yet. Migrating one project's -`main.py` to a registration would demonstrate the "only `main.py` differs" claim in the tree -rather than in a test -- and would have to convert its `with_rest_api(MonitorApi())` to the -class form, which is precisely the change the refusal above forces. - -### Phase 1, part 1 -- the registry resolves per namespace, without a namespace dimension - -Every lookup on `Registry` now takes an optional `namespace`, so two agents can own the same -component class in one process and each find its own. Verified: `orders` and `billing` both -declaring `OrderService` produce `orders_order_service` and `billing_order_service`, each -resolvable as the bare `order_service` from its own namespace, with a root-registered -`shared_audit` inherited by both. - -**The storage was not changed, and the plan's `dict[str, dict[str, Any]]` is not what this -needs.** The plan predates P6, which made every registry name namespace-qualified -(`qualified_component_name`). With qualified names, a namespace → name → component nesting -duplicates the namespace in the outer key and the inner name at once, and either the inner key is -the qualified name -- in which case the outer level carries no information -- or it is the bare -name, in which case `get_component("orders_order_service")` stops resolving and every existing -lookup, health-check entry and log line that uses `Component.name` breaks. So the namespace -dimension the plan asked for is already present in the key space, and what was missing was only -the ability to *ask* through it. - -Two kinds of question, and they resolve differently on purpose: - -- **"Find me the one X"** -- `get_component`, `get_service`, `get_scheduler`, `get_client`, - `get_agent` -- resolves **namespace first, then root**, because infrastructure stays shared - while an agent overrides what it owns. For a name that is `_lookup`, a new private helper that - tries `_` before ``; for a class it is `resolve_for_namespace`, which - P6 already wrote for this and whose docstring said it would become the registry's - implementation when the registry grew a namespace. It now is. -- **"Give me all the Xs"** -- `get_components_by_type`, `get_services`, `get_schedulers`, - `get_rest_apis`, `get_clients`, `get_event_handler` -- filters to **that namespace exactly**, - since iterating one agent's components must not sweep in a neighbour's. - -**`namespace=None` is the default and means every namespace, not the root** -- a departure from -the plan's `namespace: str = ""`. With `""` as the default, `build()` calling -`get_event_handler()` would have quietly seen only root handlers: correct on a single-agent -application, and silently short-staffed on a grouped one, which is the worst possible shape for -a default. `None` keeps today's behaviour exactly, so every existing caller is unaffected. - -Filtering is on the component's own `namespace` attribute, not on its registry name. An explicit -`name=` overrides the qualified name (documented on `Component.__init__`, used by -`AIClientBase`), so a name-based filter would lose exactly those components. - -**Ambiguity raises rather than picking a first match.** A class lookup with a namespace goes -through `resolve_for_namespace`, which refuses two candidates at the same level; without a -namespace the pre-existing "Multiple components of type X found" applies. Silently handing an -agent a neighbour's collaborator is the attribution the whole topology exists to provide. - -**`get_known_namespaces()` was NOT added, because C6 forbids it.** The plan asks for it so -`NatsEventing` and `build()` can iterate namespaces. But C6 says no API reachable from agent code -may expose the group's membership or size, and `Component.registry` is a public property on every -component -- so a `get_known_namespaces()` here is precisely the API C6 rules out, reachable by -`self.registry.get_known_namespaces()` from any handler. The builder already knows the group -composition, because it was told: it passes each namespace to the wiring that needs one, which is -also the layering the plan argues for elsewhere ("`AppBuilder` must remain a pure function of its -call sequence"). A test asserts the method does not exist, so it cannot be added back without the -reason being read. - -**Tests.** 1514 unit tests pass (up from 1498), 16 new in `test_registry.py` -(`TestNamespacedNameLookup`, `TestNamespacedTypeLookup`, `TestC6`): the fallback in both -directions, an already-qualified name still resolving, a bare name *not* resolving without a -namespace, the error naming where it looked, `None` returning every namespace, filtering by -attribute rather than name, ambiguity refused both across and within a namespace, and the absence -of `get_known_namespaces`. - -Still to do in phase 1: named caches (spec sec. 8) and the per-namespace executor. Note that the -executor has its own plan-versus-spec conflict to settle -- the plan provisions the root executor -eagerly in `build()`, while spec sec. 4.3 requires it to be created **lazily on first access**, so -that an application which never performs blocking work spawns no threads. - -### Phase 1, part 2 -- caches are looked up by name, and never substituted for one another - -`_cache_service: CacheService | None` became `_caches: dict[str, CacheService]`, with -`add_cache(name, cache)`, `get_cache(name="default")`, `has_cache(name="default")` and -`get_all_caches()`. `DEFAULT_CACHE_NAME = "default"` names the one every existing application -has, and `registry.cache_service` -- getter and setter -- is retained as an alias for it, which -spec sec. 8 requires. Every existing caller (`with_cache`, `HandlerChain`, the scheduler tick -claim, the cache management endpoints, the health check) reads the alias and is untouched. - -**`get_cache` has no fallback to the default cache, deliberately.** Spec sec. 8: two -independently written agents both asking for `"sessions"` must not silently share one store the -moment they are grouped. A missing name is therefore an error naming what *is* registered, not -an invitation to hand over some other cache. This is the opposite of how components resolve -- -where namespace-then-root is right, because infrastructure is shared on purpose -- and the two -sit next to each other in the same class, so the module docstring and both docstrings say which -is which and why. - -**One behaviour change: registering a second cache under one name now replaces it and warns, -where the setter used to raise.** The plan asks for an upsert so a cache can be added after -startup, and an alias for `add_cache` cannot be stricter than the method it aliases. Replacing -silently would be worse than either, because the usual way to arrive twice at `"default"` is two -calls to `with_cache()` -- so it logs at WARNING with both backend types named. Two tests -asserted the old raise and were rewritten to assert the new behaviour; -`test_cache_sharing_via_registry.py` now protects the invariant that actually matters -- both -services still resolve one object, and `get_all_caches()` still has exactly one entry. - -`clear()` clears and drops every cache rather than the single one. - -`get_or_create_cache` from the plan was **not** written. It is specified as "atomic get-or-create -protected by an `asyncio.Lock`", but every registry method here is synchronous and every cache is -registered during `build()`, before a loop exists -- a lock that cannot be awaited protects -nothing, and nothing in the framework creates a cache lazily for it to protect. When something -does, it can be added with a mechanism that matches how it is actually called. - -### Phase 1, part 3 -- one thread pool per agent, and only if something needs one - -`Registry.get_or_create_executor(namespace, max_workers)` returns a namespace's -`ThreadPoolExecutor`, creating it on first use; `Component.executor` is the property a component -reaches it through: - -```python - @cached_property - def executor(self) -> ThreadPoolExecutor: - return self.registry.get_or_create_executor(self._namespace, self.config.get("executor_workers")) -``` - -One pool per namespace, so an agent doing blocking work -- DiskCache, SQLite, a synchronous SDK --- cannot exhaust the pool another agent is waiting on. Threads are named -`blueprint-_N`, so a stack dump says which agent a blocked thread belongs to. - -**Created on first access, not provisioned in `build()`, which is a departure from the plan and -required by spec sec. 4.3.** The plan says "the root executor is provisioned in -`AppBuilder.build()` (not in `with_namespace`) so standalone apps always have one". That would -add `cpu_count() + 4` idle threads to every application that has no blocking work at all -- -including every single-agent application that exists today -- and works directly against the -thread budget in #36. Verified: with nothing asking, the process has one thread and -`_executors` is empty. - -**The plan's root fallback is subsumed rather than implemented.** `get_executor` was to fall back -to the root when a namespace had no pool; with creation on demand a namespace can never be -missing one, so that branch could never be taken. For the same reason there is no `add_executor`: -nothing needs to hand a pool in. - -**Sizing is per namespace, and the first asker wins.** `executor_workers` is read through -`Component.config`, which is the namespace's scoped view (C5), so one agent can be sized -differently from its neighbour. A live pool cannot be resized, so a later component of the same -namespace passing a different value is ignored rather than raising -- failing an application over -a number nobody chose deliberately would be worse than using the first one. - -**The pools are shut down with the application.** `Registry.shutdown_executors()` waits for -running work and clears the map, and it is called at the very end of the lifespan shutdown -- -after every `on_shutdown`, because a component may well run its last blocking call there -- and -from `Registry.clear()`, so a test suite building many applications does not accumulate pools. -This is not optional tidiness: a `ThreadPoolExecutor`'s workers are non-daemon threads, so -leaving them running keeps the interpreter alive past the point the container was asked to stop. - -No public read accessor for the executors was added; nothing in `src/` needs one, and the two -tests that check the map is empty read the private attribute rather than growing the API for -their own convenience. - -**Tests.** 1538 unit tests pass (up from 1514), 24 new. `TestNamedCaches` (11) covers lookup by -name, the absence of a fallback, the error listing what is registered, the alias in both -directions, `get_all_caches` returning a copy, and `clear` clearing every cache. -`TestExecutors` (9) covers nothing existing until asked, creation then reuse, isolation between -namespaces, sizing on the creating call and being ignored afterwards, thread naming, and -shutdown from both entry points. `TestExecutorBelongsToTheNamespace` (5) covers the component -side: its own namespace's pool, two agents not sharing, two components of one agent sharing, and -sizing from the scoped configuration. - -**Phase 1 is complete.** `Component.executor` belongs to spec sec. 4.3 rather than to phase 1 -strictly, and was written here because the registry half is unreachable without it -- an -executor store with no way to reach it is the unused surface this repo keeps out. - -### Phase 2 -- a component's registry answers for its own agent - -Phase 2 is titled "component namespace awareness", and three of its four bullets were already -satisfied by earlier work: the `ContextVar` and `Component.__init__` reading it landed in phase 0 -part 2, `Component.executor` in phase 1 part 3, and `shared_registry` was never going to stop -being a class-level singleton. Its fourth -- passing `namespace=` to `add_component` -- is -obsolete: phase 1 kept the flat store precisely because P6 had already made the registry name -namespace-qualified, so the namespace is in the key. - -What was actually missing is the half phase 1 enabled and nothing used. Every lookup on `Registry` -took a `namespace`, and **no caller passed one**, so a grouped process would have resolved -collaborators at random or refused to choose. Two examples from the framework's own code, both -written long before namespaces: - -```python -self._client = self.registry.get_component(NATSClient) # io/api/eventing/nats.py:33 -handlers = sorted(self.registry.get_event_handler()) # handler/handler_chain.py:130 -``` - -With one transport client per namespace (P6) the first raises "Multiple components of type -NATSClient found" the moment a second agent joins the process, and the second dispatches one -agent's event to another agent's handlers. Neither call site may grow a namespace argument, -because the constraint is that no code names a namespace unless it is about namespaces. - -**`Registry.for_namespace(namespace)` returns a view, and `Component.registry` hands each -component its own.** The mechanism is the one `Config.for_namespace` established in the config -rework, deliberately: a shallow `copy` sharing `_components`, `_caches` and `_executors` by -reference -- one registry per process, a view is a lens on it -- differing only in what an -*omitted* `namespace` argument means. - -```python - def _effective_namespace(self, namespace: str | None) -> str | None: - return self._default_namespace if namespace is None else namespace -``` - -- On the application's registry, an omitted namespace still means **every namespace**, so - `build()` and the lifespan keep iterating everything. Nothing about a single-agent application - changes; `for_namespace("")` returns the registry itself, as `Config.for_namespace("")` does. -- On a view it means **that agent**, so `self.registry.get_service(OrderService)` resolves this - agent's service, and `self.registry.get_service(EventProcessingService)` still finds the shared - root one through the namespace-then-root fallback. -- An explicit argument wins on either. - -**Calling `for_namespace` on a view raises**, as on `Config`: a view is one agent's lens, and -letting it mint another agent's would hand every component a route to its neighbours, which is -what C6 forbids. - -Verified with a service written the way a project writes one -- no namespace anywhere in it: - -``` - orders self.registry.get_service(OrderService) -> orders_order_service Audit -> audit - billing self.registry.get_service(OrderService) -> billing_order_service Audit -> audit -``` - -One declaration, two agents, each wiring itself correctly, plus a root-registered `Audit` shared -by both. - -**A hand-rolled resolution was deleted.** `EventPublishingService.on_startup` called -`resolve_for_namespace(self.registry.get_io_clients(), self.namespace, ...)` by hand, because P6 -needed namespace resolution before the registry could do it. It is now -`self.registry.get_io_client(IOClientBase)` -- the view resolves it -- which is what P6's own -changelog predicted would happen to that helper. - -**A bug the test rewrite caught, worth recording because the shape recurs.** `get_component` -gathered its candidates with `self.get_components_by_type(name_or_class, None)`, passing `None` -to mean "every namespace". On a *view* `None` means *this* namespace, so the resolver was handed -only the asking agent's components and its root fallback could never fire: a namespaced service -in a process with one shared root transport failed to find it. Fixed with `_all_of_type`, a -namespace-blind helper used by the two callers that must not have their argument reinterpreted --- the class-resolution path and the message that lists candidates when it cannot choose. The -six `EventPublishingService` ownership tests were rewritten from a `MagicMock` registry onto a -**real** one for exactly this reason: the mock version asserted that a stub returned what it was -told to, and would not have caught this. - -While there, the class-lookup failure message stopped printing a class repr: -"No IOClientBase is registered for namespace 'orders' or at the root" rather than -"No is registered ...". - -**Tests.** 1554 unit tests pass (up from 1538). `TestNamespaceViews` (12) covers the root -identity, caching, the shared store, the C6 refusal, omitted-means-this-agent, the root fallback -for both name and class lookups, plural lookups returning one agent, an explicit override, and -the application registry still seeing everything. `TestRegistryIsScopedToTheComponent` (4) covers -the component side. The six rewritten ownership tests now exercise the real resolution. - -### Still open after phase 2: cache names are not namespace-scoped yet - -Spec sec. 8 requires cache *names* to be namespace-scoped by default, with an explicit opt-in for -genuinely shared caches, so that two agents both asking for `"sessions"` do not silently share a -store. Phase 1 gave the registry the name dimension that policy needs, and phase 2 gave every -component a namespace-aware view -- but `get_cache` on a view still resolves the bare name, so -the policy is not enforced. - -It is left open rather than guessed at because the obvious implementation collides with something -that already exists: `CacheService.get/set/delete` take their own `namespace=` argument, which is -a *partition inside* a cache and is what a project already uses (`CACHE_NAMESPACE` in two -examples). So there are two plausible designs and they are not equivalent -- qualify the cache -*name* on the way in (`orders_sessions`, one backend per agent per name), or prefix the -*partition* the agent's calls land in (one backend, agent-scoped keys). The first isolates -storage and multiplies backends; the second keeps one backend and has to compose with the -developer's own partition argument without either silently winning. That is a decision, not an -implementation detail. - -### Cache names become namespace-scoped (spec sec. 8), and the pod filesystem decides how - -Sec. 8's requirement -- two independently written agents both asking for `"sessions"` must not -silently share a store once grouped -- had two plausible implementations, and the deployment -constraint settled it rather than taste. - -**The constraint.** A pod may write only where its process user is allowed to, and under -`readOnlyRootFilesystem: true` only where a volume is mounted -- a mount declared in the pod spec, -not discovered at runtime. `DiskCacheService` is a directory; `RedisCacheService` is a connection. -So the design that registers **one cache backend per agent per name** multiplies the writable -paths a group needs, gives each agent its own `size_limit` over one node-backed `emptyDir` (five -agents at the 1 GB default is 5 GB against one volume, and an `emptyDir` over its limit evicts the -pod), and turns "add an agent to this group" into a change to the pod spec. The design that -**prefixes the partition** needs no new path at all. - -**So the partition carries the agent.** New `services/infrastructure/agent_scoped_cache.py`: -`AgentScopedCache` wraps one shared backend and prefixes every call's `namespace` argument with -the agent, so `orders` writing `"prices"` lands in `orders.prices` and `billing` writing the same -name lands in `billing.prices`. One directory, one connection, one budget, whatever the group -size. - -`Registry.get_cache` (and the `cache_service` alias) returns that lens **when asked through a -namespace view**, and the raw backend at the root -- which is unchanged behaviour for every -single-agent application, and is also sec. 8's "explicit opt-in for genuinely shared caches": -framework code holding `Component.shared_registry` gets the shared store. The lens is cached per -name per view. Nothing at a call site changes: a service writing -`self.registry.cache_service.set(key, value, namespace="prices")` is isolated without naming a -namespace, because phase 2 already gave it a namespace-aware registry. - -The separator is `.`, not `:`: `:` already separates the partition from the hashed key -(`cache_key_mixin._make_key`) and `list_namespaces` splits on the first one, so `orders:prices` -would read back as the partition `orders`. A namespace cannot contain `.`, so stripping -`.` back off is unambiguous whatever the agent called its own partition. - -Three methods needed more than a prefix: - -- **`clear(None)` means this agent's partitions, never the whole cache.** The backend's own - `clear(None)` would take the neighbours' data with it -- the exact accident this class exists to - prevent -- so the lens enumerates the partitions it owns and clears those. -- **`list_namespaces()`** returns this agent's partitions with the prefix stripped, so an agent - sees the names it used. -- **`close()` raises.** The backend belongs to the process; closing it from one agent's lens would - take every other agent's cache down with it, silently. - -`get_stats()` forwards the backend's numbers and adds the agent's name: size, hits and eviction -are properties of the one shared store, and there is nothing per-agent to report. - -`ServiceBase.__init__` gained a keyword-only `should_register: bool = True`. `CacheService` is a -`ServiceBase`, so the lens is a component by inheritance, and one per agent per cache would -otherwise add a registry entry each. `RestApiBase` has taken the same parameter since before -namespaces, so this is the existing pattern rather than a new one. - -### The same constraint exposed a pre-existing defect: the disk cache cannot create its directory - -Read from the generated Dockerfile rather than observed in a cluster, and independent of grouping: - -- `cache.cache_dir` defaults to the **relative** `.cache/blueprint`, resolved against the working - directory, so `/app/.cache/blueprint` in the image. -- `DiskCacheService.__init__` creates it at **runtime** (`mkdir(parents=True, exist_ok=True)`). -- The image does `WORKDIR /app` **before** `USER appuser`, so `/app` is root-owned, and only - `src/` and `settings.toml` are `--chown`ed. Creating `/app/.cache` as `appuser` therefore fails - with EACCES. - -So a container built from the generated Dockerfile, running as the user it declares, with the -default cache backend, cannot start. It has not been noticed because tests and local runs have a -writable working directory. Three changes: - -- **The image creates the directory and hands it over**: - `RUN mkdir -p /app/.cache && chown -R appuser:appuser /app/.cache`. A project scaffolded before - this needs the same two lines. -- **The failure explains itself.** The `mkdir` is wrapped, and an `OSError` becomes a - `RuntimeError` naming the path and the four ways out -- create and chown it in the image, mount - a volume if the root filesystem is read-only, point `cache.cache_dir` somewhere writable, or use - the redis backend, which needs no filesystem. The original error is kept as `__cause__`. -- **`docs/guides/deployment.md` gained "Writable Cache Directory"**: the ownership requirement, - the `readOnlyRootFilesystem` + `emptyDir` manifest with `sizeLimit` matched to - `cache.size_limit`, the note that a grouped process needs no additional paths, and redis as the - filesystem-free alternative. - -**Tests.** 1577 unit tests pass (up from 1554). 21 new in `test_agent_scoped_cache.py`, against a -**real** `DiskCacheService` rather than a mock, since what is under test is which keys end up -where: isolation of values, absence rather than a neighbour's value, one backend, the partition -carrying the agent, per-agent `list_namespaces`, the scoped default partition, per-agent `delete` -and `claim` (two schedulers must not steal each other's tick slots), both `clear` shapes, the -`close` refusal, the root-namespace refusal, not registering itself, and the six paths through the -registry. Two more in `test_disk_cache_service.py` cover the unwritable directory: the message -names the path and the options, and the original `PermissionError` survives as the cause. - -### Not fixed, found while doing this: `app_environment` in `[default]` selects nothing - -The bootstrap pass runs with `environments=False`, so it sees only top-level keys -- `[default]` -arrives as one opaque value. All five examples declare `app_environment` *inside* `[default]`, where -that pass cannot read it, so it never selects an environment: it only lands in the loaded tree as a -value that `config.get("app_environment")` returns. A project that adds a `[production]` section and -sets `app_environment = "production"` under `[default]` gets `[development]` loaded and no warning. -Only a top-level `app_environment`, or `DYNACONF_APP_ENVIRONMENT`, actually switches sections. - -Pre-existing and out of this step, and the fix is not obviously safe -- honouring the sectioned key -would change which section an existing project loads. Left as a decision to take, not a defect to -patch inside a config change. - -### Deployment guide corrected (`2d80b63`) - -The guide recommended `replicaCount: 2`, an HPA, and `--set replicaCount=3` as ordinary scaling. It -now opens with a warning naming the three defects that make multi-replica incorrect rather than -merely inefficient, its examples default to one replica, and the HPA section says to leave -autoscaling off for now. Also dropped the spec's ADR-derived `Status: draft` row, since `draft` -belongs to ADR vocabulary while this repo uses Status as a revision marker. - -**Motivation.** This is the only piece of *existing, shipped* documentation that could cause harm -before any code changes: following it doubles every side effect and every inference bill, and -duplicates every cron tick. - -### Working rules for this feature (`4cf2d51`, `7735251`) - -`CLAUDE.md` gained two rules scoped to this feature: work in reviewable steps, one change at a time, -reported before the next begins; and explain new code, not just its arrival -- a walkthrough of the -mechanism whenever real implementation lands, with lint, typing, tests and docs exempt. - -**Motivation.** The feature is delivered across many sessions and unreviewed batches are expensive -to unpick. - -### Phase 3, part 1 -- a namespace can be named at the call site, and a group can be written by hand - -Phase 0 part 3 made the namespace ambient, and phase 1 and 2 made the registry answer per -namespace. What was still missing is the *entry point*: nothing outside `AgentRegistration.apply` -could put a component in a namespace, and there was no way to assemble a group at all. This step -adds the three builder-side pieces of phase 3; `with_cache(name=...)` follows as part 2. - -**The five `with_*` methods take a keyword-only `namespace`, and it never reaches the component.** -Their bodies were five copies of "build it if it is a class, adopt it if it is not, rename it if -asked", so they now share one helper and differ only in the type check `with_handler` performs: - -```python - def with_handler( - self, handler: type[HandlerT] | HandlerT, *, name: str | None = None, namespace: str = ROOT_NAMESPACE, **kwargs: Any - ) -> "AppBuilder": - if isinstance(handler, type) and not issubclass(handler, EventHandlerBase): - raise TypeError(f"Expected EventHandlerBase subclass, got {handler.__name__}") - self._register(handler, namespace, kwargs, name=name, method="with_handler") - return self -``` - -`AppBuilder._register` is where the namespace is turned into a scope rather than an argument: - -```python - if isinstance(target, type): - with _construction_scope(namespace): - instance = target(**kwargs) -``` - -This is the point of the whole ambient mechanism, and it is why the parameter cannot simply be -forwarded. The builder passes `**kwargs` straight to the constructor, and a project's component -takes the arguments its author wrote -- `StrictService(retries=3)`, no namespace anywhere -- so -`with_service(StrictService, namespace="orders", retries=3)` must construct -`StrictService(retries=3)` *inside* namespace `orders` and let `Component.__init__` read the -namespace from the context variable. Forwarding it would be a `TypeError` on every component a -developer has ever written. - -**`_construction_scope` exists because `namespace_scope("")` is not a no-op** -- it *sets* the -current namespace to the root: - -```python -@contextmanager -def _construction_scope(namespace: str) -> Iterator[None]: - if not namespace: - yield - return - with namespace_scope(namespace): - yield -``` - -Without that branch this step would have broken the mechanism it is extending. -`AgentRegistration.apply` opens one `namespace_scope("orders")` and then calls -`builder.with_service(target, name=...)` with no namespace argument -- so an unconditional -`namespace_scope(namespace)` would reset every component of every agent back to the root, with no -error, and every registration applied per agent would have produced a root component. There is a -test for exactly this (`test_the_default_does_not_reset_an_ambient_namespace`), because the failure -is invisible: the app builds, and the registry keys are simply wrong. - -**An explicit `name=` is now qualified with the namespace the component ended up in:** - -```python - if name is not None: - instance.name = qualified_component_name(namespace_of(instance), name) -``` - -A defect, not a refinement. `Component.__init__` qualifies a *derived* name but uses an explicit -one verbatim, so `AgentRegistration().with_service(OrderService, name="db")` applied to two agents -registered both as `db` and the second failed with "Component with name db already exists" -- the -one-declaration-per-group case, which is the primary API. Qualifying costs the caller nothing: -`Registry._lookup` tries `_` before ``, so `get_component("db")` from -inside the agent still finds it. `namespace_of(instance)` rather than the `namespace` argument, -because the instance may have come from the ambient scope instead. - -**An already-built instance offered to a namespace is refused rather than silently rerouted.** -A component's namespace and its registry key are fixed by the scope it was constructed in, so -`with_service(instance, namespace="orders")` cannot do what it says: - -```python - built_in = namespace_of(target) - if namespace and built_in != namespace: - raise ValueError( - f"{type(target).__name__} was passed to {method}() as an instance for namespace '{namespace}', " - f"but it was already built in namespace '{built_in or ROOT_LABEL}', and a component cannot change " - ... - ) -``` - -Ignoring the argument would register the component at the root while the caller believed it -belonged to an agent -- the same trap `AgentRegistration._add` already refuses instances for, and -the message points the same way: pass the class. An instance built inside the matching scope is -accepted, since nothing is being changed. - -**`NamespaceBuilder` is one agent's view of the builder**, and it holds no build state: five -`with_*` that delegate with `namespace=` filled in, `with_registration`, and `end()` returning the -parent. Registering a component therefore still has exactly one implementation, and this class only -decides which namespace it goes to. It has no `with_cache` -- a cache is process-wide (spec sec. 8), -and an agent registering its own would duplicate or quietly take over a neighbour's. - -**`AppBuilder.with_namespace(name, *, registration=None)`** is the entry point: - -```python - namespace = validate_namespace(name) - if not namespace: - raise ValueError("with_namespace('') names no agent: ...") - if namespace not in self._namespaces: - self._namespaces.append(namespace) - logger.info("Hosting agent namespace '%s'", namespace) - if registration is None: - return NamespaceBuilder(self, namespace) - return self.with_registration(registration, namespace) -``` - -`with_namespace("")` is refused: the root is the absence of an agent, and returning a block that -registers into it would be a silent no-op dressed as a declaration. The namespace is recorded -*before* anything is built, so a registration that fails half way through still leaves the agent -declared -- the startup log (spec sec. 9.2) and the readiness policy have to be able to say an -agent was meant to be here. - -**Two spec departures, both argued rather than assumed.** - -- **The `AppBuilder | NamespaceBuilder` union is kept, but no caller sees it.** Spec sec. 4.2 - types `with_namespace` as returning the union, which would make every call site narrow a type - it already knows statically. Two `@overload`s resolve it instead: `registration=` is an `AppBuilder`, `registration` omitted is a `NamespaceBuilder`. The runtime - behaviour is exactly what the spec asks for; the union survives only as the implementation - signature. -- **The `config: Config | None` parameter is not accepted.** Spec sec. 4.2 and the plan both list - it, and the plan says `with_namespace` should build a `Config` with `agent_scope=name` from the - root config's settings files. Config rework step 2 made that obsolete: `Config.for_namespace` - returns a view sharing the one loaded tree, and `Component.config` already hands each component - the view for its own namespace, which tries `.` before `` (C5). A `Config` - passed here would have no reader -- components do not consult the builder -- so it would be - either ignored outright or re-parse the same files once per agent and then be ignored. Accepting - a parameter that does nothing is worse than not having it: it reads as per-agent configuration - support that is not there. **Needs a spec amendment**; listed under *Open points*. - -**`AppBuilder.namespaces`** exposes the declared agents in declaration order, root excluded, so -phase 6 can iterate them. It lives on the builder because it may not live on the registry: -`Registry` is reachable from every component (C6), so a `get_known_namespaces()` there would let -an agent enumerate its neighbours, and grouping is supposed to be invisible from inside. The -builder is the object that was *told* which agents to host and is not reachable from a component. -A tagged `with_service(X, namespace="orders")` deliberately does *not* record a namespace: the -list is what the builder was told to host, not every namespace a component was tagged with. - -`NamespaceBuilder` is exported from `blueprint.agents`, since it is a return type callers can hold. - -Tests: `tests/unit/agents/app_builder/test_namespace_builder.py`, 36 cases -- the namespace -qualifying the registry key and reaching the component; the constructor *not* receiving it; the -ambient namespace surviving the default and being overridden by an explicit one; an explicit name -qualified, unchanged at the root, and one declaration with an explicit name serving two agents; an -instance refused for another namespace and accepted for its own; both `with_namespace` forms; the -root and an illegal namespace refused; `namespaces` order, dedup and its indifference to tagged -calls; and the block delegating, chaining, closing and carrying constructor arguments. - -### Phase 3, part 2 -- a cache has a name, and a name buys it its own store - -Phase 1 part 2 gave the registry `add_cache(name, cache)` / `get_cache(name)` and no fallback -between names. The builder never used any of it: `with_cache()` still went through the -`cache_service` setter, so a process could hold exactly one cache. This step is the builder side, -and three defects had to be fixed for it to work at all. - -**The signature change, and why the parameter order is the whole point:** - -```python - def with_cache(self, enabled: bool = True, enable_locking: bool = True, *, name: str = DEFAULT_CACHE_NAME) -> "AppBuilder": - if not enabled: - logger.info("Caching disabled; cache '%s' is not registered", name) - return self - - cache_config = _cache_config_for(self._config.get_cache_config(), name) -``` - -`name` is keyword-only and follows the two existing positional parameters, as spec sec. 4.2 -requires. Had it come first, `with_cache(False)` -- which *disables* caching in projects that -exist today -- would have become a cache named `False` with caching silently switched on, no -`TypeError` and no warning. `with_cache()`, `with_cache(False)` and `with_cache(True, False)` all -still mean exactly what they meant, and there are tests for the three of them. - -**Turning a name into isolated storage lives in `CacheBackendFactory`, not in the builder.** -It was written in `app_builder.py` first and moved on review, and the review was right: the -builder would have been the one place that knew disk caches isolate by directory and Redis caches -by key prefix. Anyone adding a third backend edits the factory and has no reason to open the -builder, so their backend would have inherited one store shared across every name -- the exact -failure the scoping exists to prevent, arrived at by writing new code in the obvious place. So -`create` takes the cache name and each `_create_*` scopes what its own backend needs: - -```python - @staticmethod - def create(config: CacheConfig, enable_locking: bool = True, name: str = DEFAULT_CACHE_NAME) -> CacheService: - CacheBackendFactory._validate_name(name) - if config.backend == "redis": - return CacheBackendFactory._create_redis(config, enable_locking, name) - return CacheBackendFactory._create_disk(config, enable_locking, name) -``` - -`create` is the single door through which a cache is built, so the name cannot arrive -unvalidated and a backend cannot be reached without having answered how it separates one name -from another. The builder is left with one line and no cache knowledge: - -```python - cache_service = CacheBackendFactory.create(self._config.get_cache_config(), enable_locking=enable_locking, name=name) -``` - -`config` reaches the factory **unscoped**. That matters for the fallback: `_create_redis` scopes -a key prefix, and when Redis is unreachable it hands `_create_disk` the original config plus the -name, so the fallback isolates by directory rather than carrying a prefix that means nothing to -it. Pre-scoping both fields before the branch -- what the first version did -- only worked because -it scoped fields no chosen backend would read. - -The two derivations, each on the backend that needs it. The default name returns the configured -value untouched, so an existing application's cache directory and Redis keyspace do not move: - -```python - def _scoped_cache_dir(config: CacheConfig, name: str) -> str: - if name == DEFAULT_CACHE_NAME: - return config.cache_dir - return str(PurePosixPath(config.cache_dir.replace("\\", "/")) / name) - - def _scoped_key_prefix(config: CacheConfig, name: str) -> str: - if name == DEFAULT_CACHE_NAME: - return config.key_prefix - return f"{config.key_prefix}:{name}" if config.key_prefix else name -``` - -- **Disk: `/`, a subdirectory and not a sibling.** The plan says - `{base_dir}/{name}` without saying which directory `base_dir` is, and only one reading is always - writable: a deployment may mount its volume *at* `cache.cache_dir`, and under - `readOnlyRootFilesystem` a sibling of the mount cannot be created -- see "Writable Cache - Directory" in `docs/guides/deployment.md`. The cost is that a named cache's directory sits - inside the default cache's own store. diskcache ignores directories it did not create, and the - alternative fails in production only. -- **Redis: the name is appended to `cache.key_prefix`.** *Not in the plan, and without it naming a - cache would have isolated nothing on Redis.* The disk backend separates caches by directory and - Redis has no analogue -- `RedisCacheService` scopes every key by `key_prefix` alone -- so two - caches registered as `sessions` and `prompts` against one Redis with one configured prefix would - have written the same keys. That is precisely the silent cross-cache sharing spec sec. 8 exists - to prevent, and here the name is the only thing meant to tell them apart. - -**The cache name is validated, because it is now a filesystem path segment:** - -```python -_ALLOWED_CACHE_NAME = re.compile(r"\A[a-z0-9][a-z0-9_.-]*\Z") -``` - -`with_cache(name="../evil")` would otherwise write outside the cache directory entirely. Lower -case only, and that is not tidiness: a directory whose name differs only by case is one directory -on a developer's macOS or Windows machine and two on the Linux node, so `Sessions` and `sessions` -would be one cache locally and two in production. Validation runs before anything is constructed, -so a refused name never creates a directory. - -**Three defects fixed to get here.** - -1. **Two caches collided on one registry name.** A `CacheService` is a `ServiceBase` and therefore - a `Component`, so it registers itself under a derived name -- and a second `DiskCacheService` - raised `Component with name disk_cache_service already exists`. Registering a named cache - without a component entry was not an option: the lifespan closes caches by iterating - `registry.get_services()`, so an unregistered one would leak its file handle or Redis - connection for the life of the process. `DiskCacheService.__init__` and - `RedisCacheService.__init__` therefore take `component_name`, forwarded to - `super().__init__(name=...)`, and `CacheBackendFactory.create` passes it through: - - ```python - @staticmethod - def _component_name(name: str) -> str | None: - return None if name == DEFAULT_CACHE_NAME else f"cache_{name}" - ``` - - `None` for the default, so `disk_cache_service` stays the key existing lookups and health - entries already use. `cache_` rather than `_` because `fallback_to_local` - swaps `RedisCacheService` for `DiskCacheService` at construction -- a registry key that depends - on whether Redis answered the startup ping is worse than one that does not name the backend. - Both fallback paths therefore produce the same registry name as the Redis service would have. - -2. **`with_cache()` as an application's first builder call crashed.** `Component.shared_registry` - is `None` until the first `Component.__init__` creates it, and a cache service is what creates - it here. Reading the registry before building the service is an `AttributeError` on `None`; the - old code happened to read it afterwards. The order is now explicit and commented, because - nothing about the line says it matters: - - ```python - cache_service = CacheBackendFactory.create(cache_config, enable_locking=enable_locking, component_name=component_name) - registry: Registry = Component.shared_registry # type: ignore[assignment] - registry.add_cache(name, cache_service) - ``` - -3. **`registry.add_cache` replaced the `cache_service` setter.** The setter still exists as the - spec sec. 8 alias and still reads and writes the `"default"` cache, so `registry.cache_service` - keeps working; the builder simply no longer goes through it. - -`CacheBackendFactory.create`'s third parameter is `name`, not `component_name`: the registry name -is derived from the cache name, so there is one name to pass rather than two that must agree. - -**Not done here, and deliberately.** Readiness and the management endpoints still see only the -default cache -- `if registry.has_cache(): health_providers["cache"] = ...` and the `CacheManagementApi` -mount are both keyed on the default name. Plan phase 6 owns both ("`CacheManagementApi`: one router, -endpoints accept optional `?name=`" and "`ActuatorApi` cache health: iterates all entries"), so a -project that registers only a named cache gets no cache health check until then. Nothing regresses: -those call sites are guarded by `has_cache()` and simply do not fire. - -Also noted rather than fixed: `add_cache`'s documented replace-and-warn path is unreachable from -the builder, because two `with_cache()` calls with one name now collide on the *component* name -first. That was already true before this change, and the resulting error names the colliding key. - -Tests, split the way the code is. `tests/unit/agents/app_builder/test_named_caches.py`, 33 cases, -covers what is visible through `with_cache`: the default cache keeping its name, directory, -registry key and `cache_service` alias; `with_cache()` working as an application's first builder -call; the three positional forms; a named cache getting its own directory (asserted on disk), its -own registry name, coexisting with the default, and appearing in `get_services()` so the lifespan -closes it; an unregistered name raising instead of yielding the default; and eleven rejected names. -`tests/unit/agents/services/infrastructure/test_cache_backend_factory.py` gains 34 cases for the -isolation itself: the derived registry name and its independence from the backend; the disk -subdirectory including a Windows separator in the configured path; the Redis prefix, asserted both -on the derivation and on the kwargs the service is constructed with; both fallback paths isolating -as disk rather than as Redis; and the name being validated before any directory is created. - -### Phase 4, part 1 -- dispatch happens per agent, and the root stops reaching into one - -Phase 1 and 2 made the registry answer per namespace and gave every component its own view of -it. The dispatch path never used any of that: one `HandlerChain` served the process, and it asked -the *application's* registry for handlers -- which in a grouped process means every agent's. This -step makes an event reach one agent's handlers and no other's. The dispatch index (spec sec. 7.7, -the second half of plan phase 4) is a separate step and is not in this one. - -**A `HandlerChain` now belongs to a namespace, and that is the only line about it in the class:** - -```python - def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: - super().__init__(should_register=False, namespace=namespace) -``` - -Everything else follows from `Component.registry` and `Component.config` handing a component its -own namespace's view: the handlers it dispatches to, the `idempotency_enabled` / `idempotency_ttl` -it reads, and the cache partition the dedup markers are claimed in (the agent-scoped lens from -spec sec. 8) are all that agent's already, with no further plumbing. Two agents in one process can -therefore run different dedup windows, and the tests assert exactly that against one settings -tree. - -**The namespace is named explicitly in `_dispatch`, and that is the load-bearing part:** - -```python - handlers = sorted(self.registry.get_event_handler(namespace=self.namespace)) -``` - -It looks redundant -- the registry view already defaults to its own namespace -- and it is not. -`Registry.for_namespace("")` returns the registry *itself*, whose `_default_namespace` is `None`, -and on the registry an omitted namespace means **every namespace**. So a root chain in a grouped -process would have dispatched one delivery through every agent's handlers. Naming the namespace -makes the root chain mean strictly the root, which in a single-agent application is every handler -there is -- unchanged. `test_the_root_chain_does_not_reach_into_an_agent` is the test for it. - -There is deliberately **no fallback to root handlers** either, unlike the singleton lookups that -resolve namespace-then-root. A handler registered at the root of a grouped process would -otherwise run for every agent in it, and nothing in a handler's code could tell its author that -was happening. - -**`EventProcessingService` keeps one chain per agent and stays a single root service.** What it -does -- correlation context, request ids, Dapr unwrapping, normalising handler output -- is the -same for every agent; what differs is the dispatch. So: - -```python - self._handler_chains: dict[str, HandlerChain] = {ROOT_NAMESPACE: HandlerChain()} -``` - -The root chain always exists, so an application that never mentions a namespace behaves exactly -as it did. `_chain_for(namespace)` creates the others: - -```python - chain = self._handler_chains.get(namespace) - if chain is None: - chain = HandlerChain(namespace=namespace) - self._handler_chains[namespace] = chain -``` - -**The chains are built at startup, not on first delivery**, and the namespaces come from the -handlers rather than from a list of agents: - -```python - for namespace in sorted({namespace_of(handler) for handler in self.registry.get_event_handler()}): - self._chain_for(namespace) - - for namespace, chain in self._handler_chains.items(): - await chain.on_startup() -``` - -A chain's startup resolves its idempotency policy, and the existing guarantee is that a -misconfigured dedup window fails the pod rather than the first event. That guarantee is *per -agent*: built lazily, a group whose second agent has a bad `idempotency_ttl` would start cleanly -and fail on a delivery hours later, while the first agent's clean startup said nothing about it. - -Reading the namespaces off the registered handlers is not a way around C6. The registry -deliberately cannot enumerate agents, and this service is not the builder -- but what it needs is -not "which agents exist", it is "which namespaces have handlers to dispatch to", and the handlers -are the authority on that. `_chain_for` stays lazy for anything that arrives later, because a -handler registered after startup should produce a dispatch that finds nobody -- an outcome the -acknowledgement contract already has a disposition for -- rather than a failed delivery. - -**`process_event` and `process_rest_request` take a keyword-only `namespace`.** Keyword-only -because both already have positional tails that existing callers use; `""` is the root, which is -what every caller that does not know about agents gets. - -**The publishing-service lookup became namespace-aware, and that was a latent crash:** - -```python - # This agent's publishing service, falling back to a root one. Not the - # 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) -``` - -P6 already gives each namespace its own `EventPublishingService`. The old call passed no -namespace, which on the application's registry means "search every namespace and raise if more -than one matches" -- so the first handler in a grouped process to return a `HandlerResult` with an -`event_type` would have raised `Multiple components of type EventPublishingService found`. With -`namespace=""` the lookup is restricted to the root, which is where the only publishing service in -a single-agent application lives. - -**The two call sites pass their own namespace**, which is what makes the parameter reach anything: - -- `CloudEventProcessorMixin._dispatch_cloud_event` passes `namespace=self.namespace` -- the - namespace of the transport endpoint that received the delivery. Its docstring's contract grew - from "a class that supplies a `registry` attribute" to `registry` and `namespace`. -- `RestApiBase._process_resource` passes `namespace=self.namespace`, so a REST call into one agent - is not offered to another agent's handlers. - -Both are the root today, so both are today's behaviour today; they become per-agent the moment -phase 5 and 6 give each namespace its own endpoints. - -**Not in this step.** The plan's third phase-4 bullet -- "wire previously unused `runtime_name`: -after the chain picks a winner, resolve the agent via `get_runtime_name()`" -- depends on -`EventHandlerBase.get_runtime_name`, which phase 7 adds. The spec's own compatibility table -(sec. 10) records `runtime_name` as only logged today, so it stays logged; the namespace is now -logged alongside it. - -Tests: `tests/unit/agents/services/eventing/test_event_processing_namespaces.py`, 18 cases against -real `Config`, `Registry`, `HandlerChain` and handler subclasses rather than mocks -- an event -reaching one agent's handler and not the other's; a namespace with no handler returning -`NO_HANDLER_FOUND` rather than raising; the root chain not reaching into an agent; a root handler -not running for an agent; a single-agent application dispatching as before over both `process_event` -and `process_rest_request`; one chain per namespace with handlers, each carrying its own namespace -and resolving its own agent's dedup policy from one settings tree; a chain created on first use for -an unknown namespace and reused across deliveries; an illegal namespace refused; and four cases for -`HandlerChain` itself, including that it is still not a registered component. The three -mock-based lifecycle tests in `test_event_processing_service.py` were updated to the chain map and -one added for the per-namespace startup. - -### Phase 4, part 2 -- a handler can say what it wants, and stops being asked about the rest - -`_dispatch` asked every registered handler's `can_handle` in turn until one said yes, so a -process hosting fifty handlers awaited fifty coroutines to find the one that wanted the event. -Grouping multiplies exactly that, because a group's handlers all live in one process. Spec -sec. 7.7 asks for an in-process dispatch index; this is it. - -**The declaration: `EventHandlerBase.get_handled_event_types()`**, defaulting to `[]`. It joins -the two declaration methods already on the class (`get_published_event_types`, -`get_subscribed_topics`) and is a *selection hint, not a selector* -- `can_handle_event` still -decides, and a declared handler is still asked and may still say no. - -**The default means "offer me everything", and getting that backwards is the whole risk.** No -handler in this framework or in any scaffolded project declares an event type today, so an index -that read an empty declaration as an empty set would silence every handler that exists -- and -because an unhandled event acknowledges (spec sec. 7.2), the deliveries would be consumed and -discarded rather than piling up anywhere visible. Spec sec. 7.7 calls this "the most destructive -failure mode available in this design". - -**`DispatchIndex`** is a frozen dataclass with two fields and one question: - -```python - by_type: dict[str, tuple[EventHandlerBase, ...]] - wildcard: tuple[EventHandlerBase, ...] - - def candidates(self, event_type: str) -> tuple[EventHandlerBase, ...]: - return self.by_type.get(event_type, self.wildcard) -``` - -`by_type[t]` already holds the *merged* candidate list -- the handlers that declared `t` plus -every wildcard handler -- so dispatch is one dictionary lookup and no per-event merging or -sorting. An event type nobody declared falls back to `wildcard`, because a type no handler named -is not a type no handler wants. - -**The candidate lists are built by filtering the priority-sorted order, not by concatenating -buckets:** - -```python - wildcard = tuple(handler for handler, declared in declarations if not declared) - by_type = { - event_type: tuple(handler for handler, declared in declarations if not declared or event_type in declared) - for event_type in {event_type for _, declared in declarations for event_type in declared} - } -``` - -Concatenating `typed + wildcard` and sorting would have put declared handlers ahead of undeclared -ones *of equal priority*, and priority ties are currently resolved by registration order -- -something a project may be relying on without having said so. Filtering the already-sorted list -means the sequence a handler is tried in is exactly the sequence it would have been tried in -without an index. There is a test comparing the two orders. - -**A declaration that looks like a pattern is refused, at startup:** - -```python - if _WILDCARD_IN_DECLARATION.search(event_type): - raise ValueError( - f"Handler '{handler.name}' declares the event type '{event_type}', which looks like a pattern. " - "Declarations are matched by equality, so this handler would never be asked about any event. ..." - ) -``` - -This is not defensive tidiness, it closes a hole the new API opens. Declarations are matched by -equality, so `get_handled_event_types() -> ["order.*"]` is a type no event ever has: the handler -would go in the typed bucket for the literal string and never be asked about anything -- the same -silent silencing, reintroduced by the very method meant to avoid it. Blank declarations are -refused for the same reason. Both fail while the pod is starting, naming the handler. - -**The index is built once at startup, and checked on every dispatch.** `on_startup` builds it (so -a malformed declaration fails the pod) and logs how many handlers are offered every event against -how many event types are declared -- the observable evidence that nothing was silenced. But -`_candidates` re-reads the handlers: - -```python - handlers = self._handlers() - if self._index is None or handlers != self._indexed: - self._indexed = handlers - self._index = DispatchIndex.build(handlers) - return self._index.candidates(event_type) -``` - -Before the index, the chain queried the registry per event, so a handler registered after startup -was picked up automatically. A purely startup-built index would drop it silently, which is the -class of failure this design is most careful about. The check costs exactly what the old code -already paid -- one registry query and now a tuple comparison instead of a sort -- while the index -still removes the `can_handle` await per handler, which is the expensive part. `HandlerChain` -being unregistered means nothing calls its `on_startup` when it is used outside `AppBuilder`, and -the same branch covers that. - -**`SessionsJobHandler` opts in without its subclasses writing anything.** Its `can_handle_event` -was `event.type == f"sessions.job.created.{self.JOB_TYPE}"`; that string now has one definition: - -```python - @property - def job_created_event_type(self) -> str: - return f"sessions.job.created.{self.JOB_TYPE}" - - def get_handled_event_types(self) -> list[str]: - return [self.job_created_event_type] -``` - -`can_handle_event` reads the same property. Written out twice the two could drift, and a -declaration that no longer matches the check is a handler the index never offers an event to -- -which is why the property exists rather than a second f-string. A subclass opts in by setting the -`JOB_TYPE` class variable it already had to set. - -`_dispatch` was also split: `_handlers()` now owns the namespace-scoped registry query (with the -explanation of why the namespace is named explicitly, from part 1), and `_dispatch` itself asks -`_candidates(event.type)`. The `handlers.count` span attribute keeps its meaning -- how many -handlers this dispatch will walk -- and the debug line now reports candidates against the total. - -Tests: `tests/unit/agents/handler/test_dispatch_index.py`, 24 cases -- an undeclared handler being -a candidate for every event type, including alongside a declared one, and an undeclared-only -application indexing to nothing at all; declarations narrowing who is asked, every declared type -keyed, and an unknown type falling back to the wildcard handlers or to nobody; candidate order -identical to the unindexed order and priority still deciding; dispatch asking only the candidates, -the chain-of-responsibility fallthrough surviving, and an event no candidate wants returning -`None`; a pattern and a blank declaration refused with the handler named, and the refusal landing -on `on_startup`; the index built at startup, not rebuilt when nothing changed, rebuilt for a -handler registered afterwards, and built on demand for a chain nobody started; and two agents in -one process indexing only their own handlers. One mock-based test in -`test_event_processing_service.py` grew a small stub handler, because a bare `MagicMock` is no -longer sortable now that startup indexes. - -### Phase 5, part 1 -- a transport endpoint subscribes for one agent, and only for one agent - -P6 gave each namespace its own `NATSClient`, with the queue group and the durable derived from -the namespace. What still ran once for the whole process was the thing that decides *what to -subscribe to*: `NatsEventing` and `DaprEventing` each collected topics from -`registry.get_event_handler()` with no namespace, which on the application's registry means every -agent's handlers, and deduplicated the result globally. - -Both of those are wrong in a group, and the second is wrong in the way spec sec. 7.6 singles out. - -**The endpoints are namespace-owned.** `NatsEventing(namespace=...)` and -`DaprEventing(namespace=...)`, so phase 6 can build one per agent: - -```python - def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: - super().__init__(should_register=False, namespace=namespace) -``` - -That needed `RestApiBase.__init__` to accept a namespace, since `EventHandlingBase` is a -`RestApiBase`: - -```python - def __init__(self, should_register: bool = True, *, namespace: str = ROOT_NAMESPACE) -> None: - super().__init__(should_register, namespace=namespace) -``` - -Keyword-only, defaulting to the root, and every existing subclass already calls -`super().__init__()` or `super().__init__(should_register=False)` by keyword -- so nothing -changes for a developer's API, which still gets its namespace from the ambient scope. The -framework's own per-agent endpoints are constructed outside any scope, which is why they name it. - -**Each endpoint resolves its own agent's client:** - -```python - self._client = self.registry.get_component(NATSClient, namespace=self.namespace) -``` - -Unscoped, this raised `Multiple components of type NATSClient found` the moment a second agent -joined the process -- P6 created the clients but nothing had been taught to pick between them. -With `namespace=""` the lookup is restricted to the root, which is where a single-agent -application's only client is. - -**`NatsEventing._declared_topics` is new and is where the per-agent scope lands:** - -```python - topics: dict[str, None] = {} - for handler in self.registry.get_event_handler(namespace=self.namespace): - for topic in handler.get_subscribed_topics(): - if topic: - topics[topic] = None - for topic in self.config.get_nats_subscription_config(): - if topic: - topics[topic] = None - return list(topics) -``` - -Two sources, handler declarations first and the configured list second, both already scoped to -this agent -- `self.registry` and `self.config` are this namespace's views, so -`orders.nats_subscriptions` resolves before the shared list (C5) with nothing here saying so. -`DaprEventing._declared_topics` took the same namespace argument, which scopes both halves of the -Dapr path at once: the sidecar's subscription document and the readiness hand-off to `DaprClient`. - -**Deduplication is now per agent because it cannot be anything else.** The `dict` above lives -inside one endpoint, and one endpoint serves one namespace, so a cross-agent "first declaration -wins" is not something that has to be avoided -- it is unreachable. That is the point of spec -sec. 7.6: two agents subscribing to one topic both want the event, and a global dedup would -silently disable one of them, invisibly to an author who runs that agent alone. - -**The unhandled and duplicate counters were attributing every event to the root.** Both are -documented as per-namespace and both were hardcoded: - -```python -- _DUPLICATE_EVENTS.add(1, {"namespace": ROOT_NAMESPACE, "topic": topic}) -+ _DUPLICATE_EVENTS.add(1, {"namespace": self.namespace, "topic": topic}) -``` - -In a group that would have reported one agent's over-broad subscription as everybody's, which is -precisely the signal spec sec. 7.7 wants those counters to carry. The value is the namespace -verbatim rather than `ROOT_LABEL`, so a single-agent application keeps emitting `""` and its -existing dashboards do not suddenly see a new label value. - -**Two plan bullets are already satisfied, and one of them must not be implemented as written.** - -- **"`NATSClient` consumer identity (C1)"** -- the durable `f"{namespace}-{topic}-durable"` and - `queue=namespace` landed with P6. Part 2 of this phase adds the invariant test the plan asks - for. -- **"Give each namespace's JetStream consumer a `filter_subjects` set"** -- already true, in a - better form, and building it as written would make things worse. The client creates **one - durable per `(namespace, topic)` pair** with `filter_subject=topic` - (`nats_client.py:_consumer_config`), so the filter set of a namespace *is* the union of its - declared topics and its `nats_subscriptions`, one consumer per element. The plan's own - objection to a multi-subject filter is the reason to keep it that way: "a filter that follows - handler churn turns adding one handler into a consumer reconfiguration -- and possibly a - redelivery storm on deploy". With one consumer per topic, declaring a new topic *adds* a - consumer and never rewrites one, so there is no reconfiguration to be had. Collapsing several - topics into one consumer with a `filter_subjects` set would reintroduce exactly that. - - The fan-out the bullet worries about is not removable at this layer either: spec sec. 7.6 - *requires* one consumer per `(namespace, topic)`, so a broad subject selected by three agents - is copied three times by definition. Sec. 7.7 asks for that to be *observable*, not absent, and - the plan puts the reporting in `asbs validate`. - -**Also not implemented as written: "iterate `registry.get_known_namespaces()`".** That method -deliberately does not exist -- the registry is reachable from every component, so it would let an -agent enumerate its neighbours (C6). It is not needed: with one endpoint per agent, each one -knows only its own namespace, which is all the collection needs. - -**Still to come in phase 6.** The Dapr path mounts `POST /events/{topic}` and -`GET /dapr/subscribe` on the endpoint's router, and two agents' routers would collide on both -paths. Phase 6 owns the route namespacing and the `_eventing_component` list that creates these -per agent; nothing in this step creates more than one, so nothing collides yet. - -Tests: `tests/unit/agents/io/api/eventing/test_eventing_namespaces.py`, 18 cases -- an endpoint -subscribing its own handlers' topics and not another agent's; two agents on one topic both -getting it, for both transports; a topic declared twice inside one agent subscribed once; the -agent's own `nats_subscriptions` winning and falling back to the shared list; handler topics -ordered before configured ones; each endpoint resolving its own namespace's client and a root -endpoint resolving the root one; only this agent's topics reaching the client; the Dapr -subscription document holding one agent's topics and a root document unchanged; and namespace -ownership, including that an illegal namespace is refused and that endpoints stay unregistered. - -### Phase 5, part 2 -- C1 gets the regression test the plan asks for - -No production change. The plan marks the consumer identity "**C1 -- invariant, cover with a -test**", and the invariant was the one thing about P6's naming that nothing checked: the durable -and the queue group are derived from the namespace, and the tests proved they *are* -- but nothing -proved a deployment value cannot get in. - -That is the failure worth a permanent guard rather than a review. A durable that picks up the -group name becomes a *different* durable the moment the agent is moved between groups, and a -fresh JetStream consumer resumes according to its delivery policy: the agent either replays the -stream from the beginning or silently skips whatever arrived while it was being renamed. Nothing -in the process reports either. And the temptation is real, because the connection name -(`f"{namespace}.{group}.{pod}"`) is right there in the same class and carries both values. - -`TestConsumerIdentityIgnoresTheDeployment` in `tests/unit/agents/clients/io/test_nats_client.py`, -four cases. Each derives the queue group and the durable, changes the deployment, and derives them -again from the same client -- so what is asserted is the derivation rather than a value cached at -subscribe time: - -- the group name changing leaves both identifiers untouched; -- the pod name changing leaves both untouched (a pod name in a durable would mean a new consumer - on every restart); -- the connection name *does* change across the same edit, which is the positive half: the - deployment is visible where attribution needs it and nowhere else; -- the JetStream `ConsumerConfig` carries `durable_name`, `filter_subject` and `deliver_group` - derived from the namespace and the topic, and neither the group nor the pod appears anywhere in - it. - -**The tests were verified to fail.** Injecting `BLUEPRINT_GROUP` into `_durable_for`'s prefix -fails three of the four; injecting `POD_NAME` fails all four. An invariant test that passes -against a broken implementation is worse than no test, so this was checked rather than assumed. - -The last case doubles as the record of why part 1 does not build a `filter_subjects` set: one -durable per `(namespace, topic)` filtering one subject means declaring a topic *adds* a consumer -and never rewrites one, so there is no filter to churn and no reconfiguration to migrate. - -### Phase 6, part 1 -- build() wires a transport per agent, and none for an agent that needs one not - -Phase 5 made a transport endpoint able to subscribe for one agent. Nothing created more than one: -`build()` still made a single client and a single endpoint for the whole process, so every agent -in a group would have shared the root's connection and the root's subscription set -- which is -neither what spec sec. 6 asks for nor what phase 5's endpoints were built to do. - -**`_eventing_component` became `_eventing_components: list[...]`**, and the decision moved into -one method per agent: - -```python - event_bus_type = str(self._config.get("event_bus", "") or "").strip().lower() - for namespace in self.hosted_namespaces: - self._wire_transport(registry, namespace, event_bus_type) -``` - -`event_bus` is read once, from the root: one transport type per process is a stated boundary of -this plan (mixing NATS and Dapr is out of scope). What is decided per agent is *whether* that -agent gets a client, and whether it gets an endpoint. - -**`AppBuilder.hosted_namespaces`** is the list `build()` iterates -- the root first, then each -declared agent. It is deliberately not `namespaces`, which is only what `with_namespace` was -told: that property answers "which agents was this builder asked to host", this one answers -"which namespaces does `build()` have to walk", and they differ by exactly the root. The root -cannot be conditional, because it is where a single-agent application's components live and where -the framework's own root components go. - -**`_wire_transport` is where the per-agent gates live:** - -```python - consumes = bool(registry.get_event_handler(namespace=namespace)) - publishes = self._publishing_requested(namespace) - ... - if not (consumes or publishes): - logger.debug("Namespace '%s' neither consumes nor publishes events; it is given no transport client", agent) - return - - if event_bus_type == "dapr": - DaprClient(namespace=namespace) # auto-registers - if consumes: - self._eventing_components.append(DaprEventing(namespace=namespace)) - elif event_bus_type == "nats": - NATSClient(namespace=namespace) # auto-registers - if consumes: - self._eventing_components.append(NatsEventing(namespace=namespace)) -``` - -The early return is a spec requirement, not an optimisation: **an agent that neither consumes nor -publishes must not be given a client** (sec. 6). A pure-scheduler agent in `in_process` mode that -has not opted into publishing is that case, and a connection for it would be a socket, a -readiness dependency and a `/connz` entry for traffic that does not exist -- on a broker its own -deployment may have no access to. The same gate is what makes the root pass a no-op in a grouped -application, where every handler belongs to a namespace and the root holds nothing. - -**Publishing became a per-agent opt-in.** `_publishing_requested` now takes a namespace and reads -through that agent's configuration view: - -```python - raw = self._config.for_namespace(namespace).get("event_publishing_enabled", False) -``` - -So one agent in a group can emit events while its neighbours do not (C5). `for_namespace("")` -returns the loader itself, so a single-agent application reads exactly the key it always read. -The error for "publishing enabled, no transport" now names the agent that asked, because in a -group "somebody set this" is not a usable message. - -**One `EventPublishingService` per agent that has a client**, which is what spec sec. 6 requires -for outbound attribution -- an agent's events go out on its own connection: - -```python - for namespace in self.hosted_namespaces: - if registry.get_io_clients(namespace=namespace): - EventPublishingService(namespace=namespace) -``` - -Keyed on the client rather than on `publishes`, so a consuming agent keeps the publishing service -it has always had without opting in. `EventProcessingService` stays single and at the root, since -phase 4 gave it a chain per agent instead. - -**The lifespan and the router mount iterate the list**, shutdown in reverse, and both log the -namespace of the endpoint they are driving -- in a group "eventing component startup failed" with -no agent named is not attributable, which is C7. - -**Three sessions components gained a namespace** (`SessionsApiClient`, `SessionKeyProvider`, -`SessionsBus`), because the sessions branch of `_wire_transport` creates them per agent like the -other two. `SessionsBus` is the one that matters beyond naming: it dispatches through -`CloudEventProcessorMixin`, which passes `self.namespace` since phase 4, so a job notification is -now offered to that agent's handlers and no other's. - -Tests: `tests/unit/agents/app_builder/test_build_namespaces.py`, 16 cases against real -components -- one client per consuming agent, one at the root for a single-agent application, none -for the root when it holds nothing, none for an agent that neither consumes nor publishes, and a -client-without-endpoint for a publish-only agent; publishing opted into per agent; one endpoint -per consuming agent, one at the root for a single-agent application, none without handlers, and -each endpoint subscribing only its own topics; one publishing service per agent with a client and -none for an agent without one; `hosted_namespaces` ordering; and the publish-opt-in error naming -the agent. - -Four existing `build()` tests were updated: the mock config gained -`for_namespace.return_value = config` (the pattern `mock_config` already used), seven -`assert_called_once_with()` assertions became `assert_called_once_with(namespace="")` -- the same -call, now explicit -- `_eventing_component is None` became `_eventing_components == []`, and one -`get_event_handler` stub lambda took the namespace argument it is now passed. None of these is a -behaviour change; each is an assertion on a call shape. - -### Phase 6, part 2 -- an agent's HTTP surface lives under its own prefix, and grouped Dapr is refused - -A group applies the same registration once per agent, so two agents declare the *same* paths. -FastAPI serves the first match, so without a prefix one agent's requests are answered by another -agent's code -- and its Dapr deliveries by another agent's handlers. Nothing about that is visible -from a response. - -**`RestApiBase.route_prefix`** is the single definition of where a component's routes go: - -```python - @property - def route_prefix(self) -> str: - return f"/api/{self.namespace}" if self.namespace else "" -``` - -It is a property on the component rather than a rule inside `AppBuilder` because **two places -have to agree on it**: the builder, which mounts the router, and `DaprEventing.subscribe`, which -tells the sidecar where to post. If those disagreed the sidecar would post to a path FastAPI does -not serve and every delivery would 404, with the application otherwise healthy. - -**`AppBuilder._mount` applies it, and rewrites the tags:** - -```python - prefix = component.route_prefix or root_prefix - if component.namespace: - for route in component.router.routes: - if isinstance(route, APIRoute) and route.tags: - route.tags = [f"{component.namespace}.{tag}" for tag in route.tags] - app.include_router(component.router, prefix=prefix) -``` - -`root_prefix` is what a *root* component keeps, and it is not the same for every kind: a REST API -has always been mounted under `/api`, a transport endpoint at the top level because its paths are -a contract with a sidecar. A namespaced component ignores it and takes `route_prefix`, so both -kinds end up under one prefix per agent -- `/api/orders/orders` for the REST API and -`/api/orders/events/{topic}` for deliveries, which matches the `/api/order/orders/{id}` shape -spec sec. 11 uses. - -The tags are **rewritten, not appended to**. `include_router(tags=...)` appends, which would put -each operation in two Swagger groups -- once under the agent and once under the bare resource -name -- so the rewrite happens on the routes. `isinstance(route, APIRoute)` rather than a -`getattr`: a Starlette `BaseRoute` has no tags, and only the decorator-produced routes do. -Mutating them is safe because a router belongs to exactly one component and `build()` runs once -per process (`Component.configure` refuses a second call). - -**Grouped Dapr is refused at build time, and this is the part worth arguing.** *(Superseded by -part 4 below, which routes and fans out in the process instead. The reasoning is kept because it -is why the endpoint had to become singular.)* Prefixing fixed -delivery, but discovery cannot be prefixed: the sidecar fetches `GET /dapr/subscribe` from one -path, fixed by Dapr's protocol. With each agent's document behind its own prefix the sidecar finds -*no* document, subscribes to nothing, and the pod reports itself healthy while consuming nothing --- the exact silent failure this feature exists to prevent. So: - -```python - if event_bus_type != "dapr" or len(self._eventing_components) <= 1: - return - ... - raise ValueError( - f"{len(self._eventing_components)} agents ({agents}) consume events and 'event_bus' is 'dapr', ..." - ) -``` - -The check is on the resolved `event_bus_type` rather than on the endpoint types, because one -transport serves the whole process and the type is what is already known here -- `isinstance` -against a module-level name would also break under the test patching that mocks these classes. - -NATS is unaffected: it has no discovery endpoint, because the client subscribes directly, per -agent. **A single-agent Dapr application is unaffected** -- one endpoint, no prefix, byte-identical -document. - -Fixing grouped Dapr properly means one process-wide discovery endpoint returning the union of -every agent's subscriptions, each entry naming that agent's own delivery route. That is a change -to the sidecar-facing contract rather than an internal detail, so it is **not** done here and is -listed under *Open points*. Refusing loudly is the interim, because the alternative is a pod that -looks healthy and consumes nothing. - -Tests: `tests/unit/agents/app_builder/test_route_namespacing.py`, 18 cases, asserting through -`app.openapi()["paths"]` rather than `app.routes` -- FastAPI stores an included router as one -opaque entry rather than flattening its routes, so `app.routes` does not contain the paths under -test while the OpenAPI document is exactly what is served. Covered: the prefix for a root and a -namespaced component; a single-agent application's paths not moving; an agent's route carrying its -namespace; two agents declaring one route not colliding; tags prefixed, the bare tag replaced -rather than added to, two agents' tags not merging, and a root component's tags untouched; grouped -Dapr refused with both agents named, one agent on Dapr fine, two on NATS fine; the root delivery -path unchanged; an agent's delivery path moved; two agents on NATS getting their own; and the -subscription document naming the mounted path for an agent and the unchanged path for the root. - -### Phase 6, part 3 -- every cache is manageable and every cache is probed - -Phase 3 part 2 let a process hold several named caches. Two things still only knew about the -default one, and both were listed as phase 6's work. - -**`CacheManagementApi` takes an optional `?name=` on every endpoint:** - -```python - async def get_cache_stats(self, name: str = DEFAULT_CACHE_NAME) -> CacheStatsResponse: - stats = self._cache(name).get_stats() -``` - -One router for the process rather than one per cache, and that is a correctness point rather -than tidiness: caches can be registered *after* startup (`registry.add_cache` exists for that), -routes cannot, so anything keyed on the set of caches at build time would serve a stale list. -Resolving the name per request has no such window. A request that names nothing reaches the -default cache, so every existing call is unchanged. - -**`_cache(name)` answers the two failures differently, and the distinction is the point:** - -```python - if not self.registry.get_all_caches(): - raise HTTPException(status_code=503, detail="Cache service not available") - try: - return self.registry.get_cache(name) - except ValueError as exc: - raise HTTPException(status_code=404, detail=str(exc)) from exc -``` - -**503** when no cache is registered at all: the application was built without one, it is not the -caller's doing, and it may resolve without a redeploy -- which is what 503 says, and it is what -this endpoint has always answered. **404** when caches exist but none has that name: that is a -bad request for a resource that is not there, and answering 503 would invite a retry that can -never succeed. The registered names go in the 404 body, because a caller who mistypes a name has -no other way to discover the right one -- there is no endpoint that lists them. - -The eviction response gained a `"cache"` field naming which cache was cleared. With one cache the -answer was implicit; with several, a response that does not say what it cleared is not usable. - -**Readiness probes every cache, not just the default:** - -```python - for cache_name, cache in registry.get_all_caches().items(): - entry = "cache" if cache_name == DEFAULT_CACHE_NAME else f"cache:{cache_name}" - health_providers[entry] = CacheHealthChecker(cache) -``` - -This was a real gap rather than a missing feature. `CacheHealthChecker` pings Redis and flips -readiness when it cannot be reached; keyed on the default name, a project whose `sessions` cache -was a Redis instance had that instance unprobed -- so a Redis outage there took the pod out of -nothing, and the agent silently served cache misses. Worse, a project that registered *only* a -named cache had no cache health check at all, because the old gate was `registry.has_cache()`, -which asks about the default. - -The default keeps the entry name `cache` it has always had, so an existing `/readiness` payload -does not change; a named cache appears as `cache:`. - -Tests: `tests/unit/agents/io/api/utilities/test_cache.py` rewritten onto the new registry calls -and grown to 20 cases -- the three endpoints reading and clearing a named cache, the default used -when no name is given, the response naming the cache it cleared, 503 with no cache registered, -404 for an unknown name on all three endpoints, and the 404 body listing the registered names. -Four cases added to `test_named_caches.py` for the readiness wiring: the default keeping the -`cache` entry name, a named cache getting its own, a *named-only* application still reaching -readiness, and each entry probing its own cache object. - -Also corrected here: part 2's entry said 17 test cases where the file has 18. - -### Phase 6, part 4 -- grouped Dapr works: one endpoint, routed and fanned out in the process - -Part 2 refused a group of consuming agents on Dapr, because discovery cannot be prefixed per -agent. The user's answer was the right one and better than the refusal: **do the routing in the -process.** Keep the one endpoint the sidecar's protocol demands, pick the agents from the event, -and fan out -- since several agents may legitimately want the same event. Part 2's guard is -removed. - -**There is one Dapr endpoint, at the root, and that is now structural:** - -```python - def __init__(self) -> None: - super().__init__(should_register=False) -``` - -`DaprEventing` takes **no namespace at all**, unlike every other transport component. That is not -a simplification -- it is what keeps `_topics_by_agent` correct. That method reads *every* handler -in the process, which it can only do because `self.registry` is the application's registry rather -than one agent's view of it; a namespaced instance would silently see one agent's handlers and -route only that agent's topics. Making the constructor refuse a namespace means the mistake cannot -be made, and `route_prefix` is then always `""`, so the two fixed paths never move. - -**The routing table is read from the handlers:** - -```python - by_agent: dict[str, dict[str, None]] = {} - for handler in self.registry.get_event_handler(): - for topic in handler.get_subscribed_topics(): - if topic: - by_agent.setdefault(namespace_of(handler), {})[topic] = None -``` - -An agent that declared no topic does not appear, because it has nothing to subscribe and nothing -to be delivered. - -**The document is the union; the delivery is the fan-out.** Those are two different readings of -the same table, and the asymmetry is the whole design: - -- `_declared_topics` flattens it, deduplicated, because the sidecar delivers a topic to the - application **once** however many agents want it -- so it is told once. -- `_agents_for(topic)` inverts it, returning every agent that declared the topic. Fanning that - single delivery out is the application's job, not the sidecar's. - -```python - declared = tuple(namespace for namespace, topics in by_agent.items() if topic in topics) - if declared: - return declared - with_handlers = tuple(dict.fromkeys(namespace_of(handler) for handler in self.registry.get_event_handler())) - return with_handlers or (ROOT_NAMESPACE,) -``` - -The fallback is the same rule `DispatchIndex.candidates` applies one level down: **an absent -declaration cannot narrow anything to nothing.** A topic nobody declared goes to every agent that -has handlers, and each agent's `can_handle_event` decides. That is what a topic arriving from -outside the application needs -- `dapr_declarative_subscriptions` makes the document empty, so no -handler need declare anything and the framework never sees the topic list, yet the sidecar still -delivers. Routing such a delivery nowhere would silence the application, and an unhandled event -acknowledges (spec sec. 7.2), so the events would be consumed and discarded. For a single-agent -application both branches are the root, so nothing changes there. - -**`publish` dispatches once per agent and does not let a failure stop the others:** - -```python - for namespace in agents: - try: - await self._process_cloud_event(cloud_event, {"dapr_topic": topic}, topic, namespace=namespace) - dispositions.append(DeliveryDisposition.ACK) - except Exception as exc: - disposition = disposition_for(exc) - dispositions.append(disposition) - ... -``` - -Letting the exception out of the loop would let one agent silently cancel a neighbour's work. Each -failure is logged with its own agent named, so a fan-out failure stays attributable (C7). - -**The single acknowledgement is `combined_disposition`, new in `models/errors.py`** beside the -disposition table it extends, since it is a spec sec. 7.2 concern rather than a Dapr detail: - -```python - outcomes = set(dispositions) - if DeliveryDisposition.NAK in outcomes: - return DeliveryDisposition.NAK - if DeliveryDisposition.ACK in outcomes or not outcomes: - return DeliveryDisposition.ACK - return DeliveryDisposition.TERM -``` - -Each step is a decision, argued in its docstring. **Any NAK wins**, because one agent asked for -the delivery again and the only way to give it one is to ask for the whole message again. -**Otherwise ACK beats TERM**, because a TERM from one agent means *that* agent found the message -undeliverable -- a finished outcome -- and if another agent handled it, the message was handled; -answering TERM would report a successful delivery as dropped. **All TERM is TERM.** Empty is ACK: -nothing was dispatched, so nothing failed. - -**The cost, stated because it has no NATS equivalent:** there is one delivery, so one -acknowledgement, so **a retry asked for by one agent redelivers to every agent in the group**. -A grouped Dapr deployment therefore wants `idempotency_enabled`, or handlers that tolerate a -repeat. Under NATS each agent has its own consumer and its own ack, and no such coupling exists. -This is in the class docstring as well as here, because it is the thing an operator has to know. - -**Plumbing:** `_process_cloud_event` and `_dispatch_cloud_event` took an optional `namespace`, -defaulting to the endpoint's own -- every caller but this one. The unhandled and duplicate -counters now carry the agent the dispatch was *for* rather than the endpoint's namespace, which -for the fan-out is the difference between attributing an event to the agent that declined it and -attributing every event in the process to the root. - -**`AppBuilder._wire_dapr_endpoint`** replaces `_refuse_grouped_dapr`: the Dapr branch of -`_wire_transport` now creates only the per-agent client, and one root endpoint is created after -the loop if anything in the process consumes. NATS endpoints stay per agent, because there the -broker routes -- one consumer per `(namespace, topic)` -- and nothing needs to be done in -process. - -Tests: `tests/unit/agents/io/api/eventing/test_dapr_fanout.py`, 24 cases against real handlers, -config and chains -- the routing table keyed per agent and an agent that declared nothing absent -from it; the document as the deduplicated union with every route at the fixed path; `_agents_for` -resolving one declaring agent, two declaring agents, an undeclared topic to every agent with -handlers, and a single-agent application to the root; the fan-out reaching both declaring agents, -skipping a non-declaring one, dispatching once for a single-agent application, and continuing past -one agent's failure; all six acknowledgement combinations; each agent's client receiving its own -topics and being kept per agent; and the constructor refusing a namespace. - -Updated: `test_route_namespacing.py` lost `TestGroupedDaprIsRefused` and gained the Dapr endpoint -staying at the root; `test_eventing_namespaces.py` is now NATS-only, since Dapr's per-agent -subscription moved to the fan-out file; `test_dapr.py` moved from `_client` to `_clients` and its -mock handlers gained a real `namespace` attribute, which `namespace_of` needs; and one -`assert_called_once_with(namespace="")` became `assert_called_once_with()`. - -### Phase 7 -- a handler says which agent runtime should serve an event - -`EventHandlerBase`'s own usage docstring has shown `get_runtime_name` since before any of this -work; the method did not exist. A project that overrode it got a method nothing ever called. -Alongside it, `process_event` has taken a `runtime_name` argument that the spec's compatibility -table records as "only logged". This closes both. - -**The hook, on `EventHandlerBase`:** - -```python - def get_runtime_name(self, event: GenericCloudEvent, context: dict[str, Any]) -> str | None: - return None -``` - -Per *event* rather than per handler, because the choice can depend on the payload -- one handler -routing to a fast model or a thorough one on the same event type is the case it exists for. - -**The resolution happens in the chain, between selection and handling, and that is a departure -from the plan.** The plan puts it in `EventProcessingService` "after the chain selects a -handler". By then the handler has already run: the chain selects *and* runs in one pass, so a -runtime resolved afterwards is a value nothing can act on. Inside the loop there is exactly one -moment where the winner is known and the answer is still useful: - -```python - if await handler.can_handle(event, context): - logger.info("Handler '%s' handling event '%s'", handler.name, event.type) - self._bind_runtime(handler, event, context) - result = await handler.handle(event, context) -``` - -So the runtime is *bound into the context the handler is about to be given*, under -`RUNTIME_CONTEXT_KEY` (`"runtime"`) and `RUNTIME_NAME_CONTEXT_KEY` (`"runtime_name"`). A handler -that wants a particular runtime reads it from the context rather than looking it up -- and in a -grouped process it gets its own agent's runtime with no namespace anywhere in handler code, which -is the constraint the whole feature is under. The fallthrough is unaffected: a candidate whose -`handle` returns `None` passes on, and the next candidate gets its own binding. - -**Three sources, most explicit first:** - -```python - declared = handler.get_runtime_name(event, context) or context.get(RUNTIME_NAME_CONTEXT_KEY) - if declared: - context[RUNTIME_NAME_CONTEXT_KEY] = declared - context[RUNTIME_CONTEXT_KEY] = self._runtime_named(str(declared), handler) - return - - names = self.registry.get_agents(namespace=self.namespace) - if len(names) == 1: - context[RUNTIME_NAME_CONTEXT_KEY] = names[0] - context[RUNTIME_CONTEXT_KEY] = self.registry.get_agent(names[0], self.namespace) - return -``` - -The handler's own answer, then the caller's `runtime_name`, then the single runtime in this -handler's namespace. `process_event` now seeds its argument into the context: - -```python - if runtime_name: - context[RUNTIME_NAME_CONTEXT_KEY] = runtime_name -``` - -Only when asked for, so a caller that passes nothing leaves the key *absent* rather than `None` -- -the difference between "no preference" and "explicitly no runtime". That is what makes a parameter -which has only ever been logged mean something, while keeping the handler's own answer above it. - -The namespace is named explicitly in both registry calls, for the reason it is named in -`_handlers`: an omitted namespace on the root registry means every namespace, so the single-runtime -count would include a neighbour's agent and "exactly one" would be wrong in a group. There is a -test for two agents each owning a `planner`, where each chain binds its own. - -**The plan's ambiguity error is not implemented, and this is the substantive departure.** The plan -says "`None` + multiple agents + no name declared -> raise a descriptive error". That would break -applications that work today: two agents plus handlers that resolve their own runtime by name is a -shape this framework already supports -- it is what the scaffolder generates, `self.registry -.get_agent('')` in a service's `on_startup` -- and those applications rely on the -framework resolving nothing. Raising would fail every delivery in them. So nothing is bound, and -the ambiguity is reported once per handler at WARNING, naming the candidates and the override. -Once, because the condition is a property of the code rather than of the event: the same handler -in the same namespace is ambiguous for every event it will ever see, and a per-delivery warning -would bury the one line that matters. This needs a spec amendment; it is under *Open points*. - -**What *does* raise is a declaration the framework cannot honour:** - -```python - raise ValueError( - f"Handler '{handler.name}' asked for agent runtime '{name}', which is not registered in namespace " - f"'{self.namespace or ROOT_LABEL}' or at the root (registered here: {registered}). Either register it, " - "or return a name that exists from get_runtime_name()." - ) -``` - -The same reading as `event_publishing_enabled` without a transport: an explicit statement the -framework cannot satisfy is a failure, not something to fall back from silently. - -**Found while writing the tests, and worth recording:** constructing a component *directly* with -an explicit `name=` does not qualify it with the namespace -- only `AppBuilder._register` does -that (phase 3 part 1). So two `AgentRuntime(name="planner")` instances in two namespace scopes -still collide on the one registry key. Everything the builder creates is safe; a test or a project -that constructs a component by hand inside a `namespace_scope` is not. The test helper qualifies -the name itself and says why. Not fixed here -- the fix would be `Component.__init__` qualifying an -explicit name, which changes naming for every component in the framework and deserves its own step. - -Tests: `tests/unit/agents/handler/test_runtime_binding.py`, 18 cases against real -`AgentRuntime`, `Config` and chains -- a declared runtime bound and bound *before* the handler -runs; the choice varying with the payload; the handler winning over the caller and the caller -winning over the fallback; `process_event` seeding its argument and leaving the key absent when -it has none; one runtime bound with no declaration, none bound when there is no runtime at all, -and each agent binding its own in a group; the ambiguous case binding nothing, reporting once -rather than per delivery; an unknown declared name raising with the handler, the namespace and the -registered names in the message; and the default hook returning `None`. - -**Verified not vacuous:** with the `_bind_runtime` call removed, 14 of the 18 fail -- the four -that survive are the ones asserting that *nothing* is bound. - -### An ambiguous name fails at startup, wherever it comes from - -Raised by the user against phase 7's open point, and the reason given is the right frame for it: -a registry name is what appears in every log line, span and health entry, so **two components -that share one -- or one whose name does not say which agent it belongs to -- cannot be told -apart when someone is reading the logs.** That has to fail while the process is starting, not be -disambiguated silently or, worse, resolved by dropping one of them. - -Four paths could produce an ambiguous name. All four are closed. - -**1. An explicit `name=` reached `Component` verbatim.** The derived name was qualified with the -namespace; an explicit one was not: - -```python -- self._name = name or qualified_component_name(self._namespace, camel_to_snake(self.__class__.__name__)) -+ self._name = qualified_component_name(self._namespace, name or camel_to_snake(self.__class__.__name__)) -``` - -So `AgentRuntime(name="planner")` built inside `namespace_scope("orders")` registered as -`planner`. The log line said `planner` and nothing about which agent's, and a second agent's -`planner` collided on the key. `AppBuilder._register` had been compensating by qualifying after -construction; it now assigns the bare name and lets the setter do it, so the rule lives in one -place instead of two. - -**2. `Component.name`'s setter took the new name verbatim** -- the same hole, reachable by any -component doing `self.name = "..."`. It qualifies now. - -**3. `Registry.update_component_name` silently dropped whatever held the target name.** It was: - -```python - self._components[new_name] = self._components.pop(old_name) -``` - -Renaming one component onto another's name **removed the other from the registry**, and the only -symptom was a collaborator that could no longer be found -- no error, no log. It now refuses, -naming what is there; renaming to the name a component already has is a no-op rather than a -failure, which is what makes the qualifying setter safe to call twice. - -**4. `AppBuilder.with_namespace` deduplicated a repeated agent name.** Declaring `orders` twice -quietly merged two agents' components into one namespace: - -```python - if namespace in self._namespaces: - raise ValueError( - f"Namespace '{namespace}' is already hosted by this process, so it cannot be declared again. Two " - "agents cannot share a name: the name is what identifies an agent in every log line, span, queue " - "group, durable and cache partition, ..." - ) -``` - -The agent name is the strongest case of the user's point: it reaches the queue group, the -JetStream durable and the cache partition as well as the logs, so two agents under one name are -indistinguishable to the broker too. The message names the legitimate case it might be mistaken -for -- one agent assembled from several parts -- and says to compose those into a single -`AgentRegistration` instead. - -**`qualified_component_name` is deliberately *not* idempotent**, and finding out why was the one -surprise here. Skipping the prefix when a name already appears to carry it looks like a safeguard -against `orders_orders_db`; it is worse than the problem. A base name can legitimately begin with -the namespace -- `BillingHandler` in namespace `billing` derives `billing_handler` -- and such a -component would then register *unqualified*, which is exactly the ambiguity being removed. It was -implemented that way first and a test caught it. "Already prefixed" is not decidable from the -string, so it is not guessed; the docstring says so, and there is a test for the -`BillingHandler`-in-`billing` case. The cost is that a caller who qualifies a name itself gets it -qualified twice -- redundant, still unambiguous, and no framework code does it. - -**The duplicate-name error now says what to do.** `add_component`'s message was `Component with -name X already exists`, which in a group does not say whose or why: - -```python - f"Component name '{name}' is already taken by a {existing}, so {type(component).__name__} in namespace " - f"'{agent}' cannot register under it. Registry names have to be unique across the whole process: they " - "are what identifies a component in logs, spans and health entries, and two components sharing one " - "name cannot be told apart afterwards. A name is qualified with its namespace automatically, so this " - "is either two components of one class in one agent, or two explicit names that collide -- pass a " - "distinct 'name=' to one of them." -``` - -Tests: `tests/unit/agents/component/test_name_uniqueness.py`, 16 cases -- a directly constructed -component qualified, two agents each holding a `planner`, the root keeping the bare name, a -rename qualified and a root rename unchanged; the `BillingHandler`-in-`billing` case and the -qualifier being a plain prefix; two components of one class in one agent colliding, two explicit -names colliding, the message naming the agent and the fix, and a root component not colliding -with an agent's; renaming onto a taken name refused with the other component still registered -afterwards, renaming to the same name and to a component's own qualified name both no-ops, and -renaming from an unregistered name still raising. `test_namespace_builder.py`'s dedupe test became -two refusal tests. - -### One name per agent: the name given in code, with `app_name` as the fallback - -Raised by the user, whose premise was worth checking first: the namespace is **not** derived from -`app_name`. It never was -- an agent's name comes from `with_namespace("orders")` in code, and -config supplies nothing. But the instinct behind the question was right, because config was -supplying a *second* name for the same agent, and two of the places that read it were wrong. - -The rule now, stated once: **the name given in code is the agent's identity; `app_name` is used -only when no name was given, and is otherwise a display string for the process.** - -**1. An agent no longer has to restate its name in config.** `Config(agent_scope=...)` carried -`Validator(f"{agent_scope}.app_name", must_exist=True)`, so every agent in a group had to declare -an `app_name` of its own -- a second name, free to disagree with the first. The same agent could -be `orders` in the registry, the queue group, the durable and the cache partition, and -`Order Processing` in a dashboard. The validator is gone. `app_name` stays a root key for the -OpenAPI title, `/info` and `/status/build`, and an agent may still set one *for display* without -it touching identity. - -**2. Telemetry identity was the display name, which breaks C2.** `otel_service_name` defaulted to -`app_name`, so an agent's `service.name` was whatever `app_name` said: - -```python - def _resolve_service_name(self) -> str: - if self._agent_scope: - scoped = self._settings.get(f"{self._agent_scope}.otel_service_name") - return str(scoped) if scoped else self._agent_scope - return str(self.get("otel_service_name", self.get("app_name", "agent-service"))) -``` - -A scoped view answers with its own `otel_service_name` if the agent set one, and otherwise with -the **namespace**. Note what it deliberately does *not* do: fall back to the root's -`otel_service_name`. That is the one place a scoped read must not, because inheriting it would -give every agent in a group the same `service.name` -- and then regrouping moves work between -agents that no dashboard can tell apart, which is the whole of what C2 forbids. The root view -keeps the old chain exactly, so a single-agent application's dashboards do not move. - -**3. A namespaced scheduler derived its tick subject from `app_name`.** This was a live defect -left behind by a placeholder: - -```python -- # ROOT_NAMESPACE is still "" for every component; phase 2 is what gives this a value. -- identity = ROOT_NAMESPACE or str(self.config.get("app_name", "") or "").strip() -+ identity = self.namespace or str(self.config.get("app_name", "") or "").strip() -``` - -`ROOT_NAMESPACE` is the module constant `""`, so the expression was *always* `app_name`. The -comment says phase 2 would give it a value -- phase 2 landed, `self.namespace` has one, and -nothing came back to this line. The consequence: two agents in a group each with a `nightly` -scheduler derived the same tick subject and would have consumed each other's ticks, and moving an -agent between groups could change the subject its external `CronJob` publishes to, which is -exactly what C1 forbids. The `source` string on the next line had the same inversion, so the -error message named the wrong key. Both fixed, with two regression tests that fail against the old -expression. - -Everything else that reads `app_name` was already right and is untouched: the NATS queue group -(`if self.namespace: return self.namespace`, then `nats_queue_group`, then `app_name`), and the -display readers. - -**Which of these are breaking, precisely.** The `otel_service_name` change is, and it is listed as -*Breaking change 2* under *Compatibility*: `Config(agent_scope=...)` is not new -- it landed in -April and is on `develop` -- so a repo already using it sees its `service.name` change. The -dropped validator is a loosening: configuration that was valid stays valid. The scheduler subject -is **not** breaking for anything deployed, because a scheduler can only have a namespace if it was -built inside a `namespace_scope`, which is branch-new; the *Compatibility* bullet says so rather -than claiming a break that cannot happen. - -Tests: `tests/unit/agents/config/test_agent_identity.py`, 8 cases -- an agent's service name being -its own name, an agent overriding it for itself, the root's override *not* leaking into an agent, -a single-agent application still reading `app_name`, an explicit root override still winning at -the root, the default when there is neither, and `app_name` staying readable and settable for -display without touching identity. Two cases added to `test_scheduler.py` for the namespaced tick -subject, and `test_agent_scope.py`'s "missing scoped app_name raises" became "an agent does not -have to restate its name". - -**Not touched, deliberately:** `black --check` still fails on `config/config.py`, and did at HEAD too -- it is one of the files `CLAUDE.local.md` documents as -disputed between `black` and `ruff format`. `black` reformatted a pre-existing ternary there when -run over the changed files; that reformat was reverted, because accepting it would have started -the ping-pong the two formatters play over that file. - -### Phase 8 -- the group becomes a running process - -Everything before this made a group *possible*; nothing made one *start*. This is the phase that -turns a deployment decision into a process: which agents run here arrives at container start, -and the code that reads it is the only code allowed to. - -Three commits, split along the one line the plan is emphatic about -- **resolution versus -wiring**. Environment reads, file reads and `sys.exit` stay out of `AppBuilder`, so it remains a -pure function of its call sequence and a test can state an exact composition without controlling -the environment or the filesystem. - -#### `GroupConfig` and its resolution (`d00ca03`) - -Two files, and their different lifetimes are the reason there are two rather than one: - -- **`agents.toml`** says which agents this *image* contains and where their declarations live. - It changes only when an agent is added or removed -- a rebuild anyway -- so it is baked in. -- **`deployment-groups.yaml`** says which of them *this process* runs. Never baked in, since one - image serves every group, so it arrives as a mount or is replaced entirely by environment - variables. - -`GroupConfig.resolve` is the only member that reads either, plus the environment: - -```python - declared = cls._read_group_file(env, root) - name, agent_names, critical_names, cache_names = cls._apply_env_overrides(env, declared) - ... - agent_map = cls._read_agent_map(env, root) - agents = cls._resolve_agents(agent_names, critical_names, agent_map, name) -``` - -**Environment overrides the file key by key** (spec sec. 5.1), so a Deployment changes the agent -list without restating the group's name or its caches, and each resolved value is logged with the -source it came from -- "which agents did this pod actually start" being the first question asked -of a group that misbehaves. - -One rule the spec does not state and the tests forced out: **when `BLUEPRINT_AGENTS` supplies the -group and `BLUEPRINT_GROUP` names none, the file is not read at all.** That is the `docker run` -and CI shape from sec. 5.1, and reading the file anyway made an unrelated multi-group file in the -image *ambiguous* -- for nothing, because with no group named no slice of it applies and the only -value it would have contributed is already overridden. - -**Every way of getting a group wrong is a startup failure**, because the alternative is a pod -that passes its probes with a queue nobody is consuming: an agent the image does not contain, an -agent named twice, a name that cannot be a namespace, an unknown group, a malformed or -`groups`-less file, a missing or malformed agent map. Each message names what it found and what it -expected. `critical` defaults to `True` for the reason sec. 9.1 gives -- a group short one -consumer is worse than no pod -- and a *non*-critical agent missing from the map is skipped with -an ERROR instead, since that flag is the deployment saying it would rather run the rest. - -Two details worth their lines. `AgentSpec.name` is put through `validate_namespace`, because it -*becomes* a namespace: rejecting it here names the group file, while letting it through would -surface as a validation error from inside some component's constructor. And PyYAML is imported -inside the parse rather than at module scope -- it is not a declared dependency of this package, -it arrives with `uvicorn[standard]`, so a module-level import would break importing *anything* -from the package in an installation that trimmed it. See *Open points*. - -#### `with_group` and `from_group` (`71dfbb1`) - -```python - for spec in group.agents: - registration = self._load_registration(spec) - if registration is None: - continue - self.with_namespace(spec.name, registration=registration) - - for cache_name in group.cache_names: - self.with_cache(name=cache_name) -``` - -The caches are the group's rather than any agent's, because a cache is process-wide (spec -sec. 8) -- so phase 3 part 2's `with_cache(name=...)` is what the group's `cache_names` feed. - -Importing an agent's module is the one thing here that reaches outside, and it is deliberately on -this side of the resolution/wiring line: it is driven entirely by the `module` strings the group -carries, so a test points them at test modules and controls neither environment nor filesystem to -do it. Imports happen **per group**, so cold start is proportional to the agents this process -hosts rather than to the agents the image contains. - -`_load_registration` catches **every** exception from the import, not `ImportError` alone: -importing a module runs it, and an agent whose declaration raises at import is exactly as -unloadable as one whose module is absent. It also refuses an attribute that is not an -`AgentRegistration`, and a `module` string that is not `package.module:attribute` -- both of which -would otherwise fail later and further away. - -A critical agent that cannot be loaded raises `GroupConfigError`; a non-critical one is skipped -with an ERROR and the rest of the group still starts. The flag is read *before* the agent is -wired rather than after an exception, because there is no partial build to unwind: one process, -one `build()`. - -#### The entry point (`029f287`) - -`python -m blueprint.agents.entrypoint`, and it exists to hold the three things `AppBuilder` must -not: reading the environment, reading files, and exiting. - -```python -def build(*, environ: dict[str, str] | None = None) -> tuple[FastAPI, Config]: - config = Config(settings_files=DEFAULT_SETTINGS_FILES) - group = GroupConfig.resolve(config, environ=environ) - app = AppBuilder(config).with_group(group).build() - return app, config -``` - -Split from `main` so the whole startup path is testable without a server and without -`sys.exit`: everything that can fail happens in `build`, and `main` only decides what to do about -it. `main` returns a status rather than exiting, so a test asserts on the status; the -`__main__` guard is what turns it into an exit. - -**Why it catches rather than lets the exception out.** A group that cannot be resolved must stop -the process *before the port is bound* (spec sec. 9.1), so Kubernetes crash-loops with a readable -message instead of reporting a healthy replica that is silently short a consumer. An uncaught -exception also exits non-zero, but buries the one line an operator needs under a traceback of -framework internals. The reason is `print`ed to stderr *as well as* logged, because logging is -configured by `AppBuilder` -- which has not run yet when resolution fails. - -A project keeps its own `main.py` if it wants: a standalone deployment is untouched, and -`uvicorn src.main:app` works exactly as before. - -#### Not in this phase, and why - -- **The settings-fragment merge.** The plan lists it here; the changelog's *Open points* has - carried it since config rework step 3a with **two unanswered questions** -- whether a fragment - declaring `envvar_prefix` is rejected, and whether a fragment may override a shared - infrastructure key at all. Both are decisions rather than implementations, and guessing either - produces a merge that silently drops or silently overrides configuration. Still open. -- **`on_startup` raising** -- the third row of sec. 9.1's failure table. It says "mark namespace - down, pause consumers (C4), continue", which is phase 9's per-namespace degradation machinery, - not something to improvise here. -- **`deployment-groups.yaml` and `agents.toml` are not generated.** Phase 8 *reads* them; the - scaffolder writing them belongs with the manifest generation that is already parked. - -Tests: `tests/unit/agents/test_group_config.py` (33 cases), `test_with_group.py` (24) and -`test_entrypoint.py` (12) -- 69 in total. The group file and the environment as sources and in -combination, precedence and its logging, criticality from both sources, every validation failure, -the value object's freezing; one namespace per agent with order preserved, the group's caches, -every declaration-loading failure for critical and non-critical agents, and that `with_group` -ignores the environment even when it is set; and the entry point building from either source, -serving what it built, and returning non-zero with the reason on stderr without binding a port. - -### `build()` did not change, and one `main.py` does serve both shapes - -Both raised by the user against phase 8, and the first was a fair misreading of a name I chose -badly. - -**`AppBuilder.build()` still returns a `FastAPI`.** Nothing about it changed in phase 8, and no -existing `main.py` needs editing. The function that returns a tuple was `entrypoint.build()` -- a -*different* function, in a module nothing imported before this phase. But a second `build` in the -same package returning a different shape is exactly the trap it looks like, so it is now -`entrypoint.build_group_app()`, with the reason in its docstring and a test asserting that -`entrypoint.build` does not exist. The lesson is worth keeping: `build` is spoken for in this -package. - -**One `main.py` for both shapes is not merely possible, it is what spec sec. 11 requires** -- and -it already works. The single declaration the spec asks for is the whole file: - -```python -registration = ( - AgentRegistration() - .with_service(OrderService) - .with_handler(OrderValidationHandler) - .with_rest_api(OrderApi) -) -``` - -No `AppBuilder`, no `Config`, no `run_app`, no `if __name__`, no namespace, no group. The same -object then serves three deployments, which `TestOneDeclarationServesBothDeploymentShapes` now -pins down rather than asserting: - -| Deployment | How | What runs | -|---|---|---| -| Standalone, as today | `AppBuilder(config).with_registration(registration).build()`, `uvicorn src.main:app` | root namespace | -| Alone, as a group of one | `BLUEPRINT_AGENTS=order python -m blueprint.agents.entrypoint` | namespace `order` | -| Beside other agents | `BLUEPRINT_AGENTS=order,billing ...` | namespaces `order`, `billing` | - -The dual-branch `main.py` the plan once described -- the component list duplicated under -`if __name__ == "__main__"` and `else:` -- is what the spec forbids, and nothing in the -implementation needs it: `agents.toml` points at `main:registration` like any other module, and a -group of one is an ordinary group. - -**The one consequence to know about, and it is deliberate.** A group of one is *not* identical to -standalone, because it uses the agent's real name: components become `order_order_service` rather -than `order_service`, routes move from `/api/...` to `/api/order/...`, and the queue group becomes -`order` rather than `app_name`. Spec sec. 11 chooses this on purpose -- "a dev mode that ran at -`namespace=""` would give every developer local URLs and integration tests that differ from -production" -- so local and CI match the deployment instead of diverging from it. Migrating an -existing agent from standalone to a group of one therefore moves its routes and its consumer -identity, which is a migration with consequences rather than a rename; phase 10 is where that gets -written up for a project to follow. - -### The builder surface: one class, and the group's rules in the class that imposes them - -**No code changed. Two proposals written, and the spec and plan amended to match.** Recorded here -because the decisions are the reviewable artefact, and because the next phase is their -implementation. - -`docs/plans/2026-09-10-builder-unification.md` -- **phase 8b**, decided, not written. -`docs/plans/2026-09-10-config-validation-unification.md` -- deliberately **not** part of this -feature. - -**The problem, restated correctly.** Adding one `with_*` method today means editing four places: -`AppBuilder`, `AgentRegistration`, `NamespaceBuilder`, and `AgentRegistration.apply`'s `appliers` -dict. Three of those fail *silently* -- the capability is simply absent from that surface -- and -nothing tells the next developer the four exist. The duplication looked like a style problem and -is not: `AppBuilder.with_handler(H)` **constructs `H` immediately**, and a component constructed -before a namespace exists belongs to the root for ever, so a second class had to exist to defer -construction until a namespace was in force. `AgentRegistration` is that class, `NamespaceBuilder` -is its block-form sugar, and `appliers` is the bridge. So the fix is not to share the methods but -to remove the reason they diverged: an `AppBuilder` that **records** instead of constructing -serves both shapes, and the other three have no purpose left. Four sites become one. - -**Collection is its own class.** An intermediate design put an `absorb(builder, namespace=...)` -method on `AppBuilder`; the user's objection retired it -- an `AppBuilder` does not know it is -being collected, because the collection happens elsewhere. So `AgentGroup` (new class, new module) -takes named builders and one configuration and drives one wiring pass, `AppBuilder` keeps exactly -one job, and `with_group` / `from_group` move off `AppBuilder` too. The refusals move with them, -which is the better half of the change: the group's restrictions belong to the thing imposing -them, so **standalone stays permissive and the collector enforces**. That is also the rule stated -plainly -- standalone allows more; to join a group you accept the group's constraints. - -**Decisions, D1-D7 in the proposal:** - -- **Standalone knows nothing about namespaces.** `build()` wires at the root, and the agent's name - lives only in the group configuration. Consequence, stated rather than hidden: a standalone agent - moved into a group changes its queue group and durable once, on the first grouped deploy. -- **Refusals at assembly, each named:** instances (their namespace and registry key were fixed - before the group existed), `AppBuilder(config)` (one process, one settings tree, one port), a - builder already built. Nothing loses a capability -- the factory form recovers the instance case. - No deprecation warnings: sec. 10 makes the standalone shape supported indefinitely, so warning - about it every startup would be crying wolf. -- **A cache is private to the agent that declared it.** Names qualified per namespace, no root - fallback, no shared-cache opt-in. This finally implements what spec sec. 8 always said and only - half of which was built. It **deletes** `GroupConfig.cache_names` and `AgentScopedCache`: - separate stores make the isolation structural, so the prefixing lens has nothing left to prevent. -- **A health checker's key carries its agent.** Two agents calling - `with_health_checker("db", ...)` currently collide in a dict and one disappears silently. - `(namespace, name)` is stored as data, the prefix is its rendering -- phase 9's - `readiness_policy = "critical"` has to attribute a failing checker to an agent, and recovering - that by splitting a string breaks the moment a name contains the separator. -- **Group settings are defaults, and only defaults**; each agent's own `settings.toml` merges under - that agent's scope. So an agent may set any key for itself and can never change what another - agent or the process sees -- which closes the fragment-merge open point below rather than - answering it. -- **`AgentBuilder` records too**, and this fixes a live defect rather than only changing a shape. - `AgentBuilder.__init__` requires a `Config`, and `Component._shared_config` deliberately has no - public read path -- so the factory form phase 8 documents, - `lambda: AgentBuilder(config, runtime_name="orders").build()`, **cannot be written at all** in a - declaration-only `main.py`. Passing the unbuilt builder to `with_agent` and calling - `agent.build(config.for_namespace(ns))` at wiring time removes the lambda and a second latent bug - with it: a lambda closes over whichever configuration was in scope where it was written, which in - a group is the wrong one. - -**Two behavioural changes worth knowing.** `configure_logging()` moves from `__init__` into -`build()` -- with nothing constructed before `build()`, that is where it belongs. And registration -order keeps its meaning, but an instance recorded *after* a class registers *before* it, which can -flip equal-priority tie-breaking; `build()` knows both the recorded order and which entries were -instances, so it raises on that combination instead of silently reordering. - -**Checked against the four Builder anti-patterns**, which was the user's question. Collect-then-wire -is the pattern, not an abuse of it; what exists today is the smell. (1) Side effects during -accumulation -- removed. (2) A silently single-use builder -- `build()` calls -`Component.configure`, which refuses a second call and surfaces as someone else's error; it gets -its own message. (3) Requiring the product's context in the constructor -- `config` moves to -`build()`. (4) Replay drift -- mitigated by storing the *method name* and resolving it with -`getattr`, plus a test asserting the declaration surface and the replay agree. - -**Deferred, and not to be touched during 8b:** configuration validation. Four mechanisms disagree -about what a missing key means, and two findings are worth recording because they are not visible -from reading the code: - -- **The three root validators cannot fail.** `must_exist=True` together with `default=` never - fires -- Dynaconf injects the default. Verified against the installed version: - `Validator("app_name", must_exist=True, default="agent_blueprint")` yields - `'agent_blueprint'`; drop the default and the same declaration raises. So the only condition - among the three that can actually fail is `is_type_of=int` on `app_port`, and an application with - no `settings.toml` starts and calls itself `agent_blueprint`. The defaults are defensible; the - code *claiming* `must_exist=True` is not, because the next genuinely required key gets copied - from it. -- **The actuator's configuration branches are dead.** `Config.validate()` runs inside - `__init__` and raises, so a `Config` that exists has always passed and `_validation_errors` is - always empty -- making `actuator_api.py:95` (readiness 503 carrying the reasons) and `:149` - (liveness warning) unreachable. The readiness probe was written for a behaviour the process does - not have. - -**Amended in the spec:** sec. 2 (Registration -> Declaration), 4.1 (`AgentGroup`, no cache list), -4.2 (deferred wiring normative, the refusal table, config resolution order, order semantics), 4.3 -(the ContextVar's owner), 5.3 (defaults-only group settings; process-scope keys raise), 8 (caches -declared-only), 9 (startup sequence), 10 (three new compatibility rows), 11 (`main.py` and the -optional `create_app`). - -**Amended in the plan:** phase 8b added between 8 and 9 with an eight-step breakdown, and it is -before 9 deliberately because 9 needs D4's attribution data; phases 0 and 3 carry superseded -banners rather than being deleted, because their ContextVar and `with_cache`-signature reasoning -still stands; the migration path corrected from two file changes to **three** (`agents.toml` was -missing) and its `main.py` rewritten; the dual-branch migration recipe under *File change summary* -removed, since it contradicted the rejection stated 600 lines above it; `python -m -blueprint.agents.orchestrator` corrected to `entrypoint`; the *not a separate orchestrator* -argument reconciled with `AgentGroup`; cache and executor sharing rows corrected; testing -expectations extended. - -### Phase 8b, step 1 -- `AppBuilder` records, and `build()` is the only thing that builds - -**`Declaration` (`app_builder.py`), the five `with_*` and `with_cache` store instead of -constructing, `build(config=None)` replays them.** This is the change the whole unification rests -on: `with_handler(H)` used to construct `H` on the spot, so a component declared before any -namespace existed belonged to the root for ever -- which is the only reason `AgentRegistration` -had to exist as a second class. It no longer does. - -- **`Declaration`** is a frozen value object holding `kind`, `target`, `name`, `namespace` and - `kwargs`. `target` is a class, a zero-argument factory, an already-built component, or `None` - for a cache. `is_built` reports whether `target` is already a `Component`, which is what the - order check below reads. -- **`_record(kind, target, namespace, kwargs, *, name, method)`** replaces `_register`. It - resolves the namespace **at the call**, not at construction -- `namespace or - current_namespace()` -- because the caller's scope is what carries it and by the time the - replay runs no scope is in force. Two checks stay at record time, both answerable there and - both better reported at the offending line: `validate_namespace(namespace)`, and the - already-built-instance-for-another-namespace refusal (unchanged wording, moved from - `_register`). -- **`_construct(declaration)`** is the other half of the old `_register`: it enters - `_construction_scope(declaration.namespace)` and calls `declaration.target(**kwargs)`, or - adopts the instance, then assigns the explicit name. A class and a factory are now handled by - the same branch, because a class *is* a zero-argument factory once its keyword arguments are - applied -- which is what lets `lambda: AgentBuilder(...).build()` be deferred exactly as far as - a class is. -- **`declarations`** is a public read-only snapshot, for the collector in step 3 and for a test - that wants to assert what a `main.py` declares without building any of it. -- **`_construct_declarations()`** replays in call order, then creates the caches. Caches last on - purpose: a cache backend is itself a `Component`, so building one mid-pass would interleave it - into the registry's insertion order and shift every component declared after it. - -**`build(config=None)`** gained three things. It refuses a second call with its own message -rather than surfacing `Component.configure`'s "already set" from three frames down. It settles -the configuration -- given to `__init__`, given here, or, when neither, loaded from -`DEFAULT_SETTINGS_FILES`, which is what makes the migrated `AppBuilder().build()` shape work. -And it injects the configuration **before** constructing anything, which is strictly more correct -than the old order: every component now exists in a process that already has its configuration. - -**`_check_declaration_order`** is the one new refusal. An instance is constructed by the caller -at its own source line and is therefore in the registry *before* `build()` runs, while a class is -constructed during the replay -- so an instance recorded after a class registers before it. -That is not cosmetic: `DispatchIndex.build` resolves handler priority ties by registration order. -The check runs **after** construction, deliberately, because a class's priority is a property of -the object and reading it off the class would mean parsing a default argument and being wrong -about every handler that computes one; the application is not returned when it raises, so the -components already in the registry go nowhere. It fires only for handlers, only within one -namespace, and only at equal priority -- the only case where the order decides anything. - -**`configure_logging()` moves, but not all the way to `build()`.** The plan says `build()`; that -is right for a declaration-only `main.py` and wrong for the shape the scaffolder still generates, -where `with_service(OrderService())` constructs at its source line and the builder's own -`with_namespace` / `with_cache` calls log as they go. So the call lives in one place, -`_use_config`, which runs from `__init__` when a configuration is given there and from `build()` -when it is not. An existing `AppBuilder(config)` chain therefore logs exactly as it did. - -**Smaller changes that this needed:** - -- `EventHandlerBase.priority` -- a public property over `_priority`. The ordering rule is - enforced from outside the class, and `__lt__` answers the sorting question, not that one. -- `CacheBackendFactory._validate_name` -> `validate_name`. `with_cache` calls it at record time, - because a cache name becomes a directory segment and a Redis key prefix: it crosses the process - boundary, so it is validated where it is written. The factory still validates when it creates - the backend -- it owns the rule, and nothing reaches it only through the builder. -- `DEFAULT_SETTINGS_FILES` moved from `entrypoint.py` to `config/config.py` and is exported from - the `config` package. Two callers now need the same answer: the container entry point, and - `build()` when the application handed it no configuration. -- `AgentRegistration.apply` hands a factory to the builder instead of calling it. A factory used - to be invoked at apply time -- producing an instance that landed in the registry before every - class of the same agent -- and now defers as far as a class does. -- The registry-creation fallback considered for `build()` was **not** added: `AppBuilder.__init__` - constructs a `TelemetryManager`, which is a `Component`, so the shared registry always exists by - the time `build()` runs. Verified rather than assumed. - -**Behavioural change, stated for the migration guide:** nothing is in the registry until -`build()`, so code that looks a component up between `with_*` calls breaks. The framework's own -convention already forbids it -- collaborators are resolved in `on_startup` -- so the fix is the -documented pattern. - -**Tests.** New `tests/unit/agents/app_builder/test_deferred_wiring.py` (32 cases): nothing is -constructed or registered before `build()`, what a declaration records, the order refusal and the -three cases it must *not* fire on, where the configuration may be handed over, the single-use -guard, and an application that declares nothing. The existing suites that asserted on the registry -straight after a `with_*` call now say when construction happens, through a `realize()` helper in -`conftest.py` that runs `build()`'s own replay pass without the actuator, root API and FastAPI -application that would drown the assertion. 1962 unit tests pass, 34 more than before this step. - ---- - -### Phase 8b gains a step 9: the rules this overhaul establishes, written where they will be read - -**No code changed. A step was added to the plan, and a documentation audit was run to decide where -it lands.** Recorded here because the audit's findings are the reviewable artefact and because they -changed the answer. - -**The question.** This overhaul settles principles -- collect then wire, the namespace is ambient, -a name that leaves the process is validated and never repaired -- that a later feature can violate -without anyone noticing. They exist today only in this changelog, which is now over 4600 lines and -which nobody will read end to end. So: write them down as rules, and put a test behind the ones a -test can hold. Placed **last** in phase 8b, because a rule can only describe something that exists. - -**The finding that decided the location.** `CLAUDE.md:5` has always said *"See `AGENTS.md` for -architecture, component patterns, and testing conventions shared across all AI assistants."* -**`AGENTS.md` has never existed.** `git log --all --diff-filter=A -- AGENTS.md` returns nothing -- -it was not written and later deleted, it was cited into existence. Worse, -`docs/plans/2026-06-10-sessions-job-handler.md:122` quotes what it *states* about versioning, so a -claim has already been sourced to a document that is not there. - -That inverted the recommendation. A new `docs/concepts/design-rules.md` would have added a file and -left the dead pointer beside a live one; writing `AGENTS.md` turns a reference that resolves nowhere -into one that resolves, at no net cost in files. - -**The rest of the audit**, over all 61 tracked markdown files. Two real problems, both duplication -rather than absence: - -- **`docs/superpowers/`** holds `plans/` and `specs/` mirroring `docs/plans` and `docs/specs` -- - 3 files, 2079 lines -- and **nothing in the repository links to any of them.** A second, - abandoned home for the same two document types. -- **Four cache documents totalling 968 lines:** `docs/concepts/caching.md` (347), - `docs/concepts/cache-system-overview.md` (232), `docs/concepts/cache-architecture.md` (181), - `docs/guides/caching-getting-started.md` (208). `docs/README.md` links one of the four. - -Two further references resolve nowhere and are legitimate: `docs/guides/multi-agent-setup.md` is a -phase 10 deliverable, and `agent_group.py` is phase 8b step 3. One is not: -`docs/development-workflow.md`, cited by this plan's own file summary and never written. Everything -else that a naive sweep flags -- `nats.py`, `config.py`, `settings.toml` -- is this repository's -bare-filename shorthand, which is convention rather than rot; the audit script resolves those -against `src/blueprint/agents/` before reporting. - -**What step 9 will do**, in three commits: write `AGENTS.md`; add -`tests/unit/agents/test_design_rules.py` with one guard per mechanically checkable rule -- including -a reference-resolution guard, which is the check that would have caught `AGENTS.md` and is what -makes the rest durable; and clean up the duplication above. Step 8's surfaces-agree test moves into -that file rather than being written twice. - -**The user's instruction, recorded because it widened the step:** `AGENTS.md` alone is not enough -- -everything else has to be coherent too. Hence part 3, which is documentation debt this feature did -not create. - ---- - -### Phase 8b, step 2 -- `AgentBuilder` records too, and is built against its own agent's configuration - -**This fixes a live defect, not only a shape.** `AgentBuilder.__init__` required a `Config`, and -`Component._shared_config` deliberately has no public read path (config rework step 2b). So in a -`main.py` that only declares -- which is every grouped agent -- there was no configuration in -scope to pass, and the factory form phase 8 documents, -`lambda: AgentBuilder(config, runtime_name="orders").build()`, **could not be written at all**. -`AgentBuilder` was unusable in exactly the deployment shape this feature exists for. - -**`agent/agent_builder.py`** - -- **`__init__(config: Config | None = None, ...)`.** `config` stays the first positional - parameter, so `AgentBuilder(config, runtime_name="x")` is untouched; it is now optional, which - is what makes an unbuilt builder declarable. -- **`with_model_from_config` records.** It used to call `self._config.get_ai_config(...)` on the - spot, apply the `model_name` override and raise all three of its refusals. Now it sets - `_model_from_config` and `_model_name_override` and returns. The reading moved to a new - `_resolve_ai_config`, called from `build()`, which carries the same three refusals with the - same messages, naming the same runtime. -- **`build(config: Config | None = None, **kwargs)`.** The single-use guard moved to the top, - ahead of the "model must be configured" check it used to follow -- with `_ai_config` now - resolved *inside* `build`, the old first check tested a field that is `None` on every call, so - the two had to be reordered and the model check rewritten to ask whether - `with_model_from_config()` was called rather than whether it left a result. Then - `_resolve_config`, `_resolve_ai_config`, and the AI client, prompt and metrics as before, all - reading the resolved configuration rather than `self._config` directly. -- **`_resolve_config` -- and its precedence is the opposite of `AppBuilder`'s, deliberately.** - `build(config)` **wins** over `AgentBuilder(config)`. An `AppBuilder` is the application, so - nothing above it knows better and two configurations mean the author is confused -- step 1 made - that a refusal. An `AgentBuilder` sits *inside* an application, and what the application passes - is the view scoped to this agent's namespace (C5), which is the whole point of D6. A - constructor argument is a convenience for the standalone chain, so it yields. When the two - differ the choice is logged at DEBUG. At the root `for_namespace("")` returns the loader - itself, so for a single-agent application they are the same object and nothing is chosen. -- **`_require_config`** raises when neither was given, naming both places one can be passed. - Not defaulted to `DEFAULT_SETTINGS_FILES` the way `AppBuilder.build()` is: an `AgentBuilder` - always sits inside an application that already has a configuration, so a missing one is a - wiring mistake rather than a case to guess a settings file for. -- **`runtime_name`** is now a public property. The application names the agent in its logs and - its failures before the agent exists. -- `get_model_settings()` reads through `_require_config()`, so it is unchanged for anyone who - constructed with a configuration and raises a named error for anyone who did not. - -**`app_builder.py`** - -- **`with_agent` accepts an unbuilt `AgentBuilder`** -- a class, an unbuilt builder, a factory, - or an instance (D6). `_record` had to learn it, because an `AgentBuilder` is neither a - `Component` nor callable and would have been refused by the `not callable(target)` branch. It - is accepted for `kind == "agent"` only; passed to any other `with_*` it is refused with a - message saying where it belongs. -- **`_construct(declaration, config)`** gained the configuration and a third branch: - - elif isinstance(declaration.target, AgentBuilder): - with _construction_scope(declaration.namespace): - instance = declaration.target.build(config.for_namespace(declaration.namespace), **declaration.kwargs) - - That one line is D6: the model, prompt and metrics of a grouped agent are read from its own - configuration section rather than from the root or from a neighbour's. `_construct_declarations` - takes the configuration and passes it through; `build()` hands it the one it resolved. -- `AgentRegistration.with_agent` and `_add` learned the same, and the docstring's `lambda` - example is replaced by the builder form. The factory form still works and is still the escape - hatch for anything a plain call cannot express -- but it is no longer what the documentation - recommends, because a lambda closes over whichever configuration was in scope where it was - written, which in a group is another agent's. -- Importing `AgentBuilder` into `app_builder.py` introduces no cycle: `agent_builder.py` imports - the config package, the AI clients and `AgentRuntime`, and none of them import the builder. - Verified by import, not by reading. - -**Behavioural change:** the three model refusals move from `with_model_from_config()` to -`build()`. An application that misconfigures its model now learns at build time rather than at -declaration time. Nothing else about them changed -- same conditions, same messages, same runtime -named. - -**Tests.** `tests/unit/agents/agent/test_agent_builder.py` gains `TestTheModelRefusalsMovedToBuild` -(the three refusals, plus one asserting the message still names the runtime) and -`TestWhereTheConfigurationComesFrom` (constructible without a config; `build(config)` supplies -one; neither is refused with a message naming both places; `build`'s wins over the constructor's; -`get_model_settings` without one is refused; `runtime_name` readable before building), and -`TestWithModelFromConfig` now pins that it reads no configuration at all. -`test_deferred_wiring.py` gains `TestAnUnbuiltAgentBuilder`: recorded rather than refused, not -built by the `with_` call, handed the namespace-scoped view, handed the loader itself at the root, -constructor arguments forwarded to `build`, and refused by the other `with_*` methods. The -`realize()` helper passes the builder's configuration through the replay. 1979 unit tests pass, -17 more than before this step. - ---- - -### Phase 8b, step 3 -- `AgentGroup`: named declarations in, one application out - -**New module `agent_group.py`.** Collection is its own unit, in a class `AppBuilder` has never -heard of. That is the correction that killed the earlier `absorb(builder)` design: an -`AppBuilder` records what *one* agent is made of and never learns it can be collected, so every -rule that exists only because agents share a process lives in the new file rather than being -scattered into the builder, where it would punish the single-agent case for a situation it is -not in. - -**`AgentGroup(name, agents, *, cache_names=())`** takes a `Mapping[str, AppBuilder]` -- a mapping -rather than a list because two agents cannot share a name, and a mapping says so structurally -instead of needing a check. Each key is validated as a namespace and the root is refused. -`cache_names` is D3's casualty and is marked as such; it is what `GroupConfig` still carries. - -**Three things happen there and nowhere else:** - -- **`resolve(config, *, environ=None)`** -- the only I/O: `GroupConfig.resolve` reads the - environment and the group file. It is `AppBuilder.from_group` moved and renamed. -- **`from_config(group)`** -- imports each agent's module and reads the named attribute, which - must now be an **`AppBuilder`**, not an `AgentRegistration`. `_load_declaration` and - `_skip_or_raise` moved across with the critical/non-critical rule intact: a critical agent - that cannot be loaded raises, a non-critical one is skipped with an ERROR. Reads no - environment and no files, so a test states an exact composition literally. -- **`assemble(config)`** -- one root `AppBuilder`, one `build()`, one `FastAPI`: - - for namespace, builder in self._agents.items(): - root.host_agent(namespace) - with namespace_scope(namespace): - for declaration in builder.declarations: - declaration.replay(root) - - The namespace is never passed as an argument. The collector opens a `namespace_scope` and - `_record` reads it from there -- the same ambient mechanism a component uses, and the reason - step 4 can delete the `namespace=` keyword without the group losing anything. - -**`Declaration.replay(builder)`** is how a recorded call moves onto another builder: - - arguments = () if self.target is None else (self.target,) - getattr(builder, f"with_{self.kind}")(*arguments, name=self.name, **self.kwargs) - -Resolved by name with `getattr` rather than through a table, which is the fourth Builder -anti-pattern -- replay drift -- mitigated as the proposal specified: a table is a second place -to edit, and a missing method fails just as loudly as a `KeyError` while needing no maintenance. -One branch above it handles `with_health_checker(name, checker)`, whose name is positional where -every other `with_*` takes it as a keyword; the irregularity is cheaper in one commented branch -than as a breaking change to published API. - -**The refusals** (spec sec. 4.2), all in `_refuse_what_a_group_cannot_honour`, all run before -anything is replayed so a bad group leaves no half-populated registry: - -| Refused | Because | -|---|---| -| the builder has already been built | its components exist and belong to the root, and `build()` injects the configuration process-wide, which happens once | -| `AppBuilder(config)` | one process has one settings tree, one logging configuration and one port, and the group supplies all three | -| a declaration holding an instance | it was constructed at that line, before the group existed, so its namespace and registry key are already the root's | - -**Order matters and is documented in the code:** the already-built check runs *first*, because -`build()` adopts whatever configuration it resolved, so a built builder always reports one too -- -check the configuration first and its message is the only one anybody ever sees. Found by a test -that asserted the wrong message. - -**`app_builder.py`** - -- **`host_agent(namespace)`** -- extracted from `with_namespace`, which now calls it. Not a - `with_*`: it declares no component, it states a fact about the process. `build()` needs that - fact because two of the things it does are per agent rather than per component -- it wires one - transport per hosted agent, and asks each agent's configuration whether that agent publishes. - Neither can be derived from the declarations, because an agent may declare nothing and still - have opted into publishing. The builder is *told*; it never learns another builder exists. -- **`has_config` and `is_built`** -- two public booleans, which is what the collector reads. - Booleans rather than the objects: handing out the configuration would hand out the *unscoped* - loader, and config rework step 2b removed every path to that. -- **`with_health_checker` records** a `Declaration` with `kind="health_checker"` instead of - stashing into a lazily-created `_custom_health_checkers` attribute behind a `hasattr` check. - This is what stops a group silently dropping an agent's readiness checks, and it hands step 6 - the `(namespace, name)` pair it needs as data. The key is still the bare name, so a readiness - payload is unchanged and two agents declaring `"db"` still collide -- that is step 6's fix. - Calling it *after* `build()` still adds straight to the live `ActuatorApi`, because by then - the declarations have been replayed and recording would do nothing. -- `_UNCONSTRUCTED_KINDS` names the two kinds the replay pass does not construct: a cache is - created by `CacheBackendFactory`, and a health checker is not a `Component` at all. -- **Deleted:** `from_group`, `with_group`, `_load_registration`, `_skip_or_raise` -- 126 lines, - and with them the `importlib` and `group_config` imports. `AppBuilder` no longer references - `GroupConfig` in any form. - -**`entrypoint.py`** now reads: - - config = Config(settings_files=DEFAULT_SETTINGS_FILES) - app = AgentGroup.resolve(config, environ=environ).assemble(config) - -so the module holds the one thing neither `AppBuilder` nor `assemble` may do: exit the process. -Its header said it held "the three things `AppBuilder` must not: reading the environment, reading -files, and exiting the process"; two of those now belong to `AgentGroup.resolve`, and the -docstring says so. - -`AgentGroup` is exported from `blueprint.agents`. - -**Tests.** `test_with_group.py` becomes `tests/unit/agents/test_agent_group.py`, rewritten -against the new surface: one namespace per agent, a group of one, one declaration serving two -agents, a declaration not consumed by being assembled, an empty group, name validation, all -three refusals with the messages that name the agent and the fix, a factory accepted where an -instance is refused, nothing assembled when a refusal fires, the group's caches and an agent's -own cache, a health checker carried over, loading and the critical flag, no I/O in `from_config`, -`resolve`, and a case asserting `AppBuilder` has neither `with_group` nor `from_group`. -`test_entrypoint.py`'s declaration is now an unbuilt `AppBuilder`, and its standalone case builds -a separate one -- a builder builds once, and only that file runs both shapes in one process. -1994 unit tests pass, 15 more than before this step. - ---- - -### Phase 8b, step 4 -- four declaration surfaces become one - -**Deleted: `RegisteredComponent`, `AgentRegistration`, `NamespaceBuilder`, -`AppBuilder.with_registration`, `AppBuilder.with_namespace` and its two `@overload`s, and the -`namespace=` keyword on all five `with_*`.** `app_builder.py` goes from 1566 lines to 1236. -`AgentRegistration.apply` and its `appliers` dict go with the class. - -This is the payoff the phase was for. Adding one `with_*` method meant editing four places -- -`AppBuilder`, `AgentRegistration`, `NamespaceBuilder`, and `apply`'s `appliers` dict -- and -three of those failed *silently*, the capability simply absent from that surface. There is now -one place. The other three existed only to defer construction until a namespace was in force, -and step 1 removed that reason. - -**What replaced each of them** - -| Deleted | Now | -|---|---| -| `AgentRegistration` | an unbuilt `AppBuilder` -- used without `build()`, it *is* the declaration | -| `NamespaceBuilder` + `with_namespace` | `AgentGroup`, which takes named builders | -| `AgentRegistration.apply` + `appliers` | `Declaration.replay`, resolving the method with `getattr` | -| `namespace=` on the five `with_*` | the ambient scope the group opens | - -**`_record` lost its namespace parameter**, and that is the point rather than a tidy-up: - - namespace = current_namespace() - -A declaration takes the namespace in force *where it is written* -- the root for a standalone -application, the agent's own for a declaration a group is replaying inside `namespace_scope`. -So nothing a developer writes names a namespace, and the same file serves both deployment -shapes unchanged. - -**A removed keyword that would have kept working is refused.** `namespace` is not an error to -Python once the parameter is gone -- it falls into `**kwargs` and is forwarded to the -component's constructor, and `ServiceBase` accepts one. So `with_service(OrderService, -namespace="orders")` would have gone on placing the component in `orders`, by an entirely -different mechanism, until the first component with its own `__init__` failed at build time -instead. `_record` therefore refuses the keyword by name and says what it would otherwise do. -Found by writing the test that asserts the keyword is gone and watching it not raise. - -**Smaller changes:** - -- The five `with_*` type hints gained `| Callable[[], T]`. Factories were always accepted and - were only ever in `AgentRegistration`'s signatures; with that class gone, `AppBuilder`'s - signatures have to say what it takes. -- The instance-namespace refusal is still there and still reachable -- ``with_service(instance)`` - with a scope open -- but its message no longer suggests a `namespace=` argument as the fix. -- `blueprint.agents` no longer exports `AgentRegistration` or `NamespaceBuilder`. -- `AgentSpec.module`'s docstring says `AppBuilder` rather than `AgentRegistration`; it is what - step 3 made true and this is where it is written down. - -**Tests.** `test_agent_registration.py` deleted -- its subject no longer exists. -`test_namespace_builder.py` becomes `test_namespace_placement.py`, keeping every case whose -subject survives the API change: the ambient scope qualifies the registry name, reaches the -component, is never forwarded to its constructor, and is captured at the call rather than at -construction; explicit names are qualified; an already-built instance is refused for another -namespace; `host_agent` records the composition and refuses a duplicate, the root and an illegal -name; a scoped declaration is not a hosted agent. It gains `TestTheDeletedSurfaces`, four cases -pinning that the other three surfaces stay deleted and unexported. - -`test_build_namespaces.py` and `test_route_namespacing.py` were written against -`with_namespace(...)`. The route tests now use `AgentGroup(...).assemble(config)` directly, -because they assert on the application. The transport tests need the *root builder* -- the -endpoints they assert on register nowhere, and `assemble()` returns the application and keeps -its builder private -- so they use a local `hosting()` helper that runs `assemble`'s loop -through the same public `Declaration.replay`, with a docstring pointing at `test_agent_group.py` -for the group's own behaviour. - -`tests/unit/agents/app_builder/TESTS.md` updated: it documented two files that no longer exist -and a `with_health_checker` that no longer works that way. - -1963 unit tests pass, zero failures. The count is 31 *lower* than after step 3, and that is the -deletion showing up rather than coverage lost: the cases for two classes that no longer exist -went with them. - ---- - -### The migration guide implied a default group, and there is none - -**Documentation only. No code changed, and none should.** - -`docs/guides/multi-agent-setup.md` could be followed to the end and produce an image that will not -start. Its section B -- migrating an existing single-agent project -- changes the `Dockerfile` to -`CMD ["python", "-m", "blueprint.agents.entrypoint"]`, copies `agents.toml` in beside the settings, -and stops. Nothing on that path says the container also needs `BLUEPRINT_AGENTS` or a mounted group -file, and three separate passages actively suggest it does not: - -- "*The `Dockerfile` runs `python -m blueprint.agents.entrypoint`, which reads `agents.toml`, works - out this process's group, and serves it*" -- which states the causal order backwards. The entry - point resolves the group *first* and reads the map afterwards, to turn the names it already has - into modules. -- "*Required even for a group of one: it is the only thing that turns an agent's name into code*", - said of `agents.toml`, which reads as though the map is what makes the group-of-one case work. -- The three-ways table, whose grouped row was a bare `python -m blueprint.agents.entrypoint` beside - two other rows that genuinely are complete commands. - -The behaviour those passages describe does not exist. `GroupConfig.resolve` takes the agent list -from the group file slice or from `BLUEPRINT_AGENTS`, and raises `GroupConfigError` when it has -neither -- *before* `_read_agent_map` is called at all (`group_config.py:166-173`), so "every agent -in the map" is not a fallback that was considered and rejected at runtime, it is not reachable. The -refusal is pinned by `test_no_agents_anywhere_is_an_error`, which deliberately writes a populated -`agents.toml` into the fixture and asserts the resolve still fails: the test's subject is precisely -that a full map does not supply a group. - -**The refusal is right, and the fix is in the prose.** A default of "run everything in the image" -would mean that adding a second agent to `agents.toml` silently changes what every already-deployed -process runs -- new queue-group consumers, new durables, new routes -- with no Deployment edit -anywhere. That is the failure the two-file split exists to prevent: the map has image lifetime, the -group has deployment lifetime, and a default would collapse the two. `asbs dev` *can* default to -every agent in the map (`cli-reference.md`) because a developer's laptop is the whole deployment; -that asymmetry is where the expectation comes from, and it is not one a container can copy. - -Four edits, all in `docs/guides/multi-agent-setup.md`: - -- The introduction to the entry point now states the order the code actually runs in, and follows - it with the rule in its own paragraph: the group is never read from `agents.toml`, there is no - default and no "every agent in the map", and a container given neither exits before binding its - port. -- Section B step 2 is retitled "one command, and the group it runs" and gains the missing half: - that unlike `uvicorn src.main:app`, which named what it served, the entry point has to be told, - and that copying the map does not tell it. It shows both routes -- an `ENV BLUEPRINT_AGENTS` line - as a development default, or `-e` per run -- notes that `asbs setup` writes that `ENV` line while - a hand-migrated `Dockerfile` has to add it, and quotes the `Cannot start:` line a container - produces without it. -- Step 3 keeps its claim about the map and adds what the claim is not: it turns a name into code, - it does not supply the name. The existing argument against discovery by convention is extended - by one clause, since "run everything in the map" is the same mistake in a different costume. -- The three-ways table's grouped row becomes `BLUEPRINT_AGENTS=order python -m - blueprint.agents.entrypoint`, with a paragraph under it saying the group is required, that - `BLUEPRINT_AGENTS` is the short form, and that a mounted `deployment-groups.yaml` declaring - exactly one group needs no `BLUEPRINT_GROUP` beside it. - -`docs/guides/deployment.md` needed nothing: it already says "*With neither, the process stops -before binding its port and prints which of the two is missing*", and gives both `docker run` -shapes. `README.md` already shows `-e BLUEPRINT_AGENTS=...` on every grouped example. The defect -was specific to the migration path, which is also the one path where the scaffolding does not -supply the answer for you -- a project from `asbs setup` gets `ENV BLUEPRINT_AGENTS` written into -its `Dockerfile` and never meets this. - -**Left alone, deliberately:** the error message names only the two environment-variable routes -("*Either mount a group file and name the group with `BLUEPRINT_GROUP`, or set `BLUEPRINT_AGENTS`*") -and omits the mounted-file-with-exactly-one-group case that `_read_group_file` supports, so it tells -you to set `BLUEPRINT_GROUP` when you may not need to. That is a `src/` change and is not part of a -documentation fix; it is listed under Open points. - ---- - -## Compatibility - -**Two breaking changes have landed.** The second one only affects a project that already uses -`Config(agent_scope=...)`; the scheduler change discussed further down is deliberately *not* on -this list, and why is stated with it. - -**Breaking change 1: `scheduler_mode` is required.** A project that registers a -scheduler and does not set it fails at `build()` with an error naming both values and what each -one costs. Nothing changes behaviour silently: the alternative -- defaulting the key -- would -either keep firing a timer per replica (#73) or stop ticking a service that has no broker, and -neither is safe to inherit. The reasoning, including the counter-argument, is under *P5* above; it -is a deliberate departure from spec sec. 7.5 and needs a spec amendment. - -**Breaking change 2: a scoped `Config`'s telemetry `service.name` is now the agent's name.** -This affects a project that constructs `Config(agent_scope="foo")` -- which is not new, it has -been available since April and is on `develop`, so this is a change to shipped behaviour rather -than to something only this branch can reach. - -| | Was | Is | -|---|---|---| -| `otel_service_name` for a scoped view | `.otel_service_name`, else root `otel_service_name`, else `.app_name`, else root `app_name` | `.otel_service_name`, else the scope name | - -So a repo with `foo.app_name = "Foo Service"` and no `foo.otel_service_name` sees its -`service.name` change from `Foo Service` to `foo`, and one relying on a *root* -`otel_service_name` while using a scope sees it change to the scope name as well. The root path is -untouched, so a project that passes no `agent_scope` -- every single-agent application -- is -unaffected. - -**Migration** is one line if the old name matters: set `.otel_service_name` to whatever the -dashboards already key on. Keeping the old chain was the alternative and is what C2 forbids: it -lets every agent in a group report one `service.name`, and then regrouping moves work between -agents no dashboard can tell apart. The point of the change is that the agent's name is the one -identity it has. - -**Migrating an existing service with a scheduler** is one line, and which line depends on the -deployment: - -| Situation | Set | -|---|---| -| No `event_bus`, or plain Docker, or local development | `scheduler_mode = "in_process"` | -| Kubernetes with `event_bus = "dapr"` / `"nats"`, more than one replica | `scheduler_mode = "event"`, plus a `CronJob` publishing to `.scheduler.` | - -`"in_process"` reproduces today's behaviour exactly, including its once-per-replica firing -- it is -the no-op migration. `"event"` is the one that fixes #73, and until P5's second half generates the -`CronJob` the publisher has to be written by hand, which is why the second row is not yet the -recommended answer for anyone. - -**A spaced `app_name` now fails an event-mode scheduler's startup instead of being rewritten.** -This is the one behaviour change here that can affect an existing project: `app_name = "Health -Monitor"` with `scheduler_mode = "event"` used to derive the tick subject -`Health_Monitor.scheduler.` and now raises at startup, naming the key, the value and that -subject. The rewrite was never safe -- the `CronJob` publishing the tick is written against the -subject by someone who cannot see the rewrite, so the failure it produced was a tick that never -arrived and no log line anywhere explaining it. Migration is either renaming `app_name` to a -subject-safe value or passing `topic=` explicitly. A wildcard in `app_name` or `nats_queue_group` -likewise now fails, where before it reached the broker as a queue name and seeded a wildcard -dead-letter subject. - -**The namespace alphabet is a constraint on code that does not exist yet.** Nothing constructs a -namespaced client today, so no name in any deployment is affected; a namespace must now be `""` or -`[a-z][a-z0-9_]*`, which is enforced before the first namespaced agent can be declared. Doing it -now is free -- after the first namespaced deployment, changing the alphabet would rename durables, -and renaming a durable is a consumer migration (spec sec. 7.7). - -Everything else remains non-breaking. Specifically: - -- `Component.__init__`, `ClientBase.__init__` and `ServiceBase.__init__` gained an optional - `name` parameter, and `IOClientBase.__init__`, `NATSClient.__init__`, `DaprClient.__init__` and - `EventPublishingService.__init__` an optional `namespace`. All default to the previous - behaviour, and the root namespace keeps every existing registry name, so no existing - construction site or lookup changes. -- `NATSClient._durable_for` became an instance method (it reads the namespace). It is private; - the public `nats_durable_name` behaviour is unchanged for the root namespace. -- `EventPublishingService.on_startup` now raises a different message when no transport client is - registered -- it names the namespace it looked in. It raised before too, so this is wording. -- `ClientBase.subscribe`'s abstract signature changed from `(topic, callback)` to - `(topic_callbacks)` in P0. This is the one signature change in the feature so far; it affects - implementations of the transport-client interface, of which the repo contains two (`NATSClient`, - `DaprClient`), both updated. It must not change again -- a third-party transport would break. -- `EventHandlingBase.subscribe` (abstract) and `POST /nats/subscribe/{topic}` were removed. The - removed endpoint triggered subscription over HTTP, which the managed lifecycle makes meaningless. -- `DaprEventing.subscribe`'s signature changed, but no working caller can exist: the old signature - answered 422 to the only intended caller. Overrides are unaffected, because `_wire_routes` - registers `getattr(self, name)` walking the MRO subclass-first, so an override's own signature is - what FastAPI sees. -- The Dapr subscription document is empty for every project **in this repository**, since - `get_subscribed_topics()` is overridden nowhere here. That is not a guarantee about downstream - projects: the method is a documented override point (`event_handler_base.py:164`, with an example - in its docstring), so a consumer project may well override it. For such a project the discovery fix - changes Dapr behaviour by design -- declared topics went from subscribing to nothing to - subscribing -- and if it *also* declares the same topics as Kubernetes `Subscription` resources, - the sidecar now holds a declarative and a programmatic subscription for one topic. - `dapr_declarative_subscriptions = true` exists for exactly that case, but it defaults to `false`. - Whether Dapr merges the two or delivers twice needs checking against a real sidecar; it belongs on - the broker-test list. -- New config keys all default to current behaviour. -- **Phase 8 is entirely additive.** A standalone `main.py` deployment is untouched: nothing - reads `deployment-groups.yaml` or `agents.toml` unless `python -m blueprint.agents.entrypoint` - or `GroupConfig.resolve` is called, and `uvicorn src.main:app` behaves exactly as before. -- **New environment variables, all optional**: `BLUEPRINT_GROUP_CONFIG`, `BLUEPRINT_GROUP`, - `BLUEPRINT_AGENTS`, `BLUEPRINT_CRITICAL_AGENTS`, `BLUEPRINT_AGENT_MAP`. They are read only by - the group resolution, never by `Config`, so they cannot collide with a project's settings. -- **`pyyaml>=6.0` is a new declared dependency.** Asked for and approved; it is what reads the - group file. Already present in every environment through `uvicorn[standard]`, so declaring it - changes no installed set -- it stops the group file depending on a *transitive* dependency, - which is the thing that breaks on an unrelated upgrade. -- **`.app_name` is no longer required.** A scoped `Config` used to refuse to load without - it. Setting one is still allowed and still read, but only for display. -- **An agent's `otel_service_name` now defaults to its own name rather than to `app_name`, and no - longer inherits a root-level `otel_service_name`.** A single-agent application is unchanged: - explicit `otel_service_name`, then `app_name`, then the default. A grouped agent's - `service.name` becomes its agent name unless it sets its own -- which is the point (C2), and - which does change what a dashboard sees for a project that had been relying on the root value - while using namespaces. -- **A namespaced scheduler's derived tick subject changes from `.scheduler.` to - `.scheduler.` -- and this is deliberately *not* counted as a breaking change.** - A scheduler's namespace is only non-empty when it was constructed inside a `namespace_scope`, - which exists only on this branch: `SchedulerBase.__init__` never took a namespace, and - `Component`'s namespace parameter arrived with P6. So no deployed scheduler can have one, and - no `CronJob` in the field publishes to a namespaced subject. A root scheduler -- every one that - exists -- derives exactly what it derived before. - - It *is* a change for anyone who adopted this branch mid-flight and gave a scheduler a - namespace: their tick subject moves, and the publisher has to move with it. The startup log - names the subject in both modes, which is where to read the new value. Note also that - `Config(agent_scope=...)` alone does **not** give a scheduler a namespace -- a scoped config and - a component's namespace are different things before this branch -- so a project using - `agent_scope` today is unaffected by this one. -- **An explicit `name=` is now namespace-qualified, wherever it is set.** At the root -- every - single-agent application -- `qualified_component_name("", name)` is `name`, so nothing changes. - Inside a namespace, a component constructed directly with `name="planner"` registers as - `orders_planner` where it used to register as `planner`. The builder path already behaved this - way. -- **`Registry.update_component_name` refuses a name that is taken** instead of overwriting the - entry. Anything relying on the overwrite was losing a component silently. -- **`AppBuilder.with_namespace` refuses an agent name it already hosts** instead of merging into - it. To assemble one agent from several parts, compose them into one `AgentRegistration`. -- **`EventHandlerBase.get_runtime_name(event, context)` is new and defaults to `None`.** It was - already in the class's usage docstring, so a project may have written one; it is now actually - called. Returning `None` keeps today's behaviour. -- **The processing context gains `runtime` and `runtime_name` keys when a runtime can be chosen.** - A single-agent application with one `AgentRuntime` now finds them populated where it did not - before -- additive, and nothing in the framework reads them. With several runtimes and no - declaration neither key is set, and a WARNING names the candidates once per handler. -- **`process_event`'s `runtime_name` argument is no longer only logged.** It seeds the context as - the caller's choice, below the handler's own `get_runtime_name` and above the single-runtime - fallback. A caller that passes nothing is unaffected. -- **`DaprEventing()` takes no namespace, and `DaprEventing._client` is now `_clients`, a dict - keyed by namespace.** There is one endpoint per process, at the root. A single-agent - application's document, delivery path and acknowledgement are all unchanged. -- **A group of consuming agents on Dapr now works** (it was refused in phase 6 part 2). One - delivery is fanned out to every agent that declared the topic, and the one acknowledgement is - their combination -- so **a retry asked for by one agent redelivers to all of them.** Set - `idempotency_enabled` for grouped Dapr, or keep handlers repeat-tolerant. NATS is unaffected. -- **`_process_cloud_event` and `_dispatch_cloud_event` gained a trailing optional `namespace`.** - Both are protected; the default is the endpoint's own namespace, which is what every caller - except the Dapr fan-out passes. -- **The `/cache/*` endpoints take an optional `?name=`, defaulting to `default`.** Every existing - call is unchanged. New answer: an unknown name is `404` rather than `503`, and `POST - /cache/evict` now includes a `"cache"` field in its response body. -- **`/readiness` gains one entry per named cache, as `cache:`.** The default cache keeps - the entry name `cache`, so an existing payload is unchanged. A project that registered only a - named cache previously had no cache health check at all. -- **A namespaced component's routes move to `/api//...`, and its tags gain an - `.` prefix.** Nothing moves for an application that declares no namespace: a root REST - API stays under `/api`, and a root transport endpoint stays at `/events/{topic}` and - `/dapr/subscribe`. -- **`RestApiBase.route_prefix` is new**, and public, because `DaprEventing.subscribe` has to - render the same prefix the builder mounts. -- **A group of two or more consuming agents on `event_bus = "dapr"` now fails at `build()`.** - The sidecar fetches the subscription document from one fixed path, so per-agent documents - would leave it subscribed to nothing. Single-agent Dapr is unchanged; NATS hosts groups - normally. Listed under *Open points*. -- **`AppBuilder._eventing_component` is now `_eventing_components`, a list.** Underscore-private, - but anything introspecting it breaks. It holds exactly one element for every application that - declares no namespace. -- **`event_publishing_enabled` is now read per agent**, through that agent's configuration view. - A root-level key still applies to a single-agent application unchanged; in a group an agent can - set its own, and `.event_publishing_enabled` wins over the shared value. -- **`SessionsApiClient`, `SessionKeyProvider` and `SessionsBus` gained a leading optional - `namespace`.** All three are framework-constructed from `build()`, so the leading position - affects nobody. -- **Phase 5 is not a consumer migration, and expects neither a replay nor a gap.** The plan - requires this to be stated, because renaming a durable or changing a filter set is broker-side - state and a recreated consumer resumes by its delivery policy. Neither happens here: the - namespace-qualified durable landed with P6 and is dormant until a namespace exists (the root - keeps `-durable`), and phase 5 changes no filter set -- one durable per - `(namespace, topic)` filtering one subject was already the shape, so declaring a topic adds a - consumer instead of reconfiguring one. The first deployment that *is* a migration is the first - one that declares a namespace, and it creates new consumers rather than renaming existing ones. -- **`RestApiBase.__init__` gained a keyword-only `namespace`**, forwarded to `Component`. - Defaults to the root, and every subclass in the repo already passes `should_register` by - keyword, so no existing call changes. -- **`NatsEventing.__init__` and `DaprEventing.__init__` gained a leading optional `namespace`.** - Both are framework-constructed and unregistered, so the leading position affects nobody. -- **The `blueprint.events.unhandled` and `blueprint.events.duplicate` counters now carry the - endpoint's real namespace** instead of a hardcoded root. A single-agent application still - reports `namespace=""`, so no existing dashboard sees a new label value. -- **`EventHandlerBase.get_handled_event_types()` is new and defaults to `[]`**, which means - "offer me every event" -- the behaviour every handler has today. Overriding it narrows only - which events that handler is *asked* about; `can_handle_event` still decides. Declarations are - matched by equality: a pattern such as `order.*` is refused at startup rather than silently - matching nothing. -- **`SessionsJobHandler` now declares its event type**, derived from the `JOB_TYPE` its - subclasses already set. Selection is unchanged -- the declaration and `can_handle_event` read - one property -- so a subclass sees no difference beyond not being asked about other job types. -- **`HandlerChain.__init__` gained a leading optional `namespace`, and `process_event` / - `process_rest_request` a trailing keyword-only one.** All default to the root. `HandlerChain` - is constructed by the framework only -- it is `should_register=False` and nothing looks it up -- - so the leading position is safe; the two service methods took keyword-only because their - positional tails are used by callers. -- **`HandlerChain._dispatch` now asks for its own namespace's handlers instead of every - namespace's.** For a single-agent application these are the same set: every handler is at the - root. In a grouped process it is the difference between dispatching to one agent and to all of - them. -- **`CloudEventProcessorMixin` requires a `namespace` attribute as well as `registry`.** Both come - from `Component`, which every class it is mixed into already subclasses. -- **`AppBuilder.with_cache` gained a keyword-only `name`, and the three positional forms are - unchanged.** `with_cache()`, `with_cache(False)` and `with_cache(True, False)` mean what they - always meant, which is why `name` had to come last and be keyword-only (spec sec. 4.2). The - default cache keeps its registry key `disk_cache_service`, its configured `cache.cache_dir` and - its Redis key prefix, so no existing cache data moves. -- **`DiskCacheService.__init__` and `RedisCacheService.__init__` gained a trailing optional - `component_name`, and `CacheBackendFactory.create` a trailing optional `name`.** Additive and - defaulted; existing positional calls are unaffected. `create` derives the component name from - the cache name, so callers pass one name rather than two that have to agree. -- **`AppBuilder.with_*` gained a keyword-only `namespace`, and an explicit `name=` is now qualified - with the namespace the component was built in.** At the root -- every single-agent application -- - `qualified_component_name("", name)` is `name`, so nothing changes. In a namespace the key becomes - `_`, which is what makes one registration applicable to two agents at all. -- **`EventHandlingBase._process_cloud_event` takes a third argument, `topic`.** A protected method, - so this affects only a third-party transport implementation that called it -- of which the repo - contains two, both updated. -- **`POST /events/{topic}` answers `200 {"status": "DROP"}` instead of `422` for a body that is not - a CloudEvent -- but only on `DaprEventing`.** Chosen so the two transports dispose of an - unparseable payload identically; NATS already terminated it. A caller that treated 422 from this - path as its error signal sees a 200 instead. The same path on `NatsEventing` is unchanged and - still answers 422, since there the caller is a REST client rather than a sidecar. -- `nats_queue_group` is new and defaults to `app_name`, so no deployment has to set it. It does - change broker-side behaviour for anyone already running more than one replica on Core NATS: - duplicate processing stops, which is the point. A deployment whose correctness depended on every - replica seeing every message would be affected, but that shape cannot be built on this framework - today -- there is no way to opt a subscription out of the queue group. -- **`app_name` values containing whitespace are now rejected at startup.** `nats-py` raises - `BadSubjectError` for a queue name containing a space, so an `app_name` like `"My Agent Service"` - -- legal, and working, before subscriptions carried a queue group -- would have failed inside the - background retry task and retried forever behind a red readiness probe. `_resolve_queue_group` - checks for whitespace and raises at startup naming the key and the value, so the cause is visible. - Affected projects set `nats_queue_group` to a whitespace-free name. This is the one case where a - single-replica deployment that worked before does not start after the upgrade. -- **Single-replica Core NATS behaviour is otherwise unchanged**: a group of one receives everything, - exactly as an ungrouped subscription did. The exception is an agent subscribing to overlapping - subjects (a wildcard plus a literal it covers), where the count of dispatches per message may drop - from two to one -- see the broker-test open point. -- **Dapr is untouched by P1.** The queue group is a NATS concept; `DaprClient` has no equivalent, and - no Dapr code path reads the new key. Delivery under Dapr is unchanged by this change. -- **Dapr is untouched by P3 as well.** Consumer tuning, deliver groups and dead-lettering are - JetStream concepts; under Dapr the sidecar owns retries and its own dead-letter topic, configured - on the Dapr component rather than here. No Dapr code path reads the new keys. -- **Core NATS is untouched by P3.** The new keys are read only when `nats_use_jetstream = true`, and - `_settle` still returns immediately on Core NATS, where there is nothing to acknowledge. -- **A JetStream deployment that already has a durable consumer keeps it, unchanged.** The client - binds to what the broker has and logs the difference. Until that consumer is deleted, the new - `ack_wait`, `max_ack_pending`, `max_deliver` and -- importantly -- the deliver group are not in - force, so such a deployment is still single-subscriber. This is deliberate: recreating a durable - replays or gaps. -- **The JetStream stream may gain subjects on startup.** An existing stream is widened to cover each - subscribed subject and the dead-letter subject. Widening is additive and never removes a subject, - but it is a write against a resource an operator may consider theirs. A stream the application - cannot update is reported as an error naming the missing subjects, and the consumer bind then - fails visibly rather than silently consuming nothing. -- **`nats_durable_name` set together with more than one subscribed topic now fails at startup.** It - could not have worked: a durable filters one subject, so the second consumer would have been - rejected by the broker. The error names both topics. -- **Durable names change for dotted topics** -- `orders.created` now yields `orders_created-durable` - rather than the illegal `orders.created-durable`. No migration is possible or needed, because a - consumer under the old name could never have been created. -- **JetStream now publishes to a second subject.** With dead-lettering enabled, which is the default, - the client publishes to `.dead-letter`. A deployment whose broker permissions allow - publishing only to specific subjects has to grant that one, or set `nats_dead_letter_subject = ""`. - -- **P4 changes nothing for a project that does not opt in.** `idempotency_enabled` defaults to - `false`, and with it off `_claim` returns immediately and the cache is never touched. The handler - loop itself is unchanged -- it moved from `process` into `_dispatch` verbatim. -- **`EventProcessingService.on_startup` and `on_shutdown` are no longer no-ops.** They delegate to - the handler chain's hooks. A subclass overriding either without calling `super()` now skips the - chain's startup, and with dedup enabled would run with an unresolved policy -- which `process` - then resolves on first use, so it degrades to a late error rather than a silent one. -- **Enabling dedup without `idempotency_ttl`, or without a cache, fails at startup.** Both are - deliberate: the first is the decision the spec requires the author to make, and the second would - otherwise disable dedup silently at the moment it was switched on. -- **`blueprint.events.duplicate` is a new counter.** `blueprint.events.unhandled` no longer counts a - deduplicated event, but it could not have: nothing could be deduplicated before this change. -- **The `idempotency` cache namespace is new.** It shares the registered cache with application - data but not its namespace, so nothing an application stores can collide with a marker. A - deployment sizing its cache should account for one small entry per event within the TTL window. - -- **A spaced `app_name` no longer breaks an event-mode scheduler.** Whitespace in a *derived* tick - topic is rewritten to `_`, so `app_name = "Health Monitor"` yields - `Health_Monitor.scheduler.`. An explicitly passed `topic=` is not rewritten and still - fails on whitespace, and a wildcard fails in either form. -- **P5 adds a subscription and a publish permission an event-mode scheduler needs.** The scheduler - subscribes to `.scheduler.`, and whatever publishes its tick has to be - allowed to publish there. Under JetStream that subject also has to be covered by the stream, which - the client widens on startup. -- **A registered scheduler now makes the application create a transport, in event mode only.** The - scheduler contributes a tick handler, and `build()` creates `NATSClient`/`DaprClient` and the - eventing endpoint when any handler is registered. A project that had a scheduler and no handlers - previously started no transport at all; in event mode it now requires `event_bus`, enforced by - `_require_event_transport` rather than left to the generic "no valid event_bus configured" - warning. In `"in_process"` mode nothing is contributed and no transport is created. -- **`POST /api/{scheduler_name}/trigger` starts working.** It was added to the router during startup, - after `include_router` had already copied it, so it was never served. Anything relying on it - answering 404 sees a behaviour change. -- **A subclass overriding `on_startup` without calling `super()` was already broken and still is.** - The base method is what starts the timer, wires the tick handler and registers the trigger route. - The scaffold and the generated docs no longer show an override without the `super()` call. -- **`SchedulerBase.__init__` gained a keyword-only `topic` parameter.** Positional callers are - unaffected; `crontab` is still the first positional argument. -- **A scheduler's `on_startup` and `on_shutdown` now run once per lifespan instead of twice.** A - subclass that relied on the second call -- for instance by counting on an idempotent resolve - happening twice -- changes behaviour. Every scheduler in this repository and in the scaffold is - unaffected. The visible effect is the opposite of a regression: an in-process scheduler now runs - one timer where it used to run two. -- **`event_publishing_enabled` is new and defaults to off**, so no existing application creates a - client it did not create before. A consuming application is unaffected: its handler already - implies the client, and `EventPublishingService` is still keyed on the client existing rather - than on the new key. Setting it with no `event_bus`, or with `event_bus = "sessions"`, fails at - startup rather than at the first publish. -- **`parse_bool` is new in `blueprint.agents.utils`** and is exported from that package. Nothing - was removed: `HandlerChain._read_bool` keeps its signature and behaviour. -- **`CacheService` gained an abstract method, `claim`.** Both bundled backends implement it. A - third-party subclass of `CacheService` outside this repository will not instantiate until it - does too -- the one signature change in this step, and it is additive to the interface rather - than a change to an existing method. -- **An `"in_process"` scheduler now consults the cache on every tick.** With a cache registered - the tick fires once per scheduled slot across all replicas instead of once per replica, which is - the fix; a deployment that was (knowingly or not) relying on N replicas each doing the work will - see it done once. With no cache registered nothing changes except a startup warning. -- **An event-mode scheduler's crontab is now validated at startup.** A project whose declared - expression is not a five-field cron -- including an apscheduler six-field form with seconds -- - fails `build()` where it previously started and waited for a tick. In `"in_process"` mode nothing - changes: `CronTrigger.from_crontab` already rejected the same expressions. -- **`blueprint.agents.io.api.scheduling` exports exactly what it did before**, plus - `SchedulerTickHandler` and the three `SCHEDULER_MODE*` names. `validate_crontab` is importable - from `...scheduling.scheduler` but is not part of the package's public surface. - -The spec's one deliberate future break is `with_cache`'s `name` parameter (sec. 10.1), which must -stay keyword-only and last, or an existing `with_cache(False)` would silently become a cache named -`False`. - ---- - -### Phase 8b, step 5 -- a cache is private to the agent that declared it - -**D3, and the half of spec sec. 8 that was never built.** Sec. 8 requires that cache names be -namespace-scoped and that `get_cache(name)` resolve within the declaring agent and raise -otherwise. What existed was the *data-partition* half: `AgentScopedCache`, a lens that prefixed -each call's partition argument with the agent, over one shared backend. Two agents therefore -still shared a store, a `size_limit` and a Redis keyspace, and the isolation held only as long -as every call site went through the lens. - -The isolation is now **structural**: separate registry entries, separate directories, separate -key prefixes. There is nothing left for a prefixing lens to prevent, so it is deleted. - -**`Registry` -- the store is keyed on `(namespace, name)`** - - self._caches: dict[tuple[str, str], CacheService] = {} - -and every cache method takes the owning agent, defaulted from the object it is called on: - - def _cache_owner(self, namespace: str | None) -> str: - if namespace is not None: - return namespace - return self._default_namespace or ROOT_NAMESPACE - -That default is the whole developer-facing story: `Component.registry` hands a component its own -namespace's view, so `self.registry.get_cache("sessions")` reaches this agent's store with no -namespace at the call site -- and `add_cache`, `has_cache`, `get_all_caches` and the -`cache_service` alias resolve the same way. `add_cache(name, cache, namespace=...)` names one -explicitly, which is what `build()` uses. - -**`_cache_owner` deliberately differs from `_effective_namespace`.** For components an omitted -namespace on the application's registry means *every* namespace, which is what `build()` and the -lifespan need when they iterate. For caches it means *the root*, because every cache operation -names exactly one cache: there is no cache that belongs to all agents, and a lookup ranging over -the process would be the cross-agent sharing sec. 8 exists to prevent. - -- `get_cache` has **two fallbacks that do not exist** -- none from an unknown name to the - default, and none from an agent to the root or a neighbour. The message names the agent and - lists what *that* agent has: `No cache registered as 'sessions' for agent 'billing' - (registered: none)`. -- `get_all_caches(namespace=None)` is **one agent's**, keyed by bare name. -- **`cache_entries()` is new** and is the only cache view that crosses agents: - `list[tuple[str, str, CacheService]]`, `(namespace, name, cache)`. It **raises on a view** - (C6) -- a view is what agent code holds, and an agent that can enumerate its neighbours' caches - can be written to depend on them. The agent is returned **as data**, not folded into the name, - because a cache name may legally contain the separator (`v2.sessions`), so a caller that has to - attribute a cache to an agent must not be splitting a string. `clear()` iterates the tuple keys - and names the agent in its log line. - -**`CacheBackendFactory` -- one argument carries every consequence of ownership** - -`create(config, enable_locking, name, *, namespace="")`. The bare name stays what is validated -and what appears in the registry; the *storage* name is composed here, in the same class that -already owned "how a name becomes a separate store": - - @staticmethod - def storage_name(namespace: str, name: str) -> str: - return name if not namespace else f"{namespace}.{name}" - -`_scoped_cache_dir` and `_scoped_key_prefix` now take that storage name, so agent `orders` -declaring `sessions` gets `/orders.sessions` on disk and `:orders.sessions` on -Redis, and its *default* cache gets `/orders.default` -- only the root keeps the -configured directory itself, which is what leaves a single-agent application reading exactly the -store it always did. The directory stays a **subdirectory** of `cache.cache_dir` for the reason -named caches already did: under `readOnlyRootFilesystem` only the mount is writable, so one -volume per group still works and a group does not multiply the writable paths a pod needs. - -`.` is the separator because it is in the cache-name alphabet and not in the namespace alphabet: -an agent's storage name is still a legal cache name, and no cache name can forge one. `_` is in -both, which would make `orders_sessions` ambiguous between agent `orders` and a root cache of -that name. - -**`create` also enters the namespace scope itself**: - - storage = CacheBackendFactory.storage_name(namespace, name) - with construction_scope(namespace): - if config.backend == "redis": - return CacheBackendFactory._create_redis(config, enable_locking, name, storage) - return CacheBackendFactory._create_disk(config, enable_locking, name, storage) - -A cache backend is itself a `Component`, so two agents' caches both derive -`disk_cache_service` and collide on that one registry name unless each is constructed inside its -agent's scope. Doing it in the factory rather than at the call site means the `namespace` -argument alone decides *both* where the cache stores and what it registers as, whatever scope -the caller happens to be in -- **found by a test**: the first version scoped only in `build()`, -and a direct `create(..., namespace="orders")` produced an agent-scoped store with a root -registry name, which failed the moment a second agent did the same. - -**`construction_scope` moved to `component/namespace.py`** and is now public. It was -`app_builder._construction_scope`: the guarded form of `namespace_scope` that leaves the ambient -namespace alone for the root, because `namespace_scope("")` is not a no-op -- it *sets* the root. -The factory needs exactly that guard, and the trap is one that gets re-derived wrongly, so the -one implementation lives beside the thing it guards. - -**`AppBuilder` -- three things are per agent at build time** - -`_create_cache(declaration, config)` now takes the configuration and reads the agent's own view: - - cache_service = CacheBackendFactory.create( - config.for_namespace(namespace).get_cache_config(), - enable_locking=enable_locking, - name=name, - namespace=namespace, - ) - registry.add_cache(name, cache_service, namespace=namespace) - -So the *backend* is chosen per agent too (C5): one agent in a group can run on redis while its -neighbour uses the disk, which a process-wide read of `cache.backend` could not express. - -**The readiness probe attributes each cache to its agent:** - - for namespace, cache_name, cache in registry.cache_entries(): - entry = "cache" if cache_name == DEFAULT_CACHE_NAME else f"cache:{cache_name}" - health_providers[f"{namespace}.{entry}" if namespace else entry] = CacheHealthChecker(cache) - -Two agents' default caches were previously one entry keyed `cache`, so the payload reported -whichever registered last and one agent's Redis outage was invisible. The root keeps the bare -`cache` / `cache:sessions` entries, so an existing readiness payload does not change. (Step 6 -generalises this to every health checker and stores the attribution as data; this is the cache -half, which step 5 cannot leave broken.) - -**`/cache/*` became per agent:** - - for namespace in self._cache_owners(registry): - with construction_scope(namespace): - cache_api = CacheManagementApi() - self._mount(app, cache_api, root_prefix="/api") - -One router per agent that declared a cache, mounted under that agent's `/api/` prefix by -the `route_prefix` mechanism phase 6 built, each resolving names through its own registry view. -So `/api/orders/cache/stats` reports the orders agent's caches and cannot reach billing's -- -where one process-wide endpoint would have reported one agent's keys to another. `_cache_owners` -derives the list from `cache_entries()` rather than from `hosted_namespaces`, because a cache is -declared and not implied: an agent that declared none gets no endpoint, exactly as an application -built without `with_cache()` has never served `/cache/*`. A standalone application keeps -`/api/cache/*` unchanged, and its 503/404 branches now speak about that agent's caches. - -**Deleted** - -- **`AgentScopedCache`** (`services/infrastructure/agent_scoped_cache.py`) and `Registry`'s - `_scoped_cache` / `_scoped_caches` machinery, including the reset of `_scoped_caches` in - `for_namespace`. Separate stores make the isolation structural, so the lens has nothing left to - prevent -- and it had a real weakness: it was per registry *view*, so framework code holding - `Component.shared_registry` directly still reached the shared store. -- **`GroupConfig.cache_names`**, its env-override slot and its line in the resolution log; the - `cache_names` argument to `AgentGroup` and the `with_cache` replay loop in `assemble`. A group - declares no caches because there is no process-wide cache to declare. `cache_names` in a - mounted group file is now **read by nothing** -- ignored rather than refused, because a - rollout must not fail over a key that has become inert, and `GroupConfig` reports only what it - understands. - -**Knock-on, as D3 predicted:** `has_cache()` and `cache_service` answer per agent, so an agent -with `idempotency_enabled = true` must itself declare `with_cache()`; a neighbour's cache no -longer satisfies it. The existing error message already says exactly what to add. This is what -changed `test_event_processing_namespaces.py`'s fixture, whose `orders` agent enables dedup: its -cache is now registered *for* `orders` instead of at the root. - -**Tests.** `test_agent_scoped_cache.py` deleted with its subject. New: `TestCachesPerAgent` in -`test_registry.py` (13 cases -- two agents holding one name, no fallback by name, through the -root or by enumeration, the per-agent alias and `has_cache`, `cache_entries` carrying the agent -as data and refused on a view, `clear` reaching every agent); -`TestACacheBelongsToTheAgentThatDeclaredIt` in `test_named_caches.py` (registration, directory, -two agents' separate stores, both backends registering as components, the agent's own config view, -and the readiness entry); `TestAgentIsolation` in `test_cache_backend_factory.py` (the storage -name at the root and for an agent, the separator staying a legal cache name, separate directories -and Redis prefixes, the directory staying inside the mount); `TestCacheEndpointsPerAgent` in -`test_route_namespacing.py` (per-agent paths through `app.openapi()`, no endpoint for an agent -that declared none, and the standalone paths unchanged). `test_agent_group.py`'s -`TestTheGroupsCaches` is rewritten around agents owning caches, including the D3 case -- two -agents declaring `sessions` get separate stores and neither can read the other's. - -1975 unit tests pass, zero failures. - ---- - -### Phase 8b, step 6 -- a health check carries the agent it belongs to - -**D4.** A readiness check was a dict entry, `name -> checker`, and that lost the attribution -twice over. Two agents calling `with_health_checker("db", ...)` collided on one key and one -disappeared with nothing logged; and even where the keys differed -- a client's registry name is -already unique -- nothing recorded *whose* check a failing entry was, which is exactly what -`readiness_policy = "critical"` (phase 9) has to answer. - -**`HealthCheckEntry`, in `health/health_base.py`** -- the value object the dict becomes: - - @dataclass(frozen=True) - class HealthCheckEntry: - name: str - namespace: str - checker: HealthCheckerBase - - @property - def key(self) -> str: - return qualified_entry_name(self.namespace, self.name) - - @property - def agent(self) -> str: - return self.namespace or ROOT_LABEL - -The agent is **data**; `key` is only its rendering. Recovering the namespace by splitting the key -would break on the first name containing the separator, and `cache:v2.sessions` is one. `agent` -exists so a log line can name the root without every caller writing the `or ROOT_LABEL`. - -**`qualified_entry_name` in `component/namespace.py`** is the rendering, and it is a *second* -naming rule rather than a reuse of `qualified_component_name`: - - def qualified_entry_name(namespace: str, name: str) -> str: - return name if not namespace else f"{namespace}.{name}" - -`.` rather than `_`, deliberately. A registry name is an identifier other code looks up, and `_` -is what every lookup qualifies with; an entry name is a label nothing resolves, and it may -contain characters a registry name never does -- `cache:sessions` already does. Rendering both -the same way would suggest a readiness key can be passed to `get_component`, and it cannot. The -route-tag prefixing in `_mount` now calls it too, so the dotted form has one definition instead -of two spellings. - -**`HealthCheckCache` polls entries, not a mapping.** `set_health_check_provider(dict)` becomes -`set_health_entries(Sequence[HealthCheckEntry])`, and the poll loop lost its intermediate dict: - - results = await asyncio.gather(*(entry.checker.health_check() for entry in self._entries), return_exceptions=True) - - for entry, result in zip(self._entries, results, strict=True): - if isinstance(result, BaseException): - logger.warning("Health check '%s' of agent '%s' failed: %s", entry.name, entry.agent, result) - components[entry.key] = ComponentHealth(status="unhealthy", message=f"Check failed: {result}") - else: - components[entry.key] = result - -The payload is still `dict[str, ComponentHealth]` keyed by `entry.key`, so the response *shape* -is unchanged and the root's keys do not move. What is new is that the object doing the ANDing -knows whose each result is -- phase 9 groups these by `entry.namespace` and needs no string -surgery to do it. The failure log names the agent separately from the entry, because "whose -check is failing" is the question asked of a group. - -**`ActuatorApi.add_health_providers` accumulates, and refuses a duplicate key.** It took a -mapping and **assigned** it: - - self._pending_providers = providers # before - self._health_cache.set_health_check_provider(providers) - -That is a live defect, not just a shape: the method's own docstring documents calling -`with_health_checker` *after* `build()`, and doing so replaced every client and cache check the -build had wired -- before startup by overwriting `_pending_providers`, after startup by -overwriting the cache's mapping. The readiness probe then reported one component and nothing -else. It now appends to `self._health_entries`, re-pushes the whole list to a live cache, and -raises on a key that is already taken: - - raise ValueError( - f"Health check '{entry.name}' of agent '{entry.agent}' would appear in the readiness payload as " - f"'{entry.key}', which is already taken by a {type(existing.checker).__name__} of agent " - f"'{existing.agent}'. Two checks under one entry cannot be told apart in the payload, so one of " - "them has to be renamed." - ) - -Refused rather than kept-last, because silent loss is the whole of what D4 is about. It is -checked here rather than at `with_health_checker` because this is the single funnel every source -passes through -- clients, caches, declared checkers, and post-build additions -- and a collision -between two *different* sources is only visible at this point. `health_entries` is a public -read-only property; `_pending_providers` is gone. - -**`AppBuilder` attributes every source.** `_health_checkers` is a `list[HealthCheckEntry]`, and -the three sources compose their entries: - - health_providers: list[HealthCheckEntry] = [ - HealthCheckEntry(name=client.base_name, namespace=client.namespace, checker=ClientHealthChecker([client])) - for client in registry.get_clients() - ] - for namespace, cache_name, cache in registry.cache_entries(): - name = "cache" if cache_name == DEFAULT_CACHE_NAME else f"cache:{cache_name}" - health_providers.append(HealthCheckEntry(name=name, namespace=namespace, checker=CacheHealthChecker(cache))) - health_providers.extend(self._health_checkers) - -and `with_health_checker` records `current_namespace()` on the entry for the post-build path as -well, so a checker declared inside an agent's scope belongs to that agent wherever it is flushed. - -**`Component.base_name` is new, and the client entry is why.** A client's registry name is -already qualified -- `orders_nats_client` -- so passing it as the entry name rendered -`orders.orders_nats_client`. Stripping the prefix back off is not available: -`qualified_component_name` is deliberately not idempotent, precisely because "does -`billing_handler` in agent `billing` carry a prefix?" is not decidable from the string. So the -unqualified half is kept at construction instead of being recovered later: - - self._base_name = name or camel_to_snake(self.__class__.__name__) - self._name = qualified_component_name(self._namespace, self._base_name) - -The setter updates both. A grouped client's readiness key is therefore `orders.nats_client`, and -a root client's is `nats_client` -- the key it has always had. - -**What a payload looks like now**, from a probe against real objects (two agents, each with a -handler, a cache and a `db` checker): - - orders.nats_client | orders | ClientHealthChecker - billing.nats_client | billing | ClientHealthChecker - orders.cache | orders | CacheHealthChecker - billing.cache:sessions | billing | CacheHealthChecker - orders.db | orders | DbChecker - billing.db | billing | DbChecker - -Every entry reads `.`, and the same probe confirmed the duplicate refusal fires and -that a post-build checker now adds a seventh entry instead of replacing the six. - -**Unchanged on purpose:** the policy. Every checker is still polled on a timer and ANDed, so one -unhealthy check still returns 503 for the whole pod -- in a group, one agent's outage still -removes every agent from rotation. That is `readiness_policy = "all"`, which phase 9 makes -selectable; this step only makes the attribution available to it. `ComponentHealth` and -`ReadinessResponse` are untouched, so nothing about the response schema changes. - -**Tests.** `test_health_cache.py` moved onto entries and gained `TestAnEntryIsAttributedToItsAgent` -(root keeps the bare name, an agent's is prefixed, two agents declaring one name are two -components, the failure log names the agent). `test_actuator_api.py` gained -`TestRegisteringChecks` (accumulation across calls, two agents sharing a name, a duplicate -refused across calls and within one call, a post-startup addition reaching the live cache). -`test_build_namespaces.py` gained `TestEveryReadinessEntryNamesItsAgent` against real components --- including that the key does not carry the agent twice, and that `namespace` is readable -without splitting the key. `test_name_uniqueness.py` gained `TestBaseName`, whose last case pins -the non-idempotence that `base_name` exists to work around. The app_builder, named-cache and -agent-group tests that asserted on the old dict now read `health_entries`. - -1996 unit tests pass, zero failures. - ---- - -### Phase 8b, step 7 -- an agent's own settings file becomes that agent's scope - -**D5, spec sec. 5.3.** An agent author writes plain keys in their own directory's -`settings.toml` -- `model_name = "..."`, or a `[default]` section, which is what every scaffolded -project has -- and the build merges that file **under that agent's scope**. The author never -learns that a scope exists, and the same file serves the project standalone and as one agent of a -group. That is the requirement the whole feature rests on: only `main.py` may differ between the -two. - -**`Config.merge_agent_settings(namespace, path)`** is the whole of it, and it is on the loader -only -- calling it on a view raises, because authoring another agent's configuration through a -view is the breach that reading one is (C6). - - fragment = self._layer_fragment(document) - fragment = self._drop_process_scope_keys(namespace, resolved, fragment) - ... - existing = self._settings.get(namespace) - merged = dict(existing.items()) if hasattr(existing, "items") else {} - added = self._fill_missing(merged, fragment) - self._settings[namespace] = merged - -Writing a subsection into the loaded tree is all the "merge" a scope needs: probed first, and -`for_namespace("orders").get("model_name")`, `_scoped_get("cache.cache_dir")` and -`resolved_settings("orders")` all pick it up, because the tree is what they read and a view -shares it by reference. - -**Precedence: what is already in the tree wins, and the fragment fills the gaps.** -`_fill_missing` recurses so a fragment's `[cache] cache_dir` joins a group's -`[default..cache] size_limit` instead of replacing the table or being dropped by it. Two -things this protects at once: a value the group's own settings state under `[]` -- the -deployment named the agent, so it meant it, and a file baked into the image does not overrule it --- and an environment override (`DYNACONF___KEY`), which Dynaconf has already put in the -tree by the time this runs and which a file read afterwards must not clobber. - -**`_layer_fragment` resolves the file itself rather than handing it to Dynaconf**, and that is -forced rather than chosen. Dynaconf always reads `DYNACONF_*` from the environment and cannot be -told not to (`loaders/env_loader.py`, established in config rework step 3a), so a Dynaconf-loaded -fragment would pull *process-wide* environment overrides into one agent's scope -- including the -very keys the next paragraph refuses, which would then be reported against a file that does not -contain them. So the file is read with `tomllib` and layered explicitly, lowest first: keys -written at the top level, `[default]`, the section for the environment in force, then `[global]`, -matching what Dynaconf does with the process's own file. A top-level table that is *not* one of -those three names is a value, not an environment: `[cache]` beside `[default]` is this agent's -cache configuration. - -**Process-scope keys are dropped, loudly** -- `PROCESS_SCOPE_KEYS` in `config.py`: - - {"app_port", "app_host", "app_workers", "app_environment", "envvar_prefix", "event_bus", - "log_level", "log_format", "suppress_noisy_loggers", "health_check_interval_seconds", - "dot_placeholder", "nats_stream_name"} - -plus `DEPLOYMENT_IDENTITY_KEYS`, which `get()` refuses to answer at all. One process binds one -port, loads one environment section, reads its environment through one prefix, speaks one event -bus and configures logging once, so every one of those is read from the group's configuration and -never from an agent's scope: a copy under `[]` would be read by nothing. -`nats_stream_name` is the one entry whose reason differs -- it *is* read through an agent's own -view, so a scoped value would take effect, and it is dropped because the stream is a server-side -object shared with every other deployment on that broker. - -**Departure from the spec, argued: sec. 5.3 says such a key MUST raise; it warns instead.** The -evidence is in this repository. Every one of the seven example projects declares `app_port` and -`app_environment` in its `settings.toml`, and several declare `log_level` and `event_bus`: - - [default] - app_name = "Order Event Pipeline" - app_port = 8000 - app_environment = "development" - log_level = "INFO" - event_bus = "dapr" - -Raising would mean **no existing project could be hosted as an agent without first editing a file -that is correct for its own standalone deployment** -- which contradicts the constraint the spec -itself serves, and would fail a rollout over a key the file has every right to contain. The -purpose of the MUST is that the author can discover the value is inert, and that is what the -warning does, naming the agent, the key, the file and the value in force: - - Agent 'orders' sets 'app_port' in /app/pkg/orders/settings.toml, and that is a process-wide - setting: one process has one of it, so this value (8000) is ignored and the group's own value - (8080) is used. Remove it from the agent's settings file, or set it in the group's. - -**Display metadata is deliberately not in the list.** `app_name`, `app_version` and -`app_description` are in every scaffolded file, and a scoped `app_name` is genuinely read -- the -NATS queue group falls back to it, and so does the telemetry service name -- so an agent naming -itself is its own business. - -**Where the file is looked for: beside the module that declares the agent.** - - module_path = module_spec.partition(":")[0] - module = sys.modules.get(module_path) - file = getattr(module, "__file__", None) - ... - return Path(file).parent / "settings.toml" - -One rule, and one an author can see without reading the framework: an agent is a directory of -handlers, services and a declaration, and its settings belong to that directory the same way. -Read from `sys.modules` rather than by importing again, so the answer is the file Python actually -loaded rather than one guessed from a dotted path. `AgentGroup.from_config` records it per agent -that loaded -- a skipped non-critical agent has no scope to merge into -- and -`AgentGroup(name, agents, settings={...})` takes them directly, which is what the tests use. - -**`assemble` merges before the root builder exists:** - - for namespace in self._agents: - path = self._settings.get(namespace) - if path is not None: - config.merge_agent_settings(namespace, path) - - root = AppBuilder(config) - -Ordering is the load-bearing part: `build()` is where components are constructed and where each -one reads its keys through its agent's view, so a fragment merged afterwards would be a file read -too late to matter. A test pins it by having a service read `model_name` in its constructor. - -**One guard found by its own test.** A fragment path that resolves to one of the process's own -settings files is skipped, with DEBUG naming it. Without it, an agent whose declaration module -sits beside the group's `settings.toml` would have every root key merged under its scope a second -time -- and every process-scope key reported against the group's own file. It fired immediately: -the first version of the group tests wrote the fragment into `tmp_path`, which is where the -fixture's own settings file lives, and the merge correctly did nothing. - -**Not done, deliberately:** `.secrets.toml` per agent. The spec names `settings.toml`, and an -agent's secret belongs in the environment, where `DYNACONF___KEY` already resolves per -agent (verified during the config rework). One file, one rule. - -**Tests.** New `tests/unit/agents/config/test_agent_settings_fragments.py`, 38 cases in five -classes: what an agent reads (a plain key, a `[default]` section, the environment section winning -over it, another environment's section ignored, nested tables, a top-level table as a value, the -root default still the fallback); isolation (the root and a neighbour unchanged, two agents -declaring one key, a view refused, the root refused); precedence (the group's own value for the -agent wins, the fragment fills the rest, a nested table merged key by key); process-scope keys -(dropped, reported with the file and the value in force, an existing project's file hosted -unchanged, every listed key parameterised, deployment identity dropped too); and files that are -not there (absent, the process's own, empty, unparseable -> `ConfigError`). -`test_agent_group.py` gained `TestEachAgentsOwnSettings`: where the file is looked for, an agent -that ships none, a fragment merged under its scope, merged *before* the components are built, one -agent's file not reaching another, and a group given none. - -2040 unit tests pass, zero failures. - ---- - -### Phase 8b, step 8 -- what a group does to each declaration, said where it is read, and gated - -Three parts, and the first one is documentation on purpose. The decision taken when `AgentGroup` -was designed was **RTFM, not authoring-time validation**: a group refuses what it cannot honour -at assembly, and everything else it does to a declaration -- moving routes, scoping a cache, -resolving a scheduler's mode per agent -- is *behaviour*, not an error, so the place it has to be -written is the method a developer is already reading. - -**Part 1: group behaviour on each `with_*`.** Every declaration method now carries an **In a -group:** paragraph, and each says something that method does not share with the others: - -- `with_handler` -- its own `HandlerChain` and its own subscription, so it is never offered a - neighbour's events, and `idempotency_enabled` needs a cache *this* agent declared. -- `with_service` -- only the registry name changes (`orders_order_service`), plus what - `self.registry` and `self.config` answer for. -- `with_agent` -- the class and factory forms work, but only the `AgentBuilder` form is handed - the scoped configuration view, so a runtime reading its own model wants that one. -- `with_scheduler` -- `scheduler_mode` resolves per agent, so an in-process timer can sit beside - an event-driven neighbour; `"in_process"` claims each tick in *this* agent's cache and - `"event"` needs the group's `event_bus`; its routes move with the agent's. -- `with_rest_api` -- **the routes move**: `/api/`, tags prefixed, nothing in the component - changed, but a client of a grouped agent addresses the prefixed path. -- `with_cache` -- private to the declaring agent, separate stores for the same name, backend from - this agent's configuration, `/cache/*` per agent. -- `with_health_checker` -- the entry becomes `.`, a collision is refused rather than - silently reduced, and the readiness *policy* is unchanged (still ANDed, still 503 for the pod). - -**Part 2: the surfaces-agree gate**, `tests/unit/agents/app_builder/test_declaration_surface.py`. -Adding a capability is now one edit, but the group still has to move a recorded call from one -builder to another, and `Declaration.replay` does that with -`getattr(builder, f"with_{self.kind}")`. So there are exactly two ways for the halves to part -company, and **neither is visible in a single-agent application**: a method that records a `kind` -no method answers to, and a replay that does not reproduce the call. Both would be found in -production by whoever first grouped two agents. - -The gate discovers the methods rather than listing them -- - - return sorted(name for name in dir(AppBuilder) if name.startswith("with_")) - --- and pairs each with a sample call, so **a new `with_*` fails this file until it is listed**. -Per method it asserts: exactly one declaration recorded; the registry untouched (collect, then -wire); `replay` onto a fresh builder reproduces the declaration exactly; a replay inside -`namespace_scope("orders")` takes the namespace from the scope and not from the source; and the -recorded `kind` has a `with_` to go back to. - -**Probed, because a gate that cannot fail is decoration.** Three drift modes injected against -the real classes: - - 1. uncovered methods the gate would report: ['with_widget'] - 2. recorded kind 'gadget'; AppBuilder has with_gadget(): False - replay of that kind fails, as the gate predicts: 'AppBuilder' object has no attribute 'with_gadget' - 3. declarations equal after a lossy replay: False - recorded name: planner | replayed name: None - -A `with_widget` added to `AppBuilder` is reported as uncovered; one recording `kind="gadget"` is -caught by the kind assertion *and* fails replay with the `AttributeError` the docstring predicts; -and a `replay` that drops `name` breaks the equality. - -**Part 3: the frozen compatibility suite**, `tests/unit/agents/test_frozen_compatibility.py` -- -spec sec. 10.2, which asks for a suite "never updated to the new API; if it needs editing, a -break shipped". It did not exist; it does now, and its module docstring says exactly that. Twenty -cases, every one written the way a project in `examples/` writes it today, instance forms -included, because four of the seven examples pass constructed objects: - - app = AppBuilder(config).with_service(InventoryService).with_rest_api(InventoryApi()).with_cache().build() - -and asserting the observable things such a project depends on: `with_cache(False)` and -`with_cache(True, False)` positionally (sec. 10.1 names both); `get_component("inventory_service")` -and `get_component("disk_cache_service")` resolving unprefixed; `registry.cache_service` as the -alias; two services resolving *one* cache object; `/api/inventory` with its own tag unrewritten; -`/api/cache/stats` unprefixed; `/health/ready`, `/health/live` and `/info` where they were; the -readiness entries `cache` and a bare `database`; and a component constructed with -`super().__init__()` getting `("inventory_service", "")`. - -The fixture is an example's `settings.toml` key for key -- `app_name`, `app_port`, -`app_environment`, `log_level`, `[default.cache]` -- which is the same file step 7 refuses to -raise over. The one fixture that is *not* frozen usage is the autouse -`Component.reset_shared_state()`, and it says so: a test file is many processes in one, which a -deployment never is. - -**Not done, and belongs in this open point rather than this step:** sec. 10.2's second half, the -generated-project smoke test (`asbs setup`, then build and start the result unchanged). It needs -Docker, which this machine does not have, and it is the only part of the compatibility guarantee -that covers the Dockerfile and `main.py` paths a unit test cannot reach. - -2100 unit tests pass, zero failures. The 60 added are the two new files. - ---- - -### Phase 8b, step 9 part 1 -- `AGENTS.md` exists - -`CLAUDE.md:5` has said *"See `AGENTS.md` for architecture, component patterns, and testing -conventions shared across all AI assistants"* for months, and -`git log --all --diff-filter=A -- AGENTS.md` returns nothing: the file was never written and -later deleted, it was **cited into existence**. `docs/plans/2026-06-10-sessions-job-handler.md:122` -goes further and quotes what it "states" about versioning. So this part adds no new home for -documentation -- it turns a pointer that resolves nowhere into one that resolves. - -**What it contains**, in the order it is read: - -- **Where things are** -- one table for `src/blueprint/agents/`, module by module, and one - paragraph pointing at the prose in `docs/` for users. Every path in it was checked to exist. -- **Component patterns** -- the six base classes and the five things every component of any of - them has in common (its constructor takes only what its author wrote; `self.registry`, - `self.config` and `self.executor` answer for its own agent; collaborators are resolved in - `on_startup`, not `__init__`; the lifecycle pair; what `should_register=False` is for), plus - the acknowledgement contract for handlers. -- **Design rules**, in six groups, each rule stating the rule, the reason, and **the failure it - prevents**: construction and assembly (collect then wire; one declaration surface; single-use - builders; group policy belongs to the collector), namespaces and isolation (a component never - learns it is in a group; structural where it can be and audited where it cannot; no cross-agent - fallback; an omitted namespace on the root registry means every namespace; entering the root - scope is not a no-op), names that leave the process (validated never repaired; two components of - one class collide on the derived name; a check answerable at the call stays at the call), - declarations and defaults (an empty declaration means everything; a key whose absence changes - behaviour is required), configuration and logging (injected before any component exists, read - through the component's own view, no public read path to the loader; isolation audited not - enforced; a process-scope key cannot be set per agent; logging belongs to the application), and - versioning. -- **Testing conventions** -- the unit/integration split and the `integration` marker, the - `TESTS.md` per package, probing against real objects, asserting on the observable thing rather - than on the call, what a test's docstring is for, that the frozen suite is frozen, and that a - guard test states its rule in its failure message. -- **How the work is done** -- no unused code; probe rather than assume, and say which it was; the - spec wins on precedence, not on correctness; report the code, not the wrapper. - -**The failure line is the point.** A rule without the failure it prevents is advice, and advice -gets argued away by the next person with a deadline. Most of these were bought with a defect -- -`namespace_scope("")` silently resetting every component to the root, a `MagicMock` registry -hiding six ownership bugs, `must_exist=True` beside a `default=` passing while the key is unset -- -and the failure line is the receipt. - -**Two claims in it were wrong when written, and were fixed rather than softened.** - -- *"Every test package has a `TESTS.md`."* Ten of them do, all under `tests/unit/agents/`, but - the top level -- where `test_agent_group.py`, `test_group_config.py`, `test_entrypoint.py` and - the new frozen suite live -- had none, and `tests/unit/agent_generator/` and - `tests/integration/` still have none. So `tests/unit/agents/TESTS.md` was written as part of - this commit, and the rule now says what is true, exceptions included. A rule that is already - violated by the tree it governs is the same failure as a document cited into existence. -- *"A `CHANGELOG.md` entry under the unreleased section."* The section is spelled `[Unreleased]`; - checked against the file. - -**The versioning quotation now resolves.** `.github/workflows/publish.yml` extracts the version -from the git tag and rewrites `pyproject.toml` at build time, so the sessions plan's claim that -"`AGENTS.md` states versioning is handled by CI publishing; manual bumps are forbidden" is true -of the pipeline -- and is now stated in `AGENTS.md`, which is where that plan said to look. Part 3 -has one less thing to fix. - -`CLAUDE.md:5` was extended to name the design rules as well, since the file it points at now -carries them. - -No production code changed; 2100 unit tests still pass. Parts 2 (the guard tests) and 3 (the -documentation cleanup) follow as their own commits. - -### Phase 8b, step 9 part 2 -- the guards, and the four defects they found - -`tests/unit/agents/test_design_rules.py`: one section per rule from `AGENTS.md`, and **every -failure message names the rule it enforces**, because someone who hits one of these has not made -an ordinary mistake in a test -- they have crossed a design decision and need to read the -decision. 565 cases, all of them cheap. - -| Guard | What it asserts | -|---|---| -| *Collect, then wire* | every `with_*` on `AppBuilder` **and** `AgentBuilder`, called reflectively: the registry is untouched, **no configuration is linked at all**, and the builder comes back for the next call | -| *One declaration surface* | per `AppBuilder` method: one declaration recorded, `replay` reproducing it, the namespace taken from the scope in force, and the recorded `kind` having a `with_` to replay onto | -| *A lookup never falls back across agents* | two agents' `sessions` caches kept apart, and no fallback to a neighbour, to the root, or from an unknown name to the default | -| *A component never learns it is in a group* | the ambient namespace reaching a component nobody passed one to; no `get_known_namespaces` on `Registry`, `Component` or `Config`; and the two refusals a view gives (`cache_entries`, `for_namespace`) | -| *A name is validated, never repaired* | five namespace entry points and the deployment route against seven illegal names, the cache alphabet at the `with_cache` call, and a legal name coming back unchanged | -| *No public read path to the unscoped loader* | the public configuration surface is exactly `config`, `configure`, `has_config`; no public attribute *is* the loader; a namespaced component reads through its own view | -| *Logging is configured by the application* | no logging configuration at import time anywhere under `src/`, and none in the framework outside `LoggingManager` | -| *No diagnostics via print* | nothing in the framework prints except the two listed stderr writes, each of which must still write to stderr | -| *References resolve* | every markdown link, every cited path in the documents that describe the tree as it stands, and every document cited by name | - -**The declaration-surface test moved here from `tests/unit/agents/app_builder/`** and was -generalised: the collect-then-wire half now runs over `AgentBuilder` as well, which records fields -rather than `Declaration` objects but is bound by the same rule -- `with_model_from_config` is the -method that used to read configuration while accumulating, and that one read is what forced an -agent to be built before its namespace existed. The stronger form of the assertion is that -**nothing is configured at all** while declarations are recorded: a `with_*` that reads a key -cannot pass it. - -**Four defects, found by the guards rather than by reading.** Two are production code: - -- **`clients/io/dapr_client.py` configured logging at import time.** Two `setLevel` calls on the - `httpx` and `httpcore` loggers at module level, so importing the Dapr client silenced those - loggers process-wide for an application that never asked. Both levels are already in - `LoggingManager._suppress_noisy_loggers`, which the `suppress_noisy_loggers` setting turns off - -- so the lines were duplication that also **overrode the application that had turned it off**. - Deleted; the setting is now the only thing that decides. -- **`agent_generator/generator/generator.py` configured logging at import time**, and that one - had a visible symptom: `asbs setup` imports `AgentGenerator`, so the module-level `basicConfig` - ran first and installed a root handler, and `setup.py`'s own `basicConfig` -- the one that reads - `--verbose` -- then found the root already configured and **did nothing**. `asbs setup --verbose` - has not been verbose. Moved into `cli()`, which is an entry point and may configure logging; - the flag works again. - -Two are documentation, both of which the references guard found: - -- **`CHANGELOG.md`** linked `ServiceInfo` to `/src/blueprint/agents/models/status.py:8:0-25:5` -- - an editor-pasted location, not a path. Rewritten as a citation. -- **`tests/unit/agents/services/TESTS.md`** still listed - `infrastructure/test_agent_scoped_cache.py`, deleted with `AgentScopedCache` in step 5. Row - removed. - -**One finding is listed rather than fixed.** `README.md` links twice to a `LICENSE` file that has -never been committed, while the README text and `pyproject.toml`'s classifier both say MIT. -Writing a licence file is a legal artefact and a human decision, so it is in the guard's -`KNOWN_GAPS` with that reason -- and a further case asserts every listed gap is **still** broken, -since an allowlist that outlives its entries is how a guard stops guarding. - -**The evidence corrected the guard twice**, which is worth recording because both were premises -that looked obviously right: - -- *A padded agent name is refused everywhere.* It is not, and should not be: the agent list is a - list, and both routes into it (`BLUEPRINT_AGENTS="orders, billing"`, or a YAML sequence) strip - each element before validating it. That is list parsing, not name repair -- the whitespace - belongs to the separator. The guard now uses `" Orders "` there instead, which is trimmed and - then still refused on the capital, so the trim cannot grow into a general repair. -- *A document cited by name must exist, in every document.* Not in the records: a proposal names - the documents it intends to write (`docs/guides/multi-agent-setup.md`, phase 10's deliverable) - and the alternatives it rejected (`docs/concepts/design-rules.md`), and both would fail. So that - check skips `docs/plans`, `docs/specs`, `docs/superpowers` and `CHANGELOG.md`, whose **links** - are still checked. The citation that motivated the whole guard was in `CLAUDE.md`, which is not - a record. - -The reference guard's scope is stated in the file with its reasoning, since a check on prose has -to say what it holds prose to: links are checked everywhere; path citations only in the documents -that describe this repository as it stands -- not in the records, which correctly name deleted -files, and not in the project-facing guides, whose `src/main.py` resolves in a generated project. -`docs/adr/` and `CLAUDE.local.md` are not scanned at all: neither is part of the repository, and a -guard has to give the same answer on every machine. - -**Every guard was verified by injection**: an import-time `setLevel` and a `print()` in -`utils/utils.py`, a dead link, a dead path citation and a fictitious `NOTHING.md` in `AGENTS.md`, a -root fallback in `Registry.get_cache`, and a construction inside `AppBuilder._record`. Each failed -exactly one guard, with the rule in the message, and nothing else. - -`AGENTS.md` now cites the file -- part 1 deliberately did not, since it did not yet exist -- both -under *Design rules* and beside the testing convention that requires a guard to state its rule. -`tests/unit/agents/TESTS.md` gained the row; `tests/unit/agents/app_builder/TESTS.md` lost the one -for the moved file. - -2625 unit tests pass, zero failures. Part 3, the documentation cleanup, follows. - -### Phase 8b, step 9 part 3 -- one home per document, and the 500 that documenting one found - -The audit behind step 9 listed four pieces of documentation debt. Two were real and are fixed, one -had already been closed by part 1, and **one turned out to rest on a misreading** -- recorded here -rather than quietly dropped, because an audit item that dissolves on inspection is worth the same -sentence as one that holds. - -**`docs/superpowers/` is gone.** It held `plans/` and `specs/` mirroring `docs/plans` and -`docs/specs` -- 3 files, 2079 lines, linked from nothing. They are ordinary plan and spec -documents, so they were **moved** rather than deleted: `2026-04-01-component-naming-refactor.md` -and `2026-07-06-sessions-agent-registration.md` into `docs/plans/`, -`2026-07-06-sessions-agent-registration-design.md` into `docs/specs/`. The plan's one citation of -its own spec was repointed; the only other links in the three files are same-document anchors. -`test_design_rules.py` lost `docs/superpowers` from `HISTORICAL_DOCUMENTS`, which would otherwise -have been a prefix matching nothing -- dead configuration in the guard that exists to catch dead -pointers. - -**Four cache documents became one.** `docs/concepts/caching.md` (347), -`docs/concepts/cache-system-overview.md` (232), `docs/concepts/cache-architecture.md` (181) and -`docs/guides/caching-getting-started.md` (208) -- 968 lines, one of which `docs/README.md` linked --- are now a single 387-line `docs/concepts/caching.md`, the path both READMEs already pointed at. -The other three are deleted; git history keeps them. - -It is a rewrite rather than a merge, because the linked one was wrong about nearly everything a -reader would try: - -- **The REST API section documented four endpoints that have never existed** - (`GET`/`PUT`/`DELETE /api/cache/{namespace}/{key}`, `DELETE /api/cache/{namespace}`). The real - API is `GET /cache/stats`, `GET /cache/namespaces` and `POST /cache/evict`, each taking `?name=`. -- **Every example awaited a synchronous method.** `CacheService.get`/`set`/`delete` are ordinary - `def`s; `await self.cache.get(...)` does not work and never did. -- The closing example called `with_agent("embedder", EmbedderAgent)`, a signature that does not - exist. -- Nothing mentioned per-agent caches, named caches, `claim`, or `/api//cache/*`. -- `caching-getting-started.md` documented `default_ttl = null` as "no expiry". `CacheConfig.default_ttl` - is an `int`, and TOML has no null: **there is no way to configure "never expires"**, and an - omitted `ttl` gets the 3600-second default on both backends. - -The new document states what the code does, verified against it: declaration and the -`with_cache(False)` / `name=` shapes, the synchronous operations table, `claim` and the race it -closes, key hashing, namespaces, TTL, per-agent isolation with the storage layout for both -backends, the configuration table with per-agent `[default..cache]`, the Redis startup ping -and `fallback_to_local`, readiness entry names, the three real endpoints with their 503/404 split, -a short design section, and troubleshooting. - -**`GET /cache/stats` answered 500, on both backends, for as long as it has existed.** -`CacheStatsResponse` required five fields. `DiskCacheService.get_stats()` returns four of them -- -never `ttl_tracked_keys`, which **no backend has ever produced** -- so constructing the model -raised `ValidationError`. `RedisCacheService.get_stats()` returns a different shape entirely -(`backend`, `key_prefix`, `redis_version`, `connected_clients`, ...), so on Redis all five were -missing. Confirmed by probe before anything was changed: - -``` -real get_stats() -> {'cache_dir': ..., 'size': 2, 'size_limit': 1000000000, 'eviction_policy': 'least-recently-used'} -CacheStatsResponse RAISED: ValidationError -- ttl_tracked_keys: Field required -``` - -It was invisible because the endpoint's only test fed a hand-written dictionary through a -`MagicMock` -- a dictionary that contained `ttl_tracked_keys`, invented to satisfy a model nothing -satisfied. *Probe against real objects*, exactly. - -The fix says what was true all along: **the statistics are the backend's, not a fixed schema.** -`CacheStatsResponse` keeps the disk backend's four fields as optional, allows extras so Redis's -seven pass through, and the route carries `response_model_exclude_none=True` so each backend -answers with its own fields and no nulls. `ttl_tracked_keys` is deleted, and so is -`CacheEvictResponse`, which was referenced by nothing and described a shape (`success`, -`evicted_keys`) that the evict endpoint does not return. The test now constructs a real -`DiskCacheService` and a real `RedisCacheService` over `fakeredis`, and a third case pins the -behaviour when a backend's own stats call fails: `get_stats` returns `{}` and the endpoint answers -200 with an empty payload rather than taking itself down. End-to-end through a built application: - -``` -/api/cache/stats -> 200 {'size': 0, 'cache_dir': '...', 'size_limit': 1000000000, 'eviction_policy': 'least-recently-used'} -/api/cache/stats?name=sessions -> 200 {'size': 0, 'cache_dir': '.../sessions', ...} -/api/cache/stats?name=nope -> 404 {'detail': "No cache registered as 'nope' for agent '' (registered: default, sessions)"} -``` - -**The false quotation was already closed.** `docs/plans/2026-06-10-sessions-job-handler.md:122` -attributes to `AGENTS.md` that versioning is handled by CI publishing and manual bumps are -forbidden. Part 1 verified that against `.github/workflows/publish.yml` and wrote the rule into -`AGENTS.md`, so the attribution now resolves. Nothing to change; checked, not assumed. - -**`docs/development-workflow.md` is not a dead pointer.** The audit called it "cited by this -plan's own file summary and never written". It is not cited anywhere as existing: its three -mentions are this plan's part 3 item, the changelog, and the plan's *Planned, not yet written* -section, whose own preamble says "each is a deliverable, not an open question". So there is no -reference to drop, and writing the end-to-end walkthrough now would pre-empt phase 10, which owns -the narrative documentation. Left where it is. This is the same distinction the references guard -draws by not holding a record to the tree as it stands -- and the audit item was, in effect, the -guard's rejected premise in prose form. - -`README.md` and `docs/README.md` keep their one caching link, with descriptions that now say what -the document covers. - -2620 unit tests pass, zero failures. - ---- - -### Phase 9 -- an agent's identity, and its failure, survive being grouped - -Phase 9 is the deployment-facing half of the namespace model. Everything before it made agents -share a process correctly; this makes the sharing legible from outside. Grouping takes away three -things a process per agent got for free -- a `service.name` that means one agent, a pod restart -that named the failure, and a readiness probe with one subject -- and the four invariants here -(C2, C3, C4, C7) put each of them back deliberately. - -#### C2 -- one telemetry identity per agent, and the root unchanged - -`io/telemetry/telemetry.py` configured one `TracerProvider` for the whole process, with -`service.name` from `otel_service_name`. Setting that to the group would break every dashboard on -the day of a regrouping; leaving it would attribute twenty agents' spans to one service. - -`TelemetryManager.configure_tracing(namespaces)` now builds **one provider pair per namespace**, -through `_configure_namespace`: - -```python -service_name = root_service_name if namespace == ROOT_NAMESPACE else namespace -resource = Resource.create({"service.name": service_name, "deployment.group": group, "service.instance.id": pod}) -provider = TracerProvider(resource=resource) -for processor in span_processors: - provider.add_span_processor(processor) -readers = [PeriodicExportingMetricReader(exporter) for exporter in metric_exporters] -register_providers(namespace, provider, MeterProvider(resource=resource, metric_readers=readers)) -``` - -The root is always configured, first, and stays the global provider -(`trace.set_tracer_provider(tracer_provider(ROOT_NAMESPACE))`), so every module-level -`trace.get_tracer(...)` in the framework and in any library resolves as it always has -- which is -what keeps a single-agent application's traces identical. - -The **same `BatchSpanProcessor` object** goes on every provider: a processor owns a queue and an -export thread, and the resource travels on the span rather than on the processor, so a processor -per agent would multiply both by the group size for nothing. Metric readers are the exception and -each provider gets its own, because the SDK binds a reader's collect callback to the provider that -registered it -- a shared reader would only ever collect from the last provider built. The -exporter behind them is still one object. - -**`io/telemetry/providers.py` is new, and is a leaf.** It holds the two registers and -`agent_tracer` / `agent_meter`, and imports nothing from this framework. That is not tidiness: a -component reads its own agent's tracer, so with the register beside the manager, `component.py` -imports the module that imports `Config`, which imports the manager, which imports -`component.namespace` -- a cycle that was confirmed by building it and watching the import fail. -It is also why a component holds no reference to the manager: the group's shape would then be -reachable from the object graph, which is what C6 forbids. - -`Component.tracer` is the one seam that had to change: - -```python -@cached_property -def tracer(self) -> trace.Tracer: - return agent_tracer(self._namespace, type(self).__qualname__) -``` - -Cached, and therefore resolved at first *use* -- which is the only reason this works. Components -are constructed by `build()`; the providers do not exist until the lifespan's `configure_tracing` -call, which is now the first thing startup does, before the actuator and before any client. -`agent_tracer` falls back to the global provider for a namespace nothing configured, so the call -is safe unconditionally and no caller branches on whether telemetry is on. - -`traced()` additionally stamps `agent` on every span: - -```python -if span.is_recording(): - span.set_attribute("agent", self._namespace or ROOT_LABEL) -``` - -Redundant with the resource for a span that reaches an exporter, and not redundant at all for the -failure C7 is about: a span still open when the process is killed never has a resource applied, so -what the span itself carries is all a post-mortem has. - -**`deployment.py` is new**, holding `deployment_group()` and `pod_identity()` -- moved out of -`nats_client.py`, which had them privately. Two subsystems now need the same two values, and two -copies would be two answers to "which pod is this" the day one of them learned a new environment -variable. `nats_client.py` imports them; its connection name is unchanged, and the two tests that -patched `nats_client.socket.gethostname` now patch `deployment.socket.gethostname`. - -#### C3 -- readiness is a policy, and it is per agent - -`io/api/actuators/health/readiness_policy.py` is new: a `ReadinessPolicy` str-enum with `parse` -and `is_ready`. - -```python -def is_ready(self, namespace_status: Mapping[str, bool], critical_namespaces: Collection[str]) -> bool: - if not namespace_status.get(ROOT_NAMESPACE, True): - return False - agents = {ns: healthy for ns, healthy in namespace_status.items() if ns != ROOT_NAMESPACE} - if not agents: - return True - if self is ReadinessPolicy.ALL: - return all(agents.values()) - if self is ReadinessPolicy.CRITICAL: - return all(healthy for ns, healthy in agents.items() if ns in critical_namespaces) - return any(agents.values()) -``` - -Two decisions in that function are not in the spec's table. **The root gates under every policy** --- it holds the shared infrastructure, and in a single-agent application it is the whole -application, so all three policies agree there and the key is safe to set in a settings file that -a standalone project also reads. And **an unrecognised value raises** rather than defaulting: a -misspelt `critcal` read as `all` would remove a whole group from rotation the first time a -non-critical agent wobbled, with nothing to say the key had never taken effect. - -`HealthCheckCache` reduces the individual results to one verdict per agent before applying the -policy. `_aggregate_by_agent` reads the agent **from the entry, never from the key** -- the reason -`HealthCheckEntry` has carried it as data since step 6, because splitting -`orders.cache:v2.sessions` on a separator attributes it correctly only by luck. Every supervised -namespace appears even with no checks of its own, so `any` and `critical` do not read a shorter -list than the group has. - -`ReadinessResponse` gained `policy` and `namespaces`, the latter a `NamespaceReadiness` per agent -(`status`, `critical`, `failing`). It exists because the policy makes `status` no longer derivable -from `components`: a pod can answer `UP` with a failing check in it, and without the per-agent -section that reads as a contradiction with no way to resolve it. The `components` keys are -untouched, so a single-agent payload is unchanged apart from the two added fields. - -The `critical` flag is plumbed from where it already was. `AgentSpec.critical` already decided -whether a failed import stops the process (spec sec. 9.1); `AgentGroup.from_config` now also -collects it, `AgentGroup.assemble` passes it to `root.host_agent(namespace, critical=...)`, and -`build()` hands `ActuatorApi` the composition: - -```python -self._actuator_api = ActuatorApi(self.hosted_namespaces, self.critical_namespaces) -``` - -One flag, twice, deliberately: both ask whether the deployment can run without that agent, so a -second flag would be a second answer to one question. `readiness_policy` joins -`PROCESS_SCOPE_KEYS` -- one pod, one readiness probe. - -#### C7 and C4 -- the failure is reported, and it has a consequence - -`io/api/actuators/health/namespace_supervisor.py` is new, and is where one piece of state becomes -three things. `NamespaceSupervisor` is constructed by `ActuatorApi.on_startup` -- after telemetry, -because it creates instruments -- with every hosted namespace and the critical set. - -**The signal.** One observable gauge per namespace, on that namespace's own meter, rather than one -instrument with an `agent` attribute: the resource carries C2's identity and the resource belongs -to the provider, so an instrument on the root's meter would report every agent's value under the -group's `service.name`. - -```python -def _observe_gauge(self, namespace: str, label: str) -> Callable[[CallbackOptions], Iterable[Observation]]: - def observe(_options: CallbackOptions) -> Iterable[Observation]: - return [Observation(1 if self._up.get(namespace, True) else 0, {"agent": label})] - return observe -``` - -`_set` acts only on **transitions**, and logs at ERROR with the deployment identity in the line: - -```python -logger.error( - "Agent '%s' has stopped serving (group '%s', pod '%s'): %s", - namespace or ROOT_LABEL, self._group, self._pod, reason, -) -await self._pause_consumption(namespace) -``` - -Transitions rather than states, because an alert repeated every poll stops being read, and because -the client is already paused. - -**The consequence (C4).** `IOClientBase` gained `consumption_paused`, `pause_consumption()` and -`resume_consumption()`. `NATSClient` overrides them: pausing **drains** the subscriptions -- -already-queued messages reach their handler and acknowledge over the connection that delivered -them, where an unsubscribe would strand every one of them -- and resuming calls `_subscribe_all()`. -`_on_reconnected` returns early while paused, or the broker dropping and restoring a connection -would silently resubscribe a degraded agent, and C4 would hold only until the next network blip. - -Under Dapr there is nothing client-side to unsubscribe: the sidecar posts to a fixed path whatever -the application thinks. So `DaprEventing.publish` checks before dispatching: - -```python -if self._is_paused(namespace): - dispositions.append(DeliveryDisposition.NAK) - ... - continue -``` - -which the fan-out renders as `RETRY`, redelivering to a replica whose agent is up. `_is_paused` -reads that agent's own client rather than a process-wide register of degraded agents, so both -transports answer the same question from the same state. - -**Two departures from the spec, both because the obvious reading latches.** Spec C4 says a -degraded namespace's client is *closed*. A closed client reports itself unhealthy for ever, so the -agent could never be seen to recover and a transient Redis outage would take it off its topics -permanently -- the connection is therefore kept open, and only consumption stops. For the same -reason `NATSClient.health_check` reports a **paused client as healthy**, with a message saying so: -the pause is a consequence of degradation, not a cause of it, and the check that actually failed is -still in the payload. Reporting it as unhealthy would make the pause self-sustaining. - -**Detached tasks.** `sessions_bus.py` gained `_report_task_failure`, added to both its -`create_task` sites -- the SSE consumer, which had no callback at all, and `_spawn_tracked`, whose -callback only discarded the task from a set. Both `_on_retry_done` implementations now name the -agent. A bare `create_task` is now a guarded rule (below). - -**In-flight accounting.** `io/telemetry/inflight.py` is new: a per-agent count exported as an -observable gauge, registered lazily on first sight of an agent because it is reached from the -dispatch path and has no list of agents to iterate. `EventProcessingService.process_event` counts -around the chain: - -```python -with IN_FLIGHT.track(namespace): - handler_result = await self._chain_for(namespace).process(event, context) -``` - -Around the chain rather than at a transport edge, so one measurement covers NATS, Dapr and the REST -dispatch path, and so it means "work this agent is doing" rather than "messages its client has -taken". Its whole purpose is post-mortem: an OOM kill, a native crash and a blocked loop raise -nothing catchable, so the only attribution available is what was emitted before the process died. - -#### Spec sec. 9.1 -- a failing `on_startup` no longer ends the group - -The lifespan re-raised every component's startup failure. In a single-agent process that was -right; in a group it is the blast radius grouping is paid to remove. All eight startup loops now -go through one helper: - -```python -async def _start_component(self, kind: str, component: Any, label: str) -> None: - try: - await component.on_startup() - except Exception as exc: - namespace = namespace_of(component) - if not namespace or namespace in self._critical_namespaces: - logger.error("%s %s startup failed: %s", kind, label, exc, exc_info=True) - raise - logger.error("%s %s startup failed and agent '%s' is not critical, so the process starts without it: %s", ...) - await self._mark_agent_down(namespace, f"its {kind.lower()} '{label}' failed to start: {exc}") - return - logger.info("%s %s startup completed", kind, label) -``` - -A critical agent's failure still propagates, which aborts the lifespan **before the port is -bound**, so Kubernetes crash-loops with the traceback rather than reporting a replica that is -silently short a consumer. The root is always critical: there is no rest of the process without it. -A non-critical agent's failure calls `supervisor.mark_down`, which **latches** -- unlike a -health-driven transition, because the components of an agent whose `on_startup` raised can often -still answer a health check while the agent is unusable, so an observed-health signal would put it -back into service on the next poll. - -#### Dev-mode detection -- the blocked loop - -`io/telemetry/loop_watchdog.py` is new, and is two mechanisms that are never both on. -`configure_loop_debug` turns on asyncio's debug mode -- which names the exact callback and its -source -- and returns whether it did; development defaults to on, production to off, and -`event_loop_debug` overrides either. When it returns `False`, `LoopWatchdog` starts instead: - -```python -before = loop.time() -await asyncio.sleep(self._interval) -lag = loop.time() - before - self._interval -if lag >= self._threshold: - self._report(lag) -``` - -The overshoot is time the loop could not run anything. It cannot name the culprit -- by the time it -runs again the callback has returned -- so it names the agents that have work in flight, which is -the set the culprit is in. That is the honest shape, and it is still the difference between "the -pod was slow" and "one of these two agents blocked the loop for four seconds". Both are wired from -`AppBuilder._start_loop_diagnostics`, immediately after telemetry and before the actuator. - -The other two rows of the plan's dev-mode table are already covered or belong elsewhere: -module-level side effects are guarded by -`test_design_rules.py::TestLoggingIsConfiguredByTheApplication`, which found two real ones in step -9 part 2, and the non-idempotent-handler flag is `asbs validate`, which is P4's and phase 10's. - -#### The two event-accounting metrics this changelog assigned to phase 9 - -Both were open points that said, in so many words, "it belongs with the telemetry work in phase -9". Both are one instrument each, and both measure a failure whose only other trace is silence. - -**Dead-lettering was counted nowhere.** It was logged, so "how many messages did we give up on -today" could not be answered from metrics -- and a dead letter is the one delivery outcome with no -other trace in a running system: not a retry that eventually succeeds, not an error a caller sees. -`NATSClient._count_dead_letter` records `blueprint.events.dead_lettered` with `agent`, `reason` -(`deliveries-exhausted` or `terminal-failure`) and `kept`, the last of which is what tells a -deployment with no `nats_dead_letter_subject` that it is losing payloads. Counted **once**, where -the outcome is known -- counting on entry and again on a failed publish would report two dead -letters for one message -- and the counter itself is a `cached_property` for the same reason -`Component.tracer` is: an instrument created in `__init__` would be bound to the no-op global -meter, because a client is constructed by `build()` and the providers do not exist until the -lifespan. - -**Nothing observed a tick.** A tick is an ordinary event, so a `CronJob` that stopped publishing -looked like silence rather than a fault. `SchedulerBase.run_tick` is new and is what all three -tick paths now call -- the in-process timer once it has won its slot, `SchedulerTickHandler`, and -the manual REST trigger -- so the gauge means "this scheduler did its work" rather than "one -mechanism fired": - -```python -async def run_tick(self) -> None: - try: - await self.tick() - finally: - self._last_tick = time.time() -``` - -The `finally` is deliberate: a tick that raised still happened, and "being driven and failing" is -a different alert from "not being driven". `blueprint.scheduler.tick_age_seconds` reports the age, -with `-1` before the first tick so that "never ticked" and "ticked a long time ago" are different -values -- a pod that has just started has missed nothing. Registered in `on_startup`, after -telemetry, and reported in both modes: in-process mode is where a stopped timer is already visible -as a missing pod, event mode is where it is not. - -#### The guard, and the documents - -`test_design_rules.py::TestEveryDetachedTaskIsWatched` walks every framework module's AST for a -`create_task` / `ensure_future` whose result is assigned and then given an `add_done_callback` in -the same block; a spawn whose result is discarded outright can never be watched and fails too. -Verified by deleting the callback added to `sessions_bus.py` above and watching it fail with the -file and the line. `AGENTS.md` gained three rules with the failure each prevents: attribution -independent of the probe, a done-callback on every detached task, and *the probe decides where -traffic goes, never who is woken*. - -`docs/concepts/observability.md` was **rewritten against the code** rather than extended, on the -same grounds as the caching document in step 9 part 3. It documented an endpoint that has never -existed (`/health/detailed`), an import path that does not exist (`blueprint.agents.observability`), -`@traced("some.span.name")` when the arguments are *parameter names to stamp*, and health checkers -as bare callables when `HealthCheckerBase` is a class with an `async health_check() -> -ComponentHealth`. Adding a readiness-policy section beside all that would have been worse than -either. Two smaller fixes found the same way: `docs/guides/testing.md` asserted `{"status": -"alive"}` and called `/health/detailed`, so its snippet could never have passed; and -`AppBuilder.with_health_checker`'s *In a group* paragraph still said every check is ANDed, which -phase 9 makes false. - -`docs/guides/deployment.md` also documents `/health/detailed`, and is **not** fixed here: phase 10 -owns its rewrite, and it needs more than an endpoint correction. - -#### Configuration added - -| Key | Default | Meaning | -|---|---|---| -| `readiness_policy` | `"all"` | `all` / `critical` / `any`. Process scope. | -| `event_loop_debug` | on in development | asyncio debug mode, which names the blocking callback. | -| `event_loop_slow_callback_seconds` | `0.2` | Debug mode's threshold. | -| `event_loop_watchdog_enabled` | `true` | The production watchdog, used when debug mode is off. | -| `event_loop_watchdog_interval_seconds` | `1.0` | How often it measures. | -| `event_loop_block_threshold_seconds` | `1.0` | How much lag it reports. | - -#### Metrics added - -| Metric | Attributes | -|---|---| -| `blueprint.namespace.up` | `agent` | -| `blueprint.namespace.inflight` | `agent` | -| `blueprint.events.dead_lettered` | `agent`, `reason`, `kept` | -| `blueprint.scheduler.tick_age_seconds` | `scheduler`, `agent`, `mode` | - -All four are recorded on the owning agent's meter provider, so each arrives with that agent's -`service.name` resource as well as with its `agent` attribute. - -The spec writes the first of these as `blueprint_namespace_up{agent="..."}`, which is the -Prometheus rendering of the OpenTelemetry name `blueprint.namespace.up` -- the instrument is -named in OTel's dotted form and the exporter does the substitution. They are the same metric, -not a drift. - -Three of spec sec. 12's acceptance criteria are ticked by this phase: per-namespace -`service.name` with the root unchanged (C2), a degraded namespace under all of liveness / -readiness / gauge / consumers (C3, C4), and every path that stops a namespace serving emitting -both signals (C7). The detached-task criterion asks for "a test that fails a task in each -background path"; what landed is an AST guard over every framework module, which is broader in -coverage and weaker in behaviour -- it proves the callback is attached, not that it logs what it -should -- so that box is left unticked. - -#### Tests - -`test_readiness_policy.py` (24 cases), `test_namespace_supervisor.py` (13), -`test_inflight.py` (8), `test_loop_watchdog.py` (9) and -`app_builder/test_startup_failure_policy.py` (9, driven through the real lifespan against real -components) are new. `test_telemetry.py` gained a per-agent identity class, `test_health_cache.py` -a per-agent verdict class, `test_nats_client.py` a pause/resume class, `test_dapr_fanout.py` a -paused-agent class, `test_component.py` two span-attribution cases, `test_agent_group.py` a -critical-flag class, `test_actuator_api.py` a readiness-policy class and `test_scheduler.py` a -tick-freshness class. - -One existing case changed rather than being added to: `test_actuator_api.py`'s -`test_on_startup_uses_configured_interval` asserted `assert_called_once_with(check_interval_seconds=60)` -on `HealthCheckCache`, which now also takes a policy and a supervisor; it asserts on the one kwarg -it is about instead. - ---- - -### Phase 10, step 1 -- a scaffolded project is a group of one, in every environment - -Phase 10 adds no framework behaviour; it makes what phases 0-9 built usable by someone who has -only ever written a single-agent service. Its first step is the one everything else documents: -**what `asbs setup` produces**. A guide written against the old scaffold would document a shape -the framework no longer hosts, so the generator goes first and the guides follow it. - -The decision behind the whole step is the plan's: *every newly scaffolded agent has a real -namespace in every environment*. A development server at the root namespace would serve -`/api/orders/{id}` where production serves `/api/order/orders/{id}`, and would consume under a -different queue group -- so every local URL and every local integration test would differ from -the deployed one, in a way nothing reports. `namespace = ""` is therefore reserved for -pre-migration agents, and a new project is a group of one from the first `asbs dev`. - -#### `src/main.py` is a declaration, and nothing else - -`base_files/src/main.txt` lost its `Config(...)` block and its `app = ...build()`; what it now -carries is `imports` and `agent_declaration`. `MainPartGenerator._generate_agent_declaration` -(replacing `_generate_agents_and_app_initialization`) writes: - -```python -invoice_processor_agent = ( - AgentBuilder(runtime_name="invoice_processor_agent") - .with_model_from_config() - .with_system_prompt("invoice_processor_agent_system") -) - -agent = ( - AppBuilder() - .with_service(InvoiceProcessorService) - .with_agent(invoice_processor_agent, name="invoice_processor_agent") - .with_handler(InvoiceProcessorHandler) - .with_rest_api(InvoiceProcessorApi) -) -``` - -Four things changed in that, and each is load-bearing: - -- **`AppBuilder()` with no configuration, and no `build()`.** The module's product is the - builder. The host -- `python -m blueprint.agents.entrypoint` -- supplies the configuration and - builds it inside the namespace the deployment gave it. -- **Classes, not instances.** `with_service(InvoiceProcessorService)` rather than - `...Service()`. A component constructed on the `with_*` line is constructed before any - namespace exists and belongs to the root for ever, which is exactly why `AgentGroup` refuses an - already-built instance (spec sec. 4.2). The class form is constructed by `build()` inside the - agent's own scope and works in both shapes. -- **An unbuilt `AgentBuilder`, with no `config` and no `.build(...)`.** `AppBuilder.build()` - calls `agent.build(config.for_namespace())`, so the model, prompt and metrics come from - this agent's own configuration view (C5). The old template built the runtime at that line - against whichever `Config` was in scope -- in a group, a neighbour's. -- **The runtime's name moved to `with_agent(..., name=...)`** from `AgentBuilder.build(name=...)`. - It is the registry key the generated service resolves the runtime by - (`registry.get_agent("invoice_processor_agent")`), and `AppBuilder` qualifies it with the - agent's namespace, so two agents' runtimes cannot collide on it. - -The runtime stays a **module-level variable** rather than being inlined into `with_agent`, and -that is not style: `asbs create` rewrites the chain line by line, so a registration spanning -several lines would lose its continuation lines on the next `asbs create`. The chain is also -emitted in `sort_components` order (services, agents, handlers, REST APIs) so the first -`asbs create` does not reorder everything and make its own diff unreadable. - -One quiet fix came with it: the system prompt was named from the agent's *class* name -(`camel_to_snake(agent_name) + "_system"`) while the prompt file is written from its -`runtime_name`. They coincide for everything `asbs setup` generates and diverge for any other -generator config. It now reads `runtime_name` on both sides. - -#### `agents.toml` -- the map the image's command reads - -New `base_files/agents_toml.txt` and `AgentMapPartGenerator`, written to the project root: - -```toml -[agents.invoice_processor] -module = "src.main:agent" -``` - -Without it `python -m blueprint.agents.entrypoint` cannot resolve an agent name to code at all -- -`GroupConfig._read_agent_map` refuses to start -- so a generated project that lacked one could -not be run by its own Dockerfile. - -The agent's name is **derived and validated, never repaired**: `AgentMapPartGenerator.agent_namespace` -is the project name in snake case, passed through the framework's own `validate_namespace`. It -becomes the queue group, part of the durable name, the cache partition, the telemetry -`service.name` and the `/api/` prefix, so a name quietly rewritten to fit would be four -different names for one agent. A project name that does not survive the derivation (a leading -digit, say) fails the generator with the reason, at the one moment the name is still free to -change. That is also why this module is the generator's first import of `blueprint.agents`: the -alphabet has one definition, and a copy of the regex here would drift from it. - -#### The Dockerfile runs the entry point, and bakes no group - -`ENTRYPOINT ["uvicorn", "src.main:app", ...]` became -`ENTRYPOINT ["python", "-m", "blueprint.agents.entrypoint"]`, `agents.toml` is copied into the -image beside `settings.toml`, and a comment block above the entry point gives the two supported -ways to say which agents a process hosts (`-e BLUEPRINT_AGENTS=...`, or a mounted group file -plus `BLUEPRINT_GROUP`). **No group file is generated and none is copied in**: one image serves -every group, so which agents run is a Deployment edit rather than a rebuild. With neither -supplied the process stops before binding the port and says which is missing, which is what the -entry point was built to do. - -The Dockerfile is therefore no longer copied verbatim -- `CopyPartGenerator` gained an optional -`template_vars`, and the Dockerfile is rendered with the agent's real name. A placeholder in a -`docker run` line is a command that looks runnable and is not. - -The **dev stage** keeps hot reload, through a new -`entrypoint.create_group_app()`: `build_group_app` returns `(app, config)` because `main()` needs -the configuration to decide host and port, and uvicorn's `--factory` wants the application alone. -Reload needs an *import string* rather than a built object (which is why `run_app` never enables -it), so `uvicorn blueprint.agents.entrypoint:create_group_app --factory --reload` is the only -shape that reloads a group. A resolution failure propagates there rather than becoming an exit -status: the caller is a developer's terminal, not Kubernetes. The dev stage also sets -`ENV BLUEPRINT_AGENTS` -- a development default, in that stage only, where the project is -bind-mounted anyway. - -#### `asbs dev` runs the group, and `asbs create` writes the new shape - -`dev.py` picks its target from what the project contains. With an `agents.toml` it runs the -group factory under the agents' real namespaces; without one, but with a `src/main.py`, it serves -`src.main:app` exactly as before, because a project written before the agent map still builds its -own application and is deployed at the root namespace too -- the two still agree. With neither it -stops and names both files. - -Which agents: `--agents` if given, otherwise every agent in the map (the map is the complete list -of what the project holds; picking one of several would be the tool deciding which agent is the -interesting one). It sets `BLUEPRINT_AGENTS` in its own environment so the child inherits it -- -but **only when the environment names no group already**. A developer who has exported -`BLUEPRINT_GROUP` or `BLUEPRINT_AGENTS` is reproducing a particular deployment, and defaulting -over that would quietly serve something else. - -`asbs create` had to follow, and would otherwise have corrupted the file it edits. -`extract_component_registrations` located the chain's end by its `.build()` line, which a -declaration-only `main.py` does not have; the fallback for "no `.build()`" appends the -registration to the end of the file, and the re-sort drops every line between the builder and the -end. New `_closing_parenthesis_index` reads the `)` in the first column as the other way a chain -ends. `add_component_registration_to_main` now emits the class rather than `Class()`, for the -same reason the generator does. And `create_agent` wrote -`{name}: AgentRuntime = (AgentBuilder(config=config, ...).build(name=...))` anchored on a literal -`app = (` line: the anchor does not exist in the new file, so the declaration went silently -missing while the registration referring to it was still added. New `insert_before_declaration` -matches the *shape* -- an assignment opening a parenthesis, with `AppBuilder(` on the next line -- -so it finds `agent = (` and `app = (` alike, and `create_agent` now writes an unbuilt -`AgentBuilder` with the import added if it is absent. - -Three of `create_agent`'s printed next steps were false and are gone: it claimed to have added -`from src.agents. import build_` and told the reader to add the same import to -`src/agents/__init__.py`, but this command writes no module -- an agent runtime is a builder in -`main.py` plus two prompt files. `module_name` went with them. - -`asbs validate` lost its "src/main.py does not appear to use Config" warning, which is now -backwards: a `main.py` that mentions `Config` is the pre-declaration shape. The rest of -`validate`'s group gates belong to a later step of this phase. - -#### Tests - -`tests/unit/agent_generator/generator/test_generated_project.py` is new (14 cases) and is the -first test of the generator's *output*. It generates the project into a temporary directory and -**imports** the declaration -- parsing is not the claim; the claim is that the framework can host -it -- then asserts the builder is unbuilt, that importing it puts nothing in the shared registry, -that every component is declared as a class, that the runtime carries the name the generated -service resolves it by, that `agents.toml` names a legal namespace and a module that really -resolves to an `AppBuilder`, and that the production stage of the Dockerfile bakes no group and -contains no placeholder. `src` is removed from `sys.modules` around each import: the repository -has a directory of that name too. - -`tests/unit/agent_generator/cli/utils/test_main_py_editing.py` is new (9 cases), covering both -chain shapes through `extract_component_registrations`, `add_component_registration_to_main` and -`insert_before_declaration`. `test_dev.py` was rewritten for the two targets and the environment -precedence. Eight assertions in `test_naming_utils.py` and `test_component_ordering.py` pinned -the instance form and now pin the class form. - -2865 unit tests pass, zero failures. - ---- - -### Phase 10, step 2 -- `asbs validate` says what a project has not said - -There is deliberately **no `asbs migrate`**: `main.py` is the developer's own declaration, and a -tool that rewrites it either guesses at intent or fails on anything hand-edited. What replaces it -is a checklist plus a `validate` that names what is missing, which is what this step builds. - -`validate` keeps its three grades and gains a fourth block feeding them. **Issues** mean the -project will not start (exit 1), **warnings** mean it will start and something is missing, -**notices** are a decision the framework must not make for the author. New `_group_findings` -returns one list of each, and `run()` extends the existing three with them -- so the summary, the -exit status and the output format are unchanged. - -#### The agent map, checked where the answer is a line in a terminal - -`_read_agent_map` checks the same shape `GroupConfig._read_agent_map` refuses to start on: - -```python - module = entry.get("module") if isinstance(entry, dict) else None - if not module or not isinstance(module, str): - issues.append(f"Agent '{name}' in {AGENT_MAP_FILE} has no 'module'. ...") - continue - if ":" not in module: - issues.append(... 'does not say which attribute to read. Write it as "package.module:attribute"') - continue - try: - validate_namespace(name) - except ValueError as exc: - issues.append(f"Agent '{name}' in {AGENT_MAP_FILE} cannot be a namespace: {exc}") -``` - -The name goes through the framework's own `validate_namespace` rather than a copy of the rule, for -the reason the rule exists: a name repaired differently by the queue group, the durable, the cache -partition and the telemetry resource is four names for one agent, and `order-eu` is refused here -rather than in a crash-looping pod. - -`_declaration_issues` then resolves the module **against the filesystem, not by importing it**: -`_module_file` tries `.py` and `/__init__.py`, and a regex asserts the module assigns -the attribute the map names. - -```python - if not re.search(rf"^{re.escape(attribute)}\s*=", text, re.MULTILINE): - return [f"Agent '{name}' points at '{module}', but ... assigns no '{attribute}'. ..."] -``` - -Importing would run the module, which needs the project's dependencies installed and is a -different failure from the one being looked for. What that costs is precision -- this reads text -- -and what it buys is a `validate` that works in a checkout. - -A project with **no** `agents.toml` gets a warning, not an issue, and the warning is the migration -checklist: the three changes (declaration, Dockerfile command, map entry) and the sentence that -the name chosen becomes the queue group and the route prefix, so changing it after the first -deploy is a consumer migration. A project deployed on its own is not broken. - -#### Settings that would not survive being grouped - -`_settings_scope_warnings` reports the two things that go wrong when an agent moves in beside -another, neither of which raises: - -- Its `settings.toml` is read from the directory its **declaration** lives in, so one written - anywhere else is merged into no scope at all -- every key it reads would come from the group's - shared file. -- A process-scope key under one agent's scope is dropped with a warning at startup, because one - process binds one port, speaks one bus and loads one environment. The list is imported - (`PROCESS_SCOPE_KEYS`) rather than restated. - -Two exemptions, and both are about the same fact -- the process's own settings file is not a -fragment. A project hosted **alone** is the process, so nothing is reported for it at all; and an -agent declared at the project root in a group (`main:agent` rather than `src.main:agent`) has its -settings file *at* the process's, which `Config.merge_agent_settings` recognises and leaves at the -root: - -```python - fragment = source.parent / SETTINGS_FILE - if fragment == project_dir / SETTINGS_FILE: - return [] -``` - -That second one was found by asking what `main:agent` -- the shape the plan's own migration bullet -writes -- would do to the check. - -#### The scheduler gap, which is the reason this step existed - -From the changelog's open points: *"a mode and a transport with nothing publishing does not -[fail]. Validate is where it should be caught."* `_scheduler_findings` covers the three states of a -project with anything under `src/schedulers/`: - -- **No `scheduler_mode`** -> issue. It has no default because neither value is safe to inherit, so - `build()` fails; reported here only to report it earlier, with both values and what each costs. -- **`"event"`** -> a notice that no timer runs, the tick must arrive on - `.scheduler.` from an external `CronJob`, and **nothing in this project - generates one**. A notice rather than an issue because nothing here can tell whether the CronJob - exists -- the deployment knows, and it is outside this project. That is exactly why it is said: - a scheduler waiting for a tick nobody publishes reports itself healthy and never runs. - `event_bus` unset in that mode *is* an issue, because wiring raises at startup. -- **`"in_process"` with no `.with_cache(` in `main.py`** -> a notice that every replica will run - every tick. Each tick is claimed in the agent's own cache so one replica runs it; with no cache - to claim in, the claim is a no-op. - -The crontab needs nothing here: P5 already validates it at startup in event mode -(`validate_crontab`, called from `wire()`), which is where the declaration is. - -Two small shared helpers replaced duplicated code rather than adding any: `_load_settings` and -`_declares` are what `_idempotency_notice` and `_declares_idempotency` were doing inline, and -`_value_of` is `_declares` returning the value. All three treat a key set in *any* Dynaconf -environment as set -- which environment is in force is a runtime decision this command cannot make, -and the checks ask whether the author has decided something, not what today's value is. - -#### `docs/guides/cli-reference.md` - -Four sections were made wrong by step 1 and are corrected here rather than left to accumulate: the -generated `main.py` (it claimed `app = AppBuilder(Config()).build()`, which was never what the -generator wrote), `asbs validate`'s checks and output, `asbs dev`'s flags and what it serves, and -every manual-registration example -- classes rather than instances, no `build()`, and the -`AgentBuilder` left unbuilt with the reason. The auto-registration troubleshooting section now -describes the shape the CLI actually looks for. - -**The rest of that file still needs reading against the code.** It documents `validate` checks that -have never existed, and it is the last of the audit's fiction documents; it belongs with the guides -in step 3. - -#### Tests - -`tests/unit/agent_generator/cli/commands/test_validate_group_gates.py` is new (21 cases) and drives -`_group_findings` against real project trees in `tmp_path`: every malformed agent map, a package -declaration as well as a module one, both settings exemptions, the fragment naming exactly the -process-scope keys it declares and not the scoped ones, and each of the scheduler states. 2886 unit -tests pass, zero failures. - ---- - -### Phase 10, step 3 -- the guide, and three defects that writing it found - -`docs/guides/multi-agent-setup.md` is new: how to run several agents in one process, and how to -move an agent you already have into one. It is written to be followed without reading the spec, the -plan or this changelog, and everything it claims about identity was read out of the code rather -than out of the plan -- which is what turned up the defects below. - -**Its shape is the one the plan asked for**, and the split it insists on is the first thing in the -document: an agent **left standalone** and an agent **moved into a group** are affected differently, -and only one of them changes anything. Two tables, side by side, each with the eight identities that -matter -- registry keys, queue group, JetStream durable, routes, OpenAPI tag, telemetry -`service.name`, disk cache directory, Redis key prefix -- one column for the root namespace and one -for an agent named `order`. Every value in them was read from the code that derives it -(`NATSClient._resolve_queue_group`, `_durable_for`, `RestApiBase.route_prefix`, -`qualified_component_name`, `qualified_entry_name`, `CacheBackendFactory.storage_name` and -`TelemetryManager._configure_namespace`), because a migration guide nobody can check is worse than -none. - -The other sections: what `asbs setup` writes and why one image serves every group; the three-file -migration with the before/after `main.py` that removes two things and adds none; **the one decision -to get right first** -- the agent name, what it becomes in six places, and why `-` is excluded from -the alphabet (the durable separator, where `orders-eu`/`created` and `orders`/`eu-created` would -name one consumer); the two configuration files and their different lifetimes, with the five -`BLUEPRINT_*` variables; what regrouping does and does not change, and that agent code can observe -none of it (C6); and a closing section on readiness policy, C7 attribution, per-agent schedulers and -grouped Dapr's shared acknowledgement. - -**The cache is cold after the move**, and the guide says so plainly: the key layout changed twice -during this work, so an application upgrading with a persistent Redis cache or a mounted disk cache -does not find its old entries. Nothing errors. That was an open point asking to be written down -here. - -#### Three defects the writing found - -- **`asbs setup` wrote `secrets.toml` into the working directory, not the project.** - `SecretsPartGenerator(...).create_file()` was called with no argument, and `create_file`'s - `output_path` defaults to `""` -- so the file landed wherever `asbs setup` happened to be run - from, while the command's own next-steps text said one had been created for you. Fixed by passing - `out`, and `secrets.toml.example` is now written beside it: the first is git-ignored and the - second is committed, so a scaffold that writes only the ignored one leaves nothing in the - repository for the next person to fill in. `SecretsPartGenerator` gained an `example=True` - keyword, which is the whole of the difference. -- **`asbs create agent` wrote an effort level that was a model name.** - `openai_reasoning_effort = "gpt-5-mini"` in the generated `[default.runtimes..models]` - section -- a copy of `model_name` one line above. The scaffolder's own settings writer - (`settings_part_generator.py`) has always written `"low"`, so the two disagreed; now they do not. -- **`asbs windsurf` was an advertised command with no implementation.** The subparser was declared - in `cli/main.py`, `run()` had no branch for it, and there are no Windsurf resources to copy -- - `assistant_integrations/` holds one `CLAUDE.md`. So the command printed the top-level help and - exited 1, which is what "Generate Windsurf IDE integration files" in `--help` promised. The - subparser is deleted; git history keeps it if it is ever written. - -#### `docs/guides/cli-reference.md`, read against the code - -Step 2 corrected the four sections step 1 had invalidated. This is the rest of it, and most of it -was fiction before either step: - -- **`asbs setup`** listed `tests/`, `tests/unit/`, `tests/integration/` and `pyproject.toml` in the - generated structure. None of them is written. The real tree is listed instead -- including - `agents.toml`, `secrets.toml.example` and `.gitignore`, none of which appeared -- with a sentence - saying the packaging and test layout are the project's own. The three options - (`--output-dir`, `--overwrite`, `--verbose`) were undocumented. -- **`asbs create agent`** was the worst of it: it described a module `src/agents/_agent.py` - holding a `build__agent(config)` function, showed that function's source, and named the - prompt files and the settings section after the wrong string. The command writes **no module at - all** -- two prompt files, a settings section and a declaration in `main.py` -- and the runtime - name has `_agent` appended, so the files are `document_analyzer_agent_system.prompt` and the - section is `[default.runtimes.document_analyzer_agent]`. Verified by running the command. -- **`asbs create api`** claimed one models file, `src/models/_models.py`. It writes a models - *package*, `src/models//` with `dto.py`, `domain_models.py` and `mapper.py`, and the - generated API imports from `src.models..dto`. -- **`asbs create handler`** documented `--priority` as defaulting to `0`; it is `10`, and the code - sample said `priority=0` as well. -- **`--output-dir`** was undocumented on all four `create` commands. -- **`asbs claude`** documented `create` and `update` subcommands that do not exist. It takes an - optional project directory plus `--overwrite` and `--verbose`, and it *copies* the framework's own - resources -- it generates nothing from the project, and does not update when `asbs create` runs. - -What remains in that file is now either true or an example, and the two claims that were structural -rather than incidental -- that `asbs` generates project-specific Claude context, and that it -scaffolds a test layout -- are gone rather than softened. - -#### Tests - -Two cases in `test_generated_project.py`: the secrets file and its template land in the project, and -the ignore file covers the first without covering the second. 2890 unit tests pass, zero failures. - ---- - -### Phase 10, step 4 -- the deployment guide, rewritten against what now ships - -The plan's instruction was "rewritten here or removed", and the reason was that the guide shipped -while contradicting the feature: it opened with a banner saying **more than one replica is not -safe**, recommended `replicaCount: 1` and `autoscaling.enabled: false`, assumed one Deployment per -agent, documented `CMD uvicorn src.main:app`, and said nothing about schedulers or duplicate -consumption. Every one of those is now either false or superseded. - -**What the rewrite says instead**, and each of them is a thing P0-P5 or a phase actually built: - -- **A Deployment runs a group, not an agent.** One image, `agents.toml` baked in, the group injected - at container start; a group file as a ConfigMap mounted into every Deployment, each picking its - slice with `BLUEPRINT_GROUP`. Splitting an agent out is a second Deployment and an edit to the - file -- nothing is rebuilt and nothing broker-side changes. -- **More than one replica is safe**, and the guide says *why* rather than asserting it: one queue - group so a message reaches one replica; every delivery acked, naked or termed, with the outcome - table; and deduplication for handlers that are not naturally repeatable. The two keys that decide - whether scaling helps are named -- `nats_ack_wait` must exceed p99 handler duration, and - `nats_max_ack_pending` (default 16) is the in-flight limit **across every replica sharing the - consumer**, which is usually why pod count does not buy throughput. -- **The dedup TTL question is answered, not delegated.** Spec sec. 13 left the number to the - deployment; the guide gives the working: the redelivery window is - `nats_ack_wait * nats_max_deliver`, the defaults make that 1500 s, so `idempotency_ttl = 1800` - with headroom, and it rises whenever either factor does. Too short is the case dedup exists to - prevent; too long only costs cache entries. That closes an open point that had been waiting for - this document. -- **Dead letters accumulate and nothing drains them.** Also an open point, also written here: the - default subject is `.dead-letter`, the framework never reads it, and messages age out - with the stream's retention -- so a deployment that never drains it loses them silently. Decide who - reads it before going multi-replica; alert on `blueprint.events.dead_lettered`. -- **Schedulers**, which the old guide listed only as a reason not to scale. Both modes, with what - each needs: `in_process` claims each tick in the agent's own cache, so it needs `.with_cache()` or - every replica runs every tick; `event` starts no timer and takes the tick as an event on - `.scheduler.`, delivered through the queue group to exactly one replica. A worked - `CronJob` is included, with the warning that **nothing here generates it**, that its schedule must - be kept in step with the declared crontab by hand, and that a `CronJob` is at-least-once too. -- **Probes, corrected.** The old guide documented three endpoints including `/health/detailed`, - which has never existed; it also showed `{"status": "ready"}` for a payload that is - `status`/`components`/`policy`/`namespaces`. Both fixed, with the `readiness_policy` table, the - reason liveness is never agent-dependent, and the `failureThreshold` that outlasts the broker's - own startup. -- **Alerting on an agent rather than on the pod.** Grouping removes the pod restart that used to be - the alert, so `blueprint.namespace.up{agent}` is what to alert on -- including the case a probe - cannot see, an agent whose subscriptions have gone while the process stays healthy. -- **Sizing a group.** Memory is the sum of the agents; three failure classes take a whole group down - and raise no catchable exception, so the blast radius rather than the happy path should decide - group size; and the blocked-event-loop detection, with both key names and why the two mechanisms - are never both on. - -**Corrected rather than dropped.** *Writable cache directory* stays -- `cache_backend_factory.py` -and the generated Dockerfile both point at it by name -- but its closing claim was false: grouped -agents were said to be "isolated by key prefix, not by directory", which phase 8b step 5 reversed. -Each agent's cache is now a subdirectory (`/orders.default`), the mount count is still -one, and the section says so. It also gained the cold-cache warning for an upgrade. - -The `envvar_prefix` sections were accurate and are kept whole. What was wrong around them is the -**key shapes**: the old examples used `DYNACONF_APP__PORT`, `DYNACONF_LLM__PROVIDER` and -`DYNACONF_CACHE__TTL`, and only the last of those is nested. `app_port`, `log_level`, `event_bus`, -`nats_url`, `model_provider`, `idempotency_enabled`, `scheduler_mode` and `readiness_policy` are -flat; `cache.*` and `runtimes..*` are the sectioned ones. Getting it wrong is silent -- a -nested `app.port` that nothing reads -- so the rule is stated next to the example. - -**One thing is deliberately still a warning.** Everything above is covered by unit tests against -mocked transports and has not been exercised against a real broker. The guide says so at the top, -in place of the banner it replaces: queue-group distribution, redelivery after `nats_ack_wait`, -durable survival across reconnect and the shutdown drain are specified, implemented and unwatched. - -566 lines became 809. - -### The scaffolded settings file writes keys the framework reads - -Three open points, all the same defect wearing different names: the scaffolder writes a key in a -shape nothing looks up. Nothing fails -- the file says one thing, the process does another, and -there is no message in between. Each was probed against a real `Config` before and after. - -**`base_files/settings.txt`: two tables become four flat keys.** The template wrote - -```toml -[default.logging] -level = "DEBUG" -format = "json" - -[default.observability] -otel_enabled = false -token_metrics_enabled = true -``` - -and the framework reads `log_level`, `log_format`, `otel_enabled` and `token_metrics_enabled` from -the top level of the environment table. Probed: that file yields -`get_observability_config().otel_enabled == False` and `log_level == "INFO"` -- every value in both -tables inert, including the one a developer would edit first. They are now written flat, inside -`[default]` and above the `[default.runtimes.*]` tables the generator appends, with the reason in -the file: *these are flat keys, not sections*. - -Two values changed as a consequence, because making a key effective is choosing what it does: - -- **`log_format` is now `"text"`, not `"json"`.** A scaffolded project is run locally first, where - a JSON line per log record is unreadable. Nothing had ever run with `"json"`, so this is not a - behaviour change to anything that exists. -- **`log_level` stays `"DEBUG"`**, which is what the `debug = true` two lines above it already says. - -The comment also states what these two become in a group: `log_level` and `log_format` are in -`PROCESS_SCOPE_KEYS`, so if this project is later hosted as one agent, its own copies are reported -and ignored and the group's file decides. That is a warning the author will see, and it is better -read next to the keys than in a log line. - -**`config.py`: `token_metrics_enabled` was read by nothing at all.** Flattening the key exposed -that the getter never passed it -- `get_observability_config()` built an `ObservabilityConfig` -from four keys and left the fifth to the model's default of `True`: - -```python -return ObservabilityConfig( - otel_enabled=self.get("otel_enabled", False), - otel_endpoint=self.get("otel_endpoint"), - otel_service_name=self._resolve_service_name(), - token_metrics_enabled=self.get("token_metrics_enabled", True), - log_level=self.get("log_level", "INFO"), -) -``` - -The line in the middle is new. `MetricsRecorder` gates the per-call token and latency metrics on -`observability.otel_enabled and observability.token_metrics_enabled`, so until now the key could -be written in any shape, anywhere, and the metrics stayed on. - -**`create.py`: `[default.runtimes..models]` becomes `.model_settings`.** `Config.get_ai_config` -reads `runtimes..model_settings` and hands the dictionary to the provider client verbatim; -`OpenAIClient` builds `OpenAIResponsesModelSettings(**ai_config.model_settings)` out of it. A -`.models` table is read by nothing, so the reasoning-effort block `asbs create agent` adds was -inert -- while the generator's own settings writer (`settings_part_generator.py`) has always -written the right name, so the two halves of the scaffolder disagreed. - -**A fourth defect, found by the test written for the third.** `create_agent` derived the runtime -name *inside* the try block that reads `src/main.py`: - -```python -agent_name = snake_name if snake_name.lower().endswith("agent") else snake_name + "_agent" -``` - -`read_main_py` raises when there is no `src/main.py` -- which is exactly the project that then -needs the "register it by hand" instructions printed at the end, and those name `agent_name`. So -the fallback path ended in `UnboundLocalError`, after the prompts and the settings block had -already been written. The assignment moved above the `try`. - -Tests: `TestTheGeneratedSettingsAreRead` in `test_generated_project.py` loads the generated -`settings.toml` through a real `Config`, **flipping each value first** so that what is asserted is -that the key is live rather than that its value matches the framework's default, and checks that no -`logging` or `observability` table is written at all; new -`tests/unit/agent_generator/cli/commands/test_create_agent.py` asserts the runtime block through -`get_ai_config` rather than through the file text, and takes the no-`main.py` path; two cases added -to `TestGetObservabilityConfig`. - -**Found while writing them, not fixed here:** a scaffolded project cannot start. The generator -writes `secrets.toml`, and `DEFAULT_SETTINGS_FILES` -- what `entrypoint.py` loads -- names -`.secrets.toml`. With the scaffolded `model_provider = "vllm"`, `Config.validate()` then raises -`Missing API key for vLLM provider` on a project nobody has edited. Raised rather than fixed -because which of the two names is right is a decision: the generator says `secrets.toml` in three -places (the file, `secrets.toml.example`, `.gitignore` and `asbs validate`), Dynaconf's convention -says `.secrets.toml`, and changing the framework's list moves the ground under every existing -deployment. - -### The scaffolded project's secrets file is the one the framework loads - -`asbs setup` wrote **`secrets.toml`**; `DEFAULT_SETTINGS_FILES` -- the list `entrypoint.py` hands -to `Config`, and the image's contract with the project -- is `["settings.toml", ".secrets.toml"]`. -So the file was loaded by nothing, and since the scaffolded `model_provider = "vllm"` makes the -API key a *validated* requirement, `Config.validate()` raised on a project nobody had edited: - -``` -FAILED: ConfigError Missing API key for vLLM provider -``` - -**This is fallout from phase 10 step 1**, not an old defect. Before `5740195` the generated -`main.py` built its own configuration and named the file itself: - -```python -config = Config(settings_files=["settings.toml", "secrets.toml"], root_path=...) -``` - -Step 1 made `main.py` a pure declaration and moved the construction into the entry point, which -reads `DEFAULT_SETTINGS_FILES` -- and the undotted name was left behind in the generator. - -**The dot wins, and the generator moves.** The alternative is adding `secrets.toml` to -`DEFAULT_SETTINGS_FILES`, which changes what every existing deployment loads -- a project with a -stray `secrets.toml` on disk would start reading it -- to fix a file only the scaffolder writes. -`.secrets.toml` is also Dynaconf's own convention and the same shape as `.env`, and keeping the -framework's list untouched means no consumer of this package sees a change at all. - -- `secrets_part_generator.py` writes `.secrets.toml` and `.secrets.toml.example`. The example - keeps the real name plus a suffix, so there is one rule rather than two names to remember. -- The generated `.gitignore` ignores `**/.secrets.toml` -- named exactly, **not** `.secrets.*`, - which would also ignore the committed example. -- `asbs validate` reports an undotted file as the **rename it needs**, not as a file that is - missing: `Found secrets.toml, which nothing loads: the framework reads '.secrets.toml'`. That - is the only message an already-scaffolded project will get, and "missing" would send its author - to create a second file beside the one they already have. -- The generated `Dockerfile`'s mount example named the wrong path on both sides, so following it - produced a container whose secrets were invisible. It now mounts `/app/.secrets.toml`, and the - stale `DYNACONF_SETTINGS=/run/secrets/...` example -- which does nothing, because the entry - point passes `settings_files` explicitly -- is replaced by a Docker secret with a `target=` and - by the environment-variable form. -- `asbs setup`'s printed tree and next steps name the file it actually wrote. - -Documentation: every `secrets.toml` in `docs/` and in the docs shipped into a generated project -(`claude_docs/`, `assistant_integrations/`) is now `.secrets.toml` -- 33 occurrences across 16 -files. The `Config(settings_files=["settings.toml", "secrets.toml"])` snippets worked as written, -because they name the file explicitly, but they taught the name that the scaffolder no longer -writes. - -Tests: `test_the_project_configures_itself_from_the_files_the_image_reads` is the one that would -have caught this -- it builds a `Config` over the generated project using `DEFAULT_SETTINGS_FILES` -itself, so the project and the framework have to agree on the name or the test fails the way the -container did. The `.gitignore` assertion now reads the file as *patterns* rather than as text, -since a comment naming the example would otherwise pass for a rule about it. - -**Still not startable, for a second and unrelated reason.** With the secrets file found, the -scaffolded project gets as far as building its agent and fails: - -``` -TypeError: AgentRuntime.__init__() missing 1 required positional argument: 'name' -``` - -`AgentBuilder.build()` constructs `AgentRuntime(system_prompt=..., tools=..., **kwargs)` and never -passes a name, while `AppBuilder.with_agent(agent, name=...)` keeps `name` as the *declaration's* -name and applies it after construction. Every test that builds an `AgentBuilder` through -`AppBuilder` replaces `agent.build` with a lambda returning a `MagicMock`, so the real path has -never run. Its own change. - -### An agent runtime is constructed with a name, and registered like every other component - -The last thing standing between `asbs setup` and a process that serves. With the secrets file -found, a scaffolded project got as far as building its agent and stopped: - -``` -TypeError: AgentRuntime.__init__() missing 1 required positional argument: 'name' -``` - -**Nothing passed the name.** `AgentRuntime.__init__(self, name: str, **kwargs)` requires it -- -it is the registry key -- and `AgentBuilder.build()` constructed the runtime without one, while -`AppBuilder.with_agent(agent, name=...)` keeps that name on the *declaration* and assigns it -after construction (`_construct`: `instance.name = declaration.name`). So the call raised before -the assignment that would have supplied it. The builder has held the answer all along: - -```python -kwargs.setdefault("name", self._runtime_name) -runtime = AgentRuntime( - system_prompt=self._system_prompt, - tools=self._tools if self._tools else [], - **kwargs, -) -``` - -`runtime_name` is the key the runtime's own configuration is read under, so it is the right -default, and a differing declaration name still renames it afterwards. `setdefault` rather than a -positional argument, because `build(config, name=...)` is a legal call and a positional would -have turned it into a duplicate-argument `TypeError`. - -**The half that only becomes visible once the path runs: the runtime was the one component that -registered itself.** - -```python -Agent.__init__(self, name=name, **kwargs) -Component.__init__(self, should_register=False) -self._name = name -self.registry.add_component(name, self) -``` - -Every other component is registered by `Component.__init__` under -`qualified_component_name(namespace, base_name)`; this one opted out and registered under the -**bare** name. Two agents in a group whose runtimes shared a name therefore collided on one -registry key -- `Registry.add_component` raising "name is already taken" -- instead of becoming -`orders_assistant` and `billing_assistant`. `_base_name` was never set either, so it kept the -class-derived `agent_runtime` for every agent, which is what the readiness entry and the OpenAPI -tag render from. The four lines are now two: - -```python -Agent.__init__(self, name=name, **kwargs) -Component.__init__(self, name=name) -``` - -Nothing is lost at the root, where `qualified_component_name("", name) == name`, so a -single-agent application's registry key and every lookup of it are unchanged. Inside an agent -the bare name still resolves, because `Registry._lookup` qualifies on the way in -- a service -written as `self.registry.get_agent("assistant")` finds `orders_assistant`. - -**The rename had to be fixed with it, and this is the subtle one.** pydantic-ai's `Agent.name` is -backed by `self._name` -- the *same field* `Component` uses -- and its setter does nothing else -(read from `pydantic_ai`'s source: `name_ = self._override_name.get(); return name_.value if -name_ else self._name`). The combined setter called both: - -```python -Agent.name.fset(self, value) # self._name = value, unqualified -Component.name.fset(self, value) # update_component_name(self._name, qualified) -``` - -With the runtime registered under the bare name, the first line happened to write the value the -second line then found. Registered under a *qualified* name it no longer does: `Agent`'s setter -overwrites the field with the unqualified value, and `Component`'s setter then asks the registry -to rename a key that was never there -- `Component with name assistant does not exist`. The -setter is now `Component.name.fset` alone, which qualifies, moves the key, and writes the field -both getters read. - -**A docstring that said the opposite of the code.** `Component.name`'s setter claimed -`qualified_component_name` "is idempotent, so a caller that has already qualified the name is not -punished for it". That function's own docstring spends a paragraph on being **deliberately not** -idempotent. Corrected to say what it does: pass the bare name. - -Tests: - -- `TestAnAgentRuntimeIsNamedLikeEveryOtherComponent` in `test_name_uniqueness.py`, against a real - registry: qualification, two agents with one runtime name, the root's bare name, lookup by the - bare name from inside the agent, `base_name`, and the rename. -- Two cases in `TestBuild`, which had **no successful build at all** -- every existing case was an - error path, which is the other half of why this survived. -- `TestTheProjectTheEntryPointBuilds` in `test_generated_project.py`: the scaffolded project is - built through `entrypoint.build_group_app`, the function the container's command calls. It - assembles only -- the lifespan is where an agent reaches for its model -- and asserts the - agent's components all carry its namespace. - -**One existing test was passing because of the defect.** -`test_a_model_name_override_is_applied_at_build` asserted that `build()` raised *something* -(`pytest.raises(Exception)`, with a `# noqa: B017`) and then read the override out of the -wreckage. What it raised was this `TypeError`. It now stubs the rest of the build and asserts the -override alone. - -Every test that builds an `AgentBuilder` through `AppBuilder` replaces `agent.build` with a lambda -returning a `MagicMock` (`test_deferred_wiring.py`), which is the reason a defect on the path -every grouped agent takes left a green suite. - -**A scaffolded project now starts.** Probed end to end: generate, `create_group_app`, and the -lifespan runs to `Application startup completed`. `/health/ready` answers 503 until a real -`model_api_key` replaces the scaffolded placeholder -- the AI client's health check is what fails, -which is the intended behaviour rather than a remaining defect. - -### Isolation, step 1 -- the registry's root fallback stops reaching a neighbour - -The first of the four routes out of an agent, and the one that needed no argument at all: the -asking agent already knows its neighbours' names, because they are in the group, and the -qualifier is a documented `_`. - -```python -billing.registry.get_component("orders_ledger").record_id # -> "ORDERS-RECORD-4242" -``` - -`Registry._lookup` tries `_` and then the bare name. That fallback exists to -reach the **root** -- the shared transport client, the shared health cache -- but a neighbour's -registry key *is* a bare name in the same dictionary, so the fallback resolved it. The fix is to -check who owns what the fallback found: - -```python -found = self._components.get(name) -if found is not None and namespace and namespace_of(found) not in (ROOT_NAMESPACE, namespace): - return None -return found -``` - -Two owners pass. `ROOT_NAMESPACE` is the fallback's whole purpose. The asking namespace itself is -the documented already-qualified case -- a caller holding `orders_ledger` inside `orders` misses -on `orders_orders_ledger` and then finds it bare -- and a test now pins that, because it is what -the ownership check could most easily have cost. - -**It reads as absent, not refused.** `get_component` raises its ordinary -`Component with name orders_ledger does not exist in namespace 'billing' or at the root`. A -refusal naming the agent would confirm the neighbour exists, which is the same class of -disclosure in a smaller size -- so the neighbour is simply not there. - -`namespace` is falsy on the application registry and on a root component's view, so nothing the -root does changes: `build()`, the lifespan and the fan-out services all resolve exactly what they -resolved before. - -The `xfail(strict=True)` marker came off -`test_a_neighbours_qualified_name_is_not_a_key_this_agent_can_use`, which is what strict xfail is -for -- the fix turned the test red until the marker went. - -### Isolation, step 2 -- a view may name its own agent or the root, and no other - -The second route, and the one that took two tests to state because it opens two surfaces from one -line of code. An explicit ``namespace`` argument won unconditionally: - -```python -billing.registry.get_component("ledger", namespace="orders") # -> orders' instance -billing.registry.get_cache("default", namespace="orders").get("record") # -> orders' stored record -``` - -Every agent was one keyword away from its neighbours, and the second call is the one that -matters more: a component instance holds what is in flight, a cache holds what was *kept*. - -Both resolvers now refuse a view that names another agent. `_effective_namespace`: - -```python -if namespace is None: - return self._default_namespace -if self._default_namespace and namespace not in (self._default_namespace, ROOT_NAMESPACE): - raise RuntimeError(...) -return namespace -``` - -and `_cache_owner` carries the same check rather than sharing one -- **the two cannot be merged**, -because they mean different things by an omitted argument. For components it means *every* -namespace on the application registry, which is what `build()` and the lifespan iterate over; for -a cache it means *this agent*, never every agent, since no cache belongs to all of them. That is -why they were written as separate functions in the first place, and the duplicated check is the -price of keeping it that way. - -**Refused, not answered absent** -- the opposite of step 1, deliberately. There, a bare name that -happened to be a neighbour's key is a near miss, so the neighbour is reported as not existing. -Here the caller *named* another agent, which is a decision rather than a slip, and a silent -`None` would read as "that agent has nothing registered" -- itself a claim about the neighbour. - -**One existing test asserted the hole as intended behaviour.** -`test_an_explicit_namespace_overrides_the_view` did exactly what its name says, and it was the -only casualty of the whole isolation change. It is now -`test_an_explicit_namespace_naming_a_neighbour_is_refused`, with a second case for the two names -a view may still give -- its own and the root's. - -**Nothing else in the framework is caught by it**, which is what made the change safe to make. Every -component that passes a namespace passes `self.namespace` -- its own (`handler_chain.py:419,432`, -`nats.py:55,87`) -- and the three places that pass an arbitrary one are constructed **at the -root**: `EventProcessingService` and `DaprEventing` in `build()` outside the per-agent loop -(`app_builder.py:917,1127`), and `NamespaceSupervisor`, which is handed the application registry. -A root component's `registry` property returns the registry itself, not a view, so the guard -never fires for them. Two tests pin the calls that must keep working: a view naming its own -namespace, and a view naming the root. - -**Probed while here, and sound:** class-based resolution cannot reach a neighbour even though -`_all_of_type` deliberately ignores the namespace when gathering candidates. -`resolve_for_namespace` then filters strictly to `namespace` and then `ROOT_NAMESPACE`, so a -neighbour's instance is never a candidate it can return -- only an ambiguity *within* one level -raises. - -Two `xfail(strict=True)` markers came off. - -### Isolation, step 3 -- one declaration stops handing two agents the same object - -The only one of the four routes that needs no lookup at all: the object arrives in both -constructors. - -```python -declaration = AppBuilder().with_service(Ledger, holdings=[]) -AgentGroup("finance", {"orders": declaration, "billing": declaration}).assemble(config) -orders.holdings.append("ORDER-7") -billing.holdings # -> ['ORDER-7'] -``` - -One declaration serving several agents is the property the whole design rests on -- the same -`AppBuilder` named twice in the map, replayed once per namespace. Replay re-issues the recorded -call and `_construct` spreads the recorded `kwargs` into the constructor, and `**` copies the -*mapping* and not its values. Both agents therefore hold the same list. - -**Refused rather than copied.** `deepcopy` would close the hole silently and change what the -author wrote: a client or a connection pool passed deliberately would be duplicated per agent, -and an object holding a lock or a socket cannot be copied at all -- so the failure would arrive -later, somewhere else, and look like something different. `AgentGroup._refuse_state_shared_between_agents` -runs with the other refusals, at assembly, and names the agents, the call, the argument, its type -and the way out. - -**The line is code versus data**, in a new `SHARED_NESTED_PREFIXES`-style allowlist, -`SHAREABLE_TYPES`: `None`, `bool`, `int`, `float`, `complex`, `str`, `bytes`, `frozenset`, -`range`, `Enum`, and `type`, function, method and module -- tuples checked recursively. Two agents -built from one declaration *already* share the component class, and a class, a function or a -module is behaviour rather than something an agent can write into. A list, a dict, a set or an -ordinary instance is state. Arbitrary instances are refused even when their author considers them -frozen, because "frozen" is not decidable from the object and the cost of being wrong is silent -cross-agent sharing. - -**The fix needs no new API.** A declaration's target may be a zero-argument factory, called once -per agent, so `with_service(lambda: Ledger(holdings=[]))` gives each its own -- and a test pins -that. **Only a declaration used by more than one agent is checked**: a single-agent declaration -may carry anything, because there is nobody to share it with, which is *standalone is permissive, -the group has rules* applied to the one case that is genuinely about the group. - -### Isolation, step 4 -- a dotted configuration key stays inside its own agent - -The last route, and the one with compatibility consequences, which is why it went last. - -```python -config.for_namespace("billing").get("orders.record_id") # -> "ORDERS-RECORD-4242" -``` - -An agent's section is written `[default.]`, so its keys *are* `.` to anyone -who can resolve a dotted name -- and `_scoped_get` tries `.` and then falls back to -the raw key against the whole tree. The scope prefixes a key; it never confined it. - -The fallback is now restricted to the dotted prefixes the framework itself owns, by an -**allowlist** rather than a list of agent names: - -```python -SHARED_NESTED_PREFIXES = frozenset({"cache", "event_publishing", "runtimes", "runtime"}) -``` - -Those are the only four the framework reads a dotted key under -- `cache.*` (11 keys), -`event_publishing.*` (2), and `runtimes..*` with its legacy singular. Flat is the norm for -everything else. An allowlist fails closed: a new agent needs no entry, and a prefix this list has -never heard of is refused rather than resolved, which is the opposite of the default that created -the hole. - -**It raises, and does not quietly miss**, for the reason the deployment-identity check raises: a -`None` reads as "not configured" and sends the caller hunting for a setting, when what actually -happened is that the key names somewhere they cannot read. - -**Only a view is confined.** The loader is untouched -- the application owns its whole tree, and -`build()`, `resolved_settings` and the environment endpoint read across agents by design. A test -pins that too. - -**The compatibility note:** a project reading its own *custom* nested key through a scoped view -now gets an error naming the rule. Nothing in the framework or the examples does, and -`Config.settings` remains the escape hatch, but it is a behaviour change rather than a pure -tightening -- the only one of the four. - -### Publishing is its own decision, and its subjects are declared - -Closes the defect broker step 2 found. `_stream_subjects` covered what the client *subscribed* -to and nothing it published to, so a JetStream publish to a handler-result subject waited for a -`PubAck` no stream would send, timed out, and was swallowed by `publish_handler_event` as a -WARNING -- while a Core NATS subscriber still saw the message, because the publish did go out. -A live listener looked healthy; nothing was stored. - -**The root cause was one key doing two jobs.** `nats_use_jetstream` exists so *consumers* can be -durable, and `publish()` read the same flag: - -```python -if self._use_jetstream and client.jetstream(): - ack = await client.jetstream().publish(topic, event_data) -``` - -Nobody decided that publishing should be durable -- it followed from a key about something else. -Three changes, in that order: - -**`nats_publish_mode` splits the decision.** `"core"` or `"jetstream"`; unset, it follows -`nats_use_jetstream`, so no existing deployment changes. The shape this makes reachable is -durable consumption beside fire-and-forget publishing -- a status notification nothing needs to -persist, which under the old coupling paid for a stream round trip it had no use for. A test pins -that a client with `_use_jetstream` set no longer publishes through JetStream on that basis alone. - -**`_resolve_publish_subjects` declares what may be published.** Two sources, because there are two -ways an outbound subject is chosen: `event_publishing.topic_mapping`, which is how a -`HandlerResult` is routed and therefore where nearly every outbound subject is already written -down, and `nats_publish_subjects` for a caller that passes `topic=` to `publish_event` directly -and so never appears in the mapping. - -**A wildcard is refused**, by a new `validate_publish_subject` beside the existing -`validate_subject_segment` -- same rule, whole subject rather than one segment, so dots are legal -and `*`, `>` and whitespace are not. `orders.*` is a good thing to subscribe to and a meaningless -thing to publish to: NATS takes it literally, so the message lands on a subject spelled with an -asterisk and every subscriber to the pattern misses it. Nothing fails and nothing arrives, which -is why it is worth refusing at startup. - -`_stream_subjects` then adds the publishable subjects **when publishing is durable** -- and not -otherwise, because a Core publish stores nothing and widening the stream for it would claim -subjects the deployment has no reason to own. - -One existing test had set the old coupling by hand (`nats_client._use_jetstream = True` before -calling `publish`); it now sets the publish mode, and has a companion asserting the separation. - -### The scaffolded project ships tests, and a pyproject that makes its own next step possible - -`asbs setup` printed *"Install dependencies: pip install -e ."* and wrote no `pyproject.toml`, so -that command could not work; `asbs validate` then reported `tests/` and `pyproject.toml` missing -on a project the same tool had just produced. Both are now generated, and the loop closes: -`asbs setup` -> `pytest` (7 passed) -> `asbs validate` (passes). - -**Two tests, deliberately not more.** The scaffolded handler and service `raise -NotImplementedError` in the methods that matter -- that is where the author's logic goes -- so a -generated test of `handle_event` could only assert the stub is still a stub, and would fail the -moment it stopped being one. A test that must be deleted before the project can work teaches that -the suite is noise. What is generated is what is true on day one and stays true: - -- `tests/test_declaration.py` -- `src/main.py` declares an unbuilt `AppBuilder`, constructs - nothing on import, and passes classes rather than instances. Both mistakes it guards against - work fine standalone, which is why they are easy to make: `.build()` here takes the - configuration and namespace the host is supposed to decide, and `with_service(MyService())` - creates a component before any namespace exists, so it belongs to the root for ever. -- `tests/test_mapper.py` -- the generated mapper is the one piece of scaffolded code with real - logic in it, so a DTO round trip is a real assertion, and it is what says so when a field is - added to one side and forgotten on the other. - -`pyproject.toml` declares the framework and pytest, and carries `pythonpath = ["."]` -- without -it the first `pytest` in a new project fails on importing `src.main`, which is the same import -`agents.toml` names and the entry point performs. - -### `asbs` prints UTF-8 and writes ASCII - -Every command prints check marks, warning signs and box drawing; Python encodes stdout with the -locale encoding, which on Windows is cp1252, which has none of them. The first line of output -raised `UnicodeEncodeError` -- *mid-command*: `asbs create handler` died after writing the handler -and before registering it in `main.py`, leaving the project half-edited. - -`use_utf8`, called on `sys.stdout` and `sys.stderr` at the top of `main()`, reconfigures to UTF-8 -and falls back to `errors="replace"` for a stream that refuses an encoding change -- where a lost -glyph is a `?` in a log rather than an abandoned command. Reproduced before and after with -`PYTHONIOENCODING=cp1252`, and `setup`, `create handler` and `validate` all run clean on one now. - -The other half of the rule is held by a test rather than a docstring: -`TestEverythingWrittenIsAscii` generates a **pristine** project -- the module's shared one has -`__pycache__` written into it by the tests that import `src.main`, and a `.pyc` is binary -- and -asserts every file decodes as ASCII. - -### `asbs create` writes the imports the file it edits already uses - -The generator emits relative imports throughout (`from .handlers import OrderHandler` in -`main.py`, `from ..services import OrderService` in a component); `asbs create` appended absolute -ones (`from src.handlers.order_placed_handler import ...`). Both resolve, which is why nothing -failed and why it survived -- and two styles in one file is how a later move breaks exactly one of -them. Twelve occurrences, across the handler, service, API, models and scheduler paths, plus the -"add this by hand" messages that print them. The one inside a generated API module needed `..` -rather than `.`, being a package deeper. - -### The environment endpoint reports what it claims to report - -`env_status` had a branch whose comment said *"An agent-scoped actuator reports its own scope and -nothing else"* and whose code handed `_as_dict(settings)` -- the **unscoped** tree. A scoped -actuator would have served every agent's configuration over HTTP. Latent rather than live, since -`ActuatorApi` is constructed at the root, and wrong as written either way. - -The fix needed `Config.resolved_settings` to work on a view, which it refused outright. It now -**resolves a view's own scope and nothing else**: asked for another namespace it still raises, and -the flattening is delegated to the object that owns the tree, because stripping the other agents' -subsections needs the list of namespaces and a view deliberately has none (C6). `for_namespace` -gives each view a `_loader` reference for exactly that. - -**A second defect surfaced while testing it.** The flattening derived "the other agents" from -`self._views` -- the namespaces that had *asked* for a view. An agent whose components had not yet -read their configuration was therefore left in a neighbour's resolved settings, so whether it -leaked depended on construction order. It is now derived from the tree itself: every top-level -table that is not one of `SHARED_NESTED_PREFIXES` is an agent's section. - -`_as_dict` was that branch's only caller and is gone. The existing test -`test_an_agent_scoped_actuator_reports_only_its_own_scope` asserted `APP_NAME == "root-app"` while -`orders` overrides it -- the second test in this session found asserting the bug its name -disclaims. - -### Five examples declared an app_name the framework refuses - -Since P1 a root-namespace application's `app_name` *is* its NATS queue group, and the dead-letter -subject derives from it -- so a space in it is a subject the broker rejects and the application -raises at subscribe time. `examples/webhook_relay` was broken outright, being the only example on -`event_bus = "nats"`; the other four were the same illegal value waiting for somebody to switch -bus. All five renamed to hyphenated forms, and `tests/unit/examples` now holds every example's -`app_name` to `validate_subject_segment`, so the next one cannot ship. The prose and docstrings -keep the readable names -- nothing reads those. - -### Where the group file lives, and what stops it reaching the image - -Three documents said a container needs a group and none said how one gets there. The skills -stopped at "yes: an agent map and a group"; the migration guide changed the `Dockerfile` command -and copied the map in, which is the half that does not start a container; and every example used -the default filename, so `BLUEPRINT_GROUP_CONFIG` read as a name rather than the path it is. - -No `src/` change -- the variable already takes a path, and one file per group works today. What -was missing was saying so, and saying what it costs. - -- **`template_for_docker_ignore.txt`** excluded `deployment-groups.yaml` and `.yml` by exact - name. That is the whole guard, and a repository keeping `deployment/groups/*.yaml` matches - neither, so a wildcard copy bakes the group files into the layer -- an image that serves - whichever group was on disk when it was built, failing silently because it does start. The - template now states the rule and carries a commented example rather than an active line: an - uncommented path would be a convention the framework does not have, and would quietly do - nothing for anyone whose layout differs. Written by both scaffolds (`generator.py:363`, - `group_setup.py:79`). -- **`blueprint-multi-agent/SKILL.md`** gains *Supplying the group*: the two routes, the five - variables, the one-file-per-group layout, and why `BLUEPRINT_GROUP` is worth setting even - where a sole group makes it optional -- a name absent from the file is refused by name, where - an unnamed sole group is accepted whatever it contains, which is the difference between a - mounted wrong file failing and running. -- **`blueprint-deployment/SKILL.md`** gains *How the group reaches the container*: both - `docker run` shapes, and the group file's own reason for staying out of the build context, - which is not the `.secrets.toml` reason already there. -- **`multi-agent-setup.md`** gains *One file, or one file per group* -- blast radius against a - single reviewable diff -- and its `agents.toml` example is corrected: it still showed `module` - alone, having been written before `root` became required, so following it produced a startup - failure naming a key the example never mentions. -- **`multi-agent-migration.md`** step 2 regains the half lost when the guide was split and - rewritten: the entry point has to be told which agents to run, the map does not tell it, and a - container given neither exits before binding its port. - -No Kubernetes material was added. The framework ships no chart or manifest files and should not; -what it ships is the capabilities a cluster uses -- probes, `POD_NAME`, `scheduler_mode` -- which -`guides/deployment.md` already documents. - -### `asbs validate --group` disagreed with the runtime about where `root` points - -Reported from a consumer repository on 0.9.0a6, and reproduced both ways: `asbs validate --group` -at the top said "No agents.toml here" (the map was in `deploy/`), and `asbs validate --group -deploy` resolved `root = "agents/riskmanagement/risk_identifier"` to `deploy/agents/...` and called -it "not a directory". - -The part the report did not reach is the one that decided the fix: **the runtime accepts that -layout.** `_read_agent_map` resolves `agent_root = (root / declared_root)` where `root` is -`config.get_package_root()` -- the image root -- while `path`, the map itself, is separately -relocatable with `BLUEPRINT_AGENT_MAP`. `validate_group._agent_findings` resolved against the -directory holding the map. The two coincide exactly where `asbs setup --group` puts the map, which -is why 3147 tests passed over it. - -So the command was not missing a check. It was making a false statement -- "1 issue(s) would stop -this image starting" -- about an image that starts, and the reader's correct response to it is to -break a layout that worked. - -Four documents, the template and two docstrings all said `root` was relative to the map's own -directory, including `group_config.py`'s own error message for a missing `root` and -`GroupConfig.image_root`'s docstring, which describes the map's directory while the field is -assigned the package root. The code was consistent with none of them and correct anyway: the map -is a packaging manifest, and letting its location define the image root means moving one file -moves every agent. - -- **`validate_group.py`** now separates the two questions. `_agent_map_path(image_root, configured)` - returns where the map is -- `--agent-map`, else `BLUEPRINT_AGENT_MAP`, else `image_root/agents.toml`, - with relative values resolved against the image root exactly as the runtime resolves them -- - and `_findings(image_root, agent_map)` takes both. Agent roots keep resolving against - `image_root`, which is now the runtime's meaning rather than a coincidence. The absent-map issue - names the flag and the variable instead of asserting "this directory is not an image"; the header - prints the map's path when it is not beside the image root, so the reader can see which file was - read. -- **`main.py`** gains `--agent-map PATH` on the validate parser. -- **`group_config.py`** carries no behaviour change and three corrected descriptions: the missing- - `root` message now names the image root, gives its resolved value and says the map can be moved - without moving the agents; `AgentSpec.root` says what it resolves against; `GroupConfig.image_root` - says what it is and, explicitly, what it is not. -- **The template and four documents** say image root instead of "relative to this file". - `guides/cli/validate.md` documents `--agent-map` and why the directory argument and the map are - two arguments rather than one. - -`tests/unit/agent_generator/cli/commands/test_validate_group.py` is new -- `validate_group._findings` -had no test file at all, which is the second reason this shipped -- and holds the reported layout, -the scaffolded one, the flag's resolution rules and the still-refused root outside the image. -`test_group_config.py` gains the runtime half: a relocated map resolves roots against the image -root and leaves `image_root` at the process root. - -### The migration guide said three files and meant five, twice - -Five findings against `multi-agent-migration.md`, all traceable to `a9a8f3b` splitting it out of -`multi-agent-setup.md`: the new opening was written and the lifted one was kept. - -- **The intro appeared twice.** "Three files change, and nothing else", the link to *the one - decision to get right first*, and "a name you cannot cheaply change" were in the opening - paragraph and again, near-verbatim, after the `---`. The second copy is gone. -- **"Three files change, and nothing else" was not true of the guide's own steps.** Step 3 moves - process-wide keys into the image's `settings.toml` and may require unprefixing the agent's own. - It now says three files carry the migration and names the two that may need an edit, with the - distinction that matters to somebody estimating the work: those two already exist, and whether - they are touched depends on what the project already sets. -- **Map relocation was undocumented**, which is the gap the consumer report started from. New - *Keeping the map somewhere else*, and it separates two relocations that the report itself ran - together, because only one of them needs configuration: a map kept in `deploy/` **in the - repository** and copied to the image root (`COPY deploy/agents.toml ./`) needs nothing at - runtime and only `--agent-map` for the tooling, while a map that stays in a subdirectory - **inside the image** needs `BLUEPRINT_AGENT_MAP`. Both state the consequence that makes the - design legible: no `root` changes when the map moves, because roots resolve against the image - root -- a map in `deploy/` naming `root = "agents/order"` still means `/app/agents/order`. -- **Section 3 opened by contradicting itself.** It placed the map "at the top of the repository - that builds the image" flatly, three paragraphs above wording that hedged "normally the one - holding `agents.toml`". The rule -- not inside an agent, which `asbs validate --group` enforces - -- is now stated as the rule, and the top of the repository as the default that `asbs setup - --group` writes. -- **Step 4's `# at the top` comment** assumed the same thing, and now says "where the map is", - with the two-argument invocation below it. - -### A coherence sweep of the packaged docs against the code - -Mechanically clean: all 40 pages' links and anchors resolve, all 29 `asbs docs ` targets -referenced by the skills exist, the docs index matches what is on disk, and every `agents.toml` -example carries `root` bar the one below. Six substantive findings, four of them one cause -- -`676731d` changed what a standalone project *is*, and the pages written before it were not swept. - -- **Both scaffolded `Dockerfile`s probed `/health`, which is not a route.** Fixed separately as a - `fix(docker)`; see `CHANGELOG.md`. It is the only one of the six that was shipped behaviour - rather than prose, and the only one older than the standalone change. -- **`guides/cli/setup.md` documented an `agents.toml` that `asbs setup` does not write** -- with - an example missing the required `root`, for a file `asbs validate` now refuses outright. The - CLI prints the opposite in the same breath (`setup.py:199`). The page now states that no map is - written and why, and shows the entry to add to the *image's* map instead. -- **`guides/deployment.md`'s "The image" described the group image and called it the scaffolded - one.** There are two images now, and `blueprint-deployment/SKILL.md` already said so, so the - skill and the guide it points at disagreed. The section opens by naming both and says which one - it is about; the bullet about the entry point no longer claims a scaffolded `main.py` builds - nothing, which stopped being true when `create_app()` was added to it. -- **`setup.py`'s own output claimed the single-agent Dockerfile "writes a one-agent map".** It - serves `create_app` with uvicorn and writes no map -- the Dockerfile says so in a comment three - lines above the `ENTRYPOINT`. -- **`guides/troubleshooting.md`'s `dapr run` named `src.main:app`**, which a scaffolded project - has not defined since the split. -- **`asbs docs` was registered and undocumented.** `main.py:149` registers it, every skill tells - the reader to run it, and `cli-reference.md` listed neither it nor `setup --group`, - `validate --group` or `--agent-map`. All added. - -Noted, not fixed: `tests/unit/agent_generator/generator/test_generated_project.py` joins the list -of files `black --check` wants to reformat and `ruff format --check` considers clean. It is the -disagreement `CLAUDE.local.md` records, it predates this work (reproduced with the change -stashed), and it is not one formatter's to settle mid-change. - -### `asbs claude` had no migration skill, and announced its skills from a hand-kept list - -Reported by a colleague during PR review: the skills `asbs claude` installs did not include one -for migration. The command itself dropped nothing -- `ClaudeGenerator.generate()` copies -`claude_docs/skills/` wholesale and `pyproject.toml` packages `claude_docs/**/*` -- but no -migration skill had ever been written. `guides/multi-agent-migration.md` was reachable only as one -row of a table inside `blueprint-multi-agent`, so nothing surfaced as `/blueprint-migration`, and a -user asking Claude to migrate an agent depended on the multi-agent skill's description happening to -match. - -- **New skill `blueprint-migration`.** The five files the migration touches, the rules that break - it (instances instead of classes, the entry point without `BLUEPRINT_AGENTS`, a map inside the - agent, `[default.]` nesting twice), `asbs validate --group`, and the broker-identity change - that makes the move visible. It points at the guide for the diffs rather than repeating them. - `blueprint-multi-agent`'s description now routes migration to it, and the shipped `CLAUDE.md`'s - skill list names it. -- **The "Next steps" slash-command list was a hand-kept block** in `generate()`, so the next skill - added would have been copied and never announced. `skill_names()` and `agent_names()` now read - `claude_docs/` and the output is built from them. -- **Guarded** by `tests/unit/agent_generator/generator/test_claude_generator.py`: every skill's - frontmatter `name` matches its directory (a mismatch installs a skill under a slash command - nobody is told about), every skill is copied and announced, and the shipped `CLAUDE.md` names - every `blueprint-*` reference skill. The existing `test_docs.py` already checks that the new - skill's `asbs docs` targets exist. - -Checked and found complete: every guide under `docs/guides/` now has a skill; `concepts/`, -`components/` and `reference/` are reached through the existing skills rather than one each. - -### An environment override of a key the agent's file also sets was silently defeated - -Reported by a DevOps review of a first group deployment (their H3). `merge_agent_settings` -promises that an environment override (`DYNACONF___KEY`) is left alone and the agent's file -fills only the gaps. It did not keep that promise for any key the file also set: - -- `DYNACONF_RISK_IDENTIFIER__NATS_SUBSCRIPTIONS='["t.T1.risk.>"]'` against a file setting - `["risk.>", "t.*.risk.>"]` resolved to all three -- the lists were concatenated. -- `DYNACONF_RISK_IDENTIFIER__APP_NAME=FromEnv` resolved to the file's `RiskIdentifier`. -- The merge reported both keys as added. - -**Cause.** Dynaconf stores what it loads upper-cased (`NATS_SUBSCRIPTIONS`); the agent's file is -parsed with `tomllib` and keeps its lower case (`nats_subscriptions`). `Config._fill_missing` -compared keys verbatim, never saw the override, and wrote the fragment's key beside it. Dynaconf -then folded the two spellings into one key -- merging the lists, letting the later scalar win. The -existing precedence tests passed because they set the override through the group's -`settings.toml`, which does not take the upper-case path. - -**Fix.** `_fill_missing` matches keys case-insensitively, at every level, and keeps the spelling of -the key already present. Consequence for deployments: any key an agent's file sets can now be -overridden per agent from the environment, which the reviewer's interim of one process per tenant -depends on. - -Guarded by `TestEnvironmentOverrides` in `test_agent_settings_fragments.py`: a list, a scalar and -a nested key each keep the environment's value, and only the keys the environment left out are -reported. All four fail against the previous `_fill_missing`. - -### `nats_url` no longer defaults to localhost outside development - -From the same review (their M1). `NATSClient.connect()` read `nats_url` with a default of -`nats://localhost:4222`. In a pod that is almost always wrong, and the failure mode is the worst -available: the connection happens in the background retry loop, which retries every error forever, -so a pod the operator deployed without computed settings kept retrying against itself while the -process looked alive. - -The reviewer asked for the default to go and for startup to fail naming the key. Removing it -outright would have broken the case the default exists for -- a broker on a developer's machine -with nothing configured -- so, agreed with the user, the fallback survives in development only: - -- **`NATSClient.on_startup()`** now resolves the URL through `_resolve_nats_url()`. Set: used. - Unset and `app_environment` is `"development"`: `DEVELOPMENT_NATS_URL`, with a WARNING naming the - agent. Unset anywhere else: `ValueError` naming `nats_url`, the environment, and the variable to - set (following the configured `envvar_prefix`, or unprefixed when there is none). The client - phase of the lifespan runs before the eventing services, so under sec. 9.1 this aborts a - standalone, root or critical agent before the port is bound and marks a non-critical one down -- - the same path `_resolve_queue_group()` takes. -- **`connect()`** uses the resolved URL, and resolves it itself if nothing ran `on_startup()`, so a - lazily connected client cannot reach localhost by the back door either. -- **`AppBuilder._warn_if_development()`**, called once at the start of the lifespan, logs that the - process runs in development mode and is not suitable for production. - -**The residual gap, stated rather than hidden.** `app_environment` itself defaults to -`"development"`, and no scaffolded file sets anything else. A pod that sets neither key therefore -still connects to localhost -- but now under two WARNINGs, one saying the process is in -development mode and one naming the fallback. Closing that fully would mean changing the -default environment, which is a larger decision than this fix; the user chose the warning. - -Docs: `reference/configuration-keys.md` (`nats_url`, `app_environment`) and a new symptom plus a -localhost note in `guides/troubleshooting.md`. Guarded by `TestNATSClientUrl` in -`test_nats_client.py` and `test_development_warning.py`. - -### NATS connections can carry credentials, and a URL's credentials stop leaking - -From the same review (their M2). Under tenant-scoped auth the broker enforces per-account -permissions, and the only way to authenticate was credentials inside `nats_url` -- which makes the -URL a secret. Two places were not treating it as one: - -- **`connect()` logged it** at INFO in both "Connected to NATS server ..." lines. -- **`health_check()` put `connected_url` in its message**, and that is a `ParseResult` carrying - `user:password@`, so it reached `/health`. The existing tests mocked `connected_url` as a string, - which is why this was never seen; the mocks in `conftest.py` now use a `ParseResult`. - -`/status/env` was already safe: it masks keys by marker and strips userinfo from every URL. - -**What was built.** - -- **`redact_url()`**, module level in `nats_client.py`: returns the URL with its userinfo replaced - by `***`. Used by both call sites above. -- **`NATSClient._resolve_connect_options(nats_url)`**, called from `on_startup()` beside - `_resolve_nats_url()` (and from `connect()` if startup never ran), returns the keyword arguments - that `connect()` now splats into `nats.connect()`: `user`/`password`, `token`, - `user_credentials` (from `nats_creds_file`), `nkeys_seed_str` (from `nats_nkey_seed`) and - `inbox_prefix`. It refuses, at startup: one of `nats_user`/`nats_password` without the other; a - creds file that is not a file; more than one method, counting credentials in the URL as one; a - creds file or seed when the `nkeys` package is not installed; an inbox prefix with whitespace, a - wildcard or a trailing dot. It logs the method's *name* at DEBUG, never a value. -- Every key is read through the agent's view, so per-agent accounts work with - `[default.]` or `DYNACONF___NATS_CREDS_FILE` -- which, since the fix above, the - environment can now override. - -**`nkeys` is now a dependency**, declared as `nats-py[nkeys]` so nats-py chooses the compatible -version (0.2.1, which pulls in PyNaCl 1.6.2; both Apache-2.0). nats-py needs it for creds files and -nkey seeds; decided with the user over an optional extra, because creds files are the normal route -under decentralised auth, which is where tenant-scoped auth is heading. The startup check stays for -an environment installed without it. - -Installing it locally hit the known fatal uv `os error 5` (nkeys ships only as an sdist, and uv -cannot reopen the wheel it builds). Worked around by building the wheel with the system -interpreter's pip and installing that file with uv. `.venv` does not have it yet. - -Docs: five rows in `reference/configuration-keys.md` and a paragraph on choosing one method. -Guarded by `TestNATSClientAuthentication` and `TestRedactUrl` in `test_nats_client.py`. - -### Handlers see the subject a message was delivered on - -From the same review (their cross-repo change 1, the real fix for their W17 interim). The -tenant-auth plan wants the tenant taken from the subject the broker checked, not from the -publisher-controlled `event.tenantid`. `_subscribe_one()` passed its callback only the decoded -event, and the context `NatsEventing` built held `nats_topic` -- the *subscription*, e.g. -`t.*.risk.>`, which says nothing about which tenant matched. - -The reviewer offered two routes: the handler context, or a framework-set CloudEvent extension. -**The context was chosen** because a publisher cannot reach it by construction: the context is -built by the transport edge from transport facts, and nothing in the event is copied into it. An -extension would live in the payload the publisher writes, and the framework would have to -overwrite or strip it on every delivery -- a guarantee that holds only as long as no path forgets. - -**What changed.** - -- **`DeliveryCallback`**, new in `clients/client_base.py`: - `Callable[[CloudEvent[Any], str], Awaitable[None]]`. `ClientBase.subscribe()`'s abstract - signature fixed callbacks to one argument, so passing the subject from NATS alone would have - violated the contract (mypy caught it as an incompatible override). The contract itself is - widened instead, and `NATSClient`, `DaprClient`, `OpenAIClient` and `VLLMClient` use it. -- **`NATSClient._subscribe_one()`**: `await callback(cloud_event, msg.subject)`. -- **`NatsEventing._make_event_callback()`**: the callback takes the subject and builds - `{"nats_topic": topic, NATS_SUBJECT_CONTEXT_KEY: subject}`. The constant is public in - `io/api/eventing/nats.py`. -- **`DaprEventing._make_event_callback()`** accepts and ignores it: `DaprClient` stores its - callbacks and never calls them, because Dapr delivers over HTTP (verified: nothing indexes - `_topic_callbacks`). - -**Breaking**, and recorded as such: a one-argument callback handed to `NATSClient.subscribe()` -now fails on its first message. Handlers are unaffected. Eighteen test callbacks in -`test_nats_client.py` and two call sites in `test_nats.py` were written against the old shape and -were updated. - -**Not covered, and stated:** Dapr has no equivalent. The sidecar delivers to a fixed topic path, -and whether its envelope's `topic` is broker-checked depends on the pubsub component, not on this -framework. A handler under Dapr gets no `nats_subject` and must not assume one. - -Docs: *What the transport puts in `context`* in `components/event-handlers.md`, with the three -transport keys and the rule to derive tenants from the subject. Guarded by -`test_the_delivery_subject_reaches_the_callback` in `test_nats_client.py` and -`TestNatsEventingDeliverySubject` in `test_nats.py`, including an event that carries a spoofed -`nats_subject` extension and a different `tenantid`. - -### A latched-down agent consumed events anyway (C4) - -Found while verifying a report from the dynamic-subscriptions work: "a non-critical agent whose -`on_startup` raised is marked down, and nothing ever calls `clear_forced_down`". That report is -accurate, and is recorded under *Open points* below -- but checking it turned up a defect that -breaks the **committed** spec, not only the draft's D9. - -**Cause.** Sec. 9.1 marks a non-critical agent down when a component's `on_startup` raises, and -`NamespaceSupervisor._set` pauses its clients (C4). The lifespan starts clients before services, -so an agent whose *client* failed is paused before its `NatsEventing` has subscribed -- there is -nothing to drain, and `pause_consumption()` only sets the flag. `subscribe()` then started the -retry loop regardless, and neither `_start_with_retry()` nor `_connect_and_subscribe()` read the -flag. Reproduced: a client paused before `subscribe()` ended with one live subscription. The same -held for a pause arriving while the loop was still connecting (a later component of the same agent -failing). The pause was only enforced on reconnect and in `health_check()`. - -**Fix, in `NATSClient`.** - -- `subscribe()`: a paused client registers its topics, resolves its queue group and durables (so - configuration errors still surface at startup), and returns without starting the loop. -- `_start_retry_task()`, new: starts the loop unless one is running; used by `subscribe()` and by - `resume_consumption()`. -- `_connect_and_subscribe()`: paused after connecting -> subscribe nothing; `_start_with_retry()` - then leaves `subscriptions_ready` false. -- `resume_consumption()`: a client that never connected starts the loop instead of returning. - -Guarded by `TestAPauseBeforeSubscribing` in `test_nats_client.py`; two of its three cases fail -against the previous code. - -### A latched agent recovers, and readiness shows it - -Two findings, one subject: the open point recorded just above ("a startup-failure latch is never -released"), and #3 of an external defect list ("`mark_down` does not affect readiness"). Decided -with the user: retry, never terminate, and show the latch in `/health/ready`. Sec. 9.1 of the spec -is amended to say so. - -**#3, verified.** `HealthCheckCache._aggregate_by_agent` built each namespace's verdict from its -check results and never read the supervisor's latch. A latched agent -- paused, gauge at 0 -- -was therefore `UP` in `/health/ready` with `failing: []`, and `ReadinessPolicy` counted it as -serving. Separately, `_run_health_checks` returned before doing anything when no check was -registered, so neither the verdict nor `supervisor.observe()` ran -- and `observe()` is what -resumes an agent. - -- **`NamespaceReadiness.reason`**, new: why an agent is out of service when no check says so. -- **`NamespaceSupervisor.forced_down`**, new property: every latched namespace and its reason. -- **`_aggregate_by_agent`** reads it: a latched namespace is `False` in `namespace_status` (so - the policy counts it) and `DOWN` with its `reason` in the payload, whatever its checks say. -- **`_run_health_checks`** no longer returns early without checks. -- **`HealthCheckCache.refresh()`** and **`ActuatorApi.refresh_health()`**, new: recompute now. - Called when a latch is set or released, so the probe does not lag one interval behind. - -**Recovery.** - -- **`AppBuilder._start_component`**, non-critical branch: records `(kind, component, label)` in - `_failed_startups[namespace]`, in start order, before latching. -- **`_startup_retry_interval()`**: reads `startup_retry_interval_seconds` at the start of the - lifespan, refusing a non-positive or non-numeric value -- so a bad value fails startup rather - than surfacing on the day an agent first fails. -- **`_start_startup_recovery()`**, after every component has started: one task per latched agent. -- **`_recover_agent()`**: sleeps, then calls `on_startup` on the pending components in order, - stopping at the first that raises (a later one may depend on it). A failure logs a WARNING and - refreshes the latch's reason, so the payload shows the current error. When none are pending: - `clear_forced_down`, INFO, `refresh_health()` -- the refresh runs `observe()`, which resumes - consumption if the checks pass. Never terminates. -- **`_stop_startup_recovery()`**, first thing in shutdown: cancels and awaits the tasks. -- **`_on_recovery_done()`**: the done-callback the design rules require on every spawned task; it - logs a recovery that ended by raising, naming the task's agent. -- **`_mark_agent_down()`** now refreshes readiness after latching. -- `startup_retry_interval_seconds` joins `PROCESS_SCOPE_KEYS`. - -**Why never terminate**, pushing back on D9 of the dynamic-subscriptions draft: a deterministic -failure (a bad key) fails identically after a restart, and the restart crash-loops the pod and -every healthy agent in it -- the blast radius sec. 9.1 exists to remove. The ERROR on the -transition, the gauge, the payload's reason and a WARNING per attempt keep it visible. - -**Re-running `on_startup` was audited** for every framework component that implements it: each -raises before acquiring anything (configuration checks, then the client object) or guards a -repeated start (`SchedulerBase`, `SessionsBus`). User components are now required to be safe too; -`concepts/observability.md` and the spec say so. - -**Checked, not a defect:** the previous commit stops a paused client starting its retry loop, and a -health poll pauses an agent whose NATS check fails -- which looked like it could deadlock an agent -whose broker was down at startup. It cannot: `ClientHealthChecker` calls `client.connect()` before -every check, so polls connect the client independently of the loop, and the poll that finds it -connected resumes and subscribes it. - -Docs: `concepts/observability.md` (retry, the `reason`, the `on_startup` requirement), -`concepts/configuration.md` and `reference/configuration-keys.md` (the key). Guarded by -`TestReadinessShowsTheLatch` and `TestRecovery` in `test_startup_failure_policy.py`, through the -real lifespan: both readiness cases fail without the aggregation change, and four of the six -recovery cases fail with the recovery disabled (the other two assert that it never terminates and -that a bad interval is refused). - -### A handler result that fails to publish fails the delivery (#1) - -**Verified.** `EventPublishingService.publish_handler_event` wrapped everything in -`except Exception` and logged a WARNING; `EventProcessingService.process_event` then returned -normally, the NATS edge acked, and the handler's output was gone -- not redelivered, not -dead-lettered. The result event also got a fresh `uuid4()` per attempt, so even a redelivery -would have reached consumers under a new id. - -**A second defect behind the first, found while fixing it.** With `idempotency_enabled`, the -chain claims the event's marker before dispatch and releases it only when *dispatch* raises. -Publishing happens after `process()` returned, so a publish failure left the marker in place: -fixing only the swallow would have nak'd the event, and the redelivery would have been skipped as -a duplicate -- the output lost one step later. - -**What changed.** - -- **`publish_handler_event()`** no longer catches. A publish failure gets a note - (`exc.add_note`) naming the result's position, type, id and the source event, and propagates. - The two deliberate skips -- no topic mapping, a loop to the source topic -- still only warn. -- **`_result_event_id()`**, new: `uuid5(HANDLER_RESULT_ID_NAMESPACE, agent | source | id | - event_type | index)`, random only for a source event without an id. The agent is in the name - because two agents answering one event can share a `source` (a root-level `app_name`). -- **`publish_handler_event(..., index=)`**, new keyword, passed by `process_event` from - `enumerate(handler_results)`. -- **`process_event()`**: on a publish failure, `self._chain_for(namespace).release(event)`, then - re-raise. -- **`HandlerChain.release(event)`**, new public method over the existing `_release`, resolving - the policy itself; a no-op with dedup off. - -Decided with the user: the redelivery re-runs the handler, including an LLM call. That is the -at-least-once contract every other failure already has, and the deterministic id is what makes the -repeated publish safe downstream. - -Docs: *When publishing a result fails* in `concepts/event-processing.md`. Guarded by -`TestAFailedHandlerPublish` and `TestTheResultIdIsDerived` (`test_event_publishing_service.py`), -`TestAFailedResultPublish` (`test_event_processing_service.py`) and two `release` cases in -`test_handler_chain.py`; all nine behaviour cases fail against the previous code. - -### The declared transport mode is enforced (#4, decision D) - -**Verified.** `NATSClient.connect()` called `connection.jetstream()` inside a `try` and, if it -raised, logged a WARNING and set `_use_jetstream = False` -- falling back to Core NATS: no durable -consumers, and `_settle` returns early on Core NATS, so every handler failure was dropped. Worse, the -fallback almost never fired: `jetstream()` only builds a local context and asks the server nothing, -so an agent on a server without JetStream connected "successfully" and failed later, confusingly, -at stream provisioning. - -Decided with the user: `nats_use_jetstream` is the declaration, and a server that does not match it -fails the agent. Core declared on a JetStream-enabled server is fine -- Core NATS works everywhere. - -**What changed, in `nats_client.py`.** - -- **`JetStreamUnavailableError`**, new: the declared-JetStream-but-not-offered error. -- **`_require_jetstream()`**, new, called by `connect()` right after `jetstream()`: sends - `account_info()`. `NoRespondersError` and `APIError` (which covers `ServiceUnavailableError`) - are answers: the connection is closed, the error recorded in `_jetstream_mismatch`, reported - (below), and raised. A `nats.errors.TimeoutError` is not an answer and propagates as an ordinary, - retried connection failure. The fallback block is gone. -- **`_start_with_retry()`** re-raises `JetStreamUnavailableError` without retrying. -- **`health_check()`** reports the recorded mismatch as the unhealthy message. -- **`on_startup()`**: if a mismatch was recorded -- normally by the actuator's first health poll, - which connects every client before any component starts -- it probes again (`connect()`), so the - startup failure policy (sec. 9.1) applies and a retried startup sees a fixed server. It then marks - the client started. -- **`set_fatal_handler()`**, **`_report_fatal()`**: after startup, a mismatch is handed once to the - installed handler, as a watched task. - -**In `app_builder.py`:** every `NATSClient` gets `set_fatal_handler(self._on_transport_fatal)`. -**`_on_transport_fatal()`**, new: the root or a critical agent logs CRITICAL and sends SIGTERM to the -process (`signal.raise_signal`), so uvicorn runs the graceful shutdown and the other agents drain; a -non-critical agent is marked down and stays down, because this is a deployment error no retry fixes -(it is deliberately not added to the startup-recovery list). - -Docs: `nats_use_jetstream` in `reference/configuration-keys.md`, *JetStream delivery* in -`concepts/event-processing.md`, a new symptom in `guides/troubleshooting.md`. Guarded by -`TestTheDeclaredModeIsEnforced` (`test_nats_client.py`, 12 cases) and -`TestAFatalTransportErrorAfterStartup` (`test_startup_failure_policy.py`, 3 cases). One existing -test (`test_connect_enables_jetstream_when_configured`) needed `account_info` mocked as awaitable. - -### Event deduplication claims atomically (#6) - -**Verified.** `HandlerChain._claim` called `cache.exists()` and then `cache.set()`: two replicas -handed the same event between those calls both passed and both dispatched. The class docstring -admitted it. `CacheService.claim()` -- atomic set-if-absent, `add` on the disk cache and `SET NX` -on Redis, whose own docstring names event deduplication as a purpose -- was used only by the -scheduler. - -**Change:** `_claim` returns `self.registry.cache_service.claim(key, marker, namespace=..., ttl=...)`. -The release on failure (`_release` / `release`) is unchanged: it deletes the marker. The docstring -and `idempotency_enabled` in `reference/configuration-keys.md` now describe what the claim -guarantees: atomic across replicas that share a cache, per pod otherwise, and failing open on a cache -error. - -Guarded by `test_the_claim_is_one_atomic_call` in `test_handler_chain.py`, which simulates the race -window (`exists()` says absent, `claim()` says taken) and fails against the previous code. The stub -cache in that file gained `claim()`. - -### Structured output and deps types reach the agent (#2) - -**Verified.** `AgentBuilder.with_result_type()` and `with_deps_type()` set `_result_type` and -`_deps_type`; `build()` constructed `AgentRuntime(system_prompt=..., tools=..., **kwargs)` with -neither, and `_result_type` appeared only in a log line. `components/agents.md` documents -`result.output.`, which failed on the `str` the agent actually returned. The only working -route was `build(output_type=X)` through the kwargs check. - -**Change, in `build()`:** each configured type is put into the agent kwargs (`output_type`, -`deps_type`); a type given both ways raises `ValueError`. Unset now means `None` rather than the -`BaseModel` / `type(None)` placeholders, so pydantic-ai's defaults apply untouched. The build log -says `str (default)` when no result type was set. - -Guarded by `TestStructuredOutputReachesTheAgent` in `test_agent_builder.py`: three of its five -cases fail against the previous code (the other two check that unset changes nothing and that the -kwargs route still works). - -### One `AgentBuilder` declaration serves several agents (#10) - -**Verified by reproduction** (the list marked it unverified): `AgentGroup("pair", {"order": decl, -"billing": decl})` with `decl = AppBuilder().with_agent(AgentBuilder(...))` raised -`RuntimeError: AgentBuilder.build() has already been called` for the second agent, through the real -`build()`. `AgentGroup`'s own docstring calls one declaration serving several agents the group's -central property; no test covered it with an agent. - -**Change.** `AppBuilder._construct` builds from `copy.copy(declaration.target)` instead of the -recorded builder. The builder is a recipe; `build()` stores what it resolved on the builder, which -is why it is single-use, and a copy per agent keeps that guard for direct use while letting a group -build the recipe once per agent. The recorded builder stays unbuilt. `AgentBuilder.build()` now -hands `list(self._tools)` to the runtime, so copies of one builder do not give two agents one tool -list. - -Not a conflict with `_refuse_state_shared_between_agents`, which refuses *user* objects passed as -arguments rather than copying them: the builder is the framework's own declaration type, and copying -it is the framework's decision. - -Guarded by `TestOneAgentBuilderServesSeveralAgents` in `test_agent_group.py` (3 cases, all failing -against the previous code). - -### vLLM timeout and Dapr routing key (#7, #8) - -- **#7, verified.** `VLLMClient.create_model` passed `timeout=ai_config.max_tokens or 60` to - `AsyncOpenAI`. New key `model_timeout` (resolved per runtime like the other `model_*` keys) -> - `AIConfig.timeout` (`gt=0`, so a non-positive value is a validation error), and the vLLM client - uses it with a 60 s default (`DEFAULT_VLLM_TIMEOUT`). The OpenAI client passes it only when set, - so its SDK default is otherwise unchanged. -- **#8, checked against Dapr's publish API**, which reads metadata from query parameters prefixed - `metadata.`: `DaprClient.publish` put `metadata.routingKey` in the headers, where the sidecar - ignores it. It is now sent as `params`. Not exercised against a running sidecar here; Dapr is not - used by the project this round serves. - -Guarded by `TestTheRequestTimeout` (`test_vllm_client.py`) and the two routing-key cases in -`test_dapr_client.py`, which replace the two that asserted the header; four cases fail against the -previous code. - -### REST payload logging and request id (#12, #13) - -- **#12, verified.** `RestApiBase._process_resource` logged `extra={"payload": payload, ...}` at - INFO -- the full request body, against the org's PII rule and the repo's rule that sensitive data - is not logged at any level. Replaced by `payload_type`. -- **#13, verified end to end.** `_process_resource` creates a `request_id`, sets it as - `request.state.trace_id` (the problem-details `traceId`) and passes it in `context` through - `process_rest_request` to `process_event` -- which assigned `context["request_id"] = str(uuid4())` - unconditionally. It now keeps `context.get("request_id")` and only makes one when absent, so the - NATS and Dapr paths, which pass none, are unchanged. - -Guarded by `TestProcessResourceLogging` (`test_rest_api_base.py`) and `TestTheRequestIdIsKept` -(`test_event_processing_service.py`); one case of each fails against the previous code, the other -pins the part that was already right. - -### The sessions replay guard is bounded (#14) - -**Verified.** `SessionsJobHandler._seen` was a `set[UUID]` added to on every terminal outcome -(complete, fail, cancel) and never pruned: one UUID per finished job, for the life of the process. - -**Change.** New `RecentJobIds` in `sessions_job_handler.py`: an `OrderedDict` of id -> monotonic -time with `add()`, `__contains__` and `__len__`, evicting ids older than `ttl` and the oldest beyond -`max_entries`. `_seen` is one, sized by the class attributes `SEEN_TTL_SECONDS = 3600` and -`SEEN_MAX_ENTRIES = 10_000`. Its purpose is recognising a *redelivery*, which arrives in minutes; a -redelivery after the window is processed again, which the terminal call's retry already tolerates. -The handler's own tests use `in` and `.add()`, and pass unchanged. - -The finding also noted that this guard is per process and inconsistent with the chain's cache-based -dedup. That is true and deliberate here: the guard protects one handler instance against the -sessions bus redelivering to it; unifying it with the cache is a design change, not a fix. - -Guarded by `TestTheReplayGuardIsBounded` in `test_sessions_job_handler.py` (3 cases). - -### Generator and CLI (#11 and the low-priority generator findings) - -All verified before changing: - -- **`base_files/Dockerfile`** copied `pyproject.toml README.md`; no `README.md` is generated and the - generated `pyproject.toml` declares no readme. Now copies the manifest only. -- **`asbs validate`** warned an agent directory that it had no `agents.toml` and told it to add - one -- the opposite of `layout.py`, `asbs setup` and the migration guide, which all say the map - belongs to the image. `NO_AGENT_MAP_WARNING` became `NO_AGENT_MAP_NOTICE`: a notice that the map - belongs to the image, pointing at `asbs validate --group` and the migration guide. The test that - pinned the old advice (`test_a_project_without_one_is_told_the_three_changes`) now pins the new. -- **`asbs setup`** printed "this agent's routes are under /api/{namespace}"; a standalone - `create_app` builds at the root. It now names both. -- **`base_files/settings.txt`**: `scheduler_mode = "in_process"` was active, choosing the value the - framework deliberately has no default for; both values are now commented out. Its tick-topic - comment said `.scheduler...`; the code derives `.scheduler...` and falls back to - `app_name` only at the root. `model_base_url` named an internal host; now a placeholder. -- **`generator.py`** passed an `agent_namespace` template variable the Dockerfile has no token for - (removed, with its now unused import), and `load_config` called `sys.exit(1)` on an invalid - config; it raises `ValueError` after the `try`, and the CLI entry point still turns it into exit - status 1. -- **`assistant_integrations/CLAUDE.md`** was packaged (`pyproject.toml` package-data) and read by - nothing. Removed with its package-data entry. - -Guarded by `test_every_file_the_dockerfile_copies_is_generated` (checks every build-context -`COPY` source exists in a generated project), `TestTheGeneratedSettings` and -`TestAnInvalidGeneratorConfig` in `test_generated_project.py`, all four failing against the previous -templates and code; and the rewritten validate case in `test_validate_group_gates.py`. - -### Event counters on the agent's meter; the httpx instrumentation declared (metrics findings) - -- **Verified.** `event_handling_base.py` created `blueprint.events.unhandled` and - `blueprint.events.duplicate` at import on `metrics.get_meter(__name__)` -- the global provider -- - so every agent's count reported under the root's resource (C2), labelled `namespace` where every - other metric uses `agent`. **`EventHandlingBase._count(name, namespace, topic)`**, new: creates - the counter on `agent_meter(namespace, ...)` on first use -- the per-agent providers do not exist - at construction -- caches it per (counter, agent) on the instance, and labels - `{"agent": namespace or ROOT_LABEL, "topic": topic}`. The cache is keyed by agent, not topic, so - the no-per-topic-state guarantee holds; `test_many_distinct_topics_leave_no_state_behind` now - measures after the first event and asserts the cache stays at one entry. -- **Breaking for dashboards:** the label is now `agent`, and the root reports `` instead of - `""`. Listed in `CHANGELOG.md`'s Breaking section. -- **Verified.** `telemetry.py` imports `opentelemetry.instrumentation.httpx`, which `pyproject.toml` - did not declare; it is now declared (`>=0.59b0`, matching the other instrumentation). The unused - `opentelemetry-instrumentation-fastapi` was **not** removed: it belongs to trace propagation (#15), - deferred, and removing a dependency is not this change's call. - -Spec: the acceptance-criteria line for `blueprint.events.unhandled` says (agent, topic). -`concepts/observability.md` lists the two labels. Guarded by the converted accounting tests and the -new `test_it_is_counted_on_the_agents_own_meter` in `test_event_handling_base.py`. - -### Log once, and documentation that matches the code (low-priority findings) - -**Log or raise, not both** (the repo's logging rule), all verified: - -- `HandlerChain._dispatch` logged a failing handler at ERROR and re-raised; so did - `EventProcessingService.process_event`; and the transport edge -- NATS `message_handler`, Dapr - `_process_event` / fan-out, REST `_process_resource` (`logger.exception`) -- logged it again with - its disposition. Verified each edge logs before removing the two inner ones; one failure is now - one ERROR line. The chain still records the exception on the span. -- `DaprClient.publish` logged and re-raised a publish failure; now it only raises. -- `NATSClient.connect` logged "Failed to connect" and re-raised; the retry loop already logs each - attempt. Now it adds a note with the (redacted) URL and raises. -- `Config.validate` logged each of its three failure kinds before raising `ConfigError`. - -**Found while rewriting the health README:** `HealthCheckerBase`'s docstring example returned -`status="UP"` and documented `"UP"`/`"DOWN"`, while `HealthCheckCache` counts anything other than -`"healthy"` as failing -- so a check written from the example was permanently failing. This is -the "status vocabulary is split" finding, and `SessionsServiceHealthChecker` had the same bug. Both -now use `"healthy"`/`"unhealthy"`; the docstring says why `"UP"` is wrong for a component. - -**Docs and docstrings:** `io/api/actuators/health/README.md` (383 lines describing -`DaprPubSubHealthChecker`, `VLLMProviderHealthChecker` and `HealthCheckerRegistry`, none of which -exist) rewritten to the actual modules; `components/services.md` (the two abstract lifecycle -methods); `RestApiBase` module docstring (syntactically broken, called a non-existent -`get_registry()`); `EventHandlerBase` example (subclassed `EventHandler`, assigned `self.name`); -`namespace_of` (the namespace lives on `Component` now); "ComponentRegistry" in the registry's log -line and `component/__init__.py`. - -**Observed, not changed:** `TestClaimedTick::test_three_replicas_run_one_tick` failed once in a full -run (two replicas claimed one tick) and passed five times in a row alone. Nothing in this change -touches the scheduler or `DiskCacheService`; `DiskCacheService.claim` documents one non-atomic path -(taking over an expired claim), which is the likely cause. Recorded under *Open points*. - -Guarded by `test_a_handler_failure_is_raised_not_logged` (`test_handler_chain.py`) and the -vocabulary cases in `test_sessions_health.py`. - -### Dead code: only what is internal (decision E) - -Decided with the user: remove what is clearly internal, keep public API for now. - -**Removed:** `models/event_routing.py` (0 bytes, imported by nothing); `AnalysisRequest` and -`AnalysisResponse` in `models/result.py` -- an old example domain, not exported by -`blueprint.agents.models`, used by nothing but `AnalysisRequest`'s own validator tests, which went -with it (and the now unused `model_validator` import). `tests/unit/agents/models/TESTS.md` updated. - -**Kept, deliberately:** - -- Public API, per decision E: the unused registry getters, `EventPublishingService.publish_status_event`, - `get_topic_for_event_type`, `get_available_event_types`, `AgentRuntime.run_with_prompt(_sync)`, - `EventHandlerBase.get_published_event_types`, `Config.get_sessions_config`, and `RuntimeConfig` - (exported in `models.__all__`). -- `IOBase` -- empty, but the base of `RestApiBase` and `TelemetryManager`, so not dead. -- `DaprEventing._make_event_callback` -- proposed for removal, kept on inspection: `ClientBase.subscribe()` - requires the callbacks by contract, so removing them means changing that contract again. Its - docstring (since `75bc08e`) says they are never invoked. -- `NamespaceSupervisor.clear_forced_down` has a caller since the startup-recovery change. - -### A standalone agent's existing output is restored (audit against v0.8.1) - -**Why.** The user's rule for this feature: nothing built for namespaces may change what a -standalone agent (namespace `""`) emits. An audit of v0.8.1 against this branch, for namespace -`""`, found `ROOT_LABEL` (``) -- which the spec mandates only for the NATS connection name -(sec. 6) -- used as the general rendering of "no namespace", so lines a standalone agent had always -logged were reworded. The namespace-derived identifiers themselves are clean for the root (no -prefix on queue group, durable, routes, cache or registry names). - -**Scope, as decided:** outputs that existed in v0.8.1 and changed are restored where that needs no -change of behaviour; outputs that are new are left alone for now; nothing is worked around. - -**Restored, each as `if namespace: else: `:** - -- `AppBuilder`: "Caching disabled"; "Registered with cache_dir=... (locking=...)" for the - root's default cache; the no-event-bus WARNING; "Eventing component startup completed / failed" - and "Eventing component shutdown failed" (the root's endpoint is now passed unlabelled to - `_start_component`, which omits an empty label). -- `Registry`: "Registering cache service: "; `ValueError("No cache service registered")`; - `ValueError("Component with name already exists")`; the "does not exist" suffix only for a - named namespace. -- `HandlerChain`: "No handler processed event ''". -- `NatsEventing`: one "NatsEventing: auto-subscribed to topic ''" per topic, and - "NatsEventing: no auto-subscriptions configured". -- `NATSClient`: "Connected to NATS server (Core NATS) / with JetStream at " without the - connection name (`_log_connected`); "Subscribed to JetStream / Core NATS topic ''" without - durable, deliver group or queue group. The URL stays redacted -- that is a security fix. -- `HealthCheckCache`: "Health check failed for : "; `ActuatorApi`: "Readiness probe - failed: " when the process hosts no agents. -- `TelemetryManager`: "OpenTelemetry configured for service ''" when no group is set; - `Config`: "Loading configuration properties for environment: " with the default prefix. - -Guarded by `test_standalone_log_lines.py` (6 cases, including "building a standalone agent logs no -``") and `Standalone*` cases in the NATS client, NATS eventing, handler chain, registry, -health cache and actuator tests (10 cases); all 16 fail against the previous code. No existing test -had pinned any of these lines, which is how they changed unnoticed. - -**Kept, decided with the user:** the error lines removed by "log each failure once" stay removed -(each failure is logged once, at the transport edge), and so does the old "Failed to publish handler -event" WARNING, which belonged to acknowledging an event whose result was lost. The rule behind it -is now stated in `concepts/event-processing.md`: a delivery is acknowledged only when its work -- -the handler chain and publishing every result -- is complete; otherwise it is a nak or a dead -letter. `CLAUDE.md` now states that the repository is written entirely in English. - -**The NATS connection name, decided with the user.** v0.8.1 sent none; the feature named every -connection `f"{namespace}.{group}.{pod}"`, so a standalone agent appeared in `/connz` as -`..`. The user chose to keep a name -- more information is good -- but not to -imply a group where none exists. `NATSClient._resolve_connection_name` now returns the pod alone -when the namespace is `""` and `BLUEPRINT_GROUP` is unset, and `""` when the pod is unknown too; -`connect()` passes `name=self._connection_name or None`, so the latter sends no name, as v0.8.1 did. -The root of a grouped process keeps the full form, since its group exists. Spec sec. 6 is amended -with the exception; `reference/configuration-keys.md` and `guides/deployment.md` say so. The -connection-name tests were rewritten for the standalone case and one added for the namespaced form -with placeholders. - -**`/health/ready`, decided with the user:** "a `namespaces` key only in a group". `ReadinessResponse.policy` -and `.namespaces` are now `None` by default with `Field(exclude_if=lambda value: value is None)`, so -they are omitted from the JSON and from the 503 `detail` (`model_dump`) when unset -- without -`exclude_none` on the route, which would also drop the `null` values inside `components` that -v0.8.1 returned. `HealthCheckCache` sets both only when a namespace besides the root is supervised -(`self._grouped`). `policy` goes with `namespaces` under the same rule: it decides between agents, -and a standalone process has none. Nothing needed flattening: for a standalone agent the root's -entry repeats the top-level `status`, `failing` is derivable from `components`, `critical` is always -true, and `reason` is only ever set for a latched non-critical agent. Guarded by -`test_standalone_readiness.py` over HTTP through the real lifespan (keys, a `null` inside -`components` kept, and the group form). `guides/testing.md` had an example asserting -`namespaces[""]` for a single-agent application; corrected, and the two payload -descriptions say when the fields appear. - -**`/status/env`, same rule:** `EnvironmentStatus.namespaces` is `None` by default with `exclude_if`, -and `env_status` fills it only when the application's own configuration hosts namespaces -- so a -standalone agent's response has no `namespaces` key, where it had `{}`. `envvar_prefix` stays, as the -user decided: it is new and not about groups. The log line is the v0.8.1 one ("Returning environment -status for env ") for a standalone agent with the default prefix, keeps the override source -for a custom prefix, and adds the namespace count only in a group. Two env-status tests expected -`{}` and now expect no key; `test_standalone_readiness.py` checks the key is absent over HTTP. - -**JetStream consumer settings, decided with the user: "we do not change server defaults".** P1/P3 -made the framework set `ack_wait` 300 s, `max_ack_pending` 16 and `max_deliver` 5 on every consumer -it created; v0.8.1 left all three to the server. Now: - -- `ConsumerTuning.ack_wait`, `.max_ack_pending`, `.max_deliver` are `None` when not configured. - `_resolve_consumer_tuning` reads them through new `_read_optional_float` / `_read_optional_int` - and validates only configured values; the warning for an explicit `-1` stays. -- `_consumer_config` passes them as they are; nats-py leaves `max_deliver` and `max_ack_pending` out - and sends `ack_wait: 0`, which the server reads as its default (not verified against a broker). -- `_deliveries_exhausted` treats an unset `max_deliver` as unlimited -- the server's default -- so no - delivery is the last one and exhaustion never dead-letters. -- `_consumer_drift` ignores a setting the configuration leaves unset, so a consumer created by an - earlier alpha with 300 / 16 / 5 is not reported as drifting. - -Consequence, stated in the docs: unset `nats_max_deliver` means unlimited retries and no dead -letter on exhaustion, and dedup's TTL window needs it set. Docs: the three rows and the example in -`reference/configuration-keys.md`, `guides/deployment.md` (keys, the dedup window, scaling), the -disposition table in `concepts/event-processing.md`, and the class docstring. While there, fixed -`guides/deployment.md` still calling dedup "exists-then-set, not atomic", missed by the atomic-claim -change. Tests: the tuning-defaults test now expects `None`; new cases for a value left out of the -consumer, an unset `max_deliver` never exhausting, and an unset value not reported as drift; the -drift test sets `nats_ack_wait` so it still has a difference to report. - -**The durable consumer's creation and binding, decided with the user: keep it, reuse old durables, -deprecate them.** The user's worry was that the upgrade silently creates durables. It does not: -Core NATS stays the default, and under `nats_use_jetstream = true` v0.8.1 already created a -durable (`js.subscribe(topic, durable=f"{topic}-durable", manual_ack=True)`). What changed is the -form of a *new* durable -- a named `_DELIVER.` subject and a deliver group -- because the -v0.8.1 form can serve one replica: nats-py refuses a second `js.subscribe` to a push-bound consumer -without a deliver group ("consumer is already bound to a subscription"). An existing durable was -already left as it is by `_ensure_consumer`. New: when that existing consumer has no deliver group --- the pre-0.9 form -- a `DEPRECATED` WARNING names it, its deliver subject, and the fix (delete it -in a maintenance window), and the missing deliver group is no longer also reported as drift -(`_consumer_drift(..., ignore=("deliver_group",))`). - -Unit tests: `test_a_pre_09_consumer_is_still_used_as_it_is` (no `add_consumer`, bound with the -broker's own config) and `test_a_pre_09_consumer_is_announced_as_deprecated` (one deprecation, no -drift line); the drift test now uses a consumer with a *different* deliver group. Integration -tests, `tests/integration/test_upgrade_from_0_8.py`, against the compose broker: a consumer created -exactly as 0.8 left it is used as it is (no second consumer, same deliver subject, no deliver -group, and it delivers), is announced as deprecated, and the broker (or nats-py) refuses a dotted -durable name -- which is why the dotted-topic rename orphans nothing. Not run here: no Docker in -this environment. `CHANGELOG.md` gains a Deprecated section and "Upgrading a standalone agent from -0.8" (reused durables, the dotted name, `nats_durable_name` with several topics, the widened -stream, the Core NATS queue group). Two stale comments fixed on the way: `integration_config`'s -"the framework default is 300" and `docker-compose.yml`'s "falls back to Core NATS". - -**The scheduler's startup line, decided with the user: keep it, and call the behaviour breaking.** -The line changed with the behaviour (#73: a tick is claimed, one replica runs it), so the v0.8.1 -wording would now be wrong. But a deployment that expected every replica to run each tick in -parallel sees that change, so `CHANGELOG.md` [0.9.0] Breaking gains item 13 for it -- and item 14 -for the same shift on Core NATS, where the new queue group means one replica per event instead of -every replica. - -**`Config` behaviour, decided with the user.** `get("hostname" / "pod_name" / "blueprint_group")` -raised `ValueError` on every configuration since the deployment-identity blocklist (C6). The user -asked what those keys have to do with namespaces: nothing directly -- C6 keeps an agent from -knowing *where* it runs, and the pod keys were blocked alongside the group because the connection -name uses them. For a standalone agent there is no group to keep out of reach, and with the default -prefix the keys are ordinary settings anyway. `Config.get` now refuses them only on a view -(`self._is_view`), which is what agent code in a group holds; the process's own configuration -- -a standalone agent's and the framework's -- reads them as in v0.8.1. Tests: the refusal cases now go -through a view, plus a case that the process configuration reads all three and, with the prefix -disabled, a standalone agent reading the environment value. `reference/configuration-keys.md` -says so, and its connection-name paragraph, stale since the pod-only change, is corrected. -The two other `Config` changes stay, as breaking changes 15 and 16 in `CHANGELOG.md` [0.9.0]: -`Config()` no longer configures logging, and `Config.settings` is read-only. - -**Telemetry, decided with the user.** (1) "We *must* use the values in `OTEL_RESOURCE_ATTRIBUTES`: -without the variable, do your own thing; with it, follow it strictly." `Resource.create(attrs)` -lets explicit attributes override the environment, so the framework's `service.name`, -`deployment.group` and `service.instance.id` replaced declared values -- `service.name` already in -v0.8.1. New module function `_framework_attributes(service_name, group, pod)` in `telemetry.py`: -builds the framework's attributes, omits `deployment.group` without a group and -`service.instance.id` for an unknown pod (no placeholders), then drops every key that -`OTELResourceDetector().detect()` reports as declared (it reads `OTEL_RESOURCE_ATTRIBUTES` and -`OTEL_SERVICE_NAME`); `Resource.create` supplies those from the environment. Read as "declared keys -win, the framework fills the rest"; in a group a declared `service.name` therefore names every -agent alike, which the docs state. Found on the way: OpenTelemetry SDK 1.44 sets a random -`service.instance.id` itself when none is given, so an unknown pod now shows the SDK's default. -Tests: `TestTheDeploymentDeclaresTheResource` (4 cases; three fail against the previous code). -(2) The global `MeterProvider` stays; its side effect -- a project's own `metrics.get_meter()` -metrics are now exported -- is breaking change 17 in `CHANGELOG.md` [0.9.0]. - -**A breaking note that did not hold for standalone agents.** `CHANGELOG.md` [0.9.0] breaking change 6 -("Cache keys moved ... sees its old entries as absent") was written as if it applied to every -application. The audit found a standalone agent's default cache unchanged -- same directory, Redis -prefix and key hash. The item now says it applies to named caches and to agents in a group, and -that a standalone agent's default cache keeps its entries. - -**Not restored -- listed for the user, not worked around:** the Dapr degraded reason, the -behaviour changes of the transport fixes, `Config` behaviour changes, the scheduler line, and the -new outputs (metrics, span and resource attributes, new log lines). - -### A Dapr sidecar mock for demos and integration work - -`tests/integration/dapr_mock.py`, standard library only, run as a script -(`python tests/integration/dapr_mock.py`, port 3500). Written while preparing a demo of the -grouping feature: a Dapr agent without a sidecar reports readiness DOWN, and there was nothing -short of a real `daprd` to make it come up. It answers exactly what the framework calls -- -`GET /v1.0/healthz` (and `/outbound`) with 204, `POST /v1.0/publish//` with 204 and -a log line naming the topic and event id -- and 404s anything else with a warning, so an unmocked -call is visible rather than silently answered. - -Checked by hand against `examples/order_event_pipeline` served standalone: readiness 503 without -it, 200 five seconds after starting it (the client's `event_client_retry_delay`), and an -`order.created` event posted to `/events/orders` shows up in the mock's log as a publish to -`pubsub/orders-validated`. - -It does **not** close the Dapr item under *Infrastructure* in -`docs/plans/2026-09-11-broker-integration-tests.md`: it reads no `/dapr/subscribe` and delivers -nothing to `/events/{topic}`, which is the half that item is about. No test uses it yet; the -obvious next step is a fixture that serves it in-process on a free port and sets `dapr_url`. - -### The migration docs name absolute `src` imports as a pitfall - -Found preparing the same demo: both examples it uses import their own code absolutely -(`from src.services.order_service import OrderService`), and neither the `blueprint-migration` -skill nor `guides/multi-agent-migration.md` said that this breaks in a group. Standalone the -agent's directory is the working directory, so `src` is a top-level package; in a group the agent -is imported by its `module` path (`agents.<...>.src.main`) and nothing puts its directory on -`sys.path`. Confirmed by importing `examples/inventory_api` from a group layout: -`ModuleNotFoundError: No module named 'src'`. - -Worse than a crash for a non-critical agent: `AgentGroup._skip_or_raise` skips it, so the group -starts, logs one ERROR, and the agent's routes are missing from `/docs`. - -Documented as a pitfall rather than a migration step, because relative imports are already common -and a project that uses them has nothing to do. New *Common pitfalls* sections in both the guide -(before *After the move*) and the skill carry the cause, the log line, the fix and a `grep` that -finds the imports; the pattern was checked against both examples (6 hits). The scaffolder already -writes relative imports, so new agents are not affected. `getting-started.md` still shows the -absolute style and was left as it is -- both styles are legitimate for a standalone agent. - -### `asbs validate --group` warns about absolute `src` imports - -The mechanical half of the entry above. `_agent_findings` in -`agent_generator/cli/commands/validate_group.py` now calls `_absolute_src_import_warnings` for -each agent that has a `src/` of its own; it parses (`ast`, never imports) every `.py` under it and -reports `import src...` and level-0 `from src... import` with `file:line`, five listed and the rest -counted, plus the fix. - -Three decisions in it: - -- **A warning, not an issue.** Issues mean "would stop this image starting"; a non-critical agent - with the defect is skipped and the image starts, and a critical one fails loudly on its own. -- **Skipped when the agent's `src` is the image root's `src`.** There `src` really is the agent's - package -- a single agent at the image root, served as a group of one -- and reporting it would - be a false statement about a working image, the failure `test_validate_group.py`'s docstring - exists to prevent. (The `src/order/main.py` layout in `multi-agent-setup.md` is not reached at - all: its agents have no `src/` of their own.) -- **Parsed, not grepped**, so a docstring or comment naming an import is not reported, and - `srcutils` is not `src`. - -Checked against both demo agents in a group layout: 5 hits in `inventory_api`, 1 in -`order_event_pipeline`, the same six the documented `grep` finds. Tests: -`TestAbsoluteSrcImports` (6 cases) in `tests/unit/agent_generator/cli/commands/test_validate_group.py`. - -### A grouped agent's HTTP surface: plan and spec amendment (step 0) - -Found setting up a group in a consuming repository: the image's Swagger UI filed most operations -under "default" and scattered the rest as `.nats`, `.cache` among them. Two causes -in `AppBuilder._mount`: it rewrites only routes that already carry a tag (`and route.tags`), so a -developer's untagged route keeps `[]` and lands in "default"; and nothing orders the rewritten -tags, so Swagger UI lists them in first-seen order across agents. - -New plan `docs/plans/2026-09-28-grouped-http-surface.md` (steps 0-4) and a new spec sec. 11.2, -plus a sec. 10 row. What they decide: - -- **One Swagger group per agent**: every operation of a grouped agent carries exactly the tag - ``, replacing declared tags; none is untagged. -- **The second level is the path**: `nats`, `cache` and `scheduler` are reserved segments under - `/api//`. NATS publish moves to `/api//nats/events/{topic}` and the scheduler trigger - to `/api//scheduler//trigger`; cache already had its segment. -- **Standalone is untouched**: every rule applies to namespaced components only, so a - standalone agent keeps its declared tags, "default" included, and its paths. -- **A developer prefix is optional**, applies in both modes, and a grouped agent's route may - not start with a reserved segment -- refused at `build()`. - -Rejected, with reasons in the plan: ReDoc's `x-tagGroups` (invisible in Swagger UI, and ReDoc -hides every ungrouped tag once it is present) and ` / ` sub-tags (Swagger UI has one -tag level). The grouped path changes are breaking for grouped 0.9.0 deployments -- grouping -shipped in 0.9.0 -- and are release-noted under *Breaking* (step 4). This entry first said -nothing released was affected, which was wrong. - -### Reserved path segments for a grouped agent's framework endpoints (step 1) - -Step 1 of `docs/plans/2026-09-28-grouped-http-surface.md`. `RestApiBase` gains a class attribute -`group_segment` (default `""`), and `route_prefix` folds it in for a namespaced component only: -`/api//` when it is set, `/api/` otherwise, `""` at the root whatever it says. -`NatsEventing.group_segment = "nats"` and `SchedulerBase.group_segment = "scheduler"`, so in a -group the NATS publish endpoint moves from `/api//events/{topic}` to -`/api//nats/events/{topic}` and a scheduler's trigger from `/api///trigger` to -`/api//scheduler//trigger`. Cache endpoints already had `cache/` in their declared -paths and are unchanged. - -In `route_prefix` rather than in `_mount` because `DaprEventing.subscribe` also reads it to tell -the sidecar where to post; one property keeps the two agreeing. `DaprEventing` declares no segment -and is always root, so the subscription document is unchanged. Standalone paths do not move: -`/events/{topic}` and `/api//trigger` stay where they were, and the frozen compatibility -suite passes unedited. - -Tests in `tests/unit/agents/app_builder/test_route_namespacing.py`: segment follows the prefix, -a root component ignores it, the framework's segment values, grouped NATS and scheduler paths, -standalone NATS and scheduler paths unchanged; the two-agent NATS test now expects the `nats/` -paths. - -### One Swagger group per grouped agent (step 2) - -Step 2 of `docs/plans/2026-09-28-grouped-http-surface.md`, and the fix for what the consuming -repository saw. In `AppBuilder._mount` the rewrite of a namespaced component's routes was - -```python -if isinstance(route, APIRoute) and route.tags: - route.tags = [qualified_entry_name(component.namespace, str(tag)) for tag in route.tags] -``` - -and is now - -```python -if isinstance(route, APIRoute): - route.tags = [component.namespace] -``` - -Dropping `and route.tags` is what empties "default": an untagged route of a grouped agent used to -keep `[]`. Replacing instead of qualifying is what makes one group per agent: `orders.Items`, -`orders.nats`, `orders.cache` and `orders.Scheduler` were separate Swagger groups, interleaved with -other agents' in first-seen order, and a route with two tags sat in two of them. The second level -is now the path (step 1). Root components are not touched, so a standalone agent keeps its -declared tags and its untagged routes still fall under "default". - -`qualified_entry_name` is no longer imported by `app_builder.py`; it still renders readiness -entries (`health_base.py`), whose `orders.cache` keys are a payload contract and do not change. -Docstrings of `_mount`, `with_rest_api` and `qualified_entry_name`, and the comment in -`_build_rest_endpoints`, updated to match. - -Tests: `TestTags` in `tests/unit/agents/app_builder/test_route_namespacing.py` rewritten around a -new `ItemApi` with a tagged, an untagged and a two-tag route -- each gets exactly `[]` in a -group; the NATS endpoint joins its agent's group; no `/api//...` operation carries anything but -`[]` across two agents; standalone keeps `["Items"]`, `[]` and `["Items", "Reports"]`. The old -tests asserted `orders.orders`, which is the behaviour removed. - -### A developer path prefix, and reserved segments refused in a group (step 3) - -Step 3 of `docs/plans/2026-09-28-grouped-http-surface.md`. - -**`RestApiBase.path_prefix`** (class attribute, default `""`). Passed through a module-private -`_normalise_path_prefix` (surrounding slashes and whitespace ignored, `""` or `/segment` out -- -the form FastAPI asserts) into `APIRouter(prefix=...)` in `RestApiBase.__init__`. Being the -router's prefix, it is part of every route's path -- decorated or added to `self.router` directly --- and so applies in both modes: `path_prefix = "reports"` serves `/api/reports/daily` standalone -and `/api/orders/reports/daily` in a group. Independent of `group_segment`, which belongs to the -mount and applies in a group only. Optional, so no existing API moves. - -**`AppBuilder._refuse_reserved_segments`**, called from `_mount` for namespaced components only, -before the tag rewrite. For every route with a path it takes the path relative to `/api/` -(the component's `route_prefix` minus the agent prefix, plus the route path) and looks its first -segment up in the new module constant `_RESERVED_SEGMENTS` = `{"nats": NatsEventing, "cache": -CacheManagementApi, "scheduler": SchedulerBase}`. A hit on a component that is not an instance of -the owner raises `ValueError` naming the class, the agent, the route, the segment and the owner. -Keyed on the owner's class rather than on "declares a `group_segment`" because the cache API -reserves `cache` through its route paths and declares no segment, while a developer's scheduler -subclass is a legitimate owner of `scheduler`. Matched on the whole segment, so `/caches/...` is -fine. Not checked standalone: a route an existing agent serves at `/api/cache/...` keeps working. - -It raises out of `build()` and therefore out of `AgentGroup.assemble`, taking the image down -rather than one agent: the collision is deterministic and visible in the first local run -(`asbs dev` runs a group of one), and serving it would answer one of the two routes with the -other's handler, depending on mount order. `_RESERVED_SEGMENTS` is typed `dict[str, type]` since -mypy rejects abstract classes as `type[RestApiBase]`. - -Tests in `tests/unit/agents/app_builder/test_route_namespacing.py`: `TestPathPrefix` (standalone, -grouped, slashes, no prefix) and `TestReservedSegments` (a `/cache/...` route and a `nats` prefix -refused in a group, the same route served standalone, `caches` allowed, a developer's scheduler -allowed its segment). - -### Documentation for the grouped HTTP surface (step 4) - -Step 4 of `docs/plans/2026-09-28-grouped-http-surface.md`; documentation only, plus one docstring. - -- `guides/multi-agent-setup.md`: both identity tables gain the NATS publish and scheduler trigger - rows, and the OpenAPI tag row now reads `order` (grouped, whatever was declared) against - `Orders` (standalone, as declared). New section *An agent's Swagger group and its reserved - paths*. -- `guides/multi-agent-migration.md`: a pitfall *Routes under `/nats`, `/cache` or `/scheduler`* - with the error text, and a paragraph in *After the move* on the HTTP surface moving. -- `components/rest-apis.md`: the `tags` parameter row says it is replaced in a group; new section - *Path Prefix*. -- `components/schedulers.md`, `reference/api.md`, `claude_docs/CLAUDE.md`: the grouped trigger - path. `reference/api.md` also lists `path_prefix` and `group_segment` as class attributes, the - latter marked framework-internal. -- `blueprint-migration` skill: a reserved-segment pitfall and a *Swagger in a group* section. -- `AppBuilder.with_scheduler` docstring: the trigger moves under `/api//scheduler`. -- `CHANGELOG.md`: `path_prefix` under *Added*; the grouped path and tag changes under **Breaking**. - -**Correction.** The step 0 entry and the plan said the grouped path changes broke nothing released -because grouping was not on `main`. Grouping shipped in 0.9.0 (`CHANGELOG.md`, 2026-09-14), so a -grouped 0.9 deployment's clients of `/api//events/{topic}` and `/api///trigger` -do break. Found writing the `CHANGELOG.md` entry, which is why it is under *Breaking* and not -*Added*; both earlier statements are corrected in place. - -### Successful health probes are not access-logged - -Reported after `v0.9.0a13`: a grouped deployment logged every Kubernetes probe. Not a regression of -this feature -- the filter never worked -- but the group entrypoint is where it shows. - -- `HealthCheckFilter.filter` (`config/custom_logging.py`) searched uvicorn's access line for - `" 200 "` or `" 204 "`. uvicorn logs `'%s - "%s %s HTTP/%s" %d'`, so the status code ends the - line and the delimited search never matched. The filter now parses the line with `_ACCESS_LINE`, - matches the path (query string excluded) against `HEALTH_PROBE_PATHS` as a suffix, and drops 2xx - only. A line it cannot parse is kept. -- Why it shows in a group and not standalone: `suppress_noisy_loggers` (default `true`) sets - `uvicorn.access` to WARNING. Standalone, `uvicorn src.main:create_app --factory` configures - uvicorn's logging first and builds the app second, so that level stands and no access line is - written at all. The group entrypoint builds the app first and then calls `run_app` -> - `uvicorn.run(app, log_level=...)`, which sets `uvicorn.access` back to the uvicorn level -- and - from there only the filter stood between the probes and the log. -- `test_health_check_filter.py` built records in an invented format (`GET /health/live HTTP/1.1 - 200 0`) that the old check happened to match. The records are now built from uvicorn's format - string and arguments, and a test pins how they render. Checked against a real uvicorn server in - the entrypoint's order: before, `/health/live` 200 was logged; after, only the 503 probe and the - ordinary route are. - -### Deliveries run concurrently, and long runs send heartbeats - -Found while measuring an agent group against a real broker (2026-10-14): every agent handled -one NATS event per subscription and process at a time. nats-py gives a subscription one task, which -awaits the callback before taking the next message (`nats/aio/subscription.py`, `_wait_for_msgs`), -and `message_handler` ran the whole handler chain inside that callback. An agent spending minutes -per run waiting on a model therefore queued every further event behind it, on an idle event loop. -The behaviour dates from the first NATS commit (`c347f30`); P1/P3 contained it with -`max_ack_pending` 16, which `604bebb` made opt-in again. - -- `_subscribe_one.message_handler` now only acquires a slot of `_run_slots` (an - `asyncio.Semaphore` of `nats_max_concurrent_runs`, created in `subscribe()`), counts the delivery - in with `_enter_handler()`, and starts `_run_delivery` as a task kept in `_runs`. Waiting for the - slot inside the callback is the back-pressure: with every slot taken the subscription's task stops - taking messages. -- `_run_delivery` is the former callback body -- decode, dispatch, settle with the sec. 7.2 table -- - plus a heartbeat around the dispatch, stopped before settling. A cancelled run is not settled. -- `_run_finished` (done-callback) frees the slot and calls `_exit_handler()`, so `close()` and - `pause_consumption()` still wait for running deliveries through `_await_inflight`, although the - callback has already returned. It logs a run that failed outside its handler. -- `_start_heartbeat` / `_keep_alive` / `_heartbeat_finished`: JetStream only, `in_progress()` every - `ack_wait / 3` of the bound consumer's config (stored per topic in `_ack_waits` from - `_ensure_consumer`'s result; `SERVER_DEFAULT_ACK_WAIT` if the config has none) -- Part A sec. 4.1 - and 4.2 of `docs/specs/2026-09-24-handler-time-bounds.md`, without its `nats_heartbeat_enabled` - switch and hard limit. A failed heartbeat is logged at DEBUG and never fails the run. -- `nats_max_concurrent_runs` (`_resolve_max_concurrent_runs`): int >= 1, default 1, which keeps one - run at a time per agent. Per agent across all of its subscriptions, not per subscription. - -Tests: `_until_settled` in `test_nats_client.py` awaits the started run, because the callback -returns before the delivery is settled; the 26 tests that assert a settlement use it. Docs: -`reference/configuration-keys.md` (the key, `nats_max_ack_pending` sized against it, the example), -`concepts/event-processing.md`, `guides/deployment.md`; `CHANGELOG.md` Fixed and Added. - -Measured against `nats:2.10-alpine` with a group built by `AgentGroup.assemble`, 2 s handlers: -5 events of one subject 10.1 s -> 4.0 s at 4 runs; 6 events of two tenants' subjects on one -subscription 12.1 s -> 4.0 s; one 7 s run under `nats_ack_wait = 3` ran three times before (redelivered -while running, then queued behind itself) and once after. - -Not changed: spec sec. 5.2 still lists 300 s / 16 as the defaults of `nats_ack_wait` / -`nats_max_ack_pending`, which `604bebb` made server defaults; and handler-time-bounds sec. 4.5 -assumes running handlers are bounded by `nats_max_ack_pending`, while they were bounded by one per -subscription and now by `nats_max_concurrent_runs`. Both are for the spec owner. - -### Links and bindings inside `NATSClient`; one run per subscription restored (named connections, step 1) - -Step 1 of `docs/plans/2026-10-14-named-connections.md`: the client's per-connection state moves into -two objects, so later steps can give an agent several connections without reshaping the delivery -path. No behaviour change, with one deliberate addition and one correction. - -- `_Link` (module-private dataclass): the broker connection -- URL, connect options, connection - name, `nats.Client`, JetStream context, JetStream mismatch. `_Binding`: what one agent consumes - over one link -- topic callbacks, durables, consumer tuning, subscriptions, readiness flag, run - slots, running tasks, per-topic `ack_wait`, in-flight count and idle event, with `enter_run()` / - `exit_run()` / `slots_for(topic)`. The client holds one of each, `_link` and `_binding`. -- The delivery path takes the binding the message arrived on: `_subscribe_one(..., binding=None)` - captures it in `message_handler`; `_run_delivery`, `_start_heartbeat`, `_run_finished`, `_settle`, - `_deliveries_exhausted`, `_dead_letter`, `_drain_subscriptions` and `_await_inflight` act on it - (default: the client's own). A dead letter is published on the binding's own link. -- Transitional: the client's former private names (`_nats_client`, `_subscriptions`, `_tuning`, - ...) are properties over the default link and binding, because 237 unit-test lines reach them by - name. They go when the tests address links and bindings directly (plan step 3). -- **Addition:** `nats_heartbeat_enabled` (bool, default `true`, `_resolve_heartbeat_enabled`); - `_start_heartbeat` returns `None` when it is off. A non-boolean is refused: `"false"` as a string - would read as true. -- **Correction of the previous entry:** `19c4c48` gave an agent one semaphore across all of its - subscriptions, default 1 -- so an agent with two subscriptions, which ran one delivery per - subscription at once before, ran one in total. Measured: two topics, 3 events each, 6.0 s before, - 12.1 s after `19c4c48`, 6.0 s now. Unset, `nats_max_concurrent_runs` now keeps one slot per - subscription (`_Binding.subscription_slots`); set, the subscriptions share K (`run_slots`). - -Tests: `TestConcurrentRuns` (K at once, one at a time unset, one per subscription unset, shared when -set, slot freed after a failure, values below 1 refused) and `TestHeartbeat` (progress reported and -stopped before the ack, none for a short run, switched off, a string refused) -- the concurrency and -heartbeat of `19c4c48` had no unit test of their own. Docs: the key rows, event processing, -deployment guide; `CHANGELOG.md`. - -Acceptance against `nats:2.10-alpine` in WSL, same probe as `19c4c48`: one topic 5 events 10.1 s, -two tenants on one subscription 12.1 s, two topics 6.0 s / 2 at once, two agents 6.0 s / 2 at once, -`nats_max_concurrent_runs = 4` 4.0 s / 4 at once, a 7 s run under a 3 s `ack_wait` once. Integration -suite: 41 passed, 2 failed -- `test_the_broker_counts_it_as_a_redelivery` and -`test_two_processes_share_cache`, both failing identically without these changes (control run). - -### Binding mode: consuming through a consumer the deployment defines (named connections, step 2) - -Step 2 of `docs/plans/2026-10-14-named-connections.md`. Not reachable from configuration yet -- the -connection source that creates such bindings is step 3. - -- New module `clients/io/nats_connections.py`, `JetStreamBinding` (frozen dataclass): the declared - subjects a connection serves, `subject_prefix`, stream, durable, deliver subject, deliver group, - the contract values `ack_wait` and `max_deliver`, optional `max_ack_pending`, `deliver_policy`, - `manage_consumer`, optional `dead_letter_subject`. `filter_subjects` = prefix + declared subject; - `consumer_config()` builds the consumer from those values verbatim; `local_subject()` strips the - prefix; `topic_for()` finds the declared subject covering a delivery. -- `_Binding.jetstream`: set, `_subscribe_all` calls `_bind` instead of provisioning a stream and - subscribing per topic. `_bind` makes **one plain subscription** on the deliver subject in the - deliver group -- as the first consumer's own pool does -- so receiving needs no JetStream - API request; with `manage_consumer` unset it sends none at all. With it set, - `_ensure_bound_consumer` checks the stream exists (missing: `JetStreamBindingError`, never created) - and creates or updates the consumer, deleting and recreating it when the broker refuses the - update (WARNING: its unacknowledged messages are lost) -- the deployment's behaviour today, and - unlike the agent's own consumers, which are never rewritten. -- `_message_handler(binding, slot_key, topic, callback)` replaces the closure in `_subscribe_one` - and serves both modes; in binding mode the topic is found per delivery (`_bound_topic`), and a - delivery no declared subject covers is termed without running. `_run_delivery` hands the handler - the subject without the prefix (plan D10). `_settles(binding)` makes a binding-mode delivery - settle and heartbeat whatever `nats_use_jetstream` says; the heartbeat interval comes from the - binding's `ack_wait`, exhaustion from its `max_deliver`, the dead-letter subject from the binding - (none: term + log, plan D6), published on the binding's own link. - -Tests: `test_nats_binding_mode.py`, 15 cases (the binding's values, no JetStream request when -unmanaged, create / recreate / missing stream when managed, prefix stripped, uncovered delivery -termed, heartbeat interval, nak below and dead letter or term at exhaustion). - -Acceptance against `nats:2.10-alpine` in WSL with a **restricted account** -- the agent user may -subscribe to its deliver subject and publish `$JS.ACK.>`, nothing else: an operator-made consumer -was bound, three `t..risk.created` events reached the handler as `risk.created`, one -`issue.created` was filtered out, all acked (ack pending 0, redelivered 0), the consumer's config -unchanged, **0 permission violations** in the broker log. Control: a managed binding with the same -user fails on `$JS.API.STREAM.INFO` with a publish violation, so the check is real. A consumer -created by the binding (`manage_consumer`) and one created by the first consumer's own pool for the -same tenant document are **identical** as the broker reports them. Unit suite 3391 passed; -integration 41 passed, the same 2 failing as without the change. - -Open for step 3: reconnect handling exists for the default link only (`_on_reconnected`); a named -link needs its own. A plain subscription is restored by nats-py on reconnect; whether the push -consumer delivers again without a JetStream request is to be shown against a broker restart. - -### Named connections from a connection source (named connections, step 3a) - -Step 3a of `docs/plans/2026-10-14-named-connections.md` (decisions D1-D4, D8, D10). - -- `clients/io/nats_connections.py` gains the deployment-facing API: `ConnectionSpec` (name, URL, - credentials -- secrets kept out of `repr` -- and `connect_options()`), the `ConnectionSource` - protocol (`connections()`, `binding(agent, subjects, connection)`, `validate(connection, subject, - event)`, `run_scope(connection)`), `load_connection_source()` for the process-scope key - `nats_connection_source` (added to `PROCESS_SCOPE_KEYS`), and `current_connection()` / - `mark_connection()` over a ContextVar that is only ever set inside a run's own task. -- `AppBuilder.build` loads the source once per process (NATS only) and `_wire_transport` hands it to - every agent's client (`NATSClient.set_connection_source`) -- no global state; a wrong path fails - the build. -- `NATSClient.subscribe` asks the source per connection (`_plan_named_bindings`): each binding gets a - `_Link` of its own (D1) and its own run slots; the subjects it serves leave the default binding - (D10); a binding claiming an undeclared subject, or named connections together with - `event_publishing.topic_mapping` (D4, `_refuse_result_publishing`), fail startup. -- Each named binding connects and binds in a loop of its own (`_start_named_links`, - `_run_named_link`, `_open_named_link`): retried forever, reconnecting forever once open, one - failing never holding up another or the default connection. On reconnect nothing is re-bound: the - plain subscription is restored by nats-py and the push consumer delivers to it again. -- Pause drains every binding, resume restarts the named loops (re-binding over the open link), - `close` drains all, waits for every run within the one `event_client_drain_timeout`, then closes - every link. `inflight_handlers` counts every connection; `named_connections` lists them. -- A run from a named connection starts in an empty `contextvars.Context` (N1; the default - connection keeps its copied context, N6), marks its connection, is checked by `_accepted` - (validation hook: a reason terms it, an exception naks it) and runs inside `_run_scope` (the - source's sync or async context manager). `NatsEventing` adds `nats_connection` to the handler - context only when a run has one. - -Tests: `test_nats_connection_source.py` (22: loading the source, the spec, planning the bindings, -D4, scope and connection inside the run, an ambient ContextVar not inherited, two connections never -sharing a run context, rejection, a raising validator, the default connection unchanged, the -context key, shutdown of every link) and `TestConnectionSourceWiring` in `test_app_builder.py` (3). - -Acceptance in WSL against `nats:2.10-alpine` with three accounts -- a process account allowed -nothing, and per tenant an admin (provisioning, operator) and an agent user allowed only its deliver -subjects and `$JS.ACK.>` -- and a real group of three agents on two named connections, the source -binding them as the first consumer does and validating as W17.2 does: 32 of 32 runs, none whose -connection, scope tenant (also after awaiting) and event tenant disagreed; handlers saw -`risk.created` / `issue.created` and their declared topics; at most 2 runs per (agent, connection) -with `nats_max_concurrent_runs = 2`, 12 at once overall; every consumer acked, none redelivered; an -event in tenant A's stream claiming tenant B ran nowhere and was termed; after a broker restart all -named connections were back and delivering without a JetStream request; 0 permission violations. - -### Run limits: a guaranteed run per pair, a process pool for the rest (named connections, step 3b) - -Step 3b of `docs/plans/2026-10-14-named-connections.md` (decision D7). - -- New module `clients/io/nats_run_pool.py`. `RunLimit.parse` reads a number or `"N%"` (refusing - anything else, naming the key); `resolve(pairs)` turns a percentage into runs of the process's - current (agent, connection) pairs, never below its minimum. `PairRuns` holds whether a pair's - guaranteed run is busy and how many it runs. `RunPool.acquire(pair, limit)` grants the guaranteed - run whenever it is free and a further run only while the pair is below K and the pool below its - size; waiters are woken in arrival order, a cancelled waiter returns what it was granted, and - `add_pair` / `remove_pair` re-resolve percentages. -- `AppBuilder.build` creates one `RunPool` per process from `nats_extra_runs_per_process` (added to - `PROCESS_SCOPE_KEYS`) and hands it to every client (`NATSClient.set_run_pool`). -- `NATSClient`: `nats_max_concurrent_runs` now accepts a percentage (`_resolve_max_concurrent_runs` - returns a `RunLimit`); `_Binding.limit` / `_Binding.pair` replace the shared semaphore; the - delivery path waits in `_acquire_run` -- unset K: the subscription's one slot as before; set: the - pool -- and the run's done-callback calls the returned release. `_register_pairs` counts each - client's pairs into the pool at `subscribe()` and out at `close()`. - -Tests: `test_nats_run_pool.py`, 21 (parsing, percentages, guaranteed run with an exhausted pool, K and -pool together, arrival order, cancellation, a percentage following the pairs, and through the client -an idle connection running while a busy one has exhausted the pool). - -Acceptance in WSL, the 3a set-up (three agents on two restricted connections, six pairs) with -`nats_max_concurrent_runs = 3`, `nats_extra_runs_per_process = 2`, a burst on every pair at once, 1 s -runs: all 40 runs, the first run of every pair started within 0.16 s, at most 2 per pair and **8 at -once overall -- six guaranteed plus the pool of two**, no run whose tenants disagreed, 0 permission -violations. - -### A run can be bounded: `nats_handler_timeout` (named connections, step 3c) - -Step 3c of `docs/plans/2026-10-14-named-connections.md` (decision D9; part A's hard limit of -`docs/specs/2026-09-24-handler-time-bounds.md`, without its shutdown part). - -- `_resolve_handler_timeout` reads `nats_handler_timeout` in `subscribe()`: unset -> `None` (no - limit), a number or numeric text > 0 -> seconds; zero, negative, other text and booleans are - refused naming the key. -- `_run_delivery` runs the handler chain (and the source's run scope) inside - `asyncio.timeout(self._handler_timeout)` -- in the run's own task, so its ContextVars stay - visible. A `TimeoutError` with `limit.expired()` -> `NAK` and an ERROR naming agent, event, topic - and the connection if named; any other exception, a handler's own `TimeoutError` included, keeps - `disposition_for`. A handler that swallows the cancellation and returns -> `limit.expired()` on a - normal exit -> `NAK` and an ERROR saying it held its slot until it returned. The slot is released - by the run's done-callback, so only when the task has really ended. The heartbeat is still stopped - in the `finally` before the delivery is settled. A nak on the last allowed delivery becomes the - usual dead letter / term. - -Tests: `test_nats_handler_timeout.py`, 11 (cut and nak'd without the handler continuing, heartbeat -stopped before the nak, the handler's own `TimeoutError` an ordinary failure, unset never cut, a -swallowed cancellation holding the slot and nak'd, invalid values refused, numeric text read, the -limit on a named connection naming it). - -Acceptance in WSL, the multi-account set-up (two agents on two restricted connections), one event -on agent1@A whose handler hangs forever, three further events on agent1@A, events on every other -pair, `nats_handler_timeout = 2`: the hung event ran on agent1@A five times (starts at 0.0, 2.7, 4.7, -6.7, 8.7 s -- `max_deliver` 5) and was then given up (consumer: ack pending 0), agent1@A's other -three events ran in between, agent2@A 4 of 4 and tenant B 6 of 6 finished. Control without the key: -the hung run held agent1@A for the whole window -- its other three events never ran (ack pending -4) -- while every other pair finished. 0 permission violations in both runs. - -### `asbs validate` warns about a swallowed cancellation - -Decided with the owner after step 3c: a handler that catches the cancellation and returns normally -is nak'd (the limit was exceeded), and the validator says so before it happens. - -- New `agent_generator/cli/utils/cancellation_check.py`: `swallowed_cancellations(src_dir)` parses - every module under `src/` and reports `path:line` for an `except` that catches a cancellation -- - bare, `BaseException`, `CancelledError` (by name or attribute, alone or in a tuple) -- whose body - contains no `raise` outside nested functions, and for `contextlib.suppress(...)` naming one of - them. `swallowed_cancellation_warning(agent, found)` words the consequence. -- `validate.run` adds the warning for the project's `src/`; `validate_group._agent_findings` for every - agent root. A warning, not an issue: the agent still runs. - -Docs: `guides/cli/validate.md`, the `blueprint-events` skill (rule: never swallow -`asyncio.CancelledError`; `asbs validate` warns), `CHANGELOG.md`. Tests: -`test_validate_cancellation.py`, 15. Checked against the first consumer (`--group --agent-map -deploy/agents.toml`): valid, no finding in any agent; control -- a copy of `business_case` with an -injected `except asyncio.CancelledError: return None` -- reported with file and line, validation -passing with the warning. - -### A closed NATS connection comes back with its subscriptions (named connections, step 4a; review finding #10) - -- `connect()`: `nats_max_reconnect_attempts` defaults to `-1`; `closed_cb=_on_closed`. Once - subscriptions are managed, a `connect()` from outside the retry loop (the health checker polls it) - only starts the loop, which connects and subscribes -- or, while the agent is paused, connects and - subscribes nothing until `resume_consumption`. `_on_closed` restarts the loop unless we closed it - ourselves (`_closing`, set in `close()`). -- Tests: `TestAClosedConnectionComesBack` (7). -- Measured in WSL, JetStream, broker stopped for 45/60/75 s, control on the code before: both recover; - the code before only because the health checker reconnected bare and pause/resume (C4) resubscribed. - A first version of this change refused that bare connect also while paused and so never recovered - (caught by the control run, fixed). Time from broker start to the first event handled is bounded by - the next health poll in both versions (C4 resumes only on a healthy poll): 3.0-14.2 s before, - 14.2-29.3 s after, by phase of the 30 s poll. **Open:** resume on reconnect without waiting for the - next poll would cut up to one `health_check_interval_seconds` from every recovery. - -### Named connections change at runtime (named connections, step 4b) - -Step 4b of `docs/plans/2026-10-14-named-connections.md`, following the rules of the -dynamic-subscriptions draft spec (7.2, 7.4, 7.5, 7.7, 7.9, 7.10) for whole connections. - -- `ConnectionSource.watch(notify)` is optional (looked up with `getattr`; not part of the protocol's - `isinstance` check). `subscribe()` registers `_connections_changed`, which hops onto the client's - loop with `call_soon_threadsafe`; `_schedule_reconcile` runs one `_reconcile_loop` at a time and a - notify during a pass makes it run once more. -- `_reconcile` (under `_change_lock`, which `pause_consumption` and `resume_consumption` also take) - re-reads `connections()`/`binding()` for the declared subjects and diffs by name against the - bindings that are not `superseded`: **added** -> `_new_named_binding` + `_start_named_link`; **changed** - (`ConnectionSpec` or `JetStreamBinding` differs) -> a new binding with `replaces` = the old one, which - is marked `superseded` and keeps serving; `_run_named_link` retires it only once the new one is bound - (`_start_retirement`); **removed** -> `_retire`. A binding claiming undeclared subjects is skipped with - an ERROR; an agent mapping results to topics gains no connection (D4). The default connection's - subjects stay as computed at startup. -- `_retire`: cancels the binding's loop, drains its subscriptions, waits `subscription_change_grace` - (agent scope, default `event_client_drain_timeout`) for its runs, then sets `revoked`, cancels their - heartbeats (`_Binding.heartbeats`), closes the link (`_Link.closing`, so the disconnect is not logged - as a lost broker) and removes the pair from the pool. A revoked run is never settled - (`_run_delivery` returns before `_settle`), and `publish` from it raises the new - `models.errors.DeliveryRevokedError` (the run's binding is in the ContextVar `_CURRENT_BINDING`). No - consumer is deleted. -- Permission violations reported through a named link's `error_cb` are kept on `_Link.permission_errors`; - an attempt that failed while one arrived is logged at ERROR and retried every - `PERMISSION_RETRY_SECONDS` (60) instead of at the normal pace. -- `close()` cancels a running reconcile and pending retirements first; the normal close then drains - and closes every binding still listed. -- Found by the unit tests while building it: `_reconcile` first called `_start_named_links()`, which - restarted the loop of every already bound connection -- each would have bound a second subscription. - It now starts only the bindings it created (`_start_named_link`). - -Tests: `test_nats_runtime_changes.py`, 19 (watch optional and registered; added, removed, changed with -new-before-old order and the old link serving while the new one cannot bind; unchanged left alone; -undeclared subjects and D4 skipped; revocation -- never settled, publish refused, heartbeat stopped, -settled normally within the grace; coalescing; notify from another thread; pause waits for a change; -close during a change; permission back-off and error_cb recording). Unit suite 3509 passed. - -Acceptance in WSL against `nats:2.10-alpine` with accounts PROC (nothing allowed) and TA/TB/TC (admin -plus two agent users each, allowed only their deliver subjects and `$JS.ACK.>`), a group of two -agents, a source changed through `watch` while A and B received an event every 0.1 s: -(1) C added -> 10 of 10 runs, A and B undisturbed; (2) A's credentials switched to its second user -> -114 events, none missing, none duplicated, longest gap 0.14 s, consumers of A ack pending 0; -(3) B removed while a 5 s run was in flight, grace 1 s -> revoked after 1 s, the run finished 4.5 s -later and was not settled (each B consumer: ack pending 1, the delivery stays with the broker); every -B event before the removal handled. 360 runs, none whose connection, scope tenant and event tenant -disagreed; 0 permission violations. **Control for (2):** the old link closed abruptly before the change --> still none missing and no visible gap, but each A consumer ended with **ack pending 2**: acks lost -with the link, redelivered after `ack_wait` as duplicates. That is what binding first and draining -then prevents. - -### Claimed subjects never reach the default connection (named connections, step 4c) - -Decided with the owner after 4b: the hybrid of named and default connection is allowed only -explicitly, and an undeclared mapping fails startup. - -- `ConnectionSource.claims(agent, subjects)` (required): the subjects that belong to named - connections, from the deployment's scheme, independent of the connections that exist now. -- `NATSClient._plan_named_bindings`: `_claimed_subjects` (a claim must name declared subjects); - unclaimed subjects fail startup unless `_resolve_unclaimed_policy` reads `nats_unclaimed_subjects = - "default_connection"`; a binding may serve claimed subjects only; the default binding gets the - unclaimed subjects only. `_reconcile` skips a connection whose binding serves an unclaimed subject. -- Before this, a start without any connection put every subject on the default connection for good, - and a tenant added later was served in addition. - -Tests: 8 new cases in `test_nats_connection_source.py`; the fakes implement `claims`. Live, three -accounts with a process account allowed nothing: before 4c a fresh start subscribed `risk.>` / -`issue.>` on the default connection -- 3 permission violations -- and kept them after tenant A -arrived; with 4c nothing on the default connection, 0 violations, tenant A's 3 events handled; an -unclaimed `scheduler.tick` fails startup with the message; with `"default_connection"` it is -subscribed there (1 violation, because that test's process account may subscribe nothing -- the -deployment must allow it). - -### Broker integration tests for the delivery features and named connections - -The acceptance runs of steps 1 to 4c, as repeatable tests in `tests/integration`. - -- `test_delivery_concurrency.py`: up to K runs at once on one subscription; unset, one run per - subscription with subscriptions in parallel; heartbeat keeps a run longer than `ack_wait` from - being redelivered, and switched off it is redelivered while it runs; `nats_handler_timeout` cuts a - hung run, which comes back at once (`nak`) while the others flow; an exhausted run pool never holds - back a pair's first run. -- `test_named_connections.py`: two tenants on their own accounts, 16 runs, no run whose connection, - scope tenant and event tenant disagree, consumer config unchanged, 0 permission violations; an - event `validate` rejects never runs and is `term`ed; an unclaimed subject fails startup; with - `nats_unclaimed_subjects = "default_connection"` it is served there; a connection added, its - credentials switched and removed at runtime, none lost, none duplicated. -- `docker-compose.yml` gains `nats-accounts` (4223) with `nats-accounts.conf`: process account - allowed nothing (and a hybrid user allowed `hybrid.>`), one account per tenant with an admin and - agent users allowed only their deliver subjects and `$JS.ACK.>`. Test-only placeholder passwords. -- `conftest.py`: `settings_group` (a group from settings the test writes, waiting for named - bindings), `base_settings`, `accounts_url`; `connection_source.py` is the test `ConnectionSource`. - -11 new tests, about 15 s together. Two full integration runs on fresh brokers: 52 passed, 2 failed -each, both failures pre-existing and failing at HEAD as well (`test_two_processes_share_cache`: -the subprocess does not find `blueprint`; `test_the_broker_counts_it_as_a_redelivery`: now -deterministic, see Open points). - -### Named connections, step 5: readiness and telemetry per connection (D5, review finding #6) - -- **Readiness only, never a pause.** `HealthCheckEntry` gains `affects_consumption` (default `True`). - `HealthCheckCache` computes two verdicts per agent: readiness from every entry (payload, policy) and - consumption from the entries that may pause (what `NamespaceSupervisor.observe` gets). The new - entry `.nats_client:connections` (`NamedConnectionsHealthChecker`, registered by `build()` - for each NATS client given a connection source) is readiness-only: a tenant connection that is down - never pauses the agent on its other connections, in any mode. -- **`nats_connections_readiness`** (agent scope): `"never"` (default, the entry always healthy and - only reports), `"any"` (fails while none is bound; zero connections count as none), `"all"` (fails - while one is not bound). Another value fails `subscribe()`, naming the key. The default - connection's entry is unchanged. -- **Per-connection state** (`NATSClient.named_connection_states()`): `bound`, `connecting`, - `reconnecting`, `retrying` with the last error (URL and the link's credentials redacted, 200 - characters), `paused`, and whether a permission violation was seen. A refused login never surfaces - as an exception -- with `max_reconnect_attempts=-1` `nats.connect()` retries it itself and never - returns -- so `error_cb` records it as the last error, and the state reads `retrying`. -- **Metrics** on the agent's meter: gauge `blueprint.nats.connection.bound` and counter - `blueprint.nats.connection.permission_violations`, both with `agent` and `connection`. -- **#6:** `get_health_status()` no longer takes the lock the poll holds while it awaits the checks; - the lock now only serialises polls. Live over HTTP with a 4 s check: max 3928 ms and 5 of 25 probes - over 0.5 s on the old code, max 82 ms and none over 0.5 s now. -- **Immediate re-evaluation:** `NATSClient.set_health_refresh()` (wired by `build()` to - `ActuatorApi.refresh_health`). The default connection coming back while the agent is paused runs - the checks at once, so a pause its own disconnect caused ends on the reconnect; under `any`/`all` - a named connection becoming bound or unbound does the same. The refresh runs in a watched task. -- Tests: unit (states, redaction, modes, checker, two verdicts, lock-free read, serialised polls, - refresh, gauge, counter, wiring); integration `TestADeadConnectionCountsForReadinessOnly` on the - accounts broker -- tenant B with a wrong password, per mode: A bound and B `retrying`, `/health/ready` - 200/200/503 for never/any/all, the agent not paused, A still delivering, no password in the payload. - -### A responsible handler can skip an event: `HandlerResult.skipped` (named connections, D11) - -- **`HandlerResult.skipped(reason, *, metadata=None)`** (`models/events.py`): a new field - `skip_reason`, a validator that refuses an empty reason and a skip that would also carry - `event_type`, `subject` or `data`, and the property `is_skipped`. -- **`HandlerChain._dispatch`**: a skipped result is returned like any non-`None` result -- so the - chain stops and no later handler is asked -- and is logged at INFO with the reason, with the span - attributes `handler.skipped` and `handler.skip_reason`. -- **`ProcessingStatus.SKIPPED`**: `EventProcessingService.process_event` reports it when every result - of the run is a skip (a list mixing a skip with real results stays `PROCESSED`; the skip publishes - nothing either way, because it has no `event_type`). Message: `Skipped: `. -- **`EventHandlingBase._process_cloud_event`** counts it as `blueprint.events.skipped` (`agent`, - `topic`), apart from `blueprint.events.unhandled`. Acknowledgement is unchanged: a return acks. -- **`RestApiBase._process_resource`**: `success` is true for `PROCESSED` and `SKIPPED`. -- Live in WSL against `nats:2.10-alpine` (`tests/integration/test_skipped_result.py`): a skipped event - acked once, ack floor 1, 0 redeliveries after `nats_ack_wait`, nothing on the outbound subject, the - second handler never called, INFO line with the reason and no "No handler processed event". Control - on the unchanged code (the only handler returning `None`, the way an agent had to say "nothing to - do"): acked, but WARNING `No handler processed event 'orders.created'` and counted as unhandled. +--- -### Named connections, step 6: documentation, scaffold and skills agree with the code +## Compatibility -- **One `main.py` pattern** everywhere (W1): the installed `CLAUDE.md`, `blueprint-builder.md`, - `getting-started.md`, `concepts/architecture.md`, `components/agents.md`, `event-handlers.md`, - `rest-apis.md`, `schedulers.md`, `services.md`, `caching.md`, `configuration.md` and - `reference/api.md` now show the template's declaration. `reference/api.md` documents - `AppBuilder(config=None)` and `build(config=None)`. -- **Chain semantics** (W2): `event-handlers.md` and `concepts/event-processing.md` said a - `HandlerResult` (and any other value) let later handlers run; `_dispatch` returns the first - non-`None` result. Both now carry a table per return value, including `skipped`. -- **`concepts/architecture.md`** (W3) used `with_agent(name, Cls)`, a synchronous - `can_handle_event(event)`, `register_routes`, `execute()` and `priority = 10`; rewritten. -- **Scheduler** (W4): `blueprint-builder.md` showed `on_startup` without `super().on_startup()`. -- **W5** was already fixed (`519566f` removed the second `CLAUDE.md`). -- **Handler template** (W7, W8): docstrings and the idempotency comment now put the decision in the - service. **Runtime in `context`** (W9): documented as framework plumbing a handler never runs. - **Models** (W11): `models/` is `dto.py` + `domain_models.py` (+ `mapper.py`) as the templates - already scaffold it. -- **Handler rules** (2026-10-15) in the installed `CLAUDE.md` (rules 7-10), the builder and architect - agents, `blueprint-events` and `add-component`. -- **`event-handlers.md` context keys:** `nats_topic`/`nats_subject` as the agent declared/knows them, - `nats_connection` added; the tenant example is gone (the framework names no tenant). -- **Spec sec. 5.2** listed `nats_ack_wait = 300`, `nats_max_ack_pending = 16`, `nats_max_deliver = 5` - as defaults; the code leaves them unset (server defaults). Corrected, the new keys added; sec. 7.3 - states the default heartbeat. -- **`guides/deployment.md`**: the "never exercised against a real broker" banner is replaced by - what `tests/integration` covers; dispositions for skipped and timed-out runs; the heartbeat. -- **`reference/configuration-keys.md`**: `nats_subscriptions`, `nats_publish_mode` and - `nats_publish_subjects` were read by the code and documented nowhere. -- **`asbs validate`** (`_nats_findings`): the NATS keys parsed with the client's own parsers; the - source's module found via `importlib.util.find_spec`, the factory never called. +Every breaking change, with its migration, is listed in `CHANGELOG.md` under +`[Unreleased]` -> *Breaking*. The two that most often bite: -### The delivery attempt in the handler context +- **`scheduler_mode` is required** for a project with a scheduler; startup fails naming both values. + A deliberate departure from spec sec. 7.5 (defaulting would either keep a timer per replica, #73, + or stop ticking a service without a broker). +- **A scoped `Config`'s telemetry `service.name` is the agent's name** unless + `.otel_service_name` is set. -- `nats_connections.py`: `DeliveryAttempt(attempt, max_deliver)` in a ContextVar, set by - `NATSClient._run_delivery` inside the run's own task from `msg.metadata.num_delivered` and - `_max_deliver_of(binding)` (the binding's `max_deliver` on a named connection, `nats_max_deliver` - on the agent's own consumers; `None` for unset or `-1`). `_deliveries_exhausted` now uses the same - helper. A message without JetStream metadata (Core NATS) sets nothing. -- `NatsEventing._make_event_callback` copies it into the context as `nats_delivery_attempt` and - `nats_max_deliver`. -- Unit tests: named run attempts 1 and 2 with the binding's limit, default connection with unset - `nats_max_deliver` -> `None`, no metadata -> no keys, both keys in the context. +`tests/unit/agents/test_frozen_compatibility.py` holds what existing projects do; it is never edited +to accommodate an API change. --- ## Open points -- **A grouped scheduler's trigger path repeats the agent.** `register_trigger_route` builds the - path from `self.name`, the registry name, which a group qualifies: agent `orders` serves - `/api/orders/scheduler/orders_nightly_scheduler/trigger`. Standalone the name is unqualified, so - using the base name would change grouped paths only. Found in step 1 of the grouped-HTTP-surface - plan (it predates that step); deferred by decision on 2026-09-28. - -- **`test_three_replicas_run_one_tick` is flaky in a full run.** Seen once on 2026-09-24 (two of three - replicas ran one tick), passing alone. Likely `DiskCacheService.claim`'s documented non-atomic - takeover of an expired claim, or a run straddling a minute boundary; not investigated. - -- **`test_the_broker_counts_it_as_a_redelivery` now fails every time** (2026-10-15, also with the - test changes stashed). The consumer info it reads shows `num_pending=0, num_redelivered=0`: the - retryable failure is `nak`ed at once, so all `max_deliver` attempts are used up within - milliseconds and the message has left the pending set before the test reads the count, which - then no longer includes it. Likely the assertion, not the client; not fixed here. - -- ~~**A startup-failure latch is never released.**~~ **Closed** -- see *A latched agent recovers, and - readiness shows it* above. A non-critical agent whose `on_startup` raised - is latched by `AppBuilder._mark_agent_down` -> `NamespaceSupervisor.mark_down`, and nothing in - `src/` calls `clear_forced_down`, so it stays degraded until the pod restarts. That is what sec. - 9.1 specifies -- it names no recovery -- so it is not a defect against the committed spec; it - violates D9 of the untracked dynamic-subscriptions draft, which proposes retrying `on_startup` - with a budget and then terminating. Terminating is not obviously right for a *deterministic* - failure (a bad key): the restart fails the same way, and crash-looping the pod takes every - healthy agent down with it, which is the blast radius sec. 9.1 exists to remove. Undecided. - -- ~~**The generated `settings.toml` writes two sections nothing reads.**~~ **Done.** `[default.logging]` - (`level`, `format`) and `[default.observability]` (`otel_enabled`, `token_metrics_enabled`) are - sectioned, and the framework reads all four as **flat** keys -- `log_level`, `log_format`, - `otel_enabled`, `token_metrics_enabled`. Probed against a real `Config`: a settings file with - `[default.observability] otel_enabled = true` yields `get_observability_config().otel_enabled == - False`, so a developer who turns telemetry on in the file scaffolded for them gets nothing and no - message. `base_files/settings.txt` is where it is written. -- ~~**`asbs create agent` writes `[default.runtimes..models]`; the framework reads - `runtimes..model_settings`.**~~ **Done.** The generator's own settings writer - (`settings_part_generator.py`) writes `.model_settings` correctly, so the two halves of the - scaffolder disagree and the block `asbs create agent` adds is inert. Found beside the - `openai_reasoning_effort` value fixed in step 3, in the same statement. -- ~~**A scaffolded project cannot start: its secrets file is never loaded.**~~ **Done** -- the - generator moved to `.secrets.toml`. `asbs setup` used to write - `secrets.toml`, and `DEFAULT_SETTINGS_FILES` -- the list `entrypoint.py` hands to `Config` -- - names `.secrets.toml`. The scaffolded `model_provider = "vllm"` makes the API key a validated - requirement, so `Config.validate()` raises `Missing API key for vLLM provider` on a project - nobody has edited. Probed by generating a project and loading it with the framework's own - defaults. Which name is right is the decision: the generator says `secrets.toml` in four places - (the file it writes, `secrets.toml.example`, the `.gitignore` entry and `asbs validate`'s two - checks), Dynaconf's own convention is `.secrets.toml`, and adding a name to the framework's list - changes what every existing deployment loads. -- ~~**A scaffolded project still cannot start: `AgentRuntime` is constructed without a name.**~~ - **Done.** - `AgentBuilder.build()` calls `AgentRuntime(system_prompt=..., tools=..., **kwargs)`, and - `AgentRuntime.__init__` takes `name` as a required positional argument; - `AppBuilder.with_agent(agent, name=...)` records `name` on the declaration and assigns it after - construction, so nothing supplies it. Every unit test of that path stubs `agent.build`, which is - why it is green. Reproduced by generating a project and calling `create_group_app`. - -- ~~**An agent can read a neighbour's data by four routes.**~~ **All four closed** in isolation - steps 1-4; what follows is the record of what each was. The barrier is now enforced rather - than conventional, with one deliberate exception (`Config.settings`, below). Grouping's whole premise is that co-hosted agents are isolated; each of these was - reached with nothing but the framework's public API and a neighbour's *name*, which an agent - knows because it is in the group. Stated as tests in - `tests/unit/agents/test_agent_isolation.py`, marked `xfail(strict=True)` so that closing one - turns the test red until the marker goes. - - ~~**`Registry._lookup` falls back from `_` to the bare name**~~ **Closed in - isolation step 1.** A neighbour's key *is* a bare name in the same dictionary, so - `get_component("orders_ledger")` from `billing` returned orders' instance. The fallback now - checks that what it found belongs to the root or to the asking agent. - - ~~**`_effective_namespace` lets an explicit `namespace=` win on a view**~~ **Closed in - isolation step 2**, together with the same hole in `_cache_owner` -- both now refuse a view - that names an agent other than itself or the root. - - ~~**A scoped `get()` resolves a dotted key against the whole tree**~~ **Closed in - isolation step 4.** The root fallback now accepts only the framework's own dotted prefixes - (`SHARED_NESTED_PREFIXES`), an allowlist that fails closed. - - ~~**One declaration serving two agents constructs both with the same mutable argument.**~~ - **Closed in isolation step 3.** A declaration used by more than one agent is refused at - assembly if it carries anything but code or an immutable value; a zero-argument factory is - the way out and needs no new API. - - `Config.settings` is a fifth route and is **deliberate** -- the documented escape hatch, which - returns the unscoped tree and logs a WARNING naming the agent. It is covered by a passing test - rather than an xfail, because what it does is what it is for; whether an escape hatch belongs in - the barrier at all is the question to settle with the other four. - - What holds, and is now pinned: two agents get separate instances of one declared class; a - lookup by bare name, by class, or by enumeration sees only the asking agent's own; the root - remains resolvable; two agents declaring one cache name get separate stores and cannot read each - other's keys; `cache_entries()` refuses on a view (C6); `Config.for_namespace` refuses to hand - out another agent's view; and each agent gets its own thread pool. - -- ~~**A handler's published result is lost under JetStream unless something else provisions the - stream.**~~ **Closed.** The client declares its publishable subjects and the stream carries - them; publishing is now its own mode. Originally: `NATSClient._stream_subjects` covers the subscribed topics and the dead-letter - subject; a subject a `HandlerResult` is published *to* is not among them, so `js.publish` waits - for a stream acknowledgement that never comes, times out, and - `EventPublishingService.publish_handler_event` swallows it as a WARNING. A Core NATS listener - still sees the event, so a live subscriber looks healthy while a downstream JetStream consumer - gets nothing. Found and reproduced against a real broker in broker step 2; stated as an - `xfail(strict=True)` in `tests/integration/test_event_path.py`, and written up in - `docs/plans/2026-09-11-broker-integration-tests.md`. The fix is a design question rather than a - line: the client would have to learn its publishable subjects, and `topic_mapping` is read by - the publishing service rather than by the client. - -- ~~**`asbs` crashes on a Windows console**~~ **Closed** -- `use_utf8` at the CLI entry point. - Originally: still open from step 1, and the only thing standing - between the CLI and the ASCII rule. Every command prints check marks and box drawing; on a cp1252 - console the first one raises `UnicodeEncodeError` mid-command, after files have been written. -- ~~**`docs/guides/cli-reference.md` still documents checks that have never existed.**~~ **Done in - phase 10 step 3.** Every command was read against the code: the generated project structure (it - listed a `tests/` tree and a `pyproject.toml` that are not written), `asbs create agent` (an - entire module and builder function that do not exist), `asbs create api`'s models file (it is a - package of three), `--priority`'s default, `--output-dir` on all four `create` commands, and - `asbs claude`'s `create`/`update` subcommands. Writing it found three defects, listed in that - step. -- **`asbs` crashes on a Windows console.** Every command prints check marks, warning signs and - box-drawing characters (`setup.py`, `create.py`, `validate.py`), and on a console whose encoding - is cp1252 -- the Windows default -- the first one raises `UnicodeEncodeError` mid-command, after - files have already been written. `asbs create handler` dies after writing the handler but before - registering it in `main.py`. Found while probing phase 10 step 1 against a generated project. - It is also a standing rule violation: source files are ASCII only. The fix is a sweep of the - CLI's output glyphs, which is its own step rather than a drive-by inside a step about the - generated project's shape. -- ~~**`asbs create` writes absolute imports into a file that uses relative ones.**~~ **Closed** -- - twelve occurrences rewritten. Originally: a generated - `main.py` imports `from .handlers import ...`; `asbs create handler` appends - `from src.handlers.order_placed_handler import OrderPlacedHandler`. Both resolve, so nothing - fails -- but the two styles in one file are how a later refactor breaks one of them. -- ~~**The migration guide must carry the cache key layout change.**~~ **Done in phase 10 step 3.** - `docs/guides/multi-agent-setup.md` says it under *The cache is cold after the move*, for both - hops, together with the surviving deployment constraint that an agent's disk cache is a - subdirectory of `cache.cache_dir` so a group still needs exactly one writable mount. -- **Two spec amendments from phase 9, both because the spec's wording latches.** Spec C4 says a - degraded namespace's transport client is *closed*. Implemented as a **pause** -- subscriptions - drained, connection kept -- because a closed client reports itself unhealthy for ever, so the - agent could never be seen to recover and a transient fault would take it off its topics - permanently. The same reasoning makes `NATSClient.health_check` report a paused client as - *healthy*, which is the second amendment: the pause is a consequence of degradation, not a cause - of it, and the check that actually failed is still in the payload. Sec. 3's C4 should say "stops - consuming" rather than "closes its client". -- **Spec C2's shared `BatchSpanProcessor` holds; its shared metric reader cannot.** The - OpenTelemetry SDK binds a reader's collect callback to the provider that registered it, so a - reader shared across providers collects only from the last one built. Each provider therefore - has its own `PeriodicExportingMetricReader` over the one shared exporter -- one export thread per - agent for metrics, one for the whole process for spans. Worth stating in sec. 3's C2, which - currently says "all providers SHOULD share one exporter and one `BatchSpanProcessor`" and is - silent on readers. -- **The readiness policy's treatment of the root is not in the spec.** The root gates readiness - under all three policies, because it holds the shared infrastructure and because a single-agent - application is *entirely* root -- so the key has to be a no-op there or it could not be set in a - settings file that standalone projects read. Sec. 3's C3 table should say so. -- **The blocked-loop watchdog names candidates, not a culprit.** It measures the overshoot of a - known sleep, so by the time it runs the blocking callback has returned; it reports the agents - with work in flight, which is the set the culprit is in. asyncio's debug mode gives the exact - answer and is available in production behind `event_loop_debug`, at the cost of wrapping every - coroutine creation. There is no cheap way to have both. -- **`readiness_policy = "any"` is implemented but has no acceptance criterion.** Spec sec. 12 lists - criteria for `all` and `critical` and none for `any`, and no example project or group file uses - it. It is the one of the three that has never been exercised against a real deployment. -- **Phase 7's ambiguity error needs a spec amendment.** The plan asks `process_event` to raise - when a handler declares no runtime and several are registered. It is implemented as a - once-per-handler WARNING with nothing bound, because raising would fail every delivery in an - application that has two agents and handlers resolving their own runtime by name -- the shape - the scaffolder generates. The spec's compatibility table already calls phase 7 "purely - additive", which the raise would contradict; the plan bullet is what should change. -- **P0-P5 have landed. P6 is next**, and two requirements for it were settled during P5 (see the - namespace bullet below). What remains open from P5 is deferred work rather than unfinished work: - both modes now fire a cron once across three replicas, which was P5's acceptance criterion. - Still open, in rough order of how much it matters: - - **Manifest generation is deliberately deferred** (decided 2026-09-04), and the renderer - written for it was removed rather than left unused. Two constraints settled the shape of the - missing caller and then removed the ground it would stand on: - - **Nothing may import a project's `src/main.py`.** Stated as an absolute rule. The - declaration is readable without it -- configure `Config` from the project's - `settings.toml`, import the leaf modules under `src/schedulers/`, instantiate each - `SchedulerBase` subclass and read its `crontab`, `scheduler_mode` and `tick_topic` -- - verified against - `examples/health_monitor`. What that cannot see is a `with_scheduler(Klass, name=...)` - rename, which changes both the tick topic and the object name, and a scheduler whose - `__init__` takes arguments passed at registration. - - **The image and entrypoint model is about to change underneath it.** Phase work turns - `main.py` into a pure `AgentRegistration` declaration with no `build()` call and the - Dockerfile's command into `python -m blueprint.agents.entrypoint`, with one image for the - platform and the group injected at container start. Manifests then belong to a *group*, - not to a project, and the agent-to-schedule map falls out of the in-image agent map the - entrypoint already has to construct. A per-project CLI written now would target a project - shape that is being replaced. - - The design decisions to carry forward when it resumes: **generate at scaffolding time**, - where the tool authored the registrations itself and therefore knows them; **a developer who - then edits the registration by hand owns the drift**; and **fail loudly** on anything the - generator cannot see rather than emitting a manifest that publishes to a subject nobody - subscribes to. The six traps the removed renderer surfaced are listed in the *P5* section - above, so they do not have to be rediscovered. - - **Timezone is not reconciled between the two modes.** Spec sec. 7.5 requires them not to - diverge. `"in_process"` uses apscheduler's timezone handling for the declared crontab; whatever - ends up publishing the tick in `"event"` mode will have its own. A scheduler tested locally in - one zone and deployed in another fires at a different hour, and nothing would notice. Dormant - while manifest generation is parked, since there is no second timezone to disagree with yet. - - **The tick claim is verified against a real cache but not a real cluster.** Three replicas - are simulated in one process against one `DiskCacheService` directory, which exercises the - set-if-absent path but not file locking across genuinely separate processes, nor Redis under - contention. Both belong on the broker/integration list below. - - ~~**`asbs validate` says nothing about schedulers.**~~ **Done in phase 10 step 2.** A - project in `"event"` mode is now told that nothing here generates the `CronJob` that must - publish its tick, a missing mode and a missing `event_bus` are both reported before startup, - and `"in_process"` with no cache is told that every replica will run every tick. What stays - outside `validate`'s reach is whether the `CronJob` actually exists -- the deployment knows - that, and this project cannot -- which is why it is a notice rather than a gate. -- ~~**The settings-fragment merge has two unanswered questions, both raised by step 3a.**~~ - **Answered 2026-09-10 (D5), and by dissolving the questions rather than deciding them.** A - group's settings supply *defaults only*, and each agent's own `settings.toml` merges under that - agent's scope -- so a fragment and a root key never occupy the same slot and there is no - collision to report or refuse. The second sub-question therefore has no subject, and the first is - generalised: process-scope keys in a fragment (`app_port`, `event_bus`, `envvar_prefix`, - `nats_stream_name`) **raise**, from an explicit list, because scoped they are read by nothing and - reported by nothing. **Implemented in phase 8b step 7** (`Config.merge_agent_settings`), with one departure: a - process-scope key in a fragment is **reported and ignored**, not raised, because every example - project declares `app_port` and `app_environment` in its settings file and raising would mean no - existing project could be hosted as an agent without editing it. Spec sec. 5.3's MUST should - become a MUST-report. The original text follows, because the probe in it is the evidence for - what the merge had to be built around. - - Spec - sec. 5.3 requires each agent to keep writing plain top-level keys in its own `settings.toml` and - the build to merge each fragment under that agent's scope, reporting collisions with a root key. - Confirmed by probe that nothing does this yet: handing two fragments to - `Config(settings_files=[...])` merges them *flat*, so the last file silently wins -- two - fragments each declaring `model_name` at root end with `for_namespace("orders")` returning - billing's value. What the merge must decide, and the spec does not say: - - **A fragment declaring `envvar_prefix` must be rejected, not merged.** The prefix is - process-wide -- one group, one prefix -- and it is now a *top-level* key, which is exactly the - shape a fragment consists of. `_reject_sectioned_envvar_prefix` does not catch this: it looks - for the key nested inside a section, and a fragment's is at the top level where it looks - legitimate. Merged and scoped it would be silently inert; merged at root, whichever agent - happens to load last would decide how the whole group reads its environment. - - **Whether a fragment may override a shared infrastructure key at all.** Sec. 5.3 says a - collision between a fragment and a root key MUST be *reported*; it does not say whether it is - then refused. The two readings differ in practice: an agent overriding `model_name` is the - point of scoping, while an agent overriding `nats_url` or `app_port` breaks the group it is - hosted in -- and `app_port` is already root-only (config rework step 1), so at least one key - has to be refused rather than reported. The likely answer is a small set of group-owned keys - that a fragment may not carry, with everything else scoped. -- **Two requirements this raised for later phases, now written into the spec.** - `scheduler_mode` **must** resolve per namespace through C5 rather than once per process, or a - group cannot host a pure-scheduler agent on `"in_process"` next to an event-driven agent on - `"event"` -- which is precisely the deployment freedom grouping exists to provide. Today - `Config` is scope-aware only when `agent_scope` is set on the single shared instance, so every - scheduler in a process shares one mode. And P6 **must not** create a client for a namespace that - neither subscribes nor publishes: sec. 6 argues connection count is cheap and refuses a knob, - which is right per namespace that uses a connection and wrong for one that does not. Both are - recorded in spec sec. 7.5 and sec. 6 with acceptance criteria; neither is implemented. -- **Exclusivity between scheduling and event consumption is not enforced, and deliberately so.** - `scheduler_mode = "in_process"` with no handlers already produces a process that subscribes to - nothing and opens no connection, and publish-only produces one that subscribes to nothing while - still emitting -- so the shapes are expressible without a new switch. A third key would only - overlap `event_bus` and `scheduler_mode` and create a contradiction to resolve. What is *not* - covered is making it observable: spec sec. 9.2 already requires the startup log to carry each - namespace's queue group and durable names, and extending that to "namespace X consumes: nothing" - is what would let a regrouping be checked by diffing logs. If a hard guarantee is wanted later, - the right form is an opt-in per-namespace declaration validated at build time, not an execution - mode. -- **The tick subject is provisional.** `.scheduler.` is a choice this - change had to make, and the subject taxonomy is explicitly unratified (spec sec. 13: who owns - `..`, and how a subject is added). Changing it later moves a subscription, - which under JetStream means a durable's filter changes -- a migration, not a config change - (sec. 7.7). The `topic=` override exists so an agent can opt out of the guess, but the default is - what the generated `CronJob` will encode. -- ~~**Nothing observes a tick.**~~ **Done in phase 9.** `blueprint.scheduler.tick_age_seconds` - reports the age of the last tick, `-1` before the first, in both modes. What it does *not* do is - interpret the crontab: "two intervals" is an alerting expression written against the gauge, not - something the framework decides, because the framework has no view of what a missed tick costs. -- **There is no generated README**, so the third surfacing channel spec sec. 7.4 asks for has - nowhere to go. `asbs setup` writes a Dockerfile, settings, secrets and source, and the - generated `CLAUDE.md` and `settings.toml` carry the idempotency note instead. If a README is - ever generated, the note belongs in it too. -- **Dedup is best-effort and unverified against a real broker.** `exists` then `set` is not - atomic on either cache backend, so two replicas handed the same event simultaneously can both - dispatch, and a cache error fails open. Whether that window is ever hit in practice depends on - how the broker distributes a redelivery, which belongs on the broker-test list below. A - compare-and-set primitive on `CacheService` (Redis `SET NX`) would close most of it and is not - written yet. -- **Nothing bounds the dedup cache, and the same now applies to tick claims.** Every dispatched - event writes one entry for `idempotency_ttl` seconds, and every scheduler tick writes one for - `TICK_CLAIM_TTL_SECONDS`. On Redis both expire server-side. On disk they expire *logically* -- - `exists` and `get` honour the TTL metadata -- but the bytes are reclaimed only when the entry is - read again, and a slot key is never read again. One small entry per tick is negligible next to a - per-event marker, but it is unbounded on the same terms. Every dispatched event writes one entry - for `idempotency_ttl` `DiskCacheService` expires lazily -- an entry is removed when it is next read, so - markers nobody asks about again stay on disk. A long TTL on a high-volume topic grows the cache - directory without limit, and no metric reports its size. -- **The dedup TTL question in spec sec. 13 is not answered, it is delegated.** Requiring the key - puts the number in the deployment that knows its own redelivery window; it does not tell that - deployment what the number is. Guidance -- worked from `nats_ack_wait * nats_max_deliver` -- - belongs in the deployment guide and is not written. -- **The dead-letter subject has no consumer.** Messages accumulate on it and are subject to the - stream's retention, so a deployment that never reads it will silently lose dead letters when the - stream ages them out. Draining it is an operational task the framework does not do, and no - guidance for it is written yet. -- ~~**Nothing observes dead-lettering.**~~ **Done in phase 9.** `blueprint.events.dead_lettered`, - with `reason` and `kept`, next to `blueprint.events.unhandled`. -- ~~**Cache names are not namespace-scoped**~~ -- **done twice.** First by prefixing the - partition (`AgentScopedCache`), then properly in phase 8b step 5, which keys the registry on - `(namespace, name)` and gives each agent its own directory and Redis prefix; the lens is - deleted, and with it the hole that framework code reaching `Component.shared_registry` - directly still got the shared store. The deployment constraint that argued for one shared - backend still holds and is still honoured: an agent's store is a *subdirectory* of - `cache.cache_dir`, so a group still needs exactly one writable mount. What remains open is - migration -- **the key layout changed twice**, so an application upgrading with a persistent - redis cache or a mounted disk cache sees its old entries as absent. A cold cache rather than - an error, and it must be said in the migration guide (phase 10), for both hops. -- ~~**The cache documentation is wrong about the endpoints**~~ -- **done in step 9 part 3.** - The four overlapping documents became one, rewritten against the code: the three real endpoints - with their `?name=` and their 503/404 split, the per-agent `/api//cache/*` paths, and the - synchronous interface every old example awaited. Writing it turned up a 500 in - `GET /cache/stats`, fixed in the same commit. -- **`size` in the cache statistics counts the TTL metadata entries.** The disk backend stores a - parallel `:ttl` entry beside every value, and `get_stats()["size"]` is the raw key count -- so a - cache holding two values reports `size: 4`, exactly double. `list_values` and `list_namespaces` - already filter those entries out; `size` does not. Documented as it is rather than changed, - because a reported metric is somebody's dashboard: the fix is to count filtered keys, and it - wants a decision rather than a drive-by. -- **The examples are not migrated, by decision (2026-09-08).** Note that phase 8b changes what - blocks them: `AgentRegistration` is deleted, and passing instances (`with_rest_api(MonitorApi())`) - stays legal standalone -- it is refused only when a builder is collected into a group. So the - examples keep working untouched, and converting them is only needed if they are to be *grouped*. - Asked - whether to convert one project's `main.py` as proof, the user chose not to touch the examples - part-way through the changes, and to revisit them when the integration tests are written -- - where two real example projects grouped into one process would be a better test of C1 and C5 - than a fixture written for the purpose. So the "only `main.py` differs" claim currently lives - in `test_agent_registration.py` rather than in the tree, and the examples keep passing - instances (`with_rest_api(MonitorApi())`), which `AgentRegistration` refuses -- converting them - is part of that later work, not a prerequisite for it. -- **Local NATS and Dapr integration environment.** **Now tracked in its own document:** - `docs/plans/2026-09-11-broker-integration-tests.md` holds the plan, the running record and - the chores, and its step 0 settled #80 -- `tests/integration/` was not run by CI and sat at - 29 failures, so nothing added there would have meant anything. The original text follows, - because it is the list of what only a real broker can settle. - Everything above is covered by unit tests with - mocked transports. Once the feature is implemented, stand both brokers up locally (compose file - plus a CI job) and cover the behaviour that only a real broker exhibits: queue-group distribution - across replicas, ack/nak/term and redelivery after `ack_wait`, JetStream durable survival across - reconnect, the shutdown drain acknowledging in-flight work, `filter_subjects` behaviour on a - durable that already exists, and the Dapr sidecar actually fetching the discovery document and - delivering to `/events/{topic}`. Depends on the unit/integration split in #80 being settled first, - since `tests/integration/` is currently not run by CI at all. P3 adds several items that only a - real broker can settle: whether `subscribe_bind` against a shared durable actually distributes - across replicas, whether widening a live stream's subjects behaves as expected, what the server - does with an `add_consumer` whose config differs from an existing durable, and whether the - delivery count read from `msg.metadata.num_delivered` lines up with `max_deliver` the way the - dead-letter trigger assumes. Add to that list: **what a queue - group does when one agent's subjects overlap** -- a wildcard plus a literal it covers, both in the - same group, both matching one message. `nats-server` is expected to merge subscriptions by queue - name across matching nodes and deliver once (to either callback, non-deterministically), which - would also end the double dispatch such a pair caused before P1. If it does not merge, the agent - receives the event twice and P2 acks both copies as ordinary work, so the answer changes what P2 - has to handle. P5's in-process claim adds two that no unit test reaches: whether - `diskcache-rs` file locking actually makes `add` atomic across separate processes sharing a - volume, and whether Redis `SET NX` holds up under real contention from several replicas firing in - the same instant. P5 adds two more: whether a `CronJob` publishing to the scheduler's - subject is in fact delivered to exactly one replica through the queue group, and what a - `CronJob` restart or a missed `startingDeadlineSeconds` actually produces -- both modes are - at-least-once, so the answer decides whether an event-mode scheduler needs `idempotency_enabled` - on by default in the generated settings. -- **The two design questions in spec sec. 13** that change the shape rather than the parameters: 20 - or 100 agents, and whether the 4 GB host budget is real. -- **There is no `LICENSE` file.** `README.md` links to one twice -- a badge and the closing line - -- and `pyproject.toml` carries the MIT classifier, but no licence text has ever been committed. - Found by step 9 part 2's reference guard and listed in its `KNOWN_GAPS`, because adding a - licence is a legal artefact and somebody's decision rather than a documentation fix. Whoever - settles it removes that entry, which a guard case then requires. -- **#80** -- the failing example tests and the unenforced test split. -- **The "no agents resolved" message omits a route that works.** It says to mount a group file - *and* name it with `BLUEPRINT_GROUP`, or to set `BLUEPRINT_AGENTS` -- but `_read_group_file` - takes the sole group when a mounted file declares exactly one and `BLUEPRINT_GROUP` is unset, so - the message asks for a variable the reader may not need. A `src/` change, and the only part of - this still open: the migration step it was found alongside is fixed above, and the docs now say - to set `BLUEPRINT_GROUP` regardless, which makes the message's advice sound rather than - complete. -- **A `BLUEPRINT_GROUP_CONFIG` pointing at a directory fails as if nothing were mounted.** - `_group_file_path` returns it, `path.is_file()` is false (`group_config.py:250`), and the reader - gets "no agents were resolved" -- naming neither the directory nor the fact that a directory is - not a file it can read. Cheap to fix and a plausible mistake now that one file per group is - documented; deliberately not folded into a documentation change. -- ~~**Breaking change #12 was missing from the list: `Component.shared_config` → - `Component._shared_config`.**~~ **Closed.** Found during a real compatibility pass against - a consuming project's test suite: its `conftest.py` reset - shared state between test cases via `Component.shared_config = None`, which is a silent no-op - under the rename described above -- the real state lives on `_shared_config` now -- so - `Component.configure()`'s "already set" guard tripped starting from the second test in the run, - 16 of 27 tests failing, with nothing in the error naming this rename. The rename itself was - correct and already reasoned through above; only its absence from the numbered breaking-changes - list was the gap. Added as breaking change 12 in `CHANGELOG.md`'s `[0.9.0]` entry, with the - one-line fix (`Component.reset_shared_state()` in place of the old assignment). +Still open (the closed ones, and their history, are in `git log`): + +- **Pre-existing integration failure:** `test_acknowledgement_lifecycle.py::TestARetryableFailureComesBack::test_the_broker_counts_it_as_a_redelivery` + fails on the unchanged code too: the retryable failure is nak'd at once, so all `max_deliver` + attempts are spent before the test reads `num_redelivered`. The test's premise needs revisiting. +- **Broker-test gap -- overlapping subjects in one queue group:** a wildcard plus a literal it covers + on one client is expected to be merged by the server into one delivery; not yet verified against + a real broker (referenced from `NATSClient`'s docstring). +- **`test_three_replicas_run_one_tick` was flaky once** (2026-09-24); likely the disk cache's + non-atomic takeover of an expired claim. Not investigated. +- **A grouped scheduler's trigger path repeats the agent** (`/api/orders/scheduler/orders_nightly_scheduler/trigger`). +- **Spec amendments owed:** C4 (a degraded transport is paused, not closed), C2 (the metric reader + cannot be shared across providers), the root's role under `readiness_policy`, phase 7's ambiguity + is a WARNING rather than an error. `readiness_policy = "any"` has no acceptance criterion. +- **The tick subject `.scheduler.` is provisional** (subject taxonomy unratified, + spec sec. 13). +- **Dedup and tick claims are unbounded on disk** (logical expiry only); the dedup TTL is delegated + to the deployment (guidance: `nats_ack_wait * nats_max_deliver`). +- **The dead-letter subject has no consumer;** draining it is an operational task. +- **`get_stats()["size"]` double-counts** the disk backend's TTL entries. +- **Spec sec. 13's shape questions** (20 or 100 agents; whether the 4 GB host budget is real). +- **Group-file diagnostics:** the "no agents resolved" message omits the sole-group route, and a + `BLUEPRINT_GROUP_CONFIG` pointing at a directory is reported as nothing mounted. + +Closed since they were listed, for readers following older references: the four isolation routes +(see `tests/unit/agents/test_agent_isolation.py`), the broker integration tests +(`docs/plans/2026-09-11-broker-integration-tests.md`, #80), the latch that never released, the +scaffold's settings and secrets files, the Windows console crash, the examples' migration, and the +missing `LICENSE`. From 7e4764c2bf5b3b2bfa5a5b31daf7a4ad0396beb4 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:14:46 +0200 Subject: [PATCH 102/133] fix(dedup,logs): keep the dedup marker only when acknowledged; no payload or secret in logs Steps 1 and 2 (B1, M11, B2, S4, S8, N3): the marker is released on any BaseException from dispatch and when post-dispatch processing fails, and only by the delivery that won the claim. Validation failures are logged as loc: type only, a Dapr reason is a HandlerError's or the exception's type name, _Link hides url and connect_options from repr, connection logs go through _describe_error. Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 22 +++ ...26-08-28-multi-agent-grouping-changelog.md | 17 +++ .../docs/concepts/event-processing.md | 7 + .../agents/clients/io/nats_client.py | 28 ++-- src/blueprint/agents/handler/handler_chain.py | 76 +++++++---- src/blueprint/agents/io/api/eventing/dapr.py | 19 ++- src/blueprint/agents/models/errors.py | 24 +++- .../eventing/event_processing_service.py | 72 ++++++---- tests/unit/agents/clients/TESTS.md | 2 +- .../agents/clients/io/test_nats_client.py | 69 ++++++++++ tests/unit/agents/handler/TESTS.md | 2 +- .../unit/agents/handler/test_handler_chain.py | 68 ++++++++- tests/unit/agents/io/TESTS.md | 2 +- .../unit/agents/io/api/eventing/test_dapr.py | 29 +++- tests/unit/agents/models/TESTS.md | 3 +- tests/unit/agents/models/test_errors.py | 36 +++++ tests/unit/agents/services/TESTS.md | 2 +- .../eventing/test_event_processing_service.py | 129 ++++++++++++++++++ 18 files changed, 531 insertions(+), 76 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e8d997c..a72ee02e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,28 @@ ### Fixed +- **With deduplication on, an event cut off by `nats_handler_timeout` is no longer lost.** The run + is cancelled and nak'd, but the dedup marker was released only for an `Exception`, and + cancellation is not one. The redelivery found the marker, was skipped as a duplicate and + acknowledged, and the event was never processed. The same happened to a handler that swallowed + the cancellation, to a run cancelled by a shutdown, and to a failure after the handler returned + (a scalar return value that is not a valid `HandlerResult`). A delivery now keeps its marker only + when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the + redelivery acknowledged unrun; now the redelivery runs to completion. + +- **Logs and Dapr answers no longer carry payload values or credentials.** A delivery that is not a + valid CloudEvent was logged with pydantic's rendering of the error, which quotes every offending + input value: under Dapr (`Discarding unparseable delivery`), under NATS (`Discarding unparseable + message`, also in 0.8) and for a malformed inner event of a `com.dapr.event.sent` envelope, which + was additionally logged in full when it had no `type`. These lines now name each field and error + type only (`body.id: string_type`). The Dapr answer for an exception that is not a `HandlerError` + carries its type name as `reason` (`"ValueError"`), no longer its text; a `HandlerError`'s + `reason` is unchanged. The NATS connection lines (a failed attempt, a permanent failure, an error + on a named connection) redact the URL and the connection's password, token and nkey seed, and the + permanent-failure line no longer adds a traceback. Measured with a placeholder secret in the + payload, against JetStream and the Dapr endpoint: before, it was in 1 to 4 log records per + scenario and in the Dapr answer; now in none. + - **`/health/ready` no longer waits for a running health poll.** The cached answer was read under the lock the poll holds while it awaits every check, so a slow check -- a NATS connect up to its 10 s timeout -- delayed every readiness probe with it. Measured with a 4 s check: up to 3.9 s per probe diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index d4e01838..fbeea7d2 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -125,6 +125,23 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a `docs/plans/2026-10-15-named-connections-step6-inventory.md`); `asbs validate` checks the NATS keys; `examples/site_readings` shows two named connections end to end. +**PR #96 review fixes** (`2026-10-16-pr96-review-fixes.md`). +- Step 1, dedup bracket (B1, M11): a delivery keeps its dedup marker only when it is acknowledged. + The chain releases on any `BaseException` from dispatch (a handler timeout or shutdown is a + `CancelledError`); `EventProcessingService.process_event` releases in a `finally` unless the result + was settled and no cancellation is pending (a handler that swallowed it). Only the delivery that + won the claim releases (`CLAIMED_CONTEXT_KEY`), so a duplicate never drops the first delivery's + marker. Measured on JetStream (`nats_handler_timeout = 0.5`, disk cache): timeout, swallowed + cancellation and a scalar return each lost the event before (redelivery skipped and acked), and + run to completion on redelivery now; a real duplicate is still skipped. +- Step 2, leaks in logs and responses (B2, S8, S4, N3): `describe_validation_errors` (`models/errors.py`) + renders a validation failure as `loc: type` only, used by the Dapr and NATS unparseable-payload lines + and the inner Dapr event's errors (no longer logged where raised, raised `from None`); a Dapr reason + is a `HandlerError`'s or the exception's type name; `_Link` hides `url` and `connect_options` from + `repr`; the default and named connection lines go through `_describe_error`. Measured with a + placeholder secret (JetStream, Dapr endpoint with the sidecar mock): in the logs and the answer + before, in neither now. A handler's own exception text is still logged as it is, by design. + **Measured against a real broker** (`tests/integration`, NATS 2.10 with JetStream, plus an accounts broker): acknowledgement exactly once, redelivery after `ack_wait`, concurrent runs, heartbeat, run timeout, reconnect with resubscription, named connections without permission diff --git a/src/blueprint/agent_generator/docs/concepts/event-processing.md b/src/blueprint/agent_generator/docs/concepts/event-processing.md index 26ad76e2..eaf4081c 100644 --- a/src/blueprint/agent_generator/docs/concepts/event-processing.md +++ b/src/blueprint/agent_generator/docs/concepts/event-processing.md @@ -165,6 +165,13 @@ at-least-once contract as a handler that raises; the alternative is an event mar whose output was never sent. If deduplication is enabled, the marker for the inbound event is released, so the redelivery is not skipped as a duplicate. +That holds for every delivery that is not acknowledged, not only for a failed publish: **with +deduplication on, a delivery keeps its marker only when it ends in an `ack`.** A handler that +raises, a run cut off by `nats_handler_timeout` or by a shutdown -- including a handler that +catches the cancellation and returns anyway -- and a return value that cannot be turned into +results all release the marker before the delivery is nak'd. A duplicate never releases the marker +it ran into: that marker belongs to the first delivery. + **A result's event id is derived, not random:** a UUIDv5 over the agent, the inbound event's `source` and `id`, the result's `event_type` and its position in the list. A redelivery therefore republishes each result under the same id -- including results an earlier attempt had already sent diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index ce7fc13b..a9831cbf 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -22,12 +22,13 @@ from nats.errors import NoRespondersError from nats.js.errors import APIError, NotFoundError from opentelemetry.metrics import CallbackOptions, Counter, Observation +from pydantic import ValidationError from ...component.namespace import ROOT_LABEL, ROOT_NAMESPACE from ...deployment import UNGROUPED_LABEL, UNKNOWN_POD_LABEL, deployment_group, pod_identity from ...io.telemetry.providers import agent_meter from ...models.api import ComponentHealth -from ...models.errors import DeliveryDisposition, DeliveryRevokedError, disposition_for +from ...models.errors import DeliveryDisposition, DeliveryRevokedError, describe_validation_errors, disposition_for from ...models.events import CloudEvent from ..client_base import DeliveryCallback from .io_client_base import IOClientBase, subject_is_covered_by, validate_publish_subject, validate_subject_segment @@ -187,8 +188,10 @@ class _Link: name: str = "" """``""`` for the agent's default connection, configured through ``nats_url`` and friends.""" - url: str = "" - connect_options: dict[str, Any] = field(default_factory=dict) + # Neither is rendered by repr (S4): connect_options holds password, token and nkey seed, and + # a nats_url may carry user:pass@. A traceback or debugger printing a link prints its repr. + url: str = field(default="", repr=False) + connect_options: dict[str, Any] = field(default_factory=dict, repr=False) connection_name: str = "" nats_client: NatsClient | None = None js: JetStreamContext | None = None @@ -656,7 +659,7 @@ def _permission_violations(self) -> Counter: @staticmethod def _describe_error(link: _Link, exc: BaseException) -> str: - """``exc`` as one short line for the readiness payload: the URL redacted, no credential of the link in it.""" + """``exc`` as one short line for the readiness payload and the link's log lines: the URL redacted, no credential of the link in it.""" text = f"{type(exc).__name__}: {exc}" if link.url: text = text.replace(link.url, redact_url(link.url)) @@ -894,7 +897,7 @@ async def _run_named_link(self, binding: _Binding) -> None: binding.link.name, attempt, delay, - exc, + binding.last_error, ) await asyncio.sleep(delay) @@ -946,7 +949,7 @@ async def on_error(error: Exception) -> None: for binding in self._named: if binding.link is link and not binding.subscriptions_ready: binding.last_error = self._describe_error(link, error) - logger.error("Agent '%s': error on named connection '%s': %s", agent, link.name, error) + logger.error("Agent '%s': error on named connection '%s': %s", agent, link.name, self._describe_error(link, error)) link.nats_client = await nats.connect( link.url, @@ -1967,8 +1970,13 @@ def _decode_message(msg: Any, topic: str) -> CloudEvent[Any] | None: try: event_data = json.loads(msg.data.decode()) return CloudEvent(**event_data) + except ValidationError as ex: + # Where and how it failed, not str(ex): that embeds the payload's values (B2). + logger.error("Discarding unparseable message on topic '%s': %s", topic, describe_validation_errors(ex.errors())) + return None except Exception as ex: - logger.error("Discarding unparseable message on topic '%s': %s", topic, ex) + # JSON, UTF-8 and mapping errors name a position, a byte or a type, not the payload. + logger.error("Discarding unparseable message on topic '%s': %s: %s", topic, type(ex).__name__, ex) return None @staticmethod @@ -2083,7 +2091,7 @@ async def _start_with_retry(self) -> None: self._subscriptions_ready = False if max_retries != -1 and attempt > max_retries: raise - logger.warning("NATSClient attempt %d failed, retrying in %.1fs: %s", attempt, delay, e) + logger.warning("NATSClient attempt %d failed, retrying in %.1fs: %s", attempt, delay, self._describe_error(self._link, e)) await asyncio.sleep(delay) def _on_retry_done(self, task: asyncio.Task[None]) -> None: @@ -2097,11 +2105,11 @@ def _on_retry_done(self, task: asyncio.Task[None]) -> None: return exc = task.exception() if exc is not None: + # No traceback: its last line is str(exc) again, unredacted (N3). logger.error( "Agent '%s' permanently failed to connect to NATS after exhausting retries: %s", self.namespace or ROOT_LABEL, - exc, - exc_info=exc, + self._describe_error(self._link, exc), ) async def _connect_and_subscribe(self) -> None: diff --git a/src/blueprint/agents/handler/handler_chain.py b/src/blueprint/agents/handler/handler_chain.py index 3b5d8116..37758dcf 100644 --- a/src/blueprint/agents/handler/handler_chain.py +++ b/src/blueprint/agents/handler/handler_chain.py @@ -26,6 +26,15 @@ reach the transport as a returned value, and a third one would invite exactly that. """ +CLAIMED_CONTEXT_KEY = "idempotency_claimed" +"""Context key set to ``True`` while this delivery holds the dedup marker it claimed. + +Only the delivery that claimed a marker may drop it. A duplicate holds none -- the marker it ran +into is the first delivery's, still running or finished -- and releasing on its behalf would +let a third copy dispatch while the first is mid-run. The flag is per delivery for the same +reason the duplicate flag is: ``context`` is the one object that belongs to exactly one. +""" + IDEMPOTENCY_CACHE_NAMESPACE = "idempotency" """Cache namespace holding the seen-event markers, kept away from application data.""" @@ -183,9 +192,13 @@ class HandlerChain(Component): ``idempotency_ttl``. When it is on, the chain claims a marker keyed on the event before dispatching and - skips the dispatch if the marker is already there. A failed dispatch releases the - claim, because the failure naks and the redelivery must be allowed to run: a claim - kept across a failure would turn every retry into a silent no-op. + skips the dispatch if the marker is already there. The marker is kept only by a delivery + that is settled as a success; every other way out releases it, because the delivery is + nak'd or abandoned and the redelivery must be allowed to run: a claim kept across a failure + would turn every retry into a silent no-op that acknowledges. A dispatch that raises -- + including ``CancelledError``, which is how a handler timeout or a shutdown ends a run -- + is released here; what fails after the dispatch is the caller's to release + (:meth:`release`), and ``EventProcessingService.process_event`` does. The claim is the cache's atomic set-if-absent (``CacheService.claim``), so two replicas handed the same event at the same instant cannot both win it -- with a cache they share @@ -280,7 +293,7 @@ async def process(self, event: CloudEvent[Any], context: dict[str, Any]) -> Any if policy is None: policy = self._policy = self._resolve_idempotency_policy() - if not self._claim(event, policy): + if not self._claim(event, policy, context): context[DUPLICATE_CONTEXT_KEY] = True trace.get_current_span().set_attribute("event.duplicate", True) logger.info("Skipping event '%s' from '%s': already processed within the dedup window", event.id, event.source) @@ -288,8 +301,11 @@ async def process(self, event: CloudEvent[Any], context: dict[str, Any]) -> Any try: return await self._dispatch(event, context) - except Exception: - self._release(event, policy) + except BaseException: + # BaseException, not Exception: a handler cut off by nats_handler_timeout, or by a + # shutdown, ends with CancelledError. Kept, the marker would make the nak'd + # redelivery a duplicate that acknowledges, and the event would be lost unrun. + self.release(event, context) raise # ------------------------------------------------------------------ @@ -473,9 +489,12 @@ def _warn_ambiguous_runtime(self, handler: EventHandlerBase, names: list[str]) - # Idempotency (P4) # ------------------------------------------------------------------ - def _claim(self, event: CloudEvent[Any], policy: IdempotencyPolicy) -> bool: + def _claim(self, event: CloudEvent[Any], policy: IdempotencyPolicy, context: dict[str, Any]) -> bool: """Record that this event is being processed, and report whether to dispatch it. + A claim that is won is recorded in ``context`` (:data:`CLAIMED_CONTEXT_KEY`), so that + :meth:`release` drops only a marker this delivery owns. + Returns: ``True`` if the event should be dispatched -- dedup is off, the event cannot be keyed, or this is the first time it has been seen. ``False`` if a marker for it @@ -490,35 +509,38 @@ def _claim(self, event: CloudEvent[Any], policy: IdempotencyPolicy) -> bool: # One atomic set-if-absent, not exists() then set(): between those two calls a second # replica handed the same event passes the check too, and both dispatch. - return self.registry.cache_service.claim( + claimed = self.registry.cache_service.claim( key, {"seen_at": time.time(), "event_type": event.type}, namespace=IDEMPOTENCY_CACHE_NAMESPACE, ttl=policy.ttl, ) + if claimed: + context[CLAIMED_CONTEXT_KEY] = True + return claimed - def release(self, event: CloudEvent[Any]) -> None: - """Drop this event's dedup marker after a failure that happened after a successful dispatch. + def release(self, event: CloudEvent[Any], context: dict[str, Any]) -> None: + """Drop the dedup marker this delivery claimed, so its redelivery is allowed to run. - For the caller that finishes the delivery: a handler result that could not be published - fails the delivery after the chain has already kept its claim, and the redelivery must be - allowed to run the chain again. A no-op when dedup is off. - """ - policy = self._policy - if policy is None: - policy = self._policy = self._resolve_idempotency_policy() - self._release(event, policy) + The claim is taken before dispatch, which is the only point at which it can stop a + concurrent duplicate. So every delivery that is not settled as a success leaves a marker + behind for an event that was *not* processed, and the nak it ends in sends the very same + event back. Without the release that retry is swallowed as a duplicate, acknowledged, + and the event is lost with no handler having finished it. - def _release(self, event: CloudEvent[Any], policy: IdempotencyPolicy) -> None: - """Drop the marker after a failed dispatch so the redelivery is allowed to run. + The chain calls this for a dispatch that raises. The caller that finishes the delivery + calls it for what fails afterwards -- a result that cannot be normalised or published, + a run cancelled after the handler returned. - The claim is taken before dispatch, which is the only point at which it can stop a - concurrent duplicate. That means a dispatch that raises leaves a marker behind for - an event that was *not* processed, and the nak this failure produces sends the very - same event back. Without this the retry would be swallowed as a duplicate and the - message would be lost after ``max_deliver`` attempts that never ran a handler. + A no-op unless ``context`` holds this delivery's claim: dedup off, an event that could + not be keyed, a duplicate (whose marker is the first delivery's), or a claim already + released. That makes it safe to call from every exit path, more than once. + + Args: + event: The event the claim was taken for. + context: The delivery's processing context, which records whether it holds a claim. """ - if not policy.enabled: + if not context.pop(CLAIMED_CONTEXT_KEY, False): return key = self._idempotency_key(event) @@ -526,7 +548,7 @@ def _release(self, event: CloudEvent[Any], policy: IdempotencyPolicy) -> None: return self.registry.cache_service.delete(key, namespace=IDEMPOTENCY_CACHE_NAMESPACE) - logger.debug("Released the dedup marker for event '%s' after a failed dispatch", event.id) + logger.debug("Released the dedup marker for event '%s': the delivery was not settled as a success", event.id) @staticmethod def _idempotency_key(event: CloudEvent[Any]) -> dict[str, str] | None: diff --git a/src/blueprint/agents/io/api/eventing/dapr.py b/src/blueprint/agents/io/api/eventing/dapr.py index c32c3616..c02629ba 100644 --- a/src/blueprint/agents/io/api/eventing/dapr.py +++ b/src/blueprint/agents/io/api/eventing/dapr.py @@ -12,7 +12,13 @@ from ....clients.client_base import DeliveryCallback from ....clients.io.dapr_client import DaprClient from ....component.namespace import ROOT_LABEL, ROOT_NAMESPACE, namespace_of -from ....models.errors import DeliveryDisposition, HandlerError, combined_disposition, disposition_for +from ....models.errors import ( + DeliveryDisposition, + HandlerError, + combined_disposition, + describe_validation_errors, + disposition_for, +) from ....models.events import CloudEvent from ..rest_api_base import RestApiBase from .dapr_response import dapr_status @@ -43,7 +49,8 @@ async def drop_unparseable_delivery(request: Request) -> Response: try: return await handle(request) except RequestValidationError as exc: - logger.error("Discarding unparseable delivery on '%s': %s", request.url.path, exc) + # Where and how it failed, not str(exc): that embeds the payload's values (B2). + logger.error("Discarding unparseable delivery on '%s': %s", request.url.path, describe_validation_errors(exc.errors())) return JSONResponse({"status": dapr_status(DeliveryDisposition.TERM), "reason": "payload is not a CloudEvent"}) return drop_unparseable_delivery @@ -285,7 +292,8 @@ async def publish(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[str, A The reason string reports the first failure. There is one field for it and no way to return several, so it names the first agent that failed rather than concatenating; the - per-agent errors are logged individually above it, each with its agent. + per-agent errors are logged individually above it, each with its agent. It is a + ``HandlerError``'s ``reason``, or for any other exception only its type name. """ agents = self._agents_for(topic) dispositions: list[DeliveryDisposition] = [] @@ -315,7 +323,10 @@ async def publish(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[str, A disposition = disposition_for(exc) dispositions.append(disposition) if reason is None: - reason = exc.reason if isinstance(exc, HandlerError) else str(exc) + # A HandlerError's reason is written for this answer; any other exception's + # text is not, and the sidecar logs the body (S8). Its type is enough there, + # and the full error is in the log line below. + reason = exc.reason if isinstance(exc, HandlerError) else type(exc).__name__ logger.error( "Handler in namespace '%s' failed for event %s on topic '%s', answering %s: %s", namespace or ROOT_LABEL, diff --git a/src/blueprint/agents/models/errors.py b/src/blueprint/agents/models/errors.py index 5ed55ce9..d63e1415 100644 --- a/src/blueprint/agents/models/errors.py +++ b/src/blueprint/agents/models/errors.py @@ -1,7 +1,29 @@ """Handler exceptions, and the delivery disposition each one implies.""" -from collections.abc import Iterable +from collections.abc import Iterable, Mapping, Sequence from enum import Enum +from typing import Any + +_DESCRIBED_ERRORS_LIMIT = 10 + + +def describe_validation_errors(errors: Sequence[Mapping[str, Any]]) -> str: + """One line naming where a payload failed validation and how, never what it contained. + + ``errors`` is what pydantic's ``ValidationError.errors()`` or FastAPI's + ``RequestValidationError.errors()`` returns. Their own rendering, ``str(exc)``, embeds + each offending ``input_value``, and a delivery's payload is customer data that may carry + a credential, so only each entry's ``loc`` and ``type`` are used. The ``msg`` is left out + too: a custom validator's message can quote the value. + + The first ten entries are listed, the rest counted. + """ + described = [ + f"{'.'.join(str(part) for part in error.get('loc', ())) or ''}: {error.get('type', 'unknown')}" + for error in errors[:_DESCRIBED_ERRORS_LIMIT] + ] + remaining = len(errors) - len(described) + return "; ".join(described) + (f" (+{remaining} more)" if remaining > 0 else "") class HandlerError(Exception): diff --git a/src/blueprint/agents/services/eventing/event_processing_service.py b/src/blueprint/agents/services/eventing/event_processing_service.py index c2fea529..dc74d829 100644 --- a/src/blueprint/agents/services/eventing/event_processing_service.py +++ b/src/blueprint/agents/services/eventing/event_processing_service.py @@ -1,5 +1,6 @@ """Unified processing service that coordinates handlers and runtimes.""" +import asyncio import logging from typing import Any from uuid import uuid4 @@ -11,6 +12,7 @@ from ...handler.handler_chain import RUNTIME_NAME_CONTEXT_KEY, HandlerChain from ...io.telemetry.inflight import IN_FLIGHT from ...models import ProcessingResult, ProcessingStatus +from ...models.errors import describe_validation_errors from ...models.events import GenericCloudEvent, HandlerResult, CloudEvent from ..service_base import ServiceBase from .event_publishing_service import EventPublishingService @@ -18,6 +20,19 @@ logger = logging.getLogger(__name__) +def _cancellation_requested() -> bool: + """Report whether the current task has been asked to cancel and has not withdrawn the request. + + How a run that swallowed its cancellation is told apart from one that finished in time: the + handler returned normally, but ``asyncio.timeout`` (``nats_handler_timeout``) or a shutdown + has cancelled the task, and the transport edge will nak or abandon the delivery rather than + acknowledge it. Erring this way is safe -- a delivery acknowledged anyway merely loses its + marker early, which is at-least-once, never a lost event. + """ + task = asyncio.current_task() + return task is not None and task.cancelling() > 0 + + class EventProcessingService(ServiceBase): """Unified service for processing requests through handlers and runtimes. @@ -156,12 +171,20 @@ async def process_event( event = self._unwrap_dapr_event(event) + chain = self._chain_for(namespace) + # The dedup bracket: from the chain's claim to a settled result. Only a delivery that + # gets to the end keeps its marker; every other exit gives it back (chain.release is a + # no-op unless this delivery holds a claim). A finally with a flag rather than an except + # clause, because the exits that lost events were not Exceptions: a handler timeout or a + # shutdown cancels the run, and a handler that swallows that cancellation returns + # normally although the edge naks it. + settled = False try: # Counted around the chain, not around the transport: this is the one place both # transports and the REST path pass through, so one measurement covers all three # and it means "work this agent is doing" rather than "messages it has taken". with IN_FLIGHT.track(namespace): - handler_result: Any | HandlerResult | list[HandlerResult] | None = await self._chain_for(namespace).process(event, context) + handler_result: Any | HandlerResult | list[HandlerResult] | None = await chain.process(event, context) handler_results: list[HandlerResult] = self._extract_handler_results(handler_result) @@ -172,22 +195,14 @@ async def process_event( # 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) - try: - await publisher.publish_handler_event( - event_type=result.event_type, - data=result.data, - metadata=result.metadata or {}, - source_event=event, - new_subject=result.subject or new_subject, - index=index, - ) - except Exception: - # The chain claimed this event's dedup marker and kept it, because the - # dispatch succeeded. The failure below naks the event; left in place, the - # marker would make the redelivery a skipped duplicate, and the result this - # publish failed to send would be lost after all. - self._chain_for(namespace).release(event) - raise + await publisher.publish_handler_event( + event_type=result.event_type, + data=result.data, + metadata=result.metadata or {}, + source_event=event, + new_subject=result.subject or new_subject, + index=index, + ) if handler_result is None: status = ProcessingStatus.NO_HANDLER_FOUND @@ -197,11 +212,15 @@ async def process_event( status = ProcessingStatus.SKIPPED else: status = ProcessingStatus.PROCESSED - return self._build_result(request_id, handler_results, status) + processing_result = self._build_result(request_id, handler_results, status) + settled = not _cancellation_requested() + return processing_result # A failure propagates unlogged: every caller is a transport edge (NATS, Dapr, REST) that # logs it with what it decided to do about it. Logging here too duplicated each failure. finally: + if not settled: + chain.release(event, context) self._correlation_context.reset(correlation_token) async def process_rest_request( @@ -289,7 +308,13 @@ def _build_result( ) def _unwrap_dapr_event(self, event: GenericCloudEvent) -> GenericCloudEvent: - """Unwrap Dapr-wrapped events (com.dapr.event.sent envelope).""" + """Unwrap Dapr-wrapped events (com.dapr.event.sent envelope). + + A malformed inner event raises and is not logged here: the transport edge logs the + failure with its traceback. The errors therefore carry no payload value, and a + validation failure is raised ``from None`` -- its pydantic cause would print every + offending input in that traceback (B2). + """ if event.type != "com.dapr.event.sent": return event @@ -304,13 +329,12 @@ def _unwrap_dapr_event(self, event: GenericCloudEvent) -> GenericCloudEvent: if isinstance(inner_event, dict): if "type" not in inner_event: - logger.error("Inner Dapr event is missing required 'type' field: %s", inner_event) raise RuntimeError("Inner Dapr event is missing required 'type' field") try: return GenericCloudEvent.model_validate(inner_event) except ValidationError as exc: - logger.error("Failed to validate inner Dapr event as CloudEvent: %s", exc) - raise RuntimeError("Inner Dapr event could not be parsed as CloudEvent") from exc + raise RuntimeError( + f"Inner Dapr event could not be parsed as CloudEvent: {describe_validation_errors(exc.errors())}" + ) from None - logger.error("Unexpected inner event type: %s", type(inner_event)) - raise RuntimeError("Unsupported inner Dapr event payload type") + raise RuntimeError(f"Unsupported inner Dapr event payload type: {type(inner_event).__name__}") diff --git a/tests/unit/agents/clients/TESTS.md b/tests/unit/agents/clients/TESTS.md index c4a36d0b..f6322c65 100644 --- a/tests/unit/agents/clients/TESTS.md +++ b/tests/unit/agents/clients/TESTS.md @@ -13,7 +13,7 @@ Test coverage for `src/blueprint/agents/clients/`. | `ai/test_openai_client.py` | `OpenAIClient` | `_is_connected`, `connect` (no-op), `close`, `subscribe`/`publish` (no-ops), `create_model`, `health_check` | | `ai/test_vllm_client.py` | `VLLMClient` | Same shape as OpenAI; additionally verifies `base_url`/`api_key` forwarding to `AsyncOpenAI` | | `io/test_dapr_client.py` | `DaprClient` | `_is_connected`, `connect`/`close`, `subscribe` (no-op), `publish` (URL, headers, routing key, pubsub name), `health_check` | -| `io/test_nats_client.py` | `NATSClient` | `__init__` defaults, `_is_connected` variants, `connect` (Core + JetStream), `close`, `publish`, `health_check` | +| `io/test_nats_client.py` | `NATSClient` | `__init__` defaults, `_is_connected` variants, `connect` (Core + JetStream), `close`, `publish`, `health_check`; no credential or payload value in logs (B2, S4, N3): an unparseable payload logs `loc: type` only, `_Link` and `_Binding` reprs hide URL and connect options, the default connection's failed attempt and permanent failure and a named connection's error and failed attempt log the URL redacted and no password or token. *Later coverage of this file is not itemised here.* | | `io/test_nats_connection_source.py` | `NATSClient` with a `ConnectionSource` | Loading the source, `ConnectionSpec`, planning bindings (claims, hybrid mode, result publishing refused), runs from named connections (run scope, validation, isolation, default connection unchanged), the handler context (`nats_connection`), the delivery attempt (named run: attempt 1 and 2 with the binding's `max_deliver`; default connection: `nats_max_deliver` unset -> `None`; no JetStream metadata -> no attempt; both keys in the handler context), shutdown. *Earlier coverage was not itemised here.* | `IOClientBase` has no logic and has no test file. diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index bbbe9869..b944c0e4 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -18,6 +18,8 @@ ConsumerTuning, JetStreamUnavailableError, NATSClient, + _Binding, + _Link, redact_url, ) from blueprint.agents.models.errors import CriticalHandlerError, InvalidEventError, RetryableHandlerError @@ -2512,3 +2514,70 @@ async def test_the_health_check_never_opens_a_connection_that_subscribes_to_noth await nats_client.connect() mock_connect.assert_not_awaited() start.assert_called_once() + + +_SECRET = "PLACEHOLDER-SECRET-VALUE" + + +class TestNoCredentialOrPayloadInLogs: + """B2/S4/N3 -- what a transport logs about a failure names where and what, never a value or a credential.""" + + async def test_an_unparseable_payload_logs_the_field_not_the_value(self, caplog: pytest.LogCaptureFixture) -> None: + payload = {"specversion": "1.0", "id": {"token": _SECRET}, "source": "s", "type": "t"} + with caplog.at_level("DEBUG"): + event = NATSClient._decode_message(MagicMock(data=json.dumps(payload).encode()), "orders.created") + assert event is None + assert _SECRET not in caplog.text + assert "id: string_type" in caplog.text + + def test_a_link_and_its_binding_render_no_credential(self) -> None: + link = _Link(name="A", url=f"nats://u:{_SECRET}@h:4222", connect_options={"user": "u", "password": _SECRET}) + assert _SECRET not in repr(link) + assert _SECRET not in repr(_Binding(link=link)) + assert "name='A'" in repr(link) + + async def test_a_failed_attempt_of_the_default_connection_is_logged_redacted( + self, nats_client: NATSClient, mock_config: MagicMock, caplog: pytest.LogCaptureFixture + ) -> None: + mock_config.get.side_effect = lambda k, d=None: {"event_client_max_retries": 1, "event_client_retry_delay": 0.0}.get(k, d) + nats_client._nats_url = f"nats://u:{_SECRET}@h:4222" + nats_client._connect_options = {"token": "PLACEHOLDER-TOKEN"} + failure = OSError(f"could not reach nats://u:{_SECRET}@h:4222 with PLACEHOLDER-TOKEN") + nats_client._subscriptions_managed = True + with ( + patch.object(nats_client, "_connect_and_subscribe", new_callable=AsyncMock, side_effect=failure), + caplog.at_level("DEBUG"), + ): + task = asyncio.ensure_future(nats_client._start_with_retry()) + await asyncio.gather(task, return_exceptions=True) + nats_client._on_retry_done(task) + assert "attempt 1 failed" in caplog.text + assert "permanently failed" in caplog.text + assert _SECRET not in caplog.text + assert "PLACEHOLDER-TOKEN" not in caplog.text + + async def test_an_error_on_a_named_connection_is_logged_redacted( + self, nats_client: NATSClient, caplog: pytest.LogCaptureFixture + ) -> None: + link = _Link(name="A", url="nats://h:4222", connect_options={"user": "u", "password": _SECRET}) + connect = AsyncMock(return_value=MagicMock(is_closed=False)) + with patch("blueprint.agents.clients.io.nats_client.nats.connect", connect), caplog.at_level("DEBUG"): + await nats_client._open_named_link(link) + await connect.call_args.kwargs["error_cb"](Exception(f"authorization violation for u/{_SECRET}")) + assert "error on named connection 'A'" in caplog.text + assert _SECRET not in caplog.text + + async def test_a_failed_attempt_of_a_named_connection_is_logged_redacted( + self, nats_client: NATSClient, caplog: pytest.LogCaptureFixture + ) -> None: + binding = _Binding(link=_Link(name="A", url=f"nats://u:{_SECRET}@h:4222")) + failure = OSError(f"could not reach nats://u:{_SECRET}@h:4222") + with ( + patch.object(nats_client, "_open_named_link", new_callable=AsyncMock, side_effect=failure), + patch("blueprint.agents.clients.io.nats_client.asyncio.sleep", new_callable=AsyncMock, side_effect=asyncio.CancelledError), + caplog.at_level("DEBUG"), + pytest.raises(asyncio.CancelledError), + ): + await nats_client._run_named_link(binding) + assert "named connection 'A' attempt 1 failed" in caplog.text + assert _SECRET not in caplog.text diff --git a/tests/unit/agents/handler/TESTS.md b/tests/unit/agents/handler/TESTS.md index bfda2242..4707e165 100644 --- a/tests/unit/agents/handler/TESTS.md +++ b/tests/unit/agents/handler/TESTS.md @@ -9,7 +9,7 @@ Test coverage for `src/blueprint/agents/handler/`. | File | Class under test | What is covered | |---|---|---| | `test_event_handler_base.py` | `EventHandlerBase` | `__init__` stores default and custom priority; `can_handle` delegates to `can_handle_event` (True/False); `handle` passes through `HandlerResult`, `list[HandlerResult]`, dict, and `None` unchanged; `get_published_event_types` default returns `None`; `get_subscribed_topics` default returns `[]`; `__lt__` priority ordering and `sorted()` correctness | -| `test_handler_chain.py` | `HandlerChain` | `on_startup`/`on_shutdown` lifecycle no-ops; `process` with no handlers → `None`; declining handler skipped; accepting handler result returned; handler returning `None` passes to next; chain stops at first non-`None` result; a `HandlerResult.skipped` stops the chain without asking the next handler and logs its reason at INFO with no WARNING; handlers executed in ascending priority order; handler exception re-raised | +| `test_handler_chain.py` | `HandlerChain` | `on_startup`/`on_shutdown` lifecycle no-ops; `process` with no handlers → `None`; declining handler skipped; accepting handler result returned; handler returning `None` passes to next; chain stops at first non-`None` result; a `HandlerResult.skipped` stops the chain without asking the next handler and logs its reason at INFO with no WARNING; handlers executed in ascending priority order; handler exception re-raised; dedup: a failed or cancelled (`CancelledError`) dispatch releases its claim, a duplicate holds no claim and releases nothing, a released claim is released once, `release` with dedup off is a no-op | --- diff --git a/tests/unit/agents/handler/test_handler_chain.py b/tests/unit/agents/handler/test_handler_chain.py index cf75449b..16402b52 100644 --- a/tests/unit/agents/handler/test_handler_chain.py +++ b/tests/unit/agents/handler/test_handler_chain.py @@ -1,11 +1,13 @@ """Unit tests for HandlerChain.""" +import asyncio from typing import Any from unittest.mock import MagicMock import pytest from blueprint.agents.handler.handler_chain import ( + CLAIMED_CONTEXT_KEY, DUPLICATE_CONTEXT_KEY, IDEMPOTENCY_CACHE_NAMESPACE, HandlerChain, @@ -290,16 +292,57 @@ async def can_handle_event(self, event, context): _wire_handlers(mock_registry, [Counting()]) - await chain.process(cloud_event, {}) - chain.release(cloud_event) + context: dict[str, Any] = {} + await chain.process(cloud_event, context) + chain.release(cloud_event, context) await chain.process(cloud_event, {}) assert seen == ["evt-001", "evt-001"] - def test_release_with_dedup_off_is_a_no_op(self, chain: HandlerChain, mock_registry: MagicMock, cloud_event: GenericCloudEvent) -> None: - chain.release(cloud_event) + async def test_release_with_dedup_off_is_a_no_op( + self, chain: HandlerChain, mock_registry: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + _wire_handlers(mock_registry, [StubHandler(result=None)]) + context: dict[str, Any] = {} + await chain.process(cloud_event, context) + + chain.release(cloud_event, context) + + assert CLAIMED_CONTEXT_KEY not in context mock_registry.cache_service.delete.assert_not_called() + async def test_a_duplicate_releases_nothing( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + """B1 -- the marker a duplicate ran into is the first delivery's; dropping it would let a third copy run.""" + cache = _enable_dedup(mock_config, mock_registry) + _wire_handlers(mock_registry, [StubHandler(result=None)]) + first: dict[str, Any] = {} + await chain.process(cloud_event, first) + duplicate: dict[str, Any] = {} + await chain.process(cloud_event, duplicate) + + chain.release(cloud_event, duplicate) + + assert first[CLAIMED_CONTEXT_KEY] is True + assert CLAIMED_CONTEXT_KEY not in duplicate + assert len(cache.store) == 1 + + async def test_a_released_claim_is_released_once( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + """Every exit path may release; only the first one deletes, so a later claim by a redelivery survives.""" + cache = _enable_dedup(mock_config, mock_registry) + _wire_handlers(mock_registry, [StubHandler(result=None)]) + context: dict[str, Any] = {} + await chain.process(cloud_event, context) + chain.release(cloud_event, context) + await chain.process(cloud_event, {}) # the redelivery claims again + + chain.release(cloud_event, context) + + assert len(cache.store) == 1 + async def test_same_event_delivered_twice_dispatches_once( self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent ) -> None: @@ -386,6 +429,23 @@ async def handle_event(self, event, context): await chain.process(cloud_event, {}) assert attempts == ["evt-001", "evt-001"] + async def test_a_cancelled_dispatch_releases_the_claim( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + """B1 -- a handler timeout or a shutdown ends the run with CancelledError, a BaseException.""" + cache = _enable_dedup(mock_config, mock_registry) + + class Cancelled(StubHandler): + async def handle_event(self, event, context): + raise asyncio.CancelledError + + _wire_handlers(mock_registry, [Cancelled()]) + + with pytest.raises(asyncio.CancelledError): + await chain.process(cloud_event, {}) + + assert cache.store == {} + async def test_event_without_a_source_is_dispatched_untracked( self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock ) -> None: diff --git a/tests/unit/agents/io/TESTS.md b/tests/unit/agents/io/TESTS.md index 37b347e2..dd2e1ef9 100644 --- a/tests/unit/agents/io/TESTS.md +++ b/tests/unit/agents/io/TESTS.md @@ -14,7 +14,7 @@ Test coverage for `src/blueprint/agents/io/`. | `api/actuators/health/test_health_cache.py` | `HealthCheckCache` | Initial state, provider updates, all-healthy→UP, one-unhealthy→DOWN, exception→unhealthy component, `get_cache_age_seconds`, `get_cache_info`, start/stop idempotency | | `api/actuators/health/test_sessions_health.py` | `SessionsServiceHealthChecker` | REST API reachable→UP, `RequestError`→DOWN with details, fresh heartbeat→UP, stale heartbeat→DOWN, no heartbeat→UP (unknown), `update_heartbeat` | | `api/eventing/test_event_handling_base.py` | `EventHandlingBase` | `_unwrap_nested_cloud_event` (via mixin) for non-dapr/dict/JSON-string/malformed-JSON/missing-fields/None data; `handle_event` PROCESSED→SUCCESS / other→RETRY; a `SKIPPED` run counted as `blueprint.events.skipped` and not as unhandled, acknowledged, with no WARNING | -| `api/eventing/test_dapr.py` | `DaprEventing` | `publish` PROCESSED→SUCCESS, no-handler→RETRY, `RetryableHandlerError`→RETRY, `InvalidEventError`→DROP, `CriticalHandlerError`→RETRY; `subscribe` returns empty dict | +| `api/eventing/test_dapr.py` | `DaprEventing` | `publish` PROCESSED→SUCCESS, no-handler→RETRY, `RetryableHandlerError`→RETRY, `InvalidEventError`→DROP, `CriticalHandlerError`→RETRY; `subscribe` returns empty dict; the reason for an exception that is not a `HandlerError` is its type name, never its text (S8); an unparseable delivery logs `body.: ` and no input value (B2). *Later coverage of this file is not itemised here.* | | `api/eventing/test_nats.py` | `NatsEventing` | `subscribe`/`publish` delegate to `_client`, RuntimeError when client is None; `on_startup` fetches client, subscribes to handler-declared and config-declared topics, deduplicates, preserves handler-first order, skips when no topics; `_subscribe_to_topic` RuntimeError when client None, calls `_client.subscribe` with topic and callback | | `api/eventing/test_sessions_bus.py` | `SessionsBus` | `on_startup` validation (no config/base_url/agent_id/api_key, already started, task created); `on_shutdown` (no task, running task cancelled); `_convert_to_cloud_event` (type/id/subject/source/data); `_process_job_notification` (no handler logged, `InvalidEventError`→cancel job, cancel failure swallowed, `RetryableHandlerError`→log, 403→invalidate+retry, 403 retry failure propagates `InvalidEventError`, non-403 propagates) | | `api/eventing/test_sessions_startup_resilience.py` | `AppBuilder.build()` with `event_bus = "sessions"` | The lifespan completes and the root REST endpoints answer when the sessions service URL points at a closed port -- a background SSE consumer that cannot connect must not stop the application starting. Offline: the refused port is bound and released on loopback, so the failure is ECONNREFUSED rather than a timeout on every platform. Moved here from `tests/integration/` (#80), where nothing ran it diff --git a/tests/unit/agents/io/api/eventing/test_dapr.py b/tests/unit/agents/io/api/eventing/test_dapr.py index 78e496a2..8b9c9bab 100644 --- a/tests/unit/agents/io/api/eventing/test_dapr.py +++ b/tests/unit/agents/io/api/eventing/test_dapr.py @@ -116,7 +116,21 @@ async def test_unexpected_exception_returns_retry( mock_registry.correlation_context.set.return_value = MagicMock() result = await dapr_eventing.publish("topic", cloud_event) assert result["status"] == "RETRY" - assert result["reason"] == "boom" + assert result["reason"] == "RuntimeError" + + async def test_an_unexpected_exceptions_text_never_reaches_the_sidecar( + self, + dapr_eventing: DaprEventing, + mock_registry: MagicMock, + cloud_event: CloudEvent, + ) -> None: + """S8 -- the reason is the type name; the text may carry anything, and the sidecar logs the body.""" + mock_registry.get_service.return_value.process_event = AsyncMock( + side_effect=ValueError("connect failed for postgres://app:PLACEHOLDER-SECRET-VALUE@db") + ) + mock_registry.correlation_context.set.return_value = MagicMock() + result = await dapr_eventing.publish("topic", cloud_event) + assert result == {"status": "RETRY", "reason": "ValueError"} @pytest.mark.parametrize( ("error", "expected"), @@ -251,6 +265,19 @@ async def test_unparseable_delivery_is_logged( assert "unparseable delivery" in caplog.text + async def test_an_unparseable_delivery_logs_where_it_failed_but_not_the_values( + self, dapr_eventing: DaprEventing, mock_registry: MagicMock, caplog: pytest.LogCaptureFixture + ) -> None: + """B2 -- FastAPI's rendering of the error embeds every offending input value.""" + body = {"specversion": "1.0", "id": {"token": "PLACEHOLDER-SECRET-VALUE"}, "source": "s", "type": "t"} + async with AsyncClient(transport=ASGITransport(app=self._app(dapr_eventing)), base_url="http://sidecar") as client: + with caplog.at_level("DEBUG"): + response = await client.post("/events/orders.created", json=body) + + assert response.json()["status"] == "DROP" + assert "PLACEHOLDER-SECRET-VALUE" not in caplog.text + assert "body.id: string_type" in caplog.text + async def test_a_valid_delivery_is_unaffected( self, dapr_eventing: DaprEventing, mock_registry: MagicMock, cloud_event: CloudEvent, processed_result: ProcessingResult ) -> None: diff --git a/tests/unit/agents/models/TESTS.md b/tests/unit/agents/models/TESTS.md index a97c0821..c3b2dd8a 100644 --- a/tests/unit/agents/models/TESTS.md +++ b/tests/unit/agents/models/TESTS.md @@ -9,6 +9,7 @@ Test coverage for `src/blueprint/agents/models/`. | File | Classes under test | What is covered | |---|---|---| | `test_config.py` | `EventPublishingConfig` | `normalize_topic_mapping`: `TopicConfig` / dict / plain-string / invalid-type values, non-dict mapping → error; `_parse_mapping_string`: empty string, quoted-key string, unquoted-key string (auto-quoting regex), non-brace format → error, malformed brace string → error; `_parse_topic_config_value`: plain string, `map[topic:t]`, `map[topic:t routing_key:rk]`, empty `map[]` → error, missing `topic` entry → error, entry without `:` → error | +| `test_errors.py` | `disposition_for`, `combined_disposition`, `describe_validation_errors` | Disposition per handler error (retryable naks, invalid and critical term, unrecognised naks, subclasses inherit); `describe_validation_errors` names `loc: type` per entry, dots nested locations, never contains an input value (which pydantic's own rendering does), cuts after ten with a count (B2) | | `test_events.py` | `CloudEvent`, `HandlerResult` | `validate_time_format`: Z-suffix, `+00:00` offset, missing timezone → error, non-string → error, default factory produces valid timestamp; `validate_data_exclusivity`: data-only, data_base64-only, neither, both → error; `HandlerResult.skipped`: carries its reason and metadata and reports `is_skipped`, an ordinary result is not skipped, an empty or blank reason is refused, a skip combined with `event_type`, `subject` or `data` is refused | | `test_result.py` | `Evidence`, `AgentOutput` | `Evidence.confidence` ge/le constraints (0.0/1.0 pass, outside → error); `AgentOutput.sort_evidence_by_confidence`: empty list, single item, multiple items sorted descending, already-sorted input | @@ -18,7 +19,7 @@ Test coverage for `src/blueprint/agents/models/`. ### Only files with non-trivial logic are tested -`api.py` and `status.py` contain only Pydantic field definitions with no custom validators or methods. `errors.py` defines three trivial exception subclasses. None of these files have test modules. +`api.py` and `status.py` contain only Pydantic field definitions with no custom validators or methods, and have no test modules. `errors.py` is tested for its functions, not for its trivial exception subclasses. ### Private helpers tested via model construction, not called directly diff --git a/tests/unit/agents/models/test_errors.py b/tests/unit/agents/models/test_errors.py index 99ba6508..07e8cfe6 100644 --- a/tests/unit/agents/models/test_errors.py +++ b/tests/unit/agents/models/test_errors.py @@ -1,12 +1,48 @@ """Unit tests for the delivery disposition mapping (spec sec. 7.2).""" +import pytest +from pydantic import ValidationError + from blueprint.agents.models.errors import ( CriticalHandlerError, DeliveryDisposition, InvalidEventError, RetryableHandlerError, + describe_validation_errors, disposition_for, ) +from blueprint.agents.models.events import CloudEvent + +SECRET = "PLACEHOLDER-SECRET-VALUE" + + +def _validation_error(**payload: object) -> ValidationError: + with pytest.raises(ValidationError) as caught: + CloudEvent(**payload) + return caught.value + + +class TestDescribeValidationErrors: + """Only where and what kind of error, never the value: payloads carry customer data and secrets.""" + + def test_names_the_field_and_the_error_type(self) -> None: + error = _validation_error(id={"token": SECRET}, source="s", type="t") + assert describe_validation_errors(error.errors()) == "id: string_type" + + def test_never_contains_the_input_value(self) -> None: + error = _validation_error(id={"token": SECRET}, source=[SECRET], type="t") + assert SECRET in str(error) # what pydantic itself renders, and why this exists + assert SECRET not in describe_validation_errors(error.errors()) + + def test_nested_locations_are_dotted(self) -> None: + assert describe_validation_errors([{"loc": ("body", "data", 0), "type": "missing"}]) == "body.data.0: missing" + + def test_a_long_list_is_cut_with_a_count(self) -> None: + errors = [{"loc": (f"f{index}",), "type": "missing"} for index in range(13)] + described = describe_validation_errors(errors) + assert described.endswith("(+3 more)") + assert "f9: missing" in described + assert "f10" not in described class TestDispositionFor: diff --git a/tests/unit/agents/services/TESTS.md b/tests/unit/agents/services/TESTS.md index 43815038..8fe5a5e7 100644 --- a/tests/unit/agents/services/TESTS.md +++ b/tests/unit/agents/services/TESTS.md @@ -8,7 +8,7 @@ Test coverage for `src/blueprint/agents/services/`. | File | Class under test | What is covered | |---|---|---| -| `eventing/test_event_processing_service.py` | `EventProcessingService` | `_extract_handler_results` (None/HandlerResult/list/dict variants), `_build_result` (message text incl. `Skipped: `, request_id, result list), a skipped run reported as `SKIPPED` and publishing nothing, a list mixing a skip with a real result reported as `PROCESSED` and publishing only the real one, `_unwrap_dapr_event` (passthrough / CloudEvent inner / dict inner / missing type / unexpected type), lifecycle no-ops, `process_rest_request` delegates to `process_event` with correct event shape | +| `eventing/test_event_processing_service.py` | `EventProcessingService` | `_extract_handler_results` (None/HandlerResult/list/dict variants), `_build_result` (message text incl. `Skipped: `, request_id, result list), a skipped run reported as `SKIPPED` and publishing nothing, a list mixing a skip with a real result reported as `PROCESSED` and publishing only the real one, `_unwrap_dapr_event` (passthrough / CloudEvent inner / dict inner / missing type / unexpected type), lifecycle no-ops, `process_rest_request` delegates to `process_event` with correct event shape; the dedup bracket with a real chain and disk cache: a run cut off by `asyncio.timeout`, a run that swallows the cancellation and a return value failing after dispatch all give the marker back (B1, M11), an acknowledged delivery keeps it; an inner Dapr event without `type`, or one failing validation, raises an error that names the field but carries no value, logs nothing itself, and has no pydantic cause in its traceback (B2) | | `eventing/test_event_publishing_service.py` | `EventPublishingService` | `on_startup` wires client and config, `_get_pub_config` raises before startup, `get_topic_for_event_type` / `get_available_event_types`, `publish_event` (topic mapping, explicit topic override, missing mapping raises, sets default source, result shape), `publish_handler_event` (no mapping → skip, loop prevention → skip, normal → publishes), `publish_status_event` type format and delegation | | `infrastructure/test_disk_cache_service.py` | `DiskCacheService` | `set`/`get` (string/dict/list keys, namespace isolation), `delete` (return values), `exists` (before/after set/delete), `clear` (namespace-scoped and full), TTL expiration via mocked `time.time`, `hash` consistency for string/list/dict inputs, `list_namespaces`, `list_values` (content, TTL-entry exclusion, limit), `get_stats` field presence, lifecycle, context-manager protocol, an unwritable cache directory failing with a message that names the path and the options (and keeping the OSError as the cause); `claim` set-if-absent (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, keys and namespaces independent, dict keys hashed consistently, TTL recorded so readers see expiry, a logically expired claim taken over, no TTL never expires, and an unreachable cache failing open) | | `infrastructure/test_redis_cache_service.py` | `RedisCacheService` | Backed by `fakeredis`. `claim` via `SET NX EX` (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, the TTL is applied to the key, namespaces are independent, and an unreachable cache fails open). *The rest of this file's coverage predates this table and is not itemised here.* | 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 12e5455c..5c52f624 100644 --- a/tests/unit/agents/services/eventing/test_event_processing_service.py +++ b/tests/unit/agents/services/eventing/test_event_processing_service.py @@ -1,13 +1,22 @@ """Unit tests for EventProcessingService.""" +import asyncio +import traceback +from pathlib import Path from unittest.mock import AsyncMock, MagicMock import pytest +from pydantic import ValidationError from blueprint.agents.component.namespace import ROOT_NAMESPACE +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.infrastructure.cache_service import DiskCacheService +from tests.unit.agents.handler.conftest import StubHandler + +_SECRET = "PLACEHOLDER-SECRET-VALUE" # --------------------------------------------------------------------------- # _extract_handler_results (static — no instance needed) @@ -118,6 +127,28 @@ def test_dapr_event_with_non_dict_non_event_inner_raises(self, event_processing_ with pytest.raises(RuntimeError, match="Unsupported inner Dapr event payload type"): event_processing_service._unwrap_dapr_event(outer) + def test_an_inner_event_without_type_is_not_logged( + self, event_processing_service: EventProcessingService, caplog: pytest.LogCaptureFixture + ) -> None: + """B2 -- the inner event is the payload; the error is raised, and the caller logs it.""" + outer = GenericCloudEvent(id="outer-1", type="com.dapr.event.sent", source="dapr", data={"id": "inner-1", "token": _SECRET}) + with caplog.at_level("DEBUG"), pytest.raises(RuntimeError) as caught: + event_processing_service._unwrap_dapr_event(outer) + assert _SECRET not in caplog.text + assert _SECRET not in "".join(traceback.format_exception(caught.value)) + + def test_an_invalid_inner_event_names_the_field_but_not_the_value( + self, event_processing_service: EventProcessingService, caplog: pytest.LogCaptureFixture + ) -> None: + """B2 -- pydantic's rendering embeds the input; the caller logs the traceback with its cause chain.""" + outer = GenericCloudEvent( + id="outer-1", type="com.dapr.event.sent", source="dapr", data={"id": {"token": _SECRET}, "type": "t", "source": "s"} + ) + with caplog.at_level("DEBUG"), pytest.raises(RuntimeError, match="id: string_type") as caught: + event_processing_service._unwrap_dapr_event(outer) + assert _SECRET not in caplog.text + assert _SECRET not in "".join(traceback.format_exception(caught.value)) + # --------------------------------------------------------------------------- # Lifecycle @@ -302,3 +333,101 @@ async def test_without_one_an_id_is_made(self, event_processing_service: EventPr await event_processing_service.process_event(GenericCloudEvent(id="e1", type="t", source="s"), context) assert context["request_id"] + + +class TestTheDedupBracket: + """B1, M11 (PR #96) -- a delivery that is not acknowledged gives its dedup marker back. + + The marker is claimed before dispatch and is only right to keep once the delivery is settled + as a success. Every other way out -- a handler timeout or a shutdown cancelling the run, a + failure after the handler returned -- naks or abandons the delivery, and a marker left behind + turns the redelivery into a skipped duplicate that acknowledges: the event is lost with no + handler having finished it. A real chain and a real cache, because the property is "the + marker is not in the cache afterwards", which a mocked chain cannot show. + """ + + KEY = {"id": "e1", "source": "s"} + + @staticmethod + def _wire(mock_registry: MagicMock, mock_config: MagicMock, tmp_path: Path, handler: StubHandler) -> DiskCacheService: + settings = {"idempotency_enabled": True, "idempotency_ttl": 60} + mock_config.get.side_effect = lambda key, default=None: settings.get(key, default) + cache = DiskCacheService(cache_dir=str(tmp_path / "cache")) + mock_registry.has_cache.return_value = True + mock_registry.cache_service = cache + mock_registry.get_event_handler.return_value = [handler] + return cache + + def _marker_held(self, cache: DiskCacheService) -> bool: + return cache.exists(self.KEY, namespace=IDEMPOTENCY_CACHE_NAMESPACE) + + async def test_a_handler_cut_off_by_its_timeout_gives_the_marker_back( + self, event_processing_service: EventProcessingService, mock_registry: MagicMock, mock_config: MagicMock, tmp_path: Path + ) -> None: + """B1 -- ``nats_handler_timeout`` cancels the run with CancelledError, which ``except Exception`` never saw.""" + runs: list[str] = [] + + class SlowOnce(StubHandler): + async def handle_event(self, event, context): + runs.append(event.id) + if len(runs) == 1: + await asyncio.sleep(10) + return HandlerResult(data={}) + + cache = self._wire(mock_registry, mock_config, tmp_path, SlowOnce()) + event = GenericCloudEvent(id="e1", type="t", source="s") + + with pytest.raises(TimeoutError): + async with asyncio.timeout(0.05): + await event_processing_service.process_event(event) + assert not self._marker_held(cache) + + result = await event_processing_service.process_event(event) + assert result.status == ProcessingStatus.PROCESSED + assert runs == ["e1", "e1"] + + async def test_a_handler_that_swallows_the_cancellation_gives_the_marker_back( + self, event_processing_service: EventProcessingService, mock_registry: MagicMock, mock_config: MagicMock, tmp_path: Path + ) -> None: + """B1 -- the run returns normally, but past its limit, and the NATS edge naks it all the same.""" + + class Stubborn(StubHandler): + async def handle_event(self, event, context): + try: + await asyncio.sleep(10) + except asyncio.CancelledError: + pass + return HandlerResult(data={}) + + cache = self._wire(mock_registry, mock_config, tmp_path, Stubborn()) + + async with asyncio.timeout(0.05): + await event_processing_service.process_event(GenericCloudEvent(id="e1", type="t", source="s")) + + assert not self._marker_held(cache) + + async def test_a_return_value_that_fails_after_dispatch_gives_the_marker_back( + self, event_processing_service: EventProcessingService, mock_registry: MagicMock, mock_config: MagicMock, tmp_path: Path + ) -> None: + """M11 -- a scalar return fails HandlerResult validation after the chain kept its claim.""" + cache = self._wire(mock_registry, mock_config, tmp_path, StubHandler(result=5)) + + with pytest.raises(ValidationError): + await event_processing_service.process_event(GenericCloudEvent(id="e1", type="t", source="s")) + + assert not self._marker_held(cache) + + async def test_an_acknowledged_delivery_keeps_the_marker( + self, event_processing_service: EventProcessingService, mock_registry: MagicMock, mock_config: MagicMock, tmp_path: Path + ) -> None: + """The control: a delivery that succeeded keeps its marker, so its redelivery is a duplicate.""" + cache = self._wire(mock_registry, mock_config, tmp_path, StubHandler(result=HandlerResult(data={}))) + event = GenericCloudEvent(id="e1", type="t", source="s") + + await event_processing_service.process_event(event) + assert self._marker_held(cache) + + context: dict = {} + result = await event_processing_service.process_event(event, context) + assert result.status == ProcessingStatus.NO_HANDLER_FOUND + assert context[DUPLICATE_CONTEXT_KEY] is True From 49558b85ddcfce4583dc13fea9dcd49d13ef11aa Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:14:47 +0200 Subject: [PATCH 103/133] chore(naming): generic names for the first consumer's product and subjects Step 3 (B3): the named-connections plan, the accounts broker config, its connection source and three unit tests use acme.agent... The earlier commits of this branch were later rewritten to the same names (D1, revised 2026-10-21). Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/plans/2026-08-28-multi-agent-grouping-changelog.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index fbeea7d2..670adeec 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -141,6 +141,10 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a `repr`; the default and named connection lines go through `_describe_error`. Measured with a placeholder secret (JetStream, Dapr endpoint with the sidecar mock): in the logs and the answer before, in neither now. A handler's own exception text is still logged as it is, by design. +- Step 3, internal naming (B3): the first consumer's product name, subject prefix and module names are + replaced by generic ones (`acme.agent..`, "the first consumer") in the named-connections + plan, the accounts broker config, its connection source and three unit tests. Tree only; the + published history keeps them (D1). The named-connection broker tests pass with the new subjects. **Measured against a real broker** (`tests/integration`, NATS 2.10 with JetStream, plus an accounts broker): acknowledgement exactly once, redelivery after `ack_wait`, concurrent runs, From b46efee72986cdcf9a7ca2281cad0ee318660800 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:14:48 +0200 Subject: [PATCH 104/133] fix(dedup): key the dedup marker on the named connection too Step 1a (T1): the same (source, id) on two named connections is two events; the default connection keeps (source, id). Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 8 +++ ...26-08-28-multi-agent-grouping-changelog.md | 5 ++ .../skills/blueprint-events/SKILL.md | 6 ++- .../docs/components/event-handlers.md | 8 +++ .../docs/concepts/event-processing.md | 4 +- .../docs/reference/configuration-keys.md | 2 +- src/blueprint/agents/handler/handler_chain.py | 23 +++++++-- tests/integration/conftest.py | 23 ++++++--- tests/integration/test_named_connections.py | 37 +++++++++++++- tests/unit/agents/handler/TESTS.md | 2 +- .../unit/agents/handler/test_handler_chain.py | 49 +++++++++++++++++++ 11 files changed, 149 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a72ee02e..d8a4ea2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,14 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **With deduplication on, one named connection's event no longer suppresses another's.** The dedup + key was the event's `source` and `id` only, so the same producer behind two connections -- two data + sources emitting the same ids for different data -- had the second connection's event skipped as a + duplicate and acknowledged. A delivery from a named connection now adds the connection's name to + the key; the default connection keeps the old key, so existing markers still match. Measured on a + broker with one account per connection: before, the second connection's event was skipped; now + both run, and a repeat on the same connection is still skipped. + - **Logs and Dapr answers no longer carry payload values or credentials.** A delivery that is not a valid CloudEvent was logged with pydantic's rendering of the error, which quotes every offending input value: under Dapr (`Discarding unparseable delivery`), under NATS (`Discarding unparseable diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 670adeec..8d83b4d5 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -141,6 +141,11 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a `repr`; the default and named connection lines go through `_describe_error`. Measured with a placeholder secret (JetStream, Dapr endpoint with the sidecar mock): in the logs and the answer before, in neither now. A handler's own exception text is still logged as it is, by design. +- Step 1a, connection isolation (T1): the dedup key adds `nats_connection` for a delivery from a named + connection (the default connection keeps `(source, id)`, no migration); handler-author docs say that + per-data-source state is keyed by that context key. Broker test on the accounts broker: the same + `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B + was skipped. - Step 3, internal naming (B3): the first consumer's product name, subject prefix and module names are replaced by generic ones (`acme.agent..`, "the first consumer") in the named-connections plan, the accounts broker config, its connection source and three unit tests. Tree only; the diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md index 9b0e8d1e..50333fa8 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md @@ -28,8 +28,10 @@ asbs docs components/event-handlers --cat # writing a handler **Delivery is at-least-once.** The same event can reach `handle_event` more than once: a lost ack, a pod restart, a rolling deploy. Either make the service it calls safe to repeat, or set **both** `idempotency_enabled = true` and `idempotency_ttl = `; the framework then skips an event -whose id and source it has already dispatched, within that window. It is off by default on purpose - -only you know whether replaying your side effects is acceptable. +whose id and source it has already dispatched, within that window (per named connection, when the +event came from one). It is off by default on purpose - only you know whether replaying your side +effects is acceptable. State your service keeps per event (an "already ingested" marker, a cache +entry) is keyed by `context.get("nats_connection")` too: each named connection is its own data source. **The handler context tells a JetStream run which attempt it is:** `nats_delivery_attempt` (1-based) and `nats_max_deliver` (`None` when unlimited). Equal means the last attempt: a failure is diff --git a/src/blueprint/agent_generator/docs/components/event-handlers.md b/src/blueprint/agent_generator/docs/components/event-handlers.md index 167bc1f0..bc528b85 100644 --- a/src/blueprint/agent_generator/docs/components/event-handlers.md +++ b/src/blueprint/agent_generator/docs/components/event-handlers.md @@ -165,6 +165,14 @@ under subject-scoped publish permissions, what the broker checked the publisher Nothing in the payload can overwrite a context key. Which deployment-level scope a connection stands for is decided by the connection source (its `validate` and `run_scope` hooks), not by handlers. +**Keep per-data-source state per connection.** Each named connection stands for a data source of its +own, and the same producer behind two of them may emit the same `source` and `id` for different +data. Anything a handler or its service keeps across deliveries -- a cache entry, an "already +ingested" marker, a cursor -- is keyed by `context.get("nats_connection")` as well, or one data +source's event suppresses or overwrites another's. The framework does so for its own state: +deduplication keys on the connection too, results are not published from named connections, dead +letters go out on the connection the event arrived on, and each run has a context of its own. + **The last attempt.** When `nats_delivery_attempt == nats_max_deliver`, a failure of this run is not redelivered -- it is dead-lettered or dropped. A service that keeps work open across attempts (a claimed job, a pending record) can close or hand it off on that attempt instead of leaving it open. diff --git a/src/blueprint/agent_generator/docs/concepts/event-processing.md b/src/blueprint/agent_generator/docs/concepts/event-processing.md index eaf4081c..10fb99d9 100644 --- a/src/blueprint/agent_generator/docs/concepts/event-processing.md +++ b/src/blueprint/agent_generator/docs/concepts/event-processing.md @@ -170,7 +170,9 @@ deduplication on, a delivery keeps its marker only when it ends in an `ack`.** A raises, a run cut off by `nats_handler_timeout` or by a shutdown -- including a handler that catches the cancellation and returns anyway -- and a return value that cannot be turned into results all release the marker before the delivery is nak'd. A duplicate never releases the marker -it ran into: that marker belongs to the first delivery. +it ran into: that marker belongs to the first delivery. The marker is keyed on the event's `source` +and `id`, and on the named connection the event came from, if any: two connections delivering the +same `source` and `id` are two events. **A result's event id is derived, not random:** a UUIDv5 over the agent, the inbound event's `source` and `id`, the result's `event_type` and its position in the list. A redelivery therefore diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 939adb5b..ed3f6ca7 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -141,7 +141,7 @@ effects is acceptable is a property of the product, not of the framework. | Key | Type | Default | Description | |-----|------|---------|-------------| -| `idempotency_enabled` | `bool` | `false` | Skip an event whose `id` and `source` were already dispatched within the window. Requires `idempotency_ttl` and a registered cache (`.with_cache()`); startup fails if either is missing, rather than leaving deduplication silently off. The claim is the cache's atomic set-if-absent, so replicas sharing a cache (Redis, or a disk cache on a shared volume) cannot both dispatch the same event; a per-pod cache deduplicates within that pod only, and a cache error fails open. | +| `idempotency_enabled` | `bool` | `false` | Skip an event whose `id` and `source` were already dispatched within the window -- on the same named connection, when it came from one (each connection is a data source of its own). Requires `idempotency_ttl` and a registered cache (`.with_cache()`); startup fails if either is missing, rather than leaving deduplication silently off. The claim is the cache's atomic set-if-absent, so replicas sharing a cache (Redis, or a disk cache on a shared volume) cannot both dispatch the same event; a per-pod cache deduplicates within that pod only, and a cache error fails open. | | `idempotency_ttl` | `int` | -- | Seconds a processed event is remembered. No default on purpose -- it must outlast the broker's redelivery window (`nats_ack_wait` * `nats_max_deliver` on JetStream, the component's retry policy under Dapr), and a window that expires before the last redelivery looks exactly like deduplication not working. | --- diff --git a/src/blueprint/agents/handler/handler_chain.py b/src/blueprint/agents/handler/handler_chain.py index 37758dcf..b4d89ff6 100644 --- a/src/blueprint/agents/handler/handler_chain.py +++ b/src/blueprint/agents/handler/handler_chain.py @@ -38,6 +38,15 @@ IDEMPOTENCY_CACHE_NAMESPACE = "idempotency" """Cache namespace holding the seen-event markers, kept away from application data.""" +CONNECTION_CONTEXT_KEY = "nats_connection" +"""Context key naming the named connection a delivery arrived on; absent on the default connection. + +Set by the NATS eventing endpoint, and the same value as ``nats_connections.NATS_CONNECTION_CONTEXT_KEY`` +(a test keeps the two equal): the chain reads it without depending on the transport package. A +named connection stands for a data source of its own, so it is part of the dedup key -- two +sources delivering the same producer's ``(source, id)`` are two events, not one (T1). +""" + RUNTIME_CONTEXT_KEY = "runtime" """Context key carrying the ``AgentRuntime`` chosen for this event, when one was. @@ -503,7 +512,7 @@ def _claim(self, event: CloudEvent[Any], policy: IdempotencyPolicy, context: dic if not policy.enabled: return True - key = self._idempotency_key(event) + key = self._idempotency_key(event, context) if key is None: return True @@ -543,7 +552,7 @@ def release(self, event: CloudEvent[Any], context: dict[str, Any]) -> None: if not context.pop(CLAIMED_CONTEXT_KEY, False): return - key = self._idempotency_key(event) + key = self._idempotency_key(event, context) if key is None: return @@ -551,7 +560,7 @@ def release(self, event: CloudEvent[Any], context: dict[str, Any]) -> None: logger.debug("Released the dedup marker for event '%s': the delivery was not settled as a success", event.id) @staticmethod - def _idempotency_key(event: CloudEvent[Any]) -> dict[str, str] | None: + def _idempotency_key(event: CloudEvent[Any], context: dict[str, Any]) -> dict[str, str] | None: """Build the dedup key, or ``None`` if the event cannot be identified. Keyed on ``source`` as well as ``id``. The CloudEvents specification requires an @@ -559,6 +568,11 @@ def _idempotency_key(event: CloudEvent[Any]) -> dict[str, str] | None: emit id ``"1"``, and keying on the id alone would let one agent's event suppress another's. Sent as a dict because the cache sorts a dict by key before hashing it, which a list of the two values would not preserve. + + A delivery from a named connection adds the connection's name + (:data:`CONNECTION_CONTEXT_KEY`): each connection is a data source of its own, and the + same producer behind two of them emits the same ids for different data (T1). The default + connection keeps the two-part key, so markers written before this change still match. """ event_id = str(getattr(event, "id", "") or "").strip() source = str(getattr(event, "source", "") or "").strip() @@ -569,6 +583,9 @@ def _idempotency_key(event: CloudEvent[Any]) -> dict[str, str] | None: source, ) return None + connection = context.get(CONNECTION_CONTEXT_KEY) + if connection: + return {"id": event_id, "source": source, "connection": str(connection)} return {"id": event_id, "source": source} def _resolve_idempotency_policy(self) -> IdempotencyPolicy: diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 2f9d6f87..f2d6b57f 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -225,16 +225,13 @@ def integration_config( "nats_use_jetstream = true\n" # Well above any handler here, and short enough that a test asserting *no* redelivery can # afford to wait the whole window out. Unset, it would be the server's default (30 s). - "nats_ack_wait = 2.0\n" - "nats_max_deliver = 3\n" + "nats_ack_wait = 2.0\n" "nats_max_deliver = 3\n" # The client retries the initial connect forever by default, which turns "the broker # refused this subscription" into a test that hangs instead of one that fails. - "event_client_max_retries = 2\n" - "event_client_retry_delay = 0.5\n\n" + "event_client_max_retries = 2\n" "event_client_retry_delay = 0.5\n\n" # Where a handler's HandlerResult goes. Without a mapping for the event type, # EventPublishingService logs "no topic mapping found" and publishes nothing at all. - f'[default.event_publishing.topic_mapping."{OUTBOUND_EVENT_TYPE}"]\n' - f'topic = "{outbound_subject}"\n', + f'[default.event_publishing.topic_mapping."{OUTBOUND_EVENT_TYPE}"]\n' f'topic = "{outbound_subject}"\n', encoding="utf-8", ) config = Config(settings_files=["settings.toml"], root_path=str(tmp_path)) @@ -388,11 +385,21 @@ def settings_group(tmp_path: Path) -> GroupFactory: @asynccontextmanager async def factory( - settings: str, agents: dict[str, type], *, named: int = 0, ready_timeout: float = 20.0, apps: list[Any] | None = None + settings: str, + agents: dict[str, type], + *, + named: int = 0, + ready_timeout: float = 20.0, + apps: list[Any] | None = None, + cache: bool = False, ) -> AsyncIterator[dict[str, NATSClient]]: (tmp_path / "settings.toml").write_text(settings, encoding="utf-8") config = Config(settings_files=["settings.toml"], root_path=str(tmp_path)) - group = AgentGroup("integration", {name: AppBuilder().with_handler(handler) for name, handler in agents.items()}) + # cache: each agent gets the cache dedup claims in (idempotency_enabled). + group = AgentGroup( + "integration", + {name: (AppBuilder().with_cache() if cache else AppBuilder()).with_handler(handler) for name, handler in agents.items()}, + ) try: app = group.assemble(config) if apps is not None: diff --git a/tests/integration/test_named_connections.py b/tests/integration/test_named_connections.py index c70820aa..b2624327 100644 --- a/tests/integration/test_named_connections.py +++ b/tests/integration/test_named_connections.py @@ -93,10 +93,12 @@ async def provision(tenants: list[str], agents: dict[str, list[str]]) -> None: await admin.close() -async def publish(accounts_url: str, prefix: str, tenant: str, subject: str, *, claimed_tenant: str | None = None) -> str: +async def publish( + accounts_url: str, prefix: str, tenant: str, subject: str, *, claimed_tenant: str | None = None, event_id: str | None = None +) -> str: user, password = ADMINS[tenant] admin = await nats.connect(accounts_url, user=user, password=password) - event_id = str(uuid.uuid4()) + event_id = event_id or str(uuid.uuid4()) body = {"specversion": "1.0", "id": event_id, "type": subject, "source": "integration-test", "tenantid": claimed_tenant or tenant} await admin.jetstream().publish(f"{subject_prefix_for(prefix, tenant)}{subject}", json.dumps(body).encode()) await admin.close() @@ -196,6 +198,37 @@ async def termed() -> bool: await poll_until(termed, timeout=10, description="the rejected delivery to be settled for good") + async def test_dedup_keeps_the_connections_apart( + self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str, tmp_path: Any + ) -> None: + """T1 -- the same producer's (source, id) on two connections is two events; a repeat on one is a duplicate.""" + agent = f"risk_{subject_prefix}" + await operator(["A", "B"], {agent: ["risk.>"]}) + runs: list[dict[str, Any]] = [] + # The agent's own section: the group's root has no cache to claim in. + extra = ( + f"[default.{agent}]\n" + "idempotency_enabled = true\n" + "idempotency_ttl = 600\n" + f"[default.{agent}.cache]\n" + f'cache_dir = "{(tmp_path / "cache").as_posix()}"\n' + ) + async with settings_group( + settings(accounts_url, subject_prefix, ["A", "B"], extra), {agent: recording_handler(["risk.>"], runs)}, named=2, cache=True + ): + shared_id = str(uuid.uuid4()) + for tenant in ("A", "B", "A"): + await publish(accounts_url, subject_prefix, tenant, "risk.created", event_id=shared_id) + await wait_until(lambda: len(runs) == 2, timeout=10, description="one run per connection") + + async def settled() -> bool: + infos = [await consumer_info(accounts_url, subject_prefix, tenant, agent) for tenant in ("A", "B")] + return [info.delivered.stream_seq for info in infos] == [2, 1] and all(info.num_ack_pending == 0 for info in infos) + + await poll_until(settled, timeout=10, description="every delivery acked, the repeat on A included") + + assert sorted(run["connection"] for run in runs) == ["A", "B"] + class TestTheAttemptOnANamedConnection: async def test_a_redelivery_shows_attempt_2_and_the_bindings_limit( diff --git a/tests/unit/agents/handler/TESTS.md b/tests/unit/agents/handler/TESTS.md index 4707e165..1760e808 100644 --- a/tests/unit/agents/handler/TESTS.md +++ b/tests/unit/agents/handler/TESTS.md @@ -9,7 +9,7 @@ Test coverage for `src/blueprint/agents/handler/`. | File | Class under test | What is covered | |---|---|---| | `test_event_handler_base.py` | `EventHandlerBase` | `__init__` stores default and custom priority; `can_handle` delegates to `can_handle_event` (True/False); `handle` passes through `HandlerResult`, `list[HandlerResult]`, dict, and `None` unchanged; `get_published_event_types` default returns `None`; `get_subscribed_topics` default returns `[]`; `__lt__` priority ordering and `sorted()` correctness | -| `test_handler_chain.py` | `HandlerChain` | `on_startup`/`on_shutdown` lifecycle no-ops; `process` with no handlers → `None`; declining handler skipped; accepting handler result returned; handler returning `None` passes to next; chain stops at first non-`None` result; a `HandlerResult.skipped` stops the chain without asking the next handler and logs its reason at INFO with no WARNING; handlers executed in ascending priority order; handler exception re-raised; dedup: a failed or cancelled (`CancelledError`) dispatch releases its claim, a duplicate holds no claim and releases nothing, a released claim is released once, `release` with dedup off is a no-op | +| `test_handler_chain.py` | `HandlerChain` | `on_startup`/`on_shutdown` lifecycle no-ops; `process` with no handlers → `None`; declining handler skipped; accepting handler result returned; handler returning `None` passes to next; chain stops at first non-`None` result; a `HandlerResult.skipped` stops the chain without asking the next handler and logs its reason at INFO with no WARNING; handlers executed in ascending priority order; handler exception re-raised; dedup: a failed or cancelled (`CancelledError`) dispatch releases its claim, a duplicate holds no claim and releases nothing, a released claim is released once, `release` with dedup off is a no-op; the same event on two named connections is two events and a claim is released under its own connection's key, the default connection keeps the two-part key, and the chain's connection context key equals the NATS endpoint's (T1) | --- diff --git a/tests/unit/agents/handler/test_handler_chain.py b/tests/unit/agents/handler/test_handler_chain.py index 16402b52..dff12bfb 100644 --- a/tests/unit/agents/handler/test_handler_chain.py +++ b/tests/unit/agents/handler/test_handler_chain.py @@ -6,8 +6,10 @@ import pytest +from blueprint.agents.clients.io.nats_connections import NATS_CONNECTION_CONTEXT_KEY from blueprint.agents.handler.handler_chain import ( CLAIMED_CONTEXT_KEY, + CONNECTION_CONTEXT_KEY, DUPLICATE_CONTEXT_KEY, IDEMPOTENCY_CACHE_NAMESPACE, HandlerChain, @@ -407,6 +409,53 @@ async def can_handle_event(self, event, context): assert seen == ["test-source", "other-source"] + async def test_the_same_event_on_two_named_connections_is_not_a_duplicate( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + """T1 -- each connection is a data source of its own; one must not suppress another's event.""" + _enable_dedup(mock_config, mock_registry) + seen: list[str] = [] + + class Counting(StubHandler): + async def can_handle_event(self, event, context): + seen.append(context[CONNECTION_CONTEXT_KEY]) + return False + + _wire_handlers(mock_registry, [Counting()]) + + await chain.process(cloud_event, {CONNECTION_CONTEXT_KEY: "A"}) + await chain.process(cloud_event, {CONNECTION_CONTEXT_KEY: "B"}) + await chain.process(cloud_event, {CONNECTION_CONTEXT_KEY: "A"}) + + assert seen == ["A", "B"] + + async def test_a_named_connections_claim_is_released_under_its_own_key( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + cache = _enable_dedup(mock_config, mock_registry) + _wire_handlers(mock_registry, [StubHandler(result=None)]) + on_a: dict[str, Any] = {CONNECTION_CONTEXT_KEY: "A"} + await chain.process(cloud_event, on_a) + await chain.process(cloud_event, {CONNECTION_CONTEXT_KEY: "B"}) + + chain.release(cloud_event, on_a) + + assert list(cache.store) == [_StubCache._key({"id": "evt-001", "source": "test-source", "connection": "B"})] + + async def test_the_default_connection_keeps_the_two_part_key( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + """Markers written before connections were part of the key still match after an upgrade.""" + cache = _enable_dedup(mock_config, mock_registry) + _wire_handlers(mock_registry, [StubHandler(result=None)]) + + await chain.process(cloud_event, {}) + + assert list(cache.store) == [_StubCache._key({"id": "evt-001", "source": "test-source"})] + + def test_the_context_key_is_the_one_the_nats_endpoint_sets(self) -> None: + assert CONNECTION_CONTEXT_KEY == NATS_CONNECTION_CONTEXT_KEY + async def test_failed_dispatch_releases_the_claim( self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent ) -> None: From f2d9932f6cded7958e320fba2e9b485514b5ae09 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:14:49 +0200 Subject: [PATCH 105/133] fix(nats): a JetStream reconnect re-checks broker state instead of resubscribing Step 4 (M1, N4, N11): nats-py replays _subs itself, so _on_reconnected only re-checks stream and consumers; a paused agent naks JetStream deliveries; the first connect is bounded. Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 20 +++ ...26-08-28-multi-agent-grouping-changelog.md | 9 ++ .../agents/clients/io/nats_client.py | 69 ++++++++-- tests/unit/agents/clients/TESTS.md | 2 +- .../agents/clients/io/test_nats_client.py | 128 ++++++++++++++++-- 5 files changed, 205 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d8a4ea2b..fe4fd835 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,26 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **A JetStream agent no longer gains a second subscription per topic on every reconnect.** nats-py + restores every subscription itself after a reconnect, the JetStream ones included; the client + subscribed again on top, and the extra subscriptions were unknown to pause, drain and shutdown. A + degraded agent therefore kept consuming through them: after one broker restart, a paused agent ran + all 10 of 10 events sent to it. A reconnect now re-checks the stream and the consumers (recreating + them if the broker lost them) and subscribes nothing. Measured: subscriptions 2 before and 2 after + a restart (4 before the fix), 0 runs while paused, every event run once after a restart and after a + broker that lost its storage. + +- **An agent started before its broker no longer hangs in startup.** With reconnects unlimited (the + default, `nats_max_reconnect_attempts = -1`) nats-py retried the first connect inside itself for + ever, so startup never returned and `event_client_max_retries` was never consulted. The first + connect now fails after two attempts, the retry loop takes over, and reconnects of an established + connection stay unlimited. An agent that connects while it is paused re-evaluates its health at once + instead of one health interval later. Measured: startup returned after 5.6 s (before: not within + 120 s), and the agent consumed once the broker was up. + +- **A delivery that reaches a paused agent is nak'd instead of run** (JetStream), so it redelivers to a + healthy replica; Core NATS, which cannot nak, still handles what the drain lets through. + - **With deduplication on, one named connection's event no longer suppresses another's.** The dedup key was the event's `source` and `id` only, so the same producer behind two connections -- two data sources emitting the same ids for different data -- had the second connection's event skipped as a diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 8d83b4d5..df977184 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,15 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 4, JetStream reconnect (M1, N4, N11): `_on_reconnected` re-checks stream and consumers + (`_ensure_broker_state`) instead of subscribing again; the message handler naks a JetStream delivery + while paused; the first `nats.connect()` is bounded (`_first_connect_attempts`) and the configured + count is set on the connection afterwards; a connect while paused requests a health refresh. Live + (NATS 2.10, `/connz?subs=1`): broker restart -- 2 subscriptions before and after (control: 4), each of + 20 events run once; restart then pause -- 0 of 10 events run (control: 10); broker without storage + replaced -- stream and consumers recreated, 20 of 20 run once; no broker at startup -- startup + returns in 5.6 s and the agent consumes after the broker comes up (control: no return within 120 s). + Integration suite: 60 passed, 3 skipped (Redis not started). - Step 3, internal naming (B3): the first consumer's product name, subject prefix and module names are replaced by generic ones (`acme.agent..`, "the first consumer") in the named-connections plan, the accounts broker config, its connection source and three unit tests. Tree only; the diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index a9831cbf..f26e12b1 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -276,8 +276,9 @@ class NATSClient(IOClientBase): keeps the pod out of service rotation until then. On disconnect the NATS library fires ``_on_disconnected``, which clears - the ready flag. On reconnect ``_on_reconnected`` re-subscribes (JetStream - only — Core NATS re-subscribes automatically) and restores the flag. + the ready flag. On reconnect the NATS library replays every subscription, + JetStream push subscriptions included; ``_on_reconnected`` re-checks the + JetStream stream and consumers (never subscribes again) and restores the flag. One connection per namespace ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1722,13 +1723,14 @@ async def connect(self) -> None: self._connect_options = self._resolve_connect_options(self._nats_url) nats_url = redact_url(self._nats_url) self._connection_name = self._resolve_connection_name() + # Unlimited by default: with 5 attempts 2 s apart, an outage of about 10 s closed the + # connection for good (review finding #10). _on_closed restarts it either way. + reconnect_attempts = self.config.get("nats_max_reconnect_attempts", -1) try: self._nats_client = await nats.connect( self._nats_url, name=self._connection_name or None, - # Unlimited by default: with 5 attempts 2 s apart, an outage of about 10 s closed the - # connection for good (review finding #10). _on_closed restarts it either way. - max_reconnect_attempts=self.config.get("nats_max_reconnect_attempts", -1), + max_reconnect_attempts=self._first_connect_attempts(reconnect_attempts), reconnect_time_wait=self.config.get("nats_reconnect_time_wait", 2), connect_timeout=10, disconnected_cb=self._on_disconnected, @@ -1736,6 +1738,8 @@ async def connect(self) -> None: closed_cb=self._on_closed, **self._connect_options, ) + # Read by nats-py on every reconnect attempt, so from here on the configured count governs. + self._nats_client.options["max_reconnect_attempts"] = reconnect_attempts self._client = self._nats_client self._use_jetstream = self.config.get("nats_use_jetstream", False) self._publish_via_jetstream = self._resolve_publish_mode() @@ -1754,6 +1758,19 @@ async def connect(self) -> None: e.add_note(f"while connecting to NATS at {nats_url}") raise + @staticmethod + def _first_connect_attempts(reconnect_attempts: int) -> int: + """``max_reconnect_attempts`` for the first ``nats.connect()``: bounded, whatever reconnects may do (N11). + + nats-py applies the count to the first connect as well, and with an unlimited count it + retries a broker that is not there inside ``nats.connect()`` for ever: the call never + returns, so neither the retry loop (``event_client_max_retries``, its WARNING per attempt) + nor the health poll that connects before startup gets an answer, and startup hangs. The + first connect therefore fails after two attempts and the retry loop decides what follows; + a positive configured count is kept as it is. + """ + return reconnect_attempts if reconnect_attempts > 0 else 1 + def _log_connected(self, mode: str, nats_url: str) -> None: """Log the connection; a standalone agent's line is the one it has always logged.""" if self.namespace: @@ -2123,6 +2140,9 @@ async def _connect_and_subscribe(self) -> None: # Paused while this loop was still connecting: stay connected, subscribe nothing. # resume_consumption() subscribes over this connection if the agent is released. logger.info("Agent '%s' connected while degraded; not subscribing", self.namespace or ROOT_LABEL) + # The pause may have been this connection's absence -- an agent that started before its + # broker. Re-evaluate now, so it resumes on this connect rather than one health interval later. + self._request_health_refresh("the default connection is up while the agent is paused") return await self._subscribe_all() @@ -2451,6 +2471,13 @@ def _message_handler( """ async def message_handler(msg: Any) -> None: + if self._consumption_paused and self._settles(binding): + # A degraded agent runs nothing (C4). What reaches it anyway -- a delivery still in + # the buffer while the pause waits for a connection change to finish, before it + # can drain -- is nak'd at once, so it redelivers to a healthy replica (N4). Core + # NATS cannot nak; its buffered messages run, as the drain lets them. + await self._settle(msg, DeliveryDisposition.NAK, msg.subject, self._peek_event_id(msg), binding) + return resolved = topic if topic is not None else self._bound_topic(binding, msg) if resolved is None: await self._settle(msg, DeliveryDisposition.TERM, msg.subject, None, binding) @@ -2472,6 +2499,15 @@ async def message_handler(msg: Any) -> None: return message_handler + @staticmethod + def _peek_event_id(msg: Any) -> str | None: + """The event id of a delivery that is settled without being decoded, for its log line; ``None`` if unreadable.""" + try: + event_id = json.loads(msg.data.decode()).get("id") + except Exception: + return None + return event_id if isinstance(event_id, str) else None + async def _acquire_run(self, binding: _Binding, slot_key: str) -> Release: """Wait until ``binding`` may start a run; return what frees it. @@ -2911,13 +2947,26 @@ async def _on_reconnected(self) -> None: self._request_health_refresh("the default connection is back while the agent is paused") return if self._use_jetstream and self._topic_callbacks: - # JetStream durable consumers do not survive reconnects; re-subscribe manually. - # Core NATS re-subscribes automatically via the client library. - self._subscriptions.clear() + # nats-py replays every subscription it holds on a reconnect -- the JetStream push + # ones too, and their deliver subject is fixed (_DELIVER.) -- so delivery + # resumes by itself. Subscribing again added a second subscription per topic that no + # pause, drain or close knew of (M1). What a reconnect can lose is broker state: a + # broker restarted without storage, a failover to a peer that never had the stream. + # That is re-checked; nothing is re-subscribed. try: - await self._subscribe_all() + await self._ensure_broker_state() except Exception as e: - logger.error("NATSClient failed to re-establish JetStream subscriptions after reconnect: %s", e) + logger.error( + "Agent '%s': re-checking the JetStream stream and consumers after a reconnect failed: %s", + self.namespace or ROOT_LABEL, + self._describe_error(self._link, e), + ) return self._subscriptions_ready = True logger.info("NATSClient subscriptions ready after reconnect") + + async def _ensure_broker_state(self) -> None: + """Provision the stream and every consumer this client's subscriptions deliver from, subscribing nothing.""" + await self._provision_stream() + for topic in self._topic_callbacks: + await self._ensure_consumer(topic, self._durables.get(topic) or self._durable_for(topic)) diff --git a/tests/unit/agents/clients/TESTS.md b/tests/unit/agents/clients/TESTS.md index f6322c65..75b117d4 100644 --- a/tests/unit/agents/clients/TESTS.md +++ b/tests/unit/agents/clients/TESTS.md @@ -13,7 +13,7 @@ Test coverage for `src/blueprint/agents/clients/`. | `ai/test_openai_client.py` | `OpenAIClient` | `_is_connected`, `connect` (no-op), `close`, `subscribe`/`publish` (no-ops), `create_model`, `health_check` | | `ai/test_vllm_client.py` | `VLLMClient` | Same shape as OpenAI; additionally verifies `base_url`/`api_key` forwarding to `AsyncOpenAI` | | `io/test_dapr_client.py` | `DaprClient` | `_is_connected`, `connect`/`close`, `subscribe` (no-op), `publish` (URL, headers, routing key, pubsub name), `health_check` | -| `io/test_nats_client.py` | `NATSClient` | `__init__` defaults, `_is_connected` variants, `connect` (Core + JetStream), `close`, `publish`, `health_check`; no credential or payload value in logs (B2, S4, N3): an unparseable payload logs `loc: type` only, `_Link` and `_Binding` reprs hide URL and connect options, the default connection's failed attempt and permanent failure and a named connection's error and failed attempt log the URL redacted and no password or token. *Later coverage of this file is not itemised here.* | +| `io/test_nats_client.py` | `NATSClient` | `__init__` defaults, `_is_connected` variants, `connect` (Core + JetStream), `close`, `publish`, `health_check`; no credential or payload value in logs (B2, S4, N3): an unparseable payload logs `loc: type` only, `_Link` and `_Binding` reprs hide URL and connect options, the default connection's failed attempt and permanent failure and a named connection's error and failed attempt log the URL redacted and no password or token; a reconnect under JetStream subscribes nothing again (nats-py replays `_subs`) and re-checks stream and consumers, a failed re-check leaves it unready (M1); a paused agent naks a JetStream delivery without running it and still runs a buffered Core NATS one (N4); the first connect is bounded while reconnects stay unlimited, and fails against a closed port instead of hanging (N11). *Later coverage of this file is not itemised here.* | | `io/test_nats_connection_source.py` | `NATSClient` with a `ConnectionSource` | Loading the source, `ConnectionSpec`, planning bindings (claims, hybrid mode, result publishing refused), runs from named connections (run scope, validation, isolation, default connection unchanged), the handler context (`nats_connection`), the delivery attempt (named run: attempt 1 and 2 with the binding's `max_deliver`; default connection: `nats_max_deliver` unset -> `None`; no JetStream metadata -> no attempt; both keys in the handler context), shutdown. *Earlier coverage was not itemised here.* | `IOClientBase` has no logic and has no test file. diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index b944c0e4..22a42f41 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -1534,21 +1534,56 @@ async def test_reconnected_callback_no_op_without_managed_subscriptions(self, co await connected_nats_client._on_reconnected() assert connected_nats_client.subscriptions_ready is False - async def test_reconnected_resubscribes_jetstream_topics(self, connected_nats_client: NATSClient, mock_nats_jetstream: tuple) -> None: - mock_nc, mock_js = mock_nats_jetstream - connected_nats_client._nats_client = mock_nc - connected_nats_client._client = mock_nc - connected_nats_client._use_jetstream = True - connected_nats_client._subscriptions_managed = True - connected_nats_client._subscriptions_ready = False - connected_nats_client._topic_callbacks = {"topic.a": AsyncMock(), "topic.b": AsyncMock()} + @staticmethod + def _jetstream_client(client: NATSClient, mock_nats_jetstream: tuple) -> MagicMock: + """A managed JetStream client whose broker connection replays its subscriptions, as nats-py does.""" + mock_nc, _ = mock_nats_jetstream + mock_nc._subs = {} + client._nats_client = mock_nc + client._client = mock_nc + client._use_jetstream = True + client._subscriptions_managed = True + client._subscriptions_ready = False + client._topic_callbacks = {"topic.a": AsyncMock(), "topic.b": AsyncMock()} + return mock_nc + + async def test_a_reconnect_subscribes_nothing_again_under_jetstream( + self, connected_nats_client: NATSClient, mock_nats_jetstream: tuple + ) -> None: + """M1 -- nats-py replays every subscription in ``_subs``; subscribing again left an orphan per topic. + + The orphan joined the deliver group next to the replayed one, so it took a share of the + deliveries, and no pause, drain or close knew of it. + """ + mock_nc = self._jetstream_client(connected_nats_client, mock_nats_jetstream) + mock_nc._subs = {1: "topic.a (replayed)", 2: "topic.b (replayed)"} - with patch.object(connected_nats_client, "_subscribe_one", new_callable=AsyncMock) as mock_sub: + with ( + patch.object(connected_nats_client, "_subscribe_one", new_callable=AsyncMock) as subscribe_one, + patch.object(connected_nats_client, "_provision_stream", new_callable=AsyncMock) as provision, + patch.object(connected_nats_client, "_ensure_consumer", new_callable=AsyncMock) as ensure_consumer, + ): await connected_nats_client._on_reconnected() - assert mock_sub.await_count == 2 + subscribe_one.assert_not_awaited() + assert len(mock_nc._subs) == 2, "only nats-py's replayed subscriptions" + provision.assert_awaited_once() + assert [call.args[0] for call in ensure_consumer.await_args_list] == ["topic.a", "topic.b"] assert connected_nats_client.subscriptions_ready is True + async def test_a_failed_recheck_after_a_reconnect_leaves_it_unready( + self, connected_nats_client: NATSClient, mock_nats_jetstream: tuple, caplog: pytest.LogCaptureFixture + ) -> None: + self._jetstream_client(connected_nats_client, mock_nats_jetstream) + with ( + patch.object(connected_nats_client, "_provision_stream", new_callable=AsyncMock, side_effect=OSError("stream gone")), + caplog.at_level("ERROR"), + ): + await connected_nats_client._on_reconnected() + + assert connected_nats_client.subscriptions_ready is False + assert "re-checking the JetStream stream and consumers after a reconnect failed" in caplog.text + # --------------------------------------------------------------------------- # asyncio import needed by the non-blocking subscribe test @@ -2332,6 +2367,48 @@ async def _js_delivery_handler(nats_client: NATSClient, mock_config: MagicMock, return mock_nc.jetstream().subscribe_bind.await_args.kwargs["cb"] +class TestAPausedAgentRunsNothing: + """N4 -- a delivery that reaches a paused agent is nak'd under JetStream, never run.""" + + async def test_a_jetstream_delivery_is_nakd_without_running( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + ran: list[str] = [] + + async def callback(event: CloudEvent, subject: str) -> None: + ran.append(event.id) + + handler = await _js_delivery_handler(nats_client, mock_config, mock_nats_jetstream, callback) + nats_client._consumption_paused = True + msg = _delivery(cloud_event) + + await handler(msg) + await asyncio.gather(*list(nats_client._runs), return_exceptions=True) + + assert ran == [] + msg.nak.assert_awaited_once() + msg.ack.assert_not_awaited() + + async def test_a_core_nats_message_in_the_buffer_still_runs( + self, nats_client: NATSClient, mock_nats_core: MagicMock, cloud_event: CloudEvent + ) -> None: + """Core NATS cannot nak; what the drain lets through is handled, as before.""" + ran: list[str] = [] + + async def callback(event: CloudEvent, subject: str) -> None: + ran.append(event.id) + + nats_client._nats_client = mock_nats_core + nats_client._client = mock_nats_core + await nats_client._subscribe_one("orders.created", callback) + handler = _until_settled(nats_client, mock_nats_core.subscribe.await_args.kwargs["cb"]) + nats_client._consumption_paused = True + + await handler(MagicMock(subject="orders.created", data=json.dumps(dict(cloud_event)).encode())) + + assert ran == [cloud_event.id] + + class TestConcurrentRuns: """Deliveries run as tasks of their own, up to nats_max_concurrent_runs per binding.""" @@ -2473,11 +2550,38 @@ class TestAClosedConnectionComesBack: async def test_reconnect_attempts_are_unlimited_by_default(self, nats_client: NATSClient, mock_config: MagicMock) -> None: base = mock_config.get.side_effect mock_config.get.side_effect = lambda key, default=None: default if key == "nats_max_reconnect_attempts" else base(key, default) - with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock) as mock_connect: + connection = MagicMock(options={}) + with patch("blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock, return_value=connection) as mock_connect: await nats_client.connect() - assert mock_connect.await_args.kwargs["max_reconnect_attempts"] == -1 + assert connection.options["max_reconnect_attempts"] == -1, "reconnects of the established connection" assert mock_connect.await_args.kwargs["closed_cb"] == nats_client._on_closed + async def test_the_first_connect_is_bounded_even_when_reconnects_are_not(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """N11 -- nats-py applies the count to the first connect too; unlimited, it never returned and startup hung.""" + base = mock_config.get.side_effect + mock_config.get.side_effect = lambda key, default=None: default if key == "nats_max_reconnect_attempts" else base(key, default) + with patch( + "blueprint.agents.clients.io.nats_client.nats.connect", new_callable=AsyncMock, return_value=MagicMock(options={}) + ) as mock_connect: + await nats_client.connect() + assert mock_connect.await_args.kwargs["max_reconnect_attempts"] == 1 + + @pytest.mark.parametrize(("configured", "first"), [(-1, 1), (0, 1), (5, 5)]) + def test_first_connect_attempts(self, configured: int, first: int) -> None: + assert NATSClient._first_connect_attempts(configured) == first + + async def test_a_broker_that_is_not_there_fails_the_first_connect(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """Against a port nobody listens on, connect() raises instead of retrying inside nats-py for ever.""" + base = mock_config.get.side_effect + overrides = {"nats_reconnect_time_wait": 0} + mock_config.get.side_effect = lambda key, default=None: ( + default if key == "nats_max_reconnect_attempts" else overrides.get(key, base(key, default)) + ) + nats_client._nats_url = "nats://127.0.0.1:1" + with pytest.raises(Exception) as caught: + await asyncio.wait_for(nats_client.connect(), timeout=20) + assert not isinstance(caught.value, TimeoutError), "connect() never returned" + async def test_a_closed_connection_restarts_the_retry_loop(self, nats_client: NATSClient) -> None: nats_client._subscriptions_managed = True nats_client._subscriptions_ready = True From 43f808e4a33596aa5e746b1001420e170d261d09 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:14:50 +0200 Subject: [PATCH 106/133] fix(supervisor): retry a failed resume; pause and resume SessionsBus too Step 5 (M2, S18): a failed resume_consumption drops what it made, stays paused and retries with backoff; SessionsBus is a consumer of the supervisor. Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 13 +++ ...26-08-28-multi-agent-grouping-changelog.md | 8 ++ .../docs/concepts/observability.md | 8 +- .../docs/reference/configuration-keys.md | 2 +- .../agents/clients/io/nats_client.py | 80 ++++++++++++++++-- .../actuators/health/namespace_supervisor.py | 28 +++++-- .../agents/io/api/eventing/sessions_bus.py | 72 ++++++++++++++-- tests/unit/agents/clients/TESTS.md | 2 +- .../agents/clients/io/test_nats_client.py | 82 ++++++++++++++++++- tests/unit/agents/io/TESTS.md | 2 +- .../io/api/eventing/test_sessions_bus.py | 73 +++++++++++++++++ 11 files changed, 340 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe4fd835..ae6330d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,19 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **A degraded agent whose resume fails is no longer left off its topics for good.** The supervisor + resumes an agent once, on the transition back to healthy, and a paused NATS client reports + healthy; a failed re-subscribe therefore left the agent paused with every check green, and nothing + tried again. The client now retries in the background -- from `event_client_retry_delay`, doubling + to 60 s, a WARNING per attempt -- drops what a failed attempt subscribed, and stops when the agent + is degraded again or shuts down. Measured: a resume failing on a stream that could not be recreated + consumed again 7 s after the obstacle was removed (before: still paused 36 s later). + +- **`event_bus = "sessions"` agents now stop consuming while degraded (C4).** The sessions job stream + is no transport client, so the supervisor never paused it: a degraded agent kept taking jobs. Its + stream is now closed while it is degraded and reopened when it recovers; a job that reaches it in + between is left pending for a healthy replica. + - **A JetStream agent no longer gains a second subscription per topic on every reconnect.** nats-py restores every subscription itself after a reconnect, the JetStream ones included; the client subscribed again on top, and the extra subscriptions were unknown to pause, drain and shutdown. A diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index df977184..b8cf0111 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,14 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 5, resume retry and C4 for sessions (M2, S18): a failed `resume_consumption` drops the partial + subscriptions, stays paused and retries in a backoff task (cancelled by a pause and by close), a + WARNING per attempt; `SessionsBus` gains `pause_consumption`/`resume_consumption` (stream closed, + a job reaching it left pending) and the supervisor pauses it with the IO clients. Live (JetStream, + health interval 2 s, a switchable check): the agent paused, its stream replaced by one blocking its + subjects, then healthy -- attempts 1-3 failed (1, 2, 4 s apart), resumed 7 s after the blocker was + removed, 5 of 5 events run. Control: one failed resume, still paused 36 s later. Sessions: unit + tests only, no sessions service to run against. - Step 4, JetStream reconnect (M1, N4, N11): `_on_reconnected` re-checks stream and consumers (`_ensure_broker_state`) instead of subscribing again; the message handler naks a JetStream delivery while paused; the first `nats.connect()` is bounded (`_first_connect_attempts`) and the configured diff --git a/src/blueprint/agent_generator/docs/concepts/observability.md b/src/blueprint/agent_generator/docs/concepts/observability.md index 53a0580e..8bd90764 100644 --- a/src/blueprint/agent_generator/docs/concepts/observability.md +++ b/src/blueprint/agent_generator/docs/concepts/observability.md @@ -282,12 +282,16 @@ mechanisms. NATS the agent's subscriptions are drained, which lets already-queued messages finish and acknowledge while new ones go to a healthy replica. Under Dapr the sidecar delivers whatever the application thinks, so the fan-out answers `RETRY` for that agent without dispatching. - The connection is kept open, because a closed client reports itself unhealthy for ever and the + Under `event_bus = "sessions"` the job stream is closed, so the agent's jobs stay pending for a + healthy replica; jobs already running finish. The connection is kept open, because a closed client reports itself unhealthy for ever and the pause could then never lift. 3. **It may take the pod out of rotation**, according to `readiness_policy`. Recovery is the reverse and needs no operator: when the agent's checks pass again, it resumes -consuming and the gauge returns to `1`. +consuming and the gauge returns to `1`. If resuming fails -- under NATS, a stream the broker no +longer has and cannot recreate -- the client retries in the background, backing off from +`event_client_retry_delay` to 60 s, with a WARNING per attempt, until it consumes again or the agent +is degraded once more. The one exception is a startup failure. If a non-critical agent's `on_startup` raises, the process starts without it and that agent is **latched** down -- its components can often still answer a diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index ed3f6ca7..f0651f93 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -40,7 +40,7 @@ Settings for the event bus transport layer. | `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. | | `event_client_drain_timeout` | `float` | `30.0` | Seconds allowed at shutdown for in-flight message handlers to finish before the broker connection is closed. Bounds the whole shutdown sequence, so keep it below the pod's termination grace period. | -| `nats_max_reconnect_attempts` | `int` | `-1` -- unlimited | Reconnect attempts after the broker drops the connection, `nats_reconnect_time_wait` seconds apart. A finite value closes the connection after that many; the client then starts over (connect, then resubscribe). | +| `nats_max_reconnect_attempts` | `int` | `-1` -- unlimited | Reconnect attempts after the broker drops the connection, `nats_reconnect_time_wait` seconds apart. A finite value closes the connection after that many; the client then starts over (connect, then resubscribe). The first connect is bounded either way (two attempts when unlimited): a broker that is not there yet fails it, and `event_client_max_retries` decides what follows. | | `nats_use_jetstream` | `bool` | `false` | Consume through a durable JetStream consumer instead of Core NATS. The keys below apply only when this is `true`. **A declaration, enforced:** with `true`, a server that does not offer JetStream to the account fails the agent -- at startup through the startup failure policy, or, if the broker was unreachable then, when it first connects: the root or a critical agent shuts the process down, a non-critical agent is marked down. There is no fallback to Core NATS. With `false`, the server is not asked; Core NATS works on a JetStream-enabled server too. | | `nats_stream_name` | `str` | `"EVENTS"` | Stream the durable consumers are created on. The framework creates it if it is missing, and widens an existing one to cover every subscribed subject plus the dead-letter subject; it never removes a subject. | | `nats_durable_name` | `str` | `"-durable"` | Name of the durable consumer. Derived from the topic by default, with `.`, `*`, `>` and whitespace replaced by `_` because NATS rejects them in a consumer name. A client that belongs to a namespace prefixes it (`"--durable"`), so two agents subscribing to the same topic get a consumer each. Setting it explicitly is only valid with a single subscribed topic: a durable filters one subject, and under a namespace it must be scoped per namespace or every namespace binds to the same consumer. | diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index f26e12b1..8325ad2c 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -88,6 +88,10 @@ class JetStreamUnavailableError(RuntimeError): """How often a named connection retries after the broker refused it a permission: a missing grant does not heal in seconds, so retrying at the normal pace would only fill the log (spec 7.9).""" +RESUME_RETRY_MAX_DELAY = 60.0 +"""The longest wait between two attempts of a resume that keeps failing (M2): the delay doubles from +``event_client_retry_delay`` up to this.""" + _CURRENT_BINDING: contextvars.ContextVar["_Binding | None"] = contextvars.ContextVar("blueprint_nats_binding", default=None) """The named binding a run's delivery arrived on; set inside that run's own task only, so ``publish`` can refuse a revoked run (dynamic-subscriptions spec 7.5).""" @@ -387,6 +391,7 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: self._queue_group: str = "" self._subscriptions_managed: bool = False self._retry_task: asyncio.Task[None] | None = None + self._resume_retry: asyncio.Task[None] | None = None self._max_concurrent_runs: RunLimit | None = None self._pool = RunPool() self._pairs_registered = 0 @@ -1842,6 +1847,8 @@ async def pause_consumption(self) -> None: The connection stays open. See :meth:`IOClientBase.pause_consumption` for why closing it would make the pause permanent, and :meth:`health_check` for the other half of that. """ + # A resume still retrying is given up: the agent is degraded again, and the next resume starts afresh. + await self._cancel_resume_retry() if self._consumption_paused: return self._consumption_paused = True @@ -1867,9 +1874,13 @@ async def pause_consumption(self) -> None: async def resume_consumption(self) -> None: """Re-subscribe this agent's topics after its health checks pass again. - Nothing is retried here: a failure to re-subscribe leaves the client paused, and the - next health poll finds the agent healthy again and calls this again. That is the whole - retry, and it is bounded by the poll interval rather than by a loop of its own. + **A failed re-subscribe is retried here, in the background** (M2, plan D2). The + supervisor resumes on the transition to healthy only, and a paused client reports + healthy, so nothing would ever call this again: the agent stayed off its topics with + every check green. The retry backs off from ``event_client_retry_delay`` up to + :data:`RESUME_RETRY_MAX_DELAY` with a WARNING per failed attempt, leaves readiness as it + is, and is cancelled by a pause and by :meth:`close`. Subscriptions a failed attempt + made are dropped first, so a retry never leaves duplicates. """ if not self._consumption_paused: return @@ -1885,14 +1896,67 @@ async def resume_consumption(self) -> None: # cleared flag by itself. self._start_retry_task() return + delay = float(self.config.get("event_client_retry_delay", 5.0)) + if not await self._try_resume(1, delay): + self._resume_retry = asyncio.ensure_future(self._retry_resume(delay)) + self._resume_retry.add_done_callback(self._on_resume_retry_done) + + async def _try_resume(self, attempt: int, next_delay: float) -> bool: + """Subscribe the default connection's topics once; on failure drop what was made and stay paused.""" try: await self._subscribe_all() except Exception as exc: + await self._drop_subscriptions() self._consumption_paused = True - logger.error("Agent '%s' could not resume consuming: %s", self.namespace or ROOT_LABEL, exc, exc_info=True) - return + logger.warning( + "Agent '%s' could not resume consuming (attempt %d), retrying in %.1fs: %s", + self.namespace or ROOT_LABEL, + attempt, + next_delay, + self._describe_error(self._link, exc), + ) + return False + self._consumption_paused = False self._subscriptions_ready = True logger.info("Agent '%s' resumed consuming: %d subscription(s) restored", self.namespace or ROOT_LABEL, len(self._subscriptions)) + return True + + async def _retry_resume(self, delay: float) -> None: + """Retry :meth:`_try_resume` with a doubling delay until it succeeds; cancelled by a pause or close.""" + attempt = 1 + while not self._closing: + await asyncio.sleep(delay) + attempt += 1 + delay = min(delay * 2, RESUME_RETRY_MAX_DELAY) + if await self._try_resume(attempt, delay): + # The named connections' loops saw the flag back up after the first failure and stopped. + async with self._change_lock: + self._start_named_links() + return + + async def _cancel_resume_retry(self) -> None: + """Stop a resume still retrying, if one is.""" + retry, self._resume_retry = self._resume_retry, None + if retry is not None and not retry.done(): + retry.cancel() + with contextlib.suppress(asyncio.CancelledError): + await retry + + def _on_resume_retry_done(self, task: asyncio.Task[None]) -> None: + """Report a resume retry that died of anything but its cancellation, naming the agent.""" + if not task.cancelled() and task.exception() is not None: + logger.error( + "Agent '%s': retrying the resume failed: %s", + self.namespace or ROOT_LABEL, + self._describe_error(self._link, task.exception()), # type: ignore[arg-type] + ) + + async def _drop_subscriptions(self) -> None: + """Unsubscribe whatever the default connection holds, so the next attempt starts from none.""" + for sub in self._subscriptions: + with contextlib.suppress(Exception): + await sub.unsubscribe() + self._subscriptions.clear() async def close(self) -> None: """Stop consuming, let in-flight handlers finish, then close the connection. @@ -1918,6 +1982,7 @@ async def close(self) -> None: self._retry_task.cancel() with contextlib.suppress(asyncio.CancelledError): await self._retry_task + await self._cancel_resume_retry() for task in list(self._named_tasks.values()): if not task.done(): task.cancel() @@ -2132,10 +2197,7 @@ def _on_retry_done(self, task: asyncio.Task[None]) -> None: async def _connect_and_subscribe(self) -> None: await self.connect() # Clean up any partial subscriptions from a previous failed attempt - for sub in self._subscriptions: - with contextlib.suppress(Exception): - await sub.unsubscribe() - self._subscriptions.clear() + await self._drop_subscriptions() if self._consumption_paused: # Paused while this loop was still connecting: stay connected, subscribe nothing. # resume_consumption() subscribes over this connection if the agent is released. diff --git a/src/blueprint/agents/io/api/actuators/health/namespace_supervisor.py b/src/blueprint/agents/io/api/actuators/health/namespace_supervisor.py index 890d9388..02b1a4f0 100644 --- a/src/blueprint/agents/io/api/actuators/health/namespace_supervisor.py +++ b/src/blueprint/agents/io/api/actuators/health/namespace_supervisor.py @@ -29,17 +29,27 @@ import logging from collections.abc import Callable, Collection, Iterable, Mapping, Sequence +from typing import Protocol from opentelemetry.metrics import CallbackOptions, Observation -from .....clients.io.io_client_base import IOClientBase from .....component.namespace import ROOT_LABEL, ROOT_NAMESPACE from .....component.registry import Registry from .....deployment import deployment_group, pod_identity from .....io.telemetry.providers import agent_meter +from ...eventing.sessions_bus import SessionsBus logger = logging.getLogger(__name__) + +class Consumer(Protocol): + """What the supervisor pauses and resumes: a transport client, or the sessions job stream.""" + + async def pause_consumption(self) -> None: ... + + async def resume_consumption(self) -> None: ... + + NAMESPACE_UP_GAUGE = "blueprint.namespace.up" """``1`` while an agent is serving, ``0`` once it is not. The C7 signal. @@ -205,7 +215,7 @@ async def _set(self, namespace: str, healthy: bool, reason: str) -> None: async def _pause_consumption(self, namespace: str) -> None: """Stop this agent taking events, so they redeliver to a replica that can serve them.""" - for client in self._clients(namespace): + for client in self._consumers(namespace): try: await client.pause_consumption() except Exception as exc: # pragma: no cover - defensive @@ -213,17 +223,23 @@ async def _pause_consumption(self, namespace: str) -> None: async def _resume_consumption(self, namespace: str) -> None: """Let this agent take events again.""" - for client in self._clients(namespace): + for client in self._consumers(namespace): try: await client.resume_consumption() except Exception as exc: # pragma: no cover - defensive logger.error("Agent '%s' could not resume consuming: %s", namespace or ROOT_LABEL, exc, exc_info=True) - def _clients(self, namespace: str) -> list[IOClientBase]: - """This agent's transport clients, and nobody else's. + def _consumers(self, namespace: str) -> list[Consumer]: + """What takes this agent's events -- its transport clients and its sessions job stream -- and nobody else's. + + The sessions stream is no transport client (``event_bus = "sessions"`` wires no + ``IOClientBase``), and left out it was the one consumer C4 never stopped (S18). The namespace is passed explicitly even for the root, where it looks redundant: on the application's registry an *omitted* namespace means every namespace, so leaving it out would pause every agent in the process the moment the root was degraded. """ - return self._registry.get_io_clients(namespace=namespace or ROOT_NAMESPACE) + namespace = namespace or ROOT_NAMESPACE + consumers: list[Consumer] = list(self._registry.get_io_clients(namespace=namespace)) + consumers.extend(self._registry.get_components_by_type(SessionsBus, namespace=namespace)) + return consumers diff --git a/src/blueprint/agents/io/api/eventing/sessions_bus.py b/src/blueprint/agents/io/api/eventing/sessions_bus.py index a158023c..a28ae669 100644 --- a/src/blueprint/agents/io/api/eventing/sessions_bus.py +++ b/src/blueprint/agents/io/api/eventing/sessions_bus.py @@ -95,6 +95,59 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: self._reconnect_delay: int = 5 self._max_reconnect_attempts: int = -1 + # C4: while the agent is degraded the job stream is closed (see pause_consumption). + self._consumption_paused = False + + @property + def consumption_paused(self) -> bool: + """Whether this agent's job stream is closed because the agent is degraded (C4).""" + return self._consumption_paused + + async def pause_consumption(self) -> None: + """Close the job stream while this agent is degraded, so its jobs stay pending for a healthy replica (C4). + + The same consequence the topic transports draw, in this transport's terms: the sessions + service pushes jobs to the agents connected to its stream, so a closed stream takes no new + jobs, and a job not yet started is left pending rather than run here. Jobs already running + finish. The registration is kept -- it is per agent id, not per replica. + """ + if self._consumption_paused: + return + self._consumption_paused = True + await self._stop_stream() + logger.error( + "Agent '%s' stopped consuming: its job stream is closed while it is degraded, so its jobs stay pending " + "for a healthy replica", + self.namespace or ROOT_LABEL, + ) + + async def resume_consumption(self) -> None: + """Reopen the job stream once the agent's health checks pass again; its catch-up collects what is pending.""" + if not self._consumption_paused: + return + self._consumption_paused = False + if self._semaphore is None or self._shutdown_event.is_set(): + return # not started, or shutting down: on_startup opens the stream, and nothing reopens it + self._start_stream() + logger.info("Agent '%s' resumed consuming: its job stream is reopened", self.namespace or ROOT_LABEL) + + def _start_stream(self) -> None: + """Run the stream loop in a task of its own, unless one is running.""" + if self._sse_task is not None and not self._sse_task.done(): + return + self._sse_task = asyncio.create_task(self._consume_sse_stream()) + self._sse_task.add_done_callback(self._report_task_failure) + + async def _stop_stream(self) -> None: + """Cancel the stream loop and wait for it, leaving in-flight jobs running.""" + task = self._sse_task + if task is not None and not task.done(): + task.cancel() + try: + await task + except asyncio.CancelledError: + logger.info("SSE task cancelled") + async def on_startup(self) -> None: """Connect to the sessions service SSE endpoint and start consuming events.""" if self._sse_task is not None and not self._sse_task.done(): @@ -131,8 +184,11 @@ async def on_startup(self) -> None: self._semaphore = asyncio.Semaphore(self._max_concurrent_jobs) self._shutdown_event.clear() - self._sse_task = asyncio.create_task(self._consume_sse_stream()) - self._sse_task.add_done_callback(self._report_task_failure) + if self._consumption_paused: + # Marked down before its endpoint started (spec sec. 9.1): resume_consumption opens the stream. + logger.info("Agent '%s' is degraded, so its job stream is not opened", self.namespace or ROOT_LABEL) + return + self._start_stream() logger.info( "SessionsBus connected: agent_id=%s, capabilities=%s, max_concurrent=%d", @@ -153,12 +209,7 @@ async def on_shutdown(self) -> None: self._shutdown_event.set() - if self._sse_task and not self._sse_task.done(): - self._sse_task.cancel() - try: - await self._sse_task - except asyncio.CancelledError: - logger.info("SSE task cancelled") + await self._stop_stream() await self._drain_inflight_jobs() @@ -403,6 +454,11 @@ async def _handle_job_notification(self, notification: JobNotification) -> None: """ if self._semaphore is None: raise RuntimeError("Semaphore not initialized") + if self._consumption_paused: + # A job that reached a degraded agent anyway -- buffered, or listed by a catch-up that + # began before the pause -- is not started, so it stays pending for a healthy replica. + logger.info("Job %s left pending: agent '%s' is degraded", notification.job_id, self.namespace or ROOT_LABEL) + return async with self._semaphore: try: await asyncio.wait_for( diff --git a/tests/unit/agents/clients/TESTS.md b/tests/unit/agents/clients/TESTS.md index 75b117d4..fb95dd27 100644 --- a/tests/unit/agents/clients/TESTS.md +++ b/tests/unit/agents/clients/TESTS.md @@ -13,7 +13,7 @@ Test coverage for `src/blueprint/agents/clients/`. | `ai/test_openai_client.py` | `OpenAIClient` | `_is_connected`, `connect` (no-op), `close`, `subscribe`/`publish` (no-ops), `create_model`, `health_check` | | `ai/test_vllm_client.py` | `VLLMClient` | Same shape as OpenAI; additionally verifies `base_url`/`api_key` forwarding to `AsyncOpenAI` | | `io/test_dapr_client.py` | `DaprClient` | `_is_connected`, `connect`/`close`, `subscribe` (no-op), `publish` (URL, headers, routing key, pubsub name), `health_check` | -| `io/test_nats_client.py` | `NATSClient` | `__init__` defaults, `_is_connected` variants, `connect` (Core + JetStream), `close`, `publish`, `health_check`; no credential or payload value in logs (B2, S4, N3): an unparseable payload logs `loc: type` only, `_Link` and `_Binding` reprs hide URL and connect options, the default connection's failed attempt and permanent failure and a named connection's error and failed attempt log the URL redacted and no password or token; a reconnect under JetStream subscribes nothing again (nats-py replays `_subs`) and re-checks stream and consumers, a failed re-check leaves it unready (M1); a paused agent naks a JetStream delivery without running it and still runs a buffered Core NATS one (N4); the first connect is bounded while reconnects stay unlimited, and fails against a closed port instead of hanging (N11). *Later coverage of this file is not itemised here.* | +| `io/test_nats_client.py` | `NATSClient` | `__init__` defaults, `_is_connected` variants, `connect` (Core + JetStream), `close`, `publish`, `health_check`; no credential or payload value in logs (B2, S4, N3): an unparseable payload logs `loc: type` only, `_Link` and `_Binding` reprs hide URL and connect options, the default connection's failed attempt and permanent failure and a named connection's error and failed attempt log the URL redacted and no password or token; a reconnect under JetStream subscribes nothing again (nats-py replays `_subs`) and re-checks stream and consumers, a failed re-check leaves it unready (M1); a paused agent naks a JetStream delivery without running it and still runs a buffered Core NATS one (N4); the first connect is bounded while reconnects stay unlimited, and fails against a closed port instead of hanging (N11); a failed resume stays paused and retries in the background, dropping what each failed attempt subscribed, until it succeeds; a pause or close stops the retry; supervisor and client together recover from a failed resume after one health transition (M2). *Later coverage of this file is not itemised here.* | | `io/test_nats_connection_source.py` | `NATSClient` with a `ConnectionSource` | Loading the source, `ConnectionSpec`, planning bindings (claims, hybrid mode, result publishing refused), runs from named connections (run scope, validation, isolation, default connection unchanged), the handler context (`nats_connection`), the delivery attempt (named run: attempt 1 and 2 with the binding's `max_deliver`; default connection: `nats_max_deliver` unset -> `None`; no JetStream metadata -> no attempt; both keys in the handler context), shutdown. *Earlier coverage was not itemised here.* | `IOClientBase` has no logic and has no test file. diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index 22a42f41..cadf99ac 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -2052,13 +2052,91 @@ async def test_resuming_one_that_was_not_paused_does_nothing(self, subscribed: N await subscribed.resume_consumption() subscribe_all.assert_not_awaited() - async def test_a_failed_resume_stays_paused(self, subscribed: NATSClient) -> None: - """The next health poll finds the agent healthy and calls this again; that is the retry.""" + async def test_a_failed_resume_stays_paused_and_retries(self, subscribed: NATSClient) -> None: + """M2 -- nothing else calls resume again: a paused client is healthy, so the supervisor sees no transition.""" await subscribed.pause_consumption() with patch.object(subscribed, "_subscribe_all", new=AsyncMock(side_effect=RuntimeError("no"))): await subscribed.resume_consumption() assert subscribed.consumption_paused is True assert subscribed.subscriptions_ready is False + assert subscribed._resume_retry is not None and not subscribed._resume_retry.done() + await subscribed.close() + + @staticmethod + def _fast_retries(mock_config: MagicMock) -> None: + base = mock_config.get.side_effect + mock_config.get.side_effect = lambda key, default=None: 0.01 if key == "event_client_retry_delay" else base(key, default) + + async def test_the_retry_resumes_once_subscribing_works( + self, subscribed: NATSClient, mock_config: MagicMock, caplog: pytest.LogCaptureFixture + ) -> None: + self._fast_retries(mock_config) + await subscribed.pause_consumption() + partial = MagicMock(unsubscribe=AsyncMock()) + + async def fail_after_one_subscription() -> None: + subscribed._subscriptions.append(partial) + raise RuntimeError("stream not there yet") + + outcomes = [fail_after_one_subscription, fail_after_one_subscription] + + async def subscribe_all() -> None: + if outcomes: + await outcomes.pop(0)() + + with patch.object(subscribed, "_subscribe_all", new=subscribe_all), caplog.at_level(logging.WARNING): + await subscribed.resume_consumption() + await asyncio.wait_for(subscribed._resume_retry, timeout=5) # type: ignore[arg-type] + + assert subscribed.consumption_paused is False + assert subscribed.subscriptions_ready is True + assert partial.unsubscribe.await_count == 2, "each failed attempt drops what it subscribed" + assert subscribed._subscriptions == [] + assert "attempt 1" in caplog.text and "attempt 2" in caplog.text + + async def test_a_pause_stops_the_retry(self, subscribed: NATSClient, mock_config: MagicMock) -> None: + await subscribed.pause_consumption() + with patch.object(subscribed, "_subscribe_all", new=AsyncMock(side_effect=RuntimeError("no"))): + await subscribed.resume_consumption() + retry = subscribed._resume_retry + await subscribed.pause_consumption() + assert retry is not None and retry.cancelled() + assert subscribed._resume_retry is None + assert subscribed.consumption_paused is True + + async def test_close_stops_the_retry(self, subscribed: NATSClient) -> None: + await subscribed.pause_consumption() + with patch.object(subscribed, "_subscribe_all", new=AsyncMock(side_effect=RuntimeError("no"))): + await subscribed.resume_consumption() + retry = subscribed._resume_retry + await subscribed.close() + assert retry is not None and retry.cancelled() + + async def test_the_supervisor_and_the_client_recover_together(self, subscribed: NATSClient, mock_config: MagicMock) -> None: + """M2 end to end in the process: one health transition, a failed resume, and the agent consumes again.""" + from blueprint.agents.io.api.actuators.health.namespace_supervisor import NamespaceSupervisor + + self._fast_retries(mock_config) + registry = MagicMock() + registry.get_io_clients.side_effect = lambda namespace=None: [subscribed] + registry.get_components_by_type.return_value = [] + supervisor = NamespaceSupervisor(registry, [""]) + failures = [RuntimeError("stream not there yet")] + + async def subscribe_all() -> None: + if failures: + raise failures.pop(0) + + with patch.object(subscribed, "_subscribe_all", new=subscribe_all): + await supervisor.observe({"": False}) + assert subscribed.consumption_paused is True + await supervisor.observe({"": True}) + assert (await subscribed.health_check()).status == "healthy", "green while it retries: the bug's disguise" + await asyncio.wait_for(subscribed._resume_retry, timeout=5) # type: ignore[arg-type] + await supervisor.observe({"": True}) # no transition, so the supervisor itself does nothing more + + assert subscribed.consumption_paused is False + assert subscribed.subscriptions_ready is True async def test_a_reconnect_does_not_undo_a_pause(self, subscribed: NATSClient) -> None: """Otherwise C4 would hold only until the next network blip.""" diff --git a/tests/unit/agents/io/TESTS.md b/tests/unit/agents/io/TESTS.md index dd2e1ef9..a6c7c17a 100644 --- a/tests/unit/agents/io/TESTS.md +++ b/tests/unit/agents/io/TESTS.md @@ -16,7 +16,7 @@ Test coverage for `src/blueprint/agents/io/`. | `api/eventing/test_event_handling_base.py` | `EventHandlingBase` | `_unwrap_nested_cloud_event` (via mixin) for non-dapr/dict/JSON-string/malformed-JSON/missing-fields/None data; `handle_event` PROCESSED→SUCCESS / other→RETRY; a `SKIPPED` run counted as `blueprint.events.skipped` and not as unhandled, acknowledged, with no WARNING | | `api/eventing/test_dapr.py` | `DaprEventing` | `publish` PROCESSED→SUCCESS, no-handler→RETRY, `RetryableHandlerError`→RETRY, `InvalidEventError`→DROP, `CriticalHandlerError`→RETRY; `subscribe` returns empty dict; the reason for an exception that is not a `HandlerError` is its type name, never its text (S8); an unparseable delivery logs `body.: ` and no input value (B2). *Later coverage of this file is not itemised here.* | | `api/eventing/test_nats.py` | `NatsEventing` | `subscribe`/`publish` delegate to `_client`, RuntimeError when client is None; `on_startup` fetches client, subscribes to handler-declared and config-declared topics, deduplicates, preserves handler-first order, skips when no topics; `_subscribe_to_topic` RuntimeError when client None, calls `_client.subscribe` with topic and callback | -| `api/eventing/test_sessions_bus.py` | `SessionsBus` | `on_startup` validation (no config/base_url/agent_id/api_key, already started, task created); `on_shutdown` (no task, running task cancelled); `_convert_to_cloud_event` (type/id/subject/source/data); `_process_job_notification` (no handler logged, `InvalidEventError`→cancel job, cancel failure swallowed, `RetryableHandlerError`→log, 403→invalidate+retry, 403 retry failure propagates `InvalidEventError`, non-403 propagates) | +| `api/eventing/test_sessions_bus.py` | `SessionsBus` | `on_startup` validation (no config/base_url/agent_id/api_key, already started, task created); `on_shutdown` (no task, running task cancelled); `_convert_to_cloud_event` (type/id/subject/source/data); `_process_job_notification` (no handler logged, `InvalidEventError`→cancel job, cancel failure swallowed, `RetryableHandlerError`→log, 403→invalidate+retry, 403 retry failure propagates `InvalidEventError`, non-403 propagates); C4 (S18): a pause closes the job stream and a resume reopens it, a job reaching a paused agent is left pending, an agent paused before startup opens no stream, and the supervisor pauses and resumes the bus | | `api/eventing/test_sessions_startup_resilience.py` | `AppBuilder.build()` with `event_bus = "sessions"` | The lifespan completes and the root REST endpoints answer when the sessions service URL points at a closed port -- a background SSE consumer that cannot connect must not stop the application starting. Offline: the refused port is bound and released on loopback, so the failure is ECONNREFUSED rather than a timeout on every platform. Moved here from `tests/integration/` (#80), where nothing ran it | `api/scheduling/test_scheduler.py` | `SchedulerBase`, `SchedulerTickHandler` | `_trigger_tick` calls `tick()` and returns `{"status": "triggered"}`; `scheduler_mode` reads both values case-insensitively, has no default so an absent, empty or missing key raises with both values named, rejects an unrecognised value and resolves once; `tick_topic` derives from `app_name` and the (possibly renamed) scheduler name, honours the `topic=` override, rejects a missing identity and a wildcard, rejects whitespace in an explicit topic and rewrites it in a derived one; `wire()` creates the tick handler in event mode only, is idempotent, registers the trigger route once in both modes, refuses event mode without a topic-carrying `event_bus` and accepts both broker transports; `on_startup` starts no timer in event mode, creates and starts `AsyncIOScheduler` on the declared crontab in in-process mode, and starts no second timer or route when called twice (#43); `on_shutdown` calls `shutdown(wait=True)` only when running and allows a later restart; the in-process tick claim -- the winner ticks and a loser does not, the key carries the scheduler and the minute, the claim carries the tick TTL and its own namespace, three replicas sharing a real `DiskCacheService` run one tick between them, a later slot is claimable again, no cache means every replica ticks and startup warns, the timer is wired to the claimed wrapper rather than to `tick`, and event mode claims nothing; `validate_crontab` accepting the five standard fields, stripping whitespace and rejecting empty, nonsense and six-field (apscheduler) expressions, with event-mode wiring failing on a bad crontab and in-process wiring not reaching the check; the tick handler declares its topic, outranks the default handler priority, claims a delivery under `nats_topic`/`dapr_topic`/`topic`, declines other or absent topics, ticks its scheduler without publishing an event, lets a failing tick reach the transport edge, and two schedulers register under distinct names in a real `Registry` | | `api/scheduling/test_scheduler_event_mode.py` | `SchedulerBase` through `AppBuilder.build()` | What only a built application can show: the tick topic reaches the Dapr subscription document and a CloudEvent posted to `/events/` runs `tick()` exactly once; event mode starts no in-process timer; `POST /api//trigger` is actually served (it used to be added to the router after `include_router` had copied it); in-process mode declares no tick topic and registers no eventing endpoint; a registered scheduler with no `scheduler_mode`, and event mode with no `event_bus`, each fail the build naming both values; and the pure-scheduler shapes -- publishing opted into, and nothing at all by default. Offline, and deterministic because `health_check_dapr = false` stops the Dapr health check probing for a sidecar: without it the namespace supervisor degrades the root agent and its paused transports refuse the tick. Moved here from `tests/integration/` (#80) 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 bde09837..f9fc4d63 100644 --- a/tests/unit/agents/io/api/eventing/test_sessions_bus.py +++ b/tests/unit/agents/io/api/eventing/test_sessions_bus.py @@ -955,3 +955,76 @@ async def test_first_connect_omits_last_event_id(self, started_sessions_bus: Ses params = mock_sse.call_args[1]["params"] assert "last_event_id" not in params + + +# --------------------------------------------------------------------------- +# C4 -- a degraded agent's job stream is closed (S18) +# --------------------------------------------------------------------------- + + +class TestPausingADegradedAgent: + """The sessions stream was the one consumer C4 never stopped: no IOClientBase, so the supervisor never saw it.""" + + @staticmethod + async def _started(sessions_bus: SessionsBus, mock_config: MagicMock) -> asyncio.Event: + """Start the bus with a stream loop that runs until cancelled; return the event set while it runs.""" + mock_config.get.return_value = _make_sessions_config() + running = asyncio.Event() + + async def stream() -> None: + running.set() + try: + await asyncio.Event().wait() + finally: + running.clear() + + sessions_bus._consume_sse_stream = stream # type: ignore[method-assign] + await sessions_bus.on_startup() + await asyncio.wait_for(running.wait(), timeout=1) + return running + + async def test_pausing_closes_the_stream(self, sessions_bus: SessionsBus, mock_config: MagicMock) -> None: + running = await self._started(sessions_bus, mock_config) + await sessions_bus.pause_consumption() + assert sessions_bus.consumption_paused is True + assert not running.is_set() + await sessions_bus.on_shutdown() + + async def test_resuming_reopens_it(self, sessions_bus: SessionsBus, mock_config: MagicMock) -> None: + running = await self._started(sessions_bus, mock_config) + await sessions_bus.pause_consumption() + await sessions_bus.resume_consumption() + await asyncio.wait_for(running.wait(), timeout=1) + assert sessions_bus.consumption_paused is False + await sessions_bus.on_shutdown() + + async def test_a_job_reaching_a_paused_agent_is_left_pending( + self, started_sessions_bus: SessionsBus, notification: JobNotification + ) -> None: + """Buffered, or listed by a catch-up begun before the pause: not started, so another replica takes it.""" + started_sessions_bus._semaphore = asyncio.Semaphore(1) + started_sessions_bus._consumption_paused = True + with patch.object(started_sessions_bus, "_process_job_notification", new=AsyncMock()) as process: + await started_sessions_bus._handle_job_notification(notification) + process.assert_not_awaited() + + async def test_an_agent_paused_before_startup_opens_no_stream(self, sessions_bus: SessionsBus, mock_config: MagicMock) -> None: + mock_config.get.return_value = _make_sessions_config() + await sessions_bus.pause_consumption() + await sessions_bus.on_startup() + assert sessions_bus._sse_task is None + + async def test_the_supervisor_pauses_it(self, sessions_bus: SessionsBus, mock_config: MagicMock) -> None: + from blueprint.agents.io.api.actuators.health.namespace_supervisor import NamespaceSupervisor + + running = await self._started(sessions_bus, mock_config) + registry = MagicMock() + registry.get_io_clients.return_value = [] + registry.get_components_by_type.side_effect = lambda kind, namespace=None: [sessions_bus] if kind is SessionsBus else [] + supervisor = NamespaceSupervisor(registry, [""]) + + await supervisor.observe({"": False}) + assert sessions_bus.consumption_paused is True and not running.is_set() + await supervisor.observe({"": True}) + await asyncio.wait_for(running.wait(), timeout=1) + await sessions_bus.on_shutdown() From f920e172063c7bfc4ecdd5cbafb98b02f28b00e9 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:14:50 +0200 Subject: [PATCH 107/133] fix(nats): named bindings -- retire superseded ones, never read a refused subscription as bound Step 6 (M3, M4, S2, S3): a binding superseded before it bound is retired and hands over; a removal retires what it replaced; _bind fails on a refusal naming its deliver subject; status-100 messages are answered or dropped; ConnectionSpec.tls is not compared. Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 17 +++ ...26-08-28-multi-agent-grouping-changelog.md | 9 ++ .../docs/reference/configuration-keys.md | 2 +- .../agents/clients/io/nats_client.py | 65 ++++++++++- .../agents/clients/io/nats_connections.py | 8 +- tests/integration/connection_source.py | 20 +++- tests/integration/test_named_connections.py | 102 ++++++++++++++++++ tests/unit/agents/clients/TESTS.md | 2 +- tests/unit/agents/clients/io/conftest.py | 1 + .../clients/io/test_nats_binding_mode.py | 67 ++++++++++++ .../io/test_nats_connection_readiness.py | 1 + .../clients/io/test_nats_connection_source.py | 12 ++- .../clients/io/test_nats_runtime_changes.py | 52 ++++++++- 13 files changed, 343 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ae6330d2..12e830b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,23 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **Named connections changed at runtime no longer leave an old link consuming.** A connection changed + twice before its new binding was bound, or changed and then removed, kept its original link + subscribed for good: only the not-yet-bound binding in between was retired. Measured on a broker + with one account per connection: the original link is now closed in both cases (before: still + open after 15 s). + +- **A named connection whose subscription the broker refuses is no longer reported as bound.** The + broker refuses a subscription asynchronously, so `subscribe()` returned and the connection read as + bound and was never retried. A bind now waits for the broker's round trip and retries a refusal as a + permission violation. Measured: `retrying` with `permission_denied` (before: `bound`). + +- **An operator's consumer with `idle_heartbeat` or `flow_control` works in binding mode.** Its status + messages reached the handler, were terminated as matching no subject, and an unanswered flow control + request stalls the consumer. Heartbeats are now dropped and flow control requests answered. A new + `tls` context alone no longer counts as a changed connection, which rebound every `tls://` + connection on every notify. + - **A degraded agent whose resume fails is no longer left off its topics for good.** The supervisor resumes an agent once, on the transition back to healthy, and a paused NATS client reports healthy; a failed re-subscribe therefore left the agent paused with every check green, and nothing diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index b8cf0111..6587da51 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,15 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 6, named bindings (M3, M4, S2, S3): a binding superseded before it bound is retired at once and + hands over the binding still delivering, and a removal retires that one too; `_bind` flushes and fails + on a refusal naming its deliver subject (compared lowercased -- nats-py lowercases the -ERR line, found + live); a reconnect restores readiness only for `bound` bindings; binding mode answers flow control and + drops heartbeats; `ConnectionSpec.tls` is not compared. Accounts broker: change-change and change-remove + close the original link (control: open after 15 s), a refused deliver subject reads `retrying` with a + permission violation (control: `bound`), an operator consumer with heartbeat and flow control delivers + 20 of 20 once with no termination (control: status messages termed). Integration suite 64 passed, + 3 skipped (Redis). - Step 5, resume retry and C4 for sessions (M2, S18): a failed `resume_consumption` drops the partial subscriptions, stays paused and retries in a backoff task (cancelled by a pause and by close), a WARNING per attempt; `SessionsBus` gains `pause_consumption`/`resume_consumption` (stream closed, diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index f0651f93..37b01d45 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -48,7 +48,7 @@ Settings for the event bus transport layer. | `nats_max_ack_pending` | `int` | unset -- the server's default (NATS: 1000) | Unacknowledged messages the consumer may have outstanding at once, counted across every replica sharing it. `-1` is unlimited. Keep it close to replicas x `nats_max_concurrent_runs`: whatever a pod receives beyond the runs it has started waits in the client's queue, unheartbeated, while its `nats_ack_wait` is already running down. | | `nats_max_concurrent_runs` | `int` or `"N%"` | unset -- one run at a time per subscription, as before the key existed | How many deliveries one (agent, connection) pair runs at once, per process. The pair's **first** run is always allowed and counts against no limit; every further run also needs a free slot of `nats_extra_runs_per_process`. A percentage is taken of the (agent, connection) pairs the process consumes on, at least 1. An agent that waits on a model or an API gains the most from raising it; every run shares the process's one event loop, so CPU-heavy handlers gain little. | | `nats_extra_runs_per_process` | `int` or `"N%"` | unset -- unlimited | **Process scope.** The pool of runs beyond each pair's guaranteed one, shared by every agent and connection of the process; a percentage is taken of the current number of pairs. It is what keeps a burst on many pairs from overloading the event loop while an idle pair still never waits. `0` allows no runs beyond the guaranteed ones. | -| `nats_connection_source` | `str` | unset -- the agent consumes on its one connection, as before | **Process scope.** `"package.module:attribute"` naming a factory that is called with the process `Config` and returns a `ConnectionSource` (`blueprint.agents.clients.io.nats_connections`). The source lists named connections -- each with its own URL and account -- and, per agent and connection, a `JetStreamBinding`: which declared subjects the connection serves, the subject prefix, and the deployment's durable consumer with its wire values verbatim. Those subjects leave the agent's default connection. Each delivery from a named connection is checked by the source's `validate` before anything runs (a reason terminates it), runs in an empty context inside the source's `run_scope`, and is settled on the connection it arrived on; the handler sees the subject without the prefix and the connection's name under the context key `nats_connection`. JetStream only. An agent with named connections may not map handler results to topics. A source that also defines `watch(notify)` is followed at runtime: connections added, changed or removed are applied while the agent runs (`subscription_change_grace`). A wrong path fails startup. | +| `nats_connection_source` | `str` | unset -- the agent consumes on its one connection, as before | **Process scope.** `"package.module:attribute"` naming a factory that is called with the process `Config` and returns a `ConnectionSource` (`blueprint.agents.clients.io.nats_connections`). The source lists named connections -- each with its own URL and account -- and, per agent and connection, a `JetStreamBinding`: which declared subjects the connection serves, the subject prefix, and the deployment's durable consumer with its wire values verbatim. Those subjects leave the agent's default connection. Each delivery from a named connection is checked by the source's `validate` before anything runs (a reason terminates it), runs in an empty context inside the source's `run_scope`, and is settled on the connection it arrived on; the handler sees the subject without the prefix and the connection's name under the context key `nats_connection`. JetStream only. An agent with named connections may not map handler results to topics. A source that also defines `watch(notify)` is followed at runtime: connections added, changed or removed are applied while the agent runs (`subscription_change_grace`); a changed connection keeps delivering on its old link until the new one is bound, however often it changes in between, and a change of its `tls` context alone is not applied. A subscription the broker refuses (a deliver subject the account may not subscribe to) reads as `retrying` with a permission violation and is retried, never as bound. A wrong path fails startup. | | `nats_handler_timeout` | `float` | unset -- no limit | Seconds one run may take, on every connection of the agent. At the limit the run is cancelled and its delivery nak'd for immediate redelivery, so a hung model request no longer holds its slot forever; after `nats_max_deliver` attempts the delivery is given up as usual. A `TimeoutError` the handler raises itself is an ordinary failure. A handler that catches the cancellation and carries on keeps its slot until it returns, which is logged, and its delivery is nak'd all the same. Set it above the longest legitimate run. | | `subscription_change_grace` | `float` | `event_client_drain_timeout` | Seconds the runs of a named connection that is removed or replaced at runtime get to finish. A run still going after that is revoked: it is never acked or nak'd -- the delivery stays with the broker and returns after `ack_wait` -- its heartbeat stops, and a `publish` from it raises `DeliveryRevokedError`; it is not cancelled. | | `nats_connections_readiness` | `str` | `"never"` | Only with a `nats_connection_source`; agent scope. Whether the agent's named connections count for its readiness: `"never"` -- they never make it not ready; `"any"` -- ready while at least one named connection is bound (none at all counts as not ready); `"all"` -- ready only while every named connection is bound. Any other value fails startup, naming the key. **Readiness only, in every mode:** a named connection that is down never pauses the agent, so its other connections keep delivering. Each connection's state (`bound`, `connecting`, `reconnecting`, `retrying` with the last error, `paused`, and a permission violation if one was seen) is listed in the readiness entry `.nats_client:connections` in every mode, and the gauge `blueprint.nats.connection.bound` reports it. The agent's default connection keeps its behaviour. | diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 8325ad2c..fdd58867 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -88,6 +88,9 @@ class JetStreamUnavailableError(RuntimeError): """How often a named connection retries after the broker refused it a permission: a missing grant does not heal in seconds, so retrying at the normal pace would only fill the log (spec 7.9).""" +CONTROL_MESSAGE_STATUS = "100" +"""The status a JetStream idle heartbeat and flow control request carry (``nats.js.api.StatusCode.CONTROL_MESSAGE``).""" + RESUME_RETRY_MAX_DELAY = 60.0 """The longest wait between two attempts of a resume that keeps failing (M2): the delay doubles from ``event_client_retry_delay`` up to this.""" @@ -237,7 +240,13 @@ class _Binding: spec: ConnectionSpec | None = None """The connection as the source last described it; a named binding is replaced when it differs.""" replaces: "_Binding | None" = None - """The binding this one replaces; retired as soon as this one is bound (new before old, spec 7.4).""" + """The bound binding this one replaces; retired as soon as this one is bound (new before old, spec 7.4). + + Always one that delivers, never a chain: a change that supersedes a binding not yet bound retires + that one at once and takes over what it was replacing (M3).""" + bound: bool = False + """The subscription is on the link: set when a bind succeeds, cleared at each attempt. A reconnect + restores readiness only for a bound binding -- nats-py replays only the subscriptions it holds.""" superseded: bool = False """A newer binding of the same connection exists; this one serves until that one is bound.""" revoked: bool = False @@ -861,12 +870,14 @@ async def _run_named_link(self, binding: _Binding) -> None: attempt = 0 while True: binding.link.permission_errors.clear() + binding.bound = False try: await self._open_named_link(binding.link) if self._consumption_paused: return binding.subscriptions.clear() await self._bind(binding) + binding.bound = True binding.subscriptions_ready = True binding.last_error = "" binding.permission_denied = False @@ -937,9 +948,11 @@ async def on_disconnected() -> None: async def on_reconnected() -> None: # A plain subscription is restored by nats-py itself, and a push consumer delivers to - # it again as soon as there is interest: nothing to re-bind, no JetStream request. + # it again as soon as there is interest: nothing to re-bind, no JetStream request. Only + # for a binding that had bound, though: one whose bind failed has no subscription to + # restore, and reading it as bound left it never retried. for binding in self._named: - if binding.link is link and not self._consumption_paused: + if binding.link is link and binding.bound and not self._consumption_paused: binding.subscriptions_ready = True self._named_bound_changed(binding) logger.info("Agent '%s': named connection '%s' is back", agent, link.name) @@ -1085,7 +1098,14 @@ async def _reconcile(self) -> None: binding = self._new_named_binding(spec, jetstream) if existing is not None: existing.superseded = True - binding.replaces = existing + if existing.bound: + binding.replaces = existing + else: + # Never bound, so it serves nothing to keep: retired now, and what it was to + # replace -- the binding still delivering -- passes to the new one. Chaining + # instead left that one consuming for good once the middle one was retired (M3). + binding.replaces, existing.replaces = existing.replaces, None + await self._retire(existing, "changed again before it was bound") self._named.append(binding) created.append(binding) logger.info("Agent '%s': connection '%s' %s", agent, name, "changed; binding the new one" if existing else "added") @@ -1097,7 +1117,11 @@ async def _reconcile(self) -> None: for name, binding in current.items(): if name not in wanted: + # The binding it was to replace goes too: it is the one still delivering (M3). + replaced, binding.replaces = binding.replaces, None await self._retire(binding, "removed") + if replaced is not None: + await self._retire(replaced, "removed") def _start_retirement(self, binding: _Binding, reason: str) -> None: """Retire ``binding`` in the background, under the change lock (a replacement that just bound).""" @@ -1137,6 +1161,7 @@ async def _retire(self, binding: _Binding, reason: str) -> None: with contextlib.suppress(asyncio.CancelledError, Exception): await task binding.subscriptions_ready = False + binding.bound = False loop = asyncio.get_running_loop() deadline = loop.time() + self._change_grace await self._drain_subscriptions(deadline, binding) @@ -2477,6 +2502,18 @@ async def _bind(self, binding: _Binding) -> None: binding.ack_waits[topic] = spec.ack_wait handler = self._message_handler(binding, spec.deliver_subject, None) sub = await client.subscribe(spec.deliver_subject, queue=spec.deliver_group, cb=handler) + # The broker refuses a subscription the account may not make asynchronously, through + # error_cb, so subscribe() returned and the binding read as bound for good (M4). The round + # trip makes any refusal arrive first; one naming this subject fails the attempt, and the + # connect loop retries it as a permission error. Compared lowercased: nats-py lowercases the + # whole -ERR line, the subject in it included. + await client.flush() + subject = spec.deliver_subject.lower() + refused = [error for error in binding.link.permission_errors if subject in error.lower()] + if refused: + with contextlib.suppress(Exception): + await sub.unsubscribe() + raise PermissionError(f"the broker refused the subscription to '{spec.deliver_subject}': {refused[0]}") binding.subscriptions.append(sub) logger.info( "Agent '%s' bound to consumer '%s' on stream '%s' (deliver subject '%s', group '%s', subjects %s)", @@ -2533,6 +2570,8 @@ def _message_handler( """ async def message_handler(msg: Any) -> None: + if binding.jetstream is not None and await self._answer_control_message(msg): + return if self._consumption_paused and self._settles(binding): # A degraded agent runs nothing (C4). What reaches it anyway -- a delivery still in # the buffer while the pause waits for a connection change to finish, before it @@ -2561,6 +2600,24 @@ async def message_handler(msg: Any) -> None: return message_handler + @staticmethod + async def _answer_control_message(msg: Any) -> bool: + """Answer or drop a JetStream status message; ``True`` if ``msg`` was one (S2). + + Binding mode consumes through a plain subscription, so what nats-py's JetStream + subscription would handle itself reaches this handler: an idle heartbeat, and a flow + control request, after which the consumer delivers nothing until it is answered. Both + carry status ``100`` and no event; run as a delivery, they were termed as unparseable. + Only an operator-made consumer with ``idle_heartbeat`` or ``flow_control`` sends them. + """ + headers = getattr(msg, "headers", None) + if not headers or headers.get(js_api.Header.STATUS) != CONTROL_MESSAGE_STATUS: + return False + if msg.reply: # a flow control request; a heartbeat has no reply subject + with contextlib.suppress(Exception): + await msg.respond(b"") + return True + @staticmethod def _peek_event_id(msg: Any) -> str | None: """The event id of a delivery that is settled without being decoded, for its log line; ``None`` if unreadable.""" diff --git a/src/blueprint/agents/clients/io/nats_connections.py b/src/blueprint/agents/clients/io/nats_connections.py index 3192a6e7..98acc0fb 100644 --- a/src/blueprint/agents/clients/io/nats_connections.py +++ b/src/blueprint/agents/clients/io/nats_connections.py @@ -84,8 +84,12 @@ class ConnectionSpec: creds_file: str | None = None nkey_seed: str | None = field(default=None, repr=False) inbox_prefix: str | None = None - tls: Any = field(default=None, repr=False) - """An ``ssl.SSLContext`` for ``tls://`` brokers with a private CA; ``None`` uses the default.""" + tls: Any = field(default=None, repr=False, compare=False) + """An ``ssl.SSLContext`` for ``tls://`` brokers with a private CA; ``None`` uses the default. + + Not compared: an ``SSLContext`` equals only itself, so a source that builds one per call made + every notify rebind every ``tls://`` connection (S3). A change of the TLS settings alone is + therefore not applied at runtime; change the connection's name or URL with it, or restart.""" def __post_init__(self) -> None: if not self.name or any(char.isspace() for char in self.name): diff --git a/tests/integration/connection_source.py b/tests/integration/connection_source.py index 8261ed22..7ad0fd9f 100644 --- a/tests/integration/connection_source.py +++ b/tests/integration/connection_source.py @@ -3,10 +3,13 @@ One named connection per tenant, each logging in as that tenant's agent user on the accounts broker (nats-accounts.conf). Everything per test comes from the process config the factory is called with, because that is all the framework hands it: ``test_source_url``, ``test_source_prefix`` (keeps -streams and subjects apart between tests), ``test_source_tenants``, ``test_source_unclaimed`` and -``test_source_wrong_password`` (tenants whose connection logs in with a password the broker refuses). +streams and subjects apart between tests), ``test_source_tenants``, ``test_source_unclaimed``, +``test_source_wrong_password`` (tenants whose connection logs in with a password the broker refuses) +and ``test_source_foreign_deliver`` (tenants whose binding names another tenant's deliver subject, +which their agent user may not subscribe to). """ +import dataclasses from collections.abc import Callable, Iterator from contextlib import contextmanager from contextvars import ContextVar @@ -61,6 +64,7 @@ def __init__(self, config: Any) -> None: self.users = {tenant: f"agent-{tenant.lower()}" for tenant in config.get("test_source_tenants") or []} self.unclaimed = tuple(config.get("test_source_unclaimed") or ()) self.wrong_password = set(config.get("test_source_wrong_password") or ()) + self.foreign_deliver = set(config.get("test_source_foreign_deliver") or ()) self.notifiers: list[Callable[[], None]] = [] SOURCES.append(self) @@ -70,9 +74,11 @@ def claims(self, agent: str, subjects: tuple[str, ...]) -> tuple[str, ...]: def watch(self, notify: Callable[[], None]) -> None: self.notifiers.append(notify) - def set_users(self, users: dict[str, str]) -> None: - """Replace the tenants and their users, and tell every client.""" + def set_users(self, users: dict[str, str], *, wrong_password: set[str] | None = None) -> None: + """Replace the tenants and their users (and which of them log in wrongly), and tell every client.""" self.users = dict(users) + if wrong_password is not None: + self.wrong_password = set(wrong_password) for notify in self.notifiers: notify() @@ -85,7 +91,11 @@ def connections(self) -> dict[str, ConnectionSpec]: } def binding(self, agent: str, subjects: tuple[str, ...], connection: ConnectionSpec) -> JetStreamBinding: - return binding_for(self.prefix, agent, self.claims(agent, subjects), connection.name) + binding = binding_for(self.prefix, agent, self.claims(agent, subjects), connection.name) + if connection.name in self.foreign_deliver: + other = "B" if connection.name == "A" else "A" + binding = dataclasses.replace(binding, deliver_subject=f"acme.agent.{other}.{agent}") + return binding def validate(self, connection: str, subject: str, event: Any) -> str | None: """W17.2 in miniature: connection, subject token and the event's tenantid must agree.""" diff --git a/tests/integration/test_named_connections.py b/tests/integration/test_named_connections.py index b2624327..f9631b35 100644 --- a/tests/integration/test_named_connections.py +++ b/tests/integration/test_named_connections.py @@ -12,6 +12,7 @@ and never pauses the agent: its other connection keeps delivering. """ +import asyncio import json import logging import uuid @@ -343,6 +344,107 @@ async def test_added_changed_and_removed_without_loss_or_duplicate( assert permission_violations(caplog) == [] +class TestAChangeThatHasNotBoundYet: + """M3 -- a binding superseded before it bound must not strand the one still delivering.""" + + async def test_a_second_change_retires_the_link_that_was_still_delivering( + self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str + ) -> None: + agent = f"risk_{subject_prefix}" + await operator(["A"], {agent: ["risk.>"]}) + runs: list[dict[str, Any]] = [] + async with settings_group( + settings(accounts_url, subject_prefix, ["A"]), {agent: recording_handler(["risk.>"], runs)}, named=1 + ) as clients: + client, source = clients[agent], SOURCES[-1] + first = client._named[0].link.nats_client + + source.set_users({"A": "agent-a2"}, wrong_password={"A"}) # changed, and it cannot log in + await wait_until(lambda: len(client._named) == 2, timeout=10, description="the changed binding to be added") + assert not first.is_closed, "the old link serves while the new one cannot bind" + + source.set_users({"A": "agent-a2"}, wrong_password=set()) # changed again, now it can + await wait_until(lambda: first.is_closed, timeout=15, description="the first link to be retired") + await wait_until( + lambda: len(client._named) == 1 and client._named[0].subscriptions_ready, timeout=10, description="one bound binding" + ) + sent = [await publish(accounts_url, subject_prefix, "A", "risk.created") for _ in range(5)] + await wait_until(lambda: all(e in [run["id"] for run in runs] for e in sent), timeout=10, description="5 events") + + assert sorted(run["id"] for run in runs) == sorted(sent), "each once" + + async def test_removing_it_retires_the_link_that_was_still_delivering( + self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str + ) -> None: + agent = f"risk_{subject_prefix}" + await operator(["A"], {agent: ["risk.>"]}) + async with settings_group( + settings(accounts_url, subject_prefix, ["A"]), {agent: recording_handler(["risk.>"], [])}, named=1 + ) as clients: + client, source = clients[agent], SOURCES[-1] + first = client._named[0].link.nats_client + source.set_users({"A": "agent-a2"}, wrong_password={"A"}) + await wait_until(lambda: len(client._named) == 2, timeout=10, description="the changed binding to be added") + + source.set_users({}) + await wait_until(lambda: client._named == [], timeout=15, description="both bindings to be retired") + assert first.is_closed + + +class TestARefusedSubscriptionIsNotBound: + """M4 -- the broker refuses a subscription through error_cb only; subscribe() returned and it read as bound.""" + + async def test_it_reads_retrying_with_a_permission_violation( + self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str + ) -> None: + agent = f"risk_{subject_prefix}" + await operator(["A"], {agent: ["risk.>"]}) + extra = 'test_source_foreign_deliver = ["A"]\n' + async with settings_group( + settings(accounts_url, subject_prefix, ["A"], extra), {agent: recording_handler(["risk.>"], [])}, named=0 + ) as clients: + client = clients[agent] + await wait_until(lambda: client._named[0].last_error != "", timeout=10, description="the bind attempt to fail") + # error_cb reports the refusal while the bind still waits on its round trip: read the state + # once that bind has finished, or a binding that goes on to read as bound passes too. + await asyncio.sleep(1.0) + state = client._state_of(client._named[0]) + assert (state.state, state.permission_denied) == ("retrying", True) + assert client._named[0].subscriptions_ready is False + + +class TestStatusMessagesOfAnOperatorsConsumer: + """S2 -- binding mode subscribes plainly, so the consumer's heartbeats and flow control reach the handler.""" + + async def test_heartbeats_and_flow_control_never_reach_a_handler( + self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str, caplog: pytest.LogCaptureFixture + ) -> None: + caplog.set_level(logging.WARNING) + agent = f"risk_{subject_prefix}" + await operator(["A"], {}) + user, password = ADMINS["A"] + admin = await nats.connect(accounts_url, user=user, password=password) + config = binding_for(subject_prefix, agent, ("risk.>",), "A").consumer_config() + config.idle_heartbeat = 0.5 + config.flow_control = True + await admin.jsm().add_consumer(stream_for(subject_prefix, "A"), config=config) + await admin.close() + runs: list[dict[str, Any]] = [] + async with settings_group(settings(accounts_url, subject_prefix, ["A"]), {agent: recording_handler(["risk.>"], runs)}, named=1): + sent = [await publish(accounts_url, subject_prefix, "A", "risk.created") for _ in range(20)] + await wait_until(lambda: len(runs) == 20, timeout=15, description="20 runs") + await asyncio.sleep(2.0) # several idle heartbeats + + async def settled() -> bool: + info = await consumer_info(accounts_url, subject_prefix, "A", agent) + return info.num_ack_pending == 0 and info.num_redelivered == 0 + + await poll_until(settled, timeout=10, description="every delivery acked once") + + assert sorted(run["id"] for run in runs) == sorted(sent) + assert [r.getMessage() for r in caplog.records if "unparseable" in r.getMessage() or "matches none" in r.getMessage()] == [] + + class TestADeadConnectionCountsForReadinessOnly: """Step 5 / D5: a tenant whose connection cannot log in never pauses the agent on its other tenants.""" diff --git a/tests/unit/agents/clients/TESTS.md b/tests/unit/agents/clients/TESTS.md index fb95dd27..2ba25ba9 100644 --- a/tests/unit/agents/clients/TESTS.md +++ b/tests/unit/agents/clients/TESTS.md @@ -13,7 +13,7 @@ Test coverage for `src/blueprint/agents/clients/`. | `ai/test_openai_client.py` | `OpenAIClient` | `_is_connected`, `connect` (no-op), `close`, `subscribe`/`publish` (no-ops), `create_model`, `health_check` | | `ai/test_vllm_client.py` | `VLLMClient` | Same shape as OpenAI; additionally verifies `base_url`/`api_key` forwarding to `AsyncOpenAI` | | `io/test_dapr_client.py` | `DaprClient` | `_is_connected`, `connect`/`close`, `subscribe` (no-op), `publish` (URL, headers, routing key, pubsub name), `health_check` | -| `io/test_nats_client.py` | `NATSClient` | `__init__` defaults, `_is_connected` variants, `connect` (Core + JetStream), `close`, `publish`, `health_check`; no credential or payload value in logs (B2, S4, N3): an unparseable payload logs `loc: type` only, `_Link` and `_Binding` reprs hide URL and connect options, the default connection's failed attempt and permanent failure and a named connection's error and failed attempt log the URL redacted and no password or token; a reconnect under JetStream subscribes nothing again (nats-py replays `_subs`) and re-checks stream and consumers, a failed re-check leaves it unready (M1); a paused agent naks a JetStream delivery without running it and still runs a buffered Core NATS one (N4); the first connect is bounded while reconnects stay unlimited, and fails against a closed port instead of hanging (N11); a failed resume stays paused and retries in the background, dropping what each failed attempt subscribed, until it succeeds; a pause or close stops the retry; supervisor and client together recover from a failed resume after one health transition (M2). *Later coverage of this file is not itemised here.* | +| `io/test_nats_client.py` | `NATSClient` | `__init__` defaults, `_is_connected` variants, `connect` (Core + JetStream), `close`, `publish`, `health_check`; no credential or payload value in logs (B2, S4, N3): an unparseable payload logs `loc: type` only, `_Link` and `_Binding` reprs hide URL and connect options, the default connection's failed attempt and permanent failure and a named connection's error and failed attempt log the URL redacted and no password or token; a reconnect under JetStream subscribes nothing again (nats-py replays `_subs`) and re-checks stream and consumers, a failed re-check leaves it unready (M1); a paused agent naks a JetStream delivery without running it and still runs a buffered Core NATS one (N4); the first connect is bounded while reconnects stay unlimited, and fails against a closed port instead of hanging (N11); a failed resume stays paused and retries in the background, dropping what each failed attempt subscribed, until it succeeds; a pause or close stops the retry; supervisor and client together recover from a failed resume after one health transition (M2); runtime changes: a second change before the first bound, and a removal before the change bound, retire the link still delivering (M3); a reconnect restores readiness only for a bound binding; binding mode: a subscription refused in the round trip (lowercased, as nats-py hands it on) fails the bind and is unsubscribed (M4); a flow control request is answered and a heartbeat dropped, neither run (S2); a new TLS context alone is no change (S3). *Later coverage of this file is not itemised here.* | | `io/test_nats_connection_source.py` | `NATSClient` with a `ConnectionSource` | Loading the source, `ConnectionSpec`, planning bindings (claims, hybrid mode, result publishing refused), runs from named connections (run scope, validation, isolation, default connection unchanged), the handler context (`nats_connection`), the delivery attempt (named run: attempt 1 and 2 with the binding's `max_deliver`; default connection: `nats_max_deliver` unset -> `None`; no JetStream metadata -> no attempt; both keys in the handler context), shutdown. *Earlier coverage was not itemised here.* | `IOClientBase` has no logic and has no test file. diff --git a/tests/unit/agents/clients/io/conftest.py b/tests/unit/agents/clients/io/conftest.py index 375f3366..c9d89c01 100644 --- a/tests/unit/agents/clients/io/conftest.py +++ b/tests/unit/agents/clients/io/conftest.py @@ -85,6 +85,7 @@ def mock_nats_core() -> MagicMock: mock.publish = AsyncMock() mock.subscribe = AsyncMock(return_value=MagicMock(unsubscribe=AsyncMock())) mock.close = AsyncMock() + mock.flush = AsyncMock() mock.jetstream = MagicMock(return_value=None) return mock diff --git a/tests/unit/agents/clients/io/test_nats_binding_mode.py b/tests/unit/agents/clients/io/test_nats_binding_mode.py index 18d4b829..5cae1a4c 100644 --- a/tests/unit/agents/clients/io/test_nats_binding_mode.py +++ b/tests/unit/agents/clients/io/test_nats_binding_mode.py @@ -206,3 +206,70 @@ async def test_below_the_limit_a_failure_is_nakd( msg = _delivery(cloud_event, delivered=1) await _settled(binding, handler, msg) msg.nak.assert_awaited_once() + + +class TestARefusedSubscription: + """M4 -- the broker refuses a subscription asynchronously; subscribe() alone made it read as bound.""" + + async def test_a_refusal_reported_before_the_round_trip_fails_the_bind( + self, nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock + ) -> None: + async def refuse() -> None: + # Lowercased, subject included, as nats-py's parser hands the -ERR line on. + nats_client._link.permission_errors.append('nats: permissions violation for subscription to "acme.agent.a.risk"') + + mock_nats_core.flush = AsyncMock(side_effect=refuse) + spec = _spec() + binding = _Binding(link=nats_client._link, jetstream=spec, topic_callbacks=dict.fromkeys(spec.subjects, AsyncMock())) + mock_nats_core.jsm = MagicMock(return_value=jsm) + nats_client._link.nats_client = mock_nats_core + + with pytest.raises(PermissionError, match="acme.agent.A.risk"): + await nats_client._subscribe_all(binding) + + mock_nats_core.subscribe.return_value.unsubscribe.assert_awaited_once() + assert binding.subscriptions == [] + + async def test_a_refusal_for_another_subject_does_not(self, nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock) -> None: + async def refuse_other() -> None: + nats_client._link.permission_errors.append('nats: permissions violation for publish to "elsewhere"') + + mock_nats_core.flush = AsyncMock(side_effect=refuse_other) + binding, _ = await _bound(nats_client, mock_nats_core, jsm, AsyncMock()) + assert len(binding.subscriptions) == 1 + + +class TestStatusMessagesInBindingMode: + """S2 -- a plain subscription receives the consumer's heartbeats and flow control requests.""" + + @staticmethod + def _status(reply: str = "") -> MagicMock: + msg = MagicMock(data=b"", reply=reply, subject="acme.agent.A.risk", headers={"Status": "100", "Description": "Idle Heartbeat"}) + msg.respond = AsyncMock() + for name in ("ack", "nak", "term"): + setattr(msg, name, AsyncMock()) + return msg + + async def test_a_flow_control_request_is_answered_and_never_run( + self, nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock + ) -> None: + callback = AsyncMock() + binding, handler = await _bound(nats_client, mock_nats_core, jsm, callback) + msg = self._status(reply="$JS.FC.NOTIFICATIONS_A.x") + + await _settled(binding, handler, msg) + + msg.respond.assert_awaited_once_with(b"") + callback.assert_not_awaited() + msg.term.assert_not_awaited() + + async def test_an_idle_heartbeat_is_dropped(self, nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock) -> None: + callback = AsyncMock() + binding, handler = await _bound(nats_client, mock_nats_core, jsm, callback) + msg = self._status() + + await _settled(binding, handler, msg) + + msg.respond.assert_not_awaited() + callback.assert_not_awaited() + msg.term.assert_not_awaited() diff --git a/tests/unit/agents/clients/io/test_nats_connection_readiness.py b/tests/unit/agents/clients/io/test_nats_connection_readiness.py index c0df5739..c53bbdba 100644 --- a/tests/unit/agents/clients/io/test_nats_connection_readiness.py +++ b/tests/unit/agents/clients/io/test_nats_connection_readiness.py @@ -75,6 +75,7 @@ async def open(self, link: Any) -> None: core = MagicMock(is_closed=False, is_reconnecting=False) core.subscribe = AsyncMock(return_value=MagicMock(drain=AsyncMock(), unsubscribe=AsyncMock())) core.close = AsyncMock() + core.flush = AsyncMock() self.cores[link.name] = core link.nats_client = core diff --git a/tests/unit/agents/clients/io/test_nats_connection_source.py b/tests/unit/agents/clients/io/test_nats_connection_source.py index e7a88304..1b1abf8b 100644 --- a/tests/unit/agents/clients/io/test_nats_connection_source.py +++ b/tests/unit/agents/clients/io/test_nats_connection_source.py @@ -3,6 +3,7 @@ import asyncio import contextvars import json +import ssl from collections.abc import Iterator from contextlib import contextmanager from typing import Any @@ -107,7 +108,10 @@ async def _bound_handler(nats_client: NATSClient, mock_nats_core: MagicMock, nam """Bind the named binding ``name`` on a mocked link and return it with its broker callback.""" binding = next(binding for binding in nats_client._named if binding.link.name == name) core = MagicMock( - subscribe=AsyncMock(return_value=MagicMock(drain=AsyncMock(), unsubscribe=AsyncMock())), close=AsyncMock(), is_closed=False + subscribe=AsyncMock(return_value=MagicMock(drain=AsyncMock(), unsubscribe=AsyncMock())), + close=AsyncMock(), + flush=AsyncMock(), + is_closed=False, ) binding.link.nats_client = core await nats_client._bind(binding) @@ -153,6 +157,12 @@ def test_an_unusable_spec_is_refused(self, kwargs: dict) -> None: with pytest.raises(ValueError): ConnectionSpec(**{"name": "A", "url": "nats://h:4222", **kwargs}) + def test_a_new_tls_context_alone_is_no_change(self) -> None: + """S3 -- an SSLContext equals only itself; a source building one per call rebound every tls:// link on every notify.""" + first = ConnectionSpec(name="A", url="tls://h:4222", tls=ssl.create_default_context()) + second = ConnectionSpec(name="A", url="tls://h:4222", tls=ssl.create_default_context()) + assert first == second + class TestPlanningTheBindings: async def test_claimed_subjects_never_go_to_the_default_connection(self, nats_client: NATSClient) -> None: diff --git a/tests/unit/agents/clients/io/test_nats_runtime_changes.py b/tests/unit/agents/clients/io/test_nats_runtime_changes.py index 097c5fa4..1c93b7e1 100644 --- a/tests/unit/agents/clients/io/test_nats_runtime_changes.py +++ b/tests/unit/agents/clients/io/test_nats_runtime_changes.py @@ -84,7 +84,7 @@ async def open(self, link: Any) -> None: if self.fail_next.get(link.name, 0): self.fail_next[link.name] -= 1 raise ConnectionError(f"{link.name} not reachable yet") - core = MagicMock(is_closed=False) + core = MagicMock(is_closed=False, flush=AsyncMock()) sub = MagicMock(drain=AsyncMock(), unsubscribe=AsyncMock()) async def subscribe(*args: Any, **kwargs: Any) -> MagicMock: @@ -225,6 +225,56 @@ async def test_the_old_link_keeps_serving_until_the_new_one_binds(self, nats_cli await _settled(nats_client) assert broker.events[-2:] == ["bind A#2", "close A#1"] + async def test_a_second_change_before_the_first_bound_still_retires_the_old_link(self, nats_client: NATSClient, broker: Broker) -> None: + """M3 -- the middle binding never bound; chaining it left the first one consuming for good.""" + source = WatchedSource(A=_binding("A")) + await _started(nats_client, source, broker) + broker.fail_next["A"] = 10_000 + source.passwords["A"] = "PLACEHOLDER-2" + source.notify() + await asyncio.sleep(0.05) + source.passwords["A"] = "PLACEHOLDER-3" + source.notify() + await asyncio.sleep(0.05) + assert "close A#1" not in broker.events, "the old link serves until the newest one binds" + + broker.fail_next["A"] = 0 + await _settled(nats_client) + + assert broker.events == ["bind A#1", "bind A#2", "close A#1"] + assert [binding.link.nats_client for binding in nats_client._named] == [broker.links["A"][1]] + + async def test_a_removal_before_the_change_bound_retires_both(self, nats_client: NATSClient, broker: Broker) -> None: + """M3 -- removing retired the pending binding only; the bound one it was to replace kept consuming.""" + source = WatchedSource(A=_binding("A")) + await _started(nats_client, source, broker) + broker.fail_next["A"] = 10_000 + source.passwords["A"] = "PLACEHOLDER-2" + source.notify() + await asyncio.sleep(0.05) + + source.change() + await _settled(nats_client) + + assert "close A#1" in broker.events + assert nats_client._named == [] + + async def test_a_reconnect_restores_readiness_only_for_a_bound_binding(self, nats_client: NATSClient, broker: Broker) -> None: + """A binding whose bind failed has no subscription for nats-py to replay.""" + source = WatchedSource(A=_binding("A")) + await _started(nats_client, source, broker) + binding = nats_client._named[0] + binding.bound = False + binding.subscriptions_ready = False + assert binding.link.nats_client is not None + + with patch.object(nats_client_module.nats, "connect", new_callable=AsyncMock, return_value=MagicMock(is_closed=False)) as connect: + binding.link.nats_client = None + await NATSClient._open_named_link(nats_client, binding.link) + await connect.call_args.kwargs["reconnected_cb"]() + + assert binding.subscriptions_ready is False + async def test_an_unchanged_connection_is_left_alone(self, nats_client: NATSClient, broker: Broker) -> None: source = WatchedSource(A=_binding("A")) await _started(nats_client, source, broker) From 871fd7ab1d8d8dc8f27fb97067dc6f65c27713c4 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:14:51 +0200 Subject: [PATCH 108/133] fix(group): refuse scalar lists, duplicate groups, unknown critical agents and empty groups Step 7 (M7, N2, D8). Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 7 ++++ ...26-08-28-multi-agent-grouping-changelog.md | 4 ++ .../agent_generator/docs/guides/deployment.md | 6 ++- .../docs/guides/multi-agent-setup.md | 5 +++ src/blueprint/agents/agent_group.py | 7 ++++ src/blueprint/agents/group_config.py | 39 ++++++++++++++++++- tests/unit/agents/TESTS.md | 4 +- tests/unit/agents/test_agent_group.py | 13 +++++++ tests/unit/agents/test_group_config.py | 37 ++++++++++++++++++ 9 files changed, 117 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 12e830b2..4d167c2f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,13 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **A group file that says something other than what it means now fails startup.** A name in + `critical_agents` (or `BLUEPRINT_CRITICAL_AGENTS`) that the group does not run made every agent + non-critical -- also when `BLUEPRINT_AGENTS` replaced the file's list, whose `critical_agents` still + applies. `agents: order` (a scalar) was read letter by letter, a group declared twice in one file + resolved to whichever came last, and a group whose agents were all skipped started with none and + reported ready. Each of these is now a `GroupConfigError` naming the problem. + - **Named connections changed at runtime no longer leave an old link consuming.** A connection changed twice before its new binding was bound, or changed and then removed, kept its original link subscribed for good: only the not-yet-bound binding in between was retired. Measured on a broker diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 6587da51..aaaaaf5c 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,10 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 7, group config validation (M7, N2, D8): unknown critical names (also against a + `BLUEPRINT_AGENTS`-replaced list), scalar `agents`/`critical_agents` and duplicate group names raise + `GroupConfigError`; `AgentGroup.from_config` refuses a group left with no agent. Unit tests fail on the + old code; the live check runs with the group image (step 14). - Step 6, named bindings (M3, M4, S2, S3): a binding superseded before it bound is retired at once and hands over the binding still delivering, and a removal retires that one too; `_bind` flushes and fails on a refusal naming its deliver subject (compared lowercased -- nats-py lowercases the -ERR line, found diff --git a/src/blueprint/agent_generator/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md index 8cf29e47..ab54c9eb 100644 --- a/src/blueprint/agent_generator/docs/guides/deployment.md +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -302,7 +302,11 @@ diff. `critical_agents` decides two things at once: whether the process starts at all when that agent cannot be loaded, and whether that agent can take the pod out of service rotation. The default is **critical** for every agent in the group. Naming a subset is the deliberate choice to run the rest -without the others. +without the others. Every name in `critical_agents` must be an agent the group runs -- also when +`BLUEPRINT_AGENTS` replaces the file's agent list -- or startup fails: a name that matches none +would make every agent non-critical. `agents` and `critical_agents` are lists (`[order]`, never a +bare `order`), a group name appears once per file, and a group none of whose agents could be loaded +fails startup instead of running empty. ### Deploying diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md index a8aa3921..c3632516 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md @@ -339,6 +339,11 @@ groups: pod's readiness. The default is **critical**: an agent that fails to load stops the process, because a pod that passes its probes while one agent's queue silently backs up is a worse failure than no pod at all. Naming an agent non-critical is the deliberate choice to run the rest without it. +Every name in `critical_agents` must be an agent the group runs -- also when +`BLUEPRINT_AGENTS` replaces the file's agent list -- or startup fails: a name that matches none +would make every agent non-critical. `agents` and `critical_agents` are lists (`[order]`, never a +bare `order`), a group name appears once per file, and a group none of whose agents could be loaded +fails startup instead of running empty. ### Environment diff --git a/src/blueprint/agents/agent_group.py b/src/blueprint/agents/agent_group.py index 840bfd24..2dac3ed7 100644 --- a/src/blueprint/agents/agent_group.py +++ b/src/blueprint/agents/agent_group.py @@ -253,6 +253,13 @@ def from_config(cls, group: GroupConfig) -> "AgentGroup": else: logger.debug("Agent '%s' ships no settings of its own (looked at %s)", spec.name, fragment) + if not agents: + # Every agent was non-critical and none loaded. A pod with no agent passes its probes + # while it consumes nothing at all -- the exact failure criticality exists to prevent (M7). + raise GroupConfigError( + f"Group '{group.name}' has no agent left to run: every one of {', '.join(group.agent_names) or 'none'} " + "was skipped. Fix the agents above, or mark the one this pod must run as critical." + ) return cls(group.name, agents, settings=settings, roots=roots, critical=critical) @staticmethod diff --git a/src/blueprint/agents/group_config.py b/src/blueprint/agents/group_config.py index bf7494f0..65f59d38 100644 --- a/src/blueprint/agents/group_config.py +++ b/src/blueprint/agents/group_config.py @@ -260,6 +260,15 @@ def _read_group_file(cls, env: dict[str, str] | Any, root: Path) -> dict[str, An if not isinstance(groups, list) or not groups: raise GroupConfigError(f"Group file {path} declares no 'groups' list, so no group can be resolved from it.") + names = [str(entry.get("name", "")) for entry in groups if isinstance(entry, dict)] + duplicates = sorted({group_name for group_name in names if names.count(group_name) > 1}) + if duplicates: + # Last one wins, silently, was the behaviour (N2): which agents a pod ran depended on + # the order of the file, and an edit to one copy did nothing. + raise GroupConfigError( + f"Group file {path} declares {', '.join(repr(group_name) for group_name in duplicates)} more than once. " + "A group name must be unique: which copy applies would depend on the order of the file." + ) by_name = {str(entry.get("name", "")): entry for entry in groups if isinstance(entry, dict)} requested = requested_group @@ -390,9 +399,22 @@ def _apply_env_overrides(env: dict[str, str] | Any, declared: dict[str, Any]) -> def _split(raw: str) -> list[str]: return [part.strip() for part in raw.split(",") if part.strip()] + def _names(key: str) -> list[str]: + # A list, and nothing else: a YAML scalar ('agents: invoice') was iterated character by + # character, and the error that followed named an agent called 'i' (M7, N2). + value = declared.get(key) + if value is None: + return [] + if not isinstance(value, list): + raise GroupConfigError( + f"'{key}' of group '{declared.get('name', '')}' must be a list of agent names, got a " + f"{type(value).__name__} ({value!r}). Write it as {key}: [name, ...]." + ) + return [str(agent).strip() for agent in value if str(agent).strip()] + name = str(declared.get("name", "") or "").strip() - agents = [str(agent).strip() for agent in declared.get("agents", []) or [] if str(agent).strip()] - critical = {str(agent).strip() for agent in declared.get("critical_agents", []) or [] if str(agent).strip()} + agents = _names("agents") + critical = set(_names("critical_agents")) sources = {"name": "file", "agents": "file", "critical_agents": "file"} if override := str(env.get(GROUP_ENV, "") or "").strip(): @@ -411,6 +433,19 @@ def _split(raw: str) -> list[str]: for key, source in sources.items(): if source != "file" or declared: logger.info("Group value '%s' resolved from %s", key, source) + + unknown = sorted(critical - set(agents)) + if unknown: + # Refused rather than ignored (plan D8): a critical set names the agents that are + # critical, so every agent it does not name is not. A typo in it therefore made every + # agent non-critical, and a group whose agents all fail to load ran empty and ready. + # With $BLUEPRINT_AGENTS replacing the file's list, the file's critical_agents still + # applies and must name agents of the new list. + raise GroupConfigError( + f"'critical_agents' (from {sources['critical_agents']}) names {', '.join(unknown)}, which group " + f"'{name}' does not run (its agents, from {sources['agents']}: {', '.join(agents) or 'none'}). Every " + "agent it does not name is non-critical, so a name that matches none makes the whole group non-critical." + ) return name, agents, critical @staticmethod diff --git a/tests/unit/agents/TESTS.md b/tests/unit/agents/TESTS.md index 65521609..82e76b70 100644 --- a/tests/unit/agents/TESTS.md +++ b/tests/unit/agents/TESTS.md @@ -13,8 +13,8 @@ Each subdirectory has its own `TESTS.md` for the package it covers. | File | Class under test | What is covered | |---|---|---| -| `test_agent_group.py` | `AgentGroup` | One namespace per agent (each agent's components qualified, a group of one, a mapping refusing two agents under one name); agent names (illegal names and the root refused); what a group refuses and does not (an already-built builder, `AppBuilder(config)`, a constructed instance, a factory accepted, nothing assembled when a refusal fires); caches (a group declares none, an agent's own is registered to it, two agents declaring one name get separate stores, neither can read the other's); loading a declaration (a missing module, a missing attribute, a non-`AppBuilder`, an import that raises -- each fatal for a critical agent and skipped with an ERROR otherwise); `from_config` performing no I/O of its own; `resolve` reading the environment and the group file; that the builder learns nothing about groups; and each agent's own settings file (looked for beside the declaration module, merged under that agent's scope, merged *before* its components are built, and not reaching a neighbour) | -| `test_group_config.py` | `GroupConfig`, `AgentSpec` | Reading the group file (the named group, another group in the same file, a single group needing no name, the agent's module coming from the image's agent map, a `cache_names` list now read by nothing); resolution from the environment alone; precedence (the environment overriding the file key by key, the file's other values surviving, the source of each value logged, the resolved group logged); criticality (a critical agent's failure fatal, a non-critical one skipped); validation against the agent map (an unknown name refused, a duplicate); agent names held to the namespace alphabet; and the value object itself (constructed literally, frozen) | +| `test_agent_group.py` | `AgentGroup` | One namespace per agent (each agent's components qualified, a group of one, a mapping refusing two agents under one name); agent names (illegal names and the root refused); what a group refuses and does not (an already-built builder, `AppBuilder(config)`, a constructed instance, a factory accepted, nothing assembled when a refusal fires); caches (a group declares none, an agent's own is registered to it, two agents declaring one name get separate stores, neither can read the other's); loading a declaration (a missing module, a missing attribute, a non-`AppBuilder`, an import that raises -- each fatal for a critical agent and skipped with an ERROR otherwise); `from_config` performing no I/O of its own; `resolve` reading the environment and the group file; that the builder learns nothing about groups; and each agent's own settings file (looked for beside the declaration module, merged under that agent's scope, merged *before* its components are built, and not reaching a neighbour); a group none of whose non-critical agents loaded fails (M7) | +| `test_group_config.py` | `GroupConfig`, `AgentSpec` | Reading the group file (the named group, another group in the same file, a single group needing no name, the agent's module coming from the image's agent map, a `cache_names` list now read by nothing); resolution from the environment alone; precedence (the environment overriding the file key by key, the file's other values surviving, the source of each value logged, the resolved group logged); criticality (a critical agent's failure fatal, a non-critical one skipped); validation against the agent map (an unknown name refused, a duplicate); agent names held to the namespace alphabet; and the value object itself (constructed literally, frozen); a critical name the group does not run (also after `BLUEPRINT_AGENTS` replaced the list, D8), a scalar `agents` or `critical_agents`, and a group declared twice are refused (M7, N2) | | `test_entrypoint.py` | `build_group_app`, `main` | `build_group_app` resolving the group and returning the application with its configuration; `main` returning `0` on a clean run and `1` for a group that cannot be resolved, printing the reason to stderr as well as logging it; that the module is runnable as `python -m blueprint.agents.entrypoint`; and that one declaration serves both deployment shapes -- the same `AppBuilder` built standalone and assembled into a group | | `test_design_rules.py` | The design rules in `AGENTS.md` | One section per rule, each failure message naming the rule it enforces. *Collect, then wire* and *one declaration surface*: every `with_*` on `AppBuilder` and `AgentBuilder` is discovered rather than listed (a new one fails the file until it has a sample call) and called reflectively -- nothing constructed, no configuration needed, the builder returned; and per `AppBuilder` method, one declaration recorded, `replay` reproducing it, the namespace taken from the scope, and the recorded `kind` having a `with_`. *A lookup never falls back across agents*: two agents' caches of one name kept apart, and no fallback to a neighbour, to the root, or from an unknown name to the default. *A component never learns it is in a group*: the ambient namespace, no `get_known_namespaces`, and the two refusals a view gives (`cache_entries`, `for_namespace`). *A name is validated, never repaired*: five namespace entry points and the deployment route against seven illegal names, the cache alphabet, and a legal name coming back unchanged. *No public read path to the unscoped loader*: the public configuration surface is exactly `config`, `configure`, `has_config`, and a namespaced component reads through its view. *Logging is configured by the application*: no logging configuration at import time anywhere in `src/`, and none in the framework outside `LoggingManager`. *No diagnostics via print*: none in the framework beyond the two listed stderr writes. *References resolve*: every markdown link, every cited path in the documents that describe the tree as it stands, and every document cited by name | | `test_frozen_compatibility.py` | `AppBuilder`, `Registry`, `Component` | **Frozen (spec sec. 10.2): never updated for an API change.** What an existing single-agent project already does -- the builder shapes the examples use including instance forms; `with_cache(False)` and `with_cache(True, False)` positionally; the registry names lookups use (derived, explicit, the cache backend's, the `cache_service` alias, two services resolving one cache); the paths a project serves (`/api/` with its own tags, `/api/cache/stats`, the actuators); the readiness entries (`cache`, a bare custom name); and a component constructed with `super().__init__()` needing no change | diff --git a/tests/unit/agents/test_agent_group.py b/tests/unit/agents/test_agent_group.py index 5424d917..0cae6202 100644 --- a/tests/unit/agents/test_agent_group.py +++ b/tests/unit/agents/test_agent_group.py @@ -336,6 +336,19 @@ def test_a_non_critical_agent_is_skipped(self, caplog: pytest.LogCaptureFixture) assert list(assembled.agents) == ["billing"] assert "is not critical, so it is skipped" in caplog.text + def test_a_group_left_with_no_agent_fails(self) -> None: + """M7 -- every agent non-critical and none loadable: the pod ran empty and reported ready.""" + group = GroupConfig( + name="finance", + agents=( + AgentSpec(name="order", module="no.such.module:declaration", root=Path("agents") / "order", critical=False), + AgentSpec(name="billing", module="no.such.module:declaration", root=Path("agents") / "billing", critical=False), + ), + ) + + with pytest.raises(GroupConfigError, match="no agent left to run: every one of order, billing was skipped"): + AgentGroup.from_config(group) + def test_a_skipped_agent_does_not_stop_the_ones_after_it(self, config: Config) -> None: group = GroupConfig( name="finance", diff --git a/tests/unit/agents/test_group_config.py b/tests/unit/agents/test_group_config.py index bb799c68..15ada02c 100644 --- a/tests/unit/agents/test_group_config.py +++ b/tests/unit/agents/test_group_config.py @@ -223,6 +223,43 @@ def test_the_file_can_declare_the_subset(self, project: Config, tmp_path: Path) assert {agent.name: agent.critical for agent in group.agents} == {"invoice": False, "order": True} +class TestTheGroupFileMeansWhatItSays: + """M7, N2 -- every shape that silently resolved to a different group now fails startup.""" + + def test_a_critical_name_the_group_does_not_run_is_refused(self, project: Config) -> None: + """A typo in it made every agent non-critical.""" + with pytest.raises(GroupConfigError, match="names invocie, which group 'finance' does not run"): + GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP": "finance", "BLUEPRINT_CRITICAL_AGENTS": "invocie"}) + + def test_the_files_critical_list_still_applies_when_the_environment_replaces_the_agents(self, project: Config, tmp_path: Path) -> None: + """Plan D8: the file's list is kept, and a name outside the resolved group fails startup.""" + path = tmp_path / "with-critical.yaml" + path.write_text("groups:\n - name: finance\n agents: [invoice, order]\n critical_agents: [order]\n") + + with pytest.raises(GroupConfigError, match=r"from file\) names order.*from \$BLUEPRINT_AGENTS: invoice"): + GroupConfig.resolve( + project, environ={"BLUEPRINT_GROUP_CONFIG": str(path), "BLUEPRINT_GROUP": "finance", "BLUEPRINT_AGENTS": "invoice"} + ) + + @pytest.mark.parametrize("key", ["agents", "critical_agents"]) + def test_a_scalar_where_a_list_belongs_is_refused(self, project: Config, tmp_path: Path, key: str) -> None: + """It was iterated character by character.""" + path = tmp_path / "scalar.yaml" + lines = {"agents": "agents: invoice", "critical_agents": "agents: [invoice]\n critical_agents: invoice"} + path.write_text(f"groups:\n - name: finance\n {lines[key]}\n") + + with pytest.raises(GroupConfigError, match=f"'{key}' of group 'finance' must be a list of agent names, got a str"): + GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP_CONFIG": str(path)}) + + def test_a_group_declared_twice_is_refused(self, project: Config, tmp_path: Path) -> None: + """Last one won, silently: which agents ran depended on the order of the file.""" + path = tmp_path / "twice.yaml" + path.write_text("groups:\n - name: finance\n agents: [invoice]\n - name: finance\n agents: [order]\n") + + with pytest.raises(GroupConfigError, match="declares 'finance' more than once"): + GroupConfig.resolve(project, environ={"BLUEPRINT_GROUP_CONFIG": str(path), "BLUEPRINT_GROUP": "finance"}) + + class TestAgainstTheAgentMap: def test_an_agent_the_image_does_not_contain_is_refused(self, project: Config) -> None: """The seam that turns a config typo into a crash-loop with a readable message.""" From 2532b9afe0506fa2cee2828b84db184b50086276 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:14:52 +0200 Subject: [PATCH 109/133] fix(config): merge each agent's secrets, layer fragments for the loaded environment, reserve shared names Step 8 (M5, S11, S12, S13, D9). Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 15 +++ ...26-08-28-multi-agent-grouping-changelog.md | 6 + .../docs/guides/multi-agent-setup.md | 11 +- src/blueprint/agents/agent_group.py | 23 +++- src/blueprint/agents/component/namespace.py | 15 +++ src/blueprint/agents/config/config.py | 114 +++++++++++++++--- tests/unit/agents/component/TESTS.md | 2 +- tests/unit/agents/component/test_namespace.py | 11 ++ .../config/test_agent_settings_fragments.py | 71 +++++++++++ tests/unit/agents/test_agent_files.py | 11 ++ tests/unit/agents/test_agent_isolation.py | 13 ++ 11 files changed, 272 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d167c2f..88a6d0c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,21 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **An agent's own `.secrets.toml` is read in a group.** Only its `settings.toml` was merged, although + the layout check, the guides and `asbs setup` said the secrets beside it are read. It is now merged + first, so a secret wins over the settings file, and none of its values is logged. + +- **Agent settings are resolved for the environment the process actually loaded.** With + `ENV_FOR_DYNACONF` set, the process loaded that environment while every agent's file was layered for + `app_environment`; and each agent kept its other environments' sections as keys (`production` in + development). Both now follow what Dynaconf loaded. + +- **An agent can no longer read or overwrite what is not its own through its name.** `cache`, + `event_publishing`, `runtimes` and `runtime` are refused as agent names (an agent's settings would + have landed in the shared section); merging an agent's settings onto a plain key of the same name + fails instead of replacing it; and a view refuses a bare key naming another agent, which returned that + agent's whole section. + - **A group file that says something other than what it means now fails startup.** A name in `critical_agents` (or `BLUEPRINT_CRITICAL_AGENTS`) that the group does not run made every agent non-critical -- also when `BLUEPRINT_AGENTS` replaced the file's list, whose `critical_agents` still diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index aaaaaf5c..458933ac 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,12 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 8, agent settings merge (M5, S11, S12, S13, D9): an agent's `.secrets.toml` is merged before its + settings (`AgentGroup.secrets`, `merge_agent_settings(..., secret=True)` logs no value); fragments are + layered for `current_env` and inactive environment sections are dropped; `cache`, `event_publishing`, + `runtimes`, `runtime` are reserved namespaces and a root scalar is never replaced; a view refuses a bare + key naming an agent's section (`Config.declare_agent`). Repro of S13 first (ENV_FOR_DYNACONF=production: + root `prod`, fragment `frag-dev`); unit tests fail on the old code; live with the group image (step 14). - Step 7, group config validation (M7, N2, D8): unknown critical names (also against a `BLUEPRINT_AGENTS`-replaced list), scalar `agents`/`critical_agents` and duplicate group names raise `GroupConfigError`; `AgentGroup.from_config` refuses a group left with no agent. Unit tests fail on the diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md index c3632516..82a9fd8c 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md @@ -167,6 +167,11 @@ agents/ ... ``` +An agent's `.secrets.toml` is merged under that agent too, before its `settings.toml`, so a secret +wins over a value the settings file states for the same key; no value of it is ever logged. Both files +are resolved for the environment the process loaded (`ENV_FOR_DYNACONF` included), and a section for +another environment is dropped rather than kept as a key. + Each agent directory is exactly what `asbs setup` writes on its own, so moving one into its own repository means deleting its line from this map -- nothing inside the directory changes. An agent may keep its own `Dockerfile` to be built as a single-agent image at the same time. @@ -208,7 +213,11 @@ durable name: `orders-eu` on topic `created` and `orders` on topic `eu-created` produce the same durable, and two agents would bind one consumer and eat each other's events. The alphabet is the intersection of what a registry key, a queue group, a consumer name and a telemetry resource all accept, and a name outside it is **refused, never repaired** -- a name quietly rewritten -by four subsystems is four names for one agent. +by four subsystems is four names for one agent. Four names are reserved because they are +configuration sections the whole process shares -- `cache`, `event_publishing`, `runtimes`, +`runtime` -- and an agent whose name is already a plain key of the group's settings cannot bring +settings of its own. An agent's view refuses a key that names another agent (`orders`, or +`orders.model_name`): that is the neighbour's section, not configuration it may read. --- diff --git a/src/blueprint/agents/agent_group.py b/src/blueprint/agents/agent_group.py index 2dac3ed7..5ebe8f92 100644 --- a/src/blueprint/agents/agent_group.py +++ b/src/blueprint/agents/agent_group.py @@ -100,6 +100,7 @@ def __init__( agents: Mapping[str, AppBuilder], *, settings: Mapping[str, Path] | None = None, + secrets: Mapping[str, Path] | None = None, roots: Mapping[str, Path] | None = None, critical: Collection[str] | None = None, ) -> None: @@ -119,6 +120,9 @@ def __init__( exists. :meth:`from_config` takes these from each agent's stated ``root``; a group constructed literally passes them, or passes none and every agent's settings then come from the group's own file. + secrets: Each agent's own ``.secrets.toml``, keyed by agent name. Merged under the + agent's scope before its settings file, so a secret wins over a value the settings + file states for the same key, and no value of it is ever logged (M5). roots: Each agent's own directory, keyed by agent name. It is what the agent's configuration view reports as its package root, so the agent's prompts are found under its own ``src/prompts`` rather than under the process's working directory -- @@ -139,6 +143,7 @@ def __init__( ) self._agents[namespace] = builder self._settings: dict[str, Path] = {name: Path(path) for name, path in (settings or {}).items()} + self._secrets: dict[str, Path] = {name: Path(path) for name, path in (secrets or {}).items()} self._roots: dict[str, Path] = {name: Path(path) for name, path in (roots or {}).items()} self._critical: frozenset[str] = frozenset(self._agents) if critical is None else frozenset(critical) @@ -157,6 +162,11 @@ def settings(self) -> Mapping[str, Path]: """Where each agent's own settings file is, for the agents that have one.""" return dict(self._settings) + @property + def secrets(self) -> Mapping[str, Path]: + """Where each agent's own ``.secrets.toml`` is, for the agents that have one.""" + return dict(self._secrets) + @property def roots(self) -> Mapping[str, Path]: """Each agent's own directory, keyed by agent name.""" @@ -222,6 +232,7 @@ def from_config(cls, group: GroupConfig) -> "AgentGroup": agents: dict[str, AppBuilder] = {} settings: dict[str, Path] = {} + secrets: dict[str, Path] = {} roots: dict[str, Path] = {} critical: set[str] = set() for spec in group.agents: @@ -252,6 +263,11 @@ def from_config(cls, group: GroupConfig) -> "AgentGroup": settings[spec.name] = fragment else: logger.debug("Agent '%s' ships no settings of its own (looked at %s)", spec.name, fragment) + # The agent's secrets beside it, as a standalone project keeps them: the layout check and + # the guides said they were read from there, and nothing did (M5). + secret_file = spec.root / ".secrets.toml" + if secret_file.is_file(): + secrets[spec.name] = secret_file if not agents: # Every agent was non-critical and none loaded. A pod with no agent passes its probes @@ -260,7 +276,7 @@ def from_config(cls, group: GroupConfig) -> "AgentGroup": f"Group '{group.name}' has no agent left to run: every one of {', '.join(group.agent_names) or 'none'} " "was skipped. Fix the agents above, or mark the one this pod must run as critical." ) - return cls(group.name, agents, settings=settings, roots=roots, critical=critical) + return cls(group.name, agents, settings=settings, secrets=secrets, roots=roots, critical=critical) @staticmethod def _load_declaration(spec: AgentSpec) -> AppBuilder | None: @@ -362,12 +378,17 @@ def assemble(self, config: Config) -> FastAPI: # every component reads its keys through its agent's scoped view during build(), so a # fragment merged afterwards would be a file that was read too late to matter. for namespace in self._agents: + config.declare_agent(namespace) # The root first: it is what the agent's view reports as its package root, and a # view taken before it is set would keep the process's root for the rest of the # process's life. agent_root = self._roots.get(namespace) if agent_root is not None: config.set_agent_root(namespace, agent_root) + # Secrets first: the merge fills in what is missing, so what comes first wins. + secret_file = self._secrets.get(namespace) + if secret_file is not None: + config.merge_agent_settings(namespace, secret_file, secret=True) path = self._settings.get(namespace) if path is not None: config.merge_agent_settings(namespace, path) diff --git a/src/blueprint/agents/component/namespace.py b/src/blueprint/agents/component/namespace.py index bdad4e45..2b213222 100644 --- a/src/blueprint/agents/component/namespace.py +++ b/src/blueprint/agents/component/namespace.py @@ -51,6 +51,14 @@ _ALLOWED_NAMESPACE = re.compile(r"\A[a-z][a-z0-9_]*\Z") """Lowercase, digits and underscore, starting with a letter. See :func:`validate_namespace`.""" +RESERVED_NAMESPACES = frozenset({"cache", "event_publishing", "runtimes", "runtime"}) +"""Names no agent may take: the configuration sections the whole process shares (S12). + +The same four names as ``config.SHARED_NESTED_PREFIXES`` -- a test keeps them equal; this module +cannot import the configuration package without a cycle. An agent's settings are merged under its +name, so an agent called ``cache`` would have written its own keys into the process's cache section. +""" + _DISPLAY_UNSAFE = re.compile(r"[<>.\s]+") """Characters a display segment cannot keep. See :func:`display_segment`.""" @@ -116,6 +124,13 @@ def validate_namespace(namespace: str) -> str: "part of a JetStream durable name and a telemetry service name, and those do not accept the same characters." ) + if namespace in RESERVED_NAMESPACES: + raise ValueError( + f"Namespace '{namespace}' is the name of a configuration section the whole process shares " + f"({', '.join(sorted(RESERVED_NAMESPACES))}). An agent's settings live under its name, so an agent " + f"called '{namespace}' would write its own settings into that shared section. Choose another name." + ) + return namespace diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index b47a7a6e..c3db6aea 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -46,6 +46,9 @@ class ConfigError(Exception): """ +CONVENTIONAL_ENVIRONMENTS = frozenset({"development", "production", "staging", "testing", "test"}) +"""Environment section names an agent's settings file may carry whether or not the process's own files use them.""" + SHARED_NESTED_PREFIXES = frozenset({"cache", "event_publishing", "runtimes", "runtime"}) """The dotted sections that belong to the process rather than to an agent. @@ -193,6 +196,10 @@ def __init__( self._agent_scope = agent_scope self._is_view = False self._views: dict[str, Config] = {} + # Every agent namespace this configuration has met: by a view, a merged file or a root. + # Shared with each view (copy() keeps the reference), so a view can refuse a bare key that + # names an agent's section without being able to list the agents itself (S11, C6). + self._agent_namespaces: set[str] = set() # Set on a view by for_namespace, so a view can ask the object that owns the tree to # flatten *its own* scope. Stripping the other agents' subsections needs the list of # namespaces, and a view deliberately does not have one (C6). @@ -292,6 +299,12 @@ def __init__( # by validate()'s exception handler. self.validate() + # The environment Dynaconf actually loaded, which is what an agent's fragment has to be + # layered for. The first pass's app_environment is only Dynaconf's starting point: + # ENV_FOR_DYNACONF wins over it, and then the root loaded [production] while every agent's + # fragment was layered for [development] (S13). + self._environment = str(self._settings.current_env or app_env).lower() + # Replace DOT placeholders dot_placeholder = self._settings.get("dot_placeholder", "") if dot_placeholder: @@ -469,6 +482,7 @@ def for_namespace(self, namespace: str) -> "Config": if cached is not None: return cached + self._agent_namespaces.add(namespace.lower()) view = copy(self) view._agent_scope = namespace view._is_view = True @@ -483,6 +497,20 @@ def for_namespace(self, namespace: str) -> "Config": self._views[namespace] = view return view + def declare_agent(self, namespace: str) -> None: + """Record that ``namespace`` is an agent this process hosts, before any agent code runs. + + A view then refuses a bare key of that name, which at the root is the agent's section + (S11). Called by :class:`~blueprint.agents.agent_group.AgentGroup` for every agent it + assembles; a view, a merged settings file and an agent root record their agent too. + + Raises: + RuntimeError: if called on a view, for the reason :meth:`set_agent_root` gives. + """ + if self._is_view: + raise RuntimeError(f"Namespace '{self._agent_scope}' tried to declare an agent. The group declares its agents.") + self._agent_namespaces.add(namespace.lower()) + def set_agent_root(self, namespace: str, root: Path | str) -> None: """Record where one agent's own files live, for the view that agent reads through. @@ -504,6 +532,7 @@ def set_agent_root(self, namespace: str, root: Path | str) -> None: "applied by the group before any agent has a view." ) resolved = Path(root) + self._agent_namespaces.add(namespace.lower()) self._agent_roots[namespace] = resolved cached = self._views.get(namespace) if cached is not None: @@ -541,7 +570,7 @@ def namespaces(self) -> tuple[str, ...]: ) return tuple(sorted(self._views)) - def merge_agent_settings(self, namespace: str, path: str | Path) -> tuple[str, ...]: + def merge_agent_settings(self, namespace: str, path: str | Path, *, secret: bool = False) -> tuple[str, ...]: """Merge one agent's own settings file under that agent's scope (spec sec. 5.3, D5). An agent author writes plain keys in their own directory's ``settings.toml`` -- @@ -578,6 +607,8 @@ def merge_agent_settings(self, namespace: str, path: str | Path) -> tuple[str, . the process's own settings files, which are loaded by ``__init__``. path: The agent's settings file. It need not exist; an agent that ships none is simply an agent with no settings of its own. + secret: The file holds secrets (the agent's ``.secrets.toml``): no value of it is + ever logged, the WARNING for a process-scope key included. Returns: The keys merged, sorted. Empty when the file is absent, holds nothing, or is one of @@ -602,6 +633,7 @@ def merge_agent_settings(self, namespace: str, path: str | Path) -> tuple[str, . "process's own settings files, which __init__ loads." ) + self._agent_namespaces.add(namespace.lower()) candidate = Path(path) resolved = (self._root_path / candidate).resolve() if resolved in self._settings_files: @@ -622,12 +654,20 @@ def merge_agent_settings(self, namespace: str, path: str | Path) -> tuple[str, . fragment = self._layer_fragment(document) self._refuse_self_scoped_fragment(namespace, resolved, fragment) - fragment = self._drop_process_scope_keys(namespace, resolved, fragment) + fragment = self._drop_process_scope_keys(namespace, resolved, fragment, secret=secret) if not fragment: logger.debug("The settings file of agent '%s' (%s) contributes nothing", namespace, resolved) return () existing = self._settings.get(namespace) + if existing is not None and not hasattr(existing, "items"): + # A root key of the agent's name that is not a table: merging would replace the value + # every other agent reads for that key with this agent's section (S12). + raise ConfigError( + f"Agent '{namespace}' cannot have settings of its own: the group's configuration already uses " + f"'{namespace}' as a key, with a value that is not a section. Merging the agent's file ({resolved}) " + "would replace that value for the whole process. Rename the agent or the key." + ) merged = dict(existing.items()) if hasattr(existing, "items") else {} added = self._fill_missing(merged, fragment) self._settings[namespace] = merged @@ -658,18 +698,43 @@ def _layer_fragment(self, document: dict[str, Any]) -> dict[str, Any]: """ sections = {str(key).lower(): value for key, value in document.items() if hasattr(value, "items")} layered: dict[str, Any] = {key: value for key, value in document.items() if not hasattr(value, "items")} - for section in ("default", self._environment.lower(), "global"): + active = ("default", self._environment, "global") + for section in active: values = sections.get(section) if values: layered.update({str(key): value for key, value in values.items()}) # A table the file wrote at the top level is a value, not a section: [cache] beside - # [default] is this agent's cache configuration, and it is only the three names above - # that mean "an environment". + # [default] is this agent's cache configuration. An environment section that is not + # active is neither: it is dropped, as Dynaconf drops the process's own. It was kept as a + # key, so every agent carried its [production] table as 'production' in development (S13). + environments = self._environment_names() for name, values in sections.items(): - if name not in ("default", self._environment.lower(), "global"): - layered.setdefault(name, values) + if name in active: + continue + if name in environments: + logger.debug("Agent settings: section [%s] is for another environment than '%s'; dropped", name, self._environment) + continue + layered.setdefault(name, values) return layered + def _environment_names(self) -> frozenset[str]: + """Every table name that is an environment section to this process, ``default`` and ``global`` excluded. + + The conventional ones, and every top-level table of the process's own settings files: in + environment mode Dynaconf reads each of those as an environment, so a fragment table of the + same name is one too. + """ + names = set(CONVENTIONAL_ENVIRONMENTS) + for path in self._settings_files: + if path.suffix != ".toml" or not path.is_file(): + continue + try: + document = tomllib.loads(path.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError): + continue + names.update(str(key).lower() for key, value in document.items() if isinstance(value, dict)) + return frozenset(names - {"default", "global"}) + @staticmethod def _refuse_self_scoped_fragment(namespace: str, path: Path, fragment: dict[str, Any]) -> None: """Refuse a fragment that already scopes its keys under the agent's own name. @@ -705,11 +770,12 @@ def _refuse_self_scoped_fragment(namespace: str, path: Path, fragment: dict[str, "standalone too, because a scoped lookup falls back to the root key." ) - def _drop_process_scope_keys(self, namespace: str, path: Path, fragment: dict[str, Any]) -> dict[str, Any]: + def _drop_process_scope_keys(self, namespace: str, path: Path, fragment: dict[str, Any], *, secret: bool = False) -> dict[str, Any]: """Return ``fragment`` without the keys an agent cannot set, warning about each. The warning carries what the process uses instead, because "your value is not used" is - only actionable next to the value that is. + only actionable next to the value that is -- except for a secrets file, whose values are + never logged, and the process's then neither. """ refused = PROCESS_SCOPE_KEYS | DEPLOYMENT_IDENTITY_KEYS kept: dict[str, Any] = {} @@ -718,14 +784,18 @@ def _drop_process_scope_keys(self, namespace: str, path: Path, fragment: dict[st kept[key] = value continue current = self._settings.get(str(key)) + if secret: + used = "the group's own value is used" if current is not None else "the group's settings do not set it" + else: + used = f"the group's own value ({current!r}) is used" if current is not None else "the group's settings do not set it" logger.warning( "Agent '%s' sets '%s' in %s, and that is a process-wide setting: one process has one of it, so this " - "value (%r) is ignored and %s. Remove it from the agent's settings file, or set it in the group's.", + "value (%s) is ignored and %s. Remove it from the agent's settings file, or set it in the group's.", namespace, key, path, - value, - f"the group's own value ({current!r}) is used" if current is not None else "the group's settings do not set it", + "" if secret else repr(value), + used, ) return kept @@ -919,9 +989,7 @@ def _convert_keyed_list_to_dict(items: Any) -> Any: ( self._process_dynabox(item, placeholder, replacement) if isinstance(item, (dict, DynaBox)) or hasattr(item, "items") - else _try_parse_json(item) - if isinstance(item, str) - else item + else _try_parse_json(item) if isinstance(item, str) else item ) for item in value ] @@ -971,12 +1039,24 @@ def _refuse_a_foreign_section(self, key: str) -> None: Args: key: The key being resolved, before the root fallback runs. + A bare key is refused by the same rule when it is an agent's name (plan D9): the root key + ``billing`` *is* billing's section, so ``for_namespace("orders").get("billing")`` returned + a neighbour's whole configuration through the fallback (S11). + Raises: ValueError: if ``key`` is dotted and its first segment is not one of the framework's - own nested sections. + own nested sections, or if it is bare and names an agent. """ head = key.split(".", 1)[0] - if "." not in key or head in SHARED_NESTED_PREFIXES: + if "." not in key: + if key.lower() in self._agent_namespaces and hasattr(self._settings.get(key), "items"): + raise ValueError( + f"Agent '{self._agent_scope}' cannot read '{key}': that is the name of an agent, and the key at " + "the root of the configuration tree is that agent's section. An agent reads its own keys and " + "the process's shared ones." + ) + return + if head in SHARED_NESTED_PREFIXES: return raise ValueError( f"Agent '{self._agent_scope}' cannot read '{key}': its first segment names a section of the " diff --git a/tests/unit/agents/component/TESTS.md b/tests/unit/agents/component/TESTS.md index 048a51f4..bc120cf0 100644 --- a/tests/unit/agents/component/TESTS.md +++ b/tests/unit/agents/component/TESTS.md @@ -12,7 +12,7 @@ Test coverage for `src/blueprint/agents/component/component.py` and | `test_component.py` | `Component`, `_ComponentMeta` | `configure`, `init_registry`, `__init__`, properties, `name` setter, namespace taken from the ambient scope (bare `super().__init__()` in a `ServiceBase` subclass, two scopes yielding two qualified names, explicit non-empty namespace still winning), `executor` resolving to the namespace's pool (not shared across agents, shared within one, sized from the scoped `executor_workers`), `registry` returning the namespace's view (the registry itself at the root, this agent's components for an unqualified lookup, two agents resolving their own of one class) | | `test_component.py` | `_is_cloud_event`, `_stamp_span` | Helper function correctness | | `test_component.py` | `traced` decorator | Async/sync span creation, error status, CloudEvent/plain-value stamping | -| `test_namespace.py` | `namespace.py` helpers | `validate_namespace`, `qualified_component_name`, `namespace_of`, `display_segment`, `resolve_for_namespace`, and `namespace_scope`/`current_namespace` (default root, set/exit, exit on exception, nesting, validation on entry) | +| `test_namespace.py` | `namespace.py` helpers | `validate_namespace`, `qualified_component_name`, `namespace_of`, `display_segment`, `resolve_for_namespace`, and `namespace_scope`/`current_namespace` (default root, set/exit, exit on exception, nesting, validation on entry); the four shared configuration sections are refused as namespaces, and the reserved list equals `SHARED_NESTED_PREFIXES` (S12) | | `test_registry.py` | `Registry` | Construction, add/get/has/rename/clear, type-based lookups, `cache_service`; namespaced lookup (bare name resolving to the asking namespace, root fallback, already-qualified names, the error naming where it looked), type queries (`None` = every namespace, a namespace = that agent exactly, filtering by attribute not name, ambiguity refused across and within a namespace), and that `get_known_namespaces` does not exist (C6); named caches (lookup by name, no fallback to the default, the error listing what is registered, the `cache_service` alias both ways, `get_all_caches` copying, `clear` clearing every cache, replace-and-warn on a second registration); per-namespace executors (none until asked, create then reuse, isolation, sizing on the creating call only, thread naming, shutdown from `clear` and `shutdown_executors`); namespace views (`for_namespace` identity at the root, caching, the shared store, the C6 refusal on a view, omitted-means-this-agent, root fallback for name and class lookups, plural lookups scoped to one agent, explicit override, and the application registry still seeing everything) | --- diff --git a/tests/unit/agents/component/test_namespace.py b/tests/unit/agents/component/test_namespace.py index 93f3d156..c896d802 100644 --- a/tests/unit/agents/component/test_namespace.py +++ b/tests/unit/agents/component/test_namespace.py @@ -2,7 +2,9 @@ import pytest +from blueprint.agents.config.config import SHARED_NESTED_PREFIXES from blueprint.agents.component.namespace import ( + RESERVED_NAMESPACES, ROOT_LABEL, ROOT_NAMESPACE, current_namespace, @@ -107,6 +109,15 @@ def test_whitespace_only_namespace_is_not_the_root(self) -> None: with pytest.raises(ValueError, match="is not the root namespace"): validate_namespace(" ") + @pytest.mark.parametrize("namespace", sorted(RESERVED_NAMESPACES)) + def test_a_shared_configuration_section_is_not_a_namespace(self, namespace: str) -> None: + """S12 -- an agent's settings are merged under its name, which would land in the process's section.""" + with pytest.raises(ValueError, match="configuration section the whole process shares"): + validate_namespace(namespace) + + def test_the_reserved_names_are_the_shared_sections(self) -> None: + assert RESERVED_NAMESPACES == SHARED_NESTED_PREFIXES + def test_the_error_names_the_offending_characters(self) -> None: with pytest.raises(ValueError, match="'A'"): validate_namespace("Agent") diff --git a/tests/unit/agents/config/test_agent_settings_fragments.py b/tests/unit/agents/config/test_agent_settings_fragments.py index b650f1b8..1fb5dc06 100644 --- a/tests/unit/agents/config/test_agent_settings_fragments.py +++ b/tests/unit/agents/config/test_agent_settings_fragments.py @@ -293,3 +293,74 @@ def test_a_broken_file_is_reported_not_skipped(self, config: Config, tmp_path: P """A file that is there was meant to be used, so failing to read it is an error.""" with pytest.raises(ConfigError, match="could not be read"): config.merge_agent_settings("orders", fragment(tmp_path, "orders", "this is not = = toml\n")) + + +class TestTheEnvironmentTheProcessLoaded: + """S13 -- a fragment is layered for the environment Dynaconf loaded, and no other section survives as a key.""" + + def test_env_for_dynaconf_decides_for_the_fragment_too(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """ENV_FOR_DYNACONF wins over app_environment; the root loaded [production], the agent [development].""" + (tmp_path / "settings.toml").write_text('[production]\nmarker = "prod"\n[development]\nmarker = "dev"\n') + monkeypatch.setenv("ENV_FOR_DYNACONF", "production") + config = Config(settings_files=["settings.toml"], root_path=str(tmp_path)) + body = '[development]\nmodel_name = "frag-dev"\n[production]\nmodel_name = "frag-prod"\n' + + config.merge_agent_settings("orders", fragment(tmp_path, "orders", body)) + + assert config.get("marker") == "prod" + assert config.for_namespace("orders").get("model_name") == "frag-prod" + + def test_an_inactive_environment_section_is_dropped(self, config: Config, tmp_path: Path) -> None: + body = "[default]\ntemperature = 0.2\n[production]\ntemperature = 0.0\n[staging]\ntemperature = 0.1\n" + + config.merge_agent_settings("orders", fragment(tmp_path, "orders", body)) + + assert sorted(dict(config.get("orders")).keys()) == ["temperature"] + + def test_a_section_the_processs_own_file_uses_as_an_environment_is_one(self, tmp_path: Path) -> None: + (tmp_path / "settings.toml").write_text('[default]\napp_environment = "development"\n[qa]\nmarker = "qa"\n') + config = Config(settings_files=["settings.toml"], root_path=str(tmp_path)) + + config.merge_agent_settings("orders", fragment(tmp_path, "orders", 'model_name = "m"\n[qa]\nmodel_name = "qa"\n')) + + assert "qa" not in {key.lower() for key in dict(config.get("orders"))} + + +class TestTheProcessesSectionsAreNotAnAgents: + """S12 -- an agent's settings are merged under its name; that name must not be the process's.""" + + def test_a_root_scalar_of_the_agents_name_is_not_replaced(self, tmp_path: Path) -> None: + (tmp_path / "settings.toml").write_text('[default]\napp_environment = "development"\nmodel_name = "group-model"\n') + config = Config(settings_files=["settings.toml"], root_path=str(tmp_path)) + + with pytest.raises(ConfigError, match="already uses 'model_name' as a key"): + config.merge_agent_settings("model_name", fragment(tmp_path, "model_name", "x = 1\n")) + + assert config.get("model_name") == "group-model" + + +class TestAnAgentsOwnSecrets: + """M5 -- an agent's ``.secrets.toml`` is merged, before its settings, and none of its values is logged.""" + + @staticmethod + def secrets(tmp_path: Path, agent: str, body: str) -> Path: + path = tmp_path / "pkg" / agent / ".secrets.toml" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(body) + return path + + def test_a_secret_wins_over_the_settings_file(self, config: Config, tmp_path: Path) -> None: + config.merge_agent_settings("orders", self.secrets(tmp_path, "orders", 'model_api_key = "PLACEHOLDER-SECRET"\n'), secret=True) + config.merge_agent_settings("orders", fragment(tmp_path, "orders", 'model_api_key = "from-settings"\nmodel_name = "m"\n')) + + view = config.for_namespace("orders") + assert view.get("model_api_key") == "PLACEHOLDER-SECRET" + assert view.get("model_name") == "m" + + def test_no_value_of_a_secrets_file_is_logged(self, config: Config, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: + body = 'model_api_key = "PLACEHOLDER-SECRET"\nlog_level = "PLACEHOLDER-SECRET-2"\n' + with caplog.at_level("DEBUG"): + config.merge_agent_settings("orders", self.secrets(tmp_path, "orders", body), secret=True) + + assert "PLACEHOLDER-SECRET" not in caplog.text + assert "log_level" in caplog.text, "the process-scope key is still reported, by name" diff --git a/tests/unit/agents/test_agent_files.py b/tests/unit/agents/test_agent_files.py index 9491589c..434ac0cd 100644 --- a/tests/unit/agents/test_agent_files.py +++ b/tests/unit/agents/test_agent_files.py @@ -128,6 +128,17 @@ def test_each_agent_resolves_its_own_prompt(self, two_agents: Path) -> None: assert PromptLoader.load_prompt("system", config.for_namespace("alpha")) == "ALPHA PROMPT" assert PromptLoader.load_prompt("system", config.for_namespace("beta")) == "BETA PROMPT" + def test_each_agents_own_secrets_are_read_and_win(self, two_agents: Path) -> None: + """M5 -- the layout check and the guides said secrets are read from beside src; nothing read them.""" + (two_agents / "services/beta/.secrets.toml").write_text('model_name = "beta-secret-model"\n', encoding="utf-8") + config = process_config(two_agents) + group = AgentGroup.from_config(GroupConfig.resolve(config, environ={"BLUEPRINT_AGENTS": "alpha,beta"})) + group.assemble(config) + + assert group.secrets == {"beta": two_agents / "services/beta/.secrets.toml"} + assert config.for_namespace("beta").get("model_name") == "beta-secret-model" + assert config.for_namespace("alpha").get("model_name") == "alpha-model" + def test_the_package_root_each_agent_sees_is_its_own(self, two_agents: Path) -> None: config = process_config(two_agents) AgentGroup.from_config(GroupConfig.resolve(config, environ={"BLUEPRINT_AGENTS": "alpha,beta"})).assemble(config) diff --git a/tests/unit/agents/test_agent_isolation.py b/tests/unit/agents/test_agent_isolation.py index 9237ceea..eb306c5f 100644 --- a/tests/unit/agents/test_agent_isolation.py +++ b/tests/unit/agents/test_agent_isolation.py @@ -267,6 +267,19 @@ def test_a_dotted_key_cannot_walk_into_a_neighbours_section(self, config: Config with pytest.raises(ValueError, match="outside this agent"): config.for_namespace("billing").get("orders.record_id") + def test_a_bare_key_naming_a_neighbour_is_refused(self, config: Config) -> None: + """S11, plan D9 -- the root key ``orders`` is orders' section; the fallback handed it over whole.""" + config.declare_agent("orders") + with pytest.raises(ValueError, match="that is the name of an agent"): + config.for_namespace("billing").get("orders") + + def test_a_flat_root_value_that_shares_an_agents_name_still_resolves(self, tmp_path: Path) -> None: + """Only a section is an agent's; a scalar of the same name is the process's.""" + (tmp_path / "settings.toml").write_text('[default]\napp_environment = "development"\ntimeout = 5\n') + config = Config(settings_files=["settings.toml"], root_path=str(tmp_path)) + config.declare_agent("timeout") + assert config.for_namespace("billing").get("timeout") == 5 + def test_the_frameworks_own_nested_sections_still_resolve(self, config: Config) -> None: """An allowlist, so what the process genuinely shares keeps working -- and this is the case that would have been broken by a denylist of agent names.""" From d3858d4564f351757322cfacc251f2befdbede6c Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:14:53 +0200 Subject: [PATCH 110/133] fix(registry): ownership checks on views; look into bound methods and closures when sharing Step 9 (S15, S16, S17, W6, D11). Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 6 +++ ...26-08-28-multi-agent-grouping-changelog.md | 5 ++ .../docs/guides/multi-agent-migration.md | 14 ++++++ src/blueprint/agents/agent_group.py | 49 +++++++++++++++++-- .../agents/clients/io/nats_client.py | 12 ++++- src/blueprint/agents/component/registry.py | 38 +++++++++++++- .../clients/io/test_nats_binding_mode.py | 13 +++++ tests/unit/agents/component/TESTS.md | 2 +- tests/unit/agents/component/test_registry.py | 29 +++++++++++ tests/unit/agents/test_agent_isolation.py | 33 +++++++++++++ 10 files changed, 193 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 88a6d0c3..2e3dcf30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,12 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **The registry keeps agents apart where it did not.** A namespaced lookup's qualified key could be + another agent's (`orders` + `eu_ledger` is `orders_eu` + `ledger`); it now has to belong to the asking + agent. A view can no longer clear the registry, shut down the thread pools, rename or register + another agent's component, or take another agent's thread pool. A declaration shared by several + agents is now also refused when it carries state in a bound method or a closure. + - **An agent's own `.secrets.toml` is read in a group.** Only its `settings.toml` was merged, although the layout check, the guides and `asbs setup` said the secrets beside it are read. It is now merged first, so a secret wins over the settings file, and none of its values is logged. diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 458933ac..05f3265a 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,11 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 9, registry and sharing guards (S15, S16, S17, W6, D11): the qualified hit in `_lookup` must + belong to the asking namespace; `clear`, `clear_components`, `shutdown_executors` are refused on a view, + `add_component`/`update_component_name` only for the view's own components, `get_or_create_executor` + only for its own namespace or the root; `is_shareable` looks into a bound method's `__self__` and a + closure's cells, and a shared declaration's factory target is checked too. W6 documented as allowed. - Step 8, agent settings merge (M5, S11, S12, S13, D9): an agent's `.secrets.toml` is merged before its settings (`AgentGroup.secrets`, `merge_agent_settings(..., secret=True)` logs no value); fragments are layered for `current_env` and inactive environment sections are dropped; `cache`, `event_publishing`, diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md index 6996bf56..f52d72f3 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md @@ -278,6 +278,20 @@ imports keep working standalone as well, so the change needs no second copy. `as grep -rnE "^\s*(from|import) src(\.|\s|$)" src/ ``` +### One declaration serving two agents + +A group may name the same `AppBuilder` for several agents; it is replayed once per agent. What that +declaration was handed is then handed to every one of them, so it must not carry state. Refused at +assembly, with the agents and the argument named: + +- a mutable argument -- `with_service(Ledger, holdings=[])`; +- a bound method, which carries its instance -- `on_record=journal.append`; +- a factory closing over a mutable value -- `with_service(lambda: Ledger(holdings=shared))`. + +Create the state inside the factory (`lambda: Ledger(holdings=[])`), or declare the component +separately per agent. Two *separate* declarations that are both given one object -- a connection +pool, deliberately -- share it: that is the author's decision, and it is allowed. + ### Routes under `/nats`, `/cache` or `/scheduler` In a group, `nats`, `cache` and `scheduler` directly under `/api//` belong to the framework: diff --git a/src/blueprint/agents/agent_group.py b/src/blueprint/agents/agent_group.py index 5ebe8f92..90aab1f0 100644 --- a/src/blueprint/agents/agent_group.py +++ b/src/blueprint/agents/agent_group.py @@ -28,6 +28,7 @@ from enum import Enum from pathlib import Path from types import BuiltinFunctionType, FunctionType, MethodType, ModuleType +from typing import Any from fastapi import FastAPI @@ -71,13 +72,38 @@ """ -def is_shareable(value: object) -> bool: - """Whether ``value`` may be handed to more than one agent. See :data:`SHAREABLE_TYPES`.""" +def is_shareable(value: object, _seen: frozenset[int] = frozenset()) -> bool: + """Whether ``value`` may be handed to more than one agent. See :data:`SHAREABLE_TYPES`. + + **Code is shareable only when it carries no state** (S17). A bound method holds its instance + in ``__self__`` -- ``ledger.add`` hands over ``ledger`` -- and a built-in one the same way + (``holdings.append``); a closure holds whatever it closes over in its cells. Each is + shareable exactly when what it carries is, so a classmethod, a module function and a lambda + closing over constants pass, and one closing over a list does not. + """ + if id(value) in _seen: + return True # a recursive closure: what it carries is being checked already + seen = _seen | {id(value)} if isinstance(value, tuple): - return all(is_shareable(item) for item in value) + return all(is_shareable(item, seen) for item in value) + if isinstance(value, MethodType): + return is_shareable(value.__self__, seen) + if isinstance(value, BuiltinFunctionType): + bound_to = getattr(value, "__self__", None) + return bound_to is None or isinstance(bound_to, ModuleType) or is_shareable(bound_to, seen) + if isinstance(value, FunctionType): + return all(is_shareable(_cell_value(cell), seen) for cell in value.__closure__ or ()) return isinstance(value, SHAREABLE_TYPES) +def _cell_value(cell: Any) -> object: + """What a closure cell holds; ``None`` for a cell not yet filled, which holds nothing.""" + try: + return cell.cell_contents + except ValueError: + return None + + class AgentGroup: """The agents one process hosts, and the single application they become. @@ -437,6 +463,13 @@ def _refuse_state_shared_between_agents(self) -> None: *standalone is permissive, the group has rules* applied to the one case that is genuinely about the group. + **Two declarations that are handed one object share it, and that is allowed** (plan D11, + W6). The check is keyed by the declaration, so ``orders_builder.with_service(A, pool=p)`` + and ``billing_builder.with_service(B, pool=p)`` both get ``p``: their author passed it to + two agents explicitly, which is a decision rather than an accident of replay -- a shared + connection pool is the usual reason. What is never shared between agents is framework + state per data source; see the named-connection rules (step 1a). + Raises: ValueError: naming the agents, the call, the argument and the way out. """ @@ -450,6 +483,16 @@ def _refuse_state_shared_between_agents(self) -> None: if len(namespaces) < 2: continue for declaration in builders[identity].declarations: + if isinstance(declaration.target, (FunctionType, MethodType)) and not is_shareable(declaration.target): + # A factory is called once per agent, but what it closes over -- or the + # instance a bound method belongs to -- is one object for all of them (S17). + raise ValueError( + f"One declaration serves agents {', '.join(repr(name) for name in namespaces)}, and its " + f"{declaration.kind} call is given a factory that carries state: a bound method, or a " + "closure over a mutable value. Every agent's component would then be built from the same " + "object, so a value written by one agent is read by the others. Create the state inside " + "the factory, or declare this component separately for each agent." + ) for argument, value in declaration.kwargs.items(): if is_shareable(value): continue diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index fdd58867..06d35b98 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -2570,7 +2570,7 @@ def _message_handler( """ async def message_handler(msg: Any) -> None: - if binding.jetstream is not None and await self._answer_control_message(msg): + if binding.jetstream is not None and await self._answer_control_message(msg, binding): return if self._consumption_paused and self._settles(binding): # A degraded agent runs nothing (C4). What reaches it anyway -- a delivery still in @@ -2601,7 +2601,7 @@ async def message_handler(msg: Any) -> None: return message_handler @staticmethod - async def _answer_control_message(msg: Any) -> bool: + async def _answer_control_message(msg: Any, binding: _Binding) -> bool: """Answer or drop a JetStream status message; ``True`` if ``msg`` was one (S2). Binding mode consumes through a plain subscription, so what nats-py's JetStream @@ -2609,6 +2609,9 @@ async def _answer_control_message(msg: Any) -> bool: control request, after which the consumer delivers nothing until it is answered. Both carry status ``100`` and no event; run as a delivery, they were termed as unparseable. Only an operator-made consumer with ``idle_heartbeat`` or ``flow_control`` sends them. + + A heartbeat may report a stalled consumer in ``Nats-Consumer-Stalled``: a flow control + reply subject that was never answered, which is answered here as nats-py would. """ headers = getattr(msg, "headers", None) if not headers or headers.get(js_api.Header.STATUS) != CONTROL_MESSAGE_STATUS: @@ -2616,6 +2619,11 @@ async def _answer_control_message(msg: Any) -> bool: if msg.reply: # a flow control request; a heartbeat has no reply subject with contextlib.suppress(Exception): await msg.respond(b"") + stalled = headers.get(js_api.Header.CONSUMER_STALLED) + client = binding.link.nats_client + if stalled and client is not None: + with contextlib.suppress(Exception): + await client.publish(stalled, b"") return True @staticmethod diff --git a/src/blueprint/agents/component/registry.py b/src/blueprint/agents/component/registry.py index f91a1718..c96af6a2 100644 --- a/src/blueprint/agents/component/registry.py +++ b/src/blueprint/agents/component/registry.py @@ -159,6 +159,19 @@ def for_namespace(self, namespace: str) -> "Registry": self._views[namespace] = view return view + def _refuse_on_a_view(self, action: str) -> None: + """Refuse a process-wide mutation asked of a view (S16). + + A view shares the registry's dictionaries by reference, so ``clear()`` on one agent's view + emptied the registry of every agent. What acts on the whole process belongs to the + application's registry, which agent code never holds. + """ + if self._default_namespace: + raise RuntimeError( + f"The registry view for namespace '{self._default_namespace}' was asked to {action}. That acts on " + "every agent of the process, so only the application's registry does it." + ) + @property def default_namespace(self) -> str | None: """The namespace this object answers as; ``None`` on the application's own registry.""" @@ -232,8 +245,11 @@ def _lookup(self, name: str, namespace: str | None) -> Any | None: namespace = self._effective_namespace(namespace) if namespace: qualified = qualified_component_name(namespace, name) - if qualified in self._components: - return self._components[qualified] + hit = self._components.get(qualified) + # Checked like the fallback below (S15): '_' joins namespace and name and may occur in + # either, so 'orders' + 'eu_ledger' is the key 'orders_eu' + 'ledger' registered. + if hit is not None and namespace_of(hit) == namespace: + return hit found = self._components.get(name) if found is not None and namespace and namespace_of(found) not in (ROOT_NAMESPACE, namespace): @@ -271,6 +287,9 @@ def get_or_create_executor(self, namespace: str = ROOT_NAMESPACE, max_workers: i The pool for that namespace. """ + # Own pool or the root's, never a neighbour's: the pools exist so that no agent can + # exhaust another's (S16). + namespace = self._effective_namespace(namespace) or ROOT_NAMESPACE executor = self._executors.get(namespace) if executor is None: executor = ThreadPoolExecutor( @@ -294,6 +313,7 @@ def shutdown_executors(self) -> None: hangs until the last blocking call returns on its own. """ + self._refuse_on_a_view("shut down the thread pools") for namespace, executor in self._executors.items(): logger.info("Shutting down thread pool for namespace '%s'", namespace or ROOT_LABEL) executor.shutdown(wait=True) @@ -474,6 +494,11 @@ def add_component(self, name: str, component: Any) -> None: if not isinstance(component, self._component_class): # type: ignore[arg-type] raise ValueError(f"component must be an instance of {self._component_class}") + if self._default_namespace and namespace_of(component) != self._default_namespace: + raise RuntimeError( + f"The registry view for namespace '{self._default_namespace}' was asked to register a component of " + f"namespace '{namespace_of(component) or ROOT_LABEL}'. A view registers its own agent's components." + ) if name in self._components: existing = type(self._components[name]).__name__ @@ -512,6 +537,13 @@ def update_component_name(self, old_name: str, new_name: str) -> None: if old_name not in self._components: raise ValueError(f"Component with name {old_name} does not exist") + if self._default_namespace and namespace_of(self._components[old_name]) != self._default_namespace: + # A view renames its own agent's components only: a rename moves a neighbour's + # component out from under every lookup that finds it (S16). + raise RuntimeError( + f"The registry view for namespace '{self._default_namespace}' was asked to rename '{old_name}', which " + "belongs to another namespace." + ) if new_name == old_name: return @@ -650,6 +682,7 @@ def has_component_of_type(self, component_type: Any, name: str | None = None, na def clear_components(self) -> None: """Clear all registered components (useful for testing).""" + self._refuse_on_a_view("clear the components") logger.info("Clearing all registered components") self._components.clear() @@ -660,6 +693,7 @@ def clear(self) -> None: Useful for testing or resetting the registry state. """ + self._refuse_on_a_view("clear the registry") logger.info("Clearing all components from registry") self.clear_components() self.shutdown_executors() diff --git a/tests/unit/agents/clients/io/test_nats_binding_mode.py b/tests/unit/agents/clients/io/test_nats_binding_mode.py index 5cae1a4c..6deecbb5 100644 --- a/tests/unit/agents/clients/io/test_nats_binding_mode.py +++ b/tests/unit/agents/clients/io/test_nats_binding_mode.py @@ -263,6 +263,19 @@ async def test_a_flow_control_request_is_answered_and_never_run( callback.assert_not_awaited() msg.term.assert_not_awaited() + async def test_a_stalled_consumer_reported_by_a_heartbeat_is_answered( + self, nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock + ) -> None: + callback = AsyncMock() + binding, handler = await _bound(nats_client, mock_nats_core, jsm, callback) + msg = self._status() + msg.headers["Nats-Consumer-Stalled"] = "$JS.FC.NOTIFICATIONS_A.y" + + await _settled(binding, handler, msg) + + mock_nats_core.publish.assert_awaited_once_with("$JS.FC.NOTIFICATIONS_A.y", b"") + callback.assert_not_awaited() + async def test_an_idle_heartbeat_is_dropped(self, nats_client: NATSClient, mock_nats_core: MagicMock, jsm: MagicMock) -> None: callback = AsyncMock() binding, handler = await _bound(nats_client, mock_nats_core, jsm, callback) diff --git a/tests/unit/agents/component/TESTS.md b/tests/unit/agents/component/TESTS.md index bc120cf0..d6b754bf 100644 --- a/tests/unit/agents/component/TESTS.md +++ b/tests/unit/agents/component/TESTS.md @@ -13,7 +13,7 @@ Test coverage for `src/blueprint/agents/component/component.py` and | `test_component.py` | `_is_cloud_event`, `_stamp_span` | Helper function correctness | | `test_component.py` | `traced` decorator | Async/sync span creation, error status, CloudEvent/plain-value stamping | | `test_namespace.py` | `namespace.py` helpers | `validate_namespace`, `qualified_component_name`, `namespace_of`, `display_segment`, `resolve_for_namespace`, and `namespace_scope`/`current_namespace` (default root, set/exit, exit on exception, nesting, validation on entry); the four shared configuration sections are refused as namespaces, and the reserved list equals `SHARED_NESTED_PREFIXES` (S12) | -| `test_registry.py` | `Registry` | Construction, add/get/has/rename/clear, type-based lookups, `cache_service`; namespaced lookup (bare name resolving to the asking namespace, root fallback, already-qualified names, the error naming where it looked), type queries (`None` = every namespace, a namespace = that agent exactly, filtering by attribute not name, ambiguity refused across and within a namespace), and that `get_known_namespaces` does not exist (C6); named caches (lookup by name, no fallback to the default, the error listing what is registered, the `cache_service` alias both ways, `get_all_caches` copying, `clear` clearing every cache, replace-and-warn on a second registration); per-namespace executors (none until asked, create then reuse, isolation, sizing on the creating call only, thread naming, shutdown from `clear` and `shutdown_executors`); namespace views (`for_namespace` identity at the root, caching, the shared store, the C6 refusal on a view, omitted-means-this-agent, root fallback for name and class lookups, plural lookups scoped to one agent, explicit override, and the application registry still seeing everything) | +| `test_registry.py` | `Registry` | Construction, add/get/has/rename/clear, type-based lookups, `cache_service`; namespaced lookup (bare name resolving to the asking namespace, root fallback, already-qualified names, the error naming where it looked), type queries (`None` = every namespace, a namespace = that agent exactly, filtering by attribute not name, ambiguity refused across and within a namespace), and that `get_known_namespaces` does not exist (C6); named caches (lookup by name, no fallback to the default, the error listing what is registered, the `cache_service` alias both ways, `get_all_caches` copying, `clear` clearing every cache, replace-and-warn on a second registration); per-namespace executors (none until asked, create then reuse, isolation, sizing on the creating call only, thread naming, shutdown from `clear` and `shutdown_executors`); namespace views (`for_namespace` identity at the root, caching, the shared store, the C6 refusal on a view, omitted-means-this-agent, root fallback for name and class lookups, plural lookups scoped to one agent, explicit override, and the application registry still seeing everything); a qualified key another agent owns is not found (S15); a view cannot clear, shut down the pools, rename or register another agent's component, or take another agent's pool (S16) | --- diff --git a/tests/unit/agents/component/test_registry.py b/tests/unit/agents/component/test_registry.py index 59fb0540..b0b5917c 100644 --- a/tests/unit/agents/component/test_registry.py +++ b/tests/unit/agents/component/test_registry.py @@ -550,6 +550,35 @@ def test_an_omitted_namespace_means_this_agent(self, grouped_registry: Registry) def test_an_omitted_namespace_still_falls_back_to_the_root(self, grouped_registry: Registry) -> None: assert grouped_registry.for_namespace("orders").get_component("shared_audit").namespace == "" + def test_a_qualified_key_another_agent_owns_is_not_found(self) -> None: + """S15 -- 'orders' + 'eu_ledger' is the key 'orders_eu' + 'ledger' registered.""" + registry = Registry(StubBase) + registry.add_component("orders_eu_ledger", _Namespaced("orders_eu")) + + assert registry.has_component("eu_ledger", "orders") is False + assert registry.get_component("ledger", "orders_eu").namespace == "orders_eu" + + @pytest.mark.parametrize("action", ["clear", "clear_components", "shutdown_executors"]) + def test_a_view_cannot_act_on_the_whole_process(self, grouped_registry: Registry, action: str) -> None: + """S16 -- a view shares the dictionaries, so clear() on one agent's view emptied every agent's.""" + with pytest.raises(RuntimeError, match="acts on every agent of the process"): + getattr(grouped_registry.for_namespace("orders"), action)() + assert grouped_registry.has_component("billing_order_service") + + def test_a_view_cannot_rename_a_neighbours_component(self, grouped_registry: Registry) -> None: + with pytest.raises(RuntimeError, match="belongs to another namespace"): + grouped_registry.for_namespace("orders").update_component_name("billing_order_service", "orders_taken") + assert grouped_registry.has_component("billing_order_service") + + def test_a_view_registers_only_its_own_agents_components(self, grouped_registry: Registry) -> None: + with pytest.raises(RuntimeError, match="registers its own agent's components"): + grouped_registry.for_namespace("orders").add_component("billing_extra", _Namespaced("billing")) + + def test_a_view_cannot_take_a_neighbours_thread_pool(self, grouped_registry: Registry) -> None: + with pytest.raises(RuntimeError, match="was asked for namespace 'billing'"): + grouped_registry.for_namespace("orders").get_or_create_executor("billing") + grouped_registry.shutdown_executors() + def test_a_class_lookup_on_a_view_finds_this_agents_instance(self, grouped_registry: Registry) -> None: assert grouped_registry.for_namespace("billing").get_component(_Namespaced).namespace == "billing" diff --git a/tests/unit/agents/test_agent_isolation.py b/tests/unit/agents/test_agent_isolation.py index eb306c5f..34c4a289 100644 --- a/tests/unit/agents/test_agent_isolation.py +++ b/tests/unit/agents/test_agent_isolation.py @@ -366,6 +366,39 @@ def test_one_agent_may_carry_whatever_it_likes(self, config: Config) -> None: assert registry is not None assert registry.get_component("orders_ledger").holdings == [] + def test_a_bound_method_carries_its_instance_and_is_refused(self, config: Config) -> None: + """S17 -- ``holdings.append`` hands every agent the one list it is bound to.""" + shared: list[str] = [] + declaration = AppBuilder().with_service(Ledger, on_record=shared.append) + + with pytest.raises(ValueError, match="written by one agent is read by the others"): + AgentGroup("finance", {"orders": declaration, "billing": declaration}).assemble(config) + + def test_a_factory_closing_over_a_list_is_refused(self, config: Config) -> None: + """S17 -- the factory runs once per agent, but the list it closes over is one.""" + holdings: list[str] = [] + declaration = AppBuilder().with_service(lambda: Ledger(holdings=holdings)) + + with pytest.raises(ValueError, match="factory that carries state"): + AgentGroup("finance", {"orders": declaration, "billing": declaration}).assemble(config) + + def test_a_factory_closing_over_constants_is_fine(self, config: Config) -> None: + name = "read-only" + declaration = AppBuilder().with_service(lambda: Ledger(holdings=(name,))) + AgentGroup("finance", {"orders": declaration, "billing": declaration}).assemble(config) + + def test_two_declarations_handed_one_object_share_it_deliberately(self, config: Config) -> None: + """Plan D11 (W6): passed to two agents by their author, not by replay -- allowed, and documented.""" + shared: list[str] = [] + AgentGroup( + "finance", + {"orders": AppBuilder().with_service(Ledger, holdings=shared), "billing": AppBuilder().with_service(Ledger, holdings=shared)}, + ).assemble(config) + + registry = Component.shared_registry + assert registry is not None + assert registry.get_component("orders_ledger").holdings is registry.get_component("billing_ledger").holdings + class TestTheProcessLevelResourcesAreStillPerAgent: """Not data, but channels through which data would flow.""" From b99d75b7c42c7adbe8816fa83cc6d16ed42fbc4b Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:14:55 +0200 Subject: [PATCH 111/133] fix(scheduler): a grouped tick handler belongs to its agent; subject and route from the base name Step 10 (M8, M9). Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 8 +++++ ...26-08-28-multi-agent-grouping-changelog.md | 7 +++- .../agent_generator/claude_docs/CLAUDE.md | 2 +- .../skills/blueprint-config/SKILL.md | 2 +- .../docs/components/schedulers.md | 5 +-- .../agent_generator/docs/guides/deployment.md | 3 +- .../docs/reference/configuration-keys.md | 2 +- .../agents/io/api/scheduling/scheduler.py | 27 +++++++++----- tests/unit/agents/io/TESTS.md | 2 +- .../io/api/scheduling/test_scheduler.py | 35 ++++++++++++++++++- 10 files changed, 75 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e3dcf30..3f134f6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,14 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **A grouped scheduler's tick subject and trigger route name the agent once.** Both were built from the + scheduler's qualified name, so the subject was `orders.scheduler.orders_nightly` and the route + `/api/orders/scheduler/orders_nightly/trigger`; they are now `orders.scheduler.nightly` and + `/api/orders/scheduler/nightly/trigger`, as the docs said. **Alpha users of grouped event-mode + schedulers: move the publishing `CronJob` to the new subject.** A standalone scheduler is unchanged. + An event-mode scheduler's tick handler now belongs to the scheduler's agent; it was registered at the + root, in the root's handler chain. + - **The registry keeps agents apart where it did not.** A namespaced lookup's qualified key could be another agent's (`orders` + `eu_ledger` is `orders_eu` + `ledger`); it now has to belong to the asking agent. A view can no longer clear the registry, shut down the thread pools, rename or register diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 05f3265a..ec2c50e8 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,12 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 10, grouped scheduler (M8, M9): the tick handler is built under `namespace_scope(self.namespace)`; + tick subject, trigger route and handler name use `base_name`; docs agree. Live (Core NATS, a group + with agent `orders`, scheduler `nightly`, event mode): subscribed `orders.scheduler.nightly`, handler + in `orders`, one tick from that subject and none from the doubled one, `POST + /api/orders/scheduler/nightly/trigger` 200 and ticks. Control: subscribed the doubled subject, handler + at the root, the documented route 404. - Step 9, registry and sharing guards (S15, S16, S17, W6, D11): the qualified hit in `_lookup` must belong to the asking namespace; `clear`, `clear_components`, `shutdown_executors` are refused on a view, `add_component`/`update_component_name` only for the view's own components, `get_or_create_executor` @@ -227,7 +233,6 @@ Still open (the closed ones, and their history, are in `git log`): a real broker (referenced from `NATSClient`'s docstring). - **`test_three_replicas_run_one_tick` was flaky once** (2026-09-24); likely the disk cache's non-atomic takeover of an expired claim. Not investigated. -- **A grouped scheduler's trigger path repeats the agent** (`/api/orders/scheduler/orders_nightly_scheduler/trigger`). - **Spec amendments owed:** C4 (a degraded transport is paused, not closed), C2 (the metric reader cannot be shared across providers), the root's role under `readiness_policy`, phase 7's ambiguity is a WARNING rather than an error. `readiness_policy = "any"` has no acceptance criterion. diff --git a/src/blueprint/agent_generator/claude_docs/CLAUDE.md b/src/blueprint/agent_generator/claude_docs/CLAUDE.md index 7b1072a2..88781e51 100644 --- a/src/blueprint/agent_generator/claude_docs/CLAUDE.md +++ b/src/blueprint/agent_generator/claude_docs/CLAUDE.md @@ -215,7 +215,7 @@ class CleanupScheduler(SchedulerBase): - **`scheduler_mode` decides what calls `tick()`, and it is required.** It has no default: registering a scheduler without setting it fails at startup, because neither value is safe to inherit silently. `"event"` starts no timer in the process -- the tick arrives as an ordinary - event on `.scheduler.`, published by an external `CronJob`, so the + event on `.scheduler.` (`app_name` instead of the agent at the root), published by an external `CronJob`, so the queue group already guarantees that exactly one replica runs it; it needs `event_bus` set to `"dapr"` or `"nats"`. `"in_process"` runs an APScheduler timer in **every** replica and claims each tick in the cache so one replica runs it -- so it needs `.with_cache()` to fire a diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md index a7838e45..7b0e61b1 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md @@ -42,7 +42,7 @@ These fail at startup rather than guess, so they must be set deliberately: - **`scheduler_mode`** - required once any scheduler is registered. `"in_process"` runs an APScheduler timer in *every* replica and claims each tick through the cache, so it needs `.with_cache()` or every replica runs every tick. `"event"` starts no timer: the tick arrives as - an event on `.scheduler.`, so it needs `event_bus` set. + an event on `.scheduler.` (`app_name` instead of the agent at the root), so it needs `event_bus` set. - **`idempotency_enabled` and `idempotency_ttl`** - both, or neither. Delivery is at-least-once; deduplication is off by default because only you know whether replaying your side effects is acceptable. The TTL must outlast the broker redelivery window. diff --git a/src/blueprint/agent_generator/docs/components/schedulers.md b/src/blueprint/agent_generator/docs/components/schedulers.md index b12599e7..2a889841 100644 --- a/src/blueprint/agent_generator/docs/components/schedulers.md +++ b/src/blueprint/agent_generator/docs/components/schedulers.md @@ -112,8 +112,9 @@ POST /api/data_sync_scheduler/trigger ``` In a group, the trigger moves under the agent's reserved `scheduler` segment: -`POST /api//scheduler//trigger`. The name there is the scheduler's registry name, -which a group qualifies with the agent -- `/api/order/scheduler/order_data_sync_scheduler/trigger`. +`POST /api//scheduler//trigger`. The name there is the scheduler's own name, without +the agent -- `/api/order/scheduler/data_sync_scheduler/trigger` -- because the path names the agent +already. This is useful for testing, debugging, and on-demand execution without waiting for the next cron interval. diff --git a/src/blueprint/agent_generator/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md index ab54c9eb..7d39f803 100644 --- a/src/blueprint/agent_generator/docs/guides/deployment.md +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -466,7 +466,8 @@ No timer runs in the process at all. The tick arrives as an ordinary event on .scheduler. ``` --- the agent's namespace, or `app_name` for a scheduler at the root. It is the queue group that +-- the agent's namespace, or `app_name` for a scheduler at the root, then the scheduler's own name +without the agent (`order.scheduler.nightly`). It is the queue group that delivers it, so exactly one replica runs it however many there are. It needs `event_bus` set. **Nothing in this repository generates the `CronJob`.** The schedule stays declared in agent code, diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 37b01d45..175988f3 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -150,7 +150,7 @@ effects is acceptable is a property of the product, not of the framework. | Key | Type | Default | Description | |-----|------|---------|-------------| -| `scheduler_mode` | `str` | -- (**required** when a scheduler is registered) | Where a scheduler's tick comes from. `"event"` starts no in-process timer: the tick arrives as an ordinary event on the scheduler's own topic (`.scheduler.` unless overridden with `topic=` in the scheduler's constructor), published by an external `CronJob`, so the queue group already picks exactly one replica and nothing is elected -- it requires `event_bus` to be `"dapr"` or `"nats"`, since `"sessions"` cannot deliver a topic. `"in_process"` runs an APScheduler timer inside every replica and coordinates them through the registered cache: each tick is claimed under a key derived from the scheduler and the scheduled minute, and only the replica that stores the marker runs it. Intended for local development and un-orchestrated Docker, where no `CronJob` exists. **With no cache registered the ticks cannot be coordinated and every replica runs every tick**; startup warns about it. **No default:** neither value is safe to inherit silently, and which one applies depends on the deployment (is a broker reachable, does more than one replica run, is there an orchestrator at all) rather than on the code, so the author states it -- the same reasoning as `idempotency_ttl`. An absent, empty or unrecognised value fails startup. | +| `scheduler_mode` | `str` | -- (**required** when a scheduler is registered) | Where a scheduler's tick comes from. `"event"` starts no in-process timer: the tick arrives as an ordinary event on the scheduler's own topic (`.scheduler.`, with `app_name` for a scheduler at the root and the scheduler's name without the agent, unless overridden with `topic=` in the scheduler's constructor), published by an external `CronJob`, so the queue group already picks exactly one replica and nothing is elected -- it requires `event_bus` to be `"dapr"` or `"nats"`, since `"sessions"` cannot deliver a topic. `"in_process"` runs an APScheduler timer inside every replica and coordinates them through the registered cache: each tick is claimed under a key derived from the scheduler and the scheduled minute, and only the replica that stores the marker runs it. Intended for local development and un-orchestrated Docker, where no `CronJob` exists. **With no cache registered the ticks cannot be coordinated and every replica runs every tick**; startup warns about it. **No default:** neither value is safe to inherit silently, and which one applies depends on the deployment (is a broker reachable, does more than one replica run, is there an orchestrator at all) rather than on the code, so the author states it -- the same reasoning as `idempotency_ttl`. An absent, empty or unrecognised value fails startup. | --- diff --git a/src/blueprint/agents/io/api/scheduling/scheduler.py b/src/blueprint/agents/io/api/scheduling/scheduler.py index c3a59d38..63599cc3 100644 --- a/src/blueprint/agents/io/api/scheduling/scheduler.py +++ b/src/blueprint/agents/io/api/scheduling/scheduler.py @@ -51,7 +51,7 @@ async def tick(self) -> None: from ....clients.io.io_client_base import TOPIC_TRANSPORTS, validate_subject_segment from ....component.component import traced -from ....component.namespace import ROOT_LABEL +from ....component.namespace import ROOT_LABEL, namespace_scope from ....handler.event_handler_base import EventHandlerBase from ....models.events import GenericCloudEvent from ...telemetry.providers import agent_meter @@ -166,7 +166,9 @@ def __init__(self, scheduler: SchedulerBase, topic: str) -> None: # registers under the class-derived name, so a second scheduler's handler would # collide with the first one on "scheduler_tick_handler". Renaming pops that key # out of the registry again, which is what leaves it free for the next instance. - self.name = f"{scheduler.name}_tick" + # The scheduler's base name: the setter qualifies with this handler's namespace, which + # is the scheduler's, so the qualified name would carry the agent twice. + self.name = f"{scheduler.base_name}_tick" self._scheduler = scheduler self._topic = topic @@ -322,7 +324,11 @@ def wire(self) -> SchedulerTickHandler | None: # reported itself healthy. validate_crontab(self._crontab) if self._tick_handler is None: - self._tick_handler = SchedulerTickHandler(self, self.tick_topic) + # In the scheduler's own namespace (M8): build() calls this outside any scope, so the + # handler -- a Component taking its namespace from the ambient scope -- landed at the + # root, in the root's chain, outside its agent's registry view and consumer (C1). + with namespace_scope(self.namespace): + self._tick_handler = SchedulerTickHandler(self, self.tick_topic) return self._tick_handler def register_trigger_route(self) -> None: @@ -334,10 +340,12 @@ def register_trigger_route(self) -> None: if self._trigger_route_registered: return + # The base name: in a group the router is already under /api//scheduler, and the + # qualified name repeated the agent -- /api/orders/scheduler/orders_nightly/trigger (M9). self.router.post( - f"/{self.name}/trigger", + f"/{self.base_name}/trigger", tags=["Scheduler"], - summary=f"Manually trigger {self.name}", + summary=f"Manually trigger {self.base_name}", )(self._trigger_tick) self._trigger_route_registered = True @@ -397,8 +405,9 @@ def _require_event_transport(self) -> None: def _resolve_topic(self) -> str: """Derive the tick topic from the agent's own identity, or take the override. - ``f"{namespace}.scheduler.{name}"``, falling back to ``app_name`` only for a scheduler - at the root -- the same identity the queue group derives from, so moving the scheduler + ``f"{namespace}.scheduler.{name}"`` with the scheduler's own name, not the qualified one + that already carries the namespace (M9: ``orders.scheduler.orders_nightly``), falling + back to ``app_name`` only for a scheduler at the root -- the same identity the queue group derives from, so moving the scheduler between deployment groups does not change the subject a ``CronJob`` has to publish to (C1). An agent's name is the agent's own; ``app_name`` is a display string belonging to the whole process, so deriving a namespaced scheduler's subject from it would give two @@ -438,10 +447,10 @@ def _resolve_topic(self) -> str: "set 'app_name', or pass topic=... to SchedulerBase.__init__." ) - topic = f"{identity}.scheduler.{self.name}" + topic = f"{identity}.scheduler.{self.base_name}" source = "The scheduler's namespace" if self.namespace else "'app_name'" validate_subject_segment(identity, source=source, subject=topic) - validate_subject_segment(self.name, source=f"The name of scheduler '{self.name}'", subject=topic) + validate_subject_segment(self.base_name, source=f"The name of scheduler '{self.base_name}'", subject=topic) return topic # ------------------------------------------------------------------ diff --git a/tests/unit/agents/io/TESTS.md b/tests/unit/agents/io/TESTS.md index a6c7c17a..b3a958bf 100644 --- a/tests/unit/agents/io/TESTS.md +++ b/tests/unit/agents/io/TESTS.md @@ -18,7 +18,7 @@ Test coverage for `src/blueprint/agents/io/`. | `api/eventing/test_nats.py` | `NatsEventing` | `subscribe`/`publish` delegate to `_client`, RuntimeError when client is None; `on_startup` fetches client, subscribes to handler-declared and config-declared topics, deduplicates, preserves handler-first order, skips when no topics; `_subscribe_to_topic` RuntimeError when client None, calls `_client.subscribe` with topic and callback | | `api/eventing/test_sessions_bus.py` | `SessionsBus` | `on_startup` validation (no config/base_url/agent_id/api_key, already started, task created); `on_shutdown` (no task, running task cancelled); `_convert_to_cloud_event` (type/id/subject/source/data); `_process_job_notification` (no handler logged, `InvalidEventError`→cancel job, cancel failure swallowed, `RetryableHandlerError`→log, 403→invalidate+retry, 403 retry failure propagates `InvalidEventError`, non-403 propagates); C4 (S18): a pause closes the job stream and a resume reopens it, a job reaching a paused agent is left pending, an agent paused before startup opens no stream, and the supervisor pauses and resumes the bus | | `api/eventing/test_sessions_startup_resilience.py` | `AppBuilder.build()` with `event_bus = "sessions"` | The lifespan completes and the root REST endpoints answer when the sessions service URL points at a closed port -- a background SSE consumer that cannot connect must not stop the application starting. Offline: the refused port is bound and released on loopback, so the failure is ECONNREFUSED rather than a timeout on every platform. Moved here from `tests/integration/` (#80), where nothing ran it -| `api/scheduling/test_scheduler.py` | `SchedulerBase`, `SchedulerTickHandler` | `_trigger_tick` calls `tick()` and returns `{"status": "triggered"}`; `scheduler_mode` reads both values case-insensitively, has no default so an absent, empty or missing key raises with both values named, rejects an unrecognised value and resolves once; `tick_topic` derives from `app_name` and the (possibly renamed) scheduler name, honours the `topic=` override, rejects a missing identity and a wildcard, rejects whitespace in an explicit topic and rewrites it in a derived one; `wire()` creates the tick handler in event mode only, is idempotent, registers the trigger route once in both modes, refuses event mode without a topic-carrying `event_bus` and accepts both broker transports; `on_startup` starts no timer in event mode, creates and starts `AsyncIOScheduler` on the declared crontab in in-process mode, and starts no second timer or route when called twice (#43); `on_shutdown` calls `shutdown(wait=True)` only when running and allows a later restart; the in-process tick claim -- the winner ticks and a loser does not, the key carries the scheduler and the minute, the claim carries the tick TTL and its own namespace, three replicas sharing a real `DiskCacheService` run one tick between them, a later slot is claimable again, no cache means every replica ticks and startup warns, the timer is wired to the claimed wrapper rather than to `tick`, and event mode claims nothing; `validate_crontab` accepting the five standard fields, stripping whitespace and rejecting empty, nonsense and six-field (apscheduler) expressions, with event-mode wiring failing on a bad crontab and in-process wiring not reaching the check; the tick handler declares its topic, outranks the default handler priority, claims a delivery under `nats_topic`/`dapr_topic`/`topic`, declines other or absent topics, ticks its scheduler without publishing an event, lets a failing tick reach the transport edge, and two schedulers register under distinct names in a real `Registry` | +| `api/scheduling/test_scheduler.py` | `SchedulerBase`, `SchedulerTickHandler` | `_trigger_tick` calls `tick()` and returns `{"status": "triggered"}`; `scheduler_mode` reads both values case-insensitively, has no default so an absent, empty or missing key raises with both values named, rejects an unrecognised value and resolves once; `tick_topic` derives from `app_name` and the (possibly renamed) scheduler name, honours the `topic=` override, rejects a missing identity and a wildcard, rejects whitespace in an explicit topic and rewrites it in a derived one; `wire()` creates the tick handler in event mode only, is idempotent, registers the trigger route once in both modes, refuses event mode without a topic-carrying `event_bus` and accepts both broker transports; `on_startup` starts no timer in event mode, creates and starts `AsyncIOScheduler` on the declared crontab in in-process mode, and starts no second timer or route when called twice (#43); `on_shutdown` calls `shutdown(wait=True)` only when running and allows a later restart; the in-process tick claim -- the winner ticks and a loser does not, the key carries the scheduler and the minute, the claim carries the tick TTL and its own namespace, three replicas sharing a real `DiskCacheService` run one tick between them, a later slot is claimable again, no cache means every replica ticks and startup warns, the timer is wired to the claimed wrapper rather than to `tick`, and event mode claims nothing; `validate_crontab` accepting the five standard fields, stripping whitespace and rejecting empty, nonsense and six-field (apscheduler) expressions, with event-mode wiring failing on a bad crontab and in-process wiring not reaching the check; the tick handler declares its topic, outranks the default handler priority, claims a delivery under `nats_topic`/`dapr_topic`/`topic`, declines other or absent topics, ticks its scheduler without publishing an event, lets a failing tick reach the transport edge, and two schedulers register under distinct names in a real `Registry`; in a group the subject and the trigger route name the agent once (`orders.scheduler.nightly`, `/nightly/trigger`) and the tick handler belongs to the scheduler's agent (M8, M9) | | `api/scheduling/test_scheduler_event_mode.py` | `SchedulerBase` through `AppBuilder.build()` | What only a built application can show: the tick topic reaches the Dapr subscription document and a CloudEvent posted to `/events/` runs `tick()` exactly once; event mode starts no in-process timer; `POST /api//trigger` is actually served (it used to be added to the router after `include_router` had copied it); in-process mode declares no tick topic and registers no eventing endpoint; a registered scheduler with no `scheduler_mode`, and event mode with no `event_bus`, each fail the build naming both values; and the pure-scheduler shapes -- publishing opted into, and nothing at all by default. Offline, and deterministic because `health_check_dapr = false` stops the Dapr health check probing for a sidecar: without it the namespace supervisor degrades the root agent and its paused transports refuse the tick. Moved here from `tests/integration/` (#80) | `api/utilities/test_cache.py` | `CacheManagementApi` | Which cache each endpoint reaches (`?name=` selecting a named cache, the default when none is given, evict clearing only the one it names) and how it fails (503 with no cache registered at all, 404 for an unknown name, the 404 listing the registered names); and the statistics payload **against real backends** -- a real `DiskCacheService` reporting its four fields, a real `RedisCacheService` over `fakeredis` reporting a different seven, and a backend whose own stats call fails answering an empty payload rather than a 500 | | `api/utilities/test_root.py` | `RootApi` | Service name/version/description from config (and defaults when `None`); both/one/neither doc links rendered; non-`APIRoute` routes skipped; `GET` route → direct link; non-`GET` route with `docs_url` → Swagger anchor link, without `docs_url` → plain path; route summary and sorted methods in row; cache hit skips config on second call | diff --git a/tests/unit/agents/io/api/scheduling/test_scheduler.py b/tests/unit/agents/io/api/scheduling/test_scheduler.py index 589bf273..30504dd3 100644 --- a/tests/unit/agents/io/api/scheduling/test_scheduler.py +++ b/tests/unit/agents/io/api/scheduling/test_scheduler.py @@ -203,7 +203,40 @@ def test_a_namespaced_scheduler_derives_from_its_own_name(self, settings: dict[s with namespace_scope("orders"): namespaced = _TestScheduler() - assert namespaced.tick_topic == f"orders.scheduler.{namespaced.name}" + assert namespaced.tick_topic == f"orders.scheduler.{namespaced.base_name}" + + def test_the_agent_appears_once_in_the_subject(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + """M9 -- the literal subject a CronJob publishes to; it was 'orders.scheduler.orders_nightly'.""" + settings["scheduler_mode"] = SCHEDULER_MODE_EVENT + with namespace_scope("orders"): + nightly = _TestScheduler() + nightly.name = "nightly" + + assert nightly.tick_topic == "orders.scheduler.nightly" + + def test_a_grouped_trigger_route_names_the_agent_once(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + """M9 -- the router already sits under /api//scheduler; the qualified name repeated the agent.""" + settings["scheduler_mode"] = SCHEDULER_MODE_IN_PROCESS + with namespace_scope("orders"): + nightly = _TestScheduler() + nightly.name = "nightly" + nightly.register_trigger_route() + + assert [route.path for route in nightly.router.routes] == ["/nightly/trigger"] + + def test_a_grouped_tick_handler_belongs_to_the_schedulers_agent(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + """M8 -- build() wires outside any scope, and the handler landed at the root (C1).""" + settings["scheduler_mode"] = SCHEDULER_MODE_EVENT + settings["event_bus"] = "nats" + with namespace_scope("orders"): + nightly = _TestScheduler() + nightly.name = "nightly" + + handler = nightly.wire() + + assert handler is not None + assert handler.namespace == "orders" + assert handler.name == "orders_nightly_tick" def test_two_agents_schedulers_of_one_name_get_two_subjects(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: """Derived from app_name they shared a subject and consumed each other's ticks.""" From c05b740804ddc4babb16986f05cb0804ad42e243 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:14:56 +0200 Subject: [PATCH 112/133] fix(scheduler): crontab checked per mode, timezone, one gauge per meter, started only on success Step 11 (S24-S27, D14, D15): asbs validate and --group use the runtime's mode and transport checks. Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 21 ++ ...26-08-28-multi-agent-grouping-changelog.md | 6 + .../agent_generator/cli/commands/validate.py | 103 ++++++++-- .../cli/commands/validate_group.py | 26 +++ .../docs/components/schedulers.md | 12 +- .../agent_generator/docs/guides/cli/create.md | 10 +- .../docs/reference/configuration-keys.md | 1 + .../agents/io/api/scheduling/scheduler.py | 181 +++++++++++++++--- .../cli/commands/test_validate_group.py | 32 ++++ .../cli/commands/test_validate_group_gates.py | 38 +++- .../io/api/scheduling/test_scheduler.py | 96 +++++++++- 11 files changed, 469 insertions(+), 57 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f134f6a..04a484f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,27 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **Crontabs read the same in both scheduler modes, or fail startup.** The day of the week is + apscheduler's count -- `0` = Monday ... `6` = Sunday -- so `in_process` firing days do not move. `7` is + refused (it was accepted in `event` mode and failed only when the timer was built), and **an `event`-mode + scheduler whose crontab gives the day of the week by number (`1-5`, `*/2`) now fails startup**: the + external cron counts `0` as Sunday, so the number named a different day there. Write names + (`mon-fri`). The crontab is now checked when the scheduler is wired in both modes. New, opt-in: + `scheduler_timezone` for the `in_process` timer; unset keeps the host's local time. + +- **A scheduler whose startup failed is no longer reported as recovered.** It was marked started before + its timer existed, so the startup retry found it "already started" and cleared the agent's latch + with no timer running. + +- **Every scheduler's `blueprint.scheduler.tick_age_seconds` is exported.** A second scheduler of one + agent created a second gauge of the same name, which the SDK drops, so only the first was reported. + Measured with two in-process schedulers: two points (before: one). + +- **`asbs validate` checks schedulers as the runtime does.** It accepts `scheduler_mode` written as the + runtime reads it (`"Event"`), counts environment overrides, refuses an `event_bus` that cannot deliver + a tick, reports a missing `event_bus` as a notice (it is a process-wide key and may be set elsewhere), + and `--group` runs the scheduler checks per agent. + - **A grouped scheduler's tick subject and trigger route name the agent once.** Both were built from the scheduler's qualified name, so the subject was `orders.scheduler.orders_nightly` and the route `/api/orders/scheduler/orders_nightly/trigger`; they are now `orders.scheduler.nightly` and diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index ec2c50e8..130996a5 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,12 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 11, scheduler robustness (S24-S27, D14, D15): `_started` is set only after the timer or the event + wiring stands; one tick-age gauge per meter reports every scheduler of it (weak registry); `validate_crontab` + runs in both modes, refuses day `7` and, in event mode, any numeric weekday; opt-in `scheduler_timezone`; + `asbs validate` and `--group` use the runtime's mode and transport checks and count environment + overrides. Live (real APScheduler timer, every-minute crontab, UTC, two schedulers): both ticked at the + next minute and the gauge reported both; control: one gauge point. - Step 10, grouped scheduler (M8, M9): the tick handler is built under `namespace_scope(self.namespace)`; tick subject, trigger route and handler name use `base_name`; docs agree. Live (Core NATS, a group with agent `orders`, scheduler `nightly`, event mode): subscribed `orders.scheduler.nightly`, handler diff --git a/src/blueprint/agent_generator/cli/commands/validate.py b/src/blueprint/agent_generator/cli/commands/validate.py index 3b2e5bd9..904615d8 100644 --- a/src/blueprint/agent_generator/cli/commands/validate.py +++ b/src/blueprint/agent_generator/cli/commands/validate.py @@ -2,6 +2,7 @@ import importlib.util import logging +import os import re import sys import tomllib @@ -16,7 +17,13 @@ from . import validate_group from ..utils.cancellation_check import swallowed_cancellation_warning, swallowed_cancellations -from blueprint.agents.io.api.scheduling.scheduler import SCHEDULER_MODE_EVENT, SCHEDULER_MODE_IN_PROCESS, SCHEDULER_MODES +from blueprint.agents.io.api.scheduling.scheduler import ( + SCHEDULER_MODE_EVENT, + SCHEDULER_MODE_IN_PROCESS, + SCHEDULER_MODES, + delivers_ticks, + normalise_scheduler_mode, +) logger = logging.getLogger(__name__) @@ -402,23 +409,49 @@ def _scheduler_findings(project_dir: Path) -> tuple[list[str], list[str]]: external ``CronJob`` must publish, and nothing in this repository generates one -- so a project can be correct in every mechanical respect and simply never run. """ - schedulers = _scheduler_modules(project_dir) + settings = _load_settings(project_dir / SETTINGS_FILE) or {} + return scheduler_findings(project_dir, mode_sources=[settings], bus_sources=[settings], where=SETTINGS_FILE) + + +def scheduler_findings( + agent_dir: Path, *, mode_sources: list[dict[str, Any]], bus_sources: list[dict[str, Any]], where: str, agent: str = "" +) -> tuple[list[str], list[str]]: + """The scheduler checks, on the runtime's own terms (S27); shared by the single and the group command. + + ``scheduler_mode`` is read from ``mode_sources`` in order (an agent's file before the image's) + and ``event_bus`` from ``bus_sources`` (the process's file: it is a process-scope key), each + with an environment override winning, as at runtime. The mode is normalised like the runtime + normalises it, and an event-mode transport must be one that delivers a tick. + + Args: + agent_dir: The directory whose ``src/schedulers`` is looked at. + mode_sources: Parsed settings files to read ``scheduler_mode`` from, first wins. + bus_sources: Parsed settings files to read ``event_bus`` from, first wins. + where: The file(s) named in a message. + agent: The agent's name in a group, for its scoped environment override and the messages. + """ + schedulers = _scheduler_modules(agent_dir) if not schedulers: return [], [] + prefix = _envvar_prefix([*mode_sources, *bus_sources]) + named = f"Agent '{agent}': " if agent else "" - settings = _load_settings(project_dir / SETTINGS_FILE) - mode = _value_of(settings, "scheduler_mode") if settings is not None else None + raw_mode = _env_value(prefix, "scheduler_mode", agent) + if raw_mode is None: + raw_mode = _first_value(mode_sources, "scheduler_mode") + mode = normalise_scheduler_mode(raw_mode) - if mode is None: + if not mode: return [ - f"{len(schedulers)} scheduler(s) under src/schedulers/ and no 'scheduler_mode' in {SETTINGS_FILE}. It has " - f"no default, because neither value is safe to inherit, so build() fails: set '{SCHEDULER_MODE_IN_PROCESS}' " - f"to run a timer in the process (needs .with_cache(), or every replica runs every tick) or " - f"'{SCHEDULER_MODE_EVENT}' to take the tick as an event (needs 'event_bus', and something publishing it)" + f"{named}{len(schedulers)} scheduler(s) under src/schedulers/ and no 'scheduler_mode' in {where} or the " + f"environment. It has no default, because neither value is safe to inherit, so build() fails: set " + f"'{SCHEDULER_MODE_IN_PROCESS}' to run a timer in the process (needs .with_cache(), or every replica runs " + f"every tick) or '{SCHEDULER_MODE_EVENT}' to take the tick as an event (needs 'event_bus', and something " + "publishing it)" ], [] if mode not in SCHEDULER_MODES: - return [f"'scheduler_mode' is {mode!r} in {SETTINGS_FILE}; it must be one of {', '.join(SCHEDULER_MODES)}"], [] + return [f"{named}'scheduler_mode' is {raw_mode!r}; it must be one of {', '.join(SCHEDULER_MODES)}"], [] issues: list[str] = [] notices: list[str] = [] @@ -437,14 +470,26 @@ def _scheduler_findings(project_dir: Path) -> tuple[list[str], list[str]]: ] ) ) - if not _declares(settings or {}, "event_bus"): + bus = _env_value(prefix, "event_bus") + if bus is None: + bus = _first_value(bus_sources, "event_bus") + if bus is None: + # A notice: event_bus is a process-scope key, so it may well be set where this command + # does not look -- the group's settings, the deployment's environment. + notices.append( + f"{named}'scheduler_mode' is '{SCHEDULER_MODE_EVENT}' and no 'event_bus' is set in {where} or the " + "environment. The tick arrives as an event, so startup fails unless the process sets one of " + "'dapr' or 'nats'." + ) + elif not delivers_ticks(bus): # This one *does* fail at startup -- the tick is an ordinary event, so without a - # transport there is nothing to subscribe to -- so it is an issue rather than advice. + # transport that carries topics there is nothing to subscribe to. issues.append( - f"'scheduler_mode' is '{SCHEDULER_MODE_EVENT}' and no 'event_bus' is set. The tick arrives as an event, " - "so there is nothing to subscribe to and wiring the scheduler fails at startup" + f"{named}'scheduler_mode' is '{SCHEDULER_MODE_EVENT}' and 'event_bus' is {bus!r}, which cannot deliver " + "a tick: the tick is an event on a topic, so it needs 'dapr' or 'nats'. Wiring the scheduler fails at " + "startup" ) - elif not _main_declares_a_cache(project_dir): + elif not _main_declares_a_cache(agent_dir): notices.append( "\n".join( [ @@ -562,6 +607,34 @@ def _declares(settings: dict[str, Any], key: str) -> bool: return any(isinstance(value, dict) and key in value for value in settings.values()) +def _first_value(sources: list[dict[str, Any]], key: str) -> Any | None: + """``key``'s value from the first of ``sources`` that sets it (see :func:`_value_of`).""" + for settings in sources: + value = _value_of(settings, key) + if value is not None: + return value + return None + + +def _envvar_prefix(sources: list[dict[str, Any]]) -> str: + """The environment prefix the process reads overrides through: ``envvar_prefix``, else ``DYNACONF``.""" + configured = _first_value(sources, "envvar_prefix") + return str(configured).strip() if configured else "DYNACONF" + + +def _env_value(prefix: str, key: str, agent: str = "") -> str | None: + """An environment override of ``key``, as the runtime reads it: the agent's scoped one first, then the root's. + + Read so that a value the deployment supplies is not reported as missing (S27). + """ + names = ([f"{prefix}_{agent.upper()}__{key.upper()}"] if agent else []) + [f"{prefix}_{key.upper()}"] + for name in names: + value = os.environ.get(name) + if value is not None and value.strip(): + return value + return None + + def _value_of(settings: dict[str, Any], key: str) -> Any | None: """Return ``key``'s value from the top level, or from the first environment that sets it. diff --git a/src/blueprint/agent_generator/cli/commands/validate_group.py b/src/blueprint/agent_generator/cli/commands/validate_group.py index a2066a8f..cf6c39cc 100644 --- a/src/blueprint/agent_generator/cli/commands/validate_group.py +++ b/src/blueprint/agent_generator/cli/commands/validate_group.py @@ -188,6 +188,22 @@ def _agent_findings(image_root: Path, name: str, entry: Any, claimed: dict[Path, else: print(f"[--] {name}: no settings.toml of its own; it reads the image's") + # The scheduler checks the single-agent command runs, on the group's terms (S27): the agent's + # scheduler_mode before the image's, and event_bus from the image, where a process key lives. + from .validate import scheduler_findings # here, not at the top: validate imports this module + + agent_settings = _load(settings) + image_settings = _load(image_root / "settings.toml") + scheduler_issues, scheduler_notices = scheduler_findings( + root, + mode_sources=[agent_settings, image_settings], + bus_sources=[image_settings], + where=f"{declared_root}/settings.toml or the image's settings.toml", + agent=name, + ) + issues.extend(scheduler_issues) + notices.extend(scheduler_notices) + if root != image_root and root.name != name: notices.append( f"Agent '{name}' lives in a directory named '{root.name}'. Nothing breaks, but 'asbs dev' in that " @@ -198,6 +214,16 @@ def _agent_findings(image_root: Path, name: str, entry: Any, claimed: dict[Path, return issues, warnings, notices +def _load(settings: Path) -> dict[str, Any]: + """A parsed settings file, or ``{}`` when it is missing or unreadable (its own check reports that).""" + if not settings.is_file(): + return {} + try: + return tomllib.loads(settings.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError): + return {} + + def _self_scoped_issues(name: str, settings: Path) -> list[str]: """Report an agent settings file that scopes keys under the agent's own name. diff --git a/src/blueprint/agent_generator/docs/components/schedulers.md b/src/blueprint/agent_generator/docs/components/schedulers.md index 2a889841..d053d0e1 100644 --- a/src/blueprint/agent_generator/docs/components/schedulers.md +++ b/src/blueprint/agent_generator/docs/components/schedulers.md @@ -52,7 +52,7 @@ A cron expression consists of five fields separated by spaces: │ ┌───────────── hour (0-23) │ │ ┌───────────── day of month (1-31) │ │ │ ┌───────────── month (1-12) -│ │ │ │ ┌───────────── day of week (0-6, 0 = Sunday) +│ │ │ │ ┌───────────── day of week (mon-sun; 0-6 = Monday-Sunday) │ │ │ │ │ * * * * * ``` @@ -64,10 +64,16 @@ A cron expression consists of five fields separated by spaces: | `0 * * * *` | Every hour, on the hour | | `0 */2 * * *` | Every 2 hours | | `30 9 * * *` | Daily at 09:30 | -| `0 9 * * 1` | Every Monday at 09:00 | +| `0 9 * * mon` | Every Monday at 09:00 | | `0 0 1 * *` | First day of each month at midnight | | `0 6,18 * * *` | At 06:00 and 18:00 daily | -| `*/15 9-17 * * 1-5` | Every 15 minutes during business hours, weekdays only | +| `*/15 9-17 * * mon-fri` | Every 15 minutes during business hours, weekdays only | + +**The day of the week counts from Monday:** `0` is Monday and `6` is Sunday, as in apscheduler, which +runs the `in_process` timer. A standard cron -- the `CronJob` that fires an `event`-mode tick -- counts +`0` as Sunday, so write days as names (`mon`, `mon-fri`, `sun`), which both read the same. `7` is +refused, and in `event` mode so is any day given by number. The `in_process` timer runs in the +host's local time unless `scheduler_timezone` names one (`"UTC"`, `"Europe/Berlin"`). ## Abstract Method: tick diff --git a/src/blueprint/agent_generator/docs/guides/cli/create.md b/src/blueprint/agent_generator/docs/guides/cli/create.md index 285c2f26..cc884a54 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/create.md +++ b/src/blueprint/agent_generator/docs/guides/cli/create.md @@ -426,7 +426,7 @@ Use standard 5-field cron syntax: │ ┌───────────── hour (0-23) │ │ ┌───────────── day of month (1-31) │ │ │ ┌───────────── month (1-12) -│ │ │ │ ┌───────────── day of week (0-7, 0=Sunday) +│ │ │ │ ┌───────────── day of week (mon-sun; 0-6 = Monday-Sunday) │ │ │ │ │ │ │ │ │ │ * * * * * @@ -436,9 +436,15 @@ Common patterns: - `*/5 * * * *` - Every 5 minutes - `0 * * * *` - Every hour at minute 0 - `0 2 * * *` - Daily at 2:00 AM -- `0 8 * * 1-5` - Weekdays at 8:00 AM +- `0 8 * * mon-fri` - Weekdays at 8:00 AM - `0 0 1 * *` - Monthly at midnight on the 1st +**The day of the week counts from Monday:** `0` is Monday and `6` is Sunday, as in apscheduler, which +runs the `in_process` timer. A standard cron -- the `CronJob` that fires an `event`-mode tick -- counts +`0` as Sunday, so write days as names (`mon`, `mon-fri`, `sun`), which both read the same. `7` is +refused, and in `event` mode so is any day given by number. The `in_process` timer runs in the +host's local time unless `scheduler_timezone` names one (`"UTC"`, `"Europe/Berlin"`). + ### Examples #### Hourly Scheduler diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 175988f3..e199beac 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -150,6 +150,7 @@ effects is acceptable is a property of the product, not of the framework. | Key | Type | Default | Description | |-----|------|---------|-------------| +| `scheduler_timezone` | `str` | unset -- the host's local time | The IANA timezone the `in_process` timer reads its crontab in (`"UTC"`, `"Europe/Berlin"`). An unknown name fails startup. In `event` mode the external cron's own timezone decides and this key changes nothing. | | `scheduler_mode` | `str` | -- (**required** when a scheduler is registered) | Where a scheduler's tick comes from. `"event"` starts no in-process timer: the tick arrives as an ordinary event on the scheduler's own topic (`.scheduler.`, with `app_name` for a scheduler at the root and the scheduler's name without the agent, unless overridden with `topic=` in the scheduler's constructor), published by an external `CronJob`, so the queue group already picks exactly one replica and nothing is elected -- it requires `event_bus` to be `"dapr"` or `"nats"`, since `"sessions"` cannot deliver a topic. `"in_process"` runs an APScheduler timer inside every replica and coordinates them through the registered cache: each tick is claimed under a key derived from the scheduler and the scheduled minute, and only the replica that stores the marker runs it. Intended for local development and un-orchestrated Docker, where no `CronJob` exists. **With no cache registered the ticks cannot be coordinated and every replica runs every tick**; startup warns about it. **No default:** neither value is safe to inherit silently, and which one applies depends on the deployment (is a broker reachable, does more than one replica run, is there an orchestrator at all) rather than on the code, so the author states it -- the same reasoning as `idempotency_ttl`. An absent, empty or unrecognised value fails startup. | --- diff --git a/src/blueprint/agents/io/api/scheduling/scheduler.py b/src/blueprint/agents/io/api/scheduling/scheduler.py index 63599cc3..d24bb435 100644 --- a/src/blueprint/agents/io/api/scheduling/scheduler.py +++ b/src/blueprint/agents/io/api/scheduling/scheduler.py @@ -38,12 +38,15 @@ async def tick(self) -> None: from __future__ import annotations +import functools import logging import time +import weakref from abc import abstractmethod from collections.abc import Iterable from datetime import UTC, datetime from typing import Any +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.triggers.cron import CronTrigger @@ -91,22 +94,58 @@ async def tick(self) -> None: outlast the interval between ticks, because the next tick claims a different key. """ +_TICK_GAUGE_SCHEDULERS: weakref.WeakKeyDictionary[Any, weakref.WeakSet[SchedulerBase]] = weakref.WeakKeyDictionary() +"""Per meter, the schedulers its one tick-age gauge reports (S26). Weak both ways: a meter replaced +with its provider, or a scheduler gone with its application, drops out by itself.""" -def validate_crontab(crontab: str) -> str: - """Return the crontab if an external cron can read it, else raise. - In ``"in_process"`` mode ``CronTrigger.from_crontab`` parses the expression, so a typo - fails the pod. In ``"event"`` mode nothing parses it at all -- the tick arrives from - outside -- so without this a typo surfaces as a tick that never comes, long after the - process reported itself healthy. +def _observe_tick_ages(schedulers: weakref.WeakSet[SchedulerBase], _options: CallbackOptions) -> Iterable[Observation]: + return [scheduler.tick_age_observation() for scheduler in list(schedulers)] + + +def normalise_scheduler_mode(raw: object) -> str: + """``scheduler_mode`` as the runtime reads it: trimmed and lower-cased; ``""`` when unset. + + Shared with ``asbs validate`` (S27), which compared the raw value and so refused ``"Event"``, + a value the runtime runs. + """ + return str(raw or "").strip().lower() + + +def delivers_ticks(event_bus: object) -> bool: + """Whether ``event_bus`` names a transport that can deliver an event-mode tick (a topic subscription). + + Shared with ``asbs validate`` (S27), which only checked that the key was present. + """ + return str(event_bus or "").strip().lower() in TOPIC_TRANSPORTS + + +def validate_crontab(crontab: str, mode: str | None = None) -> str: + """Return the crontab if this scheduler and an external cron read it alike, else raise. + + Run in both modes (S27). In ``"event"`` mode nothing else parses the expression -- the tick + arrives from outside -- so without this a typo surfaces as a tick that never comes, long + after the process reported itself healthy. ``croniter`` is used rather than apscheduler's parser because the consumer of this - expression is an external scheduler reading the five standard fields, and apscheduler + expression may be an external scheduler reading the five standard fields, and apscheduler accepts extensions such as a leading seconds field that no cron implementation does. + **The day of the week** (plan D14). The blueprint's dialect is apscheduler's, which runs the + ``"in_process"`` timer: ``0`` is Monday and ``6`` is Sunday. A standard cron counts ``0`` as + Sunday, so the two disagree on every number; names (``mon``, ``mon-fri``, ``sun``) read the + same in both. Hence ``7`` is refused everywhere (Sunday to cron, nothing to apscheduler), and + in ``"event"`` mode -- where an external cron fires the tick -- a day of the week given by + number is refused, because which day it names depends on who reads it. + + Args: + crontab: The declared expression. + mode: ``"event"`` or ``"in_process"``; ``None`` leaves out the numeric-weekday check. + Raises: - ValueError: if the expression is empty, is not a valid cron expression, or does not - have exactly the five standard fields. + ValueError: if the expression is empty, is not a valid cron expression, does not have + exactly the five standard fields, names day ``7``, or names a day by number in + ``"event"`` mode. """ expression = crontab.strip() if not expression: @@ -124,9 +163,51 @@ def validate_crontab(crontab: str) -> str: "ones (minute hour day-of-month month day-of-week); seconds and year are apscheduler extensions it will not " "understand." ) + weekday = fields[4] + if _names_day_seven(weekday): + raise ValueError( + f"The declared crontab '{crontab}' names day 7 in its day-of-week field. In the blueprint 0 is Monday and 6 " + "is Sunday (apscheduler's count); 7 is Sunday to a standard cron and nothing to apscheduler. Name the day " + "instead: 'sun'." + ) + if mode == SCHEDULER_MODE_EVENT and _names_a_day_by_number(weekday): + raise ValueError( + f"The declared crontab '{crontab}' gives the day of the week by number ('{weekday}'), and in event mode an " + "external cron fires the tick. A standard cron counts 0 as Sunday, the blueprint counts 0 as Monday, so the " + "number names a different day depending on who reads it. Use names, which both read the same: 'mon-fri', " + "'sun', 'mon,wed'." + ) return expression +def _weekday_terms(field: str) -> list[tuple[str, str]]: + """The ``(base, step)`` terms of a day-of-week field: ``"mon-fri/2,sun"`` -> ``[("mon-fri", "2"), ("sun", "")]``.""" + terms = [] + for term in field.split(","): + base, _, step = term.partition("/") + terms.append((base, step)) + return terms + + +def _names_day_seven(field: str) -> bool: + """Whether a day-of-week field uses ``7`` as a day (not as a step).""" + return any("7" in base.split("-") for base, _ in _weekday_terms(field)) + + +def _names_a_day_by_number(field: str) -> bool: + """Whether a day-of-week field depends on how days are numbered. + + A number as a day or a range end does, and so does ``*/n``: it steps from day 0, which is a + different day in each count. ``*`` alone and names do not. + """ + for base, step in _weekday_terms(field): + if any(character.isdigit() for character in base): + return True + if base == "*" and step: + return True + return False + + _TOPIC_CONTEXT_KEYS = ("nats_topic", "dapr_topic", "topic") """Every key a transport spells the delivery topic with. @@ -242,6 +323,7 @@ def __init__(self, crontab: str, *, topic: str | None = None) -> None: self._tick_handler: SchedulerTickHandler | None = None self._scheduler: AsyncIOScheduler | None = None self._started = False + self._gauge_registered = False self._trigger_route_registered = False # When this scheduler last ran its tick, for the freshness gauge. None until the first. self._last_tick: float | None = None @@ -314,15 +396,14 @@ def wire(self) -> SchedulerTickHandler | None: transport that can deliver the tick, or if the tick topic is unusable. """ self.register_trigger_route() + # Both modes (S27): in in_process mode apscheduler parses it too, but only in on_startup, + # and it neither refuses 7 with a reason nor reads a weekday as an external cron would. + validate_crontab(self._crontab, self.scheduler_mode) if self.scheduler_mode != SCHEDULER_MODE_EVENT: return None self._require_event_transport() - # Nothing else ever parses the crontab in event mode -- no CronTrigger is built -- so a - # typo would otherwise surface as a tick that never arrives, long after this process - # reported itself healthy. - validate_crontab(self._crontab) if self._tick_handler is None: # In the scheduler's own namespace (M8): build() calls this outside any scope, so the # handler -- a Component taking its namespace from the ambient scope -- landed at the @@ -369,7 +450,7 @@ def _resolve_mode(self) -> str: not fall back to either mode. """ raw = self.config.get("scheduler_mode", None) - mode = str(raw or "").strip().lower() + mode = normalise_scheduler_mode(raw) if not mode: raise ValueError( f"Scheduler '{self.name}' is registered but 'scheduler_mode' is not set, and it has no default. " @@ -382,6 +463,27 @@ def _resolve_mode(self) -> str: raise ValueError(f"Config key 'scheduler_mode' must be one of {', '.join(SCHEDULER_MODES)}, got {raw!r}.") return mode + def _resolve_timezone(self) -> Any: + """``scheduler_timezone`` as a ``ZoneInfo``, or ``None`` for the host's local time (plan D15). + + Opt-in: unset keeps the host-local timezone every in-process scheduler has always used. + Only the in-process timer reads it; in event mode the external cron's own timezone + decides, and this key changes nothing. + + Raises: + ValueError: if the value is not an IANA timezone name. + """ + raw = str(self.config.get("scheduler_timezone", "") or "").strip() + if not raw: + return None + try: + return ZoneInfo(raw) + except (ZoneInfoNotFoundError, ValueError): + raise ValueError( + f"'scheduler_timezone' of scheduler '{self.base_name}' is {raw!r}, which is not an IANA timezone name " + "(such as 'Europe/Berlin' or 'UTC')." + ) from None + def _require_event_transport(self) -> None: """Fail unless a transport that can deliver a tick is configured. @@ -394,7 +496,7 @@ def _require_event_transport(self) -> None: a topic subscription. """ bus = str(self.config.get("event_bus", "") or "").strip().lower() - if bus not in TOPIC_TRANSPORTS: + if not delivers_ticks(bus): raise ValueError( f"Scheduler '{self.name}' is in '{SCHEDULER_MODE_EVENT}' mode, which delivers its tick as an event on " f"'{self.tick_topic}', but 'event_bus' is {bus or 'not set'!r}. Set 'event_bus' to one of " @@ -472,7 +574,9 @@ async def on_startup(self) -> None: if self._started: logger.warning("Scheduler '%s' is already started; ignoring the repeated startup", self.name) return - self._started = True + # Marked started only once it is (S25). Set first, a startup that raised -- a crontab the + # timer refuses -- left the flag up, and the startup retry then found it "already started", + # cleared the agent's latch and reported a recovery with no timer running. self._register_tick_gauge() # Normally already done by AppBuilder.build(); repeated here so a scheduler driven @@ -480,6 +584,7 @@ async def on_startup(self) -> None: self.wire() if self.scheduler_mode == SCHEDULER_MODE_EVENT: + self._started = True logger.info( "Scheduler '%s' is in event mode: no in-process timer. Its tick arrives as an event on topic '%s', " "on the declared crontab '%s'.", @@ -489,11 +594,14 @@ async def on_startup(self) -> None: ) return - trigger = CronTrigger.from_crontab(self._crontab) + timezone = self._resolve_timezone() + trigger = CronTrigger.from_crontab(self._crontab, timezone=timezone) - self._scheduler = AsyncIOScheduler() - self._scheduler.add_job(self._claimed_tick, trigger, name=self.name) - self._scheduler.start() + scheduler = AsyncIOScheduler(timezone=timezone) if timezone is not None else AsyncIOScheduler() + scheduler.add_job(self._claimed_tick, trigger, name=self.name) + scheduler.start() + self._scheduler = scheduler + self._started = True if self.registry.has_cache(): logger.info( @@ -521,18 +629,29 @@ def _register_tick_gauge(self) -> None: missing pod; event mode is where it is not, because a ``CronJob`` that stopped publishing leaves a perfectly healthy process ticking never. """ - name = self.name - - def observe(_options: CallbackOptions) -> Iterable[Observation]: - age = -1.0 if self._last_tick is None else max(0.0, time.time() - self._last_tick) - return [Observation(age, {"scheduler": name, "agent": self.namespace or ROOT_LABEL, "mode": self.scheduler_mode})] + if self._gauge_registered: + return + # One instrument per meter, reporting every scheduler of it (S26): a second + # create_observable_gauge of the same name on one meter is dropped by the SDK, so only the + # first scheduler of an agent was ever exported. + meter = agent_meter(self.namespace, __name__) + schedulers = _TICK_GAUGE_SCHEDULERS.get(meter) + if schedulers is None: + schedulers = weakref.WeakSet() + _TICK_GAUGE_SCHEDULERS[meter] = schedulers + meter.create_observable_gauge( + TICK_AGE_GAUGE, + callbacks=[functools.partial(_observe_tick_ages, schedulers)], + description="Seconds since this scheduler last ticked; -1 before its first", + unit="s", + ) + schedulers.add(self) + self._gauge_registered = True - agent_meter(self.namespace, __name__).create_observable_gauge( - TICK_AGE_GAUGE, - callbacks=[observe], - description="Seconds since this scheduler last ticked; -1 before its first", - unit="s", - ) + def tick_age_observation(self) -> Observation: + """This scheduler's point of the tick-age gauge.""" + age = -1.0 if self._last_tick is None else max(0.0, time.time() - self._last_tick) + return Observation(age, {"scheduler": self.name, "agent": self.namespace or ROOT_LABEL, "mode": self.scheduler_mode}) async def run_tick(self) -> None: """Run the tick and record that it happened. diff --git a/tests/unit/agent_generator/cli/commands/test_validate_group.py b/tests/unit/agent_generator/cli/commands/test_validate_group.py index 5b9c3d07..f8d721dd 100644 --- a/tests/unit/agent_generator/cli/commands/test_validate_group.py +++ b/tests/unit/agent_generator/cli/commands/test_validate_group.py @@ -165,3 +165,35 @@ def test_a_long_list_is_summarised(self, tmp_path: Path) -> None: found = [w for w in warnings if "imports its own code as 'src'" in w] assert "and 3 more" in found[0] + + +class TestSchedulersInAGroup: + """S27 (d) -- '--group' ran no scheduler check at all.""" + + @staticmethod + def _image(tmp_path: Path, agent_settings: str, image_settings: str = "") -> Path: + _agent_dir(tmp_path / "agents" / "orders") + schedulers = tmp_path / "agents" / "orders" / "src" / "schedulers" + schedulers.mkdir(parents=True) + (schedulers / "nightly_scheduler.py").write_text("# scheduler\n", encoding="utf-8") + (tmp_path / "agents" / "orders" / "settings.toml").write_text(agent_settings, encoding="utf-8") + if image_settings: + (tmp_path / "settings.toml").write_text(image_settings, encoding="utf-8") + (tmp_path / "agents.toml").write_text(_map_text("agents/orders"), encoding="utf-8") + return tmp_path + + def test_a_scheduler_without_a_mode_is_an_issue(self, tmp_path: Path) -> None: + image = self._image(tmp_path, '[default]\nmodel_name = "x"\n') + + issues, _, _ = _findings(image, image / "agents.toml") + + assert any("Agent 'orders'" in issue and "no 'scheduler_mode'" in issue for issue in issues) + + def test_the_images_event_bus_serves_an_agents_event_mode(self, tmp_path: Path) -> None: + """scheduler_mode from the agent's file, event_bus from the image's -- where a process key lives.""" + image = self._image(tmp_path, '[default]\nscheduler_mode = "event"\n', '[default]\nevent_bus = "nats"\n') + + issues, _, notices = _findings(image, image / "agents.toml") + + assert not [issue for issue in issues if "scheduler" in issue] + assert any("CronJob" in notice for notice in notices) diff --git a/tests/unit/agent_generator/cli/commands/test_validate_group_gates.py b/tests/unit/agent_generator/cli/commands/test_validate_group_gates.py index 06e0adae..2a76f2fb 100644 --- a/tests/unit/agent_generator/cli/commands/test_validate_group_gates.py +++ b/tests/unit/agent_generator/cli/commands/test_validate_group_gates.py @@ -8,6 +8,8 @@ from pathlib import Path +import pytest + from blueprint.agent_generator.cli.commands.validate import _group_findings DECLARATION = "from blueprint.agents.app_builder import AppBuilder\n\nagent = AppBuilder()\n" @@ -190,13 +192,43 @@ def test_event_mode_says_that_nothing_here_publishes_the_tick(self, tmp_path: Pa assert len(notices) == 1 assert "CronJob" in notices[0] - def test_event_mode_without_a_bus_is_an_issue(self, tmp_path: Path) -> None: - """The tick is an ordinary event, so with no transport there is nothing to subscribe to.""" + def test_event_mode_without_a_bus_in_this_file_is_a_notice(self, tmp_path: Path) -> None: + """S27 -- event_bus is a process-scope key: the group's settings or the environment may set it.""" project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings='[default]\nscheduler_mode = "event"\n')) + issues, _, notices = _group_findings(project) + + assert issues == [] + assert any("no 'event_bus' is set" in notice for notice in notices) + + def test_event_mode_on_a_bus_that_cannot_deliver_a_tick_is_an_issue(self, tmp_path: Path) -> None: + """S27 (a) -- the runtime needs a topic transport; 'sessions' is present but delivers no tick.""" + settings = '[default]\nscheduler_mode = "event"\nevent_bus = "sessions"\n' + project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings=settings)) + issues, _, _ = _group_findings(project) - assert any("no 'event_bus' is set" in issue for issue in issues) + assert any("'event_bus' is 'sessions', which cannot deliver a tick" in issue for issue in issues) + + def test_the_mode_is_read_as_the_runtime_reads_it(self, tmp_path: Path) -> None: + """S27 (e) -- 'Event' runs; validate refused it.""" + settings = '[default]\nscheduler_mode = " Event "\nevent_bus = "nats"\n' + project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings=settings)) + + issues, _, _ = _group_findings(project) + + assert issues == [] + + def test_an_environment_override_counts(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """S27 (c) -- a value the deployment supplies is not missing.""" + monkeypatch.setenv("DYNACONF_SCHEDULER_MODE", "event") + monkeypatch.setenv("DYNACONF_EVENT_BUS", "nats") + project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings='[default]\napp_name = "demo"\n')) + + issues, _, notices = _group_findings(project) + + assert issues == [] + assert not any("no 'event_bus'" in notice for notice in notices) def test_in_process_mode_without_a_cache_says_every_replica_runs_every_tick(self, tmp_path: Path) -> None: settings = '[default]\nscheduler_mode = "in_process"\n' diff --git a/tests/unit/agents/io/api/scheduling/test_scheduler.py b/tests/unit/agents/io/api/scheduling/test_scheduler.py index 30504dd3..13b46f32 100644 --- a/tests/unit/agents/io/api/scheduling/test_scheduler.py +++ b/tests/unit/agents/io/api/scheduling/test_scheduler.py @@ -174,8 +174,8 @@ async def tick(self) -> None: with pytest.raises(ValueError, match="cron"): _BadCrontabScheduler().wire() - def test_in_process_wiring_does_not_reach_the_check(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: - """apscheduler validates it there, at the point it builds the trigger.""" + def test_in_process_wiring_checks_it_too(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + """S27 -- apscheduler parsed it only in on_startup, so a bad crontab passed wiring (and validate).""" settings["scheduler_mode"] = SCHEDULER_MODE_IN_PROCESS class _LooseCrontabScheduler(SchedulerBase): @@ -185,7 +185,28 @@ def __init__(self) -> None: async def tick(self) -> None: """Never called.""" - assert _LooseCrontabScheduler().wire() is None + with pytest.raises(ValueError, match="not a valid cron expression"): + _LooseCrontabScheduler().wire() + + @pytest.mark.parametrize("mode", [SCHEDULER_MODE_IN_PROCESS, SCHEDULER_MODE_EVENT]) + def test_day_seven_is_refused_in_both_modes(self, mode: str) -> None: + """D14 -- 7 is Sunday to a standard cron and nothing to apscheduler.""" + with pytest.raises(ValueError, match="names day 7.*Name the day instead: 'sun'"): + validate_crontab("0 3 * * 7", mode) + + @pytest.mark.parametrize("crontab", ["0 3 * * 1", "0 3 * * 1-5", "0 3 * * */2", "0 3 * * mon,3"]) + def test_a_weekday_by_number_is_refused_in_event_mode(self, crontab: str) -> None: + """D14 -- an external cron counts 0 as Sunday, the blueprint 0 as Monday.""" + with pytest.raises(ValueError, match="names a different day depending on who reads it"): + validate_crontab(crontab, SCHEDULER_MODE_EVENT) + + @pytest.mark.parametrize("crontab", ["0 3 * * mon-fri", "0 3 * * sun", "*/15 9-17 * * mon-fri", "0 3 * * *", "0 3 * * mon-fri/2"]) + def test_named_weekdays_pass_in_event_mode(self, crontab: str) -> None: + assert validate_crontab(crontab, SCHEDULER_MODE_EVENT) == crontab + + def test_a_weekday_by_number_still_runs_in_process(self) -> None: + """In in_process mode the blueprint itself reads it -- 0 is Monday -- so firing days do not move.""" + assert validate_crontab("0 3 * * 1-5", SCHEDULER_MODE_IN_PROCESS) == "0 3 * * 1-5" class TestTickTopic: @@ -669,3 +690,72 @@ async def tick(self) -> None: self.ticks += 1 if self.failure is not None: raise self.failure + + +class TestStartupIsMarkedOnlyOnceItSucceeded: + """S25 -- a startup that raised left _started up; the retry then reported a recovery with no timer.""" + + async def test_a_failed_startup_can_be_retried(self, in_process_scheduler: _TestScheduler) -> None: + with ( + patch(f"{_SCHEDULER_MODULE}.CronTrigger.from_crontab", side_effect=ValueError("refused")), + pytest.raises(ValueError, match="refused"), + ): + await in_process_scheduler.on_startup() + assert in_process_scheduler._started is False + + with patch(f"{_SCHEDULER_MODULE}.AsyncIOScheduler") as timer: + await in_process_scheduler.on_startup() + timer.return_value.start.assert_called_once() + assert in_process_scheduler._started is True + + +class TestEverySchedulerHasItsTickAge: + """S26 -- a second gauge of one name on one meter is dropped, so only the first scheduler was exported.""" + + def test_two_schedulers_of_one_agent_are_both_exported(self, settings: dict[str, Any], mock_registry: MagicMock) -> None: + from opentelemetry.sdk.metrics import MeterProvider + from opentelemetry.sdk.metrics.export import InMemoryMetricReader + + settings["scheduler_mode"] = SCHEDULER_MODE_IN_PROCESS + reader = InMemoryMetricReader() + meter = MeterProvider(metric_readers=[reader]).get_meter("test") + nightly, hourly = _TestScheduler(), _TestScheduler() + nightly.name, hourly.name = "nightly", "hourly" + with patch(f"{_SCHEDULER_MODULE}.agent_meter", return_value=meter): + nightly._register_tick_gauge() + hourly._register_tick_gauge() + nightly._register_tick_gauge() # a retried startup registers nothing twice + + data = reader.get_metrics_data() + points = [ + point.attributes["scheduler"] + for resource in data.resource_metrics + for scope in resource.scope_metrics + for metric in scope.metrics + if metric.name == "blueprint.scheduler.tick_age_seconds" + for point in metric.data.data_points + ] + assert sorted(points) == ["hourly", "nightly"] + + +class TestSchedulerTimezone: + """D15 -- host-local by default; scheduler_timezone opts into a named zone for the in-process timer.""" + + async def test_unset_keeps_the_host_local_timezone(self, in_process_scheduler: _TestScheduler) -> None: + with patch(f"{_SCHEDULER_MODULE}.AsyncIOScheduler"), patch(f"{_SCHEDULER_MODULE}.CronTrigger.from_crontab") as cron: + await in_process_scheduler.on_startup() + assert cron.call_args.kwargs["timezone"] is None + + async def test_a_named_zone_reaches_the_trigger(self, in_process_scheduler: _TestScheduler, settings: dict[str, Any]) -> None: + from zoneinfo import ZoneInfo + + settings["scheduler_timezone"] = "Europe/Berlin" + with patch(f"{_SCHEDULER_MODULE}.AsyncIOScheduler") as timer, patch(f"{_SCHEDULER_MODULE}.CronTrigger.from_crontab") as cron: + await in_process_scheduler.on_startup() + assert cron.call_args.kwargs["timezone"] == ZoneInfo("Europe/Berlin") + assert timer.call_args.kwargs["timezone"] == ZoneInfo("Europe/Berlin") + + async def test_an_unknown_zone_fails_startup(self, in_process_scheduler: _TestScheduler, settings: dict[str, Any]) -> None: + settings["scheduler_timezone"] = "Mars/Olympus" + with pytest.raises(ValueError, match="not an IANA timezone name"): + await in_process_scheduler.on_startup() From a10fc7d31cb7ae1e17cf4a6e0fadf5bf49cd76b5 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:14:57 +0200 Subject: [PATCH 113/133] fix(cache): a Redis clear or listing touches only the cache's own keys Step 12 (M6): a clear without key_prefix warns; no key-layout change. Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 7 ++ ...26-08-28-multi-agent-grouping-changelog.md | 6 ++ .../agent_generator/docs/concepts/caching.md | 6 ++ .../infrastructure/redis_cache_service.py | 44 ++++++++++-- tests/integration/test_shared_redis_cache.py | 6 +- tests/unit/agents/services/TESTS.md | 2 +- .../test_redis_cache_service.py | 70 +++++++++++++++++++ 7 files changed, 131 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 04a484f5..3549216c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,13 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **Clearing the root Redis cache no longer clears every agent's.** Every named and agent cache nests + under the default store's key prefix, and its `clear()` deleted everything under it -- with + `key_prefix = ""`, the whole database. Its `list_namespaces()` listed the nested stores as its own + namespaces. The default store now touches only keys of its own form, and a clear without a prefix + warns. The key layout is unchanged. Measured on Redis 7: two agents' caches and a foreign key survive + a root clear (before: all gone, the database empty without a prefix). + - **Crontabs read the same in both scheduler modes, or fail startup.** The day of the week is apscheduler's count -- `0` = Monday ... `6` = Sunday -- so `in_process` firing days do not move. `7` is refused (it was accepted in `event` mode and failed only when the timer was built), and **an `event`-mode diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 130996a5..2ac44251 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,12 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 12, Redis cache isolation (M6): the default store's `clear`, `list_namespaces` and `list_values` + take only keys of its own form (`::`); a clear without `key_prefix` warns; + no key-layout change. Live (Redis 7 in WSL, stores from `CacheBackendFactory` for root, `orders`, + `billing`): after a root clear both agents' keys and a foreign key remain, with prefix and without; + control: all agent keys gone, and without a prefix the whole database. The Redis integration tests + (`BLUEPRINT_TEST_REDIS_URL`) ran for the first time on this branch: 3 passed. - Step 11, scheduler robustness (S24-S27, D14, D15): `_started` is set only after the timer or the event wiring stands; one tick-age gauge per meter reports every scheduler of it (weak registry); `validate_crontab` runs in both modes, refuses day `7` and, in event mode, any numeric weekday; opt-in `scheduler_timezone`; diff --git a/src/blueprint/agent_generator/docs/concepts/caching.md b/src/blueprint/agent_generator/docs/concepts/caching.md index 9363cfac..f5c6873c 100644 --- a/src/blueprint/agent_generator/docs/concepts/caching.md +++ b/src/blueprint/agent_generator/docs/concepts/caching.md @@ -154,6 +154,12 @@ Where the data goes: | Agent `orders`, default cache | `/orders.default` | keys under `:orders.default` | | Agent `orders`, cache `sessions` | `/orders.sessions` | keys under `:orders.sessions` | +On Redis every other store nests under the default store's prefix, so the default store's `clear()` +and `list_namespaces()` take only keys of its own form (`::`): clearing +the root cache leaves every agent's and every named cache alone. With `key_prefix = ""` the process +shares the database's keyspace with anything else using it; a clear then warns, and still deletes +only its own keys -- set a prefix. + A named store is a **subdirectory** of `cache_dir` rather than a sibling, because a deployment may mount its volume at `cache_dir` itself and nothing outside the mount can be created under `readOnlyRootFilesystem`. See *Writable Cache Directory* in diff --git a/src/blueprint/agents/services/infrastructure/redis_cache_service.py b/src/blueprint/agents/services/infrastructure/redis_cache_service.py index bcaffbe0..d51d02e0 100644 --- a/src/blueprint/agents/services/infrastructure/redis_cache_service.py +++ b/src/blueprint/agents/services/infrastructure/redis_cache_service.py @@ -2,6 +2,7 @@ import asyncio import json +import re import logging from collections.abc import Iterator from typing import Any @@ -19,6 +20,9 @@ logger = logging.getLogger(__name__) +_DIGEST = re.compile(r"[0-9a-f]{64}") +"""The last segment of every key this class writes: the SHA-256 of the cache key (``CacheKeyMixin.hash``).""" + class RedisCacheService(_CacheKeyMixin, CacheService): """Centralized Redis cache — shares state across multiple service instances. @@ -106,15 +110,30 @@ def _all_scan_pattern(self) -> str: return f"{self._key_prefix}:*" if self._key_prefix else "*" def _parse_namespace(self, redis_key: str) -> str | None: - """Extract namespace from a Redis key, accounting for optional key_prefix.""" + """The namespace of one of this store's own keys; ``None`` for any other key (see :meth:`_owns`).""" + if not self._owns(redis_key): + return None + key = redis_key[len(self._key_prefix) + 1 :] if self._key_prefix else redis_key + return key.split(":", 1)[0] + + def _owns(self, redis_key: str) -> bool: + """Whether ``redis_key`` is this store's own: ``::``, nothing deeper (M6). + + Every other store of the process nests under this one's prefix -- a named cache, every + agent's cache: ``:::``. A scan of ``:*`` + therefore found them all, so clearing the root cache emptied every agent's, and listing + it reported their storage names as namespaces. One segment too many marks a child's key, + and a last segment that is not this class's digest marks a key someone else wrote -- with + ``key_prefix = ""`` the scan covers the whole database. + """ key = redis_key if self._key_prefix: prefix = f"{self._key_prefix}:" if not key.startswith(prefix): - return None + return False key = key[len(prefix) :] - parts = key.split(":", 1) - return parts[0] if len(parts) >= 2 else None + parts = key.split(":") + return len(parts) == 2 and _DIGEST.fullmatch(parts[1]) is not None def get(self, key: str | list[str] | dict[str, Any], namespace: str = "default") -> Any | None: try: @@ -192,14 +211,23 @@ def exists(self, key: str | list[str] | dict[str, Any], namespace: str = "defaul def clear(self, namespace: str | None = None) -> None: try: + if not namespace and not self._key_prefix: + logger.warning( + "Clearing a Redis cache with no key_prefix: its keys share the database with whatever else uses it. " + "Only keys of this store's own form are deleted; set 'cache.key_prefix' to give the process a space " + "of its own." + ) pattern = self._namespace_scan_pattern(namespace) if namespace else self._all_scan_pattern() cursor = 0 deleted_count = 0 while True: cursor, keys = self._client.scan(cursor=cursor, match=pattern, count=500) - if keys: - self._client.delete(*keys) - deleted_count += len(keys) + # Only this store's keys: the pattern also matches every store nested under this + # one's prefix -- every named and every agent cache (M6). + own = [key for key in keys if self._owns(key)] + if own: + self._client.delete(*own) + deleted_count += len(own) if cursor == 0: break if namespace: @@ -256,6 +284,8 @@ def list_values(self, namespace: str = "default", limit: int = 100, offset: int while True: cursor, batch = self._client.scan(cursor=cursor, match=pattern, count=500) for key in batch: + if not self._owns(key): + continue # a nested store's key whose storage name equals this namespace if skipped < offset: skipped += 1 continue diff --git a/tests/integration/test_shared_redis_cache.py b/tests/integration/test_shared_redis_cache.py index 527879cf..523ad041 100644 --- a/tests/integration/test_shared_redis_cache.py +++ b/tests/integration/test_shared_redis_cache.py @@ -10,6 +10,7 @@ """ import json +import os import subprocess import sys import textwrap @@ -19,7 +20,8 @@ from .conftest import COMPOSE_HINT -REDIS_URL = "redis://localhost:6379/0" +REDIS_URL = os.environ.get("BLUEPRINT_TEST_REDIS_URL", "redis://localhost:6379/0") +"""The shared Redis (``redis`` in docker-compose.yml); overridden like ``BLUEPRINT_TEST_NATS_URL``.""" KEY_PREFIX = "pytest_shared_cache" IMPORT_BUDGET_SECONDS = 60 @@ -38,7 +40,7 @@ def redis_url() -> str: client.ping() client.close() except Exception: - pytest.skip("Redis is not available at localhost:6379. Start it with: " + COMPOSE_HINT) + pytest.skip(f"Redis is not available at {REDIS_URL}. Start it with: " + COMPOSE_HINT) return REDIS_URL diff --git a/tests/unit/agents/services/TESTS.md b/tests/unit/agents/services/TESTS.md index 8fe5a5e7..f3ac9844 100644 --- a/tests/unit/agents/services/TESTS.md +++ b/tests/unit/agents/services/TESTS.md @@ -11,7 +11,7 @@ Test coverage for `src/blueprint/agents/services/`. | `eventing/test_event_processing_service.py` | `EventProcessingService` | `_extract_handler_results` (None/HandlerResult/list/dict variants), `_build_result` (message text incl. `Skipped: `, request_id, result list), a skipped run reported as `SKIPPED` and publishing nothing, a list mixing a skip with a real result reported as `PROCESSED` and publishing only the real one, `_unwrap_dapr_event` (passthrough / CloudEvent inner / dict inner / missing type / unexpected type), lifecycle no-ops, `process_rest_request` delegates to `process_event` with correct event shape; the dedup bracket with a real chain and disk cache: a run cut off by `asyncio.timeout`, a run that swallows the cancellation and a return value failing after dispatch all give the marker back (B1, M11), an acknowledged delivery keeps it; an inner Dapr event without `type`, or one failing validation, raises an error that names the field but carries no value, logs nothing itself, and has no pydantic cause in its traceback (B2) | | `eventing/test_event_publishing_service.py` | `EventPublishingService` | `on_startup` wires client and config, `_get_pub_config` raises before startup, `get_topic_for_event_type` / `get_available_event_types`, `publish_event` (topic mapping, explicit topic override, missing mapping raises, sets default source, result shape), `publish_handler_event` (no mapping → skip, loop prevention → skip, normal → publishes), `publish_status_event` type format and delegation | | `infrastructure/test_disk_cache_service.py` | `DiskCacheService` | `set`/`get` (string/dict/list keys, namespace isolation), `delete` (return values), `exists` (before/after set/delete), `clear` (namespace-scoped and full), TTL expiration via mocked `time.time`, `hash` consistency for string/list/dict inputs, `list_namespaces`, `list_values` (content, TTL-entry exclusion, limit), `get_stats` field presence, lifecycle, context-manager protocol, an unwritable cache directory failing with a message that names the path and the options (and keeping the OSError as the cause); `claim` set-if-absent (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, keys and namespaces independent, dict keys hashed consistently, TTL recorded so readers see expiry, a logically expired claim taken over, no TTL never expires, and an unreachable cache failing open) | -| `infrastructure/test_redis_cache_service.py` | `RedisCacheService` | Backed by `fakeredis`. `claim` via `SET NX EX` (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, the TTL is applied to the key, namespaces are independent, and an unreachable cache fails open). *The rest of this file's coverage predates this table and is not itemised here.* | +| `infrastructure/test_redis_cache_service.py` | `RedisCacheService` | Backed by `fakeredis`. `claim` via `SET NX EX` (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, the TTL is applied to the key, namespaces are independent, and an unreachable cache fails open); the default store leaves nested stores alone -- clear, a namespace clear, list_namespaces -- and without a prefix deletes only its own keys and warns (M6). *The rest of this file's coverage predates this table and is not itemised here.* | | `infrastructure/test_cache_backend_factory.py`, `infrastructure/test_cache_sharing_via_registry.py`, `infrastructure/test_redis_url_utils.py` | `CacheBackendFactory`, registry cache sharing, Redis URL helpers | Present but not itemised in this table. | | `sessions/test_api_client.py` | `SessionsApiClient` | `on_startup` (valid config, missing config/base_url/api_key → ValueError), `on_shutdown` (closes client, no-op when uninitialised), `get_job_detail`/`start_job`/`complete_job`/`cancel_job` (URL shape, required headers, payload contents, uninitialised guard) | | `sessions/test_key_provider.py` | `SessionKeyProvider` | `on_startup` (initialises cache, reads source/env_var from config, missing config → ValueError), `on_shutdown` (clears cache, no-op when uninitialised), `get_session_key` (env hit/miss, config source, vault → NotImplementedError, remote source via respx — happy path/caching/404/missing session_id/missing URL, unknown source, cache-hit bypass, result cached after fetch), `invalidate_cache` (default and per-session key removal, no-op when empty/uninitialised) | diff --git a/tests/unit/agents/services/infrastructure/test_redis_cache_service.py b/tests/unit/agents/services/infrastructure/test_redis_cache_service.py index bea523db..4d061f23 100644 --- a/tests/unit/agents/services/infrastructure/test_redis_cache_service.py +++ b/tests/unit/agents/services/infrastructure/test_redis_cache_service.py @@ -365,3 +365,73 @@ def test_namespace_isolates_claims(self, redis_cache_service: RedisCacheService) def test_an_unreachable_cache_fails_open(self, redis_cache_service: RedisCacheService) -> None: with patch.object(redis_cache_service._client, "set", side_effect=ConnectionError("redis gone")): assert redis_cache_service.claim("slot", 1) is True + + +def _store(client: "fakeredis.FakeRedis", prefix: str) -> RedisCacheService: + """A store on a shared fake Redis, as the factory builds them: one per cache, nested by prefix.""" + svc = RedisCacheService.__new__(RedisCacheService) + svc._client = client + svc._key_prefix = prefix + svc._default_ttl = None + svc._fallback_to_local = False + svc._redis_url = "redis://fake:6379/0" + svc._safe_redis_url = "redis://fake:6379/0" + svc._password = None + svc._db = 0 + svc._tls = False + return svc + + +class TestTheRootStoreLeavesNestedStoresAlone: + """M6 -- every named and agent cache nests under the root store's prefix, so its scans found them all.""" + + @pytest.fixture + def stores(self, mock_registry, mock_config) -> Generator[tuple[RedisCacheService, RedisCacheService, "fakeredis.FakeRedis"]]: + client = fakeredis.FakeRedis(decode_responses=True) + root, orders = _store(client, "app"), _store(client, "app:orders.default") + root.set("k", "root-value") + orders.set("k", "orders-value") + orders.set("k", "orders-session", namespace="sessions") + yield root, orders, client + client.close() + + def test_clearing_the_root_keeps_an_agents_cache(self, stores) -> None: + root, orders, _ = stores + root.clear() + assert root.get("k") is None + assert orders.get("k") == "orders-value" + assert orders.get("k", namespace="sessions") == "orders-session" + + def test_clearing_a_root_namespace_keeps_a_store_of_that_name(self, stores) -> None: + """A root cache named 'sessions' and the root store's namespace 'sessions' share a scan pattern.""" + root, _, client = stores + sessions = _store(client, "app:sessions") + sessions.set("k", "named-cache") + root.set("k", "root-session", namespace="sessions") + + root.clear(namespace="sessions") + + assert sessions.get("k") == "named-cache" + assert root.get("k", namespace="sessions") is None + + def test_the_roots_namespaces_are_its_own(self, stores) -> None: + root, orders, _ = stores + assert root.list_namespaces() == ["default"] + assert orders.list_namespaces() == ["default", "sessions"] + + def test_without_a_prefix_only_this_stores_keys_are_cleared(self, mock_registry, mock_config, caplog: pytest.LogCaptureFixture) -> None: + """key_prefix = "" scans the whole database: other users' keys must survive, and the clear warns.""" + client = fakeredis.FakeRedis(decode_responses=True) + root = _store(client, "") + root.set("k", "root-value") + client.set("someone:else", "theirs") + client.set("orders.default:default:" + "a" * 64, "nested") + + with caplog.at_level("WARNING"): + root.clear() + + assert client.get("someone:else") == "theirs" + assert client.get("orders.default:default:" + "a" * 64) == "nested" + assert root.get("k") is None + assert "no key_prefix" in caplog.text + client.close() From a7a3c1db5631f49ef1ba4cd9f0d35b939a1a1512 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:14:58 +0200 Subject: [PATCH 114/133] fix(actuator): /status/env masking fails closed Step 13 (M12): userinfo, secret query parameters, Name=value; segments, sections under secret keys. Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 7 ++ ...26-08-28-multi-agent-grouping-changelog.md | 5 + .../agent_generator/docs/guides/deployment.md | 6 +- .../agents/io/api/actuators/actuator_api.py | 103 ++++++++++++++---- tests/unit/agents/io/TESTS.md | 2 +- .../io/api/actuators/test_actuator_api.py | 45 ++++++++ 6 files changed, 147 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3549216c..31f9d50e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,13 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **`/status/env` no longer leaks what its masking missed, and no longer fails on `${PORT}`.** A URL + password holding `/`, `?` or `#` was partly returned, a token in a query string, an `AccountKey=` in + a connection string and every value of a section under a secret-named key (`credentials`) were + returned in clear, and keys such as `sentry_dsn` or `db_pass` were not recognised; a URL with a + non-numeric port answered 500. Measured over HTTP: seven placeholder secrets in the response + before, none now; status 200 with `${PORT}` (before: 500). + - **Clearing the root Redis cache no longer clears every agent's.** Every named and agent cache nests under the default store's key prefix, and its `clear()` deleted everything under it -- with `key_prefix = ""`, the whole database. Its `list_namespaces()` listed the nested stores as its own diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 2ac44251..102a9f41 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,11 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 13, `/status/env` masker (M12): URL userinfo fails closed (an `@` left after `://`, an + unparseable port), secret query parameters and `Name=value;` segments are masked, a section under a + secret key is masked whole, `pass`/`dsn`/`conn`/`sig`/`signature` count as whole words. Live (a built + app under uvicorn, `GET /status/env`): 200 and no placeholder in the body; control: 500 with + `${PORT}`, and without it seven placeholders returned. - Step 12, Redis cache isolation (M6): the default store's `clear`, `list_namespaces` and `list_values` take only keys of its own form (`::`); a clear without `key_prefix` warns; no key-layout change. Live (Redis 7 in WSL, stores from `CacheBackendFactory` for root, `orders`, diff --git a/src/blueprint/agent_generator/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md index 7d39f803..105cf2bd 100644 --- a/src/blueprint/agent_generator/docs/guides/deployment.md +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -526,7 +526,11 @@ probe, Kubernetes would restart every agent in the group, reintroducing exactly grouping was paid to remove. Also served, and useful when debugging rather than as probes: `GET /info`, `/status/env`, -`/status/llm`, `/status/build`. There is no `/health/detailed`. +`/status/llm`, `/status/build`. There is no `/health/detailed`. `/status/env` masks every key that +names a secret (`key`, `token`, `password`, `secret`, ... and `pass`, `dsn`, `conn` as words) together +with any section under it, a URL's userinfo, secret query parameters (`token=`, `sig=`) and +`Name=value` segments of connection strings (`AccountKey=`); a URL whose userinfo cannot be told +from the rest is masked whole. Treat it as an operator endpoint all the same. ### `readiness_policy` diff --git a/src/blueprint/agents/io/api/actuators/actuator_api.py b/src/blueprint/agents/io/api/actuators/actuator_api.py index 75f78391..757b9917 100644 --- a/src/blueprint/agents/io/api/actuators/actuator_api.py +++ b/src/blueprint/agents/io/api/actuators/actuator_api.py @@ -3,11 +3,12 @@ import logging import os import platform +import re from collections.abc import Sequence from importlib import metadata from importlib.metadata import PackageNotFoundError from typing import Any -from urllib.parse import urlsplit, urlunsplit +from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit import httpx from fastapi import HTTPException, status @@ -40,6 +41,14 @@ publishes a credential to anything that can reach the actuator. """ +SECRET_KEY_WORDS = frozenset({"pass", "dsn", "conn", "sig", "signature"}) +"""Words that mark a key only as a whole ``_``/``.``/``-``-delimited word (M12). + +As substrings they would mask half the configuration -- ``passthrough_mode``, +``connection_timeout`` -- so they count only where they stand alone: ``db_pass``, +``sentry_dsn``, ``db_conn``, a query string's ``sig``. +""" + CONFIG_MASK = "***" """What a masked value is replaced with. Presence stays visible; the value does not.""" @@ -328,9 +337,7 @@ async def llm_status(self) -> LLMStatus: ai_config_dict = ( ai_config_model.model_dump() if hasattr(ai_config_model, "model_dump") - else ai_config_model.dict() - if hasattr(ai_config_model, "dict") - else {} + else ai_config_model.dict() if hasattr(ai_config_model, "dict") else {} ) ai_config = self._sanitize_config(ai_config_dict) @@ -405,12 +412,17 @@ def _sanitize_config(self, data: dict[str, Any]) -> dict[str, Any]: This endpoint publishes configuration over HTTP, so the bias is towards masking: a false positive loses a line of diagnostics, a false negative publishes a secret. - Three rules, in order: - - 1. A key containing any of :data:`SECRET_KEY_MARKERS` is masked, whatever its value. - 2. A string value that parses as a URL carrying userinfo has that userinfo stripped, - whatever its key -- ``redis://user:pass@host`` under a key called ``nats_url`` - names nothing sensitive but carries a password. + The rules, in order: + + 1. A key containing any of :data:`SECRET_KEY_MARKERS`, or one of + :data:`SECRET_KEY_WORDS` as a whole word, is masked, whatever its value -- a section + or a list under it included, whole (M12: ``credentials = {user, value}`` named + nothing below it and came back in clear). + 2. A string value is cleaned whatever its key: a URL loses its userinfo, failing + closed -- the whole value masked -- when the userinfo cannot be told from the rest + (a password containing ``/``, ``?`` or ``#``) or the URL does not parse; a query + parameter or a ``Name=value;`` segment with a secret name loses its value + (``?token=``, ``&sig=``, ``AccountKey=``). 3. Booleans pass through even under a matching key. A flag cannot carry a credential, and ``auth_enabled`` is exactly the kind of value someone reads this endpoint for. @@ -421,23 +433,69 @@ def _sanitize_config(self, data: dict[str, Any]) -> dict[str, Any]: def _sanitize_value(self, key: str, value: Any) -> Any: """Apply the rules in :meth:`_sanitize_config` to one key/value pair.""" + if isinstance(value, bool): + return value if isinstance(value, dict): - return self._sanitize_config(value) + return CONFIG_MASK if self._is_secret_key(key) and value else self._sanitize_config(value) if isinstance(value, (list, tuple)): + if self._is_secret_key(key) and any(isinstance(item, (dict, list, tuple)) for item in value): + return CONFIG_MASK return [self._sanitize_value(key, item) for item in value] - if isinstance(value, bool): - return value if self._is_secret_key(key): return CONFIG_MASK if isinstance(value, str): - return self._strip_url_userinfo(value) + return self._sanitize_string(value) return value @staticmethod def _is_secret_key(key: str) -> bool: """Return whether a configuration key may carry a credential.""" lowered = key.lower() - return any(marker in lowered for marker in SECRET_KEY_MARKERS) + if any(marker in lowered for marker in SECRET_KEY_MARKERS): + return True + return any(word in SECRET_KEY_WORDS for word in re.split(r"[_.\-]+", lowered)) + + def _sanitize_string(self, value: str) -> str: + """Clean one string value: URL userinfo, secret query parameters, secret ``Name=value;`` segments.""" + value = self._strip_url_userinfo(value) + if value == CONFIG_MASK: + return value + value = self._mask_secret_query(value) + return self._mask_secret_segments(value) + + def _mask_secret_query(self, value: str) -> str: + """Mask the value of each query parameter with a secret name (``?token=``, ``&sig=``).""" + if "://" not in value or "?" not in value: + return value + try: + parts = urlsplit(value) + except ValueError: + return CONFIG_MASK + if not parts.query: + return value + pairs = parse_qsl(parts.query, keep_blank_values=True) + if not any(self._is_secret_key(name) for name, _ in pairs): + return value + masked = [(name, CONFIG_MASK if self._is_secret_key(name) else item) for name, item in pairs] + query = urlencode(masked, safe="*") + return urlunsplit((parts.scheme, parts.netloc, parts.path, query, parts.fragment)) + + def _mask_secret_segments(self, value: str) -> str: + """Mask the value of each ``Name=value`` segment with a secret name, in a ``;``-separated string. + + The shape of a connection string -- ``AccountName=x;AccountKey=...`` -- whose own key + (``storage``, ``connection``) names nothing a marker would catch. + """ + if "=" not in value or ";" not in value: + return value + segments = value.split(";") + changed = False + for index, segment in enumerate(segments): + name, sep, _ = segment.partition("=") + if sep and self._is_secret_key(name.strip()): + segments[index] = f"{name}={CONFIG_MASK}" + changed = True + return ";".join(segments) if changed else value @staticmethod def _strip_url_userinfo(value: str) -> str: @@ -449,19 +507,26 @@ def _strip_url_userinfo(value: str) -> str: returned unchanged -- most configuration values are not URLs, and replacing them with a placeholder would empty the endpoint. """ - if "@" not in value or "//" not in value: + scheme_end = value.find("://") + if scheme_end < 0 or "@" not in value[scheme_end + 3 :]: return value try: parts = urlsplit(value) + port = parts.port # raises for a non-numeric port, '${PORT}' among them (M12) except ValueError: return CONFIG_MASK if not parts.username and not parts.password: - return value + # An '@' after '://' that is not userinfo: a password holding '/', '?' or '#' ends + # the authority early, and the rest of it sits in the path, query or fragment. + return CONFIG_MASK host = parts.hostname or "" if ":" in host: host = f"[{host}]" - netloc = f"{host}:{parts.port}" if parts.port is not None else host - return urlunsplit((parts.scheme, netloc, parts.path, parts.query, parts.fragment)) + netloc = f"{host}:{port}" if port is not None else host + stripped = urlunsplit((parts.scheme, netloc, parts.path, parts.query, parts.fragment)) + # Fail closed (M12): an '@' left after '://' means the userinfo did not end where the + # parser thought, and part of a password is still in the value. + return CONFIG_MASK if "@" in stripped[scheme_end + 3 :] else stripped def _ensure_config(self) -> Config: if not self.config: diff --git a/tests/unit/agents/io/TESTS.md b/tests/unit/agents/io/TESTS.md index b3a958bf..c768341b 100644 --- a/tests/unit/agents/io/TESTS.md +++ b/tests/unit/agents/io/TESTS.md @@ -9,7 +9,7 @@ Test coverage for `src/blueprint/agents/io/`. | File | Class under test | What is covered | |---|---|---| | `api/test_rest_api_base.py` | `RestApiBase` | HTTP verb decorators attach `_route`, `_wire_routes` registers routes, `_build_problem_details` RFC 7807 fields, `_resolve_status_title`, a skipped run answers a REST caller with `success=True`, the skip reason as message and no data | -| `api/actuators/test_actuator_api.py` | `ActuatorApi` | `_sanitize_config` (flat + nested), `liveness_probe` always UP, `on_startup`/`on_shutdown` lifecycle, `env_status` per-namespace breakdown and masking, reported `envvar_prefix`, one audited tree read per request | +| `api/actuators/test_actuator_api.py` | `ActuatorApi` | `_sanitize_config` (flat + nested), `liveness_probe` always UP, `on_startup`/`on_shutdown` lifecycle, `env_status` per-namespace breakdown and masking, reported `envvar_prefix`, one audited tree read per request; the masker fails closed on a URL password with `/`, `?` or `#` and on a non-numeric port, masks secret query parameters and `Name=value;` segments and a whole section under a secret key, and takes `pass`/`dsn`/`conn` as whole words only (M12) | | `api/actuators/health/test_client_health.py` | `ClientHealthChecker` | `connect()` called before `health_check()`, healthy/unhealthy/mixed aggregation, empty client list | | `api/actuators/health/test_health_cache.py` | `HealthCheckCache` | Initial state, provider updates, all-healthy→UP, one-unhealthy→DOWN, exception→unhealthy component, `get_cache_age_seconds`, `get_cache_info`, start/stop idempotency | | `api/actuators/health/test_sessions_health.py` | `SessionsServiceHealthChecker` | REST API reachable→UP, `RequestError`→DOWN with details, fresh heartbeat→UP, stale heartbeat→DOWN, no heartbeat→UP (unknown), `update_heartbeat` | diff --git a/tests/unit/agents/io/api/actuators/test_actuator_api.py b/tests/unit/agents/io/api/actuators/test_actuator_api.py index 4a9167da..ca50590c 100644 --- a/tests/unit/agents/io/api/actuators/test_actuator_api.py +++ b/tests/unit/agents/io/api/actuators/test_actuator_api.py @@ -109,6 +109,51 @@ def test_booleans_pass_through_even_under_a_matching_key(self, actuator_api: Act def test_a_plain_string_that_merely_contains_an_at_sign_is_untouched(self, actuator_api: ActuatorApi) -> None: assert actuator_api._sanitize_config({"contact": "team@example.com"})["contact"] == "team@example.com" + @pytest.mark.parametrize( + "url", + [ + "redis://admin:p@ss/word@cache.internal:6379/0", + "redis://admin:pa#ss@cache.internal:6379/0", + "redis://admin:pa?ss@cache.internal:6379/0", + ], + ) + def test_a_password_with_a_url_delimiter_is_not_leaked(self, actuator_api: ActuatorApi, url: str) -> None: + """M12 -- urlsplit ends the authority at '/', '?' or '#', so the rest of the password stayed in the value.""" + result = actuator_api._sanitize_config({"redis_url": url})["redis_url"] + assert not any(part in result for part in ("ss/word", "pa#ss", "pa?ss", "word@", "#ss", "?ss")) + + def test_a_port_placeholder_does_not_fail_the_endpoint(self, actuator_api: ActuatorApi) -> None: + """M12 -- parts.port raised for 'redis://u:pw@host:${PORT}', which answered 500.""" + result = actuator_api._sanitize_config({"redis_url": "redis://u:PLACEHOLDER@host:${PORT}/0"})["redis_url"] + assert "PLACEHOLDER" not in result + + def test_a_token_in_the_query_string_is_masked(self, actuator_api: ActuatorApi) -> None: + result = actuator_api._sanitize_config({"webhook_url": "https://hooks.example.com/x?token=PLACEHOLDER&channel=ops"}) + assert result["webhook_url"] == "https://hooks.example.com/x?token=***&channel=ops" + + def test_a_signature_in_the_query_string_is_masked(self, actuator_api: ActuatorApi) -> None: + url = "https://acct.blob.core.windows.net/c?sv=2024-01-01&sig=PLACEHOLDER" + assert "PLACEHOLDER" not in actuator_api._sanitize_config({"blob_url": url})["blob_url"] + + def test_a_key_segment_of_a_connection_string_is_masked(self, actuator_api: ActuatorApi) -> None: + """M12 -- 'AccountKey=' in a value whose own key names nothing sensitive.""" + value = "DefaultEndpointsProtocol=https;AccountName=acct;AccountKey=PLACEHOLDER;EndpointSuffix=core.windows.net" + result = actuator_api._sanitize_config({"storage": value})["storage"] + assert result == "DefaultEndpointsProtocol=https;AccountName=acct;AccountKey=***;EndpointSuffix=core.windows.net" + + def test_a_section_under_a_secret_key_is_masked_whole(self, actuator_api: ActuatorApi) -> None: + """M12 -- its own keys ('value', 'user') named nothing, so it came back in clear.""" + result = actuator_api._sanitize_config({"credentials": {"user": "svc", "value": "PLACEHOLDER"}}) + assert result["credentials"] == "***" + + @pytest.mark.parametrize("key", ["db_pass", "sentry_dsn", "db_conn", "postgres_dsn"]) + def test_pass_dsn_and_conn_as_words_are_markers(self, actuator_api: ActuatorApi, key: str) -> None: + assert actuator_api._sanitize_config({key: "PLACEHOLDER"})[key] == "***" + + @pytest.mark.parametrize("key", ["passthrough_mode", "connection_timeout", "bypass_cache"]) + def test_those_words_inside_others_are_not(self, actuator_api: ActuatorApi, key: str) -> None: + assert actuator_api._sanitize_config({key: "visible"})[key] == "visible" + # --------------------------------------------------------------------------- # liveness_probe From b4abbbe8ee7e1b5417810ea1d3aec1e30a45fd6e Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:14:59 +0200 Subject: [PATCH 115/133] fix(scaffold): select production, Python healthcheck, CLI messages and name checks Step 14 (M10, S14, N6-N9, D10). Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 9 +++ ...26-08-28-multi-agent-grouping-changelog.md | 9 +++ .../agent_generator/base_files/Dockerfile | 10 ++- .../base_files/group_Dockerfile | 11 +++- .../agent_generator/base_files/settings.txt | 2 +- .../base_files/src/services/service.txt | 1 - .../agent_generator/cli/commands/create.py | 16 +++-- .../agent_generator/cli/commands/dev.py | 18 +++--- .../agent_generator/cli/commands/setup.py | 14 +++-- .../cli/commands/validate_group.py | 6 +- src/blueprint/agent_generator/cli/main.py | 4 +- .../agent_generator/docs/guides/cli/dev.md | 16 ++--- .../agent_generator/docs/guides/cli/setup.md | 2 +- .../docs/guides/cli/validate.md | 2 +- .../agent_generator/docs/guides/deployment.md | 12 +++- .../docs/guides/multi-agent-setup.md | 4 +- .../pyproject_part_generator.py | 4 +- .../part_generators/service_part_generator.py | 7 +++ .../cli/commands/test_create_agent.py | 20 ++++++ .../generator/test_generated_project.py | 62 ++++++++++++++++++- 20 files changed, 180 insertions(+), 49 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 31f9d50e..a266d548 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,15 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **Scaffolded images select the production environment, and the group image turns healthy.** The + generated Dockerfiles set `DYNACONF_ENVIRONMENT`, which selects nothing, so every image ran the + `development` section; they now set `DYNACONF_APP_ENVIRONMENT` (`production`, and `development` in + the dev stage). **Existing projects: rename the variable in your Dockerfile** -- the image then + loads `[production]`, with no localhost broker fallback. The group image's health check used `curl`, + which its slim base does not have, and is now a Python one. `asbs setup` checks the agent's name + before writing anything, `asbs create service` writes a service that imports, and the messages + about what `asbs dev` serves without `--name` (the agent alone, at the root namespace) are correct. + - **`/status/env` no longer leaks what its masking missed, and no longer fails on `${PORT}`.** A URL password holding `/`, `?` or `#` was partly returned, a token in a query string, an `AccountKey=` in a connection string and every value of a section under a secret-named key (`credentials`) were diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 102a9f41..f539530a 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,15 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 14, scaffold and CLI (M10, S14, N6-N9, D10): `DYNACONF_APP_ENVIRONMENT` in both Dockerfiles + (production, development in the dev stage), a Python health check in `group_Dockerfile`, `asbs setup` + validates the name before writing, the `settings.txt` comment no longer carries the substituted token, + `asbs create service` imports what it names, `AgentRuntime` only where agents are used, the scheduler + template no longer claims a generated CronJob, and every `asbs dev` message says that without `--name` + the agent is served alone at the root. Live (WSL): a scaffolded two-agent group image built from the + working tree turned healthy in 10 s and loaded `production`; control with the old template: `curl: not + found`, never healthy, `development`. In the same image: `BLUEPRINT_CRITICAL_AGENTS=ordrs` exits 1 + naming the typo (step 7), and a `.secrets.toml` mounted for `orders` reaches `orders` only (step 8). - Step 13, `/status/env` masker (M12): URL userinfo fails closed (an `@` left after `://`, an unparseable port), secret query parameters and `Name=value;` segments are masked, a section under a secret key is masked whole, `pass`/`dsn`/`conn`/`sig`/`signature` count as whole words. Live (a built diff --git a/src/blueprint/agent_generator/base_files/Dockerfile b/src/blueprint/agent_generator/base_files/Dockerfile index 9f32a2ed..a09c3979 100644 --- a/src/blueprint/agent_generator/base_files/Dockerfile +++ b/src/blueprint/agent_generator/base_files/Dockerfile @@ -31,7 +31,10 @@ FROM builder AS dev RUN uv pip install --system --no-cache ".[dev]" ipython debugpy pytest ENV PYTHONPATH="/app/src" -ENV DYNACONF_ENVIRONMENT="development" +# app_environment selects the settings section, and it defaults to development. The variable is +# DYNACONF_APP_ENVIRONMENT -- DYNACONF_ENVIRONMENT selects nothing -- and a project that sets its own +# envvar_prefix renames it to _APP_ENVIRONMENT. +ENV DYNACONF_APP_ENVIRONMENT="development" # src/main.py declares an agent; it does not build one, so there is no `src.main:app` to # serve. create_app() builds the declaration with this directory's settings, and uvicorn @@ -92,8 +95,11 @@ RUN mkdir -p /app/.cache && chown -R appuser:appuser /app/.cache # An individual key can also be supplied as an environment variable instead, with no file at # all: -e DYNACONF_MODEL_API_KEY=... +# app_environment selects the settings section, and it defaults to development. The variable is +# DYNACONF_APP_ENVIRONMENT -- DYNACONF_ENVIRONMENT selects nothing -- and a project that sets its own +# envvar_prefix renames it to _APP_ENVIRONMENT. ENV PYTHONPATH="/app/src" \ - DYNACONF_ENVIRONMENT="production" \ + DYNACONF_APP_ENVIRONMENT="production" \ PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 diff --git a/src/blueprint/agent_generator/base_files/group_Dockerfile b/src/blueprint/agent_generator/base_files/group_Dockerfile index bf98a12d..ce74c905 100644 --- a/src/blueprint/agent_generator/base_files/group_Dockerfile +++ b/src/blueprint/agent_generator/base_files/group_Dockerfile @@ -52,12 +52,21 @@ COPY --chown=appuser:appuser agents.toml ./ # root-owned, so mkdir() as appuser fails with EACCES. Created and handed over at build time. RUN mkdir -p /app/.cache && chown -R appuser:appuser /app/.cache +# app_environment selects the settings section, and it defaults to development. The variable is +# DYNACONF_APP_ENVIRONMENT -- DYNACONF_ENVIRONMENT selects nothing -- and a project that sets its own +# envvar_prefix renames it to _APP_ENVIRONMENT. +ENV DYNACONF_APP_ENVIRONMENT="production" \ + PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 + USER appuser EXPOSE 8000 +# Python, not curl: the slim base image has no curl, so a curl check failed for ever and the +# container never turned healthy. HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ - CMD curl -f http://localhost:8000/health/live || exit 1 + CMD ["python", "-c", "import sys, urllib.request; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/health/live', timeout=4).status == 200 else 1)"] # Which agents this process runs is the deployment's to say: # diff --git a/src/blueprint/agent_generator/base_files/settings.txt b/src/blueprint/agent_generator/base_files/settings.txt index 28008ef5..c8be7e0b 100644 --- a/src/blueprint/agent_generator/base_files/settings.txt +++ b/src/blueprint/agent_generator/base_files/settings.txt @@ -17,7 +17,7 @@ model_base_url = "https://YOUR_VLLM_HOST/v1" # Required as soon as a scheduler is registered -- it has no default, because neither # value is safe to inherit, and this template does not choose for you. "event" starts no # in-process timer: the tick arrives as an event on .scheduler. -# (.scheduler. when the agent is served on its own), published +# (the application's name instead of the agent when it is served on its own), published # by an external CronJob, so exactly one replica runs it -- and it needs event_bus set. # "in_process" runs an APScheduler timer in the process and claims each tick in the cache # so one replica runs it; it is right for local development and plain Docker, and it diff --git a/src/blueprint/agent_generator/base_files/src/services/service.txt b/src/blueprint/agent_generator/base_files/src/services/service.txt index 84f995f6..03d0afd8 100644 --- a/src/blueprint/agent_generator/base_files/src/services/service.txt +++ b/src/blueprint/agent_generator/base_files/src/services/service.txt @@ -4,7 +4,6 @@ service_description import logging -from blueprint.agents.agent import AgentRuntime from blueprint.agents.services import ServiceBase imports diff --git a/src/blueprint/agent_generator/cli/commands/create.py b/src/blueprint/agent_generator/cli/commands/create.py index 841c0fd7..c8e51a07 100644 --- a/src/blueprint/agent_generator/cli/commands/create.py +++ b/src/blueprint/agent_generator/cli/commands/create.py @@ -194,10 +194,13 @@ def create_service(args: Namespace) -> None: "description": f"Service for {snake_name} operations", "uses_domain_models": [], "uses_agents": [], + # Types the generated file can import (N9): InputData and OutputData were + # named and defined nowhere, so the new service did not import. + "type_imports": "from pydantic import BaseModel", "process_function": { "name": "process", - "input_type": "InputData", - "output_type": "OutputData", + "input_type": "BaseModel", + "output_type": "BaseModel", }, } }, @@ -717,10 +720,11 @@ def __init__(self) -> None: The crontab is declared here in both scheduler modes, and 'scheduler_mode' in settings.toml decides what calls tick(). It is required and has no default: with 'event' nothing in this process keeps time -- the tick arrives as an event on this - scheduler's own topic, published by an external CronJob generated from this - declaration, and 'event_bus' has to be set. With 'in_process' an APScheduler timer - runs here, which is right for local development and un-orchestrated Docker but - fires once per replica. + scheduler's own topic, published by an external CronJob that the deployment provides + (nothing in this project generates it), and 'event_bus' has to be set. With + 'in_process' an APScheduler timer runs here, which is right for local development and + un-orchestrated Docker; with a cache each tick is claimed so one replica runs it. + Write days of the week as names ('mon-fri'): 0 is Monday here and Sunday to cron. """ super().__init__(crontab="{args.cron}") diff --git a/src/blueprint/agent_generator/cli/commands/dev.py b/src/blueprint/agent_generator/cli/commands/dev.py index 31a85f6e..189aa870 100644 --- a/src/blueprint/agent_generator/cli/commands/dev.py +++ b/src/blueprint/agent_generator/cli/commands/dev.py @@ -32,11 +32,11 @@ def run(args: Namespace) -> None: """Execute the dev command. - Runs the project the way the deployment does, under the agents' **real** namespaces. A - development server at the root namespace would serve ``/api/orders/{id}`` where production - serves ``/api/order/orders/{id}`` and would consume under a different queue group, so every - local URL and every local integration test would differ from the deployed one in a way - nothing reports. + In an image directory (an ``agents.toml`` here) it hosts that image's agents under their real + namespaces, as the deployment does. In an agent directory it serves the agent **on its own, at + the root namespace** -- as its own Dockerfile does -- unless ``--name`` asks for the namespace a + group image would give it, which is the shape whose routes (``/api//...``) and consumer + identity match a grouped deployment. Args: args: Parsed command-line arguments @@ -182,9 +182,9 @@ def _declares(entry_point: Path, name: str) -> bool: def _dev_agent_name(args: Namespace) -> str: """Return the name this agent runs under while developing. - ``--name``, or the directory's own name. The agent itself does not carry one: the name is - its identity on the broker, in telemetry and in its routes, and who supplies it depends on - who is hosting it -- a group image's map, a single-agent image's Dockerfile, or this. + ``--name`` -- only asked for when it was given; without it the agent is served at the root. + The agent itself does not carry a name: it is its identity on the broker, in telemetry and in + its routes, and who supplies it depends on who is hosting it -- a group image's map, or this. Raises: SystemExit: if neither yields a legal namespace, because a repaired name would be a @@ -215,6 +215,6 @@ def _temporary_agent_map(args: Namespace) -> Path: os.environ[AGENT_MAP_ENV] = str(path) atexit.register(lambda: path.unlink(missing_ok=True)) print(f"No {AGENT_MAP_FILE} here, which is how an agent directory should look.") - print(f"Serving it as '{name}' (from {'--name' if getattr(args, 'name', '') else 'the directory name'}).") + print(f"Serving it as '{name}' (from --name).") print(f"Its routes are under /api/{name}.") return path diff --git a/src/blueprint/agent_generator/cli/commands/setup.py b/src/blueprint/agent_generator/cli/commands/setup.py index fd85e2db..016a85a6 100644 --- a/src/blueprint/agent_generator/cli/commands/setup.py +++ b/src/blueprint/agent_generator/cli/commands/setup.py @@ -152,12 +152,19 @@ def run(args: Namespace) -> None: print("Use --overwrite to write over it", file=sys.stderr) sys.exit(1) + # The name is checked before anything is written (N7): it was checked after generate(), + # so a name that cannot be a namespace left a whole project behind with the error. + config = create_basic_config(project_name) + try: + namespace = PartGeneratorBase.agent_namespace(config) + except ValueError as exc: + print(f"Error: {exc}", file=sys.stderr) + sys.exit(1) + print(f"\nScaffolding agent: {project_name}") print(f"Location: {output_dir}") try: - # Create basic configuration - config = create_basic_config(project_name) # Create a temporary config file for the generator with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False, encoding="utf-8") as f: @@ -186,7 +193,6 @@ def run(args: Namespace) -> None: print(" ├── Dockerfile") print(" └── .gitignore") - namespace = PartGeneratorBase.agent_namespace(config) print("\nNext steps:") print(" 1. Review and edit the generated files") print(" 2. Add your LLM API key to .secrets.toml") @@ -204,7 +210,7 @@ def run(args: Namespace) -> None: print("knows whether it is running alone. Whoever hosts it supplies the name:") print(" - its own Dockerfile serves it directly with uvicorn src.main:create_app --factory") print(" - a group image maps it in the repository's agents.toml, with root and module") - print(" - asbs dev uses this directory's name unless --name says otherwise") + print(" - asbs dev serves it on its own; asbs dev --name serves it under that name") print("\nThat name is the agent's identity on the broker, in telemetry and in its routes") print("(/api/) -- change it now if you are going to, because changing it after the") print("first deploy is a consumer migration.") diff --git a/src/blueprint/agent_generator/cli/commands/validate_group.py b/src/blueprint/agent_generator/cli/commands/validate_group.py index cf6c39cc..a2c1aa30 100644 --- a/src/blueprint/agent_generator/cli/commands/validate_group.py +++ b/src/blueprint/agent_generator/cli/commands/validate_group.py @@ -206,9 +206,9 @@ def _agent_findings(image_root: Path, name: str, entry: Any, claimed: dict[Path, if root != image_root and root.name != name: notices.append( - f"Agent '{name}' lives in a directory named '{root.name}'. Nothing breaks, but 'asbs dev' in that " - f"directory serves it as '{root.name}' unless --name says otherwise, so its routes differ between " - "development and this image." + f"Agent '{name}' lives in a directory named '{root.name}'. Nothing breaks; to develop it with the " + f"routes this image gives it, run 'asbs dev --name {name}' in that directory -- without --name it is " + "served on its own, at the root namespace." ) return issues, warnings, notices diff --git a/src/blueprint/agent_generator/cli/main.py b/src/blueprint/agent_generator/cli/main.py index 7e745c28..eb2309c5 100644 --- a/src/blueprint/agent_generator/cli/main.py +++ b/src/blueprint/agent_generator/cli/main.py @@ -200,8 +200,8 @@ def main() -> None: ) dev_parser.add_argument( "--name", - help="The name to serve a single agent under (default: this directory's name). An agent " - "directory carries no agent map, so the name comes from whoever hosts it.", + help="Serve a single agent under this name, as a group image would (default: served on its own, " + "at the root namespace). An agent directory carries no agent map, so the name comes from whoever hosts it.", ) dev_parser.add_argument( "--agents", diff --git a/src/blueprint/agent_generator/docs/guides/cli/dev.md b/src/blueprint/agent_generator/docs/guides/cli/dev.md index c39e2b7a..0845e519 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/dev.md +++ b/src/blueprint/agent_generator/docs/guides/cli/dev.md @@ -43,22 +43,22 @@ The development server watches for file changes in the `src/` directory and auto ## Running a single agent -An agent directory carries no `agents.toml`, so there is nothing there to name it. `asbs dev` -supplies the name instead -- from `--name`, or the directory's own name: +An agent directory carries no `agents.toml`, so there is nothing there to name it. Without +`--name`, `asbs dev` serves the agent on its own, at the root namespace, as its own Dockerfile +does; `--name` serves it under that name, as a group image would: ```bash cd agents/some_topic/my_agent -asbs dev # serves it as "my_agent" -asbs dev --name orders # serves it as "orders" +asbs dev # served on its own: routes under /api/... +asbs dev --name orders # served as "orders": routes under /api/orders/... ``` -The map it needs is written outside the project for that run and removed afterwards. Nothing is +With `--name`, the map it needs is written outside the project for that run and removed afterwards. Nothing is created in the agent's directory: an `agents.toml` left behind there is exactly the file an agent must not carry. -The name decides the route prefix, so `/api/my_agent/...` here and `/api//...` in a -group image. If they differ, development and production differ -- `asbs validate --group` says -so when a map key does not match its directory name. +The name decides the route prefix, so pass the agent's map key as `--name` to develop against the +routes of the group image (`/api//...`). Where an `agents.toml` *is* present -- an image's directory -- `asbs dev` hosts the agents it names, as before. diff --git a/src/blueprint/agent_generator/docs/guides/cli/setup.md b/src/blueprint/agent_generator/docs/guides/cli/setup.md index 36348827..5e00972c 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/setup.md +++ b/src/blueprint/agent_generator/docs/guides/cli/setup.md @@ -44,7 +44,7 @@ agent's namespace is that name in snake case (`order_processor`). There is no `agents.toml`. The agent map says which agents an *image* contains, which is a packaging decision -- an agent that carried one would be an agent that knows whether it is running alone. The generated `Dockerfile` writes a one-agent map into its own image; a group image maps it -in the repository's `agents.toml`; `asbs dev` supplies the name from the directory. `asbs validate +in the repository's `agents.toml`; `asbs dev --name` supplies it while developing. `asbs validate --group` refuses one found inside an agent. A `pyproject.toml` is written only if the directory has none: `asbs` runs from the project's own diff --git a/src/blueprint/agent_generator/docs/guides/cli/validate.md b/src/blueprint/agent_generator/docs/guides/cli/validate.md index 13b94053..d70e2d1c 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/validate.md +++ b/src/blueprint/agent_generator/docs/guides/cli/validate.md @@ -99,7 +99,7 @@ It checks, per agent: - which `settings.toml` each agent actually reads, printed, so "is it picking mine up?" is answerable without starting the process - process-wide keys left in an agent's settings, which are dropped before the merge -- whether the map key matches the directory name, since `asbs dev` defaults to the latter +- whether the map key matches the directory name, and the `asbs dev --name` that gives the image's routes Exit status is 1 when anything would stop the image starting, 0 otherwise. diff --git a/src/blueprint/agent_generator/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md index 105cf2bd..21d296de 100644 --- a/src/blueprint/agent_generator/docs/guides/deployment.md +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -48,14 +48,14 @@ COPY --chown=appuser:appuser agents.toml ./ RUN mkdir -p /app/.cache && chown -R appuser:appuser /app/.cache ENV PYTHONPATH="/app/src" \ - DYNACONF_ENVIRONMENT="production" \ + DYNACONF_APP_ENVIRONMENT="production" \ PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 USER appuser -HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ - CMD curl -f http://localhost:8000/health/live || exit 1 +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ + CMD ["python", "-c", "import sys, urllib.request; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/health/live', timeout=4).status == 200 else 1)"] EXPOSE 8000 @@ -74,6 +74,12 @@ Three things about it are load-bearing: this process's group, builds it and serves it. A project from before the split, whose `main.py` builds its own application, keeps `uvicorn src.main:app` and keeps working. - **`.secrets.toml` is never copied in.** Mount it, or supply the values as environment variables. +- **`app_environment` defaults to `development`, and a deployment sets `production` itself.** The + variable is `DYNACONF_APP_ENVIRONMENT` (`_APP_ENVIRONMENT` with a custom `envvar_prefix`); + `DYNACONF_ENVIRONMENT` selects nothing. Left at `development`, a process falls back to a localhost + broker when `nats_url` is unset, logs as in development and runs asyncio in debug mode. +- **The health check is Python, not `curl`:** the slim base image has no `curl`, so a `curl` check + fails for ever and the container never turns healthy. ### Building and running diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md index 82a9fd8c..c6349aac 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md @@ -77,7 +77,7 @@ Whoever hosts the agent supplies its name: |---|---| | Its own `Dockerfile` | a one-agent map written into the image, with `root = "."` | | A group image | an entry in the repository's `agents.toml` | -| `asbs dev` | `--name`, defaulting to the directory's name | +| `asbs dev` | `--name`; without it the agent is served on its own, at the root namespace | The generated `Dockerfile` runs `uvicorn src.main:create_app --factory`: one agent, served directly, with no map and no group involved. A group image runs `python -m blueprint.agents.entrypoint` @@ -91,7 +91,7 @@ asbs dev --agents order_processor asbs validate # what this project has not said yet ``` -`asbs dev` runs your agents under their **real** namespaces, so a local route is +In an image directory `asbs dev` runs your agents under their **real** namespaces, so a local route is `/api/order_processor/orders/{id}` -- byte-identical to production -- and the local consumer identity is the production queue group. A development server at the root namespace would give every developer URLs and integration tests that differ from the deployed ones, in a way nothing reports. diff --git a/src/blueprint/agent_generator/generator/part_generators/pyproject_part_generator.py b/src/blueprint/agent_generator/generator/part_generators/pyproject_part_generator.py index 3c96a667..2f6658fb 100644 --- a/src/blueprint/agent_generator/generator/part_generators/pyproject_part_generator.py +++ b/src/blueprint/agent_generator/generator/part_generators/pyproject_part_generator.py @@ -29,7 +29,7 @@ def to_py_file_name(self) -> str: def _pyproject(self) -> str: distribution = self.camel_to_snake(self.config["name"]).replace("_", "-") - return f'''[project] + return f"""[project] name = "{distribution}" version = "0.1.0" description = "{self.config["description"]}" @@ -58,4 +58,4 @@ def _pyproject(self) -> str: # run in a new project fails on the import rather than on anything the author wrote. pythonpath = ["."] asyncio_mode = "auto" -''' +""" diff --git a/src/blueprint/agent_generator/generator/part_generators/service_part_generator.py b/src/blueprint/agent_generator/generator/part_generators/service_part_generator.py index f3590f4a..2f4b1c07 100644 --- a/src/blueprint/agent_generator/generator/part_generators/service_part_generator.py +++ b/src/blueprint/agent_generator/generator/part_generators/service_part_generator.py @@ -30,6 +30,13 @@ def _create_service_imports(self) -> str: """ lines = [] + service = self.config["service_layer"][self.service_name] + # Each import only where it is used (N9): AgentRuntime sat unused in every service that + # holds no agent, and a service with no domain models named its types nowhere. + if service.get("uses_agents"): + lines.append("from blueprint.agents.agent import AgentRuntime") + if service.get("type_imports"): + lines.append(service["type_imports"]) if self.config["service_layer"][self.service_name]["uses_domain_models"]: if len(self.config["service_layer"][self.service_name]["uses_domain_models"]) < 4: lines.append( diff --git a/tests/unit/agent_generator/cli/commands/test_create_agent.py b/tests/unit/agent_generator/cli/commands/test_create_agent.py index 0fd43894..db0304fe 100644 --- a/tests/unit/agent_generator/cli/commands/test_create_agent.py +++ b/tests/unit/agent_generator/cli/commands/test_create_agent.py @@ -76,3 +76,23 @@ def test_it_prints_the_registration_to_add_by_hand( printed = capsys.readouterr().out assert f'.with_agent({RUNTIME}, name="{RUNTIME}")' in printed assert f'AgentBuilder(runtime_name="{RUNTIME}")' in printed + + +class TestCreateService: + """N9 -- the generated service named InputData and OutputData nowhere and imported AgentRuntime for nothing.""" + + def test_the_service_compiles_and_imports_what_it_names(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + import ast + from argparse import Namespace + + from blueprint.agent_generator.cli.commands.create import create_service + + monkeypatch.chdir(tmp_path) + create_service(Namespace(name="Billing", output_dir="src/services")) + source = (tmp_path / "src" / "services" / "billing_service.py").read_text(encoding="utf-8") + tree = ast.parse(source) + + imported = {alias.asname or alias.name for node in ast.walk(tree) if isinstance(node, ast.ImportFrom) for alias in node.names} + assert "InputData" not in source and "OutputData" not in source + assert "BaseModel" in imported + assert "AgentRuntime" not in source diff --git a/tests/unit/agent_generator/generator/test_generated_project.py b/tests/unit/agent_generator/generator/test_generated_project.py index 74ecabcc..3923407b 100644 --- a/tests/unit/agent_generator/generator/test_generated_project.py +++ b/tests/unit/agent_generator/generator/test_generated_project.py @@ -443,9 +443,9 @@ def test_the_command_is_the_framework_entry_point(self, project: Path) -> None: assert "src.main:create_app" in final assert "--factory" in final, "create_app is a factory; uvicorn needs an import string to reload it" - assert "blueprint.agents.entrypoint" not in final, ( - "The image serves one agent through the group entry point, which makes a standalone agent declare itself a group of one." - ) + assert ( + "blueprint.agents.entrypoint" not in final + ), "The image serves one agent through the group entry point, which makes a standalone agent declare itself a group of one." def test_no_agent_map_is_in_the_image(self, project: Path) -> None: """This image holds one agent and serves it; there is no group for a map to describe.""" @@ -495,6 +495,50 @@ def test_the_healthcheck_names_a_route_the_application_serves(self, project: Pat assert "8000/health || exit 1" not in dockerfile, "the bare /health is not a route this application serves" +class TestTheImageEnvironment: + """S14, D10 -- DYNACONF_ENVIRONMENT selected nothing, so every image ran the development section.""" + + def test_the_production_stage_selects_production(self, project: Path) -> None: + final = (project / "Dockerfile").read_text(encoding="utf-8").split("FROM python:3.13-slim-bookworm AS final")[1] + assert 'DYNACONF_APP_ENVIRONMENT="production"' in final + + def test_the_dev_stage_selects_development(self, project: Path) -> None: + dev = (project / "Dockerfile").read_text(encoding="utf-8").split("AS dev")[1].split("AS final")[0] + assert 'DYNACONF_APP_ENVIRONMENT="development"' in dev + + def test_the_variable_that_selects_nothing_is_set_nowhere(self, project: Path) -> None: + dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") + assert 'DYNACONF_ENVIRONMENT="' not in dockerfile + + def test_the_variable_is_the_one_config_reads(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + (tmp_path / "settings.toml").write_text('[development]\nmarker = "dev"\n[production]\nmarker = "prod"\n') + monkeypatch.setenv("DYNACONF_APP_ENVIRONMENT", "production") + assert Config(settings_files=["settings.toml"], root_path=str(tmp_path)).get("marker") == "prod" + + +class TestTheGroupImage: + """M10 -- the group image's slim base has no curl, so a curl health check failed for ever.""" + + GROUP_DOCKERFILE = Path(__file__).resolve().parents[4] / "src" / "blueprint" / "agent_generator" / "base_files" / "group_Dockerfile" + + def test_the_health_check_needs_no_curl(self) -> None: + dockerfile = self.GROUP_DOCKERFILE.read_text(encoding="utf-8") + healthcheck = dockerfile.split("HEALTHCHECK", 1)[1].split("\n\n", 1)[0] + assert "curl" not in healthcheck + assert "/health/live" in healthcheck and "python" in healthcheck + + def test_it_selects_production(self) -> None: + assert 'DYNACONF_APP_ENVIRONMENT="production"' in self.GROUP_DOCKERFILE.read_text(encoding="utf-8") + + +class TestTheGeneratedSettingsComments: + """N8 -- the generator replaces the token app_name everywhere, comments included.""" + + def test_no_comment_carries_a_substituted_key(self, project: Path) -> None: + comments = [line for line in (project / "settings.toml").read_text(encoding="utf-8").splitlines() if line.lstrip().startswith("#")] + assert not [line for line in comments if 'app_name = "' in line] + + class TestAnUnusableProjectNameIsRefused: """A name that cannot be a namespace fails the generator rather than the deployment.""" @@ -504,6 +548,18 @@ def test_a_leading_digit_is_refused_with_the_reason(self) -> None: with pytest.raises(ValueError, match="cannot be used"): PartGeneratorBase.agent_namespace({"name": "2ndAgent"}) + def test_setup_refuses_it_before_writing_anything(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + """N7 -- the name was checked after generate(), so a refused name left a whole project behind.""" + from argparse import Namespace + + from blueprint.agent_generator.cli.commands import setup + + with pytest.raises(SystemExit): + setup.run(Namespace(project_name="Cache", output_dir=str(tmp_path), overwrite=False, verbose=False, group=False)) + + assert list(tmp_path.iterdir()) == [] + assert "configuration section the whole process shares" in capsys.readouterr().err + class TestTheGeneratedSettings: """What settings.toml must not decide for the author, or bake in.""" From 4939cab43dba64c2401af366b34fd55b924ff26b Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:15:01 +0200 Subject: [PATCH 116/133] fix(dedup): cache calls off the event loop; redis-py >= 8; warn without a heartbeat Step 15 (S6, S7, D4): opt-in cache.redis_socket_timeout. Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 10 +++ ...26-08-28-multi-agent-grouping-changelog.md | 5 ++ pyproject.toml | 4 +- .../agent_generator/docs/concepts/caching.md | 1 + .../docs/concepts/event-processing.md | 7 ++ src/blueprint/agents/config/config.py | 1 + src/blueprint/agents/handler/handler_chain.py | 48 +++++++++++-- .../agents/io/api/scheduling/scheduler.py | 9 ++- src/blueprint/agents/models/config.py | 4 ++ .../eventing/event_processing_service.py | 2 +- .../infrastructure/cache_backend_factory.py | 1 + .../infrastructure/redis_cache_service.py | 7 ++ tests/unit/agents/handler/TESTS.md | 2 +- .../unit/agents/handler/test_handler_chain.py | 71 +++++++++++++++++-- tests/unit/agents/services/TESTS.md | 2 +- .../eventing/test_event_processing_service.py | 8 ++- .../test_redis_cache_service.py | 22 ++++++ 17 files changed, 181 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a266d548..1eb22b3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,16 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **A slow cache no longer holds up every delivery of the process.** The dedup claim and release, and + the in-process scheduler's tick claim, ran on the event loop, so a Redis that stopped answering + stalled every agent for as long as the call blocked. They now run in a worker thread. **The minimum + redis-py is now 8.0**, the release that bounds every call by a 5 s default; before it the default + was no timeout at all. New, opt-in: `cache.redis_socket_timeout`. Measured with the Redis container + paused and a 2 s timeout: the event loop's longest gap was 0.06 s (before: 2.02 s), and the claim + failed open after 2 s. Startup now warns when deduplication runs without a heartbeat -- NATS with + `nats_heartbeat_enabled = false`, and Dapr -- where a redelivery of a running event is skipped as a + duplicate. + - **Scaffolded images select the production environment, and the group image turns healthy.** The generated Dockerfiles set `DYNACONF_ENVIRONMENT`, which selects nothing, so every image ran the `development` section; they now set `DYNACONF_APP_ENVIRONMENT` (`production`, and `development` in diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index f539530a..06ebe221 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,11 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 15, dedup without a heartbeat and Redis calls (S6, S7, D4): `HandlerChain._claim`/`release` and the + scheduler's `_claim_tick_slot` run the cache call in `asyncio.to_thread`; a startup WARNING for dedup with + the NATS heartbeat off and for dedup under Dapr; `cache.redis_socket_timeout` (opt-in); redis-py floor + raised to 8.0 (its 5 s default timeout; 7.x had none). Live (Redis 7 in WSL, container paused, timeout 2 s): + longest event-loop gap 0.06 s and the claim failed open after 2.01 s; control: the loop stood for 2.02 s. - Step 14, scaffold and CLI (M10, S14, N6-N9, D10): `DYNACONF_APP_ENVIRONMENT` in both Dockerfiles (production, development in the dev stage), a Python health check in `group_Dockerfile`, `asbs setup` validates the name before writing, the `settings.txt` comment no longer carries the substituted token, diff --git a/pyproject.toml b/pyproject.toml index bf460cac..0e3928bc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -56,10 +56,10 @@ ci = [ "mypy>=1.18.2", "httpx>=0.28.1", "fakeredis>=2.26.0", - "redis[hiredis]>=5.0.0", + "redis[hiredis]>=8.0.0", "respx>=0.22.0", ] -redis = ["redis[hiredis]>=5.0.0"] +redis = ["redis[hiredis]>=8.0.0"] dev = [ "avs-blueprint-agents[ci]", "debugpy>=1.8.17", diff --git a/src/blueprint/agent_generator/docs/concepts/caching.md b/src/blueprint/agent_generator/docs/concepts/caching.md index f5c6873c..de9c02bb 100644 --- a/src/blueprint/agent_generator/docs/concepts/caching.md +++ b/src/blueprint/agent_generator/docs/concepts/caching.md @@ -198,6 +198,7 @@ default_ttl = 3600 # seconds | `redis_password` | `str \| None` | `None` | redis -- read it from a secrets file | | `redis_db` | `int` | `0` | redis | | `redis_tls` | `bool` | `false` | redis | +| `redis_socket_timeout` | `float` | unset -- redis-py's own, 5 s | redis | | `fallback_to_local` | `bool` | `false` | redis | In a group each agent may configure its own cache under its own scope, so one agent can run on diff --git a/src/blueprint/agent_generator/docs/concepts/event-processing.md b/src/blueprint/agent_generator/docs/concepts/event-processing.md index 10fb99d9..a288cea8 100644 --- a/src/blueprint/agent_generator/docs/concepts/event-processing.md +++ b/src/blueprint/agent_generator/docs/concepts/event-processing.md @@ -174,6 +174,13 @@ it ran into: that marker belongs to the first delivery. The marker is keyed on t and `id`, and on the named connection the event came from, if any: two connections delivering the same `source` and `id` are two events. +**The marker has no "in progress" state.** A redelivery that arrives while the first run is still +going finds the marker, is skipped and acknowledged; if the first run then fails, the event is lost. +Under NATS the heartbeat (`nats_heartbeat_enabled`, on by default) keeps the broker from redelivering a +running delivery, so this needs the heartbeat off; startup warns about that combination. Dapr has no +heartbeat: keep runs well under the sidecar's app-call timeout -- startup warns there too. The claim +and its release run in a worker thread, so a slow cache does not hold up other deliveries. + **A result's event id is derived, not random:** a UUIDv5 over the agent, the inbound event's `source` and `id`, the result's `event_type` and its position in the list. A redelivery therefore republishes each result under the same id -- including results an earlier attempt had already sent diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index c3db6aea..d75c792e 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -1331,6 +1331,7 @@ def get_cache_config(self) -> CacheConfig: redis_db=self.get("cache.redis_db", 0), redis_tls=self.get("cache.redis_tls", False), fallback_to_local=self.get("cache.fallback_to_local", False), + redis_socket_timeout=self.get("cache.redis_socket_timeout"), ) def get_sessions_config(self) -> SessionsServiceConfig | None: diff --git a/src/blueprint/agents/handler/handler_chain.py b/src/blueprint/agents/handler/handler_chain.py index b4d89ff6..6a2215bc 100644 --- a/src/blueprint/agents/handler/handler_chain.py +++ b/src/blueprint/agents/handler/handler_chain.py @@ -1,5 +1,6 @@ """Handler chain for executing event handlers in priority order.""" +import asyncio import logging import re import time @@ -267,6 +268,7 @@ async def on_startup(self) -> None: self.namespace or ROOT_LABEL, self._policy.ttl, ) + self._warn_without_a_heartbeat() index = self._refresh_index() logger.info( @@ -302,7 +304,7 @@ async def process(self, event: CloudEvent[Any], context: dict[str, Any]) -> Any if policy is None: policy = self._policy = self._resolve_idempotency_policy() - if not self._claim(event, policy, context): + if not await self._claim(event, policy, context): context[DUPLICATE_CONTEXT_KEY] = True trace.get_current_span().set_attribute("event.duplicate", True) logger.info("Skipping event '%s' from '%s': already processed within the dedup window", event.id, event.source) @@ -314,7 +316,7 @@ async def process(self, event: CloudEvent[Any], context: dict[str, Any]) -> Any # BaseException, not Exception: a handler cut off by nats_handler_timeout, or by a # shutdown, ends with CancelledError. Kept, the marker would make the nak'd # redelivery a duplicate that acknowledges, and the event would be lost unrun. - self.release(event, context) + await self.release(event, context) raise # ------------------------------------------------------------------ @@ -498,7 +500,34 @@ def _warn_ambiguous_runtime(self, handler: EventHandlerBase, names: list[str]) - # Idempotency (P4) # ------------------------------------------------------------------ - def _claim(self, event: CloudEvent[Any], policy: IdempotencyPolicy, context: dict[str, Any]) -> bool: + def _warn_without_a_heartbeat(self) -> None: + """Warn when dedup runs where a run can outlast its delivery (S6, plan D4). + + A marker has no "in progress" state: a redelivery that arrives while the first run is + still going finds the marker, is skipped as a duplicate and acknowledged -- and if the + first run then fails, the event is lost. The NATS heartbeat (``in_progress``) is what + stops the broker redelivering a running delivery, so dedup without it is the one + combination where that can happen. Dapr has no heartbeat at all: the sidecar's app-call + timeout decides when it gives up on a delivery and sends it again. + """ + bus = str(self.config.get("event_bus", "") or "").strip().lower() + agent = self.namespace or ROOT_LABEL + if bus == "nats" and self.config.get("nats_heartbeat_enabled", True) is False: + logger.warning( + "Agent '%s' deduplicates events with 'nats_heartbeat_enabled = false': a run that outlasts ack_wait is " + "redelivered while it runs, the redelivery is skipped as a duplicate and acknowledged, and if the " + "first run then fails the event is lost. Keep the heartbeat on, or keep runs well under ack_wait.", + agent, + ) + elif bus == "dapr": + logger.warning( + "Agent '%s' deduplicates events under Dapr, which has no heartbeat: a run that outlasts the sidecar's " + "app-call timeout is delivered again while it runs, that delivery is skipped as a duplicate, and if " + "the first run then fails the event is lost. Keep runs well under that timeout.", + agent, + ) + + async def _claim(self, event: CloudEvent[Any], policy: IdempotencyPolicy, context: dict[str, Any]) -> bool: """Record that this event is being processed, and report whether to dispatch it. A claim that is won is recorded in ``context`` (:data:`CLAIMED_CONTEXT_KEY`), so that @@ -517,8 +546,11 @@ def _claim(self, event: CloudEvent[Any], policy: IdempotencyPolicy, context: dic return True # One atomic set-if-absent, not exists() then set(): between those two calls a second - # replica handed the same event passes the check too, and both dispatch. - claimed = self.registry.cache_service.claim( + # replica handed the same event passes the check too, and both dispatch. In a thread + # (S7): both backends block -- a Redis round trip, a disk write -- and on the event loop + # every other delivery of the process waited for it. + claimed = await asyncio.to_thread( + self.registry.cache_service.claim, key, {"seen_at": time.time(), "event_type": event.type}, namespace=IDEMPOTENCY_CACHE_NAMESPACE, @@ -528,7 +560,7 @@ def _claim(self, event: CloudEvent[Any], policy: IdempotencyPolicy, context: dic context[CLAIMED_CONTEXT_KEY] = True return claimed - def release(self, event: CloudEvent[Any], context: dict[str, Any]) -> None: + async def release(self, event: CloudEvent[Any], context: dict[str, Any]) -> None: """Drop the dedup marker this delivery claimed, so its redelivery is allowed to run. The claim is taken before dispatch, which is the only point at which it can stop a @@ -556,7 +588,9 @@ def release(self, event: CloudEvent[Any], context: dict[str, Any]) -> None: if key is None: return - self.registry.cache_service.delete(key, namespace=IDEMPOTENCY_CACHE_NAMESPACE) + # In a thread, like the claim. Once started it completes even if this await is cancelled + # again -- a shutdown -- because the thread runs on regardless. + await asyncio.to_thread(self.registry.cache_service.delete, key, namespace=IDEMPOTENCY_CACHE_NAMESPACE) logger.debug("Released the dedup marker for event '%s': the delivery was not settled as a success", event.id) @staticmethod diff --git a/src/blueprint/agents/io/api/scheduling/scheduler.py b/src/blueprint/agents/io/api/scheduling/scheduler.py index d24bb435..18d097ab 100644 --- a/src/blueprint/agents/io/api/scheduling/scheduler.py +++ b/src/blueprint/agents/io/api/scheduling/scheduler.py @@ -38,6 +38,7 @@ async def tick(self) -> None: from __future__ import annotations +import asyncio import functools import logging import time @@ -705,12 +706,12 @@ async def _claimed_tick(self) -> None: unconditionally. That is the behaviour this mode had before, and ``on_startup`` warns about it once rather than on every tick. """ - if not self._claim_tick_slot(): + if not await self._claim_tick_slot(): logger.debug("Scheduler '%s' did not win this tick; another replica is running it", self.name) return await self.run_tick() - def _claim_tick_slot(self) -> bool: + async def _claim_tick_slot(self) -> bool: """Claim the current tick slot, reporting whether this replica may run it. The key is the *slot*, not the scheduler: ``(scheduler, minute)``. Cron granularity @@ -728,7 +729,9 @@ def _claim_tick_slot(self) -> bool: return True slot = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M") - return self.registry.cache_service.claim( + # In a thread: a blocking Redis round trip or disk write on the event loop (S7). + return await asyncio.to_thread( + self.registry.cache_service.claim, {"scheduler": self.name, "slot": slot}, {"claimed_at": time.time()}, namespace=TICK_CACHE_NAMESPACE, diff --git a/src/blueprint/agents/models/config.py b/src/blueprint/agents/models/config.py index a55a081d..1571e0ba 100644 --- a/src/blueprint/agents/models/config.py +++ b/src/blueprint/agents/models/config.py @@ -168,6 +168,10 @@ class CacheConfig(BaseModel): redis_db: int = Field(default=0, description="Redis database index") redis_tls: bool = Field(default=False, description="Enable TLS for Redis connection") fallback_to_local: bool = Field(default=False, description="Fall back to DiskCacheService if Redis is unavailable at startup") + redis_socket_timeout: float | None = Field( + default=None, + description="Seconds a Redis call may block, connect included; unset keeps redis-py's own default (5 s since redis-py 8)", + ) class RuntimeConfig(BaseModel): diff --git a/src/blueprint/agents/services/eventing/event_processing_service.py b/src/blueprint/agents/services/eventing/event_processing_service.py index dc74d829..0f2a8561 100644 --- a/src/blueprint/agents/services/eventing/event_processing_service.py +++ b/src/blueprint/agents/services/eventing/event_processing_service.py @@ -220,7 +220,7 @@ async def process_event( # logs it with what it decided to do about it. Logging here too duplicated each failure. finally: if not settled: - chain.release(event, context) + await chain.release(event, context) self._correlation_context.reset(correlation_token) async def process_rest_request( diff --git a/src/blueprint/agents/services/infrastructure/cache_backend_factory.py b/src/blueprint/agents/services/infrastructure/cache_backend_factory.py index e878dd86..9bfe327d 100644 --- a/src/blueprint/agents/services/infrastructure/cache_backend_factory.py +++ b/src/blueprint/agents/services/infrastructure/cache_backend_factory.py @@ -179,6 +179,7 @@ def _create_redis( default_ttl=config.default_ttl, fallback_to_local=config.fallback_to_local, component_name=CacheBackendFactory._component_name(name), + socket_timeout=config.redis_socket_timeout, ) # Probe the connection synchronously so a "RedisCacheService" instance diff --git a/src/blueprint/agents/services/infrastructure/redis_cache_service.py b/src/blueprint/agents/services/infrastructure/redis_cache_service.py index d51d02e0..16130e9a 100644 --- a/src/blueprint/agents/services/infrastructure/redis_cache_service.py +++ b/src/blueprint/agents/services/infrastructure/redis_cache_service.py @@ -41,6 +41,7 @@ def __init__( default_ttl: int | None = None, fallback_to_local: bool = False, component_name: str | None = None, + socket_timeout: float | None = None, ) -> None: # component_name: registry name to use instead of the derived 'redis_cache_service'. # A process may hold several named caches (spec sec. 8), and two instances of this @@ -62,11 +63,17 @@ def __init__( effective_url = "rediss://" + redis_url[len("redis://") :] # Typed as Any: redis-py's sync methods are statically declared as ``Awaitable | T`` # (the same Redis class is used for sync and async), which trips mypy on every call. + # socket_timeout bounds every call, the connect included (S7). Unset leaves redis-py's + # default, which is 5 s since redis-py 8 -- the minimum this package requires, because + # before it the default was no timeout, and a Redis that stopped answering held the call + # (and, through the claim, a delivery) for ever. + timeouts = {} if socket_timeout is None else {"socket_timeout": socket_timeout, "socket_connect_timeout": socket_timeout} self._client: Any = redis.Redis.from_url( effective_url, password=password, db=db, decode_responses=True, + **timeouts, ) async def ping(self) -> None: diff --git a/tests/unit/agents/handler/TESTS.md b/tests/unit/agents/handler/TESTS.md index 1760e808..154c19e4 100644 --- a/tests/unit/agents/handler/TESTS.md +++ b/tests/unit/agents/handler/TESTS.md @@ -9,7 +9,7 @@ Test coverage for `src/blueprint/agents/handler/`. | File | Class under test | What is covered | |---|---|---| | `test_event_handler_base.py` | `EventHandlerBase` | `__init__` stores default and custom priority; `can_handle` delegates to `can_handle_event` (True/False); `handle` passes through `HandlerResult`, `list[HandlerResult]`, dict, and `None` unchanged; `get_published_event_types` default returns `None`; `get_subscribed_topics` default returns `[]`; `__lt__` priority ordering and `sorted()` correctness | -| `test_handler_chain.py` | `HandlerChain` | `on_startup`/`on_shutdown` lifecycle no-ops; `process` with no handlers → `None`; declining handler skipped; accepting handler result returned; handler returning `None` passes to next; chain stops at first non-`None` result; a `HandlerResult.skipped` stops the chain without asking the next handler and logs its reason at INFO with no WARNING; handlers executed in ascending priority order; handler exception re-raised; dedup: a failed or cancelled (`CancelledError`) dispatch releases its claim, a duplicate holds no claim and releases nothing, a released claim is released once, `release` with dedup off is a no-op; the same event on two named connections is two events and a claim is released under its own connection's key, the default connection keeps the two-part key, and the chain's connection context key equals the NATS endpoint's (T1) | +| `test_handler_chain.py` | `HandlerChain` | `on_startup`/`on_shutdown` lifecycle no-ops; `process` with no handlers → `None`; declining handler skipped; accepting handler result returned; handler returning `None` passes to next; chain stops at first non-`None` result; a `HandlerResult.skipped` stops the chain without asking the next handler and logs its reason at INFO with no WARNING; handlers executed in ascending priority order; handler exception re-raised; dedup: a failed or cancelled (`CancelledError`) dispatch releases its claim, a duplicate holds no claim and releases nothing, a released claim is released once, `release` with dedup off is a no-op; the same event on two named connections is two events and a claim is released under its own connection's key, the default connection keeps the two-part key, and the chain's connection context key equals the NATS endpoint's (T1); claim and delete run off the event loop (S7); startup warns for dedup with the NATS heartbeat off and under Dapr, and is quiet with the heartbeat on (S6, D4) | --- diff --git a/tests/unit/agents/handler/test_handler_chain.py b/tests/unit/agents/handler/test_handler_chain.py index dff12bfb..2a6675a7 100644 --- a/tests/unit/agents/handler/test_handler_chain.py +++ b/tests/unit/agents/handler/test_handler_chain.py @@ -296,7 +296,7 @@ async def can_handle_event(self, event, context): context: dict[str, Any] = {} await chain.process(cloud_event, context) - chain.release(cloud_event, context) + await chain.release(cloud_event, context) await chain.process(cloud_event, {}) assert seen == ["evt-001", "evt-001"] @@ -308,7 +308,7 @@ async def test_release_with_dedup_off_is_a_no_op( context: dict[str, Any] = {} await chain.process(cloud_event, context) - chain.release(cloud_event, context) + await chain.release(cloud_event, context) assert CLAIMED_CONTEXT_KEY not in context mock_registry.cache_service.delete.assert_not_called() @@ -324,7 +324,7 @@ async def test_a_duplicate_releases_nothing( duplicate: dict[str, Any] = {} await chain.process(cloud_event, duplicate) - chain.release(cloud_event, duplicate) + await chain.release(cloud_event, duplicate) assert first[CLAIMED_CONTEXT_KEY] is True assert CLAIMED_CONTEXT_KEY not in duplicate @@ -338,10 +338,10 @@ async def test_a_released_claim_is_released_once( _wire_handlers(mock_registry, [StubHandler(result=None)]) context: dict[str, Any] = {} await chain.process(cloud_event, context) - chain.release(cloud_event, context) + await chain.release(cloud_event, context) await chain.process(cloud_event, {}) # the redelivery claims again - chain.release(cloud_event, context) + await chain.release(cloud_event, context) assert len(cache.store) == 1 @@ -438,7 +438,7 @@ async def test_a_named_connections_claim_is_released_under_its_own_key( await chain.process(cloud_event, on_a) await chain.process(cloud_event, {CONNECTION_CONTEXT_KEY: "B"}) - chain.release(cloud_event, on_a) + await chain.release(cloud_event, on_a) assert list(cache.store) == [_StubCache._key({"id": "evt-001", "source": "test-source", "connection": "B"})] @@ -568,3 +568,62 @@ async def test_no_handler_line( with caplog.at_level("WARNING", logger="blueprint.agents.handler.handler_chain"): await chain.process(cloud_event, {}) assert caplog.messages == [f"No handler processed event '{cloud_event.type}'"] + + +class TestTheCacheIsCalledOffTheEventLoop: + """S7 -- claim and delete block (a Redis round trip, a disk write); on the loop every delivery waited.""" + + async def test_claim_and_delete_run_in_another_thread( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, cloud_event: GenericCloudEvent + ) -> None: + import threading + + cache = _enable_dedup(mock_config, mock_registry) + threads: list[int] = [] + claim, delete = cache.claim, cache.delete + cache.claim = lambda *a, **k: threads.append(threading.get_ident()) or claim(*a, **k) # type: ignore[method-assign] + cache.delete = lambda *a, **k: threads.append(threading.get_ident()) or delete(*a, **k) # type: ignore[method-assign] + _wire_handlers(mock_registry, [StubHandler(result=None)]) + context: dict[str, Any] = {} + + await chain.process(cloud_event, context) + await chain.release(cloud_event, context) + + assert len(threads) == 2 + assert threading.get_ident() not in threads + + +class TestDedupWithoutAHeartbeatWarns: + """S6, plan D4 -- a redelivery while the first run still goes is skipped as a duplicate; the heartbeat prevents it.""" + + @staticmethod + def _settings(mock_config: MagicMock, **values: Any) -> None: + settings = {"idempotency_enabled": True, "idempotency_ttl": 60, **values} + mock_config.get.side_effect = lambda key, default=None: settings.get(key, default) + + async def test_nats_with_the_heartbeat_off_warns( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, caplog: pytest.LogCaptureFixture + ) -> None: + self._settings(mock_config, event_bus="nats", nats_heartbeat_enabled=False) + _wire_handlers(mock_registry, []) + with caplog.at_level("WARNING"): + await chain.on_startup() + assert "nats_heartbeat_enabled = false" in caplog.text + + async def test_dapr_warns_naming_the_app_call_timeout( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, caplog: pytest.LogCaptureFixture + ) -> None: + self._settings(mock_config, event_bus="dapr") + _wire_handlers(mock_registry, []) + with caplog.at_level("WARNING"): + await chain.on_startup() + assert "app-call timeout" in caplog.text + + async def test_nats_with_the_heartbeat_on_is_quiet( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, caplog: pytest.LogCaptureFixture + ) -> None: + self._settings(mock_config, event_bus="nats") + _wire_handlers(mock_registry, []) + with caplog.at_level("WARNING"): + await chain.on_startup() + assert [record for record in caplog.records if record.levelname == "WARNING"] == [] diff --git a/tests/unit/agents/services/TESTS.md b/tests/unit/agents/services/TESTS.md index f3ac9844..a2dbd437 100644 --- a/tests/unit/agents/services/TESTS.md +++ b/tests/unit/agents/services/TESTS.md @@ -11,7 +11,7 @@ Test coverage for `src/blueprint/agents/services/`. | `eventing/test_event_processing_service.py` | `EventProcessingService` | `_extract_handler_results` (None/HandlerResult/list/dict variants), `_build_result` (message text incl. `Skipped: `, request_id, result list), a skipped run reported as `SKIPPED` and publishing nothing, a list mixing a skip with a real result reported as `PROCESSED` and publishing only the real one, `_unwrap_dapr_event` (passthrough / CloudEvent inner / dict inner / missing type / unexpected type), lifecycle no-ops, `process_rest_request` delegates to `process_event` with correct event shape; the dedup bracket with a real chain and disk cache: a run cut off by `asyncio.timeout`, a run that swallows the cancellation and a return value failing after dispatch all give the marker back (B1, M11), an acknowledged delivery keeps it; an inner Dapr event without `type`, or one failing validation, raises an error that names the field but carries no value, logs nothing itself, and has no pydantic cause in its traceback (B2) | | `eventing/test_event_publishing_service.py` | `EventPublishingService` | `on_startup` wires client and config, `_get_pub_config` raises before startup, `get_topic_for_event_type` / `get_available_event_types`, `publish_event` (topic mapping, explicit topic override, missing mapping raises, sets default source, result shape), `publish_handler_event` (no mapping → skip, loop prevention → skip, normal → publishes), `publish_status_event` type format and delegation | | `infrastructure/test_disk_cache_service.py` | `DiskCacheService` | `set`/`get` (string/dict/list keys, namespace isolation), `delete` (return values), `exists` (before/after set/delete), `clear` (namespace-scoped and full), TTL expiration via mocked `time.time`, `hash` consistency for string/list/dict inputs, `list_namespaces`, `list_values` (content, TTL-entry exclusion, limit), `get_stats` field presence, lifecycle, context-manager protocol, an unwritable cache directory failing with a message that names the path and the options (and keeping the OSError as the cause); `claim` set-if-absent (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, keys and namespaces independent, dict keys hashed consistently, TTL recorded so readers see expiry, a logically expired claim taken over, no TTL never expires, and an unreachable cache failing open) | -| `infrastructure/test_redis_cache_service.py` | `RedisCacheService` | Backed by `fakeredis`. `claim` via `SET NX EX` (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, the TTL is applied to the key, namespaces are independent, and an unreachable cache fails open); the default store leaves nested stores alone -- clear, a namespace clear, list_namespaces -- and without a prefix deletes only its own keys and warns (M6). *The rest of this file's coverage predates this table and is not itemised here.* | +| `infrastructure/test_redis_cache_service.py` | `RedisCacheService` | Backed by `fakeredis`. `claim` via `SET NX EX` (first wins, second refused, the loser does not overwrite, exactly one of five callers wins, the TTL is applied to the key, namespaces are independent, and an unreachable cache fails open); the default store leaves nested stores alone -- clear, a namespace clear, list_namespaces -- and without a prefix deletes only its own keys and warns (M6). `redis_socket_timeout` reaches the connection, unset keeps the bounded library default, and the cache config carries the key (S7). *The rest of this file's coverage predates this table and is not itemised here.* | | `infrastructure/test_cache_backend_factory.py`, `infrastructure/test_cache_sharing_via_registry.py`, `infrastructure/test_redis_url_utils.py` | `CacheBackendFactory`, registry cache sharing, Redis URL helpers | Present but not itemised in this table. | | `sessions/test_api_client.py` | `SessionsApiClient` | `on_startup` (valid config, missing config/base_url/api_key → ValueError), `on_shutdown` (closes client, no-op when uninitialised), `get_job_detail`/`start_job`/`complete_job`/`cancel_job` (URL shape, required headers, payload contents, uninitialised guard) | | `sessions/test_key_provider.py` | `SessionKeyProvider` | `on_startup` (initialises cache, reads source/env_var from config, missing config → ValueError), `on_shutdown` (clears cache, no-op when uninitialised), `get_session_key` (env hit/miss, config source, vault → NotImplementedError, remote source via respx — happy path/caching/404/missing session_id/missing URL, unknown source, cache-hit bypass, result cached after fetch), `invalidate_cache` (default and per-session key removal, no-op when empty/uninitialised) | 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 5c52f624..32d2bed2 100644 --- a/tests/unit/agents/services/eventing/test_event_processing_service.py +++ b/tests/unit/agents/services/eventing/test_event_processing_service.py @@ -243,6 +243,7 @@ class TestAFailedResultPublish: def _wire(service: EventProcessingService, mock_registry: MagicMock, results: list[HandlerResult]) -> tuple[MagicMock, MagicMock]: chain = MagicMock() chain.process = AsyncMock(return_value=results) + chain.release = AsyncMock() service._handler_chains[ROOT_NAMESPACE] = chain publisher = MagicMock() publisher.publish_handler_event = AsyncMock() @@ -258,7 +259,7 @@ async def test_it_fails_the_delivery_and_releases_the_marker( with pytest.raises(ConnectionError): await event_processing_service.process_event(event) - chain.release.assert_called_once() + chain.release.assert_awaited_once() assert chain.release.call_args.args[0].id == "e1" async def test_a_successful_publish_keeps_the_marker( @@ -266,7 +267,7 @@ async def test_a_successful_publish_keeps_the_marker( ) -> None: chain, _ = self._wire(event_processing_service, mock_registry, [HandlerResult(event_type="done", data={})]) await event_processing_service.process_event(GenericCloudEvent(id="e1", type="t", source="s")) - chain.release.assert_not_called() + chain.release.assert_not_awaited() async def test_each_result_is_published_with_its_position( self, event_processing_service: EventProcessingService, mock_registry: MagicMock @@ -284,6 +285,7 @@ class TestASkippedRun: def _wire(service: EventProcessingService, mock_registry: MagicMock, results: object) -> MagicMock: chain = MagicMock() chain.process = AsyncMock(return_value=results) + chain.release = AsyncMock() service._handler_chains[ROOT_NAMESPACE] = chain publisher = MagicMock() publisher.publish_handler_event = AsyncMock() @@ -316,6 +318,7 @@ class TestTheRequestIdIsKept: async def test_a_callers_id_survives_processing(self, event_processing_service: EventProcessingService) -> None: chain = MagicMock() chain.process = AsyncMock(return_value=None) + chain.release = AsyncMock() event_processing_service._handler_chains[ROOT_NAMESPACE] = chain context = {"request_id": "rest-123"} @@ -327,6 +330,7 @@ async def test_a_callers_id_survives_processing(self, event_processing_service: async def test_without_one_an_id_is_made(self, event_processing_service: EventProcessingService) -> None: chain = MagicMock() chain.process = AsyncMock(return_value=None) + chain.release = AsyncMock() event_processing_service._handler_chains[ROOT_NAMESPACE] = chain context: dict = {} diff --git a/tests/unit/agents/services/infrastructure/test_redis_cache_service.py b/tests/unit/agents/services/infrastructure/test_redis_cache_service.py index 4d061f23..5a8819a3 100644 --- a/tests/unit/agents/services/infrastructure/test_redis_cache_service.py +++ b/tests/unit/agents/services/infrastructure/test_redis_cache_service.py @@ -435,3 +435,25 @@ def test_without_a_prefix_only_this_stores_keys_are_cleared(self, mock_registry, assert root.get("k") is None assert "no key_prefix" in caplog.text client.close() + + +class TestSocketTimeout: + """S7 -- an opt-in bound on every Redis call; unset keeps redis-py's own (5 s since redis-py 8, the minimum).""" + + def test_a_configured_timeout_reaches_the_connection(self, mock_registry, mock_config) -> None: + svc = RedisCacheService(redis_url="redis://127.0.0.1:1/0", socket_timeout=1.5) + kwargs = svc._client.connection_pool.connection_kwargs + assert (kwargs["socket_timeout"], kwargs["socket_connect_timeout"]) == (1.5, 1.5) + svc.close() + + def test_unset_keeps_the_library_default_which_is_bounded(self, mock_registry, mock_config) -> None: + svc = RedisCacheService(redis_url="redis://127.0.0.1:1/0") + kwargs = svc._client.connection_pool.connection_kwargs + assert kwargs.get("socket_timeout", 5) is not None + svc.close() + + def test_the_cache_config_carries_the_key(self, tmp_path) -> None: + from blueprint.agents.config import Config + + (tmp_path / "settings.toml").write_text('[default]\napp_environment = "development"\n[default.cache]\nredis_socket_timeout = 2.5\n') + assert Config(settings_files=["settings.toml"], root_path=str(tmp_path)).get_cache_config().redis_socket_timeout == 2.5 From d139c5e14e50cbc0bfc0e43d8b2bb23b6c91e5c6 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:15:02 +0200 Subject: [PATCH 117/133] fix(dapr): a copy of the event per agent, a bounded topic label, the delivery route only Step 16 (S5, S9, N5, D6). Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 14 +++++ ...26-08-28-multi-agent-grouping-changelog.md | 8 +++ .../docs/concepts/observability.md | 6 ++ .../docs/guides/multi-agent-setup.md | 5 +- src/blueprint/agents/io/api/eventing/dapr.py | 59 +++++++++++++++++-- .../io/api/eventing/event_handling_base.py | 17 +++++- tests/unit/agents/io/TESTS.md | 5 +- .../unit/agents/io/api/eventing/test_dapr.py | 23 ++++++++ .../io/api/eventing/test_dapr_fanout.py | 58 +++++++++++++++++- .../api/eventing/test_event_handling_base.py | 27 +++++++++ .../test_sessions_startup_resilience.py | 6 +- 11 files changed, 216 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1eb22b3b..c22eace7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,20 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **Grouped Dapr: each agent gets its own copy of a delivery, and the answer has no stray reason.** + The fan-out handed one `CloudEvent` object to every agent declaring the topic, so a change one + handler made to it reached the next. A delivery one agent acknowledged and another terminated + answered `SUCCESS` with the terminating agent's reason. Startup now warns about a topic two agents + declare while one of them runs without `idempotency_enabled`, since a retry asked for by one + redelivers to all of them. + +- **The `topic` label of the event counters is bounded under Dapr.** `blueprint.events.unhandled`, + `.duplicate` and `.skipped` took the topic from the request path, so posts to `/events/` + minted one time series each. A topic the agent did not declare is now counted as `` + (every topic, with `dapr_declarative_subscriptions = true`); the real one stays in the log line. + The DROP answer for an unparseable body is limited to the delivery route `/events/{topic}`: another + route of a `DaprEventing` subclass answers a malformed body with 422 again. + - **A slow cache no longer holds up every delivery of the process.** The dedup claim and release, and the in-process scheduler's tick claim, ran on the event loop, so a Redis that stopped answering stalled every agent for as long as the call blocked. They now run in a worker thread. **The minimum diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 06ebe221..92f75f63 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,14 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 16, Dapr hardening (S5, S9, N5, D6): a deep copy of the CloudEvent per agent when a delivery fans + out to more than one; a startup WARNING for a shared topic with an agent's `idempotency_enabled` off; + `EventHandlingBase._metric_topic` hook, Dapr labels an undeclared topic ``; an ACK combined + with a TERM answers SUCCESS without a reason; `DaprDeliveryRoute` wraps only `/events/{topic}`. Live (a + group served by uvicorn, Dapr sidecar mock, agents 'orders' and 'billing' on 'orders.created'): + 'billing' read `{"order": 1}` after 'orders' changed it, the answer was `{"status": "SUCCESS"}`, 5 + random topics gave one `` series per agent, the WARNING named both agents. Control: no + WARNING, reason attached, 'billing' saw the change, one series per random topic. - Step 15, dedup without a heartbeat and Redis calls (S6, S7, D4): `HandlerChain._claim`/`release` and the scheduler's `_claim_tick_slot` run the cache call in `asyncio.to_thread`; a startup WARNING for dedup with the NATS heartbeat off and for dedup under Dapr; `cache.redis_socket_timeout` (opt-in); redis-py floor diff --git a/src/blueprint/agent_generator/docs/concepts/observability.md b/src/blueprint/agent_generator/docs/concepts/observability.md index 8bd90764..5e7808e2 100644 --- a/src/blueprint/agent_generator/docs/concepts/observability.md +++ b/src/blueprint/agent_generator/docs/concepts/observability.md @@ -117,6 +117,12 @@ An exception propagating out of the method sets the span status to `ERROR` befor | `llm.tokens.count` | counter | Tokens consumed, by an agent's model calls. | | `llm.response.latency` | histogram | Model call duration. | +**The `topic` label is bounded.** Under Dapr the topic of a delivery is a segment of the request +path, which any caller of `/events/` chooses. A topic the agent did not declare is therefore +counted as ``; a declared one keeps its name. With `dapr_declarative_subscriptions = true` +the framework knows no topic list, and every topic counts as ``. The real topic stays in +the log line. Under NATS every topic is one the agent subscribed, so the label is always the name. + The first two are recorded on the agent's own meter provider, so they arrive with that agent's `service.name` as well as with the `agent` attribute -- a dashboard can group on either, and one of them survives a collector that drops resource attributes. diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md index c6349aac..721e4bcb 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md @@ -464,7 +464,10 @@ group's to set. **Dapr.** A group has one Dapr endpoint, which publishes the union of every agent's topics and fans each delivery out to the agents that declared it; the single acknowledgement is their combination. So a retry asked for by one agent redelivers to every agent in the group, and grouped Dapr therefore -wants `idempotency_enabled`. NATS has no such coupling -- each agent has its own subscription. +wants `idempotency_enabled`; startup warns about a shared topic while an agent declaring it has it off. +Each agent receives its own copy of the event, so what one handler changes on it the next does not +see. When one agent acknowledges and another terminates, the answer is `SUCCESS` without a reason. +NATS has no such coupling -- each agent has its own subscription. --- diff --git a/src/blueprint/agents/io/api/eventing/dapr.py b/src/blueprint/agents/io/api/eventing/dapr.py index c02629ba..36d00fa0 100644 --- a/src/blueprint/agents/io/api/eventing/dapr.py +++ b/src/blueprint/agents/io/api/eventing/dapr.py @@ -22,7 +22,7 @@ from ....models.events import CloudEvent from ..rest_api_base import RestApiBase from .dapr_response import dapr_status -from .event_handling_base import EventHandlingBase +from .event_handling_base import UNDECLARED_TOPIC_LABEL, EventHandlingBase logger = logging.getLogger(__name__) @@ -44,6 +44,10 @@ class DaprDeliveryRoute(APIRoute): def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: handle = super().get_route_handler() + # Only the delivery route (N5): route_class applies to every route of the router, and a + # malformed request to anything else -- /dapr/subscribe -- is a client error, not a delivery. + if not self.path.endswith("/events/{topic}"): + return handle async def drop_unparseable_delivery(request: Request) -> Response: try: @@ -126,6 +130,9 @@ def __init__(self) -> None: # The client per agent, not one client: this endpoint is shared by the process, and # the clients are not. Populated in on_startup; empty when no agent declared a topic. self._clients: dict[str, DaprClient] = {} + # Each agent's declared topics, read once in on_startup for the metric label (S9); + # None until then, when the handlers are read on demand. + self._declared_by_agent: dict[str, frozenset[str]] | None = None async def on_startup(self) -> None: """Hand each agent's topics to that agent's client, for readiness reporting. @@ -139,9 +146,11 @@ async def on_startup(self) -> None: what makes ``readiness_policy = "critical"`` unusable. """ topics_by_agent = self._topics_by_agent() + self._declared_by_agent = {namespace: frozenset(topics) for namespace, topics in topics_by_agent.items()} if not topics_by_agent: logger.debug("DaprEventing: no handler declared a topic; nothing to report as ready") return + self._warn_about_shared_topics(topics_by_agent) for namespace, topics in topics_by_agent.items(): client = self.registry.get_component(DaprClient, namespace=namespace) @@ -158,6 +167,43 @@ async def on_startup(self) -> None: async def on_shutdown(self) -> None: pass + def _warn_about_shared_topics(self, topics_by_agent: dict[str, list[str]]) -> None: + """Warn about a topic two agents declare while one of them does not deduplicate (S5). + + There is one delivery for both, and so one answer: a retry asked for by one agent + redelivers the event to every agent of the topic, and one that does not deduplicate runs + it again. + """ + sharing: dict[str, list[str]] = {} + for namespace, topics in topics_by_agent.items(): + for topic in topics: + sharing.setdefault(topic, []).append(namespace) + for topic, namespaces in sharing.items(): + if len(namespaces) < 2: + continue + repeating = [ns or ROOT_LABEL for ns in namespaces if not self.config.for_namespace(ns).get("idempotency_enabled", False)] + if repeating: + logger.warning( + "Topic '%s' is declared by agents %s, and Dapr delivers it once for all of them: a retry asked for " + "by one redelivers it to every one, and %s run it again because 'idempotency_enabled' is off.", + topic, + ", ".join(ns or ROOT_LABEL for ns in namespaces), + ", ".join(repeating), + ) + + def _metric_topic(self, namespace: str, topic: str) -> str: + """The topic for a declared one, :data:`UNDECLARED_TOPIC_LABEL` otherwise (S9, plan D6). + + With ``dapr_declarative_subscriptions`` the framework knows no topic list, so every topic + counts as undeclared. + """ + if self.config.get("dapr_declarative_subscriptions", False): + return UNDECLARED_TOPIC_LABEL + declared = self._declared_by_agent + if declared is None: + declared = {ns: frozenset(topics) for ns, topics in self._topics_by_agent().items()} + return topic if topic in declared.get(namespace, frozenset()) else UNDECLARED_TOPIC_LABEL + def _make_event_callback(self, topic: str) -> DeliveryCallback: """Return an async callback that routes an incoming Dapr event through the handler chain. @@ -316,8 +362,11 @@ async def publish(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[str, A namespace or ROOT_LABEL, ) continue + # Each agent its own copy (S5): handlers receive the object itself, so one that + # annotated or trimmed the event changed what the next agent read. + delivered = cloud_event.model_copy(deep=True) if len(agents) > 1 else cloud_event try: - await self._process_cloud_event(cloud_event, {"dapr_topic": topic}, topic, namespace=namespace) + await self._process_cloud_event(delivered, {"dapr_topic": topic}, topic, namespace=namespace) dispositions.append(DeliveryDisposition.ACK) except Exception as exc: disposition = disposition_for(exc) @@ -348,7 +397,9 @@ async def publish(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[str, A dapr_status(combined), ) # An unmatched event acknowledges like any other completed dispatch; the accounting - # that keeps it visible lives in _process_cloud_event, shared with the NATS edge. - if reason is None: + # that keeps it visible lives in _process_cloud_event, shared with the NATS edge. A + # SUCCESS carries no reason (N5): one agent's TERM is not the delivery's outcome when + # another acknowledged it. + if reason is None or combined is DeliveryDisposition.ACK: return {"status": dapr_status(combined)} return {"status": dapr_status(combined), "reason": reason} diff --git a/src/blueprint/agents/io/api/eventing/event_handling_base.py b/src/blueprint/agents/io/api/eventing/event_handling_base.py index 714c2a22..f04a9242 100644 --- a/src/blueprint/agents/io/api/eventing/event_handling_base.py +++ b/src/blueprint/agents/io/api/eventing/event_handling_base.py @@ -25,6 +25,13 @@ DUPLICATE_EVENTS_COUNTER = "blueprint.events.duplicate" SKIPPED_EVENTS_COUNTER = "blueprint.events.skipped" +UNDECLARED_TOPIC_LABEL = "" +"""The ``topic`` label of a delivery on a topic its agent did not declare (S9, plan D6). + +Under Dapr the topic is a URL path segment, so a caller choosing one per request would mint one +time series per request. Declared topics keep their name; the real one stays in the log line. +""" + _COUNTER_DESCRIPTIONS = { UNHANDLED_EVENTS_COUNTER: "Events an agent received and found nothing to do with", DUPLICATE_EVENTS_COUNTER: "Events an agent recognised as already processed and did not dispatch", @@ -138,4 +145,12 @@ def _count(self, name: str, namespace: str, topic: str) -> None: if counter is None: counter = agent_meter(namespace, __name__).create_counter(name=name, description=_COUNTER_DESCRIPTIONS[name], unit="{event}") counters[(name, namespace)] = counter - counter.add(1, {"agent": namespace or ROOT_LABEL, "topic": topic}) + counter.add(1, {"agent": namespace or ROOT_LABEL, "topic": self._metric_topic(namespace, topic)}) + + def _metric_topic(self, namespace: str, topic: str) -> str: + """The ``topic`` label for a delivery: the topic itself, which a transport may narrow (S9). + + NATS delivers only on subscriptions its agents declared, so every value is bounded. Dapr + overrides this, because its topic comes from the request path. + """ + return topic diff --git a/tests/unit/agents/io/TESTS.md b/tests/unit/agents/io/TESTS.md index c768341b..36ee0809 100644 --- a/tests/unit/agents/io/TESTS.md +++ b/tests/unit/agents/io/TESTS.md @@ -13,8 +13,9 @@ Test coverage for `src/blueprint/agents/io/`. | `api/actuators/health/test_client_health.py` | `ClientHealthChecker` | `connect()` called before `health_check()`, healthy/unhealthy/mixed aggregation, empty client list | | `api/actuators/health/test_health_cache.py` | `HealthCheckCache` | Initial state, provider updates, all-healthy→UP, one-unhealthy→DOWN, exception→unhealthy component, `get_cache_age_seconds`, `get_cache_info`, start/stop idempotency | | `api/actuators/health/test_sessions_health.py` | `SessionsServiceHealthChecker` | REST API reachable→UP, `RequestError`→DOWN with details, fresh heartbeat→UP, stale heartbeat→DOWN, no heartbeat→UP (unknown), `update_heartbeat` | -| `api/eventing/test_event_handling_base.py` | `EventHandlingBase` | `_unwrap_nested_cloud_event` (via mixin) for non-dapr/dict/JSON-string/malformed-JSON/missing-fields/None data; `handle_event` PROCESSED→SUCCESS / other→RETRY; a `SKIPPED` run counted as `blueprint.events.skipped` and not as unhandled, acknowledged, with no WARNING | -| `api/eventing/test_dapr.py` | `DaprEventing` | `publish` PROCESSED→SUCCESS, no-handler→RETRY, `RetryableHandlerError`→RETRY, `InvalidEventError`→DROP, `CriticalHandlerError`→RETRY; `subscribe` returns empty dict; the reason for an exception that is not a `HandlerError` is its type name, never its text (S8); an unparseable delivery logs `body.: ` and no input value (B2). *Later coverage of this file is not itemised here.* | +| `api/eventing/test_event_handling_base.py` | `EventHandlingBase` | `_unwrap_nested_cloud_event` (via mixin) for non-dapr/dict/JSON-string/malformed-JSON/missing-fields/None data; `handle_event` PROCESSED→SUCCESS / other→RETRY; a `SKIPPED` run counted as `blueprint.events.skipped` and not as unhandled, acknowledged, with no WARNING; a topic the agent did not declare is labelled ``, and every topic is with declarative subscriptions (S9, D6) | +| `api/eventing/test_dapr.py` | `DaprEventing` | `publish` PROCESSED→SUCCESS, no-handler→RETRY, `RetryableHandlerError`→RETRY, `InvalidEventError`→DROP, `CriticalHandlerError`→RETRY; `subscribe` returns empty dict; the reason for an exception that is not a `HandlerError` is its type name, never its text (S8); an unparseable delivery logs `body.: ` and no input value (B2). Another route of a `DaprEventing` subclass still answers a malformed body with 422 (N5). *Later coverage of this file is not itemised here.* | +| `api/eventing/test_dapr_fanout.py` | `DaprEventing` in a group | routing table, subscription union, combined answer; each agent receives its own copy of the event, an ACK beside a TERM answers SUCCESS without a reason, a shared topic with dedup off warns naming the agents (S5, N5). *Earlier coverage of this file is not itemised here.* | | `api/eventing/test_nats.py` | `NatsEventing` | `subscribe`/`publish` delegate to `_client`, RuntimeError when client is None; `on_startup` fetches client, subscribes to handler-declared and config-declared topics, deduplicates, preserves handler-first order, skips when no topics; `_subscribe_to_topic` RuntimeError when client None, calls `_client.subscribe` with topic and callback | | `api/eventing/test_sessions_bus.py` | `SessionsBus` | `on_startup` validation (no config/base_url/agent_id/api_key, already started, task created); `on_shutdown` (no task, running task cancelled); `_convert_to_cloud_event` (type/id/subject/source/data); `_process_job_notification` (no handler logged, `InvalidEventError`→cancel job, cancel failure swallowed, `RetryableHandlerError`→log, 403→invalidate+retry, 403 retry failure propagates `InvalidEventError`, non-403 propagates); C4 (S18): a pause closes the job stream and a resume reopens it, a job reaching a paused agent is left pending, an agent paused before startup opens no stream, and the supervisor pauses and resumes the bus | | `api/eventing/test_sessions_startup_resilience.py` | `AppBuilder.build()` with `event_bus = "sessions"` | The lifespan completes and the root REST endpoints answer when the sessions service URL points at a closed port -- a background SSE consumer that cannot connect must not stop the application starting. Offline: the refused port is bound and released on loopback, so the failure is ECONNREFUSED rather than a timeout on every platform. Moved here from `tests/integration/` (#80), where nothing ran it diff --git a/tests/unit/agents/io/api/eventing/test_dapr.py b/tests/unit/agents/io/api/eventing/test_dapr.py index 8b9c9bab..2ed0b928 100644 --- a/tests/unit/agents/io/api/eventing/test_dapr.py +++ b/tests/unit/agents/io/api/eventing/test_dapr.py @@ -376,6 +376,29 @@ async def test_an_ordinary_endpoint_still_answers_422(self, nats_eventing: NatsE assert response.status_code == 422 + async def test_another_route_of_the_dapr_router_still_answers_422(self, mock_config: MagicMock) -> None: + """N5 -- route_class covers every route of the router, so a developer's own POST answered DROP.""" + from pydantic import BaseModel + + from blueprint.agents.io.api.rest_api_base import RestApiBase + + class Item(BaseModel): + name: str + + class WithAnEndpoint(DaprEventing): + @RestApiBase.post("/items") + async def create_item(self, item: Item) -> dict[str, str]: + return {"name": item.name} + + mock_config.get.side_effect = lambda key, default=None: default + app = FastAPI() + app.include_router(WithAnEndpoint().router) + + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://caller") as client: + response = await client.post("/items", json={"not": "an item"}) + + assert response.status_code == 422 + class TestDaprEventingOnStartup: async def test_fetches_the_client_of_each_declaring_agent(self, dapr_eventing: DaprEventing, mock_registry: MagicMock) -> None: diff --git a/tests/unit/agents/io/api/eventing/test_dapr_fanout.py b/tests/unit/agents/io/api/eventing/test_dapr_fanout.py index 1d20119e..225fd867 100644 --- a/tests/unit/agents/io/api/eventing/test_dapr_fanout.py +++ b/tests/unit/agents/io/api/eventing/test_dapr_fanout.py @@ -12,7 +12,7 @@ from pathlib import Path from typing import Any -from unittest.mock import AsyncMock +from unittest.mock import AsyncMock, MagicMock import pytest @@ -326,3 +326,59 @@ async def test_a_healthy_agent_is_unaffected(self, config: Config, calls: list[s assert answer == {"status": "SUCCESS"} assert calls == ["orders"] + + +class TestEachAgentGetsItsOwnEvent: + """S5 -- the fan-out handed one CloudEvent object to every agent, so one agent's change reached the next.""" + + async def test_a_change_by_one_agent_is_not_seen_by_the_next(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: + from blueprint.agents.io.api.eventing.dapr import DaprEventing + from blueprint.agents.models.events import CloudEvent + + mock_config.get.side_effect = lambda key, default=None: default + endpoint = DaprEventing() + endpoint._agents_for = lambda topic: ("orders", "billing") # type: ignore[method-assign] + endpoint._is_paused = lambda namespace: False # type: ignore[method-assign] + seen: list[dict] = [] + + async def process(event, context, topic, namespace=None): + seen.append(dict(event.data)) + event.data["touched_by"] = namespace + + endpoint._process_cloud_event = process # type: ignore[method-assign] + event = CloudEvent(id="e1", type="t", source="s", data={"order": 1}) + + await endpoint.publish("orders.created", event) + + assert seen == [{"order": 1}, {"order": 1}] + assert event.data == {"order": 1} + + async def test_a_term_beside_an_ack_answers_success_without_a_reason(self, mock_registry: MagicMock, mock_config: MagicMock) -> None: + """N5 -- the combined answer was SUCCESS, with the terming agent's reason attached.""" + from blueprint.agents.io.api.eventing.dapr import DaprEventing + from blueprint.agents.models.errors import InvalidEventError + from blueprint.agents.models.events import CloudEvent + + mock_config.get.side_effect = lambda key, default=None: default + endpoint = DaprEventing() + endpoint._agents_for = lambda topic: ("orders", "billing") # type: ignore[method-assign] + endpoint._is_paused = lambda namespace: False # type: ignore[method-assign] + + async def process(event, context, topic, namespace=None): + if namespace == "orders": + raise InvalidEventError(status="invalid", reason="not for orders") + + endpoint._process_cloud_event = process # type: ignore[method-assign] + + answer = await endpoint.publish("orders.created", CloudEvent(id="e1", type="t", source="s", data={})) + + assert answer == {"status": "SUCCESS"} + + def test_a_shared_topic_without_dedup_warns(self, mock_registry: MagicMock, mock_config: MagicMock, caplog) -> None: + from blueprint.agents.io.api.eventing.dapr import DaprEventing + + mock_config.get.side_effect = lambda key, default=None: default + with caplog.at_level("WARNING"): + DaprEventing()._warn_about_shared_topics({"orders": ["orders.created"], "billing": ["orders.created", "x"]}) + assert "declared by agents orders, billing" in caplog.text + assert "'idempotency_enabled' is off" in caplog.text diff --git a/tests/unit/agents/io/api/eventing/test_event_handling_base.py b/tests/unit/agents/io/api/eventing/test_event_handling_base.py index bd9435bd..8617121d 100644 --- a/tests/unit/agents/io/api/eventing/test_event_handling_base.py +++ b/tests/unit/agents/io/api/eventing/test_event_handling_base.py @@ -25,6 +25,12 @@ def _counters() -> Iterator[dict[str, MagicMock]]: yield counters +@pytest.fixture(autouse=True) +def _orders_created_is_declared(dapr_eventing: DaprEventing) -> None: + """The accounting tests count on topics their agent declared, as a real subscription has.""" + dapr_eventing._declared_by_agent = {"": frozenset({"orders.created", "orders"}), "orders": frozenset({"orders.created"})} + + # --------------------------------------------------------------------------- # _unwrap_nested_cloud_event # --------------------------------------------------------------------------- @@ -355,3 +361,24 @@ async def test_a_skip_acknowledges_and_reports_no_fault( result = await dapr_eventing.handle_event("orders", cloud_event) assert result == {"status": "SUCCESS"} assert [r for r in caplog.records if r.levelname in {"WARNING", "ERROR", "CRITICAL"}] == [] + + +class TestTheTopicLabelIsBounded: + """S9, plan D6 -- under Dapr the topic is a path segment; one label per random path is one series per request.""" + + async def test_an_undeclared_topic_is_labelled_undeclared( + self, dapr_eventing: DaprEventing, cloud_event: CloudEvent, unhandled_result: ProcessingResult + ) -> None: + dapr_eventing._dispatch_cloud_event = AsyncMock(return_value=unhandled_result) # type: ignore[method-assign] + with _counters() as counters: + await dapr_eventing._process_cloud_event(cloud_event, {}, "random-a8f3") + counters[UNHANDLED_EVENTS_COUNTER].add.assert_called_once_with(1, {"agent": "", "topic": ""}) + + async def test_with_declarative_subscriptions_every_topic_is_undeclared( + self, dapr_eventing: DaprEventing, mock_config: MagicMock, cloud_event: CloudEvent, unhandled_result: ProcessingResult + ) -> None: + mock_config.get.side_effect = lambda key, default=None: True if key == "dapr_declarative_subscriptions" else default + dapr_eventing._dispatch_cloud_event = AsyncMock(return_value=unhandled_result) # type: ignore[method-assign] + with _counters() as counters: + await dapr_eventing._process_cloud_event(cloud_event, {}, "orders.created") + counters[UNHANDLED_EVENTS_COUNTER].add.assert_called_once_with(1, {"agent": "", "topic": ""}) diff --git a/tests/unit/agents/io/api/eventing/test_sessions_startup_resilience.py b/tests/unit/agents/io/api/eventing/test_sessions_startup_resilience.py index 8580beb0..9bacc5c4 100644 --- a/tests/unit/agents/io/api/eventing/test_sessions_startup_resilience.py +++ b/tests/unit/agents/io/api/eventing/test_sessions_startup_resilience.py @@ -122,6 +122,6 @@ def _run() -> None: "SessionsBus.on_startup did not run — its 'connected' log line is missing. " "Test would pass trivially if on_startup were a no-op; that defeats the point." ) - assert any("Lifecycle component SessionsBus startup completed" in rec.getMessage() for rec in caplog.records), ( - "AppBuilder lifespan never awaited SessionsBus.on_startup." - ) + assert any( + "Lifecycle component SessionsBus startup completed" in rec.getMessage() for rec in caplog.records + ), "AppBuilder lifespan never awaited SessionsBus.on_startup." From 44d7d924ecb82131ca52913ab0cb4509eb5268da Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:15:03 +0200 Subject: [PATCH 118/133] fix(telemetry): the shared exporter is closed by the last provider; agents keep their names Step 17 (S22, W1, D17): shutdown agents first, root last, in the lifespan. Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 11 + ...26-08-28-multi-agent-grouping-changelog.md | 8 + .../docs/concepts/observability.md | 14 +- src/blueprint/agents/app_builder.py | 7 + .../agents/io/telemetry/providers.py | 27 +++ .../agents/io/telemetry/telemetry.py | 153 ++++++++++++-- .../app_builder/test_standalone_readiness.py | 16 ++ tests/unit/agents/io/TESTS.md | 2 +- .../agents/io/telemetry/test_telemetry.py | 195 ++++++++++++++++++ 9 files changed, 409 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c22eace7..b7aa6e11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,17 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **A group's telemetry is no longer cut off at shutdown.** All agents share one span processor + and one metric exporter, and the first provider to shut down closed them for every other: the + remaining agents' final metrics were dropped ("Exporter already shutdown"). They are now closed by + the last provider, and the application's shutdown flushes every provider after its components + have stopped -- agents first, the root last. Measured against a collector: 2 of 4 final metric + points arrived before, 4 of 4 now. + +- **In a group, `OTEL_SERVICE_NAME` no longer names every agent alike.** The agents keep their own + name as `service.name`; the variable names the root's telemetry, as standalone. Startup logs a + WARNING naming the value. `OTEL_RESOURCE_ATTRIBUTES` is unchanged. + - **Grouped Dapr: each agent gets its own copy of a delivery, and the answer has no stray reason.** The fan-out handed one `CloudEvent` object to every agent declaring the topic, so a change one handler made to it reached the next. A delivery one agent acknowledged and another terminated diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 92f75f63..9427953d 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,14 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 17, telemetry (S22, W1, D17): `_SharedSpanProcessor` and `_SharedMetricExporter` count their + providers and are closed by the last; providers built with `shutdown_on_exit=False`; + `providers.shutdown_providers()` (agents first, root last) from `TelemetryManager.on_shutdown` at the + end of the lifespan and once from atexit; in a group an agent keeps `service.name` although + `OTEL_SERVICE_NAME` is set, with one WARNING. Live (group 'orders' + 'billing', OTLP collector with a + file exporter, OTEL_SERVICE_NAME set, a span and a counter in each handler's on_startup and + on_shutdown): 4 of 4 metric points and 4 spans under 'orders'/'billing'. Control: everything under + 'platform-wide', 2 of 4 metric points, four 'Exporter already shutdown' warnings. - Step 16, Dapr hardening (S5, S9, N5, D6): a deep copy of the CloudEvent per agent when a delivery fans out to more than one; a startup WARNING for a shared topic with an agent's `idempotency_enabled` off; `EventHandlingBase._metric_topic` hook, Dapr labels an undeclared topic ``; an ACK combined diff --git a/src/blueprint/agent_generator/docs/concepts/observability.md b/src/blueprint/agent_generator/docs/concepts/observability.md index 5e7808e2..a5be0e5d 100644 --- a/src/blueprint/agent_generator/docs/concepts/observability.md +++ b/src/blueprint/agent_generator/docs/concepts/observability.md @@ -48,9 +48,11 @@ its own resource: **What the deployment declares wins.** A key set in `OTEL_RESOURCE_ATTRIBUTES` (or `service.name` in `OTEL_SERVICE_NAME`) is used exactly as declared; the framework sets only the -attributes the deployment left out, and never replaces a declared one. In a group, declaring -`service.name` this way gives every agent the same name -- the deployment's choice, not the -framework's. +attributes the deployment left out, and never replaces a declared one. **One exception:** in a +group, `OTEL_SERVICE_NAME` names the root's telemetry only, and every agent keeps its own name as +`service.name` -- one name for all of them would make their telemetry impossible to tell apart. +Startup logs a WARNING naming the value. A `service.name` in `OTEL_RESOURCE_ATTRIBUTES` is left as +declared, and gives every agent that name -- the deployment's choice, not the framework's. So an agent called `orders` reports `service.name = "orders"` whether it runs alone or beside nineteen others, and a dashboard keyed on it cannot tell which. A single-agent application keeps @@ -61,6 +63,12 @@ thread whatever the group size, since the resource travels on the span rather th processor. Metric readers cannot be shared (the SDK binds a reader to the provider that registered it), so each provider gets its own reader over the one shared exporter. +**Shutdown.** The application's shutdown flushes and shuts down every provider after all +components have stopped, the agents first and the root last, so what an agent records in its own +`on_shutdown` is still exported. The shared exporter and span processor are closed by the last +provider to shut down, not the first. A process that never runs the shutdown gets the same at +interpreter exit. + The root's provider is also installed as the global one, so every module-level `trace.get_tracer(...)` -- in this framework, and in any library -- resolves exactly as it did before agents had identities. diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index 393cdc3e..60ebaa7c 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -1765,6 +1765,13 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: # interpreter alive past the point the container was asked to stop. registry.shutdown_executors() + # Telemetry after everything that could still record, so the last spans and metrics + # are exported; the agents' providers first, the root's last (S22). + try: + await self._telemetry_manager.on_shutdown() + except Exception as e: + logger.warning("Failed to shut down OpenTelemetry: %s", e) + logger.info("Application shutdown completed") return lifespan diff --git a/src/blueprint/agents/io/telemetry/providers.py b/src/blueprint/agents/io/telemetry/providers.py index 7e417a1f..b69188af 100644 --- a/src/blueprint/agents/io/telemetry/providers.py +++ b/src/blueprint/agents/io/telemetry/providers.py @@ -11,10 +11,14 @@ namespace's tracer" and gets one whether or not anything configured it. """ +import logging + from opentelemetry import metrics, trace from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.trace import TracerProvider +logger = logging.getLogger(__name__) + _TRACER_PROVIDERS: dict[str, TracerProvider] = {} """The configured tracer provider per namespace, written once during startup.""" @@ -87,6 +91,29 @@ def configured_namespaces() -> tuple[str, ...]: return tuple(_TRACER_PROVIDERS) +def shutdown_providers() -> None: + """Flush and shut down every configured provider: the agents first, the root last (S22). + + The providers are built without an ``atexit`` hook of their own, because the interpreter + runs those in reverse creation order and the root -- built first -- would not be last by + design but by accident. Run by the lifespan's shutdown, and by one ``atexit`` hook as the + fallback for a process that never reaches it; a second call finds nothing left to shut down. + + The root goes last because it is the global provider: whatever an agent's shutdown still + records through a module-level tracer or meter lands there. A provider that fails to shut + down is logged and the rest still are. + """ + for namespace in [ns for ns in _TRACER_PROVIDERS if ns] + [ns for ns in _TRACER_PROVIDERS if not ns]: + providers = (_TRACER_PROVIDERS.pop(namespace), _METER_PROVIDERS.pop(namespace, None)) + for provider in providers: + if provider is None: + continue + try: + provider.shutdown() + except Exception as exc: + logger.warning("Shutting down the telemetry of agent '%s' failed: %s", namespace or "", exc) + + def reset_providers() -> None: """Forget every configured provider. diff --git a/src/blueprint/agents/io/telemetry/telemetry.py b/src/blueprint/agents/io/telemetry/telemetry.py index 5506b5d5..445698d6 100644 --- a/src/blueprint/agents/io/telemetry/telemetry.py +++ b/src/blueprint/agents/io/telemetry/telemetry.py @@ -14,7 +14,9 @@ ======================== ====================================================================== A key the deployment declares in ``OTEL_RESOURCE_ATTRIBUTES`` or ``OTEL_SERVICE_NAME`` is never -replaced -- see :func:`_framework_attributes`. +replaced -- see :func:`_framework_attributes` -- with one exception: in a group, an agent keeps its +own ``service.name`` although ``OTEL_SERVICE_NAME`` is set (W1, plan D17). That variable names one +service, and taken for every agent it would make the group's agents indistinguishable. **The empty namespace is the one that must not regress.** Implemented naively -- one provider, ``service.name`` set to the group -- every existing dashboard would go dark on the day the @@ -27,10 +29,16 @@ for no gain -- the resource is attached to the span at creation, not at export. The same processor object is therefore added to every provider. Metric readers cannot be shared the same way: the SDK binds a reader to the provider that registered it, so each provider gets its own -reader over the one shared exporter. +reader over the one shared exporter. Both shared objects count their providers and are shut down +by the last one (S22): a provider's shutdown shuts down what it holds, and the first agent to +stop would otherwise have closed the export for every other one. """ +import asyncio +import atexit import logging +import os +import threading from collections.abc import Sequence from typing import Any @@ -39,20 +47,93 @@ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor from opentelemetry.sdk.metrics import MeterProvider -from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader +from opentelemetry.sdk.metrics.export import MetricExporter, MetricExportResult, MetricsData, PeriodicExportingMetricReader from opentelemetry.sdk.resources import OTELResourceDetector, Resource -from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace import ReadableSpan, Span, SpanProcessor, TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor +from opentelemetry.context import Context from ...component.namespace import ROOT_NAMESPACE from ...deployment import UNGROUPED_LABEL, UNKNOWN_POD_LABEL, deployment_group, pod_identity from ..io_base import IOBase -from .providers import has_providers, meter_provider, register_providers, tracer_provider +from .providers import has_providers, meter_provider, register_providers, shutdown_providers, tracer_provider logger = logging.getLogger(__name__) +_exit_hook_registered = False +"""Whether :func:`shutdown_providers` is registered with ``atexit`` -- once per process.""" -def _framework_attributes(service_name: str, group: str, pod: str) -> dict[str, str]: + +class _Users: + """How many providers hold a shared export object; the last to let go closes it (S22).""" + + def __init__(self) -> None: + self._count = 0 + self._lock = threading.Lock() + + def acquire(self) -> None: + with self._lock: + self._count += 1 + + def release(self) -> bool: + """Let go of it; ``True`` for the last holder, who closes it.""" + with self._lock: + self._count -= 1 + return self._count == 0 + + +class _SharedSpanProcessor(SpanProcessor): + """The process's one span processor, added to every provider and shut down by the last.""" + + def __init__(self, processor: SpanProcessor) -> None: + self._processor = processor + self._users = _Users() + + def acquire(self) -> "_SharedSpanProcessor": + self._users.acquire() + return self + + def on_start(self, span: Span, parent_context: Context | None = None) -> None: + self._processor.on_start(span, parent_context=parent_context) + + def _on_ending(self, span: Span) -> None: + self._processor._on_ending(span) + + def on_end(self, span: ReadableSpan) -> None: + self._processor.on_end(span) + + def force_flush(self, timeout_millis: int = 30000) -> bool: + return self._processor.force_flush(timeout_millis) + + def shutdown(self) -> None: + if self._users.release(): + self._processor.shutdown() + + +class _SharedMetricExporter(MetricExporter): + """The process's one metric exporter, behind every provider's reader and shut down by the last.""" + + def __init__(self, exporter: MetricExporter) -> None: + super().__init__(preferred_temporality=exporter._preferred_temporality, preferred_aggregation=exporter._preferred_aggregation) + self._exporter = exporter + self._users = _Users() + + def acquire(self) -> "_SharedMetricExporter": + self._users.acquire() + return self + + def export(self, metrics_data: MetricsData, timeout_millis: float = 10_000, **kwargs: Any) -> MetricExportResult: + return self._exporter.export(metrics_data, timeout_millis=timeout_millis, **kwargs) + + def force_flush(self, timeout_millis: float = 10_000) -> bool: + return self._exporter.force_flush(timeout_millis=timeout_millis) + + def shutdown(self, timeout_millis: float = 30_000, **kwargs: Any) -> None: + if self._users.release(): + self._exporter.shutdown(timeout_millis=timeout_millis, **kwargs) + + +def _framework_attributes(service_name: str, group: str, pod: str, own_service_name: bool = False) -> dict[str, str]: """The resource attributes the framework sets, minus every key the deployment declared. **What the deployment declares is used as it is.** ``OTEL_RESOURCE_ATTRIBUTES`` (and @@ -64,6 +145,10 @@ def _framework_attributes(service_name: str, group: str, pod: str) -> dict[str, **Only attributes that exist.** A group that is not set and a pod that cannot be told are not written as placeholders: a standalone agent's resource carries no ``deployment.group``, since it belongs to no group. + + **The one exception** is ``own_service_name``: an agent of a group keeps its own + ``service.name`` although ``OTEL_SERVICE_NAME`` is set (W1, plan D17). Every other declared key, + and all of ``OTEL_RESOURCE_ATTRIBUTES``, is left as it is. """ attributes = {"service.name": service_name} if group != UNGROUPED_LABEL: @@ -71,7 +156,7 @@ def _framework_attributes(service_name: str, group: str, pod: str) -> dict[str, if pod != UNKNOWN_POD_LABEL: attributes["service.instance.id"] = pod declared = OTELResourceDetector().detect().attributes - return {key: value for key, value in attributes.items() if key not in declared} + return {key: value for key, value in attributes.items() if key not in declared or (own_service_name and key == "service.name")} class TelemetryManager(IOBase): @@ -101,20 +186,34 @@ def configure_tracing(self, namespaces: Sequence[str] = ()) -> None: logger.info("OpenTelemetry tracing is disabled") return - span_processors = [BatchSpanProcessor(exporter) for exporter in self._build_exporters(observability)] + span_processors = [_SharedSpanProcessor(BatchSpanProcessor(exporter)) for exporter in self._build_exporters(observability)] if not span_processors: logger.warning("No trace exporters configured") return - metric_exporters = self._build_metric_exporters(observability) + metric_exporters = [_SharedMetricExporter(exporter) for exporter in self._build_metric_exporters(observability)] group = deployment_group() pod = pod_identity() + # In a group, OTEL_SERVICE_NAME names the root only (W1, plan D17): one name for + # every agent would make their telemetry impossible to tell apart. + grouped = any(namespace != ROOT_NAMESPACE for namespace in namespaces) + declared_service_name = os.environ.get("OTEL_SERVICE_NAME", "").strip() + if grouped and declared_service_name: + logger.warning( + "OTEL_SERVICE_NAME is set to '%s', which names the root's telemetry only: in a group every agent " + "keeps its own name as service.name, so its telemetry stays apart from the other agents'.", + declared_service_name, + ) # The root first and always: it is the provider that becomes global, and every # module-level trace.get_tracer() in the framework resolves through it. for namespace in (ROOT_NAMESPACE, *namespaces): if has_providers(namespace): continue - self._configure_namespace(namespace, observability.otel_service_name, group, pod, span_processors, metric_exporters) + own_service_name = bool(declared_service_name) and namespace != ROOT_NAMESPACE + self._configure_namespace( + namespace, observability.otel_service_name, group, pod, span_processors, metric_exporters, own_service_name + ) + _register_exit_hook() # The root's provider becomes the global one, so every module-level # trace.get_tracer() and metrics.get_meter() -- in this framework and in any @@ -135,8 +234,9 @@ def _configure_namespace( root_service_name: str, group: str, pod: str, - span_processors: Sequence[BatchSpanProcessor], - metric_exporters: Sequence[Any], + span_processors: Sequence[_SharedSpanProcessor], + metric_exporters: Sequence[_SharedMetricExporter], + own_service_name: bool = False, ) -> None: """Build and record the two providers for one namespace. @@ -153,21 +253,24 @@ def _configure_namespace( span_processors: The process's span processors, shared by every provider. metric_exporters: The process's metric exporters, each wrapped in a reader of this provider's own. + own_service_name: Keep ``service.name`` although ``OTEL_SERVICE_NAME`` declares one -- + an agent of a group (D17). """ service_name = root_service_name if namespace == ROOT_NAMESPACE else namespace - resource = Resource.create(_framework_attributes(service_name, group, pod)) + resource = Resource.create(_framework_attributes(service_name, group, pod, own_service_name)) - provider = TracerProvider(resource=resource) + # No atexit hook per provider: shutdown_providers() closes them in order, the root last. + provider = TracerProvider(resource=resource, shutdown_on_exit=False) for processor in span_processors: # The same processor object on every provider: one queue and one export thread, # whatever the group size. The resource travels on the span, not on the processor. - provider.add_span_processor(processor) + provider.add_span_processor(processor.acquire()) # A reader cannot be shared -- the SDK binds its collect callback to the provider that # registered it, so a shared one would only ever collect from the last provider built -- # but the exporter behind it can be. - readers = [PeriodicExportingMetricReader(exporter) for exporter in metric_exporters] - register_providers(namespace, provider, MeterProvider(resource=resource, metric_readers=readers)) + readers = [PeriodicExportingMetricReader(exporter.acquire()) for exporter in metric_exporters] + register_providers(namespace, provider, MeterProvider(resource=resource, metric_readers=readers, shutdown_on_exit=False)) if group == UNGROUPED_LABEL: logger.info("OpenTelemetry configured for service '%s'", service_name) @@ -229,10 +332,20 @@ async def on_startup(self) -> None: pass async def on_shutdown(self) -> None: - """Shutdown OpenTelemetry.""" + """Flush and shut down every provider, the root last (S22). - # OpenTelemetry does not have a shutdown method - pass + In a worker thread: each provider exports what it still holds, and against a collector + that does not answer that waits for the exporter's timeout. + """ + await asyncio.to_thread(shutdown_providers) + + +def _register_exit_hook() -> None: + """Register :func:`shutdown_providers` with ``atexit`` once, for a process that skips the lifespan.""" + global _exit_hook_registered + if not _exit_hook_registered: + atexit.register(shutdown_providers) + _exit_hook_registered = True class TracingContext: diff --git a/tests/unit/agents/app_builder/test_standalone_readiness.py b/tests/unit/agents/app_builder/test_standalone_readiness.py index d3f5fabd..55c5dae4 100644 --- a/tests/unit/agents/app_builder/test_standalone_readiness.py +++ b/tests/unit/agents/app_builder/test_standalone_readiness.py @@ -12,6 +12,7 @@ import pytest from blueprint.agents.app_builder import AppBuilder +from blueprint.agents.component.component import Component from blueprint.agents.component.namespace import namespace_scope from blueprint.agents.config import Config from blueprint.agents.io.api.actuators.health import HealthCheckerBase @@ -87,3 +88,18 @@ async def test_status_env_has_no_namespaces_key_when_standalone(config: Config) response = await client.get("/status/env") assert response.status_code == 200 assert "namespaces" not in response.json() + + +async def test_the_lifespan_shuts_telemetry_down_after_the_components(config: Config) -> None: + """S22 -- the providers were left to their atexit hooks, which closed the shared export early.""" + from unittest.mock import AsyncMock + + builder = AppBuilder(config) + app = builder.build() + order: list[str] = [] + builder._telemetry_manager.on_shutdown = AsyncMock(side_effect=lambda: order.append("telemetry")) # type: ignore[method-assign] + registry_shutdown = Component.shared_registry.shutdown_executors + Component.shared_registry.shutdown_executors = lambda: (order.append("executors"), registry_shutdown()) # type: ignore[method-assign] + async with app.router.lifespan_context(app): + pass + assert order == ["executors", "telemetry"] diff --git a/tests/unit/agents/io/TESTS.md b/tests/unit/agents/io/TESTS.md index 36ee0809..5f079ef6 100644 --- a/tests/unit/agents/io/TESTS.md +++ b/tests/unit/agents/io/TESTS.md @@ -23,7 +23,7 @@ Test coverage for `src/blueprint/agents/io/`. | `api/scheduling/test_scheduler_event_mode.py` | `SchedulerBase` through `AppBuilder.build()` | What only a built application can show: the tick topic reaches the Dapr subscription document and a CloudEvent posted to `/events/` runs `tick()` exactly once; event mode starts no in-process timer; `POST /api//trigger` is actually served (it used to be added to the router after `include_router` had copied it); in-process mode declares no tick topic and registers no eventing endpoint; a registered scheduler with no `scheduler_mode`, and event mode with no `event_bus`, each fail the build naming both values; and the pure-scheduler shapes -- publishing opted into, and nothing at all by default. Offline, and deterministic because `health_check_dapr = false` stops the Dapr health check probing for a sidecar: without it the namespace supervisor degrades the root agent and its paused transports refuse the tick. Moved here from `tests/integration/` (#80) | `api/utilities/test_cache.py` | `CacheManagementApi` | Which cache each endpoint reaches (`?name=` selecting a named cache, the default when none is given, evict clearing only the one it names) and how it fails (503 with no cache registered at all, 404 for an unknown name, the 404 listing the registered names); and the statistics payload **against real backends** -- a real `DiskCacheService` reporting its four fields, a real `RedisCacheService` over `fakeredis` reporting a different seven, and a backend whose own stats call fails answering an empty payload rather than a 500 | | `api/utilities/test_root.py` | `RootApi` | Service name/version/description from config (and defaults when `None`); both/one/neither doc links rendered; non-`APIRoute` routes skipped; `GET` route → direct link; non-`GET` route with `docs_url` → Swagger anchor link, without `docs_url` → plain path; route summary and sorted methods in row; cache hit skips config on second call | -| `telemetry/test_telemetry.py` | `TelemetryManager`, `TracingContext` | `configure_tracing` raises when config None, no-op when disabled, creates TracerProvider when enabled; `_build_exporters` OTLP/empty; `TracingContext` span lifecycle + attribute filtering | +| `telemetry/test_telemetry.py` | `TelemetryManager`, `TracingContext` | `configure_tracing` raises when config None, no-op when disabled, creates TracerProvider when enabled; `_build_exporters` OTLP/empty; `TracingContext` span lifecycle + attribute filtering; a span and a metric recorded after one agent's provider shut down are still exported, the shared exporter is shut down once, by the last provider, and no provider has an atexit hook (S22); `shutdown_providers` shuts the root last, runs once, survives a failing provider; the manager runs it off the event loop; in a group the agents keep `service.name` under `OTEL_SERVICE_NAME` with one WARNING, standalone unchanged (W1, D17) | --- diff --git a/tests/unit/agents/io/telemetry/test_telemetry.py b/tests/unit/agents/io/telemetry/test_telemetry.py index ee33d273..04706478 100644 --- a/tests/unit/agents/io/telemetry/test_telemetry.py +++ b/tests/unit/agents/io/telemetry/test_telemetry.py @@ -294,3 +294,198 @@ def _raise() -> str: monkeypatch.setattr("blueprint.agents.deployment.socket.gethostname", _raise) configure() assert self._attributes("").get("service.instance.id") != "" + + +class _RecordingMetricExporter: + """A metric exporter that remembers what it exported, and what arrived after its shutdown.""" + + def __init__(self) -> None: + from opentelemetry.sdk.metrics.export import MetricExporter + + class _Exporter(MetricExporter): + def __init__(inner) -> None: + super().__init__() + inner.exported = 0 + inner.after_shutdown = 0 + inner.shutdowns = 0 + + def export(inner, metrics_data, timeout_millis: float = 10_000, **kwargs): # type: ignore[no-untyped-def] + from opentelemetry.sdk.metrics.export import MetricExportResult + + if inner.shutdowns: + inner.after_shutdown += 1 + return MetricExportResult.FAILURE + inner.exported += 1 + return MetricExportResult.SUCCESS + + def force_flush(inner, timeout_millis: float = 10_000) -> bool: + return True + + def shutdown(inner, timeout_millis: float = 30_000, **kwargs) -> None: # type: ignore[no-untyped-def] + inner.shutdowns += 1 + + self.exporter = _Exporter() + + +class TestTheSharedExportOutlivesOneProvider: + """S22 -- the shared exporter and span processor were closed by the first provider that shut down.""" + + @pytest.fixture + def configure(self, telemetry_manager: TelemetryManager, mock_config: MagicMock, enabled_observability: ObservabilityConfig): + from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter + + spans = InMemorySpanExporter() + metrics = _RecordingMetricExporter().exporter + + def _configure(*namespaces: str): # type: ignore[no-untyped-def] + mock_config.get_observability_config.return_value = enabled_observability + with ( + patch.object(telemetry_manager, "_build_exporters", return_value=[spans]), + patch.object(telemetry_manager, "_build_metric_exporters", return_value=[metrics]), + patch.object(telemetry_manager, "_setup_instrumentation"), + ): + telemetry_manager.configure_tracing(namespaces) + return spans, metrics + + return _configure + + def test_a_span_ended_after_one_agent_shut_down_is_still_exported(self, configure) -> None: + spans, _ = configure("orders", "billing") + tracer_provider("orders").shutdown() + + tracer_provider("billing").get_tracer("probe").start_span("after-orders-stopped").end() + tracer_provider("billing").force_flush() + + assert [span.name for span in spans.get_finished_spans()] == ["after-orders-stopped"] + + def test_the_metric_exporter_survives_until_the_last_provider(self, configure) -> None: + from blueprint.agents.io.telemetry.providers import meter_provider + + _, metrics = configure("orders", "billing") + meter_provider("orders").shutdown() + assert metrics.shutdowns == 0 + + meter_provider("billing").get_meter("probe").create_counter("probe.count").add(1) + meter_provider("billing").force_flush() + assert metrics.after_shutdown == 0 + + meter_provider("billing").shutdown() + meter_provider("").shutdown() + assert metrics.shutdowns == 1 + + def test_no_provider_shuts_itself_down_at_exit(self, configure) -> None: + """The framework shuts them down in order (agents, then the root); an atexit hook each would not.""" + from blueprint.agents.io.telemetry.providers import meter_provider + + configure("orders") + for namespace in ("", "orders"): + assert tracer_provider(namespace)._atexit_handler is None + assert meter_provider(namespace)._atexit_handler is None + + +class TestShutdownProviders: + """S22 -- every provider is flushed and shut down by the framework, the root last.""" + + @staticmethod + def _register(*namespaces: str) -> list[str]: + from opentelemetry.sdk.metrics import MeterProvider + from opentelemetry.sdk.trace import TracerProvider + + from blueprint.agents.io.telemetry.providers import register_providers + + order: list[str] = [] + for namespace in namespaces: + tracers, meters = TracerProvider(shutdown_on_exit=False), MeterProvider(shutdown_on_exit=False) + tracers.shutdown = lambda ns=namespace: order.append(f"traces:{ns}") # type: ignore[method-assign] + meters.shutdown = lambda ns=namespace, **_: order.append(f"metrics:{ns}") # type: ignore[method-assign] + register_providers(namespace, tracers, meters) + return order + + def test_the_root_is_shut_down_last(self) -> None: + from blueprint.agents.io.telemetry.providers import shutdown_providers + + order = self._register("", "orders", "billing") + shutdown_providers() + assert order[-2:] == ["traces:", "metrics:"] + assert sorted(order[:-2]) == ["metrics:billing", "metrics:orders", "traces:billing", "traces:orders"] + + def test_it_runs_once(self) -> None: + from blueprint.agents.io.telemetry.providers import shutdown_providers + + order = self._register("", "orders") + shutdown_providers() + shutdown_providers() + assert len(order) == 4 + assert configured_namespaces() == () + + def test_one_failing_provider_does_not_stop_the_rest(self, caplog: pytest.LogCaptureFixture) -> None: + from blueprint.agents.io.telemetry.providers import shutdown_providers, tracer_provider as provider_of + + order = self._register("", "orders") + + def _fail() -> None: + raise RuntimeError("collector gone") + + provider_of("orders").shutdown = _fail # type: ignore[method-assign] + with caplog.at_level("WARNING"): + shutdown_providers() + assert order == ["metrics:orders", "traces:", "metrics:"] + assert "collector gone" in caplog.text + + async def test_the_manager_shuts_them_down_off_the_event_loop(self, telemetry_manager: TelemetryManager) -> None: + import threading + + threads: list[int] = [] + with patch("blueprint.agents.io.telemetry.telemetry.shutdown_providers", lambda: threads.append(threading.get_ident())): + await telemetry_manager.on_shutdown() + assert len(threads) == 1 + assert threads[0] != threading.get_ident() + + +class TestOtelServiceNameInAGroup: + """W1, plan D17 -- OTEL_SERVICE_NAME named every agent of a group alike; the agents keep their own names.""" + + @pytest.fixture + def configure(self, telemetry_manager: TelemetryManager, mock_config: MagicMock, enabled_observability: ObservabilityConfig): + def _configure(*namespaces: str) -> None: + mock_config.get_observability_config.return_value = enabled_observability + with ( + patch.object(telemetry_manager, "_build_exporters", return_value=[MagicMock()]), + patch.object(telemetry_manager, "_build_metric_exporters", return_value=[]), + patch.object(telemetry_manager, "_setup_instrumentation"), + ): + telemetry_manager.configure_tracing(namespaces) + + return _configure + + @staticmethod + def _name(namespace: str) -> object: + provider = tracer_provider(namespace) + assert provider is not None + return provider.resource.attributes["service.name"] + + def test_the_agents_keep_their_names_and_the_root_takes_it( + self, configure, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture + ) -> None: + monkeypatch.setenv("OTEL_SERVICE_NAME", "platform-wide") + with caplog.at_level("WARNING"): + configure("orders", "billing") + assert [self._name(ns) for ns in ("", "orders", "billing")] == ["platform-wide", "orders", "billing"] + warnings = [r.getMessage() for r in caplog.records if r.levelname == "WARNING" and r.name.startswith("blueprint")] + assert len(warnings) == 1 + assert "'platform-wide'" in warnings[0] + + def test_other_declared_attributes_still_reach_the_agents(self, configure, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("OTEL_SERVICE_NAME", "platform-wide") + monkeypatch.setenv("OTEL_RESOURCE_ATTRIBUTES", "deployment.environment=prod") + configure("orders") + provider = tracer_provider("orders") + assert provider is not None + assert provider.resource.attributes["deployment.environment"] == "prod" + + def test_standalone_is_unchanged(self, configure, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture) -> None: + monkeypatch.setenv("OTEL_SERVICE_NAME", "platform-wide") + with caplog.at_level("WARNING"): + configure() + assert self._name("") == "platform-wide" + assert [r for r in caplog.records if r.levelname == "WARNING" and r.name.startswith("blueprint")] == [] From 3c7160e77afa18625c8d6622bf4c821056aba6f9 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:15:04 +0200 Subject: [PATCH 119/133] fix(nats): refuse a durable that filters another subject; free the run slot; log an unset ack_wait Step 18 (S1, W4, W5, N10). Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 11 +++ ...26-08-28-multi-agent-grouping-changelog.md | 8 +++ .../docs/reference/configuration-keys.md | 2 +- .../agents/clients/io/nats_client.py | 69 ++++++++++++------ tests/unit/agents/clients/TESTS.md | 2 +- .../agents/clients/io/test_nats_client.py | 72 +++++++++++++++++++ 6 files changed, 141 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b7aa6e11..687f288f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,17 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **A JetStream consumer that filters another subject is no longer bound.** Root topic + `orders-created` and agent `orders` on topic `created` derive the same durable name + (`orders-created-durable`). Whichever started second bound the other's consumer with only a + drift warning, and received that topic's messages in its own handler. It now refuses to bind: + the subscription fails with an error naming the consumer, its filter and the topic, and the + connection retries. Rename one of the topics. + +- **The "Created JetStream consumer" line is logged when `nats_ack_wait` is unset.** It formatted + the unset value with `%.1f`, so the line was lost to a logging error; it now reads + `ack_wait server default`. A delivery whose run could not be started no longer keeps its run slot. + - **A group's telemetry is no longer cut off at shutdown.** All agents share one span processor and one metric exporter, and the first provider to shut down closed them for every other: the remaining agents' final metrics were dropped ("Exporter already shutdown"). They are now closed by diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 9427953d..ca981d99 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,14 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 18, NATS leftovers (S1, W4, W5, N10): `_ensure_consumer` raises `JetStreamBindingError` for an existing + durable whose filter is not the topic (no rename); the run slot and in-flight count are given back when the + run cannot be started; `_durable_for` docstring corrected (dotted topics get a name 0.8 did not use); the + consumer INFO line renders an unset `ack_wait` as `server default`. Live (JetStream 2.10 in WSL): a consumer + 'orders-created-durable' filtering 'created' was refused for root topic 'orders-created', and a message on + 'created' did not reach its handler; the INFO line was logged. Control: bound, the 'created' message reached + the 'orders-created' handler, the INFO line was lost to `TypeError: must be real number, not NoneType`. + Found N12 (readiness UP while the agent is paused by its own failing subscription), left open as D21. - Step 17, telemetry (S22, W1, D17): `_SharedSpanProcessor` and `_SharedMetricExporter` count their providers and are closed by the last; providers built with `shutdown_on_exit=False`; `providers.shutdown_providers()` (agents first, root last) from `TelemetryManager.on_shutdown` at the diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index e199beac..8a761f88 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -105,7 +105,7 @@ from, so it is validated once, where it enters the framework, and never rewritte | Rule | Reason | |-----|-------------| | `""` (root) or `[a-z][a-z0-9_]*` | The namespace becomes a registry key prefix, a NATS queue group, part of a JetStream durable name and a telemetry service name. The alphabet is the intersection of what those accept. | -| No `-` | `-` separates the fields of the durable name `--durable`. Allowing it makes that name ambiguous: `orders-eu` on `created` and `orders` on `eu-created` would be one consumer, so two agents would consume each other's events. Use `_`. | +| No `-` | `-` separates the fields of the durable name `--durable`. Allowing it makes that name ambiguous: `orders-eu` on `created` and `orders` on `eu-created` would be one consumer, so two agents would consume each other's events. Use `_`. The root has no namespace field, so root topic `orders-created` and agent `orders` on `created` still derive one name: the second to start finds a consumer filtering another subject and refuses to bind it (startup retries and logs why). Rename one of the topics. | | No `.`, `*`, `>` | Subject separator and wildcards; illegal in a NATS consumer name. | | No `<`, `>` | Reserved for the connection-name placeholders above. | | No surrounding whitespace | Not trimmed for you: the trimmed and untrimmed forms would be one agent registered under one name and subscribed under another. | diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 06d35b98..0d3a74cc 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -1457,11 +1457,18 @@ def _durable_for(self, topic: str) -> str: A namespaced client puts its namespace in front, for the same reason its queue group is the namespace (C1): two co-hosted agents subscribing to one topic each need their own consumer, or the broker hands every message to whichever of them - binds first. The root namespace keeps the bare ``-durable``, so no existing - consumer is renamed and no deployment of this change becomes a consumer migration. - - The result -- ``orders-orders_created-durable`` for namespace ``orders`` on topic - ``orders.created`` -- reads back unambiguously because ``-`` is excluded from the + binds first. The root namespace keeps the bare ``-durable``, so a topic + without ``.``, ``*``, ``>`` or whitespace finds the consumer 0.8 created under the same + name. A dotted topic gets a name 0.8 did not use (``orders_created-durable``), but + 0.8's ``orders.created-durable`` is one the broker refuses, so no consumer is orphaned. + + The namespace and the topic share no reserved separator: root topic ``orders-created`` + and agent ``orders`` on ``created`` derive one name. :meth:`_ensure_consumer` refuses to + bind a durable whose filter is another subject (S1), so such a clash fails loudly + instead of delivering one subscription's messages to the other. + + For two agents, ``orders-orders_created-durable`` for namespace ``orders`` on topic + ``orders.created`` reads back unambiguously because ``-`` is excluded from the namespace alphabet: the first ``-`` is always the boundary between the namespace and the topic. Were it allowed, ``orders-eu`` on ``created`` and ``orders`` on ``eu-created`` would name one consumer and two agents would share it. @@ -2369,17 +2376,30 @@ async def _ensure_consumer(self, topic: str, durable: str) -> js_api.ConsumerCon await js.add_consumer(stream, config=desired) logger.info( "Created JetStream consumer '%s' on stream '%s': filter '%s', deliver group '%s', " - "ack_wait %.1fs, max_ack_pending %s, max_deliver %s", + "ack_wait %s, max_ack_pending %s, max_deliver %s", durable, stream, topic, desired.deliver_group, - desired.ack_wait, + # Unset is None, which '%.1f' cannot render: the whole line was lost (N10). + "server default" if desired.ack_wait is None else f"{desired.ack_wait:.1f}s", desired.max_ack_pending, desired.max_deliver, ) return desired + filters = [info.config.filter_subject] if info.config.filter_subject else list(info.config.filter_subjects or []) + if filters != [topic]: + # Another subscription's consumer under this name (S1): binding to it would deliver + # that subscription's messages here. Not renamed -- the durable's pending state is + # broker-side and belongs to the subscription that made it. + raise JetStreamBindingError( + f"JetStream consumer '{durable}' on stream '{stream}' filters {', '.join(repr(f) for f in filters) or 'nothing'}, " + f"not '{topic}', so it belongs to another subscription and is not bound. A root topic and an agent's " + f"topic can derive one durable name (root 'orders-created' and agent 'orders' on 'created'): rename one " + f"of the topics, or delete the consumer if it is stale." + ) + legacy = not info.config.deliver_group if legacy: # A consumer from before 0.9: created by js.subscribe with an inbox deliver subject and @@ -2399,7 +2419,7 @@ async def _ensure_consumer(self, topic: str, durable: str) -> js_api.ConsumerCon if drift: logger.warning( "JetStream consumer '%s' on stream '%s' already exists with different settings (%s). " - "It is left unchanged: changing a durable's filter or deliver group is a migration, " + "It is left unchanged: changing a durable's deliver group is a migration, " "not a restart. Delete the consumer during a maintenance window to apply the new values.", durable, stream, @@ -2416,7 +2436,8 @@ def _consumer_drift(actual: js_api.ConsumerConfig, desired: js_api.ConsumerConfi """ return [ f"{field}: broker has {getattr(actual, field)!r}, config asks for {getattr(desired, field)!r}" - for field in ("filter_subject", "deliver_group", "ack_wait", "max_ack_pending", "max_deliver") + # Not filter_subject: a consumer filtering another subject is refused before this (S1). + for field in ("deliver_group", "ack_wait", "max_ack_pending", "max_deliver") if field not in ignore and getattr(desired, field) is not None and getattr(actual, field) != getattr(desired, field) ] @@ -2585,18 +2606,24 @@ async def message_handler(msg: Any) -> None: return release = await self._acquire_run(binding, slot_key) binding.enter_run() - dispatch = callback if callback is not None else binding.topic_callbacks[resolved] - # A run from a named connection starts in an empty context: nothing of the subscription - # task or of another run reaches it (plan N1). The default connection keeps the copied - # context it always had (N6). - context = contextvars.Context() if binding.link.name else None - run = asyncio.create_task( - self._run_delivery(msg, resolved, dispatch, binding), - name=f"nats-run-{self.namespace or ROOT_LABEL}{'-' + binding.link.name if binding.link.name else ''}", - context=context, - ) - binding.runs.add(run) - run.add_done_callback(functools.partial(self._run_finished, binding, release)) + try: + dispatch = callback if callback is not None else binding.topic_callbacks[resolved] + # A run from a named connection starts in an empty context: nothing of the subscription + # task or of another run reaches it (plan N1). The default connection keeps the copied + # context it always had (N6). + context = contextvars.Context() if binding.link.name else None + run = asyncio.create_task( + self._run_delivery(msg, resolved, dispatch, binding), + name=f"nats-run-{self.namespace or ROOT_LABEL}{'-' + binding.link.name if binding.link.name else ''}", + context=context, + ) + binding.runs.add(run) + run.add_done_callback(functools.partial(self._run_finished, binding, release)) + except BaseException: + # No run started, so no done callback will free the slot (W4). + release() + binding.exit_run() + raise return message_handler diff --git a/tests/unit/agents/clients/TESTS.md b/tests/unit/agents/clients/TESTS.md index 2ba25ba9..a49b2010 100644 --- a/tests/unit/agents/clients/TESTS.md +++ b/tests/unit/agents/clients/TESTS.md @@ -13,7 +13,7 @@ Test coverage for `src/blueprint/agents/clients/`. | `ai/test_openai_client.py` | `OpenAIClient` | `_is_connected`, `connect` (no-op), `close`, `subscribe`/`publish` (no-ops), `create_model`, `health_check` | | `ai/test_vllm_client.py` | `VLLMClient` | Same shape as OpenAI; additionally verifies `base_url`/`api_key` forwarding to `AsyncOpenAI` | | `io/test_dapr_client.py` | `DaprClient` | `_is_connected`, `connect`/`close`, `subscribe` (no-op), `publish` (URL, headers, routing key, pubsub name), `health_check` | -| `io/test_nats_client.py` | `NATSClient` | `__init__` defaults, `_is_connected` variants, `connect` (Core + JetStream), `close`, `publish`, `health_check`; no credential or payload value in logs (B2, S4, N3): an unparseable payload logs `loc: type` only, `_Link` and `_Binding` reprs hide URL and connect options, the default connection's failed attempt and permanent failure and a named connection's error and failed attempt log the URL redacted and no password or token; a reconnect under JetStream subscribes nothing again (nats-py replays `_subs`) and re-checks stream and consumers, a failed re-check leaves it unready (M1); a paused agent naks a JetStream delivery without running it and still runs a buffered Core NATS one (N4); the first connect is bounded while reconnects stay unlimited, and fails against a closed port instead of hanging (N11); a failed resume stays paused and retries in the background, dropping what each failed attempt subscribed, until it succeeds; a pause or close stops the retry; supervisor and client together recover from a failed resume after one health transition (M2); runtime changes: a second change before the first bound, and a removal before the change bound, retire the link still delivering (M3); a reconnect restores readiness only for a bound binding; binding mode: a subscription refused in the round trip (lowercased, as nats-py hands it on) fails the bind and is unsubscribed (M4); a flow control request is answered and a heartbeat dropped, neither run (S2); a new TLS context alone is no change (S3). *Later coverage of this file is not itemised here.* | +| `io/test_nats_client.py` | `NATSClient` | `__init__` defaults, `_is_connected` variants, `connect` (Core + JetStream), `close`, `publish`, `health_check`; no credential or payload value in logs (B2, S4, N3): an unparseable payload logs `loc: type` only, `_Link` and `_Binding` reprs hide URL and connect options, the default connection's failed attempt and permanent failure and a named connection's error and failed attempt log the URL redacted and no password or token; a reconnect under JetStream subscribes nothing again (nats-py replays `_subs`) and re-checks stream and consumers, a failed re-check leaves it unready (M1); a paused agent naks a JetStream delivery without running it and still runs a buffered Core NATS one (N4); the first connect is bounded while reconnects stay unlimited, and fails against a closed port instead of hanging (N11); a failed resume stays paused and retries in the background, dropping what each failed attempt subscribed, until it succeeds; a pause or close stops the retry; supervisor and client together recover from a failed resume after one health transition (M2); runtime changes: a second change before the first bound, and a removal before the change bound, retire the link still delivering (M3); a reconnect restores readiness only for a bound binding; binding mode: a subscription refused in the round trip (lowercased, as nats-py hands it on) fails the bind and is unsubscribed (M4); a flow control request is answered and a heartbeat dropped, neither run (S2); a new TLS context alone is no change (S3); a durable whose filter is another subject is refused, one listing exactly the topic in `filter_subjects` is bound (S1); a run that cannot be started gives its slot back (W4); the consumer line renders an unset `ack_wait` as `server default` and a set one in seconds (N10). *Later coverage of this file is not itemised here.* | | `io/test_nats_connection_source.py` | `NATSClient` with a `ConnectionSource` | Loading the source, `ConnectionSpec`, planning bindings (claims, hybrid mode, result publishing refused), runs from named connections (run scope, validation, isolation, default connection unchanged), the handler context (`nats_connection`), the delivery attempt (named run: attempt 1 and 2 with the binding's `max_deliver`; default connection: `nats_max_deliver` unset -> `None`; no JetStream metadata -> no attempt; both keys in the handler context), shutdown. *Earlier coverage was not itemised here.* | `IOClientBase` has no logic and has no test file. diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index cadf99ac..b01a1da1 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -2763,3 +2763,75 @@ async def test_a_failed_attempt_of_a_named_connection_is_logged_redacted( await nats_client._run_named_link(binding) assert "named connection 'A' attempt 1 failed" in caplog.text assert _SECRET not in caplog.text + + +class TestADurableOfAnotherTopicIsNotBound: + """S1 -- root topic 'orders-created' and agent 'orders' on 'created' name one durable; drift only warned.""" + + async def test_a_consumer_filtering_another_subject_is_refused( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + from blueprint.agents.clients.io.nats_client import JetStreamBindingError + + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders-created"]) + theirs = js_api.ConsumerConfig(durable_name="orders-created-durable", filter_subject="created", deliver_group="orders") + mock_js.consumer_info = AsyncMock(return_value=MagicMock(config=theirs)) + + with pytest.raises(JetStreamBindingError) as refused: + await nats_client._subscribe_one("orders-created", AsyncMock()) + + mock_js.subscribe_bind.assert_not_awaited() + assert "'orders-created-durable'" in str(refused.value) + assert "'created'" in str(refused.value) + assert "'orders-created'" in str(refused.value) + + async def test_a_consumer_listing_the_subject_in_filter_subjects_is_bound( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + existing = js_api.ConsumerConfig(durable_name="orders_created-durable", filter_subjects=["orders.created"], deliver_group="g") + mock_js.consumer_info = AsyncMock(return_value=MagicMock(config=existing)) + + await nats_client._subscribe_one("orders.created", AsyncMock()) + + assert mock_js.subscribe_bind.await_args.kwargs["config"] is existing + + +class TestTheRunSlotIsNotLeaked: + """W4 -- a failure between taking the slot and starting the run held the slot for good.""" + + async def test_a_run_that_cannot_be_started_frees_its_slot( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + handler = await _js_delivery_handler(nats_client, mock_config, mock_nats_jetstream, AsyncMock()) + with ( + patch.object(nats_client, "_run_delivery", new=MagicMock(side_effect=RuntimeError("cannot start"))), + pytest.raises(RuntimeError), + ): + await handler(_delivery(cloud_event)) + + assert nats_client.inflight_handlers == 0 + assert nats_client._binding.slots_for("orders.created").locked() is False + + +class TestTheConsumerLineRendersAnUnsetAckWait: + """N10 -- '%.1f' on an unset ack_wait (None) lost the whole INFO line to a logging error.""" + + async def test_the_line_is_logged_with_the_server_default( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, caplog: pytest.LogCaptureFixture + ) -> None: + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + assert nats_client._consumer_config("orders.created", "orders_created-durable").ack_wait is None + with caplog.at_level("INFO", logger="blueprint.agents.clients.io.nats_client"): + await nats_client._subscribe_one("orders.created", AsyncMock()) + created = [message for message in caplog.messages if message.startswith("Created JetStream consumer")] + assert len(created) == 1 + assert "ack_wait server default" in created[0] + + async def test_a_configured_ack_wait_is_shown_in_seconds( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, caplog: pytest.LogCaptureFixture + ) -> None: + await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"], nats_ack_wait=45.0) + with caplog.at_level("INFO", logger="blueprint.agents.clients.io.nats_client"): + await nats_client._subscribe_one("orders.created", AsyncMock()) + assert any("ack_wait 45.0s" in message for message in caplog.messages) From 823491fd1e6870d02bd33db91178320560c71ebf Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:15:05 +0200 Subject: [PATCH 120/133] fix(standalone): 0.8 shapes build again; event_loop_debug off unless set; shutdown runs to the end Step 19 (S10, S20, S21, N1). Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 29 +++++++ ...26-08-28-multi-agent-grouping-changelog.md | 9 +++ .../docs/concepts/observability.md | 17 +++-- .../agent_generator/docs/guides/deployment.md | 11 ++- src/blueprint/agents/app_builder.py | 73 ++++++------------ src/blueprint/agents/component/registry.py | 22 ++++++ .../agents/handler/sessions_job_handler.py | 10 ++- .../agents/io/api/actuators/actuator_api.py | 20 ++++- .../io/api/actuators/health/health_base.py | 3 + .../agents/io/telemetry/loop_watchdog.py | 43 ++++++----- tests/unit/agents/app_builder/TESTS.md | 2 +- .../app_builder/test_deferred_wiring.py | 20 ++--- .../app_builder/test_standalone_readiness.py | 75 +++++++++++++++++++ .../handler/test_sessions_job_handler.py | 14 ++++ .../agents/io/telemetry/test_loop_watchdog.py | 28 ++++--- 15 files changed, 267 insertions(+), 109 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 687f288f..30d59696 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,27 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **A standalone application written for 0.8 builds again** (S20). Three 0.8 shapes were refused + or changed: + - A health check of the application's own under a built-in name (`cache`, a client's name) + replaced the built-in in 0.8 and failed the build here. It replaces it again, with a WARNING. + Two checks of the application's own under one name are still refused. + - A handler instance passed after a handler class of the same priority failed the build. Every + declared handler now registers in declaration order, as 0.8 did, whether passed as a class or + as an instance. + - A `SessionsJobHandler` subclass that widened `can_handle_event` was only offered its own job + type, which it declared automatically. It declares nothing now when it overrides the selector, + and is offered every event as in 0.8. + +- **asyncio debug mode is off unless `event_loop_debug` is set** (S21). It was on by default in + development -- the default environment -- so an application that never set one paid for debug + mode on every coroutine. The watchdog runs instead. The value is read as a boolean: `"false"` + from an environment variable means false, and a value that is no boolean fails startup. + +- **Shutdown runs to the end past a failed step** (N1). A startup recovery task that had ended by + raising re-raised while shutdown cancelled it, and a failing actuator shutdown raised out of the + lifespan; either skipped every later step. Both are logged and shutdown goes on. + - **A JetStream consumer that filters another subject is no longer bound.** Root topic `orders-created` and agent `orders` on topic `created` derive the same durable name (`orders-created-durable`). Whichever started second bound the other's consumer with only a @@ -637,6 +658,14 @@ What the broker sees change when an agent that ran on 0.8 starts on this version - **Core NATS subscriptions join a queue group** (`nats_queue_group`, else `app_name`), so each message reaches one replica instead of every one. +What the code sees change: + +- **Components are constructed by `build()`, not by the `with_*()` call.** `with_handler(MyHandler)` + records the class; `build()` constructs it, in declaration order. Code that looked a component up + in the registry between a `with_*()` call and `build()` finds nothing, and an error a constructor + raises -- a missing configuration key, say -- is raised by `build()`. An instance passed to + `with_*()` is the caller's own and is used as it is. + ## [0.9.0] - 2026-09-14 **Multi-agent grouping.** How many agents share a process becomes a *deployment* parameter rather diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index ca981d99..b236ee57 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,15 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 19, standalone compatibility (S10, S20, S21, N1): `HealthCheckEntry.builtin` and an application check + replacing a built-in one with a WARNING; `Registry.reorder` puts declared handlers in declaration order (the + refusal is gone); `SessionsJobHandler.get_handled_event_types` declares nothing when `can_handle_event` is + overridden; `event_loop_debug` off unless set, read with `parse_bool`; recovery tasks gathered with + `return_exceptions=True`, `actuator.on_shutdown` guarded; CHANGELOG "What the code sees change" for deferred + construction. Live (standalone app, Core NATS in WSL, `with_handler(First)` then `with_handler(Second())`, + `with_health_checker("cache", ...)`): both handlers ran First then Second, `/health/ready` showed the own + check under 'cache' with the WARNING, debug mode off and the watchdog started. Control: build refused the + handler order, then the 'cache' name; with both fixed away, debug mode was on. - Step 18, NATS leftovers (S1, W4, W5, N10): `_ensure_consumer` raises `JetStreamBindingError` for an existing durable whose filter is not the topic (no rename); the run slot and in-flight count are given back when the run cannot be started; `_durable_for` docstring corrected (dotted topics get a name 0.8 did not use); the diff --git a/src/blueprint/agent_generator/docs/concepts/observability.md b/src/blueprint/agent_generator/docs/concepts/observability.md index a5be0e5d..03016c2e 100644 --- a/src/blueprint/agent_generator/docs/concepts/observability.md +++ b/src/blueprint/agent_generator/docs/concepts/observability.md @@ -252,7 +252,8 @@ Two agents may both call theirs `database`; they appear as `orders.database` and registration rather than silently reduced to one. The framework registers checks of its own: one per transport client, and one per declared cache -(`cache`, or `cache:` for a named one). +(`cache`, or `cache:` for a named one). A check of yours under one of those names replaces +the framework's, with a WARNING at startup -- the way to override a built-in check. ### Named NATS connections @@ -336,14 +337,14 @@ short a consumer. The one group-wide failure a process can detect about itself. A blocked loop raises nothing, logs nothing and keeps the pod live, while every agent in the group stops responding at once. -| Environment | Mechanism | +| Setting | Mechanism | |---|---| -| Development | asyncio's own debug mode, which names the exact callback and its source location. | -| Production | A watchdog that measures how much longer a known sleep actually took, and names the agents that had work in flight. | +| Default, every environment | A watchdog that measures how much longer a known sleep actually took, and names the agents that had work in flight. | +| `event_loop_debug = true` | asyncio's own debug mode, which names the exact callback and its source location. | ```toml [default] -event_loop_debug = false # defaults to true in development +event_loop_debug = false # off unless set, in every environment event_loop_slow_callback_seconds = 0.2 # debug mode's threshold event_loop_watchdog_enabled = true event_loop_watchdog_interval_seconds = 1.0 @@ -351,9 +352,9 @@ event_loop_block_threshold_seconds = 1.0 ``` Never both: debug mode already reports the callback, which is strictly better than the watchdog's -"one of these agents was busy". Setting `event_loop_debug = true` in production is available and -deliberate -- debug mode wraps coroutine creation and keeps tracebacks for every task, which is -why it is not the default there. +"one of these agents was busy". Setting `event_loop_debug = true` is a deliberate choice -- debug +mode wraps coroutine creation and keeps tracebacks for every task, which is why it is not the +default anywhere, development included. The watchdog cannot name the culprit. By the time it runs again the blocking callback has returned, so it reports the agents that have work in flight *now*, which is the set the culprit is diff --git a/src/blueprint/agent_generator/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md index 21d296de..42672f3c 100644 --- a/src/blueprint/agent_generator/docs/guides/deployment.md +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -812,14 +812,13 @@ What to watch when you turn it up: dies; it does not change which failures kill it. That is why attribution is emitted deliberately (see *Alerting on an agent*) -- and why the blast radius, not the happy path, is what should decide group size. -- **Blocking the event loop is the mistake that only hurts in a group.** In development, - `app_environment = "development"` puts asyncio in debug mode and names the slow callback itself - (`event_loop_slow_callback_seconds`, default `0.2`). In production a lower-overhead watchdog +- **Blocking the event loop is the mistake that only hurts in a group.** A low-overhead watchdog measures the loop's lag and reports which agents had work in flight when it stalled (`event_loop_block_threshold_seconds`, default `1.0`) -- candidates, not a culprit, because by - the time it runs the blocking call has returned. Debug mode is available in production behind - `event_loop_debug` at the cost of wrapping every coroutine creation, and the two are never both - on: with debug mode enabled the watchdog stands down. + the time it runs the blocking call has returned. `event_loop_debug = true` puts asyncio in debug + mode instead, which names the slow callback itself (`event_loop_slow_callback_seconds`, default + `0.2`) at the cost of wrapping every coroutine creation; it is off unless set, in development + too. The two are never both on: with debug mode enabled the watchdog stands down. - **One agent's failure should not remove the pod.** Use `critical_agents` plus `readiness_policy = "critical"` so that a non-critical agent going down is an alert rather than a pod out of rotation. diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index 60ebaa7c..e53b29d8 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -1,7 +1,6 @@ """Generic FastAPI application setup and configuration.""" import asyncio -import contextlib import copy import logging import signal @@ -877,11 +876,7 @@ def _construct_declarations(self, config: Config) -> None: if entry.kind not in _UNCONSTRUCTED_KINDS: built.append((entry, self._construct(entry, config))) - # After construction, not before: a class's priority is a property of the object, and - # asking the class for it means reading a default argument and being wrong about every - # handler that computes one. The application is not returned when this raises, so the - # components already in the registry go nowhere. - self._check_declaration_order(built) + self._restore_declaration_order(built) for entry in self._declarations: if entry.kind == "cache": @@ -892,53 +887,26 @@ def _construct_declarations(self, config: Config) -> None: logger.debug("Constructed %d declaration(s)", len(self._declarations)) @staticmethod - def _check_declaration_order(built: list[tuple[Declaration, Any]]) -> None: - """Refuse a declaration order that construction cannot reproduce. + def _restore_declaration_order(built: list[tuple[Declaration, Any]]) -> None: + """Register the declared handlers in the order they were declared (S20). An already-built instance is constructed by the caller at its own source line, so it is in the registry before ``build()`` runs; a class or a factory is constructed during the - replay. So an instance recorded *after* a class registers *before* it, and registration + replay. So an instance recorded *after* a class registered *before* it -- and registration order is not decoration: ``DispatchIndex.build`` resolves handler priority ties by it, - which a project may well be relying on without having said so. + which a project may well be relying on without having said so. Before 0.9 every + ``with_handler`` call registered at once, so the order was the call order. - Only handlers, only within one agent, and only at equal priority, because that is the - only case where the order decides anything. Different priorities sort deterministically - whichever way round the two were registered, two agents never share a chain, and - nothing else the registry holds is order sensitive. - - Detected rather than repaired: the fix is one keyword away -- pass the class -- and - reordering the registry behind the caller's back would make the file say one thing and - the application do another. + Restored rather than refused: the handlers are put back in declaration order in the + registry slots they already hold, so nothing else the registry holds moves. Args: built: Each non-cache declaration paired with the component it produced, in declaration order. - - Raises: - ValueError: if a handler instance was recorded after a handler class or factory of - the same priority in the same namespace. """ - handlers = [ - (position, entry, component) for position, (entry, component) in enumerate(built) if isinstance(component, EventHandlerBase) - ] - - for position, entry, component in handlers: - if entry.is_built: - continue - for later_position, later, later_component in handlers: - if later_position <= position or not later.is_built: - continue - if later.namespace != entry.namespace or later_component.priority != component.priority: - continue - raise ValueError( - f"{type(later_component).__name__} was passed to with_handler() as an instance after " - f"{type(component).__name__} was declared as a class, and both have priority " - f"{component.priority}. An instance is built where it is written and a class is built by " - "build(), so the instance registers first and is tried first -- the reverse of what this file " - f"says. Pass {type(later_component).__name__} as a class as well, so that both are built in " - "declaration order, or give one of them a different priority so the order stops depending on " - "registration at all." - ) + handlers = [component for _, component in built if isinstance(component, EventHandlerBase)] + if handlers: + Component.shared_registry.reorder(handlers) # type: ignore[union-attr] def build(self, config: Config | None = None) -> FastAPI: """Construct everything declared, wire it, and return the FastAPI application. @@ -1042,7 +1010,7 @@ def build(self, config: Config | None = None) -> FastAPI: # so passing the registry name would read 'orders.orders_nats_client'. A root client's # base name is its registry name, so an existing payload key does not move. health_providers: list[HealthCheckEntry] = [ - HealthCheckEntry(name=client.base_name, namespace=client.namespace, checker=ClientHealthChecker([client])) + HealthCheckEntry(name=client.base_name, namespace=client.namespace, checker=ClientHealthChecker([client]), builtin=True) for client in registry.get_clients() ] # Pull every registered cache into the readiness probe so a Redis outage takes the pod @@ -1055,7 +1023,7 @@ def build(self, config: Config | None = None) -> FastAPI: name = "cache" if cache_name == DEFAULT_CACHE_NAME else f"cache:{cache_name}" # The agent is carried on the entry, so two agents' default caches are two entries # rather than one that silently reports whichever was registered last. - health_providers.append(HealthCheckEntry(name=name, namespace=namespace, checker=CacheHealthChecker(cache))) + health_providers.append(HealthCheckEntry(name=name, namespace=namespace, checker=CacheHealthChecker(cache), builtin=True)) # Each agent's named connections: one entry for readiness only. Never one that pauses the # agent -- a dead tenant connection must not stop it on its other connections (plan D5). health_providers.extend( @@ -1064,6 +1032,7 @@ def build(self, config: Config | None = None) -> FastAPI: namespace=client.namespace, checker=NamedConnectionsHealthChecker(client), affects_consumption=False, + builtin=True, ) for client in self._sourced_nats_clients ) @@ -1485,9 +1454,9 @@ async def _stop_startup_recovery(self) -> None: """Cancel every recovery still running, before any component is shut down.""" for task in self._recovery_tasks: task.cancel() - for task in self._recovery_tasks: - with contextlib.suppress(asyncio.CancelledError): - await task + # Gathered, not awaited one by one (N1): a task that ended by raising -- reported by + # _on_recovery_done already -- re-raised here and aborted the whole shutdown. + await asyncio.gather(*self._recovery_tasks, return_exceptions=True) self._recovery_tasks.clear() async def _recover_agent(self, namespace: str, interval: float) -> None: @@ -1578,8 +1547,7 @@ async def _start_loop_diagnostics(self, config: Config) -> None: Args: config: The application's configuration. """ - development = str(config.get("app_environment", "development")) == "development" - if configure_loop_debug(config, development=development): + if configure_loop_debug(config): return if not parse_bool(config.get(WATCHDOG_ENABLED_KEY, True), WATCHDOG_ENABLED_KEY): logger.info("Event loop watchdog is disabled by configuration") @@ -1756,7 +1724,10 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: logger.error("Client %s shutdown failed: %s", client.name, e, exc_info=True) if self._actuator_api is not None: - await self._actuator_api.on_shutdown() + try: + await self._actuator_api.on_shutdown() + except Exception as e: + logger.error("Actuator shutdown failed: %s", e, exc_info=True) await self._loop_watchdog.stop() diff --git a/src/blueprint/agents/component/registry.py b/src/blueprint/agents/component/registry.py index c96af6a2..3bc34f6b 100644 --- a/src/blueprint/agents/component/registry.py +++ b/src/blueprint/agents/component/registry.py @@ -26,6 +26,7 @@ """ import logging +from collections.abc import Sequence from concurrent.futures import ThreadPoolExecutor from copy import copy from typing import Any, TypeVar @@ -679,6 +680,27 @@ def has_component_of_type(self, component_type: Any, name: str | None = None, na return True return bool(self.get_components_by_type(component_type, namespace)) + def reorder(self, components: Sequence[Any]) -> None: + """Give ``components`` the registration order they are listed in, within the slots they hold. + + The listed components swap places among themselves; every other component stays where + it is. Used by ``AppBuilder`` to register handlers in declaration order (S20). The + mapping is changed in place, so a namespace view of this registry sees the new order. + + Args: + components: Registered components, in the order wanted. One that is not registered + is ignored. + """ + wanted = {id(component) for component in components} + items = list(self._components.items()) + slots = [index for index, (_, component) in enumerate(items) if id(component) in wanted] + by_identity = {id(component): (name, component) for name, component in items if id(component) in wanted} + ordered = [by_identity[id(component)] for component in components if id(component) in by_identity] + for slot, item in zip(slots, ordered, strict=True): + items[slot] = item + self._components.clear() + self._components.update(items) + def clear_components(self) -> None: """Clear all registered components (useful for testing).""" diff --git a/src/blueprint/agents/handler/sessions_job_handler.py b/src/blueprint/agents/handler/sessions_job_handler.py index ebca5096..90258676 100644 --- a/src/blueprint/agents/handler/sessions_job_handler.py +++ b/src/blueprint/agents/handler/sessions_job_handler.py @@ -201,11 +201,19 @@ def job_created_event_type(self) -> str: return f"sessions.job.created.{self.JOB_TYPE}" def get_handled_event_types(self) -> list[str]: - """Declare the one event type this subclass's jobs arrive as. + """Declare the one event type this subclass's jobs arrive as -- if this class's selector decides. Derived from :attr:`JOB_TYPE`, so a subclass opts into the dispatch index by setting the class variable it already had to set -- it declares nothing of its own. + + **Not when the subclass overrides** :meth:`can_handle_event` (S10). A declaration is + matched before the selector is asked, so a subclass that widened the selector -- to + accept a second job type, say -- was never offered the events it widened it for. Such a + subclass declares nothing and is offered every event, as before 0.9; it can declare its + own list by overriding this method as well. """ + if type(self).can_handle_event is not SessionsJobHandler.can_handle_event: + return [] return [self.job_created_event_type] async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: diff --git a/src/blueprint/agents/io/api/actuators/actuator_api.py b/src/blueprint/agents/io/api/actuators/actuator_api.py index 757b9917..940269c9 100644 --- a/src/blueprint/agents/io/api/actuators/actuator_api.py +++ b/src/blueprint/agents/io/api/actuators/actuator_api.py @@ -101,18 +101,32 @@ def add_health_providers(self, providers: Sequence[HealthCheckEntry]) -> None: A duplicate key is refused. Two checks under one name is exactly the silent loss D4 exists to remove: a dict kept the last one, so an agent's check could vanish with - nothing logged and nothing failing. + nothing logged and nothing failing. **The one exception** is an application's check + under the entry of a built-in one (``cache``, a client's name): it replaces the + built-in, with a WARNING, because that is what ``with_health_checker`` did before 0.9 + and applications rely on it to override a check (S20). Args: providers: The checks to add, each carrying the agent it belongs to. Raises: - ValueError: if a key is already registered. + ValueError: if a key is already registered, other than a built-in one by an + application's check. """ registered = {entry.key: entry for entry in self._health_entries} for entry in providers: existing = registered.get(entry.key) - if existing is not None: + if existing is not None and existing.builtin and not entry.builtin: + logger.warning( + "Health check '%s' of agent '%s' replaces the framework's %s of the same name: the readiness " + "payload shows it under '%s', and the framework's own check is not run.", + entry.name, + entry.agent, + type(existing.checker).__name__, + entry.key, + ) + self._health_entries.remove(existing) + elif existing is not None: raise ValueError( f"Health check '{entry.name}' of agent '{entry.agent}' would appear in the readiness payload as " f"'{entry.key}', which is already taken by a {type(existing.checker).__name__} of agent " diff --git a/src/blueprint/agents/io/api/actuators/health/health_base.py b/src/blueprint/agents/io/api/actuators/health/health_base.py index 1add8b91..09b37a21 100644 --- a/src/blueprint/agents/io/api/actuators/health/health_base.py +++ b/src/blueprint/agents/io/api/actuators/health/health_base.py @@ -58,12 +58,15 @@ class HealthCheckEntry: affects_consumption: Whether a failure also stops the agent consuming (C4). ``False`` makes the check count for readiness only: a named NATS connection that is down must never pause the agent on its other connections (named-connections plan, D5). + builtin: Whether the framework registered it (a client, cache or connection check). An + application's own check under the same entry replaces it, as it did before 0.9. """ name: str namespace: str checker: HealthCheckerBase affects_consumption: bool = True + builtin: bool = False @property def key(self) -> str: diff --git a/src/blueprint/agents/io/telemetry/loop_watchdog.py b/src/blueprint/agents/io/telemetry/loop_watchdog.py index 35e7ca70..1f772761 100644 --- a/src/blueprint/agents/io/telemetry/loop_watchdog.py +++ b/src/blueprint/agents/io/telemetry/loop_watchdog.py @@ -6,22 +6,22 @@ process it shows up as latency in the one service that caused it; in a group it shows up as latency in twenty services, nineteen of which did nothing wrong. -Two mechanisms, because the two environments can afford different things: - -- **Development** turns on asyncio's own debug mode, which reports the exact callback that ran - too long, with its source location. It is the better diagnostic by far and it is too - expensive to leave on: debug mode wraps coroutine creation and keeps tracebacks for every - task. -- **Production** runs this watchdog instead. It sleeps for a known interval and measures how - much longer than that the sleep actually took; the excess is time the loop spent unable to - run anything. It cannot name the callback -- by the time it runs again, the callback has - returned -- so it names the agents that had work in flight, which is the set the culprit is - in. +Two mechanisms, at two prices: + +- **This watchdog**, by default in every environment. It sleeps for a known interval and + measures how much longer than that the sleep actually took; the excess is time the loop + spent unable to run anything. It cannot name the callback -- by the time it runs again, the + callback has returned -- so it names the agents that had work in flight, which is the set + the culprit is in. +- **asyncio's own debug mode**, with ``event_loop_debug = true``, which reports the exact + callback that ran too long, with its source location. It is the better diagnostic by far + and too expensive to leave on: debug mode wraps coroutine creation and keeps tracebacks for + every task. It was on by default in development, the default environment, until S21 -- so + an application that never set an environment ran with it. Naming candidates rather than the culprit is the honest shape here, and it is still the difference between "the pod was slow" and "one of these two agents blocked the loop for four -seconds". Turning debug mode on in production to get the exact answer is available and -deliberate: set ``event_loop_debug`` and accept the cost. +seconds". The exact answer is a deliberate choice: set ``event_loop_debug`` and accept the cost. """ import asyncio @@ -29,6 +29,7 @@ from collections.abc import Mapping from ...component.namespace import ROOT_LABEL +from ...utils import parse_bool from .inflight import IN_FLIGHT logger = logging.getLogger(__name__) @@ -50,24 +51,28 @@ """ DEFAULT_SLOW_CALLBACK_SECONDS = 0.2 -"""asyncio's own threshold in development, where the exact callback is worth the overhead.""" +"""asyncio's own threshold with debug mode on, where the exact callback is worth the overhead.""" -def configure_loop_debug(config: Mapping[str, object] | object, *, development: bool) -> bool: - """Turn on asyncio debug mode where it is wanted, and report whether it was turned on. +def configure_loop_debug(config: Mapping[str, object] | object) -> bool: + """Turn on asyncio debug mode if ``event_loop_debug`` asks for it, and report whether it did. + + Off unless set (S21), in every environment. Read with :func:`parse_bool`, so an environment + override of ``"false"`` -- a non-empty string, which ``bool()`` reads as true -- means false. Args: config: The application's configuration, read with ``get``. - development: Whether this process is running in the development environment, which is - what makes the debug mode's cost acceptable by default. Returns: Whether debug mode is now on, so the caller can skip the watchdog: with debug mode on, asyncio reports the blocking callback itself and the watchdog would only add a vaguer second line about the same event. + + Raises: + ValueError: ``event_loop_debug`` is set to something that is not a boolean. """ getter = getattr(config, "get", None) - enabled = bool(getter(DEBUG_KEY, development)) if callable(getter) else development + enabled = parse_bool(getter(DEBUG_KEY, False), DEBUG_KEY) if callable(getter) else False if not enabled: return False diff --git a/tests/unit/agents/app_builder/TESTS.md b/tests/unit/agents/app_builder/TESTS.md index d9206c64..9d2b9aab 100644 --- a/tests/unit/agents/app_builder/TESTS.md +++ b/tests/unit/agents/app_builder/TESTS.md @@ -8,7 +8,7 @@ Test coverage for `src/blueprint/agents/app_builder.py`. | File | Class under test | What is covered | |---|---|---| -| `test_deferred_wiring.py` | `AppBuilder`, `Declaration` | Nothing is constructed or registered before `build()`; what a declaration records (kind, target, name, ambient namespace, kwargs); the declaration-order refusal and the three cases it must *not* fire on; where the configuration may be handed over and the refusal when it is given twice; the single-use guard; an application that declares nothing; an unbuilt `AgentBuilder` handed to `with_agent` and built with its agent's scoped view | +| `test_deferred_wiring.py` | `AppBuilder`, `Declaration` | Nothing is constructed or registered before `build()`; what a declaration records (kind, target, name, ambient namespace, kwargs); handlers register in declaration order, an instance after a class and classes and instances mixed (S20), and the cases that were always accepted; where the configuration may be handed over and the refusal when it is given twice; the single-use guard; an application that declares nothing; an unbuilt `AgentBuilder` handed to `with_agent` and built with its agent's scoped view | | `test_namespace_placement.py` | `AppBuilder`, `namespace_scope`, `host_agent` | A component reaches the right agent without anyone naming a namespace: the ambient scope qualifies the registry name, reaches the component and is never forwarded to its constructor; it is captured at the call, not at construction; explicit names are qualified too; an already-built instance is refused for another namespace; `host_agent` records the composition and refuses a duplicate, the root and an illegal name; and the four deleted surfaces (`AgentRegistration`, `RegisteredComponent`, `NamespaceBuilder`, `with_namespace`/`with_registration`) stay deleted | | `test_app_builder.py` | `AppBuilder` | `with_handler` (TypeError for non-subclass, class instantiated, instance accepted without re-instantiation, name propagated, returns self); `with_service`/`with_agent`/`with_scheduler`/`with_rest_api` (instance accepted, returns self); `with_cache` (enabled creates DiskCacheService, disabled skips config read); `with_health_checker` (recorded as a `Declaration` before build, added straight to the actuator after build, several accumulate, a checker is never constructed, returns self); `build()` (event_bus=dapr/nats/unknown/no-handlers routing, EventPublishingService conditional on IO clients, pending health checkers wired, returns FastAPI instance); scheduler wiring (an event-mode scheduler is wired before the transport decision, so its tick handler is what causes a NATS client and eventing endpoint to be created; an in-process scheduler alone creates neither); the publish/consume split (`event_publishing_enabled` off means no client; on means a client with no eventing component and no `EventProcessingService`; the string form an environment variable delivers; rejections for no transport, `"sessions"` and a non-boolean; and a consuming application still publishing without the key) | diff --git a/tests/unit/agents/app_builder/test_deferred_wiring.py b/tests/unit/agents/app_builder/test_deferred_wiring.py index 5a655629..5f44d0bc 100644 --- a/tests/unit/agents/app_builder/test_deferred_wiring.py +++ b/tests/unit/agents/app_builder/test_deferred_wiring.py @@ -165,19 +165,21 @@ def test_something_that_cannot_be_called_is_refused(self, config: Config) -> Non AppBuilder(config).with_service(42) # type: ignore[arg-type] +def _handler_order() -> list[str]: + return [type(handler).__name__ for handler in Component.shared_registry.get_event_handler()] + + class TestDeclarationOrder: - def test_an_instance_after_a_class_at_equal_priority_is_refused(self, config: Config) -> None: - """The instance is already registered, so it would be tried first -- the reverse of the file.""" - builder = AppBuilder(config).with_handler(FirstHandler).with_handler(SecondHandler()) + def test_an_instance_after_a_class_registers_after_it(self, config: Config) -> None: + """S20 -- the instance registered first, so it was tried first; 0.8 registered in call order.""" + AppBuilder(config).with_handler(FirstHandler).with_handler(SecondHandler()).build() - with pytest.raises(ValueError, match="SecondHandler was passed to with_handler"): - builder.build() + assert _handler_order() == ["FirstHandler", "SecondHandler"] - def test_the_refusal_names_both_handlers_and_the_priority(self, config: Config) -> None: - builder = AppBuilder(config).with_handler(FirstHandler).with_handler(SecondHandler()) + def test_classes_and_instances_mixed_follow_the_file(self, config: Config) -> None: + AppBuilder(config).with_handler(SecondHandler()).with_handler(FirstHandler).with_handler(LowPriorityHandler()).build() - with pytest.raises(ValueError, match=r"FirstHandler was declared as a class.*priority 100"): - builder.build() + assert _handler_order() == ["SecondHandler", "FirstHandler", "LowPriorityHandler"] def test_different_priorities_are_accepted(self, config: Config) -> None: """Priority decides, so registration order decides nothing and cannot be reversed.""" diff --git a/tests/unit/agents/app_builder/test_standalone_readiness.py b/tests/unit/agents/app_builder/test_standalone_readiness.py index 55c5dae4..cb2fd4a0 100644 --- a/tests/unit/agents/app_builder/test_standalone_readiness.py +++ b/tests/unit/agents/app_builder/test_standalone_readiness.py @@ -103,3 +103,78 @@ async def test_the_lifespan_shuts_telemetry_down_after_the_components(config: Co async with app.router.lifespan_context(app): pass assert order == ["executors", "telemetry"] + + +class _OwnCacheCheck(HealthCheckerBase): + async def health_check(self) -> ComponentHealth: + return ComponentHealth(status="healthy", message="the application's own cache check") + + +def _cache_config(tmp_path: Path) -> Config: + settings = tmp_path / "settings.toml" + settings.write_text( + '[development]\napp_name = "standalone"\napp_port = 8000\napp_environment = "development"\n\n' + f'[development.cache]\ncache_dir = "{(tmp_path / "cache").as_posix()}"\n' + ) + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + +class TestAUserCheckReplacesABuiltInOne: + """S20 -- in 0.8 a user check named like a built-in replaced it; 0.9 refused the build.""" + + def test_at_build(self, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: + own = _OwnCacheCheck() + builder = AppBuilder(_cache_config(tmp_path)).with_cache().with_health_checker("cache", own) + with caplog.at_level("WARNING"): + builder.build() + entries = [entry for entry in builder._actuator_api._health_entries if entry.key == "cache"] # type: ignore[union-attr] + assert [entry.checker for entry in entries] == [own] + assert any("replaces the framework's CacheHealthChecker" in message for message in caplog.messages) + + def test_after_build(self, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: + own = _OwnCacheCheck() + builder = AppBuilder(_cache_config(tmp_path)).with_cache() + builder.build() + with caplog.at_level("WARNING"): + builder.with_health_checker("cache", own) + entries = [entry for entry in builder._actuator_api._health_entries if entry.key == "cache"] # type: ignore[union-attr] + assert [entry.checker for entry in entries] == [own] + + def test_two_user_checks_under_one_name_are_still_refused(self, tmp_path: Path) -> None: + builder = ( + AppBuilder(_cache_config(tmp_path)).with_health_checker("db", _OwnCacheCheck()).with_health_checker("db", _OwnCacheCheck()) + ) + with pytest.raises(ValueError, match="already taken"): + builder.build() + + +class TestShutdownGoesOnPastAFailure: + """N1 -- a failed recovery task and a failing actuator shutdown each aborted the rest of shutdown.""" + + async def test_a_failed_recovery_task_does_not_abort_it(self, config: Config) -> None: + import asyncio + + builder = AppBuilder(config) + + async def broken() -> None: + raise RuntimeError("recovery bug") + + task = asyncio.create_task(broken()) + await asyncio.sleep(0) + builder._recovery_tasks.append(task) + + await builder._stop_startup_recovery() + + assert builder._recovery_tasks == [] + + async def test_a_failing_actuator_shutdown_is_logged_and_the_rest_runs(self, config: Config, caplog: pytest.LogCaptureFixture) -> None: + from unittest.mock import AsyncMock + + builder = AppBuilder(config) + app = builder.build() + builder._telemetry_manager.on_shutdown = AsyncMock() # type: ignore[method-assign] + with caplog.at_level("ERROR"): + async with app.router.lifespan_context(app): + builder._actuator_api.on_shutdown = AsyncMock(side_effect=RuntimeError("cache scheduler")) # type: ignore[method-assign, union-attr] + builder._telemetry_manager.on_shutdown.assert_awaited_once() + assert any("cache scheduler" in message for message in caplog.messages) diff --git a/tests/unit/agents/handler/test_sessions_job_handler.py b/tests/unit/agents/handler/test_sessions_job_handler.py index 1df2c54c..62f25513 100644 --- a/tests/unit/agents/handler/test_sessions_job_handler.py +++ b/tests/unit/agents/handler/test_sessions_job_handler.py @@ -860,3 +860,17 @@ def test_an_id_is_forgotten_after_the_ttl(self, monkeypatch) -> None: clock[0] += 61 assert job not in seen assert len(seen) == 0 + + +class TestTheDeclarationFollowsTheSelector: + """S10 -- the auto-declared job type narrowed a subclass that widened can_handle_event.""" + + def test_the_job_type_is_declared(self, mock_config: MagicMock, mock_registry: MagicMock) -> None: + assert _Handler().get_handled_event_types() == ["sessions.job.created.demo"] + + def test_a_widened_selector_declares_nothing(self, mock_config: MagicMock, mock_registry: MagicMock) -> None: + class Widened(_Handler): + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return event.type.startswith("sessions.job.created.") + + assert Widened().get_handled_event_types() == [] diff --git a/tests/unit/agents/io/telemetry/test_loop_watchdog.py b/tests/unit/agents/io/telemetry/test_loop_watchdog.py index 2e6ebaf8..1dd5c44d 100644 --- a/tests/unit/agents/io/telemetry/test_loop_watchdog.py +++ b/tests/unit/agents/io/telemetry/test_loop_watchdog.py @@ -29,31 +29,37 @@ def _config(**values: object) -> MagicMock: class TestDebugMode: - async def test_development_turns_asyncio_debug_on(self) -> None: + async def test_it_is_off_unless_set(self) -> None: + """S21 -- it was on in development, the default environment: every coroutine wrapped by default.""" + assert configure_loop_debug(_config()) is False + assert asyncio.get_running_loop().get_debug() is False + + async def test_it_can_be_asked_for(self) -> None: + """The exact answer is available anywhere; it just costs enough to be a decision.""" loop = asyncio.get_running_loop() try: - assert configure_loop_debug(_config(), development=True) is True + assert configure_loop_debug(_config(**{DEBUG_KEY: True})) is True assert loop.get_debug() is True finally: loop.set_debug(False) - async def test_production_leaves_it_off(self) -> None: - assert configure_loop_debug(_config(), development=False) is False - assert asyncio.get_running_loop().get_debug() is False - - async def test_production_can_ask_for_it(self) -> None: - """The exact answer is available in production; it just costs enough to be a decision.""" + async def test_an_environment_string_is_read_as_a_bool(self) -> None: + """'false' from an environment variable is a non-empty string, which bool() reads as True.""" + assert configure_loop_debug(_config(**{DEBUG_KEY: "false"})) is False loop = asyncio.get_running_loop() try: - assert configure_loop_debug(_config(**{DEBUG_KEY: True}), development=False) is True - assert loop.get_debug() is True + assert configure_loop_debug(_config(**{DEBUG_KEY: "true"})) is True finally: loop.set_debug(False) + async def test_a_value_that_is_no_bool_is_refused(self) -> None: + with pytest.raises(ValueError, match="event_loop_debug"): + configure_loop_debug(_config(**{DEBUG_KEY: "sometimes"})) + async def test_the_slow_callback_threshold_is_configurable(self) -> None: loop = asyncio.get_running_loop() try: - configure_loop_debug(_config(event_loop_slow_callback_seconds=0.5), development=True) + configure_loop_debug(_config(**{DEBUG_KEY: True}, event_loop_slow_callback_seconds=0.5)) assert loop.slow_callback_duration == 0.5 finally: loop.set_debug(False) From 88bb8cfeebfbf2a66404a04624b1952a83da365a Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:15:06 +0200 Subject: [PATCH 121/133] fix: the resolved group is the deployment group; diskcache-rs >= 0.4.10; tick slot from the trigger Step 20 (S19, S23/D16, W2, W3/D7): a disk cache's claim is documented as per-process (N13). Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 12 ++++ ...26-08-28-multi-agent-grouping-changelog.md | 9 +++ pyproject.toml | 2 +- .../agent_generator/docs/guides/deployment.md | 5 +- .../docs/guides/multi-agent-setup.md | 8 ++- .../docs/reference/configuration-keys.md | 2 +- src/blueprint/agents/agent_group.py | 7 ++- src/blueprint/agents/component/component.py | 7 +++ src/blueprint/agents/deployment.py | 26 +++++++-- src/blueprint/agents/handler/handler_chain.py | 2 +- .../agents/io/api/scheduling/scheduler.py | 35 ++++++++++- .../services/infrastructure/cache_service.py | 14 +++-- tests/unit/agents/conftest.py | 10 ++++ .../io/api/scheduling/test_scheduler.py | 58 ++++++++++++++++++- tests/unit/agents/test_agent_group.py | 25 ++++++++ 15 files changed, 203 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 30d59696..23a89c4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,18 @@ when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the redelivery acknowledged unrun; now the redelivery runs to completion. +- **A group named only by its group file is the deployment group** (S19). A group file that declares + one group needs no `BLUEPRINT_GROUP`, but the name reached neither the NATS connection name, the + telemetry resource's `deployment.group` nor the supervisor's log lines, which read only the + variable: they said ``. They now carry the resolved name. + +- **`diskcache-rs` 0.4.10 is the minimum, and a disk cache's claim is documented as per-process** + (S23). 0.4.9 and earlier refused a second process the cache directory ("Database already open"). + 0.4.10 lets several open it, but its set-if-absent is not atomic between them: four processes + claiming one key at once each won in 297 of 300 rounds. Deduplication and the in-process tick + claim therefore hold across replicas, and across several `app_workers`, only with Redis; the docs no + longer say "a disk cache on a shared volume". + - **A standalone application written for 0.8 builds again** (S20). Three 0.8 shapes were refused or changed: - A health check of the application's own under a built-in name (`cache`, a client's name) diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index b236ee57..7b23ddd4 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,15 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 20, smaller items (S19, S23/D16, W2, W3/D7): `deployment.publish_deployment_group` from + `AgentGroup.resolve`, read first by `deployment_group()`; the in-process tick slot is the trigger's latest + fire time at or before now (`_arm_trigger`, `_tick_slot`); `diskcache-rs>=0.4.10`; the disk claim documented + as per-process (docstring, `handler_chain`, deployment guide, configuration keys); W3 documented on + `Component.registry` and in the grouping guide. Live (WSL): the group image with a one-group file and no + `BLUEPRINT_GROUP` exported `deployment.group = finance` for 'agent-group', 'orders' and 'billing' (control: + absent, supervisor lines said ''). Cross-process claim, 4 processes x 300 rounds on one + directory: several winners in 297 rounds through `DiskCacheService.claim` and through raw `Cache.add`, no + error; 0.4.9 refused the second process ('Database already open'). Found N13, open as D22. - Step 19, standalone compatibility (S10, S20, S21, N1): `HealthCheckEntry.builtin` and an application check replacing a built-in one with a WARNING; `Registry.reorder` puts declared handlers in declaration order (the refusal is gone); `SessionsJobHandler.get_handled_event_types` declares nothing when `can_handle_event` is diff --git a/pyproject.toml b/pyproject.toml index 0e3928bc..a6093730 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,7 +40,7 @@ dependencies = [ "dapr>=1.16.0", "python-multipart>=0.0.20", "apscheduler>=3.11.2", - "diskcache-rs>=0.4.4", + "diskcache-rs>=0.4.10", "nats-py[nkeys]>=2.13.1", "croniter>=6.0.0", "pyyaml>=6.0" diff --git a/src/blueprint/agent_generator/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md index 42672f3c..7aeb631f 100644 --- a/src/blueprint/agent_generator/docs/guides/deployment.md +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -393,8 +393,9 @@ prevent. Too long only costs cache entries. If you raise `nats_ack_wait` or `nat raise this with them. Two limits to know: dedup needs the agent to declare `with_cache()` -- the marker lives in that -agent's own cache -- and the claim is atomic only across replicas that share that cache (Redis, or -a disk cache on a shared volume); a per-pod cache deduplicates within one pod. +agent's own cache -- and the claim is atomic only across replicas that share a Redis cache. A disk +cache's claim holds within one process: two processes on one directory -- several `app_workers`, or +replicas on a shared volume -- can both win it, so they can both run one event or one tick. **Grouped Dapr is the exception that wants dedup on.** A group has one Dapr endpoint: it publishes the union of every agent's topics and fans each delivery out to the agents that declared it, and the diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md index 721e4bcb..9e974ae6 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md @@ -419,7 +419,13 @@ reporting a healthy replica that is quietly short one consumer. Nothing. There is no supported API that exposes the group's name, its membership or its size, and that is what makes regrouping incapable of breaking agent code: an agent that could read its neighbours could be written to depend on them. `deployment.group` is set by the framework on -telemetry resources and is not readable through any public API. +telemetry resources and is not readable through any public API. It is the group's name as +resolved -- from `BLUEPRINT_GROUP`, or from a group file that declares one group. + +**A component in the root namespace is the exception.** Its registry is the unscoped one, and a +collection lookup without `namespace` -- `self.registry.get_services()` -- returns every agent's +components, not the root's. Pass `namespace=""` for the root's own. An agent's components get a +view instead, where an omitted `namespace` means that agent. ### A group assembled in code diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 8a761f88..ddf765fb 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -141,7 +141,7 @@ effects is acceptable is a property of the product, not of the framework. | Key | Type | Default | Description | |-----|------|---------|-------------| -| `idempotency_enabled` | `bool` | `false` | Skip an event whose `id` and `source` were already dispatched within the window -- on the same named connection, when it came from one (each connection is a data source of its own). Requires `idempotency_ttl` and a registered cache (`.with_cache()`); startup fails if either is missing, rather than leaving deduplication silently off. The claim is the cache's atomic set-if-absent, so replicas sharing a cache (Redis, or a disk cache on a shared volume) cannot both dispatch the same event; a per-pod cache deduplicates within that pod only, and a cache error fails open. | +| `idempotency_enabled` | `bool` | `false` | Skip an event whose `id` and `source` were already dispatched within the window -- on the same named connection, when it came from one (each connection is a data source of its own). Requires `idempotency_ttl` and a registered cache (`.with_cache()`); startup fails if either is missing, rather than leaving deduplication silently off. The claim is the cache's atomic set-if-absent, so replicas sharing a Redis cache cannot both dispatch the same event. A disk cache's claim holds within one process only -- several `app_workers` or replicas on a shared volume can both win it -- and a cache error fails open. | | `idempotency_ttl` | `int` | -- | Seconds a processed event is remembered. No default on purpose -- it must outlast the broker's redelivery window (`nats_ack_wait` * `nats_max_deliver` on JetStream, the component's retry policy under Dapr), and a window that expires before the last redelivery looks exactly like deduplication not working. | --- diff --git a/src/blueprint/agents/agent_group.py b/src/blueprint/agents/agent_group.py index 90aab1f0..23f96aba 100644 --- a/src/blueprint/agents/agent_group.py +++ b/src/blueprint/agents/agent_group.py @@ -35,6 +35,7 @@ from .app_builder import AppBuilder, refuse_constructed_components from .component.namespace import namespace_scope, validate_namespace from .config import Config +from .deployment import publish_deployment_group from .group_config import AgentSpec, GroupConfig, GroupConfigError from .layout import check_agent_layout @@ -226,7 +227,11 @@ def resolve(cls, config: Config, *, environ: dict[str, str] | None = None) -> "A GroupConfigError: if the group cannot be resolved, or a critical agent cannot be loaded. """ - return cls.from_config(GroupConfig.resolve(config, environ=environ)) + group = GroupConfig.resolve(config, environ=environ) + # Before anything reads it: the connection name and the telemetry resource take the + # deployment group, and a group named only by the file never reached them (S19). + publish_deployment_group(group.name) + return cls.from_config(group) @classmethod def from_config(cls, group: GroupConfig) -> "AgentGroup": diff --git a/src/blueprint/agents/component/component.py b/src/blueprint/agents/component/component.py index 5d113dca..ecac3ba2 100644 --- a/src/blueprint/agents/component/component.py +++ b/src/blueprint/agents/component/component.py @@ -216,6 +216,13 @@ def registry(self) -> Registry: :attr:`config`, that is the definition rather than an optimisation: the root namespace *is* the unscoped registry, so every existing single-agent application resolves exactly what it resolved before. + + **So an omitted ``namespace`` means two things** (W3, plan D7). On a view it means this + agent; on the registry itself it means *every* agent, for the collection lookups + (``get_services()``, ``get_event_handler()``, ...). A root component in a group + therefore sees every agent's components; ``namespace=""`` asks for the root's alone. + The framework's own root components depend on "every agent" -- the Dapr endpoint and + the event processing service collect across the group -- so the meaning is kept. """ registry: Registry = Component.shared_registry # type: ignore[assignment] if not self._namespace: diff --git a/src/blueprint/agents/deployment.py b/src/blueprint/agents/deployment.py index baf03e53..fe7f45c2 100644 --- a/src/blueprint/agents/deployment.py +++ b/src/blueprint/agents/deployment.py @@ -35,16 +35,34 @@ """Stands in when neither the environment nor the host can say which pod this is.""" +_resolved_group: str | None = None +"""The group ``AgentGroup.resolve`` resolved for this process; ``None`` until one did (S19).""" + + +def publish_deployment_group(name: str | None) -> None: + """Record the group this process resolved, so :func:`deployment_group` reports it (S19). + + Called by ``AgentGroup.resolve``. A group can be named by the group file alone -- a file that + declares one group needs no ``BLUEPRINT_GROUP`` -- and that name reached neither the NATS + connection name nor the telemetry resource, which read only the environment. ``None`` + forgets it again, for tests. + """ + global _resolved_group + _resolved_group = name + + def deployment_group() -> str: - """Return the deployment group this process was started as, or :data:`UNGROUPED_LABEL`. + """Return the deployment group this process runs as, or :data:`UNGROUPED_LABEL`. - Read straight from the environment rather than through ``Config``: group composition - decides which agents get a configuration view at all, so it cannot itself come from one. + The group ``AgentGroup.resolve`` published, else ``BLUEPRINT_GROUP`` -- read straight from + the environment rather than through ``Config``: group composition decides which agents get a + configuration view at all, so it cannot itself come from one. The group is deployment identity, so it belongs in the connection name and on the telemetry resource, and nowhere near the queue group or the durable (C1). """ - return display_segment(os.environ.get("BLUEPRINT_GROUP", ""), UNGROUPED_LABEL) + raw = _resolved_group if _resolved_group is not None else os.environ.get("BLUEPRINT_GROUP", "") + return display_segment(raw, UNGROUPED_LABEL) def pod_identity() -> str: diff --git a/src/blueprint/agents/handler/handler_chain.py b/src/blueprint/agents/handler/handler_chain.py index 6a2215bc..e74b6491 100644 --- a/src/blueprint/agents/handler/handler_chain.py +++ b/src/blueprint/agents/handler/handler_chain.py @@ -212,7 +212,7 @@ class HandlerChain(Component): The claim is the cache's atomic set-if-absent (``CacheService.claim``), so two replicas handed the same event at the same instant cannot both win it -- with a cache they share - (Redis, or a disk cache on a shared volume). A per-pod cache deduplicates within one pod + (Redis; a disk cache's claim holds within one process only, S23). A per-pod cache deduplicates within one pod only, and a cache that is unreachable fails open: both dispatch. A handler whose side effects must never repeat still needs its own reconciliation. diff --git a/src/blueprint/agents/io/api/scheduling/scheduler.py b/src/blueprint/agents/io/api/scheduling/scheduler.py index 18d097ab..bc2ca09f 100644 --- a/src/blueprint/agents/io/api/scheduling/scheduler.py +++ b/src/blueprint/agents/io/api/scheduling/scheduler.py @@ -323,6 +323,10 @@ def __init__(self, crontab: str, *, topic: str | None = None) -> None: self._mode: str | None = None self._tick_handler: SchedulerTickHandler | None = None self._scheduler: AsyncIOScheduler | None = None + # The in-process timer's trigger and its latest fire time known to be due, which the + # tick slot is read from (W2). Set by _arm_trigger. + self._trigger: CronTrigger | None = None + self._fire_cursor: datetime | None = None self._started = False self._gauge_registered = False self._trigger_route_registered = False @@ -597,6 +601,7 @@ async def on_startup(self) -> None: timezone = self._resolve_timezone() trigger = CronTrigger.from_crontab(self._crontab, timezone=timezone) + self._arm_trigger(trigger, datetime.now(UTC)) scheduler = AsyncIOScheduler(timezone=timezone) if timezone is not None else AsyncIOScheduler() scheduler.add_job(self._claimed_tick, trigger, name=self.name) @@ -728,7 +733,7 @@ async def _claim_tick_slot(self) -> bool: if not self.registry.has_cache(): return True - slot = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M") + slot = self._tick_slot(datetime.now(UTC)) # In a thread: a blocking Redis round trip or disk write on the event loop (S7). return await asyncio.to_thread( self.registry.cache_service.claim, @@ -738,6 +743,34 @@ async def _claim_tick_slot(self) -> bool: ttl=TICK_CLAIM_TTL_SECONDS, ) + def _arm_trigger(self, trigger: CronTrigger, now: datetime) -> None: + """Remember the timer's trigger and its first fire time from ``now``, for :meth:`_tick_slot`.""" + self._trigger = trigger + self._fire_cursor = trigger.get_next_fire_time(None, now) + + def _tick_slot(self, now: datetime) -> str: + """The minute this run was scheduled for, in UTC: the slot every replica derives (W2). + + The scheduled time, not the clock at run time: a run that started late across a minute + boundary claimed the next minute's slot. The scheduled time is the trigger's latest fire + time at or before ``now``, found by walking a cursor forward from the last one -- fire + times that passed without a run (a misfire) are walked over, so they cannot be claimed + late. Without a trigger, or before its first fire time, the clock decides, as before. + + With today's 1 s misfire grace and fire times on the full minute the two agree; this is + what keeps them agreeing if either changes. + + Args: + now: The current time, timezone-aware. + """ + cursor = self._fire_cursor + if self._trigger is None or cursor is None or cursor > now: + return now.astimezone(UTC).strftime("%Y-%m-%dT%H:%M") + while (following := self._trigger.get_next_fire_time(cursor, cursor)) is not None and following <= now: + cursor = following + self._fire_cursor = cursor + return cursor.astimezone(UTC).strftime("%Y-%m-%dT%H:%M") + # ------------------------------------------------------------------ # Manual trigger # ------------------------------------------------------------------ diff --git a/src/blueprint/agents/services/infrastructure/cache_service.py b/src/blueprint/agents/services/infrastructure/cache_service.py index 5aed27b5..3df1fde4 100644 --- a/src/blueprint/agents/services/infrastructure/cache_service.py +++ b/src/blueprint/agents/services/infrastructure/cache_service.py @@ -351,11 +351,17 @@ def set( logger.warning("Error setting cache: %s", e) def claim(self, key: str | list[str] | dict[str, Any], value: Any, namespace: str = "default", ttl: int | None = None) -> bool: - """Store a value only if the key is absent (atomic), and report whether we stored it. + """Store a value only if the key is absent, and report whether we stored it. - ``diskcache_rs.Cache.add`` is the set-if-absent operation, and it is atomic across - processes sharing the directory because the cache is opened with file locking. Its - own ``expire`` argument is **not** honoured by that backend -- an entry added with + ``diskcache_rs.Cache.add`` is the set-if-absent operation. **It is atomic within one + process** -- this service's lock serialises its threads -- **and not across processes** + (S23): measured with diskcache-rs 0.4.10, four processes on one directory claiming one + key at once each won in 297 of 300 rounds, with no error raised. Processes opened one + after the other do see each other's entries. So a claim that must hold across processes + -- several ``app_workers``, several replicas -- needs Redis. (0.4.9 and earlier refused a + second process the directory altogether: "Database already open".) + + Its own ``expire`` argument is **not** honoured by that backend -- an entry added with ``expire=1`` is still readable minutes later -- so the TTL is kept in the parallel metadata entry this service already maintains, exactly as ``set`` does. diff --git a/tests/unit/agents/conftest.py b/tests/unit/agents/conftest.py index 06e47d21..91feb79c 100644 --- a/tests/unit/agents/conftest.py +++ b/tests/unit/agents/conftest.py @@ -25,3 +25,13 @@ def mock_prompt_loader(request): with patch("blueprint.agents.agent.agent_builder.PromptLoader.load_prompt") as mock_load: mock_load.return_value = "Test prompt" yield mock_load + + +@pytest.fixture(autouse=True) +def _forget_the_published_group(): + """``AgentGroup.resolve`` publishes the group into process state (S19); no case may see another's.""" + from blueprint.agents.deployment import publish_deployment_group + + publish_deployment_group(None) + yield + publish_deployment_group(None) diff --git a/tests/unit/agents/io/api/scheduling/test_scheduler.py b/tests/unit/agents/io/api/scheduling/test_scheduler.py index 13b46f32..d8a3a140 100644 --- a/tests/unit/agents/io/api/scheduling/test_scheduler.py +++ b/tests/unit/agents/io/api/scheduling/test_scheduler.py @@ -595,11 +595,10 @@ async def test_a_later_slot_is_claimable_again(self, settings: dict[str, Any], t Component.shared_registry.cache_service = cache try: scheduler = _TestScheduler() - with patch(f"{_SCHEDULER_MODULE}.datetime") as clock: - clock.now.return_value.strftime.return_value = "2026-09-04T03:00" + slots = ["2026-09-04T03:00", "2026-09-04T03:00", "2026-09-04T04:00"] + with patch.object(scheduler, "_tick_slot", side_effect=slots): await scheduler._claimed_tick() await scheduler._claimed_tick() - clock.now.return_value.strftime.return_value = "2026-09-04T04:00" await scheduler._claimed_tick() assert scheduler.tick_call_count == 2 finally: @@ -759,3 +758,56 @@ async def test_an_unknown_zone_fails_startup(self, in_process_scheduler: _TestSc settings["scheduler_timezone"] = "Mars/Olympus" with pytest.raises(ValueError, match="not an IANA timezone name"): await in_process_scheduler.on_startup() + + +class TestTheSlotIsTheScheduledMinute: + """W2 -- the slot came from the clock at run time, not from the time the run was scheduled for.""" + + @pytest.fixture + def cached_scheduler(self, settings: dict[str, Any], mock_registry: MagicMock) -> _TestScheduler: + settings["scheduler_mode"] = SCHEDULER_MODE_IN_PROCESS + mock_registry.has_cache.return_value = True + return _TestScheduler() + + @staticmethod + def _at(hour: int, minute: int, second: int, micro: int = 0): + from datetime import UTC, datetime + + return datetime(2026, 10, 19, hour, minute, second, micro, tzinfo=UTC) + + def test_a_run_late_past_the_minute_claims_the_scheduled_one(self, cached_scheduler: _TestScheduler) -> None: + from datetime import UTC + + from apscheduler.triggers.cron import CronTrigger + + cached_scheduler._arm_trigger(CronTrigger.from_crontab("*/5 * * * *", timezone=UTC), self._at(11, 58, 0)) + assert cached_scheduler._tick_slot(self._at(12, 1, 0, 200_000)) == "2026-10-19T12:00" + + def test_fire_times_passed_without_a_run_are_walked_over(self, cached_scheduler: _TestScheduler) -> None: + from datetime import UTC + + from apscheduler.triggers.cron import CronTrigger + + cached_scheduler._arm_trigger(CronTrigger.from_crontab("*/5 * * * *", timezone=UTC), self._at(11, 58, 0)) + assert cached_scheduler._tick_slot(self._at(12, 31, 0)) == "2026-10-19T12:30" + + def test_a_run_on_time_claims_its_own_minute_not_the_previous(self, cached_scheduler: _TestScheduler) -> None: + from datetime import UTC + + from apscheduler.triggers.cron import CronTrigger + + cached_scheduler._arm_trigger(CronTrigger.from_crontab("* * * * *", timezone=UTC), self._at(11, 59, 30)) + assert cached_scheduler._tick_slot(self._at(12, 0, 0)) == "2026-10-19T12:00" + assert cached_scheduler._tick_slot(self._at(12, 0, 0, 900_000)) == "2026-10-19T12:00" + assert cached_scheduler._tick_slot(self._at(12, 1, 0, 100_000)) == "2026-10-19T12:01" + + def test_another_timezone_names_the_same_instant(self, cached_scheduler: _TestScheduler) -> None: + from zoneinfo import ZoneInfo + + from apscheduler.triggers.cron import CronTrigger + + cached_scheduler._arm_trigger(CronTrigger.from_crontab("0 14 * * *", timezone=ZoneInfo("Europe/Berlin")), self._at(11, 0, 0)) + assert cached_scheduler._tick_slot(self._at(12, 0, 0, 300_000)) == "2026-10-19T12:00" + + def test_without_a_trigger_the_clock_decides(self, cached_scheduler: _TestScheduler) -> None: + assert cached_scheduler._tick_slot(self._at(12, 7, 30)) == "2026-10-19T12:07" diff --git a/tests/unit/agents/test_agent_group.py b/tests/unit/agents/test_agent_group.py index 0cae6202..024dca53 100644 --- a/tests/unit/agents/test_agent_group.py +++ b/tests/unit/agents/test_agent_group.py @@ -612,3 +612,28 @@ def test_the_agents_do_not_share_a_tool_list(self, config: Config) -> None: built = self._assemble(config, AppBuilder().with_agent(agent), ("order", "billing")) assert built[0]["tools"] is not built[1]["tools"] assert built[0]["tools"] == built[1]["tools"] + + +class TestTheResolvedGroupIsTheDeploymentGroup: + """S19 -- a group named only in the group file reached neither the connection name nor telemetry.""" + + def test_a_group_from_the_file_is_published(self, tmp_path, monkeypatch) -> None: + from unittest.mock import patch + + from blueprint.agents.deployment import deployment_group + from blueprint.agents.group_config import GroupConfig + + monkeypatch.delenv("BLUEPRINT_GROUP", raising=False) + resolved = GroupConfig(name="finance", agents=()) + with patch.object(GroupConfig, "resolve", return_value=resolved), patch.object(AgentGroup, "from_config") as built: + AgentGroup.resolve(MagicMock(), environ={}) + built.assert_called_once_with(resolved) + assert deployment_group() == "finance" + + def test_without_a_resolved_group_the_environment_still_decides(self, monkeypatch) -> None: + from blueprint.agents.deployment import UNGROUPED_LABEL, deployment_group + + monkeypatch.setenv("BLUEPRINT_GROUP", "from-env") + assert deployment_group() == "from-env" + monkeypatch.delenv("BLUEPRINT_GROUP") + assert deployment_group() == UNGROUPED_LABEL From 904ecac9dcb06335015cf5ccc45087be303f1ac7 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:15:08 +0200 Subject: [PATCH 122/133] docs(release): fold [0.9.0] into [Unreleased], version back to 0.8.2, licence deferred Step 21 (W7, W8/D19, D20): LICENSE and the licence fields removed until the licence is approved; a Rolling back to 0.8 section. Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 1193 +++++++++-------- LICENSE | 21 - ...26-08-28-multi-agent-grouping-changelog.md | 5 + pyproject.toml | 4 +- tests/unit/agents/test_agent_isolation.py | 22 +- 5 files changed, 616 insertions(+), 629 deletions(-) delete mode 100644 LICENSE diff --git a/CHANGELOG.md b/CHANGELOG.md index 23a89c4d..ac1564e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,167 +1,527 @@ # Changelog ## [Unreleased] -### Fixed - -- **With deduplication on, an event cut off by `nats_handler_timeout` is no longer lost.** The run - is cancelled and nak'd, but the dedup marker was released only for an `Exception`, and - cancellation is not one. The redelivery found the marker, was skipped as a duplicate and - acknowledged, and the event was never processed. The same happened to a handler that swallowed - the cancellation, to a run cancelled by a shutdown, and to a failure after the handler returned - (a scalar return value that is not a valid `HandlerResult`). A delivery now keeps its marker only - when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the - redelivery acknowledged unrun; now the redelivery runs to completion. - -- **A group named only by its group file is the deployment group** (S19). A group file that declares - one group needs no `BLUEPRINT_GROUP`, but the name reached neither the NATS connection name, the - telemetry resource's `deployment.group` nor the supervisor's log lines, which read only the - variable: they said ``. They now carry the resolved name. - -- **`diskcache-rs` 0.4.10 is the minimum, and a disk cache's claim is documented as per-process** - (S23). 0.4.9 and earlier refused a second process the cache directory ("Database already open"). - 0.4.10 lets several open it, but its set-if-absent is not atomic between them: four processes - claiming one key at once each won in 297 of 300 rounds. Deduplication and the in-process tick - claim therefore hold across replicas, and across several `app_workers`, only with Redis; the docs no - longer say "a disk cache on a shared volume". - -- **A standalone application written for 0.8 builds again** (S20). Three 0.8 shapes were refused - or changed: - - A health check of the application's own under a built-in name (`cache`, a client's name) - replaced the built-in in 0.8 and failed the build here. It replaces it again, with a WARNING. - Two checks of the application's own under one name are still refused. - - A handler instance passed after a handler class of the same priority failed the build. Every - declared handler now registers in declaration order, as 0.8 did, whether passed as a class or - as an instance. - - A `SessionsJobHandler` subclass that widened `can_handle_event` was only offered its own job - type, which it declared automatically. It declares nothing now when it overrides the selector, - and is offered every event as in 0.8. - -- **asyncio debug mode is off unless `event_loop_debug` is set** (S21). It was on by default in - development -- the default environment -- so an application that never set one paid for debug - mode on every coroutine. The watchdog runs instead. The value is read as a boolean: `"false"` - from an environment variable means false, and a value that is no boolean fails startup. - -- **Shutdown runs to the end past a failed step** (N1). A startup recovery task that had ended by - raising re-raised while shutdown cancelled it, and a failing actuator shutdown raised out of the - lifespan; either skipped every later step. Both are logged and shutdown goes on. - -- **A JetStream consumer that filters another subject is no longer bound.** Root topic - `orders-created` and agent `orders` on topic `created` derive the same durable name - (`orders-created-durable`). Whichever started second bound the other's consumer with only a - drift warning, and received that topic's messages in its own handler. It now refuses to bind: - the subscription fails with an error naming the consumer, its filter and the topic, and the - connection retries. Rename one of the topics. +**Multi-agent grouping.** How many agents share a process becomes a *deployment* parameter rather +than an architectural commitment. An agent's code is identical whether it runs alone or beside +nineteen others; only what starts the process differs. A standalone agent is unaffected by almost +all of this — see **Breaking** for the exceptions, which are listed in the order you are likely to +hit them. -- **The "Created JetStream consumer" line is logged when `nats_ack_wait` is unset.** It formatted - the unset value with `%.1f`, so the line was lost to a logging error; it now reads - `ack_wait server default`. A delivery whose run could not be started no longer keeps its run slot. +Full migration path, including the one decision to get right before the first deploy: +[`guides/multi-agent-setup.md`](src/blueprint/agent_generator/docs/guides/multi-agent-setup.md). The normative spec is +`docs/specs/2026-08-28-multi-agent-grouping.md`. -- **A group's telemetry is no longer cut off at shutdown.** All agents share one span processor - and one metric exporter, and the first provider to shut down closed them for every other: the - remaining agents' final metrics were dropped ("Exporter already shutdown"). They are now closed by - the last provider, and the application's shutdown flushes every provider after its components - have stopped -- agents first, the root last. Measured against a collector: 2 of 4 final metric - points arrived before, 4 of 4 now. +### Breaking -- **In a group, `OTEL_SERVICE_NAME` no longer names every agent alike.** The agents keep their own - name as `service.name`; the variable names the root's telemetry, as standalone. Startup logs a - WARNING naming the value. `OTEL_RESOURCE_ATTRIBUTES` is unchanged. +- **In a group, the NATS publish endpoint and scheduler triggers move, and each agent is one + Swagger group.** Grouped agents only; a standalone agent's paths and tags do not change. + - `/api//events/{topic}` becomes `/api//nats/events/{topic}`. + - `/api///trigger` becomes `/api//scheduler//trigger`. + - Cache endpoints stay at `/api//cache/*`. + - Every operation of a grouped agent is tagged with exactly the agent's name, replacing declared + tags and tagging untagged ones. In 0.9.0 an agent was split into `.` groups + interleaved with other agents', and its untagged routes sat under "default" beside everyone + else's. + - `nats`, `cache` and `scheduler` under `/api//` are reserved: a grouped agent's own route + starting with one now fails startup, naming the class and the route. Rename it or set + `path_prefix`. -- **Grouped Dapr: each agent gets its own copy of a delivery, and the answer has no stray reason.** - The fan-out handed one `CloudEvent` object to every agent declaring the topic, so a change one - handler made to it reached the next. A delivery one agent acknowledged and another terminated - answered `SUCCESS` with the terminating agent's reason. Startup now warns about a topic two agents - declare while one of them runs without `idempotency_enabled`, since a retry asked for by one - redelivers to all of them. + Clients and scripts calling a grouped agent's NATS publish endpoint or scheduler trigger need the + new paths. Nothing broker-side changes. +- **Removed unused internals:** the empty module `blueprint.agents.models.event_routing`, and the + example-domain models `AnalysisRequest` and `AnalysisResponse` in `blueprint.agents.models.result`, + which nothing in the framework used and the package did not export. +- **`blueprint.events.unhandled` and `blueprint.events.duplicate` carry `agent`, not + `namespace`,** and are recorded on the agent's own meter. They were created at import on the + global meter, so they reported under the root's resource for every agent, with a label no other + metric uses. The root is labelled ``, as everywhere else. Dashboards on the old label need + the new one. +- **`nats_use_jetstream = true` is enforced against the server; there is no fallback to Core + NATS.** The server is asked for the account's JetStream information on connecting. If it does not + offer JetStream, the agent fails: at startup through the startup failure policy, later (broker + unreachable at startup) by shutting the process down for the root or a critical agent and marking + a non-critical one down. The previous fallback rarely triggered, and when it did it dropped + durable consumers and acknowledgements without anyone deciding it. +- **JetStream consumer settings are opt-in again.** The framework set `ack_wait` 300 s, + `max_ack_pending` 16 and `max_deliver` 5 on every consumer it created, overriding the server's + defaults for deployments that had configured nothing. `nats_ack_wait`, `nats_max_ack_pending` and + `nats_max_deliver` are now applied only when set; unset, the server's default stands (NATS: 30 s, + 1000, unlimited). With `nats_max_deliver` unset, a message that keeps failing is retried without + limit and never dead-lettered, as before 0.9.0 -- set it to bound retries. Consumers that already + exist keep their settings, and an unset key is not reported as a difference. +- **`ClientBase.subscribe()` callbacks take the delivery subject.** The contract is now + `DeliveryCallback = Callable[[CloudEvent, str], Awaitable[None]]` (in `clients/client_base.py`): + the event, then the subject it arrived on. Only code that calls `NATSClient.subscribe()` directly, + or implements `ClientBase`, is affected -- handlers are not. A one-argument callback now fails + with a `TypeError` on the first message. +- **`nats_url` has no default outside development.** With `event_bus = "nats"` and no `nats_url`, + a process whose `app_environment` is anything but `"development"` now fails startup naming the + key -- a standalone or critical agent before the port is bound, a non-critical agent of a group + by being marked down. It used to connect to `nats://localhost:4222`, which in a pod reaches + nothing and retried forever while the pod reported healthy. Development keeps the localhost + fallback, with a WARNING. A broker in the same pod needs `nats_url` set explicitly. +- **A process in development mode logs a WARNING at startup** that it is not suitable for + production. `app_environment` defaults to `"development"`, so a deployment that sets nothing now + says so in its own log. +- **`root` is required in `agents.toml`.** Every existing entry needs one line added; a map + without it refuses to start rather than guessing. For an image that copied one agent to `/app`, + that is `root = "."`. +- **The standalone image no longer runs the group entry point.** It serves + `src.main:create_app` directly. An existing project keeps working: `uvicorn src.main:app` is + still served for a pre-split `main.py`, and a project that wants the old command can keep it. +- **`agents.toml` inside an agent is refused unconditionally**, with no exception for an agent + mapped at the image root. That shape only existed to let a standalone agent be a group of one, + which it no longer has to be. +- **`asbs setup` no longer writes `agents.toml` into an agent.** The map says which agents an + *image* contains, which is a packaging decision -- an agent carrying one is an agent that knows + whether it is running alone. The single-agent `Dockerfile` writes a one-agent map into its own + image instead. Existing projects keep working; delete the file when the agent joins a group, + where it is refused. +- **The `src//main.py` group layout is retired.** An agent is now the same directory alone + or in a group -- `/settings.toml` beside `/src/` -- which is what lets it move + between repositories untouched. Multi-agent grouping has only ever shipped in 0.9.0 alphas, so + nothing stable depended on the old shape. +- **`AgentMapPartGenerator` is gone.** It generated a file that is no longer written; its + `agent_namespace` helper moved to `PartGeneratorBase`. -- **The `topic` label of the event counters is bounded under Dapr.** `blueprint.events.unhandled`, - `.duplicate` and `.skipped` took the topic from the request path, so posts to `/events/` - minted one time series each. A topic the agent did not declare is now counted as `` - (every topic, with `dapr_declarative_subscriptions = true`); the real one stays in the log line. - The DROP answer for an unparseable body is limited to the delivery route `/events/{topic}`: another - route of a `DaprEventing` subclass answers a malformed body with 422 again. +1. **`scheduler_mode` is required.** A project that registers a scheduler and does not set it fails + at `build()`, with an error naming both values and what each costs. `"in_process"` reproduces + today's behaviour exactly and is the no-op migration; `"event"` is the one that fixes #73. + Defaulting the key would either keep firing a timer per replica or silently stop ticking a + service with no broker, and neither is safe to inherit. +2. **A subject-unsafe `app_name` or `nats_queue_group` now fails at startup** instead of being + rewritten or reaching the broker. `app_name = "Health Monitor"` with an event-mode scheduler used + to derive `Health_Monitor.scheduler.`; the rewrite was invisible to whoever wrote the + `CronJob`, so the symptom was a tick that never arrived. Rename to a subject-safe value, or pass + `topic=` explicitly. +3. **A scoped `Config`'s dotted key no longer resolves against the whole tree.** `_scoped_get` used + to fall back from `.` to the raw key, and since an agent's section is + `[default.]`, that let one agent read another's settings. The fallback is now an allowlist + of the four prefixes the framework itself owns (`cache`, `event_publishing`, `runtimes`, + `runtime`). A project reading its *own custom* nested key through a scoped view now gets an error + naming the rule; flat keys and `Config.settings` are unaffected. +4. **A registry view that names another agent is refused.** `get_component(..., namespace="other")` + and `get_cache(..., namespace="other")` raise on a scoped view. Every in-framework caller passes + its own namespace or holds the application registry, so nothing internal is affected. +5. **A scoped `Config`'s telemetry `service.name` is the agent's name.** Affects a project using + `Config(agent_scope=...)`, which has shipped since April. A repo with `foo.app_name = "Foo + Service"` and no `foo.otel_service_name` sees `service.name` change from `Foo Service` to `foo`. + Migration is one line: set `.otel_service_name` to whatever the dashboards key on. A + project that passes no `agent_scope` is unaffected. +6. **Cache keys moved, twice -- for named caches and for agents in a group.** A cache is now + private to the agent that declared it, keyed on `(namespace, name)` with its own subdirectory + and Redis prefix. Such a cache upgrading with persistent Redis or a mounted disk cache sees its + old entries as **absent** — a cold cache, not an error. **A standalone agent's default cache is + unaffected:** its directory, Redis prefix and keys are unchanged, so it keeps its entries. A + group still needs exactly one writable mount, since an agent's store is a subdirectory of + `cache.cache_dir`. If any cache entry is load-bearing rather than an optimisation, migrate it + deliberately. +7. **Four declaration surfaces are deleted**: `AgentRegistration`, `RegisteredComponent`, + `NamespaceBuilder`, and `AppBuilder.with_namespace` / `with_registration`. `AppBuilder` is the one + declaration surface; `AgentGroup` collects named declarations into a process. Passing an + already-built component instance (`with_service(MyService())`) still works for a single standalone + agent and is refused in a group — pass the class, or a zero-argument factory. +8. **`ClientBase.subscribe` changed from `(topic, callback)` to `(topic_callbacks)`**, and + `EventHandlingBase.subscribe` and `POST /nats/subscribe/{topic}` are removed. This affects + third-party transport implementations; both in-repo clients are updated. +9. **On grouped Dapr, one delivery is fanned out in-process to every agent that declared the + topic, and the single acknowledgement the sidecar receives is their combination** — so a retry + asked for by one agent redelivers to all of them. The sidecar fetches the subscription document + from one fixed path, which is why there is one endpoint at the root that routes rather than one + document per agent. Set `idempotency_enabled` for grouped Dapr, or keep handlers + repeat-tolerant. Single-agent Dapr and NATS are both unaffected. +10. **`Registry.update_component_name` refuses a name that is already taken** instead of overwriting + it. Anything relying on the overwrite was losing a component silently. +11. **`asbs setup` now scaffolds `.secrets.toml`**, the name `DEFAULT_SETTINGS_FILES` actually loads; + it used to write `secrets.toml`, which nothing read. This is a change to the *scaffolder* only — + the framework's file list is untouched, so no existing deployment changes. `asbs validate` + reports an undotted file as the rename it needs. An already-scaffolded project should rename its + file. +12. **`Component.shared_config` is now private (`Component._shared_config`)**, with + `Component.reset_shared_state()` as the one supported way to clear it. The old attribute was + public and writable but read by nothing outside `_ComponentMeta`, so hiding it looked like + code-only cleanup. It is not: a test suite that rebuilds its `AppBuilder` app once per test case + and resets state between cases with the old `Component.shared_config = None` now silently + no-ops, since the real state lives on `_shared_config` — `Component.configure()`'s "already set" + guard then trips starting from the second test in the run, with an error that does not name this + rename. **Any project resetting shared state between test cases must switch to + `Component.reset_shared_state()`** in its fixtures; this also clears `shared_registry`, which + stays public and is otherwise unaffected. A project that never resets shared state between + builds is unaffected. +13. **A scheduler tick runs in one replica, not in every one.** Before, every replica -- and every + worker -- ran its own timer and each ran every tick. Now `scheduler_mode = "event"` delivers the + tick through the queue group to one replica, and `"in_process"` claims each tick in the cache so + one replica runs it. A deployment that relied on every replica running a tick in parallel -- a + per-pod cleanup, say -- now runs it once per tick; register the cache per pod, or do the per-pod + work outside the scheduler. Without a registered cache, `"in_process"` still runs every tick in + every replica, and says so with a WARNING at startup where it used to log an INFO. +14. **A Core NATS event reaches one replica, not every one.** Subscriptions now join a queue group + (`nats_queue_group`, else `app_name`); before, every replica received and processed every event. + A deployment that relied on each replica seeing each event now sees each event once. +15. **`Config()` no longer configures logging.** Constructing a `Config` used to set up the root + logger; library code must not, so `AppBuilder` does it now. A script or test that builds only a + `Config` and relied on its logging setup has to configure logging itself. +16. **`Config.settings` is read-only.** It was a plain attribute; assigning to it now raises + `AttributeError`. Replacing the settings tree underneath a running configuration bypasses every + agent's view of it and is not supported. +17. **Metrics a project records itself are now exported.** With OpenTelemetry enabled, the framework + registers a global `MeterProvider` that exports over OTLP. Before, it registered none, so a + counter a project created through `metrics.get_meter(...)` was silently discarded; the same + unchanged code now reaches the collector, which can add series -- and cost -- to a metrics + backend. A project that registered its own `MeterProvider` first keeps it: the SDK refuses a + second one and the framework's is not installed. -- **A slow cache no longer holds up every delivery of the process.** The dedup claim and release, and - the in-process scheduler's tick claim, ran on the event loop, so a Redis that stopped answering - stalled every agent for as long as the call blocked. They now run in a worker thread. **The minimum - redis-py is now 8.0**, the release that bounds every call by a 5 s default; before it the default - was no timeout at all. New, opt-in: `cache.redis_socket_timeout`. Measured with the Redis container - paused and a 2 s timeout: the event loop's longest gap was 0.06 s (before: 2.02 s), and the claim - failed open after 2 s. Startup now warns when deduplication runs without a heartbeat -- NATS with - `nats_heartbeat_enabled = false`, and Dapr -- where a redelivery of a running event is skipped as a - duplicate. +### Added -- **Scaffolded images select the production environment, and the group image turns healthy.** The - generated Dockerfiles set `DYNACONF_ENVIRONMENT`, which selects nothing, so every image ran the - `development` section; they now set `DYNACONF_APP_ENVIRONMENT` (`production`, and `development` in - the dev stage). **Existing projects: rename the variable in your Dockerfile** -- the image then - loads `[production]`, with no localhost broker fallback. The group image's health check used `curl`, - which its slim base does not have, and is now a Python one. `asbs setup` checks the agent's name - before writing anything, `asbs create service` writes a service that imports, and the messages - about what `asbs dev` serves without `--name` (the agent alone, at the root namespace) are correct. - -- **`/status/env` no longer leaks what its masking missed, and no longer fails on `${PORT}`.** A URL - password holding `/`, `?` or `#` was partly returned, a token in a query string, an `AccountKey=` in - a connection string and every value of a section under a secret-named key (`credentials`) were - returned in clear, and keys such as `sentry_dsn` or `db_pass` were not recognised; a URL with a - non-numeric port answered 500. Measured over HTTP: seven placeholder secrets in the response - before, none now; status 200 with `${PORT}` (before: 500). - -- **Clearing the root Redis cache no longer clears every agent's.** Every named and agent cache nests - under the default store's key prefix, and its `clear()` deleted everything under it -- with - `key_prefix = ""`, the whole database. Its `list_namespaces()` listed the nested stores as its own - namespaces. The default store now touches only keys of its own form, and a clear without a prefix - warns. The key layout is unchanged. Measured on Redis 7: two agents' caches and a foreign key survive - a root clear (before: all gone, the database empty without a prefix). +- **`examples/site_readings`: named connections end to end.** One agent, two sites, each its own + NATS account, supplied by a `ConnectionSource` (claims, a per-connection subject prefix, `validate`, + `run_scope`), with the example broker, a provisioning script and offline tests. +- **A JetStream run knows which attempt it is.** The handler context carries `nats_delivery_attempt` + (1-based) and `nats_max_deliver` (`None` when unlimited) on the default and on named connections, + so a service can close open work on the last attempt instead of leaving it open. Core NATS + deliveries carry neither key. +- **`HandlerResult.skipped(reason)`.** A handler that is responsible for an event but finds it needs + nothing returns it: the chain stops (no later handler is asked, unlike `None`), the delivery is + acknowledged, nothing is published, the reason is logged at INFO and the event is counted as + `blueprint.events.skipped` rather than as unhandled. The run reports the new + `ProcessingStatus.SKIPPED`; a REST caller gets `success = true` with the reason as message. +- **Per-connection state and `nats_connections_readiness`.** Each agent with named connections gets a + readiness entry `.nats_client:connections` listing every connection as `bound`, `connecting`, + `reconnecting`, `retrying` (with the last error, redacted) or `paused`, and any permission violation, + plus the gauge `blueprint.nats.connection.bound` and the counter + `blueprint.nats.connection.permission_violations` (attributes `agent`, `connection`). The new agent-scope + key decides whether the entry can fail: `"never"` (default), `"any"` (one bound) or `"all"` (every one + bound); another value fails startup. In every mode a named connection feeds readiness only and never + pauses the agent, so its other connections keep delivering. A paused agent whose default connection + comes back re-evaluates readiness at once instead of at the next health interval. +- **Named connections change at runtime.** A connection source that defines `watch(notify)` tells every + agent's client when its connections change; the client binds a new connection, replaces a changed one + (new link bound before the old one is retired) and retires a removed one: drained, its runs given + `subscription_change_grace` seconds, the rest revoked -- never settled, `publish` refused with the new + `DeliveryRevokedError`, not cancelled. A change never interleaves with a pause, and no consumer is + deleted. A permission the broker refuses is retried every 60 s with an ERROR instead of at full pace. +- **`asbs validate` warns about a swallowed `asyncio.CancelledError`** in an agent's `src/` (and for + every agent with `--group`), with file and line: such code keeps a run going past + `nats_handler_timeout`, and the delivery is nak'd and redelivered anyway. +- **`ConnectionSource.claims(agent, subjects)` and `nats_unclaimed_subjects`.** The source says which + subjects belong to named connections, independently of which connections exist; those never go to + the agent's default connection, so a fresh deployment without a tenant subscribes nothing there. A + subject not claimed fails startup unless `nats_unclaimed_subjects = "default_connection"` allows it. +- **Named NATS connections (`nats_connection_source`).** A deployment can give its agents further NATS connections -- one account and one existing JetStream consumer each -- through a connection source named by a process-scope key. The framework binds to the deployment's consumers verbatim and never provisions on them, checks each delivery with the source's validation hook before it runs, runs it in an empty context inside the source's scope, and settles, heartbeats and dead-letters it on its own connection. Agents keep declaring their subjects as before and see them without the connection's prefix; `nats_connection` names the connection in the handler context. Unset, nothing changes. +- **`nats_max_concurrent_runs`** (number or `"N%"`, unset by default): how many deliveries an (agent, + connection) pair runs at once per process; unset keeps one run per subscription. The pair's first run + is always allowed; further runs also need a slot of **`nats_extra_runs_per_process`** (process scope, + number or percentage of the process's pairs, unset unlimited). With every slot taken the subscription stops taking + messages; keep `nats_max_ack_pending` near replicas x this value. +- **`nats_heartbeat_enabled`** (bool, default `true`): switches the delivery heartbeat off for an agent. +- **`nats_handler_timeout`** (seconds, unset by default): the longest one run may take. At the limit the + run is cancelled and nak'd for immediate redelivery; a `TimeoutError` of the handler's own is an + ordinary failure. Unset, a run is never cut. +- **`RestApiBase.path_prefix`**, an optional class attribute putting every route of an API under + one segment -- `/api/reports/...` standalone, `/api//reports/...` in a group. Default `""`, + so no existing path moves. +- **The migration docs name absolute `src` imports as a pitfall.** `from src.x import Y` works for + an agent served on its own and fails in a group, where a non-critical agent is then skipped with + one ERROR line and its routes are missing from `/docs`. The `blueprint-migration` skill and + `guides/multi-agent-migration.md` now carry the cause, the log line, the fix (relative imports, + which keep working standalone) and a `grep` that finds them. `asbs validate --group` reports + them as a warning, with file and line. +- **Handlers see the subject a NATS message was delivered on**, as `context["nats_subject"]` + (`NATS_SUBJECT_CONTEXT_KEY`), beside `nats_topic`, which is the subscription and may be a + wildcard. It comes from the broker, not the event, so a tenant can be derived from the subject the + broker checked rather than from the publisher-controlled `tenantid`. +- **NATS credentials from their own keys.** `nats_user`/`nats_password`, `nats_token`, + `nats_creds_file` and `nats_nkey_seed` are passed to the connection, so an account under + tenant-scoped auth no longer has to put its credentials inside `nats_url`. At most one method may + be configured; a half-set login, a creds file that is not there, or two methods at once fail + startup. `nats_inbox_prefix` replaces `_INBOX` for accounts not permitted `_INBOX.>`. All are read + per agent, so each agent of a group can have its own account. The dependency on `nats-py` is now + `nats-py[nkeys]`, which creds files and nkey seeds need. +- **A `blueprint-migration` Claude Code skill**, installed by `asbs claude`: moving an existing + single-agent project into a group -- the files it touches, the mistakes that break it, and how + `asbs validate --group` checks it. The migration guide was previously reachable only from inside + `blueprint-multi-agent`. `asbs claude` now lists the skills and agents it installed by reading + them from the package, rather than from a hand-kept list that would have left any new skill + unannounced. +- **A standalone agent declares nothing group-related.** `asbs setup` writes a `create_app()` + factory beside the declaration, and the generated Dockerfile serves it with + `uvicorn src.main:create_app --factory` -- no agent map, no group, no namespace. A group of one + is still a group, and requiring an agent to declare itself one in order to run alone is what put + the group's own file inside the agent. The same directory is still hosted by a group image + without changing a line; its components simply gain that agent's namespace, and with it the + `/api/` route prefix. +- **`.dockerignore`**, written by both `asbs setup` and `asbs setup --group`. Not tidy-up: the + group image copies the whole `agents/` tree, because which agents a process runs is decided at + startup rather than at build time -- and Docker's build context is the filesystem, not the + repository, so `**/.secrets.toml` being in `.gitignore` did nothing to keep real keys out of a + layer. +- **`asbs setup --group` writes a `pyproject.toml`** as well. The group Dockerfile's builder stage + installs from one, so without it the image could not be built. +- **The declaration rules apply to `create_app` too.** A component registered as an already-built + instance is refused when a *host* builds a declaration -- `create_app()` or a group -- because an + agent that works standalone only because nobody checked is an agent that fails the day it joins a + group. The older shape, `AppBuilder(config)` built in place, stays permissive and keeps working. +- **`root` in the agent map**, required per agent, relative to the directory `agents.toml` is in. + Stated rather than derived: a root guessed from where a declaration happens to sit is right for + one layout and silently wrong for every other, and nesting an agent at any depth now costs + nothing. A missing `root`, one that escapes the image, one that is not a directory, and two + agents sharing one are each refused at startup, naming the agent. +- **Misplaced files are refused, not ignored** (`blueprint.agents.layout`). One table of artefacts + with a single legal location, enforced at group assembly and reported by `asbs validate + --group`: `settings.toml` and `.secrets.toml` beside `src/`, `agents.toml` at the image root. + `Dockerfile` is deliberately absent from it -- an agent may own one while living in a group + repository. Adding an artefact is one tuple. +- **`asbs setup --group`** writes the image's files -- an empty agent map, the process settings + and a group Dockerfile -- and creates no agent. +- **`asbs validate --group`** validates an image: every `root`, each agent's layout, misplaced + files, process-wide keys left in an agent, and which `settings.toml` each agent actually reads. +- **`asbs dev --name`**, and `asbs dev` no longer needs an `agents.toml` in an agent's directory. + It writes the one-agent map outside the project for that run. -- **Crontabs read the same in both scheduler modes, or fail startup.** The day of the week is - apscheduler's count -- `0` = Monday ... `6` = Sunday -- so `in_process` firing days do not move. `7` is - refused (it was accepted in `event` mode and failed only when the timer was built), and **an `event`-mode - scheduler whose crontab gives the day of the week by number (`1-5`, `*/2`) now fails startup**: the - external cron counts `0` as Sunday, so the number named a different day there. Write names - (`mon-fri`). The crontab is now checked when the scheduler is wired in both modes. New, opt-in: - `scheduler_timezone` for the `in_process` timer; unset keeps the host's local time. +- **The documentation ships inside the package.** The user-facing guides moved from the repository + root to `src/blueprint/agent_generator/docs/` and are now installed with the wheel, so a + developer or an AI assistant working in a consuming project can read them with no network access. + Previously `README.md` became the wheel's `METADATA` while the 21 documentation pages it links to + stayed behind in the repository, and every one of those links resolved to nothing once installed. +- **`asbs docs`** locates the packaged documentation: `asbs docs` lists every page, `asbs docs + ` prints the path to one, `asbs docs --cat` prints its contents, and `--root` + prints the directory. A bare page name is accepted when it is unambiguous. +- **Seven Claude Code skills**, installed by `asbs claude` alongside the two that already existed: + `blueprint-cli`, `blueprint-config`, `blueprint-events`, `blueprint-multi-agent`, + `blueprint-testing`, `blueprint-deployment` and `blueprint-troubleshooting`. Each carries the + rules that are expensive to get wrong and points at the packaged page for the rest, rather than + restating it -- the docs stay the single source of truth. -- **A scheduler whose startup failed is no longer reported as recovered.** It was marked started before - its timer existed, so the startup retry found it "already started" and cleared the agent's latch - with no timer running. +- **Agent grouping.** `agents.toml` names the agents an image contains and the module each + declaration lives in; `BLUEPRINT_AGENTS`, or `BLUEPRINT_GROUP` plus a mounted + `BLUEPRINT_GROUP_CONFIG` file, decides which of them a given process runs; + `python -m blueprint.agents.entrypoint` resolves, builds and serves them. Each hosted agent owns + its handlers, agent runtime, REST routes (`/api/`), AI client, thread pool, caches and + broker connection; the port, the health endpoint and the process are shared. + `BLUEPRINT_CRITICAL_AGENTS` says which agents failing should fail the process. +- **Agents in one process are isolated, and the barrier is enforced rather than conventional.** An + agent resolves its own components, caches and configuration plus the root's shared ones. Reaching + a neighbour by its registry key, by an explicit `namespace=` on a view, by a dotted configuration + key, or by sharing one declaration's mutable argument between two agents is refused or reported + absent. `Config.settings` remains the documented escape hatch and logs a WARNING naming the agent. +- **An agent's identity is stable across regrouping** (spec C1): its NATS queue group, JetStream + durable, cache partition, OpenTelemetry `service.name`, registry prefix and REST prefix all derive + from the agent's own name and never from the group or the pod. +- **Per-agent observability.** `service.name` per agent, `blueprint_namespace_up{agent}`, a + readiness entry and health checks attributed per agent, `blueprint.scheduler.tick_age_seconds`, + `blueprint.events.dead_lettered`, `blueprint.events.unhandled` and `blueprint.events.duplicate`. +- **`CacheService.claim`** — set-if-absent, atomic on both backends (`add` on disk, `SET NX EX` on + Redis). This is the compare-and-set primitive the deduplication work flagged as missing. +- **Named caches.** `with_cache(name=...)`, `/cache/*` endpoints take `?name=`, and `/readiness` + gains a `cache:` entry per named cache. +- **Opt-in event deduplication** — `idempotency_enabled` and a required `idempotency_ttl`. Off by + default; a failed dispatch releases its claim so the nak's redelivery still runs. +- **`nats_publish_mode`** (`"core"` / `"jetstream"`) separates publishing from durable consumption, + with `nats_publish_subjects` for subjects not already in `event_publishing.topic_mapping`. Unset, + it follows `nats_use_jetstream`, so nothing existing changes. +- **`run_app`**, so a project can serve itself from its own settings. +- **Scaffolding**: `asbs setup` now writes `agents.toml`, a `pyproject.toml` and two tests, so + `asbs setup` → `pytest` → `asbs validate` closes; `asbs validate` reports what a project has not + said about grouping and about idempotency; the CLI no longer crashes on a Windows console. +- New config keys: `event_client_drain_timeout`, `dapr_pubsub_name`, + `dapr_declarative_subscriptions`, `idempotency_enabled`, `idempotency_ttl`, `scheduler_mode`, + `event_publishing_enabled`, `nats_publish_mode`, `nats_publish_subjects`. All default to current + behaviour except `scheduler_mode`, which is required — see below. +- `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. -- **Every scheduler's `blueprint.scheduler.tick_age_seconds` is exported.** A second scheduler of one - agent created a second gauge of the same name, which the SDK drops, so only the first was reported. - Measured with two in-process schedulers: two points (before: one). +### Changed -- **`asbs validate` checks schedulers as the runtime does.** It accepts `scheduler_mode` written as the - runtime reads it (`"Event"`), counts environment overrides, refuses an `event_bus` that cannot deliver - a tick, reports a missing `event_bus` as a notice (it is a process-wide key and may be set elsewhere), - and `--group` runs the scheduler checks per agent. +- **One `main.py` pattern in every document, skill and agent prompt: the template's.** `src/main.py` + is a declaration (`agent = AppBuilder()...`, unbuilt `AgentBuilder`, components as classes) with + a `create_app()` for running it alone. The docs showed three patterns, including `.with_config()`, + `.with_api()` and `AgentBuilder().with_name()`, which do not exist, and a built `AgentRuntime` + that a group refuses. +- **Handlers translate, services decide -- in the scaffold and every document.** The handler + template no longer says "this is where the main business logic is implemented": + `can_handle_event` routes on the envelope only, `handle_event` extracts the payload, makes one + service call and returns the answer (`HandlerResult`, `HandlerResult.skipped(reason)` or `None`); + idempotency belongs to the service; handlers never call the LLM. The chain semantics are stated + as the code has them: the first result that is not `None` ends the chain (the docs said a + `HandlerResult` let later handlers run). +- **The examples follow the handler and service rules.** One handler per event type making one + service call (`webhook_relay`, `order_event_pipeline`), APIs that translate request DTOs into + domain models (`document_summarizer`, `inventory_api`), a scheduler with one service call + (`health_monitor`), no `assert` in production code, and the template's model file names + (`dto.py`, `domain_models.py`). +- **`asbs validate` checks the NATS delivery keys** that otherwise fail only at startup: + `nats_max_concurrent_runs`, `nats_extra_runs_per_process`, `nats_handler_timeout`, + `nats_connections_readiness`, `nats_unclaimed_subjects`, and the form and module of + `nats_connection_source` (the factory is not called). +- **`docs/guides/cli-reference.md` is an index**, with one page per command under `guides/cli/` + (`setup`, `create`, `validate`, `dev`, `claude`, plus `naming` and `auto-registration`). It was a + single 1,023-line page, which meant reading about one flag cost the whole file. +- **Migrating an existing agent into a group is its own page**, + `guides/multi-agent-migration.md`, split out of `guides/multi-agent-setup.md`. +- **`README.md` links are absolute.** Relative links do not resolve on the PyPI project page or in + the installed `METADATA`. The CI badge pointed at an unrelated repository. -- **A grouped scheduler's tick subject and trigger route name the agent once.** Both were built from the - scheduler's qualified name, so the subject was `orders.scheduler.orders_nightly` and the route - `/api/orders/scheduler/orders_nightly/trigger`; they are now `orders.scheduler.nightly` and - `/api/orders/scheduler/nightly/trigger`, as the docs said. **Alpha users of grouped event-mode - schedulers: move the publishing `CronJob` to the new subject.** A standalone scheduler is unchanged. - An event-mode scheduler's tick handler now belongs to the scheduler's agent; it was registered at the - root, in the root's handler chain. +### Fixed -- **The registry keeps agents apart where it did not.** A namespaced lookup's qualified key could be - another agent's (`orders` + `eu_ledger` is `orders_eu` + `ledger`); it now has to belong to the asking - agent. A view can no longer clear the registry, shut down the thread pools, rename or register - another agent's component, or take another agent's thread pool. A declaration shared by several - agents is now also refused when it carries state in a bound method or a closure. +- **With deduplication on, an event cut off by `nats_handler_timeout` is no longer lost.** The run + is cancelled and nak'd, but the dedup marker was released only for an `Exception`, and + cancellation is not one. The redelivery found the marker, was skipped as a duplicate and + acknowledged, and the event was never processed. The same happened to a handler that swallowed + the cancellation, to a run cancelled by a shutdown, and to a failure after the handler returned + (a scalar return value that is not a valid `HandlerResult`). A delivery now keeps its marker only + when it is acknowledged. Measured against JetStream with a 0.5 s limit: before, one run and the + redelivery acknowledged unrun; now the redelivery runs to completion. -- **An agent's own `.secrets.toml` is read in a group.** Only its `settings.toml` was merged, although - the layout check, the guides and `asbs setup` said the secrets beside it are read. It is now merged - first, so a secret wins over the settings file, and none of its values is logged. +- **A group named only by its group file is the deployment group** (S19). A group file that declares + one group needs no `BLUEPRINT_GROUP`, but the name reached neither the NATS connection name, the + telemetry resource's `deployment.group` nor the supervisor's log lines, which read only the + variable: they said ``. They now carry the resolved name. -- **Agent settings are resolved for the environment the process actually loaded.** With - `ENV_FOR_DYNACONF` set, the process loaded that environment while every agent's file was layered for - `app_environment`; and each agent kept its other environments' sections as keys (`production` in - development). Both now follow what Dynaconf loaded. +- **`diskcache-rs` 0.4.10 is the minimum, and a disk cache's claim is documented as per-process** + (S23). 0.4.9 and earlier refused a second process the cache directory ("Database already open"). + 0.4.10 lets several open it, but its set-if-absent is not atomic between them: four processes + claiming one key at once each won in 297 of 300 rounds. Deduplication and the in-process tick + claim therefore hold across replicas, and across several `app_workers`, only with Redis; the docs no + longer say "a disk cache on a shared volume". -- **An agent can no longer read or overwrite what is not its own through its name.** `cache`, - `event_publishing`, `runtimes` and `runtime` are refused as agent names (an agent's settings would - have landed in the shared section); merging an agent's settings onto a plain key of the same name - fails instead of replacing it; and a view refuses a bare key naming another agent, which returned that +- **A standalone application written for 0.8 builds again** (S20). Three 0.8 shapes were refused + or changed: + - A health check of the application's own under a built-in name (`cache`, a client's name) + replaced the built-in in 0.8 and failed the build here. It replaces it again, with a WARNING. + Two checks of the application's own under one name are still refused. + - A handler instance passed after a handler class of the same priority failed the build. Every + declared handler now registers in declaration order, as 0.8 did, whether passed as a class or + as an instance. + - A `SessionsJobHandler` subclass that widened `can_handle_event` was only offered its own job + type, which it declared automatically. It declares nothing now when it overrides the selector, + and is offered every event as in 0.8. + +- **asyncio debug mode is off unless `event_loop_debug` is set** (S21). It was on by default in + development -- the default environment -- so an application that never set one paid for debug + mode on every coroutine. The watchdog runs instead. The value is read as a boolean: `"false"` + from an environment variable means false, and a value that is no boolean fails startup. + +- **Shutdown runs to the end past a failed step** (N1). A startup recovery task that had ended by + raising re-raised while shutdown cancelled it, and a failing actuator shutdown raised out of the + lifespan; either skipped every later step. Both are logged and shutdown goes on. + +- **A JetStream consumer that filters another subject is no longer bound.** Root topic + `orders-created` and agent `orders` on topic `created` derive the same durable name + (`orders-created-durable`). Whichever started second bound the other's consumer with only a + drift warning, and received that topic's messages in its own handler. It now refuses to bind: + the subscription fails with an error naming the consumer, its filter and the topic, and the + connection retries. Rename one of the topics. + +- **The "Created JetStream consumer" line is logged when `nats_ack_wait` is unset.** It formatted + the unset value with `%.1f`, so the line was lost to a logging error; it now reads + `ack_wait server default`. A delivery whose run could not be started no longer keeps its run slot. + +- **A group's telemetry is no longer cut off at shutdown.** All agents share one span processor + and one metric exporter, and the first provider to shut down closed them for every other: the + remaining agents' final metrics were dropped ("Exporter already shutdown"). They are now closed by + the last provider, and the application's shutdown flushes every provider after its components + have stopped -- agents first, the root last. Measured against a collector: 2 of 4 final metric + points arrived before, 4 of 4 now. + +- **In a group, `OTEL_SERVICE_NAME` no longer names every agent alike.** The agents keep their own + name as `service.name`; the variable names the root's telemetry, as standalone. Startup logs a + WARNING naming the value. `OTEL_RESOURCE_ATTRIBUTES` is unchanged. + +- **Grouped Dapr: each agent gets its own copy of a delivery, and the answer has no stray reason.** + The fan-out handed one `CloudEvent` object to every agent declaring the topic, so a change one + handler made to it reached the next. A delivery one agent acknowledged and another terminated + answered `SUCCESS` with the terminating agent's reason. Startup now warns about a topic two agents + declare while one of them runs without `idempotency_enabled`, since a retry asked for by one + redelivers to all of them. + +- **The `topic` label of the event counters is bounded under Dapr.** `blueprint.events.unhandled`, + `.duplicate` and `.skipped` took the topic from the request path, so posts to `/events/` + minted one time series each. A topic the agent did not declare is now counted as `` + (every topic, with `dapr_declarative_subscriptions = true`); the real one stays in the log line. + The DROP answer for an unparseable body is limited to the delivery route `/events/{topic}`: another + route of a `DaprEventing` subclass answers a malformed body with 422 again. + +- **A slow cache no longer holds up every delivery of the process.** The dedup claim and release, and + the in-process scheduler's tick claim, ran on the event loop, so a Redis that stopped answering + stalled every agent for as long as the call blocked. They now run in a worker thread. **The minimum + redis-py is now 8.0**, the release that bounds every call by a 5 s default; before it the default + was no timeout at all. New, opt-in: `cache.redis_socket_timeout`. Measured with the Redis container + paused and a 2 s timeout: the event loop's longest gap was 0.06 s (before: 2.02 s), and the claim + failed open after 2 s. Startup now warns when deduplication runs without a heartbeat -- NATS with + `nats_heartbeat_enabled = false`, and Dapr -- where a redelivery of a running event is skipped as a + duplicate. + +- **Scaffolded images select the production environment, and the group image turns healthy.** The + generated Dockerfiles set `DYNACONF_ENVIRONMENT`, which selects nothing, so every image ran the + `development` section; they now set `DYNACONF_APP_ENVIRONMENT` (`production`, and `development` in + the dev stage). **Existing projects: rename the variable in your Dockerfile** -- the image then + loads `[production]`, with no localhost broker fallback. The group image's health check used `curl`, + which its slim base does not have, and is now a Python one. `asbs setup` checks the agent's name + before writing anything, `asbs create service` writes a service that imports, and the messages + about what `asbs dev` serves without `--name` (the agent alone, at the root namespace) are correct. + +- **`/status/env` no longer leaks what its masking missed, and no longer fails on `${PORT}`.** A URL + password holding `/`, `?` or `#` was partly returned, a token in a query string, an `AccountKey=` in + a connection string and every value of a section under a secret-named key (`credentials`) were + returned in clear, and keys such as `sentry_dsn` or `db_pass` were not recognised; a URL with a + non-numeric port answered 500. Measured over HTTP: seven placeholder secrets in the response + before, none now; status 200 with `${PORT}` (before: 500). + +- **Clearing the root Redis cache no longer clears every agent's.** Every named and agent cache nests + under the default store's key prefix, and its `clear()` deleted everything under it -- with + `key_prefix = ""`, the whole database. Its `list_namespaces()` listed the nested stores as its own + namespaces. The default store now touches only keys of its own form, and a clear without a prefix + warns. The key layout is unchanged. Measured on Redis 7: two agents' caches and a foreign key survive + a root clear (before: all gone, the database empty without a prefix). + +- **Crontabs read the same in both scheduler modes, or fail startup.** The day of the week is + apscheduler's count -- `0` = Monday ... `6` = Sunday -- so `in_process` firing days do not move. `7` is + refused (it was accepted in `event` mode and failed only when the timer was built), and **an `event`-mode + scheduler whose crontab gives the day of the week by number (`1-5`, `*/2`) now fails startup**: the + external cron counts `0` as Sunday, so the number named a different day there. Write names + (`mon-fri`). The crontab is now checked when the scheduler is wired in both modes. New, opt-in: + `scheduler_timezone` for the `in_process` timer; unset keeps the host's local time. + +- **A scheduler whose startup failed is no longer reported as recovered.** It was marked started before + its timer existed, so the startup retry found it "already started" and cleared the agent's latch + with no timer running. + +- **Every scheduler's `blueprint.scheduler.tick_age_seconds` is exported.** A second scheduler of one + agent created a second gauge of the same name, which the SDK drops, so only the first was reported. + Measured with two in-process schedulers: two points (before: one). + +- **`asbs validate` checks schedulers as the runtime does.** It accepts `scheduler_mode` written as the + runtime reads it (`"Event"`), counts environment overrides, refuses an `event_bus` that cannot deliver + a tick, reports a missing `event_bus` as a notice (it is a process-wide key and may be set elsewhere), + and `--group` runs the scheduler checks per agent. + +- **A grouped scheduler's tick subject and trigger route name the agent once.** Both were built from the + scheduler's qualified name, so the subject was `orders.scheduler.orders_nightly` and the route + `/api/orders/scheduler/orders_nightly/trigger`; they are now `orders.scheduler.nightly` and + `/api/orders/scheduler/nightly/trigger`, as the docs said. **Alpha users of grouped event-mode + schedulers: move the publishing `CronJob` to the new subject.** A standalone scheduler is unchanged. + An event-mode scheduler's tick handler now belongs to the scheduler's agent; it was registered at the + root, in the root's handler chain. + +- **The registry keeps agents apart where it did not.** A namespaced lookup's qualified key could be + another agent's (`orders` + `eu_ledger` is `orders_eu` + `ledger`); it now has to belong to the asking + agent. A view can no longer clear the registry, shut down the thread pools, rename or register + another agent's component, or take another agent's thread pool. A declaration shared by several + agents is now also refused when it carries state in a bound method or a closure. + +- **An agent's own `.secrets.toml` is read in a group.** Only its `settings.toml` was merged, although + the layout check, the guides and `asbs setup` said the secrets beside it are read. It is now merged + first, so a secret wins over the settings file, and none of its values is logged. + +- **Agent settings are resolved for the environment the process actually loaded.** With + `ENV_FOR_DYNACONF` set, the process loaded that environment while every agent's file was layered for + `app_environment`; and each agent kept its other environments' sections as keys (`production` in + development). Both now follow what Dynaconf loaded. + +- **An agent can no longer read or overwrite what is not its own through its name.** `cache`, + `event_publishing`, `runtimes` and `runtime` are refused as agent names (an agent's settings would + have landed in the shared section); merging an agent's settings onto a plain key of the same name + fails instead of replacing it; and a view refuses a bare key naming another agent, which returned that agent's whole section. - **A group file that says something other than what it means now fails startup.** A name in @@ -366,461 +726,53 @@ printed the URL verbatim, and the NATS health message printed the parsed URL including `user:password@`. Both now show `***@host:port`. - **An environment override of a key an agent's own `settings.toml` also sets now wins in a group.** - `DYNACONF___KEY` was compared against the agent file's keys case-sensitively -- Dynaconf - upper-cases what it loads, the file keeps lower case -- so the override was never seen: a list - was concatenated with the file's, a scalar was replaced by the file's value, and the key was - reported as merged. Keys are now matched case-insensitively, at every nesting level. -- **Both scaffolded `Dockerfile`s declared a `HEALTHCHECK` against a route that does not exist.** - `curl -f http://localhost:8000/health` -- but `ActuatorApi` serves `/health/live` and - `/health/ready`, and nothing at `/health`. `curl -f` fails on the 404, so every container built - from a scaffold reported `unhealthy` for its whole life: compose's `depends_on: - service_healthy` never released, and anything reading Docker's health state saw a permanently - failing container that was in fact serving traffic. Both now probe `/health/live`, which is what - the deployment guide has always shown. A generated-project test holds the path. - -- **`asbs validate --group` contradicted the runtime about where an agent's `root` points.** The - runtime resolves every `root` against the **image root** -- the directory the process runs in -- - and `BLUEPRINT_AGENT_MAP` may put the map anywhere, so a repository keeping `deploy/agents.toml` - with its agents at the top runs correctly. The validator resolved each `root` against whichever - directory the map sat in, so it reported that layout as `... is not a directory` under the - verdict "would stop this image starting" -- a false statement about a working image, whose - correct reading is to break a layout that worked. The two coincide only where the map is at the - image root, which is what `asbs setup --group` writes, so no test caught it. The command now - takes the directory argument as the image root and `--agent-map PATH` (or `BLUEPRINT_AGENT_MAP`) - as where the map is; a relative path resolves against the image root, as at runtime. The error - for an absent map names the flag. Present since `root` became required in 0.9.0a4. -- **An agent settings file that scoped keys under the agent's own name merged into nothing.** - `[default.]` in that agent's own `settings.toml` nested to `..*` once the - file was merged under the agent's namespace, so every key in it was unreachable -- and the - failure surfaced far from the cause, as `No model name for runtime agent '_agent' - configured`, naming the agent rather than the file. Found migrating a real project. It is now - refused at merge, naming the section and the fix, and `asbs validate --group` reports it without - starting anything. Plain `[default]` serves both shapes: standalone resolves it because a scoped - lookup falls back to the root key. -- **A grouped agent's own `settings.toml` was never read.** The group looked for it beside the - *declaration module* -- inside `src/` -- while every scaffolded project writes it beside `src/`, - so the file existed, looked right, and was never opened. Nothing failed: the agent ran on the - group's defaults and said so nowhere. It is now read from the directory the agent map states. -- **Prompts resolved against the process working directory.** One directory for a whole group, so - it was right for at most one agent; the others found nothing, or found a neighbour's prompt of - the same name. Each agent's configuration view now reports its own directory as the package - root, so `/src/prompts` resolves exactly as it does standalone. -- **A scaffolded agent no longer ships process-wide keys.** `log_level` and `log_format` were - written into every agent's `settings.toml`, so every group one joined dropped them with a - warning about a file the scaffolder itself wrote. They are now commented out, with the reason. - -### Added - -- **`examples/site_readings`: named connections end to end.** One agent, two sites, each its own - NATS account, supplied by a `ConnectionSource` (claims, a per-connection subject prefix, `validate`, - `run_scope`), with the example broker, a provisioning script and offline tests. -- **A JetStream run knows which attempt it is.** The handler context carries `nats_delivery_attempt` - (1-based) and `nats_max_deliver` (`None` when unlimited) on the default and on named connections, - so a service can close open work on the last attempt instead of leaving it open. Core NATS - deliveries carry neither key. -- **`HandlerResult.skipped(reason)`.** A handler that is responsible for an event but finds it needs - nothing returns it: the chain stops (no later handler is asked, unlike `None`), the delivery is - acknowledged, nothing is published, the reason is logged at INFO and the event is counted as - `blueprint.events.skipped` rather than as unhandled. The run reports the new - `ProcessingStatus.SKIPPED`; a REST caller gets `success = true` with the reason as message. -- **Per-connection state and `nats_connections_readiness`.** Each agent with named connections gets a - readiness entry `.nats_client:connections` listing every connection as `bound`, `connecting`, - `reconnecting`, `retrying` (with the last error, redacted) or `paused`, and any permission violation, - plus the gauge `blueprint.nats.connection.bound` and the counter - `blueprint.nats.connection.permission_violations` (attributes `agent`, `connection`). The new agent-scope - key decides whether the entry can fail: `"never"` (default), `"any"` (one bound) or `"all"` (every one - bound); another value fails startup. In every mode a named connection feeds readiness only and never - pauses the agent, so its other connections keep delivering. A paused agent whose default connection - comes back re-evaluates readiness at once instead of at the next health interval. -- **Named connections change at runtime.** A connection source that defines `watch(notify)` tells every - agent's client when its connections change; the client binds a new connection, replaces a changed one - (new link bound before the old one is retired) and retires a removed one: drained, its runs given - `subscription_change_grace` seconds, the rest revoked -- never settled, `publish` refused with the new - `DeliveryRevokedError`, not cancelled. A change never interleaves with a pause, and no consumer is - deleted. A permission the broker refuses is retried every 60 s with an ERROR instead of at full pace. -- **`asbs validate` warns about a swallowed `asyncio.CancelledError`** in an agent's `src/` (and for - every agent with `--group`), with file and line: such code keeps a run going past - `nats_handler_timeout`, and the delivery is nak'd and redelivered anyway. -- **`ConnectionSource.claims(agent, subjects)` and `nats_unclaimed_subjects`.** The source says which - subjects belong to named connections, independently of which connections exist; those never go to - the agent's default connection, so a fresh deployment without a tenant subscribes nothing there. A - subject not claimed fails startup unless `nats_unclaimed_subjects = "default_connection"` allows it. -- **Named NATS connections (`nats_connection_source`).** A deployment can give its agents further NATS connections -- one account and one existing JetStream consumer each -- through a connection source named by a process-scope key. The framework binds to the deployment's consumers verbatim and never provisions on them, checks each delivery with the source's validation hook before it runs, runs it in an empty context inside the source's scope, and settles, heartbeats and dead-letters it on its own connection. Agents keep declaring their subjects as before and see them without the connection's prefix; `nats_connection` names the connection in the handler context. Unset, nothing changes. -- **`nats_max_concurrent_runs`** (number or `"N%"`, unset by default): how many deliveries an (agent, - connection) pair runs at once per process; unset keeps one run per subscription. The pair's first run - is always allowed; further runs also need a slot of **`nats_extra_runs_per_process`** (process scope, - number or percentage of the process's pairs, unset unlimited). With every slot taken the subscription stops taking - messages; keep `nats_max_ack_pending` near replicas x this value. -- **`nats_heartbeat_enabled`** (bool, default `true`): switches the delivery heartbeat off for an agent. -- **`nats_handler_timeout`** (seconds, unset by default): the longest one run may take. At the limit the - run is cancelled and nak'd for immediate redelivery; a `TimeoutError` of the handler's own is an - ordinary failure. Unset, a run is never cut. -- **`RestApiBase.path_prefix`**, an optional class attribute putting every route of an API under - one segment -- `/api/reports/...` standalone, `/api//reports/...` in a group. Default `""`, - so no existing path moves. -- **The migration docs name absolute `src` imports as a pitfall.** `from src.x import Y` works for - an agent served on its own and fails in a group, where a non-critical agent is then skipped with - one ERROR line and its routes are missing from `/docs`. The `blueprint-migration` skill and - `guides/multi-agent-migration.md` now carry the cause, the log line, the fix (relative imports, - which keep working standalone) and a `grep` that finds them. `asbs validate --group` reports - them as a warning, with file and line. -- **Handlers see the subject a NATS message was delivered on**, as `context["nats_subject"]` - (`NATS_SUBJECT_CONTEXT_KEY`), beside `nats_topic`, which is the subscription and may be a - wildcard. It comes from the broker, not the event, so a tenant can be derived from the subject the - broker checked rather than from the publisher-controlled `tenantid`. -- **NATS credentials from their own keys.** `nats_user`/`nats_password`, `nats_token`, - `nats_creds_file` and `nats_nkey_seed` are passed to the connection, so an account under - tenant-scoped auth no longer has to put its credentials inside `nats_url`. At most one method may - be configured; a half-set login, a creds file that is not there, or two methods at once fail - startup. `nats_inbox_prefix` replaces `_INBOX` for accounts not permitted `_INBOX.>`. All are read - per agent, so each agent of a group can have its own account. The dependency on `nats-py` is now - `nats-py[nkeys]`, which creds files and nkey seeds need. -- **A `blueprint-migration` Claude Code skill**, installed by `asbs claude`: moving an existing - single-agent project into a group -- the files it touches, the mistakes that break it, and how - `asbs validate --group` checks it. The migration guide was previously reachable only from inside - `blueprint-multi-agent`. `asbs claude` now lists the skills and agents it installed by reading - them from the package, rather than from a hand-kept list that would have left any new skill - unannounced. -- **A standalone agent declares nothing group-related.** `asbs setup` writes a `create_app()` - factory beside the declaration, and the generated Dockerfile serves it with - `uvicorn src.main:create_app --factory` -- no agent map, no group, no namespace. A group of one - is still a group, and requiring an agent to declare itself one in order to run alone is what put - the group's own file inside the agent. The same directory is still hosted by a group image - without changing a line; its components simply gain that agent's namespace, and with it the - `/api/` route prefix. -- **`.dockerignore`**, written by both `asbs setup` and `asbs setup --group`. Not tidy-up: the - group image copies the whole `agents/` tree, because which agents a process runs is decided at - startup rather than at build time -- and Docker's build context is the filesystem, not the - repository, so `**/.secrets.toml` being in `.gitignore` did nothing to keep real keys out of a - layer. -- **`asbs setup --group` writes a `pyproject.toml`** as well. The group Dockerfile's builder stage - installs from one, so without it the image could not be built. -- **The declaration rules apply to `create_app` too.** A component registered as an already-built - instance is refused when a *host* builds a declaration -- `create_app()` or a group -- because an - agent that works standalone only because nobody checked is an agent that fails the day it joins a - group. The older shape, `AppBuilder(config)` built in place, stays permissive and keeps working. -- **`root` in the agent map**, required per agent, relative to the directory `agents.toml` is in. - Stated rather than derived: a root guessed from where a declaration happens to sit is right for - one layout and silently wrong for every other, and nesting an agent at any depth now costs - nothing. A missing `root`, one that escapes the image, one that is not a directory, and two - agents sharing one are each refused at startup, naming the agent. -- **Misplaced files are refused, not ignored** (`blueprint.agents.layout`). One table of artefacts - with a single legal location, enforced at group assembly and reported by `asbs validate - --group`: `settings.toml` and `.secrets.toml` beside `src/`, `agents.toml` at the image root. - `Dockerfile` is deliberately absent from it -- an agent may own one while living in a group - repository. Adding an artefact is one tuple. -- **`asbs setup --group`** writes the image's files -- an empty agent map, the process settings - and a group Dockerfile -- and creates no agent. -- **`asbs validate --group`** validates an image: every `root`, each agent's layout, misplaced - files, process-wide keys left in an agent, and which `settings.toml` each agent actually reads. -- **`asbs dev --name`**, and `asbs dev` no longer needs an `agents.toml` in an agent's directory. - It writes the one-agent map outside the project for that run. - -### Breaking - -- **In a group, the NATS publish endpoint and scheduler triggers move, and each agent is one - Swagger group.** Grouped agents only; a standalone agent's paths and tags do not change. - - `/api//events/{topic}` becomes `/api//nats/events/{topic}`. - - `/api///trigger` becomes `/api//scheduler//trigger`. - - Cache endpoints stay at `/api//cache/*`. - - Every operation of a grouped agent is tagged with exactly the agent's name, replacing declared - tags and tagging untagged ones. In 0.9.0 an agent was split into `.` groups - interleaved with other agents', and its untagged routes sat under "default" beside everyone - else's. - - `nats`, `cache` and `scheduler` under `/api//` are reserved: a grouped agent's own route - starting with one now fails startup, naming the class and the route. Rename it or set - `path_prefix`. - - Clients and scripts calling a grouped agent's NATS publish endpoint or scheduler trigger need the - new paths. Nothing broker-side changes. -- **Removed unused internals:** the empty module `blueprint.agents.models.event_routing`, and the - example-domain models `AnalysisRequest` and `AnalysisResponse` in `blueprint.agents.models.result`, - which nothing in the framework used and the package did not export. -- **`blueprint.events.unhandled` and `blueprint.events.duplicate` carry `agent`, not - `namespace`,** and are recorded on the agent's own meter. They were created at import on the - global meter, so they reported under the root's resource for every agent, with a label no other - metric uses. The root is labelled ``, as everywhere else. Dashboards on the old label need - the new one. -- **`nats_use_jetstream = true` is enforced against the server; there is no fallback to Core - NATS.** The server is asked for the account's JetStream information on connecting. If it does not - offer JetStream, the agent fails: at startup through the startup failure policy, later (broker - unreachable at startup) by shutting the process down for the root or a critical agent and marking - a non-critical one down. The previous fallback rarely triggered, and when it did it dropped - durable consumers and acknowledgements without anyone deciding it. -- **JetStream consumer settings are opt-in again.** The framework set `ack_wait` 300 s, - `max_ack_pending` 16 and `max_deliver` 5 on every consumer it created, overriding the server's - defaults for deployments that had configured nothing. `nats_ack_wait`, `nats_max_ack_pending` and - `nats_max_deliver` are now applied only when set; unset, the server's default stands (NATS: 30 s, - 1000, unlimited). With `nats_max_deliver` unset, a message that keeps failing is retried without - limit and never dead-lettered, as before 0.9.0 -- set it to bound retries. Consumers that already - exist keep their settings, and an unset key is not reported as a difference. -- **`ClientBase.subscribe()` callbacks take the delivery subject.** The contract is now - `DeliveryCallback = Callable[[CloudEvent, str], Awaitable[None]]` (in `clients/client_base.py`): - the event, then the subject it arrived on. Only code that calls `NATSClient.subscribe()` directly, - or implements `ClientBase`, is affected -- handlers are not. A one-argument callback now fails - with a `TypeError` on the first message. -- **`nats_url` has no default outside development.** With `event_bus = "nats"` and no `nats_url`, - a process whose `app_environment` is anything but `"development"` now fails startup naming the - key -- a standalone or critical agent before the port is bound, a non-critical agent of a group - by being marked down. It used to connect to `nats://localhost:4222`, which in a pod reaches - nothing and retried forever while the pod reported healthy. Development keeps the localhost - fallback, with a WARNING. A broker in the same pod needs `nats_url` set explicitly. -- **A process in development mode logs a WARNING at startup** that it is not suitable for - production. `app_environment` defaults to `"development"`, so a deployment that sets nothing now - says so in its own log. -- **`root` is required in `agents.toml`.** Every existing entry needs one line added; a map - without it refuses to start rather than guessing. For an image that copied one agent to `/app`, - that is `root = "."`. -- **The standalone image no longer runs the group entry point.** It serves - `src.main:create_app` directly. An existing project keeps working: `uvicorn src.main:app` is - still served for a pre-split `main.py`, and a project that wants the old command can keep it. -- **`agents.toml` inside an agent is refused unconditionally**, with no exception for an agent - mapped at the image root. That shape only existed to let a standalone agent be a group of one, - which it no longer has to be. -- **`asbs setup` no longer writes `agents.toml` into an agent.** The map says which agents an - *image* contains, which is a packaging decision -- an agent carrying one is an agent that knows - whether it is running alone. The single-agent `Dockerfile` writes a one-agent map into its own - image instead. Existing projects keep working; delete the file when the agent joins a group, - where it is refused. -- **The `src//main.py` group layout is retired.** An agent is now the same directory alone - or in a group -- `/settings.toml` beside `/src/` -- which is what lets it move - between repositories untouched. Multi-agent grouping has only ever shipped in 0.9.0 alphas, so - nothing stable depended on the old shape. -- **`AgentMapPartGenerator` is gone.** It generated a file that is no longer written; its - `agent_namespace` helper moved to `PartGeneratorBase`. - -### Added - -- **The documentation ships inside the package.** The user-facing guides moved from the repository - root to `src/blueprint/agent_generator/docs/` and are now installed with the wheel, so a - developer or an AI assistant working in a consuming project can read them with no network access. - Previously `README.md` became the wheel's `METADATA` while the 21 documentation pages it links to - stayed behind in the repository, and every one of those links resolved to nothing once installed. -- **`asbs docs`** locates the packaged documentation: `asbs docs` lists every page, `asbs docs - ` prints the path to one, `asbs docs --cat` prints its contents, and `--root` - prints the directory. A bare page name is accepted when it is unambiguous. -- **Seven Claude Code skills**, installed by `asbs claude` alongside the two that already existed: - `blueprint-cli`, `blueprint-config`, `blueprint-events`, `blueprint-multi-agent`, - `blueprint-testing`, `blueprint-deployment` and `blueprint-troubleshooting`. Each carries the - rules that are expensive to get wrong and points at the packaged page for the rest, rather than - restating it -- the docs stay the single source of truth. -- **`LICENSE`** (MIT). The repository claimed MIT in its classifiers and linked a `LICENSE` file - that did not exist; the license is now declared as an SPDX expression and ships in the wheel. - -### Changed - -- **One `main.py` pattern in every document, skill and agent prompt: the template's.** `src/main.py` - is a declaration (`agent = AppBuilder()...`, unbuilt `AgentBuilder`, components as classes) with - a `create_app()` for running it alone. The docs showed three patterns, including `.with_config()`, - `.with_api()` and `AgentBuilder().with_name()`, which do not exist, and a built `AgentRuntime` - that a group refuses. -- **Handlers translate, services decide -- in the scaffold and every document.** The handler - template no longer says "this is where the main business logic is implemented": - `can_handle_event` routes on the envelope only, `handle_event` extracts the payload, makes one - service call and returns the answer (`HandlerResult`, `HandlerResult.skipped(reason)` or `None`); - idempotency belongs to the service; handlers never call the LLM. The chain semantics are stated - as the code has them: the first result that is not `None` ends the chain (the docs said a - `HandlerResult` let later handlers run). -- **The examples follow the handler and service rules.** One handler per event type making one - service call (`webhook_relay`, `order_event_pipeline`), APIs that translate request DTOs into - domain models (`document_summarizer`, `inventory_api`), a scheduler with one service call - (`health_monitor`), no `assert` in production code, and the template's model file names - (`dto.py`, `domain_models.py`). -- **`asbs validate` checks the NATS delivery keys** that otherwise fail only at startup: - `nats_max_concurrent_runs`, `nats_extra_runs_per_process`, `nats_handler_timeout`, - `nats_connections_readiness`, `nats_unclaimed_subjects`, and the form and module of - `nats_connection_source` (the factory is not called). -- **`docs/guides/cli-reference.md` is an index**, with one page per command under `guides/cli/` - (`setup`, `create`, `validate`, `dev`, `claude`, plus `naming` and `auto-registration`). It was a - single 1,023-line page, which meant reading about one flag cost the whole file. -- **Migrating an existing agent into a group is its own page**, - `guides/multi-agent-migration.md`, split out of `guides/multi-agent-setup.md`. -- **`README.md` links are absolute.** Relative links do not resolve on the PyPI project page or in - the installed `METADATA`. The CI badge pointed at an unrelated repository. + `DYNACONF___KEY` was compared against the agent file's keys case-sensitively -- Dynaconf + upper-cases what it loads, the file keeps lower case -- so the override was never seen: a list + was concatenated with the file's, a scalar was replaced by the file's value, and the key was + reported as merged. Keys are now matched case-insensitively, at every nesting level. +- **Both scaffolded `Dockerfile`s declared a `HEALTHCHECK` against a route that does not exist.** + `curl -f http://localhost:8000/health` -- but `ActuatorApi` serves `/health/live` and + `/health/ready`, and nothing at `/health`. `curl -f` fails on the 404, so every container built + from a scaffold reported `unhealthy` for its whole life: compose's `depends_on: + service_healthy` never released, and anything reading Docker's health state saw a permanently + failing container that was in fact serving traffic. Both now probe `/health/live`, which is what + the deployment guide has always shown. A generated-project test holds the path. -### Fixed +- **`asbs validate --group` contradicted the runtime about where an agent's `root` points.** The + runtime resolves every `root` against the **image root** -- the directory the process runs in -- + and `BLUEPRINT_AGENT_MAP` may put the map anywhere, so a repository keeping `deploy/agents.toml` + with its agents at the top runs correctly. The validator resolved each `root` against whichever + directory the map sat in, so it reported that layout as `... is not a directory` under the + verdict "would stop this image starting" -- a false statement about a working image, whose + correct reading is to break a layout that worked. The two coincide only where the map is at the + image root, which is what `asbs setup --group` writes, so no test caught it. The command now + takes the directory argument as the image root and `--agent-map PATH` (or `BLUEPRINT_AGENT_MAP`) + as where the map is; a relative path resolves against the image root, as at runtime. The error + for an absent map names the flag. Present since `root` became required in 0.9.0a4. +- **An agent settings file that scoped keys under the agent's own name merged into nothing.** + `[default.]` in that agent's own `settings.toml` nested to `..*` once the + file was merged under the agent's namespace, so every key in it was unreachable -- and the + failure surfaced far from the cause, as `No model name for runtime agent '_agent' + configured`, naming the agent rather than the file. Found migrating a real project. It is now + refused at merge, naming the section and the fix, and `asbs validate --group` reports it without + starting anything. Plain `[default]` serves both shapes: standalone resolves it because a scoped + lookup falls back to the root key. +- **A grouped agent's own `settings.toml` was never read.** The group looked for it beside the + *declaration module* -- inside `src/` -- while every scaffolded project writes it beside `src/`, + so the file existed, looked right, and was never opened. Nothing failed: the agent ran on the + group's defaults and said so nowhere. It is now read from the directory the agent map states. +- **Prompts resolved against the process working directory.** One directory for a whole group, so + it was right for at most one agent; the others found nothing, or found a neighbour's prompt of + the same name. Each agent's configuration view now reports its own directory as the package + root, so `/src/prompts` resolves exactly as it does standalone. +- **A scaffolded agent no longer ships process-wide keys.** `log_level` and `log_format` were + written into every agent's `settings.toml`, so every group one joined dropped them with a + warning about a file the scaffolder itself wrote. They are now commented out, with the reason. - **`pytest` and `pytest-asyncio` are no longer runtime dependencies.** They were listed in `[project.dependencies]`, so every consumer installed the test suite's tooling in production. They remain in the `ci` extra. -### Deprecated - -- **JetStream consumers created before 0.9.** 0.8 left each durable delivering to a random inbox - with no deliver group, so only one replica can consume from it. Such a consumer is still found - under its name and used exactly as it is -- it is never recreated, which would replay or gap -- - but it is logged at startup as `DEPRECATED` and will not be supported in a future release. - Delete it during a maintenance window; the framework then recreates it so that every replica - shares it. - -### Upgrading a standalone agent from 0.8 - -What the broker sees change when an agent that ran on 0.8 starts on this version, with -`nats_use_jetstream = true`: - -- **Existing durables are reused**, found under the same name for a topic without `.`, `*`, `>` or - whitespace (`orders` -> `orders-durable`), and announced as deprecated (above). For a topic with a - dot the name is now `orders_created-durable`; 0.8's `orders.created-durable` is a name the broker - refuses, so no such consumer can exist to be orphaned. -- **`nats_durable_name` with several topics fails startup.** 0.8 gave all of them one consumer, of - which only the first topic's subscription worked. -- **The stream is widened, never narrowed.** 0.8 created it over `.>` and never touched - it again; this version adds every subscribed topic, the dead-letter subject and, when publishing - through JetStream, the publish subjects. -- **Core NATS subscriptions join a queue group** (`nats_queue_group`, else `app_name`), so each - message reaches one replica instead of every one. - -What the code sees change: - -- **Components are constructed by `build()`, not by the `with_*()` call.** `with_handler(MyHandler)` - records the class; `build()` constructs it, in declaration order. Code that looked a component up - in the registry between a `with_*()` call and `build()` finds nothing, and an error a constructor - raises -- a missing configuration key, say -- is raised by `build()`. An instance passed to - `with_*()` is the caller's own and is used as it is. - -## [0.9.0] - 2026-09-14 - -**Multi-agent grouping.** How many agents share a process becomes a *deployment* parameter rather -than an architectural commitment. An agent's code is identical whether it runs alone or beside -nineteen others; only what starts the process differs. A standalone agent is unaffected by almost -all of this — see **Breaking** for the exceptions, which are listed in the order you are likely to -hit them. - -Full migration path, including the one decision to get right before the first deploy: -[`guides/multi-agent-setup.md`](src/blueprint/agent_generator/docs/guides/multi-agent-setup.md). The normative spec is -`docs/specs/2026-08-28-multi-agent-grouping.md`. - -### Added - -- **Agent grouping.** `agents.toml` names the agents an image contains and the module each - declaration lives in; `BLUEPRINT_AGENTS`, or `BLUEPRINT_GROUP` plus a mounted - `BLUEPRINT_GROUP_CONFIG` file, decides which of them a given process runs; - `python -m blueprint.agents.entrypoint` resolves, builds and serves them. Each hosted agent owns - its handlers, agent runtime, REST routes (`/api/`), AI client, thread pool, caches and - broker connection; the port, the health endpoint and the process are shared. - `BLUEPRINT_CRITICAL_AGENTS` says which agents failing should fail the process. -- **Agents in one process are isolated, and the barrier is enforced rather than conventional.** An - agent resolves its own components, caches and configuration plus the root's shared ones. Reaching - a neighbour by its registry key, by an explicit `namespace=` on a view, by a dotted configuration - key, or by sharing one declaration's mutable argument between two agents is refused or reported - absent. `Config.settings` remains the documented escape hatch and logs a WARNING naming the agent. -- **An agent's identity is stable across regrouping** (spec C1): its NATS queue group, JetStream - durable, cache partition, OpenTelemetry `service.name`, registry prefix and REST prefix all derive - from the agent's own name and never from the group or the pod. -- **Per-agent observability.** `service.name` per agent, `blueprint_namespace_up{agent}`, a - readiness entry and health checks attributed per agent, `blueprint.scheduler.tick_age_seconds`, - `blueprint.events.dead_lettered`, `blueprint.events.unhandled` and `blueprint.events.duplicate`. -- **`CacheService.claim`** — set-if-absent, atomic on both backends (`add` on disk, `SET NX EX` on - Redis). This is the compare-and-set primitive the deduplication work flagged as missing. -- **Named caches.** `with_cache(name=...)`, `/cache/*` endpoints take `?name=`, and `/readiness` - gains a `cache:` entry per named cache. -- **Opt-in event deduplication** — `idempotency_enabled` and a required `idempotency_ttl`. Off by - default; a failed dispatch releases its claim so the nak's redelivery still runs. -- **`nats_publish_mode`** (`"core"` / `"jetstream"`) separates publishing from durable consumption, - with `nats_publish_subjects` for subjects not already in `event_publishing.topic_mapping`. Unset, - it follows `nats_use_jetstream`, so nothing existing changes. -- **`run_app`**, so a project can serve itself from its own settings. -- **Scaffolding**: `asbs setup` now writes `agents.toml`, a `pyproject.toml` and two tests, so - `asbs setup` → `pytest` → `asbs validate` closes; `asbs validate` reports what a project has not - said about grouping and about idempotency; the CLI no longer crashes on a Windows console. -- New config keys: `event_client_drain_timeout`, `dapr_pubsub_name`, - `dapr_declarative_subscriptions`, `idempotency_enabled`, `idempotency_ttl`, `scheduler_mode`, - `event_publishing_enabled`, `nats_publish_mode`, `nats_publish_subjects`. All default to current - behaviour except `scheduler_mode`, which is required — see below. -- `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. - -### Breaking - -1. **`scheduler_mode` is required.** A project that registers a scheduler and does not set it fails - at `build()`, with an error naming both values and what each costs. `"in_process"` reproduces - today's behaviour exactly and is the no-op migration; `"event"` is the one that fixes #73. - Defaulting the key would either keep firing a timer per replica or silently stop ticking a - service with no broker, and neither is safe to inherit. -2. **A subject-unsafe `app_name` or `nats_queue_group` now fails at startup** instead of being - rewritten or reaching the broker. `app_name = "Health Monitor"` with an event-mode scheduler used - to derive `Health_Monitor.scheduler.`; the rewrite was invisible to whoever wrote the - `CronJob`, so the symptom was a tick that never arrived. Rename to a subject-safe value, or pass - `topic=` explicitly. -3. **A scoped `Config`'s dotted key no longer resolves against the whole tree.** `_scoped_get` used - to fall back from `.` to the raw key, and since an agent's section is - `[default.]`, that let one agent read another's settings. The fallback is now an allowlist - of the four prefixes the framework itself owns (`cache`, `event_publishing`, `runtimes`, - `runtime`). A project reading its *own custom* nested key through a scoped view now gets an error - naming the rule; flat keys and `Config.settings` are unaffected. -4. **A registry view that names another agent is refused.** `get_component(..., namespace="other")` - and `get_cache(..., namespace="other")` raise on a scoped view. Every in-framework caller passes - its own namespace or holds the application registry, so nothing internal is affected. -5. **A scoped `Config`'s telemetry `service.name` is the agent's name.** Affects a project using - `Config(agent_scope=...)`, which has shipped since April. A repo with `foo.app_name = "Foo - Service"` and no `foo.otel_service_name` sees `service.name` change from `Foo Service` to `foo`. - Migration is one line: set `.otel_service_name` to whatever the dashboards key on. A - project that passes no `agent_scope` is unaffected. -6. **Cache keys moved, twice -- for named caches and for agents in a group.** A cache is now - private to the agent that declared it, keyed on `(namespace, name)` with its own subdirectory - and Redis prefix. Such a cache upgrading with persistent Redis or a mounted disk cache sees its - old entries as **absent** — a cold cache, not an error. **A standalone agent's default cache is - unaffected:** its directory, Redis prefix and keys are unchanged, so it keeps its entries. A - group still needs exactly one writable mount, since an agent's store is a subdirectory of - `cache.cache_dir`. If any cache entry is load-bearing rather than an optimisation, migrate it - deliberately. -7. **Four declaration surfaces are deleted**: `AgentRegistration`, `RegisteredComponent`, - `NamespaceBuilder`, and `AppBuilder.with_namespace` / `with_registration`. `AppBuilder` is the one - declaration surface; `AgentGroup` collects named declarations into a process. Passing an - already-built component instance (`with_service(MyService())`) still works for a single standalone - agent and is refused in a group — pass the class, or a zero-argument factory. -8. **`ClientBase.subscribe` changed from `(topic, callback)` to `(topic_callbacks)`**, and - `EventHandlingBase.subscribe` and `POST /nats/subscribe/{topic}` are removed. This affects - third-party transport implementations; both in-repo clients are updated. -9. **On grouped Dapr, one delivery is fanned out in-process to every agent that declared the - topic, and the single acknowledgement the sidecar receives is their combination** — so a retry - asked for by one agent redelivers to all of them. The sidecar fetches the subscription document - from one fixed path, which is why there is one endpoint at the root that routes rather than one - document per agent. Set `idempotency_enabled` for grouped Dapr, or keep handlers - repeat-tolerant. Single-agent Dapr and NATS are both unaffected. -10. **`Registry.update_component_name` refuses a name that is already taken** instead of overwriting - it. Anything relying on the overwrite was losing a component silently. -11. **`asbs setup` now scaffolds `.secrets.toml`**, the name `DEFAULT_SETTINGS_FILES` actually loads; - it used to write `secrets.toml`, which nothing read. This is a change to the *scaffolder* only — - the framework's file list is untouched, so no existing deployment changes. `asbs validate` - reports an undotted file as the rename it needs. An already-scaffolded project should rename its - file. -12. **`Component.shared_config` is now private (`Component._shared_config`)**, with - `Component.reset_shared_state()` as the one supported way to clear it. The old attribute was - public and writable but read by nothing outside `_ComponentMeta`, so hiding it looked like - code-only cleanup. It is not: a test suite that rebuilds its `AppBuilder` app once per test case - and resets state between cases with the old `Component.shared_config = None` now silently - no-ops, since the real state lives on `_shared_config` — `Component.configure()`'s "already set" - guard then trips starting from the second test in the run, with an error that does not name this - rename. **Any project resetting shared state between test cases must switch to - `Component.reset_shared_state()`** in its fixtures; this also clears `shared_registry`, which - stays public and is otherwise unaffected. A project that never resets shared state between - builds is unaffected. -13. **A scheduler tick runs in one replica, not in every one.** Before, every replica -- and every - worker -- ran its own timer and each ran every tick. Now `scheduler_mode = "event"` delivers the - tick through the queue group to one replica, and `"in_process"` claims each tick in the cache so - one replica runs it. A deployment that relied on every replica running a tick in parallel -- a - per-pod cleanup, say -- now runs it once per tick; register the cache per pod, or do the per-pod - work outside the scheduler. Without a registered cache, `"in_process"` still runs every tick in - every replica, and says so with a WARNING at startup where it used to log an INFO. -14. **A Core NATS event reaches one replica, not every one.** Subscriptions now join a queue group - (`nats_queue_group`, else `app_name`); before, every replica received and processed every event. - A deployment that relied on each replica seeing each event now sees each event once. -15. **`Config()` no longer configures logging.** Constructing a `Config` used to set up the root - logger; library code must not, so `AppBuilder` does it now. A script or test that builds only a - `Config` and relied on its logging setup has to configure logging itself. -16. **`Config.settings` is read-only.** It was a plain attribute; assigning to it now raises - `AttributeError`. Replacing the settings tree underneath a running configuration bypasses every - agent's view of it and is not supported. -17. **Metrics a project records itself are now exported.** With OpenTelemetry enabled, the framework - registers a global `MeterProvider` that exports over OTLP. Before, it registered none, so a - counter a project created through `metrics.get_meter(...)` was silently discarded; the same - unchanged code now reaches the collector, which can add series -- and cost -- to a metrics - backend. A project that registered its own `MeterProvider` first keeps it: the SDK refuses a - second one and the framework's is not installed. - -### Fixed - - **⚠️ The environment a project selects is now actually the one that loads** (#89). `Config` passed the resolved `app_environment` to Dynaconf as `current_env=`, which is a *derived* property reporting the active environment, not the parameter that selects one. That parameter @@ -891,6 +843,15 @@ Full migration path, including the one decision to get right before the first de consumers share load via a deliver group; and what the framework gives up on is republished to `.dead-letter` before being termed. +### Deprecated + +- **JetStream consumers created before 0.9.** 0.8 left each durable delivering to a random inbox + with no deliver group, so only one replica can consume from it. Such a consumer is still found + under its name and used exactly as it is -- it is never recreated, which would replay or gap -- + but it is logged at startup as `DEPRECATED` and will not be supported in a future release. + Delete it during a maintenance window; the framework then recreates it so that every replica + shares it. + ### Known issues - Generating the `CronJob` for `scheduler_mode = "event"` is deliberately deferred, so the publisher @@ -906,6 +867,50 @@ Full migration path, including the one decision to get right before the first de operational task the framework does not perform. - `size` in the cache statistics counts TTL metadata entries, so a cache holding two values reports `4`. Documented as-is rather than changed, because a reported metric is somebody's dashboard. + +### Upgrading a standalone agent from 0.8 + +What the broker sees change when an agent that ran on 0.8 starts on this version, with +`nats_use_jetstream = true`: + +- **Existing durables are reused**, found under the same name for a topic without `.`, `*`, `>` or + whitespace (`orders` -> `orders-durable`), and announced as deprecated (above). For a topic with a + dot the name is now `orders_created-durable`; 0.8's `orders.created-durable` is a name the broker + refuses, so no such consumer can exist to be orphaned. +- **`nats_durable_name` with several topics fails startup.** 0.8 gave all of them one consumer, of + which only the first topic's subscription worked. +- **The stream is widened, never narrowed.** 0.8 created it over `.>` and never touched + it again; this version adds every subscribed topic, the dead-letter subject and, when publishing + through JetStream, the publish subjects. +- **Core NATS subscriptions join a queue group** (`nats_queue_group`, else `app_name`), so each + message reaches one replica instead of every one. + +What the code sees change: + +- **Components are constructed by `build()`, not by the `with_*()` call.** `with_handler(MyHandler)` + records the class; `build()` constructs it, in declaration order. Code that looked a component up + in the registry between a `with_*()` call and `build()` finds nothing, and an error a constructor + raises -- a missing configuration key, say -- is raised by `build()`. An instance passed to + `with_*()` is the caller's own and is used as it is. + +### Rolling back to 0.8 + +What does not go back by itself when a deployment returns to 0.8: + +- **JetStream durables.** This version creates each durable with a deliver subject + `_DELIVER.` and a deliver group; 0.8 subscribes with `js.subscribe(..., durable=...)` and + no queue, which does not bind to such a consumer. Delete the consumers this version created + before starting 0.8 -- messages still pending on them are lost with them. A durable of a dotted + topic (`orders_created-durable`) has no 0.8 counterpart and is simply left behind. +- **Cache entries** written under the new keys (named caches, agents in a group) are invisible to + 0.8, which reads its old keys. A standalone agent's default cache keeps its keys either way. +- **REST paths and Swagger groups** of grouped agents (`/api//nats/...`, + `/api//scheduler/...`) do not exist in 0.8; callers and probes that moved have to move + back. A standalone agent's paths are the same in both. +- **Metric labels.** Dashboards moved to `agent` on `blueprint.events.unhandled` and + `.duplicate` -- and to the `` topic label under Dapr -- see 0.8's `namespace` label + and per-topic series again. + ## [0.8.2] - 2026-10-06 ### Added diff --git a/LICENSE b/LICENSE deleted file mode 100644 index df54ac4f..00000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Bechtle AG - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 7b23ddd4..9e5d9683 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,11 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Step 21, docs and PR hygiene (W7, W8/D19, W9, D20): the isolation tests' xfail paragraph in the past tense; + `[0.9.0] - 2026-09-14` folded into `[Unreleased]`, one section per heading; `pyproject.toml` back to `0.8.2` + with no licence fields, `LICENSE` and its CHANGELOG entry removed (D20: no approval yet); a "Rolling back + to 0.8" section (durables, cache keys, grouped REST paths, metric labels). PR description drafted, not + posted. - Step 20, smaller items (S19, S23/D16, W2, W3/D7): `deployment.publish_deployment_group` from `AgentGroup.resolve`, read first by `deployment_group()`; the in-process tick slot is the trigger's latest fire time at or before now (`_arm_trigger`, `_tick_slot`); `diskcache-rs>=0.4.10`; the disk claim documented diff --git a/pyproject.toml b/pyproject.toml index a6093730..31c22207 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,15 +6,13 @@ build-backend = "setuptools.build_meta" [project] name = "avs-blueprint-agents" -version = "0.9.0" +version = "0.8.2" description = "Microservice blueprint for creating agents" authors = [ { name = "Blueprint Team", email = "patrick.maue@bechtle.com" }, { name = "Blueprint Team", email = "jan.weber@bechtle.com" } ] readme = "README.md" -license = "MIT" -license-files = ["LICENSE"] requires-python = ">=3.13" classifiers = [ "Development Status :: 3 - Alpha", diff --git a/tests/unit/agents/test_agent_isolation.py b/tests/unit/agents/test_agent_isolation.py index 34c4a289..4732e49f 100644 --- a/tests/unit/agents/test_agent_isolation.py +++ b/tests/unit/agents/test_agent_isolation.py @@ -11,21 +11,21 @@ other agent is asked for it through every API a component actually has. `namespace_of` and `agent_scope` say what something *is*; these say what can be *read*, which is the claim. -**Five of these tests fail, on four distinct mechanisms.** They are marked `xfail(strict=True)` -rather than deleted or softened, each naming the mechanism that lets the value through. Strict, so -that closing a hole turns the test red until the marker is removed -- a silently-passing xfail is -how a fix gets made and never noticed. All four are in the changelog's *Open points*: +**Five of these tests failed when they were written, on four distinct mechanisms.** They were +kept as `xfail(strict=True)` rather than deleted or softened -- strict, so that closing a hole +turned the test red until the marker came off. All four are closed and no test here is marked any +more; they are listed so that a regression is recognised for what it is: -1. the registry's fallback from a qualified name to a bare one reaches a *neighbour's* key, not +1. the registry's fallback from a qualified name to a bare one reached a *neighbour's* key, not only the root's; -2. an explicit ``namespace=`` argument wins on a view as well as on the application registry, so - an agent can address any other by naming it -- which costs two tests, because it opens both +2. an explicit ``namespace=`` argument won on a view as well as on the application registry, so + an agent could address any other by naming it -- which cost two tests, because it opened both the component lookup and the cache; -3. a scoped ``get()`` resolves a dotted key against the whole configuration tree; -4. one declaration serving two agents constructs both with the *same* mutable argument object. +3. a scoped ``get()`` resolved a dotted key against the whole configuration tree; +4. one declaration serving two agents constructed both with the *same* mutable argument object. -None of them is reachable by accident, and none of them requires anything but the framework's own -public API and a neighbour's name -- which an agent knows, because it is in the group. +None of them was reachable by accident, and none required anything but the framework's own public +API and a neighbour's name -- which an agent knows, because it is in the group. The root namespace is not a neighbour. It holds what the process genuinely shares -- one transport connection, one health cache -- so an agent resolving a root component is the design working, and From a05b1b20798c4208bf9eb4ce5ebd78ff15e73577 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Mon, 19 Oct 2026 23:15:09 +0200 Subject: [PATCH 123/133] fix: findings of the final container run N14: _bind makes two round trips, because nats-py 2.15 writes PING ahead of a SUB still waiting for the flusher, so a refusal could arrive after the first PONG. S19 follow-up: the stand-in name of a group nothing named is not published as the deployment group. Plan: docs/plans/2026-10-16-pr96-review-fixes.md; what ran live, with its control run, is recorded in docs/plans/2026-08-28-multi-agent-grouping-changelog.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../2026-08-28-multi-agent-grouping-changelog.md | 9 +++++++++ src/blueprint/agent_generator/cli/commands/setup.py | 1 - src/blueprint/agents/agent_group.py | 7 ++++--- src/blueprint/agents/clients/io/nats_client.py | 6 ++++++ src/blueprint/agents/config/config.py | 4 +++- src/blueprint/agents/group_config.py | 9 ++++++++- .../agents/io/api/actuators/actuator_api.py | 4 +++- .../agents/io/api/eventing/sessions_bus.py | 3 +-- tests/integration/conftest.py | 9 ++++++--- .../generator/test_generated_project.py | 6 +++--- .../eventing/test_sessions_startup_resilience.py | 6 +++--- tests/unit/agents/test_agent_group.py | 13 +++++++++++++ 12 files changed, 59 insertions(+), 18 deletions(-) diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 9e5d9683..c98c9ca0 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -146,6 +146,15 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a per-data-source state is keyed by that context key. Broker test on the accounts broker: the same `(source, id)` on connections A and B runs on both, a repeat on A is skipped; without the change B was skipped. +- Final run with containers (2026-10-19): unit 3781 tests, 0 failed, 1 skipped; integration (JetStream, + accounts broker, Redis in WSL) 66 of 67 -- the one failure is the pre-existing + `test_the_broker_counts_it_as_a_redelivery`, which fails on the committed HEAD too. Two findings on the way, + both fixed: N14, M4's refusal check raced because nats-py 2.15 writes PING ahead of a pending SUB -- + `_bind` now makes two round trips (8 of 8 runs green; before 3 of 9 failed); and step 20 published the + stand-in name 'ungrouped' of a group nothing named, so telemetry would have carried + `deployment.group = ungrouped` -- `group_config.DEFAULT_GROUP_NAME` is not published. The group image, + scaffolded fresh (`asbs setup --group`, two agents, `asbs validate --group` valid) and built from the + working tree, turned healthy under `BLUEPRINT_AGENTS` ('') and under a one-group file ('finance'). - Step 21, docs and PR hygiene (W7, W8/D19, W9, D20): the isolation tests' xfail paragraph in the past tense; `[0.9.0] - 2026-09-14` folded into `[Unreleased]`, one section per heading; `pyproject.toml` back to `0.8.2` with no licence fields, `LICENSE` and its CHANGELOG entry removed (D20: no approval yet); a "Rolling back diff --git a/src/blueprint/agent_generator/cli/commands/setup.py b/src/blueprint/agent_generator/cli/commands/setup.py index 016a85a6..b147c653 100644 --- a/src/blueprint/agent_generator/cli/commands/setup.py +++ b/src/blueprint/agent_generator/cli/commands/setup.py @@ -165,7 +165,6 @@ def run(args: Namespace) -> None: print(f"Location: {output_dir}") try: - # Create a temporary config file for the generator with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False, encoding="utf-8") as f: json.dump(config, f, indent=2, ensure_ascii=False) diff --git a/src/blueprint/agents/agent_group.py b/src/blueprint/agents/agent_group.py index 23f96aba..81a24f05 100644 --- a/src/blueprint/agents/agent_group.py +++ b/src/blueprint/agents/agent_group.py @@ -36,7 +36,7 @@ from .component.namespace import namespace_scope, validate_namespace from .config import Config from .deployment import publish_deployment_group -from .group_config import AgentSpec, GroupConfig, GroupConfigError +from .group_config import DEFAULT_GROUP_NAME, AgentSpec, GroupConfig, GroupConfigError from .layout import check_agent_layout logger = logging.getLogger(__name__) @@ -229,8 +229,9 @@ def resolve(cls, config: Config, *, environ: dict[str, str] | None = None) -> "A """ group = GroupConfig.resolve(config, environ=environ) # Before anything reads it: the connection name and the telemetry resource take the - # deployment group, and a group named only by the file never reached them (S19). - publish_deployment_group(group.name) + # deployment group, and a group named only by the file never reached them (S19). A group + # nothing named keeps reading as ungrouped: its stand-in name is no deployment's. + publish_deployment_group(None if group.name == DEFAULT_GROUP_NAME else group.name) return cls.from_config(group) @classmethod diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 0d3a74cc..35541650 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -2528,6 +2528,12 @@ async def _bind(self, binding: _Binding) -> None: # trip makes any refusal arrive first; one naming this subject fails the attempt, and the # connect loop retries it as a permission error. Compared lowercased: nats-py lowercases the # whole -ERR line, the subject in it included. + # Two round trips, not one: nats-py writes PING straight to the transport while the SUB + # still waits in its pending buffer for the flusher task, so the first PONG can come back + # before the broker has seen the SUB (measured with nats-py 2.15: the refusal arrived after + # flush() returned, and the binding read as bound). The flusher writes the SUB during the + # first round trip; the second PING follows it on the wire, and so does its answer. + await client.flush() await client.flush() subject = spec.deliver_subject.lower() refused = [error for error in binding.link.permission_errors if subject in error.lower()] diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index d75c792e..3e32a380 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -989,7 +989,9 @@ def _convert_keyed_list_to_dict(items: Any) -> Any: ( self._process_dynabox(item, placeholder, replacement) if isinstance(item, (dict, DynaBox)) or hasattr(item, "items") - else _try_parse_json(item) if isinstance(item, str) else item + else _try_parse_json(item) + if isinstance(item, str) + else item ) for item in value ] diff --git a/src/blueprint/agents/group_config.py b/src/blueprint/agents/group_config.py index 65f59d38..01b56385 100644 --- a/src/blueprint/agents/group_config.py +++ b/src/blueprint/agents/group_config.py @@ -60,6 +60,13 @@ GROUP_ENV = "BLUEPRINT_GROUP" AGENTS_ENV = "BLUEPRINT_AGENTS" CRITICAL_AGENTS_ENV = "BLUEPRINT_CRITICAL_AGENTS" + +DEFAULT_GROUP_NAME = "ungrouped" +"""The name of a group neither the file nor ``BLUEPRINT_GROUP`` names -- a stand-in, not a group name. + +``AgentGroup.resolve`` does not publish it as the deployment group (S19), so telemetry carries no +``deployment.group`` for such a group, as the observability guide says. +""" AGENT_MAP_ENV = "BLUEPRINT_AGENT_MAP" DEFAULT_GROUP_CONFIG = "deployment-groups.yaml" @@ -428,7 +435,7 @@ def _names(key: str) -> list[str]: if not name: # A group has to be called something: the name reaches the connection name and the # telemetry resource, where an empty segment reads as a bug rather than as "no group". - name, sources["name"] = "ungrouped", "default" + name, sources["name"] = DEFAULT_GROUP_NAME, "default" for key, source in sources.items(): if source != "file" or declared: diff --git a/src/blueprint/agents/io/api/actuators/actuator_api.py b/src/blueprint/agents/io/api/actuators/actuator_api.py index 940269c9..822d1331 100644 --- a/src/blueprint/agents/io/api/actuators/actuator_api.py +++ b/src/blueprint/agents/io/api/actuators/actuator_api.py @@ -351,7 +351,9 @@ async def llm_status(self) -> LLMStatus: ai_config_dict = ( ai_config_model.model_dump() if hasattr(ai_config_model, "model_dump") - else ai_config_model.dict() if hasattr(ai_config_model, "dict") else {} + else ai_config_model.dict() + if hasattr(ai_config_model, "dict") + else {} ) ai_config = self._sanitize_config(ai_config_dict) diff --git a/src/blueprint/agents/io/api/eventing/sessions_bus.py b/src/blueprint/agents/io/api/eventing/sessions_bus.py index a28ae669..9b8975c9 100644 --- a/src/blueprint/agents/io/api/eventing/sessions_bus.py +++ b/src/blueprint/agents/io/api/eventing/sessions_bus.py @@ -116,8 +116,7 @@ async def pause_consumption(self) -> None: self._consumption_paused = True await self._stop_stream() logger.error( - "Agent '%s' stopped consuming: its job stream is closed while it is degraded, so its jobs stay pending " - "for a healthy replica", + "Agent '%s' stopped consuming: its job stream is closed while it is degraded, so its jobs stay pending for a healthy replica", self.namespace or ROOT_LABEL, ) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index f2d6b57f..2a3b1861 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -225,13 +225,16 @@ def integration_config( "nats_use_jetstream = true\n" # Well above any handler here, and short enough that a test asserting *no* redelivery can # afford to wait the whole window out. Unset, it would be the server's default (30 s). - "nats_ack_wait = 2.0\n" "nats_max_deliver = 3\n" + "nats_ack_wait = 2.0\n" + "nats_max_deliver = 3\n" # The client retries the initial connect forever by default, which turns "the broker # refused this subscription" into a test that hangs instead of one that fails. - "event_client_max_retries = 2\n" "event_client_retry_delay = 0.5\n\n" + "event_client_max_retries = 2\n" + "event_client_retry_delay = 0.5\n\n" # Where a handler's HandlerResult goes. Without a mapping for the event type, # EventPublishingService logs "no topic mapping found" and publishes nothing at all. - f'[default.event_publishing.topic_mapping."{OUTBOUND_EVENT_TYPE}"]\n' f'topic = "{outbound_subject}"\n', + f'[default.event_publishing.topic_mapping."{OUTBOUND_EVENT_TYPE}"]\n' + f'topic = "{outbound_subject}"\n', encoding="utf-8", ) config = Config(settings_files=["settings.toml"], root_path=str(tmp_path)) diff --git a/tests/unit/agent_generator/generator/test_generated_project.py b/tests/unit/agent_generator/generator/test_generated_project.py index 3923407b..8b0a79b7 100644 --- a/tests/unit/agent_generator/generator/test_generated_project.py +++ b/tests/unit/agent_generator/generator/test_generated_project.py @@ -443,9 +443,9 @@ def test_the_command_is_the_framework_entry_point(self, project: Path) -> None: assert "src.main:create_app" in final assert "--factory" in final, "create_app is a factory; uvicorn needs an import string to reload it" - assert ( - "blueprint.agents.entrypoint" not in final - ), "The image serves one agent through the group entry point, which makes a standalone agent declare itself a group of one." + assert "blueprint.agents.entrypoint" not in final, ( + "The image serves one agent through the group entry point, which makes a standalone agent declare itself a group of one." + ) def test_no_agent_map_is_in_the_image(self, project: Path) -> None: """This image holds one agent and serves it; there is no group for a map to describe.""" diff --git a/tests/unit/agents/io/api/eventing/test_sessions_startup_resilience.py b/tests/unit/agents/io/api/eventing/test_sessions_startup_resilience.py index 9bacc5c4..8580beb0 100644 --- a/tests/unit/agents/io/api/eventing/test_sessions_startup_resilience.py +++ b/tests/unit/agents/io/api/eventing/test_sessions_startup_resilience.py @@ -122,6 +122,6 @@ def _run() -> None: "SessionsBus.on_startup did not run — its 'connected' log line is missing. " "Test would pass trivially if on_startup were a no-op; that defeats the point." ) - assert any( - "Lifecycle component SessionsBus startup completed" in rec.getMessage() for rec in caplog.records - ), "AppBuilder lifespan never awaited SessionsBus.on_startup." + assert any("Lifecycle component SessionsBus startup completed" in rec.getMessage() for rec in caplog.records), ( + "AppBuilder lifespan never awaited SessionsBus.on_startup." + ) diff --git a/tests/unit/agents/test_agent_group.py b/tests/unit/agents/test_agent_group.py index 024dca53..9f15ee68 100644 --- a/tests/unit/agents/test_agent_group.py +++ b/tests/unit/agents/test_agent_group.py @@ -630,6 +630,19 @@ def test_a_group_from_the_file_is_published(self, tmp_path, monkeypatch) -> None built.assert_called_once_with(resolved) assert deployment_group() == "finance" + def test_a_group_nothing_named_is_not_published(self, monkeypatch) -> None: + """BLUEPRINT_AGENTS alone names no group; its stand-in name must not become deployment.group.""" + from unittest.mock import patch + + from blueprint.agents.deployment import UNGROUPED_LABEL, deployment_group + from blueprint.agents.group_config import DEFAULT_GROUP_NAME + + monkeypatch.delenv("BLUEPRINT_GROUP", raising=False) + resolved = GroupConfig(name=DEFAULT_GROUP_NAME, agents=()) + with patch.object(GroupConfig, "resolve", return_value=resolved), patch.object(AgentGroup, "from_config"): + AgentGroup.resolve(MagicMock(), environ={}) + assert deployment_group() == UNGROUPED_LABEL + def test_without_a_resolved_group_the_environment_still_decides(self, monkeypatch) -> None: from blueprint.agents.deployment import UNGROUPED_LABEL, deployment_group From 665c9121ac8259d4a668284eae1eeb33aca90e21 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Tue, 20 Oct 2026 12:39:14 +0200 Subject: [PATCH 124/133] test(design-rules): prune ignored directories instead of walking .venv all_markdown() ran rglob over the whole checkout, .venv included, and dropped the ignored paths afterwards -- about 0.6 s per test, 47 s for the module. The directories are now pruned before they are entered; the same 91 files are found, the module takes 14 s (N20). Plan: docs/plans/2026-10-16-pr96-review-fixes.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- tests/unit/agents/test_design_rules.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/tests/unit/agents/test_design_rules.py b/tests/unit/agents/test_design_rules.py index 1562ea05..eb3cd11f 100644 --- a/tests/unit/agents/test_design_rules.py +++ b/tests/unit/agents/test_design_rules.py @@ -33,6 +33,7 @@ """ import ast +import os import re from collections.abc import Callable, Generator, Iterator from pathlib import Path @@ -926,11 +927,17 @@ def strip_code(text: str) -> str: def all_markdown() -> Iterator[Path]: - """Every markdown file present, ignoring the dot directories and the vendored trees.""" - for path in REPO_ROOT.rglob("*.md"): - parts = path.relative_to(REPO_ROOT).parts - if not any(part.startswith(".") or part in {"node_modules", "__pycache__"} for part in parts): - yield path + """Every markdown file present, ignoring the dot directories and the vendored trees. + + The ignored directories are pruned before they are entered, not filtered afterwards: a + ``.venv`` holds far more files than the repository, and walking it made every test that + calls this cost about half a second. + """ + for root, directories, files in os.walk(REPO_ROOT): + directories[:] = [name for name in directories if not name.startswith(".") and name not in {"node_modules", "__pycache__"}] + for name in files: + if name.endswith(".md") and not name.startswith("."): + yield Path(root) / name def markdown_documents() -> list[Path]: From 7aa775818d620055bf2a714161e50a0a7ec4f954 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Tue, 20 Oct 2026 12:39:15 +0200 Subject: [PATCH 125/133] fix(dedup): a "false" heartbeat from the environment warns; runtime docstrings match the code N17: _warn_without_a_heartbeat compared nats_heartbeat_enabled `is False`, so "false" from an environment variable did not warn; it is read with parse_bool now (unit test failed before). Docstrings and log text brought in line with steps 4, 17, 19 and 20: per-process disk-cache claims (S23), the restored declaration order (S20), the resolved deployment group (S19), the JetStream pause (N4), and the files AgentGroup reads under each agent's root. Plan: docs/plans/2026-10-16-pr96-review-fixes.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/blueprint/agents/agent_group.py | 9 ++++---- src/blueprint/agents/app_builder.py | 13 ++++-------- .../agents/clients/io/nats_client.py | 7 ++++--- src/blueprint/agents/handler/handler_chain.py | 7 ++++++- .../agents/io/api/scheduling/scheduler.py | 21 +++++++++++-------- .../agents/io/telemetry/telemetry.py | 5 +++-- .../services/infrastructure/cache_service.py | 4 ++-- .../unit/agents/handler/test_handler_chain.py | 10 +++++++++ 8 files changed, 46 insertions(+), 30 deletions(-) diff --git a/src/blueprint/agents/agent_group.py b/src/blueprint/agents/agent_group.py index 81a24f05..194c7ed7 100644 --- a/src/blueprint/agents/agent_group.py +++ b/src/blueprint/agents/agent_group.py @@ -238,10 +238,11 @@ def resolve(cls, config: Config, *, environ: dict[str, str] | None = None) -> "A def from_config(cls, group: GroupConfig) -> "AgentGroup": """Import each agent named by ``group``, and return the group they form. - **Reads no environment and no files.** Importing an agent's module is the one thing - here that reaches outside, and it is driven entirely by the ``module`` strings the - group carries -- so a test points them at test modules and controls neither the - environment nor the filesystem to do it. Imports happen per group, so cold start is + **Reads no environment, and touches the filesystem only through the group.** Importing + an agent's module is driven entirely by the ``module`` strings the group carries, and + the only files looked at are the ones under each agent's ``root``: its layout is + checked, and its ``settings.toml`` and ``.secrets.toml`` are found if they exist -- so + a test points the group at test modules and a temporary root. Imports happen per group, so cold start is proportional to the number of agents this process actually hosts rather than to the number the image contains. diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index e53b29d8..5cda6c2a 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -132,7 +132,7 @@ def is_built(self) -> bool: An already-built component was constructed at the caller's own source line, so it is in the registry before ``build()`` runs, while a class or factory is constructed during the - replay. That difference is what ``AppBuilder._check_declaration_order`` inspects, and + replay. That difference is what ``AppBuilder._restore_declaration_order`` evens out, and what a group refuses outright. """ return isinstance(self.target, Component) @@ -232,8 +232,8 @@ class AppBuilder: ``on_startup``, which is the framework's convention anyway. - **An already-built instance is the exception**, because the caller constructed it at its own source line. It is in the registry before ``build()`` runs, so an instance recorded - after a class registers before it -- see :meth:`_check_declaration_order`, which refuses - the one case where that changes behaviour. + after a class would register before it -- :meth:`_restore_declaration_order` puts the + handlers back in declaration order (S20). The configuration may be given here or to ``build()``, but not both. Given here it is adopted immediately, which is what an existing ``AppBuilder(config)...build()`` chain does @@ -866,10 +866,6 @@ def _construct_declarations(self, config: Config) -> None: Args: config: The application's configuration, handed to the declarations that take one. - - Raises: - ValueError: if the recorded order cannot be reproduced. See - :meth:`_check_declaration_order`. """ built: list[tuple[Declaration, Any]] = [] for entry in self._declarations: @@ -927,8 +923,7 @@ def build(self, config: Config | None = None) -> FastAPI: The application. Raises: - ValueError: if a configuration was given twice, or if the recorded order cannot be - reproduced (see :meth:`_check_declaration_order`). + ValueError: if a configuration was given twice. RuntimeError: if this builder has already been built. """ if self._built: diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 35541650..716bd96e 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -1872,9 +1872,10 @@ async def pause_consumption(self) -> None: """Drain this agent's subscriptions so its events redeliver elsewhere (C4). Drained rather than unsubscribed, for the same reason shutdown drains: a drain stops - new deliveries while letting the ones already in the client's buffer reach their - handler and be acknowledged over the connection that delivered them. An unsubscribe - strands those, and every one of them redelivers. + new deliveries and lets the runs in progress settle over the connection that delivered + them. A JetStream delivery still in the client's buffer reaches the message handler with + the pause already set and is nak'd, so it redelivers to a healthy replica (N4); Core NATS + runs what the drain lets through. The connection stays open. See :meth:`IOClientBase.pause_consumption` for why closing it would make the pause permanent, and :meth:`health_check` for the other half of that. diff --git a/src/blueprint/agents/handler/handler_chain.py b/src/blueprint/agents/handler/handler_chain.py index e74b6491..96d1c013 100644 --- a/src/blueprint/agents/handler/handler_chain.py +++ b/src/blueprint/agents/handler/handler_chain.py @@ -512,7 +512,12 @@ def _warn_without_a_heartbeat(self) -> None: """ bus = str(self.config.get("event_bus", "") or "").strip().lower() agent = self.namespace or ROOT_LABEL - if bus == "nats" and self.config.get("nats_heartbeat_enabled", True) is False: + try: + heartbeat = parse_bool(self.config.get("nats_heartbeat_enabled", True), "nats_heartbeat_enabled") + except ValueError: + # Not ours to refuse: the NATS client fails startup on the same value, naming it. + heartbeat = True + if bus == "nats" and not heartbeat: logger.warning( "Agent '%s' deduplicates events with 'nats_heartbeat_enabled = false': a run that outlasts ack_wait is " "redelivered while it runs, the redelivery is skipped as a duplicate and acknowledged, and if the " diff --git a/src/blueprint/agents/io/api/scheduling/scheduler.py b/src/blueprint/agents/io/api/scheduling/scheduler.py index bc2ca09f..6ff8384d 100644 --- a/src/blueprint/agents/io/api/scheduling/scheduler.py +++ b/src/blueprint/agents/io/api/scheduling/scheduler.py @@ -14,9 +14,10 @@ ``"in_process"`` An APScheduler timer in every replica, for un-orchestrated Docker and local development where no external scheduler exists. Every replica's timer fires, and - each tick is claimed in the shared cache so exactly one replica runs it. With no - cache registered there is nothing to claim with and every replica runs every tick, - which startup warns about. + each tick is claimed in the agent's cache so one replica runs it -- across replicas + only when that cache is Redis: a disk cache's claim holds within one process (S23). + With no cache registered there is nothing to claim with and every replica runs every + tick, which startup warns about. The key has **no default**: registering a scheduler without it fails at startup. Neither value is safe to inherit silently, and which one applies depends on the deployment rather @@ -301,7 +302,8 @@ class SchedulerBase(RestApiBase): ``scheduler_mode`` (str, **required**, no default): ``"event"`` starts no timer and expects the tick as an event on :attr:`tick_topic`, which needs ``event_bus`` set to one of ``TOPIC_TRANSPORTS``; ``"in_process"`` runs an APScheduler timer in every - replica, with each tick claimed in the cache so one replica runs it. See + replica, with each tick claimed in the cache so one replica runs it (on Redis; a disk + cache claims within one process). See :meth:`_resolve_mode` for why there is no default. Args: @@ -462,7 +464,7 @@ def _resolve_mode(self) -> str: f"Set it to '{SCHEDULER_MODE_EVENT}' to take the tick as an event on '{self.tick_topic}', published " f"by an external CronJob -- exactly one replica then runs it. Set it to '{SCHEDULER_MODE_IN_PROCESS}' " "to run an APScheduler timer inside the process, which is correct for local development and plain " - "Docker but fires once per replica." + "Docker but fires once per replica unless a Redis cache claims each tick." ) if mode not in SCHEDULER_MODES: raise ValueError(f"Config key 'scheduler_mode' must be one of {', '.join(SCHEDULER_MODES)}, got {raw!r}.") @@ -611,7 +613,8 @@ async def on_startup(self) -> None: if self.registry.has_cache(): logger.info( - "Scheduler '%s' started an in-process timer with crontab '%s'; each tick is claimed in the cache, so one replica runs it", + "Scheduler '%s' started an in-process timer with crontab '%s'; each tick is claimed in the cache " + "(across replicas only on Redis)", self.name, self._crontab, ) @@ -726,9 +729,9 @@ async def _claim_tick_slot(self) -> bool: slot needs only set-if-absent, which is what :meth:`CacheService.claim` provides atomically. - The consequence to be aware of: replicas whose clocks differ enough to straddle a - minute boundary derive different slots and both tick. Container clock skew is - milliseconds, and a repeated tick is what dedup covers. + The slot is the minute the tick was scheduled for (:meth:`_tick_slot`), not the clock's, + so replicas firing for one scheduled time derive one slot even with skewed clocks. The + claim is atomic across replicas only on Redis; a disk cache's holds within one process. """ if not self.registry.has_cache(): return True diff --git a/src/blueprint/agents/io/telemetry/telemetry.py b/src/blueprint/agents/io/telemetry/telemetry.py index 445698d6..90e348df 100644 --- a/src/blueprint/agents/io/telemetry/telemetry.py +++ b/src/blueprint/agents/io/telemetry/telemetry.py @@ -8,8 +8,9 @@ ``service.name`` The agent's name -- ``otel_service_name`` for the root namespace, so a single-agent application's traces are identical to what it produced before any of this existed. -``deployment.group`` Which group this pod runs, from the environment. Set by the framework - and readable through no supported API (C6). Absent without a group. +``deployment.group`` Which group this pod runs: the group the process resolved, from + ``BLUEPRINT_GROUP`` or a one-group file (S19). Set by the framework and + readable through no supported API (C6). Absent without a named group. ``service.instance.id`` Which replica this is. Absent when it cannot be told. ======================== ====================================================================== diff --git a/src/blueprint/agents/services/infrastructure/cache_service.py b/src/blueprint/agents/services/infrastructure/cache_service.py index 3df1fde4..29b89b60 100644 --- a/src/blueprint/agents/services/infrastructure/cache_service.py +++ b/src/blueprint/agents/services/infrastructure/cache_service.py @@ -223,8 +223,8 @@ def __init__( self._default_ttl = default_ttl self._lock = threading.RLock() # Reentrant lock for thread-safe operations - # Initialize diskcache-rs Cache with file locking for multi-process access - # use_file_locking=True allows multiple processes to safely access the same cache + # File locking lets several processes open one directory (diskcache-rs >= 0.4.10) and see + # each other's entries; it does not make claim() atomic between them (S23, see claim()). self._cache = Cache(str(self.cache_dir), use_file_locking=True) logger.info( diff --git a/tests/unit/agents/handler/test_handler_chain.py b/tests/unit/agents/handler/test_handler_chain.py index 2a6675a7..7b0e12e9 100644 --- a/tests/unit/agents/handler/test_handler_chain.py +++ b/tests/unit/agents/handler/test_handler_chain.py @@ -610,6 +610,16 @@ async def test_nats_with_the_heartbeat_off_warns( await chain.on_startup() assert "nats_heartbeat_enabled = false" in caplog.text + async def test_an_environment_string_false_warns_too( + self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, caplog: pytest.LogCaptureFixture + ) -> None: + """An environment override arrives as text; 'false' must count as off, as the NATS client reads it.""" + self._settings(mock_config, event_bus="nats", nats_heartbeat_enabled="false") + _wire_handlers(mock_registry, []) + with caplog.at_level("WARNING"): + await chain.on_startup() + assert "nats_heartbeat_enabled = false" in caplog.text + async def test_dapr_warns_naming_the_app_call_timeout( self, chain: HandlerChain, mock_registry: MagicMock, mock_config: MagicMock, caplog: pytest.LogCaptureFixture ) -> None: From 1d877f201a351626d635fc312be69f58c11071c1 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Tue, 20 Oct 2026 12:39:36 +0200 Subject: [PATCH 126/133] fix(validate): read settings the way the runtime does; generator and templates match it asbs validate and asbs validate --group now load settings for one target environment (--environment, else /DYNACONF_APP_ENVIRONMENT, else production) through Dynaconf, layer each agent's files with the runtime's own functions, and resolve the group file through GroupConfig.resolve_at. Where the runtime has a public rule the validator calls it (validate_crontab, parse_bool, validate_subject_segment, AGENT_REFUSED_KEYS); the rules that are still private in the runtime are restated and pinned by tests (N19, step 22). Of 19 live cases on fresh scaffolds where the runtime refuses to start or warns, the old validator reported 1, the new one all 19. New options --environment, --group-config, --group-name. Runtime: public helpers only (GroupConfig.resolve_at, Config.resolve_envvar_prefix, environment_section_names, layer_settings_document, AGENT_REFUSED_KEYS); the runtime calls the same code as before. Generator: create handler writes [default.] input_event_type; create scheduler checks the crontab before writing; the generated declaration test survives an earlier build; a test starts a fresh scaffold the way its container does (the generated handler's event-type check, N18, stays as it is: making it fire stopped every fresh scaffold); template, help and tree texts corrected. Plan: docs/plans/2026-10-16-pr96-review-fixes.md; the validator experiments (old/new/runtime per case) are summarised in the PR description. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../base_files/group_Dockerfile | 18 +- .../agent_generator/base_files/settings.txt | 13 +- .../base_files/src/handlers/handler.txt | 5 + .../agent_generator/cli/commands/create.py | 48 +- .../agent_generator/cli/commands/dev.py | 20 +- .../cli/commands/group_setup.py | 11 +- .../agent_generator/cli/commands/setup.py | 7 +- .../agent_generator/cli/commands/validate.py | 1043 +++++++++++------ .../cli/commands/validate_group.py | 449 +++++-- src/blueprint/agent_generator/cli/main.py | 27 +- .../docs/guides/cli/validate.md | 221 +++- .../part_generators/part_generator_base.py | 5 +- .../pyproject_part_generator.py | 7 +- .../part_generators/tests_part_generator.py | 39 +- src/blueprint/agents/config/config.py | 103 +- src/blueprint/agents/group_config.py | 23 +- .../cli/commands/test_create_components.py | 112 ++ .../cli/commands/test_create_scheduler.py | 14 + .../agent_generator/cli/commands/test_dev.py | 11 + .../cli/commands/test_validate.py | 10 +- .../cli/commands/test_validate_group.py | 26 +- .../cli/commands/test_validate_group_gates.py | 186 +-- .../commands/test_validate_group_runtime.py | 279 +++++ .../cli/commands/test_validate_nats.py | 10 +- .../commands/test_validate_runtime_parity.py | 317 +++++ .../cli/test_generator_text.py | 61 + 26 files changed, 2369 insertions(+), 696 deletions(-) create mode 100644 tests/unit/agent_generator/cli/commands/test_create_components.py create mode 100644 tests/unit/agent_generator/cli/commands/test_validate_group_runtime.py create mode 100644 tests/unit/agent_generator/cli/commands/test_validate_runtime_parity.py create mode 100644 tests/unit/agent_generator/cli/test_generator_text.py diff --git a/src/blueprint/agent_generator/base_files/group_Dockerfile b/src/blueprint/agent_generator/base_files/group_Dockerfile index ce74c905..02062942 100644 --- a/src/blueprint/agent_generator/base_files/group_Dockerfile +++ b/src/blueprint/agent_generator/base_files/group_Dockerfile @@ -4,13 +4,19 @@ # Group image - hosts several agents in one process # ============================================================================ # -# The difference from an agent's own Dockerfile is what gets copied, not how it runs: both end -# at the same entry point, because a standalone agent is a group of one. Here the agent -# directories are copied as they are, beside the map that names them. +# The two images run differently. An agent's own Dockerfile serves its one declaration directly +# (uvicorn src.main:create_app --factory), at the root namespace, with no map and no group. This +# one runs the group entry point, which reads agents.toml and hosts each agent the deployment +# names under its own namespace (/api/). The agent directories are copied as they are, +# beside the map that names them. # -# Each agent directory is exactly what `asbs setup ` wrote -- its own settings.toml, -# .secrets.toml and src/ -- and carries no agents.toml. That is what lets the same directory be -# built by its own Dockerfile as a single-agent image without editing anything. +# Each agent directory is exactly what `asbs setup ` wrote -- its own settings.toml and +# src/ -- and carries no agents.toml. That is what lets the same directory be built by its own +# Dockerfile as a single-agent image without editing anything. Its .secrets.toml is NOT copied +# (.dockerignore excludes every one): mount it at runtime beside the agent's src, at +# /app//.secrets.toml, where is the agent's `root` in agents.toml -- for example +# docker run -v ./agents/billing/.secrets.toml:/app/agents/billing/.secrets.toml:ro +# or supply single keys as environment variables (DYNACONF___MODEL_API_KEY=...). FROM python:3.13-bookworm AS builder diff --git a/src/blueprint/agent_generator/base_files/settings.txt b/src/blueprint/agent_generator/base_files/settings.txt index c8be7e0b..8cd76a5a 100644 --- a/src/blueprint/agent_generator/base_files/settings.txt +++ b/src/blueprint/agent_generator/base_files/settings.txt @@ -2,7 +2,6 @@ app_name app_version = "0.1.0" app_description -debug = true model_provider = "vllm" model_base_url = "https://YOUR_VLLM_HOST/v1" @@ -10,7 +9,9 @@ model_base_url = "https://YOUR_VLLM_HOST/v1" # same event, because delivery is at-least-once and an acknowledgement can always be # lost. Turn it on only after deciding it is what your handlers need -- see the DECIDE # comment in src/handlers/. idempotency_ttl is required when it is enabled, and must -# outlast the broker redelivery window (nats_ack_wait * nats_max_deliver on JetStream). +# outlast the broker redelivery window (nats_ack_wait * nats_max_deliver on JetStream); +# the markers are kept in this agent's cache, so src/main.py needs .with_cache() as well. +# Startup fails if either is missing. # idempotency_enabled = true # idempotency_ttl = 1500 @@ -19,9 +20,11 @@ model_base_url = "https://YOUR_VLLM_HOST/v1" # in-process timer: the tick arrives as an event on .scheduler. # (the application's name instead of the agent when it is served on its own), published # by an external CronJob, so exactly one replica runs it -- and it needs event_bus set. -# "in_process" runs an APScheduler timer in the process and claims each tick in the cache -# so one replica runs it; it is right for local development and plain Docker, and it -# needs .with_cache() or every replica runs every tick. +# "in_process" runs an APScheduler timer in every process and claims each tick in the +# cache; it is right for local development and plain Docker, and it needs .with_cache() +# or every replica runs every tick. The claim is atomic across processes only on Redis +# ([default.cache] backend = "redis"); on the default disk cache it holds +# within one process only, so two replicas sharing the cache directory can both run it. # scheduler_mode = "event" # scheduler_mode = "in_process" diff --git a/src/blueprint/agent_generator/base_files/src/handlers/handler.txt b/src/blueprint/agent_generator/base_files/src/handlers/handler.txt index be56acad..75fb1570 100644 --- a/src/blueprint/agent_generator/base_files/src/handlers/handler.txt +++ b/src/blueprint/agent_generator/base_files/src/handlers/handler.txt @@ -73,6 +73,11 @@ on_shutdown # idempotency_enabled = true # idempotency_ttl = 1500 # seconds; must outlast the redelivery window # + # src/main.py + # .with_cache() # the markers live in this agent's cache + # + # Startup fails without the ttl or without the cache. + # # Dedup keys on the event id and source and is best-effort: it narrows the window, # it does not close it. Whichever you choose, delete this comment once you have. diff --git a/src/blueprint/agent_generator/cli/commands/create.py b/src/blueprint/agent_generator/cli/commands/create.py index c8e51a07..b247ef1d 100644 --- a/src/blueprint/agent_generator/cli/commands/create.py +++ b/src/blueprint/agent_generator/cli/commands/create.py @@ -1,5 +1,6 @@ """Create command - scaffold individual components using existing generators.""" +import json import logging import re import sys @@ -7,10 +8,13 @@ from pathlib import Path from typing import Any +from blueprint.agents.io.api.scheduling.scheduler import validate_crontab + from ...generator.part_generators import ( HandlerPartGenerator, ServicePartGenerator, ) +from ...generator.part_generators.part_generator_base import PartGeneratorBase from ..utils.naming_utils import ( normalize_component_name, add_import_to_main, @@ -99,7 +103,7 @@ def create_handler(args: Namespace) -> None: # Create minimal config for generator config: dict[str, Any] = { - "name": "cli_generated", + "name": f"{event_type} events", "communication_layer": { "handlers": { class_name: { @@ -133,6 +137,10 @@ def create_handler(args: Namespace) -> None: print(f"✓ Created handler: {output_file}") + # The generated on_startup reads .input_event_type, so the event type goes where it + # is read -- the way create agent writes its runtime's block -- rather than into a docstring. + _write_handler_settings(project_root, PartGeneratorBase.camel_to_snake(class_name), event_type) + # Attempt to auto-register in main.py auto_registered = False try: @@ -171,6 +179,27 @@ def create_handler(args: Namespace) -> None: print(f" .with_handler({class_name})") +def _write_handler_settings(project_root: Path, section_key: str, event_type: str) -> None: + """Add ``[default.] input_event_type`` to ``settings.toml``, unless the section exists. + + An existing section is the author's and is left alone; a project without a settings file is + told what to add instead of being given one. + """ + section = f"[default.{section_key}]" + line = f"input_event_type = {json.dumps(event_type)}" + settings_file = project_root / "settings.toml" + if not settings_file.is_file(): + print(f" No settings.toml here; add this to the agent's settings.toml:\n {section}\n {line}") + return + content = settings_file.read_text(encoding="utf-8") + if section in content: + print(f" settings.toml already has {section}; left alone") + return + separator = "" if content.endswith("\n") or not content else "\n" + settings_file.write_text(f"{content}{separator}\n{section}\n{line}\n", encoding="utf-8") + print(f" Added {section} with {line} to settings.toml") + + def create_service(args: Namespace) -> None: """Create a BusinessService component using ServicePartGenerator.""" output_dir = Path(args.output_dir) @@ -187,8 +216,9 @@ def create_service(args: Namespace) -> None: sys.exit(1) # Create minimal config for generator + # "name" is what the service's docstring says it is for (N: it read "Service for cli_generated."). config: dict[str, Any] = { - "name": "cli_generated", + "name": f"{snake_name.removesuffix('_service')} operations", "service_layer": { class_name: { "description": f"Service for {snake_name} operations", @@ -686,7 +716,17 @@ def create_scheduler(args: Namespace) -> None: Note: Scheduler generation is not yet implemented with generators. This creates a simple template file. + + The crontab is checked first with the runtime's own ``validate_crontab`` -- in no mode, since + ``scheduler_mode`` is settings and not known here -- so an expression the scheduler would + refuse at startup is refused before anything is written. """ + try: + validate_crontab(args.cron) + except ValueError as exc: + print(f"Error: {exc}", file=sys.stderr) + sys.exit(1) + output_dir = Path(args.output_dir) output_dir.mkdir(parents=True, exist_ok=True) @@ -723,7 +763,9 @@ def __init__(self) -> None: scheduler's own topic, published by an external CronJob that the deployment provides (nothing in this project generates it), and 'event_bus' has to be set. With 'in_process' an APScheduler timer runs here, which is right for local development and - un-orchestrated Docker; with a cache each tick is claimed so one replica runs it. + un-orchestrated Docker; with a cache each tick is claimed first. That claim holds + across replicas only on a Redis cache -- on the default disk cache it holds within one + process, so replicas sharing the directory can each run a tick. Write days of the week as names ('mon-fri'): 0 is Monday here and Sunday to cron. """ super().__init__(crontab="{args.cron}") diff --git a/src/blueprint/agent_generator/cli/commands/dev.py b/src/blueprint/agent_generator/cli/commands/dev.py index 189aa870..618beb76 100644 --- a/src/blueprint/agent_generator/cli/commands/dev.py +++ b/src/blueprint/agent_generator/cli/commands/dev.py @@ -179,19 +179,19 @@ def _declares(entry_point: Path, name: str) -> bool: return False -def _dev_agent_name(args: Namespace) -> str: - """Return the name this agent runs under while developing. +def _dev_agent_name(requested: str) -> str: + """Return the name this agent runs under while developing: ``--name``, as a namespace. - ``--name`` -- only asked for when it was given; without it the agent is served at the root. - The agent itself does not carry a name: it is its identity on the broker, in telemetry and in - its routes, and who supplies it depends on who is hosting it -- a group image's map, or this. + Only called when ``--name`` was given; without it the agent is served alone, at the root, and + has no name to derive -- the directory's name is deliberately not one. The agent itself does + not carry a name: it is its identity on the broker, in telemetry and in its routes, and who + supplies it depends on who is hosting it -- a group image's map, or this. Raises: - SystemExit: if neither yields a legal namespace, because a repaired name would be a - different agent under the same directory. + SystemExit: if the name is not a legal namespace once dashes and spaces become + underscores, because a further-repaired name would be a different agent. """ - requested = (getattr(args, "name", "") or "").strip() or Path.cwd().name - candidate = re.sub(r"[-\s]+", "_", requested).lower() + candidate = re.sub(r"[-\s]+", "_", requested.strip()).lower() try: return validate_namespace(candidate) except ValueError as exc: @@ -207,7 +207,7 @@ def _temporary_agent_map(args: Namespace) -> Path: leave behind exactly the file an agent must not carry, and a developer who then committed it would have an agent that names itself. """ - name = _dev_agent_name(args) + name = _dev_agent_name(getattr(args, "name", "") or "") handle = tempfile.NamedTemporaryFile("w", suffix="-agents.toml", delete=False, encoding="utf-8") with handle as written: written.write(f'[agents.{name}]\nroot = "."\nmodule = "src.main:agent"\n') diff --git a/src/blueprint/agent_generator/cli/commands/group_setup.py b/src/blueprint/agent_generator/cli/commands/group_setup.py index ee6e6e95..34c45c75 100644 --- a/src/blueprint/agent_generator/cli/commands/group_setup.py +++ b/src/blueprint/agent_generator/cli/commands/group_setup.py @@ -30,11 +30,15 @@ app_port = 8000 log_level = "INFO" -# "dapr" or "nats". One process speaks one bus. +# "dapr" or "nats". One process speaks one bus. With "nats", nats_url is required outside +# development (DYNACONF_NATS_URL works too): there is no default broker in a container. # event_bus = "nats" +# nats_url = "nats://YOUR_NATS_HOST:4222" # Required once any agent registers a scheduler. "in_process" runs a timer in every replica and -# claims each tick through the cache, so it needs a cache; "event" takes the tick as an event. +# claims each tick through the agent's cache, so it needs a cache -- and Redis +# (cache.backend = "redis") once there is more than one replica: a disk cache's claim holds +# within one process only. "event" takes the tick as an event, published by an external CronJob. # scheduler_mode = "event" [development] @@ -141,7 +145,8 @@ def _report(output_dir: Path, written: list[str], skipped: list[str]) -> None: print("An agent directory carries no agents.toml of its own, which is what lets it be") print("built as its own single-agent image without editing anything.") print("") - print("Run 'asbs validate --group' here to check the map against what is on disk.") + print("Run 'asbs validate --group' here to check the map against what is on disk -- it reports the") + print("empty map as an issue until the first agent is added.") def run(args: Namespace) -> None: diff --git a/src/blueprint/agent_generator/cli/commands/setup.py b/src/blueprint/agent_generator/cli/commands/setup.py index b147c653..cc49cefa 100644 --- a/src/blueprint/agent_generator/cli/commands/setup.py +++ b/src/blueprint/agent_generator/cli/commands/setup.py @@ -187,9 +187,12 @@ def run(args: Namespace) -> None: print(" │ ├── models/") print(" │ └── prompts/") print(" ├── tests/") + print(" ├── pyproject.toml (left alone when there already is one)") print(" ├── settings.toml") - print(" ├── .secrets.toml") + print(" ├── .secrets.toml (git- and docker-ignored: mount it, never bake it in)") + print(" ├── .secrets.toml.example") print(" ├── Dockerfile") + print(" ├── .dockerignore") print(" └── .gitignore") print("\nNext steps:") @@ -215,7 +218,7 @@ def run(args: Namespace) -> None: print("first deploy is a consumer migration.") print("\nTo host it in a group, add to the repository's agents.toml:") print(f" [agents.{namespace}]") - print(' root = ""') + print(' root = ""') print(' module = ".src.main:agent"') finally: diff --git a/src/blueprint/agent_generator/cli/commands/validate.py b/src/blueprint/agent_generator/cli/commands/validate.py index 904615d8..feb0b417 100644 --- a/src/blueprint/agent_generator/cli/commands/validate.py +++ b/src/blueprint/agent_generator/cli/commands/validate.py @@ -1,34 +1,67 @@ -"""Validate command - check project structure and configuration.""" +"""Validate command - check project structure and configuration. +Every check that predicts a startup failure or a startup warning reads the settings the way the +process does, for one target environment, and applies the runtime's own rule wherever the runtime +has one as a public function. The project's own code is never imported: files are read and parsed. +""" + +import ast import importlib.util import logging import os -import re import sys import tomllib from argparse import Namespace +from dataclasses import dataclass from pathlib import Path from typing import Any +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError + +from dynaconf import Dynaconf +from blueprint.agents.clients.io.io_client_base import TOPIC_TRANSPORTS, validate_subject_segment from blueprint.agents.clients.io.nats_client import CONNECTIONS_READINESS_MODES from blueprint.agents.clients.io.nats_run_pool import RunLimit -from blueprint.agents.component.namespace import validate_namespace -from blueprint.agents.config import PROCESS_SCOPE_KEYS - -from . import validate_group -from ..utils.cancellation_check import swallowed_cancellation_warning, swallowed_cancellations +from blueprint.agents.config.config import ( + AGENT_REFUSED_KEYS, + DEFAULT_ENVVAR_PREFIX, + DEFAULT_SETTINGS_FILES, + Config, + ConfigError, + environment_section_names, + layer_settings_document, +) from blueprint.agents.io.api.scheduling.scheduler import ( SCHEDULER_MODE_EVENT, SCHEDULER_MODE_IN_PROCESS, SCHEDULER_MODES, delivers_ticks, normalise_scheduler_mode, + validate_crontab, ) +from blueprint.agents.utils import parse_bool + +from ..utils.cancellation_check import swallowed_cancellation_warning, swallowed_cancellations logger = logging.getLogger(__name__) AGENT_MAP_FILE = "agents.toml" SETTINGS_FILE = "settings.toml" +SECRETS_FILE = ".secrets.toml" + +DEFAULT_ENVIRONMENT = "production" +"""The environment checked when neither ``--environment`` nor the environment names one. + +Both scaffolded Dockerfiles set ``DYNACONF_APP_ENVIRONMENT="production"`` in the image that is +deployed, so that is the section a pod loads -- not the ``development`` the framework defaults to +when nothing sets it. +""" + +EVENT_BUSES = (*TOPIC_TRANSPORTS, "sessions") +"""The ``event_bus`` values ``AppBuilder`` wires a transport for; anything else disables event handling.""" + +READ_AT_THE_TOP_LEVEL = frozenset({"envvar_prefix", "app_environment", "dynaconf_merge", "dynaconf_include"}) +"""Keys the process does read outside any section: the bootstrap pass reads these from the top level.""" IDEMPOTENCY_NOTICE = "\n".join( [ @@ -39,10 +72,212 @@ " Decide which one this project needs:", " - handlers that are safe to repeat -- nothing to change; or", " - set 'idempotency_enabled = true' and 'idempotency_ttl = ' in settings.toml,", - " with a window that outlasts the broker redelivery window.", + " with a window that outlasts the broker redelivery window, and add .with_cache() to", + " the AppBuilder chain: the markers are kept in this agent's cache.", ] ) +Findings = tuple[list[str], list[str], list[str]] +"""Issues, warnings and notices, in that order.""" + + +# ---------------------------------------------------------------------------------------------- +# Settings, read the way the process reads them +# ---------------------------------------------------------------------------------------------- + + +def _lookup(source: Any, key: str) -> Any | None: + """``key`` (dotted for a nested table) in ``source``, matched case-insensitively; ``None`` when absent.""" + node = source + for part in key.split("."): + if not isinstance(node, dict): + return None + match = next((value for name, value in node.items() if str(name).lower() == part.lower()), None) + if match is None: + return None + node = match + return node + + +def _plain(value: Any) -> Any: + """A Dynaconf box as plain dicts and lists, so nothing downstream depends on Dynaconf's types.""" + if hasattr(value, "items"): + return {str(key): _plain(inner) for key, inner in value.items()} + if isinstance(value, (list, tuple)): + return [_plain(inner) for inner in value] + return value + + +@dataclass(frozen=True) +class SettingsView: + """What one namespace reads: its own scope first, then the process's root keys. + + ``sources`` is in precedence order and the first that sets a key wins, with ``None`` meaning + "not set" -- the resolution ``Config.get`` performs for a scoped view, where the scope holds + the image's ``[default.]`` and environment overrides, then the agent's ``.secrets.toml``, + then its ``settings.toml`` (the merge fills in what is missing), and the root tree comes last. + """ + + sources: tuple[dict[str, Any], ...] + + def get(self, key: str, default: Any = None) -> Any: + """``key``'s value as this namespace reads it, or ``default``.""" + for source in self.sources: + value = _lookup(source, key) + if value is not None: + return value + return default + + +@dataclass(frozen=True) +class ProcessSettings: + """The process's own settings files (``settings.toml`` and ``.secrets.toml``), loaded for one environment. + + Loaded through Dynaconf in environment mode, with the prefix the runtime resolves + (``Config.resolve_envvar_prefix``), so the layering is the process's own: ``[default]``, the + target environment's section and ``[global]``, plus every environment override in this + process's environment. A key written outside any section, or only in another environment's + section, is therefore not set -- as it is not for the pod. + + ``app_environment`` is set to the target environment, as the Dockerfiles' environment variable + sets it for the pod. + + Attributes: + directory: The directory the files were read from. + environment: The environment checked. + prefix: The environment-override prefix, or ``False`` for none. + tree: The loaded tree, top-level keys lower-cased. + documents: The files as parsed, for the keys they spell. + problems: What stopped the files being read, as issues. + """ + + directory: Path + environment: str + prefix: str | bool + tree: dict[str, Any] + documents: dict[str, dict[str, Any]] + problems: tuple[str, ...] + + @classmethod + def load(cls, directory: Path, environment: str | None = None) -> "ProcessSettings": + """Read the process's settings in ``directory`` for ``environment``. + + Args: + directory: The project or image root. + environment: ``--environment``. Unset, the environment variable the process reads + (``_APP_ENVIRONMENT``) decides, and without one :data:`DEFAULT_ENVIRONMENT`. + """ + files = [directory / name for name in DEFAULT_SETTINGS_FILES if (directory / name).is_file()] + documents: dict[str, dict[str, Any]] = {} + problems: list[str] = [] + for path in files: + try: + documents[path.name] = tomllib.loads(path.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError) as exc: + # Values are never shown, so an unparseable secrets file is named, not quoted. + problems.append(f"{path.name} could not be read: {exc}") + if problems: + # Guessing at a key from a file that does not parse would be worse than staying quiet. + return cls( + directory, cls._environment(environment, DEFAULT_ENVVAR_PREFIX), DEFAULT_ENVVAR_PREFIX, {}, documents, tuple(problems) + ) + + names = [str(path) for path in files] + bootstrap = Dynaconf(settings_files=names, environments=False, load_dotenv=False, merge_enabled=True) + try: + prefix = Config.resolve_envvar_prefix(bootstrap) + except ConfigError as exc: + problems.append(str(exc)) + prefix = DEFAULT_ENVVAR_PREFIX + target = cls._environment(environment, prefix) + loaded = Dynaconf(settings_files=names, environments=True, env=target, load_dotenv=False, merge_enabled=True, envvar_prefix=prefix) + tree = {str(key).lower(): _plain(value) for key, value in loaded.as_dict().items()} + tree["app_environment"] = target + return cls(directory, target, prefix, tree, documents, tuple(problems)) + + @staticmethod + def _environment(requested: str | None, prefix: str | bool) -> str: + """The target environment: the option, else the process's environment variable, else production.""" + variables = ([f"{prefix}_APP_ENVIRONMENT"] if prefix and prefix != DEFAULT_ENVVAR_PREFIX else []) + [ + f"{DEFAULT_ENVVAR_PREFIX}_APP_ENVIRONMENT" + ] + for candidate in [requested, *(os.environ.get(name) for name in variables)]: + if candidate and candidate.strip(): + return candidate.strip().lower() + return DEFAULT_ENVIRONMENT + + @property + def readable(self) -> bool: + """Whether every settings file parsed; checks that read values stay quiet otherwise.""" + return not self.problems + + @property + def override_variable_prefix(self) -> str: + """How an environment override is spelled: ``DYNACONF_`` or the declared prefix, or nothing.""" + return f"{self.prefix}_" if self.prefix else "" + + def root_view(self) -> SettingsView: + """What the root namespace -- a standalone agent, or the process itself -- reads.""" + return SettingsView((self.tree,)) + + def environment_names(self) -> frozenset[str]: + """The table names that are environment sections to this process (the runtime's own rule).""" + return environment_section_names(list(self.documents.values())) + + def layered(self, document: dict[str, Any]) -> dict[str, Any]: + """An agent's file flattened for this environment, as ``Config.merge_agent_settings`` flattens it.""" + return layer_settings_document(document, self.environment, self.environment_names()) + + def agent_view(self, name: str, fragments: list[dict[str, Any]]) -> SettingsView: + """What agent ``name`` reads, given its own files already parsed (``.secrets.toml`` first). + + The keys the merge drops (:data:`AGENT_REFUSED_KEYS`) are dropped here too, so such a key + resolves to the process's value -- which is what the agent then reads. + """ + scope = _lookup(self.tree, name) + own = [scope] if isinstance(scope, dict) else [] + kept = [ + {key: value for key, value in self.layered(document).items() if str(key).lower() not in AGENT_REFUSED_KEYS} + for document in fragments + ] + return SettingsView((*own, *kept, self.tree)) + + def unread_key_warnings(self) -> list[str]: + """Keys written at the top level of the process's own files, where the process loads nothing. + + In environment mode Dynaconf loads ``[default]``, the active environment's section and + ``[global]``; a plain key above them is read by nobody (verified against dynaconf 3.3.5). + Keys only, never values: one of these files holds secrets. + """ + warnings = [] + for file_name, document in self.documents.items(): + unread = sorted( + str(key) for key, value in document.items() if not isinstance(value, dict) and str(key).lower() not in READ_AT_THE_TOP_LEVEL + ) + if unread: + warnings.append( + f"{file_name} sets {', '.join(unread)} at the top level, outside any section. The process loads " + "[default], the active environment's section and [global] only, so nothing reads them. Move them " + "under [default]." + ) + return warnings + + +def read_document(path: Path) -> dict[str, Any] | None: + """A parsed TOML file, or ``None`` when it is missing or unreadable (its own check reports that).""" + if not path.is_file(): + return None + try: + return tomllib.loads(path.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError) as exc: + logger.debug("Could not read %s: %s", path, exc) + return None + + +# ---------------------------------------------------------------------------------------------- +# The command +# ---------------------------------------------------------------------------------------------- + def run(args: Namespace) -> None: """Execute the validate command. @@ -50,6 +285,8 @@ def run(args: Namespace) -> None: Args: args: Parsed command-line arguments """ + from . import validate_group # here, not at the top: validate_group imports this module + # An image and an agent are different things to check, so this is a mode rather than a # guess about what the directory looks like. if getattr(args, "group", False): @@ -62,44 +299,36 @@ def run(args: Namespace) -> None: print(f"Error: Project directory does not exist: {project_dir}", file=sys.stderr) sys.exit(1) + settings = ProcessSettings.load(project_dir, getattr(args, "environment", None)) print(f"Validating Blueprint Agents project: {project_dir}") + print(f"Environment: {settings.environment} (choose another with --environment)") print() - issues = [] - warnings = [] - notices = [] + issues: list[str] = [] + warnings: list[str] = [] + notices: list[str] = [] - # Check for required directories - required_dirs = ["src", "tests"] - for dir_name in required_dirs: - dir_path = project_dir / dir_name - if not dir_path.is_dir(): + for dir_name in ("src", "tests"): + if not (project_dir / dir_name).is_dir(): issues.append(f"Missing required directory: {dir_name}/") else: - print(f"✓ Found {dir_name}/") + print(f"[ok] Found {dir_name}/") - # Check for configuration files - config_files = ["settings.toml", "pyproject.toml"] - for file_name in config_files: - file_path = project_dir / file_name - if not file_path.is_file(): + for file_name in (SETTINGS_FILE, "pyproject.toml"): + if not (project_dir / file_name).is_file(): issues.append(f"Missing configuration file: {file_name}") else: - print(f"✓ Found {file_name}") - - # Check for secrets template. The leading dot is what DEFAULT_SETTINGS_FILES names, so a - # file without it is loaded by nothing -- which is why an undotted one is reported as the - # rename it needs rather than as a file that is simply missing. - secrets_example = project_dir / ".secrets.toml.example" - secrets_file = project_dir / ".secrets.toml" - undotted = project_dir / "secrets.toml" - if not secrets_example.is_file(): + print(f"[ok] Found {file_name}") + + # The leading dot is what DEFAULT_SETTINGS_FILES names, so a file without it is loaded by + # nothing -- which is why an undotted one is reported as the rename it needs rather than as a + # file that is simply missing. + if not (project_dir / ".secrets.toml.example").is_file(): warnings.append("Missing .secrets.toml.example template") else: - print("✓ Found .secrets.toml.example") - - if not secrets_file.is_file(): - if undotted.is_file(): + print("[ok] Found .secrets.toml.example") + if not (project_dir / SECRETS_FILE).is_file(): + if (project_dir / "secrets.toml").is_file(): warnings.append( "Found secrets.toml, which nothing loads: the framework reads '.secrets.toml'. " "Rename it (git mv secrets.toml .secrets.toml) or its keys are invisible at startup." @@ -107,54 +336,36 @@ def run(args: Namespace) -> None: else: warnings.append("Missing .secrets.toml (copy from .secrets.toml.example)") - # Check for main.py main_file = project_dir / "src" / "main.py" if not main_file.is_file(): issues.append("Missing src/main.py entry point") else: - print("✓ Found src/main.py") - - # Check if main.py uses AppBuilder. Nothing is checked about Config here: main.py is a - # declaration, and the configuration belongs to whatever builds it -- a main.py that - # mentions Config at all is the pre-declaration shape, not the expected one. - content = main_file.read_text() - if "AppBuilder" not in content: + print("[ok] Found src/main.py") + # Nothing is checked about Config here: main.py is a declaration, and the configuration + # belongs to whatever builds it. + if "AppBuilder" not in main_file.read_text(encoding="utf-8"): warnings.append("src/main.py does not appear to use AppBuilder") - # Check for component directories - component_dirs = ["handlers", "services", "api", "models"] src_dir = project_dir / "src" if src_dir.is_dir(): - for dir_name in component_dirs: - dir_path = src_dir / dir_name - if dir_path.is_dir(): - print(f"✓ Found src/{dir_name}/") + for dir_name in ("handlers", "services", "api", "models"): + if (src_dir / dir_name).is_dir(): + print(f"[ok] Found src/{dir_name}/") - # Check for tests tests_dir = project_dir / "tests" if tests_dir.is_dir(): test_files = list(tests_dir.glob("test_*.py")) if not test_files: warnings.append("No test files found in tests/") else: - print(f"✓ Found {len(test_files)} test file(s)") + print(f"[ok] Found {len(test_files)} test file(s)") - # Check for Docker files - dockerfile = project_dir / "Dockerfile" - docker_compose = project_dir / "docker-compose.yml" - if dockerfile.is_file(): - print("✓ Found Dockerfile") + if (project_dir / "Dockerfile").is_file(): + print("[ok] Found Dockerfile") else: warnings.append("Missing Dockerfile for containerization") - - if docker_compose.is_file(): - print("✓ Found docker-compose.yml") - - # Idempotency decision (spec sec. 7.4): the framework must not choose for the author, - # so it says nothing at all only when the project has no handlers to run twice. - notice = _idempotency_notice(project_dir) - if notice: - notices.append(notice) + if (project_dir / "docker-compose.yml").is_file(): + print("[ok] Found docker-compose.yml") # A swallowed cancellation defeats nats_handler_timeout: the run goes on and is nak'd anyway. if src_dir.is_dir(): @@ -162,17 +373,21 @@ def run(args: Namespace) -> None: if swallowed: warnings.append(swallowed_cancellation_warning(project_dir.name, swallowed)) - # The NATS delivery keys: each of these fails startup when it is wrong, so say so here first. - issues.extend(_nats_findings(project_dir)) + issues.extend(settings.problems) + warnings.extend(settings.unread_key_warnings()) - # Group readiness: what this project must state before it can be hosted beside another - # agent, and what would otherwise stay silent. - group_issues, group_warnings, group_notices = _group_findings(project_dir) + # A project holding an agent map with entries is an image, and its agents are checked as the + # group entry point would host them; otherwise the project is the process, at the root. + group_issues, group_warnings, group_notices = _group_findings(project_dir, settings.environment) issues.extend(group_issues) warnings.extend(group_warnings) notices.extend(group_notices) + if not _hosts_agents(project_dir): + root_issues, root_warnings, root_notices = root_findings(project_dir, settings) + issues.extend(root_issues) + warnings.extend(root_warnings) + notices.extend(root_notices) - # Print summary print() print("=" * 60) @@ -182,59 +397,78 @@ def run(args: Namespace) -> None: print(f" - {item}") if not issues and not warnings: - print("✓ Validation passed! Project structure looks good.") + print("[ok] Validation passed! Project structure looks good.") sys.exit(0) if warnings: - print(f"\n⚠ Warnings ({len(warnings)}):") + print(f"\nWarnings ({len(warnings)}):") for warning in warnings: print(f" - {warning}") if issues: - print(f"\n✗ Issues ({len(issues)}):") + print(f"\nIssues ({len(issues)}):") for issue in issues: print(f" - {issue}") print("\nProject validation failed. Please fix the issues above.") sys.exit(1) else: - print("\n✓ Validation passed with warnings.") + print("\n[ok] Validation passed with warnings.") sys.exit(0) -def _idempotency_notice(project_dir: Path) -> str | None: - """Return the dedup notice if this project has handlers and has not opted into dedup. +def root_findings(project_dir: Path, settings: ProcessSettings) -> Findings: + """Everything the process checks at startup for a standalone agent, which runs at the root namespace. - Returns ``None`` when the project declares ``idempotency_enabled``, whichever way it - declares it: the author has then made the decision spec sec. 7.4 asks for, and saying - it again on every run is how a notice stops being read. Also ``None`` when there are no - handlers, since nothing can be dispatched twice. + Args: + project_dir: The project root, which is also the process's directory. + settings: The project's settings, loaded for the target environment. """ - handlers_dir = project_dir / "src" / "handlers" - if not handlers_dir.is_dir() or not any(handlers_dir.glob("*_handler.py")): - return None + if not settings.readable: + return [], [], [] + view = settings.root_view() + issues: list[str] = [] + warnings: list[str] = [] + notices: list[str] = [] - settings_file = project_dir / SETTINGS_FILE - if not settings_file.is_file(): - return IDEMPOTENCY_NOTICE + # Idempotency decision (spec sec. 7.4): the framework must not choose for the author, so it + # says nothing at all only when the project has no handlers to run twice. + if has_handlers(project_dir) and view.get("idempotency_enabled") is None: + notices.append(IDEMPOTENCY_NOTICE) + + for found in ( + scheduler_findings(project_dir, view=view, settings=settings, where=SETTINGS_FILE), + dedup_findings(project_dir, view=view, settings=settings), + transport_findings(project_dir, view=view, settings=settings), + process_findings(settings), + ): + issues.extend(found[0]) + warnings.extend(found[1]) + notices.extend(found[2]) + issues.extend(nats_value_findings(project_dir, view)) + return issues, warnings, notices - settings = _load_settings(settings_file) - if settings is None: - return None - # Dynaconf environments are top-level tables, and the key is valid in any of them. - if _declares(settings, "idempotency_enabled"): +def _idempotency_notice(project_dir: Path, environment: str | None = None) -> str | None: + """Return the dedup notice if this project has handlers and has not decided on dedup. + + ``None`` when ``idempotency_enabled`` is set either way for the target environment -- the + author has then made the decision spec sec. 7.4 asks for -- when there are no handlers, and + when the settings cannot be read (that has its own report). + """ + if not has_handlers(project_dir): + return None + settings = ProcessSettings.load(project_dir, environment) + if not settings.readable: return None - return IDEMPOTENCY_NOTICE + return IDEMPOTENCY_NOTICE if settings.root_view().get("idempotency_enabled") is None else None # ---------------------------------------------------------------------------------------------- # Group readiness # -# Everything below answers one question: can this project be hosted beside another agent in one -# process, and if not, what has it failed to say? There is deliberately no `asbs migrate` -- -# main.py is the developer's own declaration, and a tool that rewrites it either guesses at -# intent or fails on anything hand-edited. A checklist plus a validate that names what is -# missing is the honest shape. +# There is deliberately no `asbs migrate` -- main.py is the developer's own declaration, and a +# tool that rewrites it either guesses at intent or fails on anything hand-edited. A checklist +# plus a validate that names what is missing is the honest shape. # ---------------------------------------------------------------------------------------------- NO_AGENT_MAP_NOTICE = "\n".join( @@ -250,219 +484,190 @@ def _idempotency_notice(project_dir: Path) -> str | None: ) -def _group_findings(project_dir: Path) -> tuple[list[str], list[str], list[str]]: - """Report what stops this project being hosted as one agent among several. +def _hosts_agents(project_dir: Path) -> bool: + """Whether ``project_dir`` holds an agent map with entries, which makes it an image.""" + document = read_document(project_dir / AGENT_MAP_FILE) + declared = document.get("agents") if document else None + return isinstance(declared, dict) and bool(declared) - Args: - project_dir: The project root. - Returns: - Issues, warnings and notices, in that order. - """ - issues: list[str] = [] - warnings: list[str] = [] - notices: list[str] = [] - - agent_map_file = project_dir / AGENT_MAP_FILE - if not agent_map_file.is_file(): - notices.append(NO_AGENT_MAP_NOTICE) - agents: dict[str, str] = {} - else: - agents, map_issues = _read_agent_map(agent_map_file) - issues.extend(map_issues) - if agents: - print(f"[ok] Found {AGENT_MAP_FILE} ({len(agents)} agent(s): {', '.join(agents)})") - - for name, module in agents.items(): - issues.extend(_declaration_issues(project_dir, name, module)) - warnings.extend(_settings_scope_warnings(project_dir, name, module, hosted_alone=len(agents) == 1)) +def _group_findings(project_dir: Path, environment: str | None = None) -> Findings: + """Report what the project's agent map says, if it has one. - scheduler_issues, scheduler_notices = _scheduler_findings(project_dir) - issues.extend(scheduler_issues) - notices.extend(scheduler_notices) + No map is the right shape for an agent, and gets a notice. A map with entries makes this + directory an image, so it is checked by ``asbs validate --group``'s own rules -- each entry + needs a ``root`` and the agent's settings are read from beside that root's ``src``, as at + runtime -- rather than by a second, older reading of the same file. - return issues, warnings, notices - - -def _read_agent_map(agent_map_file: Path) -> tuple[dict[str, str], list[str]]: - """Return ``{agent name: "module:attribute"}`` and whatever is wrong with the file. - - The same shape ``GroupConfig._read_agent_map`` refuses to start on, checked here instead -- - where the answer is a line in a terminal rather than a crash-looping pod. The agent name is - held to the namespace alphabet by the framework's own validator, because a name repaired - differently by the queue group, the durable, the cache partition and the telemetry resource - is four names for one agent. + Args: + project_dir: The project root. + environment: The target environment. """ + from . import validate_group # here, not at the top: validate_group imports this module + + agent_map = project_dir / AGENT_MAP_FILE + if not agent_map.is_file(): + return [], [], [NO_AGENT_MAP_NOTICE] try: - document = tomllib.loads(agent_map_file.read_text(encoding="utf-8")) + tomllib.loads(agent_map.read_text(encoding="utf-8")) except (OSError, tomllib.TOMLDecodeError) as exc: - return {}, [f"{AGENT_MAP_FILE} could not be read: {exc}"] + return [f"{AGENT_MAP_FILE} could not be read: {exc}"], [], [] + if not _hosts_agents(project_dir): + return [f"{AGENT_MAP_FILE} declares no [agents.] entries, so this image contains no agents"], [], [] + print(f"[ok] {AGENT_MAP_FILE} declares agents, so this directory is checked as an image (asbs validate --group)") + return validate_group.image_findings(project_dir, agent_map, environment=environment) - declared = document.get("agents") - if not isinstance(declared, dict) or not declared: - return {}, [f"{AGENT_MAP_FILE} declares no [agents.] entries, so this image contains no agents"] - agents: dict[str, str] = {} - issues: list[str] = [] - for name, entry in declared.items(): - module = entry.get("module") if isinstance(entry, dict) else None - if not module or not isinstance(module, str): - issues.append(f"Agent '{name}' in {AGENT_MAP_FILE} has no 'module'. Write it as module = \"src.main:agent\"") - continue - if ":" not in module: - issues.append( - f"Agent '{name}' in {AGENT_MAP_FILE} names the module '{module}', which does not say which attribute " - 'to read. Write it as "package.module:attribute"' - ) - continue - try: - validate_namespace(name) - except ValueError as exc: - issues.append(f"Agent '{name}' in {AGENT_MAP_FILE} cannot be a namespace: {exc}") - continue - agents[str(name)] = module +# ---------------------------------------------------------------------------------------------- +# The runtime's startup checks, for one namespace +# ---------------------------------------------------------------------------------------------- - return agents, issues +def has_handlers(agent_dir: Path) -> bool: + """Whether the agent registers event handlers (scaffolded as ``src/handlers/*_handler.py``).""" + handlers_dir = agent_dir / "src" / "handlers" + return handlers_dir.is_dir() and any(handlers_dir.glob("*_handler.py")) -def _declaration_issues(project_dir: Path, name: str, module: str) -> list[str]: - """Report an agent whose declaration cannot be found, or is not a declaration. - Checked against the file rather than by importing it: importing runs the module, which needs - the project's dependencies installed and is a different failure from the one being looked for. - What that costs is precision -- this reads text -- and what it buys is a validate that works - in a checkout. - """ - module_path, _, attribute = module.partition(":") - source = _module_file(project_dir, module_path) - if source is None: - return [ - f"Agent '{name}' points at '{module_path}', which is not a module in this project. Either the agent map " - "is out of date, or the declaration moved and the map did not" - ] +def scheduler_modules(agent_dir: Path) -> list[Path]: + """Return the scheduler modules this agent defines.""" + schedulers_dir = agent_dir / "src" / "schedulers" + if not schedulers_dir.is_dir(): + return [] + return [path for path in sorted(schedulers_dir.glob("*.py")) if path.name != "__init__.py"] - text = source.read_text(encoding="utf-8") - if not re.search(rf"^{re.escape(attribute)}\s*=", text, re.MULTILINE): - return [ - f"Agent '{name}' points at '{module}', but {source.relative_to(project_dir).as_posix()} assigns no " - f"'{attribute}'. That is the AppBuilder the host builds; without it the process stops before binding " - "its port" - ] - return [] +def main_declares_a_cache(agent_dir: Path) -> bool: + """Report whether the declaration registers a cache (read, not imported).""" + main_file = agent_dir / "src" / "main.py" + return main_file.is_file() and ".with_cache(" in main_file.read_text(encoding="utf-8") -def _settings_scope_warnings(project_dir: Path, name: str, module: str, *, hosted_alone: bool) -> list[str]: - """Report settings that will not survive this agent being hosted beside another. - Two things go wrong, and neither raises. An agent's own settings file is read from the - directory its declaration lives in, so one written anywhere else is merged into no scope at - all; and a key that describes the *process* -- the port it binds, the bus it speaks, the - environment it loads -- is dropped with a warning when it arrives under one agent's scope, - because one process has exactly one of each. +def declared_crontabs(path: Path) -> list[str]: + """The literal crontabs a scheduler module hands ``SchedulerBase.__init__``. - A project hosted alone is the process, so its settings.toml is the process's own file and - neither applies: it is reported only once there is a second agent to share with. The same - exemption covers an agent declared at the project root in a group -- ``main:agent`` rather - than ``src.main:agent`` -- whose settings file *is* the process's, which the merge recognises - and leaves at the root rather than scoping. + Parsed rather than imported: ``crontab="..."`` as a keyword anywhere, or a string as the first + argument of an ``__init__`` call. A crontab computed at runtime is not seen, and not reported. """ - if hosted_alone: - return [] - - module_path = module.partition(":")[0] - source = _module_file(project_dir, module_path) - if source is None: + try: + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + except (OSError, SyntaxError, UnicodeDecodeError): return [] - - fragment = source.parent / SETTINGS_FILE - if fragment == project_dir / SETTINGS_FILE: + found: list[str] = [] + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + for keyword in node.keywords: + if keyword.arg == "crontab" and isinstance(keyword.value, ast.Constant) and isinstance(keyword.value.value, str): + found.append(keyword.value.value) + if ( + isinstance(node.func, ast.Attribute) + and node.func.attr == "__init__" + and node.args + and isinstance(node.args[0], ast.Constant) + and isinstance(node.args[0].value, str) + ): + found.append(node.args[0].value) + return found + + +def literal_topics(agent_dir: Path) -> list[str] | None: + """The topics the agent's handlers declare, when every declaration is a literal list. + + ``None`` when any ``get_subscribed_topics`` returns something other than a list or tuple of + strings: the topics are then only known at runtime, and a check built on them would guess. + """ + handlers_dir = agent_dir / "src" / "handlers" + if not handlers_dir.is_dir(): return [] + topics: dict[str, None] = {} + for path in sorted(handlers_dir.rglob("*.py")): + try: + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + except (OSError, SyntaxError, UnicodeDecodeError): + return None + for node in ast.walk(tree): + if not isinstance(node, ast.FunctionDef) or node.name != "get_subscribed_topics": + continue + for returned in (inner for inner in ast.walk(node) if isinstance(inner, ast.Return)): + value = returned.value + if not isinstance(value, (ast.List, ast.Tuple)) or not all( + isinstance(item, ast.Constant) and isinstance(item.value, str) for item in value.elts + ): + return None + for item in value.elts: + if isinstance(item, ast.Constant) and item.value: + topics[str(item.value)] = None + return list(topics) - if not fragment.is_file(): - return [ - f"Agent '{name}' ships no settings of its own: its declaration is in " - f"{source.parent.relative_to(project_dir).as_posix()}/ and an agent's settings.toml is read from there. " - "Every key it reads will come from the group's own settings file, where it is shared with the other agents" - ] - settings = _load_settings(fragment) - if settings is None: - return [] +def _bus(settings: ProcessSettings) -> str: + """``event_bus`` as ``AppBuilder`` reads it: the process's value, trimmed and lower-cased.""" + return str(settings.root_view().get("event_bus", "") or "").strip().lower() - scoped = sorted(key for key in PROCESS_SCOPE_KEYS if _declares(settings, key)) - if not scoped: - return [] - return [ - f"Agent '{name}' declares the process-scope key(s) {', '.join(scoped)} in " - f"{fragment.relative_to(project_dir).as_posix()}. One process binds one port, speaks one event bus and loads " - "one environment, so these are dropped with a warning when this agent's settings are merged under its own " - "scope. Move them to the group's settings file" - ] +def _mode(view: SettingsView) -> str: + return normalise_scheduler_mode(view.get("scheduler_mode")) -def _scheduler_findings(project_dir: Path) -> tuple[list[str], list[str]]: - """Report a scheduler that has not said how it is fired, or that nothing fires. - ``scheduler_mode`` has no default and fails at ``build()`` when a scheduler is registered - without it, so that half is only reported earlier here. The half that fails *nowhere* is the - reason this check exists: ``"event"`` mode starts no timer and waits for a tick that an - external ``CronJob`` must publish, and nothing in this repository generates one -- so a - project can be correct in every mechanical respect and simply never run. - """ - settings = _load_settings(project_dir / SETTINGS_FILE) or {} - return scheduler_findings(project_dir, mode_sources=[settings], bus_sources=[settings], where=SETTINGS_FILE) +def consumes_events(agent_dir: Path, view: SettingsView) -> bool: + """Whether the agent has an event handler: one of its own, or an event-mode scheduler's tick handler.""" + return has_handlers(agent_dir) or (bool(scheduler_modules(agent_dir)) and _mode(view) == SCHEDULER_MODE_EVENT) -def scheduler_findings( - agent_dir: Path, *, mode_sources: list[dict[str, Any]], bus_sources: list[dict[str, Any]], where: str, agent: str = "" -) -> tuple[list[str], list[str]]: - """The scheduler checks, on the runtime's own terms (S27); shared by the single and the group command. +def scheduler_findings(agent_dir: Path, *, view: SettingsView, settings: ProcessSettings, where: str, agent: str = "") -> Findings: + """The scheduler checks, on the runtime's own terms; shared by the single and the group command. - ``scheduler_mode`` is read from ``mode_sources`` in order (an agent's file before the image's) - and ``event_bus`` from ``bus_sources`` (the process's file: it is a process-scope key), each - with an environment override winning, as at runtime. The mode is normalised like the runtime - normalises it, and an event-mode transport must be one that delivers a tick. + ``scheduler_mode`` has no default and fails at ``build()`` when a scheduler is registered + without it. The half that fails *nowhere* is the reason this check exists: ``"event"`` mode + starts no timer and waits for a tick that an external ``CronJob`` must publish, and nothing in + this repository generates one. Each literal crontab is checked with ``validate_crontab`` in + the resolved mode, and ``scheduler_timezone`` as the in-process timer reads it. Args: agent_dir: The directory whose ``src/schedulers`` is looked at. - mode_sources: Parsed settings files to read ``scheduler_mode`` from, first wins. - bus_sources: Parsed settings files to read ``event_bus`` from, first wins. + view: What this namespace reads; ``scheduler_mode`` comes from here. + settings: The process's settings; ``event_bus`` is a process key. where: The file(s) named in a message. - agent: The agent's name in a group, for its scoped environment override and the messages. + agent: The agent's name in a group, for the messages. """ - schedulers = _scheduler_modules(agent_dir) + schedulers = scheduler_modules(agent_dir) if not schedulers: - return [], [] - prefix = _envvar_prefix([*mode_sources, *bus_sources]) + return [], [], [] named = f"Agent '{agent}': " if agent else "" - raw_mode = _env_value(prefix, "scheduler_mode", agent) - if raw_mode is None: - raw_mode = _first_value(mode_sources, "scheduler_mode") + raw_mode = view.get("scheduler_mode") mode = normalise_scheduler_mode(raw_mode) - if not mode: - return [ - f"{named}{len(schedulers)} scheduler(s) under src/schedulers/ and no 'scheduler_mode' in {where} or the " - f"environment. It has no default, because neither value is safe to inherit, so build() fails: set " - f"'{SCHEDULER_MODE_IN_PROCESS}' to run a timer in the process (needs .with_cache(), or every replica runs " - f"every tick) or '{SCHEDULER_MODE_EVENT}' to take the tick as an event (needs 'event_bus', and something " - "publishing it)" - ], [] - + return ( + [ + f"{named}{len(schedulers)} scheduler(s) under src/schedulers/ and no 'scheduler_mode' in {where} or the " + f"environment for '{settings.environment}'. It has no default, because neither value is safe to inherit, " + f"so build() fails: set '{SCHEDULER_MODE_IN_PROCESS}' to run a timer in the process (needs .with_cache(), " + f"and a Redis cache once there is more than one replica) or '{SCHEDULER_MODE_EVENT}' to take the tick as an " + "event (needs 'event_bus', and something publishing it)" + ], + [], + [], + ) if mode not in SCHEDULER_MODES: - return [f"{named}'scheduler_mode' is {raw_mode!r}; it must be one of {', '.join(SCHEDULER_MODES)}"], [] + return [f"{named}'scheduler_mode' is {raw_mode!r}; it must be one of {', '.join(SCHEDULER_MODES)}"], [], [] issues: list[str] = [] notices: list[str] = [] + for path in schedulers: + for crontab in declared_crontabs(path): + try: + validate_crontab(crontab, mode) + except ValueError as exc: + issues.append(f"{named}{path.relative_to(agent_dir).as_posix()}: {exc}") + if mode == SCHEDULER_MODE_EVENT: - # A notice, not an issue: nothing here can tell whether a CronJob exists, and the thing - # that would know -- the deployment -- is outside this project. The framework cannot - # report it either, which is exactly why it is said here. + # A notice, not an issue: nothing here can tell whether a CronJob exists. notices.append( "\n".join( [ - f"'scheduler_mode' is '{SCHEDULER_MODE_EVENT}', so no timer runs in this process: each tick", + f"{named}'scheduler_mode' is '{SCHEDULER_MODE_EVENT}', so no timer runs in this process: each tick", " arrives as an event on '.scheduler.', published by an external", " CronJob. Nothing in this project generates that CronJob, and a scheduler waiting for a", " tick nobody publishes reports itself healthy and never runs. Confirm one exists, on the", @@ -470,89 +675,239 @@ def scheduler_findings( ] ) ) - bus = _env_value(prefix, "event_bus") - if bus is None: - bus = _first_value(bus_sources, "event_bus") - if bus is None: - # A notice: event_bus is a process-scope key, so it may well be set where this command - # does not look -- the group's settings, the deployment's environment. + bus = _bus(settings) + if not bus: + # A notice: event_bus is a process key, and the deployment's environment may set it. notices.append( - f"{named}'scheduler_mode' is '{SCHEDULER_MODE_EVENT}' and no 'event_bus' is set in {where} or the " - "environment. The tick arrives as an event, so startup fails unless the process sets one of " - "'dapr' or 'nats'." + f"{named}'scheduler_mode' is '{SCHEDULER_MODE_EVENT}' and no 'event_bus' is set for " + f"'{settings.environment}' in {where} or the environment. The tick arrives as an event, so startup " + "fails unless the process sets one of 'dapr' or 'nats'." ) elif not delivers_ticks(bus): - # This one *does* fail at startup -- the tick is an ordinary event, so without a - # transport that carries topics there is nothing to subscribe to. issues.append( f"{named}'scheduler_mode' is '{SCHEDULER_MODE_EVENT}' and 'event_bus' is {bus!r}, which cannot deliver " "a tick: the tick is an event on a topic, so it needs 'dapr' or 'nats'. Wiring the scheduler fails at " "startup" ) - elif not _main_declares_a_cache(agent_dir): + return issues, [], notices + + # In process: the timer reads scheduler_timezone, as SchedulerBase reads it at startup. + timezone = str(view.get("scheduler_timezone", "") or "").strip() + if timezone: + try: + ZoneInfo(timezone) + except (ZoneInfoNotFoundError, ValueError): + issues.append( + f"{named}'scheduler_timezone' is {timezone!r}, which is not an IANA timezone name (such as " + "'Europe/Berlin' or 'UTC'). Every in-process scheduler fails to start" + ) + if not main_declares_a_cache(agent_dir): notices.append( "\n".join( [ - f"'scheduler_mode' is '{SCHEDULER_MODE_IN_PROCESS}' and src/main.py declares no cache. Each tick is", - " claimed in the agent's own cache so that one replica runs it; with no cache to claim in,", - " every replica runs every tick. Add .with_cache() unless this runs as a single replica.", + f"{named}'scheduler_mode' is '{SCHEDULER_MODE_IN_PROCESS}' and src/main.py declares no cache.", + " Each tick is claimed in the agent's own cache; with no cache to claim in,", + ' every replica runs every tick. Add .with_cache() -- with cache.backend = "redis"', + " once there is more than one replica -- unless this runs as a single replica.", ] ) ) - return issues, notices + else: + notice = _disk_claim_notice(view, named, "each in-process scheduler tick") + if notice: + notices.append(notice) + return issues, [], notices -def _scheduler_modules(project_dir: Path) -> list[Path]: - """Return the scheduler modules this project defines.""" - schedulers_dir = project_dir / "src" / "schedulers" - if not schedulers_dir.is_dir(): - return [] - return [path for path in sorted(schedulers_dir.glob("*.py")) if path.name != "__init__.py"] +def _disk_claim_notice(view: SettingsView, named: str, what: str) -> str | None: + """Say that a claim on a disk cache holds within one process, when the cache is not Redis.""" + backend = str(view.get("cache.backend", "disk") or "disk").strip().lower() + if backend == "redis": + return None + return "\n".join( + [ + f"{named}The cache backend is {backend!r}, and {what} is claimed in it. A disk cache's claim", + " holds within one process only: replicas sharing its directory can each win the same claim.", + ' Set cache.backend = "redis" before running more than one replica.', + ] + ) -def _main_declares_a_cache(project_dir: Path) -> bool: - """Report whether the declaration registers a cache for the tick claim to use.""" - main_file = project_dir / "src" / "main.py" - return main_file.is_file() and ".with_cache(" in main_file.read_text(encoding="utf-8") +def dedup_findings(agent_dir: Path, *, view: SettingsView, settings: ProcessSettings, agent: str = "") -> Findings: + """The dedup policy a handler chain resolves at startup, and the warnings it logs. + The rules of ``HandlerChain._resolve_idempotency_policy`` and ``_warn_without_a_heartbeat``, + in their own words. Neither is public, and both live in the runtime, so they are restated here + and pinned by tests; the boolean is read with the runtime's ``parse_bool``. + """ + if not consumes_events(agent_dir, view): + return [], [], [] + named = f"Agent '{agent}': " if agent else "" + try: + enabled = parse_bool(view.get("idempotency_enabled", False), "idempotency_enabled") + except ValueError as exc: + return [f"{named}{exc}"], [], [] + if not enabled: + return [], [], [] + + issues: list[str] = [] + raw_ttl = view.get("idempotency_ttl") + if raw_ttl is None: + issues.append( + f"{named}'idempotency_enabled' is true but 'idempotency_ttl' is not set. It is the number of seconds a " + "processed event is remembered, and it must outlast the broker's redelivery window ('nats_ack_wait' * " + "'nats_max_deliver' on JetStream). Startup fails" + ) + else: + try: + ttl = int(raw_ttl) + except (TypeError, ValueError): + issues.append(f"{named}Config key 'idempotency_ttl' must be an integer number of seconds, got {raw_ttl!r}.") + else: + if ttl <= 0: + issues.append(f"{named}'idempotency_ttl' must be greater than 0, got {ttl}. It is the dedup window, in seconds.") + if not main_declares_a_cache(agent_dir): + issues.append( + f"{named}'idempotency_enabled' is true but src/main.py declares no cache, so there is nowhere to record " + "the events already processed. Add '.with_cache()' to the AppBuilder chain. Startup fails" + ) + + warnings: list[str] = [] + bus = _bus(settings) + label = agent or "" + if bus == "nats" and view.get("nats_heartbeat_enabled", True) is False: + warnings.append( + f"Agent '{label}' deduplicates events with 'nats_heartbeat_enabled = false': a run that outlasts ack_wait " + "is redelivered while it runs, the redelivery is skipped as a duplicate and acknowledged, and if the first " + "run then fails the event is lost. Keep the heartbeat on, or keep runs well under ack_wait." + ) + elif bus == "dapr": + warnings.append( + f"Agent '{label}' deduplicates events under Dapr, which has no heartbeat: a run that outlasts the sidecar's " + "app-call timeout is delivered again while it runs, that delivery is skipped as a duplicate, and if the " + "first run then fails the event is lost. Keep runs well under that timeout." + ) + + notices: list[str] = [] + if main_declares_a_cache(agent_dir): + notice = _disk_claim_notice(view, named, "each event's dedup marker") + if notice: + notices.append(notice) + return issues, warnings, notices -def _module_file(project_dir: Path, module_path: str) -> Path | None: - """Resolve a dotted module path to the file that defines it, or ``None``.""" - relative = Path(*module_path.split(".")) - for candidate in (project_dir / relative.with_suffix(".py"), project_dir / relative / "__init__.py"): - if candidate.is_file(): - return candidate - return None +def transport_findings(agent_dir: Path, *, view: SettingsView, settings: ProcessSettings, agent: str = "") -> Findings: + """What wiring this agent's transport refuses or warns about at startup. -def _nats_findings(project_dir: Path) -> list[str]: + Handlers with no usable ``event_bus`` (a WARNING from ``AppBuilder``); and, under NATS, for an + agent that has a client: an unset ``nats_url`` outside development, a non-boolean + ``nats_heartbeat_enabled``, one ``nats_durable_name`` for several topics and -- at the root + namespace, where the queue group is not the agent's name -- a queue group that cannot appear + in a subject (checked with the runtime's ``validate_subject_segment``). + """ + named = f"Agent '{agent}': " if agent else "" + bus = _bus(settings) + warnings: list[str] = [] + if has_handlers(agent_dir) and bus not in EVENT_BUSES: + where = f"Namespace '{agent}' has" if agent else "This project has" + warnings.append( + f"{where} event handlers registered but no valid event_bus is configured for '{settings.environment}' " + f"({', '.join(repr(name) for name in EVENT_BUSES)}). Event handling will be disabled -- the runtime only " + "logs this." + ) + if bus != "nats": + return [], warnings, [] + + consumes = consumes_events(agent_dir, view) + try: + publishes = parse_bool(view.get("event_publishing_enabled", False) or False, "event_publishing_enabled") + except ValueError: + publishes = True + if not (consumes or publishes): + return [], warnings, [] + + issues: list[str] = [] + environment = str(view.get("app_environment", "development")) + if not str(view.get("nats_url", "") or "").strip() and environment.lower() != "development": + issues.append( + f"{named}'event_bus' is 'nats' but 'nats_url' is not set (app_environment is {environment!r}). Outside " + "development there is no default: localhost is rarely right in a container, and a client pointed at it " + f"retries forever while the pod looks healthy. Set 'nats_url' in the settings or as " + f"{settings.override_variable_prefix}NATS_URL." + ) + heartbeat = view.get("nats_heartbeat_enabled", True) + if not isinstance(heartbeat, bool): + issues.append(f"{named}'nats_heartbeat_enabled' must be true or false, got {heartbeat!r}.") + if not consumes: + return issues, warnings, [] + + if not agent: + # A namespaced client's queue group is its namespace; only the root reads these keys. + for key in ("nats_queue_group", "app_name"): + name = str(view.get(key, "") or "").strip() + if not name: + continue + try: + validate_subject_segment(name, source=f"The queue group (from '{key}')", subject=f"{name}.dead-letter") + except ValueError as exc: + issues.append(str(exc)) + break + else: + issues.append( + "NATS subscriptions require a queue group: set 'nats_queue_group' or 'app_name'. Without one every " + "replica processes every message." + ) + + durable = str(view.get("nats_durable_name", "") or "").strip() + if durable and view.get("nats_use_jetstream", False) and not view.get("nats_connection_source"): + topics = literal_topics(agent_dir) + subscriptions = view.get("nats_subscriptions", []) + if topics is not None: + declared = set(topics) | ({str(topic) for topic in subscriptions if topic} if isinstance(subscriptions, list) else set()) + count = len(declared) + (len(scheduler_modules(agent_dir)) if _mode(view) == SCHEDULER_MODE_EVENT else 0) + if count > 1: + issues.append( + f"{named}'nats_durable_name' is set to '{durable}' but {count} topics are subscribed. A JetStream " + "durable filters one subject, so one name cannot serve them all. Remove the key to derive a " + "durable per topic." + ) + return issues, warnings, [] + + +def process_findings(settings: ProcessSettings) -> Findings: + """Checks on keys only the process reads: ``event_loop_debug``, read with the runtime's ``parse_bool``.""" + try: + parse_bool(settings.root_view().get("event_loop_debug", False), "event_loop_debug") + except ValueError as exc: + return [f"{exc} Startup fails"], [], [] + return [], [], [] + + +def nats_value_findings(project_dir: Path, view: SettingsView) -> list[str]: """Check the NATS delivery keys that would otherwise fail only at startup. The same parsers the client uses (``RunLimit.parse``, the readiness modes), so this command and startup cannot disagree. ``nats_connection_source`` is checked for its form and for its module - being found -- without calling the factory: what the source returns (a binding without a - stream, for example) depends on the deployment's own data and is only known at startup. + being found -- without calling the factory: what the source returns depends on the + deployment's own data and is only known at startup. """ - settings = _load_settings(project_dir / SETTINGS_FILE) - if settings is None: - return [] issues: list[str] = [] for key, minimum in (("nats_max_concurrent_runs", 1), ("nats_extra_runs_per_process", 0)): try: - RunLimit.parse(key, _value_of(settings, key), minimum=minimum) + RunLimit.parse(key, view.get(key), minimum=minimum) except ValueError as exc: issues.append(str(exc)) - timeout = _value_of(settings, "nats_handler_timeout") + timeout = view.get("nats_handler_timeout") if timeout is not None and timeout != "": if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or timeout <= 0: issues.append(f"'nats_handler_timeout' must be a number of seconds above 0, got {timeout!r}. Unset it for no limit.") - readiness = _value_of(settings, "nats_connections_readiness") + readiness = view.get("nats_connections_readiness") if readiness is not None and str(readiness).strip().lower() not in CONNECTIONS_READINESS_MODES: issues.append(f"'nats_connections_readiness' must be one of {', '.join(CONNECTIONS_READINESS_MODES)}, got {readiness!r}.") - unclaimed = _value_of(settings, "nats_unclaimed_subjects") + unclaimed = view.get("nats_unclaimed_subjects") if unclaimed is not None and str(unclaimed).strip().lower() not in ("fail", "default_connection"): issues.append(f"'nats_unclaimed_subjects' must be 'fail' or 'default_connection', got {unclaimed!r}.") - source = _value_of(settings, "nats_connection_source") + source = view.get("nats_connection_source") if source: issue = _connection_source_issue(project_dir, str(source)) if issue: @@ -560,6 +915,14 @@ def _nats_findings(project_dir: Path) -> list[str]: return issues +def _nats_findings(project_dir: Path, environment: str | None = None) -> list[str]: + """:func:`nats_value_findings` for a standalone project's own settings.""" + settings = ProcessSettings.load(project_dir, environment) + if not settings.readable: + return [] + return nats_value_findings(project_dir, settings.root_view()) + + def _connection_source_issue(project_dir: Path, path: str) -> str | None: """Report a ``nats_connection_source`` that cannot be right, or ``None``. @@ -582,69 +945,3 @@ def _connection_source_issue(project_dir: Path, path: str) -> str | None: if not found: return f"'nats_connection_source': no module '{module_path}' on the project's path; startup would fail." return None - - -def _load_settings(settings_file: Path) -> dict[str, Any] | None: - """Parse a settings file, or ``None`` when there is nothing readable to parse. - - A file that cannot be read is reported by its own check; guessing at a key from an - unparseable file would be worse than staying quiet. - """ - if not settings_file.is_file(): - return None - try: - with settings_file.open("rb") as handle: - return tomllib.load(handle) - except (OSError, tomllib.TOMLDecodeError) as exc: - logger.debug("Could not read %s: %s", settings_file, exc) - return None - - -def _declares(settings: dict[str, Any], key: str) -> bool: - """Report whether ``key`` appears at the top level or in any Dynaconf environment.""" - if key in settings: - return True - return any(isinstance(value, dict) and key in value for value in settings.values()) - - -def _first_value(sources: list[dict[str, Any]], key: str) -> Any | None: - """``key``'s value from the first of ``sources`` that sets it (see :func:`_value_of`).""" - for settings in sources: - value = _value_of(settings, key) - if value is not None: - return value - return None - - -def _envvar_prefix(sources: list[dict[str, Any]]) -> str: - """The environment prefix the process reads overrides through: ``envvar_prefix``, else ``DYNACONF``.""" - configured = _first_value(sources, "envvar_prefix") - return str(configured).strip() if configured else "DYNACONF" - - -def _env_value(prefix: str, key: str, agent: str = "") -> str | None: - """An environment override of ``key``, as the runtime reads it: the agent's scoped one first, then the root's. - - Read so that a value the deployment supplies is not reported as missing (S27). - """ - names = ([f"{prefix}_{agent.upper()}__{key.upper()}"] if agent else []) + [f"{prefix}_{key.upper()}"] - for name in names: - value = os.environ.get(name) - if value is not None and value.strip(): - return value - return None - - -def _value_of(settings: dict[str, Any], key: str) -> Any | None: - """Return ``key``'s value from the top level, or from the first environment that sets it. - - Which environment is in force is a runtime decision this command cannot make, so a key set - in any of them counts as set. That is the right answer for the checks here, which ask whether - the author has *decided* something, not what today's value is. - """ - if key in settings: - return settings[key] - for value in settings.values(): - if isinstance(value, dict) and key in value: - return value[key] - return None diff --git a/src/blueprint/agent_generator/cli/commands/validate_group.py b/src/blueprint/agent_generator/cli/commands/validate_group.py index a2c1aa30..54f9720c 100644 --- a/src/blueprint/agent_generator/cli/commands/validate_group.py +++ b/src/blueprint/agent_generator/cli/commands/validate_group.py @@ -1,4 +1,4 @@ -"""Validate an image: the agent map, and every agent directory it points at. +"""Validate an image: the agent map, the group file, and every agent directory the map points at. ``asbs validate`` checks one agent. This checks the thing that contains agents -- a different question, which is why it is a different mode rather than a heuristic about what the directory @@ -9,21 +9,54 @@ from, an agent whose map entry points at a directory that has since been renamed, process-wide keys set under an agent where nothing consults them. None of those stop a pod from starting and passing its probes, which is exactly what makes them expensive to find later. + +Where the runtime has the rule as a public function, this runs that function: the group file is +resolved by ``GroupConfig.resolve_at`` against a stub environment, an agent's settings are layered +by ``layer_settings_document``, crontabs go through ``validate_crontab``. """ import ast +import importlib.util +import logging import os +import re import sys import tomllib from argparse import Namespace +from dataclasses import dataclass from pathlib import Path from typing import Any +import yaml + +from blueprint.agents import group_config as group_config_module from blueprint.agents.component.namespace import validate_namespace -from blueprint.agents.config import PROCESS_SCOPE_KEYS +from blueprint.agents.config.config import AGENT_REFUSED_KEYS +from blueprint.agents.group_config import ( + AGENTS_ENV, + CRITICAL_AGENTS_ENV, + DEFAULT_GROUP_CONFIG, + GROUP_CONFIG_ENV, + GROUP_ENV, + GroupConfig, + GroupConfigError, +) from blueprint.agents.layout import check_agent_layout from ..utils.cancellation_check import swallowed_cancellation_warning, swallowed_cancellations +from .validate import ( + SECRETS_FILE, + SETTINGS_FILE, + Findings, + ProcessSettings, + SettingsView, + dedup_findings, + literal_topics, + nats_value_findings, + process_findings, + scheduler_findings, + transport_findings, +) AGENT_MAP_FILE = "agents.toml" AGENT_MAP_ENV = "BLUEPRINT_AGENT_MAP" @@ -32,6 +65,15 @@ _IMPORTS_SHOWN = 5 +@dataclass(frozen=True) +class _CheckedAgent: + """An agent whose entry resolved, with what it reads -- for the checks that span agents.""" + + name: str + root: Path + view: SettingsView + + def run(args: Namespace) -> None: """Execute ``asbs validate --group``. @@ -48,9 +90,17 @@ def run(args: Namespace) -> None: print(f"Validating Blueprint Agents image: {image_root}") if agent_map.parent != image_root: print(f"Agent map: {agent_map}") + environment = getattr(args, "environment", None) + print(f"Environment: {ProcessSettings.load(image_root, environment).environment} (choose another with --environment)") print() - issues, warnings, notices = _findings(image_root, agent_map) + issues, warnings, notices = image_findings( + image_root, + agent_map, + environment=environment, + group_config=getattr(args, "group_config", None), + group_name=getattr(args, "group_name", None), + ) _report(issues, warnings, notices) sys.exit(1 if issues else 0) @@ -58,12 +108,8 @@ def run(args: Namespace) -> None: def _agent_map_path(image_root: Path, configured: str | None) -> Path: """Return where the agent map is, which is not necessarily inside the directory being checked. - The map and the image root answer different questions, and conflating them is what made this - command disagree with the runtime. The runtime resolves every agent ``root`` against the image - root -- the directory the process runs in -- while the map itself may sit anywhere, because - ``BLUEPRINT_AGENT_MAP`` relocates it. A repository keeping its map in ``deploy/`` and its - agents at the top therefore runs, and used to be reported here as an image that would not - start. + The runtime resolves every agent ``root`` against the image root -- the directory the process + runs in -- while the map itself may sit anywhere, because ``BLUEPRINT_AGENT_MAP`` relocates it. Args: image_root: The directory being validated, which agent roots resolve against. @@ -80,17 +126,29 @@ def _agent_map_path(image_root: Path, configured: str | None) -> Path: return path if path.is_absolute() else image_root / path -def _findings(image_root: Path, agent_map: Path) -> tuple[list[str], list[str], list[str]]: +def image_findings( + image_root: Path, + agent_map: Path, + *, + environment: str | None = None, + group_config: str | None = None, + group_name: str | None = None, +) -> Findings: """Return issues, warnings and notices for the image at ``image_root``. Args: image_root: The directory agent roots resolve against, as at runtime. agent_map: The map to read, which may be outside ``image_root``. + environment: The environment to check; see ``ProcessSettings.load``. + group_config: ``--group-config``: the group file, if not ``BLUEPRINT_GROUP_CONFIG`` or the default. + group_name: ``--group-name``: check only this group of the group file. """ issues: list[str] = [] warnings: list[str] = [] notices: list[str] = [] + settings = ProcessSettings.load(image_root, environment) + if not agent_map.is_file(): issues.append( f"No agent map at {agent_map}, so this directory is not an image. Run 'asbs setup --group' to create " @@ -106,27 +164,64 @@ def _findings(image_root: Path, agent_map: Path) -> tuple[list[str], list[str], declared = document.get("agents") if not isinstance(declared, dict) or not declared: - warnings.append( - f"{AGENT_MAP_FILE} declares no agents. That is what 'asbs setup --group' writes, and an image with no " - "agents cannot start -- add an entry per agent before deploying it." + issues.append( + f"Agent map {agent_map} declares no [agents.] entries, so this image contains no agents and the " + "process refuses to start. 'asbs setup --group' writes it empty: add an entry per agent before deploying." ) return issues, warnings, notices print(f"[ok] {AGENT_MAP_FILE} declares {len(declared)} agent(s): {', '.join(str(name) for name in declared)}") print() + issues.extend(settings.problems) + warnings.extend(settings.unread_key_warnings()) + claimed: dict[Path, str] = {} + checked: list[_CheckedAgent] = [] + map_valid = True for name, entry in declared.items(): - agent_issues, agent_warnings, agent_notices = _agent_findings(image_root, str(name), entry, claimed) + agent_issues, agent_warnings, agent_notices, agent = _agent_findings(image_root, str(name), entry, claimed, settings) issues.extend(agent_issues) warnings.extend(agent_warnings) notices.extend(agent_notices) + if agent is None: + map_valid = False + else: + checked.append(agent) + + if settings.readable: + root_issues = nats_value_findings(image_root, settings.root_view()) + issues.extend(root_issues) + for agent in checked: + issues.extend( + f"Agent '{agent.name}': {issue}" for issue in nats_value_findings(agent.root, agent.view) if issue not in root_issues + ) + found = process_findings(settings) + issues.extend(found[0]) + warnings.extend(_shared_topic_warnings(settings, checked)) + + # The runtime reads the map before the group, and stops at its first defect; those are all + # reported above, so the group is resolved only once the map is one the runtime accepts. + if map_valid: + group_issues, group_warnings, group_notices = group_findings( + image_root, agent_map, group_config=group_config, group_name=group_name + ) + issues.extend(group_issues) + warnings.extend(group_warnings) + notices.extend(group_notices) return issues, warnings, notices -def _agent_findings(image_root: Path, name: str, entry: Any, claimed: dict[Path, str]) -> tuple[list[str], list[str], list[str]]: - """Check one map entry and the directory it points at.""" +def _agent_findings( + image_root: Path, name: str, entry: Any, claimed: dict[Path, str], settings: ProcessSettings +) -> tuple[list[str], list[str], list[str], _CheckedAgent | None]: + """Check one map entry and the directory it points at. + + Returns: + Issues, warnings, notices, and the agent when its entry resolves (``None`` when the + runtime's map reading would refuse it). + """ issues: list[str] = [] warnings: list[str] = [] notices: list[str] = [] @@ -135,14 +230,15 @@ def _agent_findings(image_root: Path, name: str, entry: Any, claimed: dict[Path, validate_namespace(name) except ValueError as exc: issues.append(f"Agent '{name}' in {AGENT_MAP_FILE} cannot be a namespace: {exc}") - return issues, warnings, notices + return issues, warnings, notices, None if not isinstance(entry, dict): issues.append(f"Agent '{name}' in {AGENT_MAP_FILE} is not a table. Write it as [agents.{name}] with root and module.") - return issues, warnings, notices + return issues, warnings, notices, None module = entry.get("module") - if not module or not isinstance(module, str) or ":" not in module: + module_ok = bool(module) and isinstance(module, str) and ":" in module + if not module_ok: issues.append(f"Agent '{name}' in {AGENT_MAP_FILE} has no usable 'module'. Write it as module = \"package.module:attribute\"") declared_root = entry.get("root") @@ -151,23 +247,26 @@ def _agent_findings(image_root: Path, name: str, entry: Any, claimed: dict[Path, f"Agent '{name}' in {AGENT_MAP_FILE} has no 'root', so there is nowhere to read its settings and prompts " 'from. Write it as root = "relative/path/to/the/agent", relative to the image root.' ) - return issues, warnings, notices + return issues, warnings, notices, None root = (image_root / declared_root).resolve() if not root.is_relative_to(image_root): issues.append(f"Agent '{name}' has root '{declared_root}', which is outside the image.") - return issues, warnings, notices + return issues, warnings, notices, None if not root.is_dir(): issues.append( f"Agent '{name}' has root '{declared_root}', and {root} is not a directory. Either the agent moved and " f"{AGENT_MAP_FILE} did not, or the path is a typo." ) - return issues, warnings, notices + return issues, warnings, notices, None if root in claimed: issues.append(f"Agents '{claimed[root]}' and '{name}' share the root {declared_root}; they would read each other's files.") - return issues, warnings, notices + return issues, warnings, notices, None claimed[root] = name + if module_ok: + issues.extend(_declaration_issues(image_root, name, str(module))) + for misplaced in check_agent_layout(root): issues.append(misplaced.describe(name)) @@ -180,29 +279,40 @@ def _agent_findings(image_root: Path, name: str, entry: Any, claimed: dict[Path, if swallowed: warnings.append(swallowed_cancellation_warning(name, swallowed)) - settings = root / "settings.toml" - if settings.is_file(): - print(f"[ok] {name}: settings from {declared_root}/settings.toml") - issues.extend(_self_scoped_issues(name, settings)) - warnings.extend(_process_key_warnings(name, settings)) - else: - print(f"[--] {name}: no settings.toml of its own; it reads the image's") - - # The scheduler checks the single-agent command runs, on the group's terms (S27): the agent's - # scheduler_mode before the image's, and event_bus from the image, where a process key lives. - from .validate import scheduler_findings # here, not at the top: validate imports this module - - agent_settings = _load(settings) - image_settings = _load(image_root / "settings.toml") - scheduler_issues, scheduler_notices = scheduler_findings( - root, - mode_sources=[agent_settings, image_settings], - bus_sources=[image_settings], - where=f"{declared_root}/settings.toml or the image's settings.toml", - agent=name, - ) - issues.extend(scheduler_issues) - notices.extend(scheduler_notices) + # The agent's own files, as AgentGroup.from_config collects them: beside its root's src. An + # agent whose root is the image root has no files of its own -- its settings are the process's. + fragments: list[dict[str, Any]] = [] + if root != image_root: + settings_file = root / SETTINGS_FILE + if settings_file.is_file(): + print(f"[ok] {name}: settings from {declared_root}/{SETTINGS_FILE}") + else: + print(f"[--] {name}: no {SETTINGS_FILE} of its own; it reads the image's") + for path in (root / SECRETS_FILE, settings_file): + if not path.is_file(): + continue + try: + document = tomllib.loads(path.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError) as exc: + issues.append(f"Agent '{name}' has a {path.name} that could not be read, and the merge refuses it at startup: {exc}") + continue + secret = path.name == SECRETS_FILE + issues.extend(_self_scoped_issues(name, path.name, document)) + warnings.extend(_process_key_warnings(name, path.name, document, secret=secret)) + fragments.append(document) + issues.extend(_root_key_issues(name, settings, fragments)) + + view = settings.agent_view(name, fragments) + if settings.readable: + where = f"{declared_root}/{SETTINGS_FILE} or the image's {SETTINGS_FILE}" + for found in ( + scheduler_findings(root, view=view, settings=settings, where=where, agent=name), + dedup_findings(root, view=view, settings=settings, agent=name), + transport_findings(root, view=view, settings=settings, agent=name), + ): + issues.extend(found[0]) + warnings.extend(found[1]) + notices.extend(found[2]) if root != image_root and root.name != name: notices.append( @@ -211,32 +321,67 @@ def _agent_findings(image_root: Path, name: str, entry: Any, claimed: dict[Path, "served on its own, at the root namespace." ) - return issues, warnings, notices + return issues, warnings, notices, _CheckedAgent(name, root, view) -def _load(settings: Path) -> dict[str, Any]: - """A parsed settings file, or ``{}`` when it is missing or unreadable (its own check reports that).""" - if not settings.is_file(): - return {} +def _declaration_issues(image_root: Path, name: str, module: str) -> list[str]: + """Report an agent whose declaration cannot be found, or is not assigned where the map says. + + Checked against the file rather than by importing it. A module that is not a file of the + image is fine when its top-level package is installed elsewhere -- an agent installed as a + distribution imports from site-packages while its files sit in the image -- and that is + looked up without importing anything. + """ + module_path, _, attribute = module.partition(":") + source = _module_file(image_root, module_path) + if source is None: + if _installed_elsewhere(image_root, module_path): + return [] + return [ + f"Agent '{name}' points at '{module_path}', which is not a module in this image (looked for it under " + f"{image_root}). Either the agent map is out of date, or the declaration moved and the map did not; a " + "critical agent then stops the process" + ] + text = source.read_text(encoding="utf-8") + if not re.search(rf"^{re.escape(attribute)}\s*[:=]", text, re.MULTILINE): + return [ + f"Agent '{name}' points at '{module}', but {source.relative_to(image_root).as_posix()} assigns no " + f"'{attribute}'. That is the AppBuilder the host builds; without it the process stops before binding " + "its port" + ] + return [] + + +def _module_file(image_root: Path, module_path: str) -> Path | None: + """Resolve a dotted module path to the file in the image that defines it, or ``None``.""" + relative = Path(*module_path.split(".")) + for candidate in (image_root / relative.with_suffix(".py"), image_root / relative / "__init__.py"): + if candidate.is_file(): + return candidate + return None + + +def _installed_elsewhere(image_root: Path, module_path: str) -> bool: + """Whether the module's top-level package is importable from outside the image (found, never imported).""" + top = module_path.split(".")[0] try: - return tomllib.loads(settings.read_text(encoding="utf-8")) - except (OSError, tomllib.TOMLDecodeError): - return {} + spec = importlib.util.find_spec(top) + except (ImportError, ValueError): + return False + if spec is None: + return False + locations = list(spec.submodule_search_locations or []) or ([spec.origin] if spec.origin else []) + return bool(locations) and not any(Path(location).resolve().is_relative_to(image_root) for location in locations) -def _self_scoped_issues(name: str, settings: Path) -> list[str]: - """Report an agent settings file that scopes keys under the agent's own name. +def _self_scoped_issues(name: str, file_name: str, document: dict[str, Any]) -> list[str]: + """Report an agent file that scopes keys under the agent's own name. The file becomes that agent's scope when merged, so a ``[default.]`` section in it - nests to ``..*`` and nothing reads those keys. The runtime refuses it; this - says so without starting the process, because the symptom otherwise arrives far from the - cause -- as a missing model name, naming the agent rather than the file. + nests to ``..*`` and nothing reads those keys. The runtime refuses it for the + environment in force; this reports it in any section, because a section that is inactive here + is active in another deployment. """ - try: - document = tomllib.loads(settings.read_text(encoding="utf-8")) - except (OSError, tomllib.TOMLDecodeError): - return [] # reported by the caller's own read - found = [ f"[{section}.{key}]" for section, value in document.items() @@ -248,40 +393,172 @@ def _self_scoped_issues(name: str, settings: Path) -> list[str]: if not found: return [] return [ - f"Agent '{name}' scopes its own settings under its own name ({', '.join(sorted(set(found)))}). That file " - f"becomes the agent's scope when it is merged, so those keys nest as '{name}.{name}.*' and nothing reads " - "them. Write them at the top level or under a plain [default] -- which also works standalone, because a " - "scoped lookup falls back to the root key." + f"Agent '{name}' scopes its own settings under its own name ({', '.join(sorted(set(found)))}) in its " + f"{file_name}. That file becomes the agent's scope when it is merged, so those keys nest as " + f"'{name}.{name}.*' and nothing reads them; the runtime refuses it at startup. Write them at the top level or " + "under a plain [default] -- which also works standalone, because a scoped lookup falls back to the root key." ] -def _process_key_warnings(name: str, settings: Path) -> list[str]: - """Report process-wide keys set in an agent's own settings file. +def _process_key_warnings(name: str, file_name: str, document: dict[str, Any], *, secret: bool) -> list[str]: + """Report the keys the merge drops from an agent's file: process-wide and deployment-identity keys. - They are dropped before the merge at runtime rather than obeyed, so this is the difference - between a key that does nothing and a key somebody believes in. + Reported in any section, which is stricter than the merge (it drops them from the sections + in force), because a section inactive here is active in another deployment. Keys only -- a + secrets file's values are never shown. """ - try: - document = tomllib.loads(settings.read_text(encoding="utf-8")) - except (OSError, tomllib.TOMLDecodeError) as exc: - return [f"Agent '{name}' has a settings.toml that could not be read: {exc}"] - found: set[str] = set() for key, value in document.items(): if isinstance(value, dict): - found.update(str(inner).lower() for inner in value if str(inner).lower() in PROCESS_SCOPE_KEYS) - elif str(key).lower() in PROCESS_SCOPE_KEYS: + found.update(str(inner).lower() for inner in value if str(inner).lower() in AGENT_REFUSED_KEYS) + elif str(key).lower() in AGENT_REFUSED_KEYS: found.add(str(key).lower()) - if not found: return [] + kind = "secrets file" if secret else "settings" return [ - f"Agent '{name}' sets process-wide key(s) in its own settings.toml: {', '.join(sorted(found))}. One process " - "has one of each, so these are dropped before the merge and the image's settings.toml decides. Move them " - "there, or remove them." + f"Agent '{name}' sets process-wide key(s) in its own {file_name}: {', '.join(sorted(found))}. One process " + f"has one of each, so these are dropped from the agent's {kind} before the merge, with a warning, and the " + f"image's {SETTINGS_FILE} decides. Move them there, or remove them." ] +def _root_key_issues(name: str, settings: ProcessSettings, fragments: list[dict[str, Any]]) -> list[str]: + """Report an image key named like the agent that is not a table, which the merge refuses (S12).""" + contributes = any(key for document in fragments for key in settings.layered(document) if str(key).lower() not in AGENT_REFUSED_KEYS) + existing = settings.tree.get(name.lower()) + if not contributes or existing is None or isinstance(existing, dict): + return [] + return [ + f"Agent '{name}' cannot have settings of its own: the image's configuration already uses '{name}' as a key, " + "with a value that is not a section. Merging the agent's file would replace that value for the whole process, " + "so startup fails. Rename the agent or the key." + ] + + +def _shared_topic_warnings(settings: ProcessSettings, checked: list[_CheckedAgent]) -> list[str]: + """Warn about a Dapr topic two agents declare while one of them does not deduplicate (S5). + + What ``DaprEventing`` warns about at startup: there is one delivery for both agents, and so + one answer -- a retry asked for by one redelivers the event to every agent of the topic. Read + from literal ``get_subscribed_topics`` returns only. + """ + if str(settings.root_view().get("event_bus", "") or "").strip().lower() != "dapr": + return [] + sharing: dict[str, list[_CheckedAgent]] = {} + for agent in checked: + for topic in literal_topics(agent.root) or []: + sharing.setdefault(topic, []).append(agent) + warnings = [] + for topic, agents in sharing.items(): + if len(agents) < 2: + continue + repeating = [agent.name for agent in agents if not agent.view.get("idempotency_enabled", False)] + if repeating: + warnings.append( + f"Topic '{topic}' is declared by agents {', '.join(agent.name for agent in agents)}, and Dapr delivers " + f"it once for all of them: a retry asked for by one redelivers it to every one, and {', '.join(repeating)} " + "run it again because 'idempotency_enabled' is off." + ) + return warnings + + +class _Collected(logging.Handler): + """Keeps the WARNING and ERROR records group resolution logs, to report them as warnings.""" + + def __init__(self) -> None: + super().__init__(level=logging.WARNING) + self.messages: list[str] = [] + + def emit(self, record: logging.LogRecord) -> None: + self.messages.append(record.getMessage()) + + +def group_findings(image_root: Path, agent_map: Path, *, group_config: str | None = None, group_name: str | None = None) -> Findings: + """Resolve the group file the way the process does, and report what it refuses. + + The runtime's ``GroupConfig.resolve_at`` runs against a stub environment holding the group + file, the agent map, and whichever of ``BLUEPRINT_GROUP``, ``BLUEPRINT_AGENTS`` and + ``BLUEPRINT_CRITICAL_AGENTS`` this environment sets, so its refusals are reported in its own + words. Without a name, every group of a multi-group file is resolved in turn. With no group + file and nothing in the environment there is nothing to resolve: which agents a process runs + is the deployment's decision, made at container start. + + Args: + image_root: The image root. + agent_map: The agent map, already checked. + group_config: ``--group-config``; else ``BLUEPRINT_GROUP_CONFIG``; else ``./deployment-groups.yaml``. + group_name: ``--group-name``, which wins over ``BLUEPRINT_GROUP``. + """ + configured = (group_config or os.environ.get(GROUP_CONFIG_ENV, "") or "").strip() + group_file = Path(configured) if configured else image_root / DEFAULT_GROUP_CONFIG + if not group_file.is_absolute(): + group_file = image_root / group_file + + environ = {AGENT_MAP_ENV: str(agent_map), GROUP_CONFIG_ENV: str(group_file)} + for variable in (GROUP_ENV, AGENTS_ENV, CRITICAL_AGENTS_ENV): + value = os.environ.get(variable, "").strip() + if value: + environ[variable] = value + if group_name: + environ[GROUP_ENV] = group_name + + named = GROUP_ENV in environ or AGENTS_ENV in environ + if not named and not group_file.is_file(): + return ( + [], + [], + [ + f"No group file at {group_file}, and neither {GROUP_ENV} nor {AGENTS_ENV} is set, so no group was " + "resolved: which agents a process runs is the deployment's decision. Pass --group-config (or set " + f"{GROUP_CONFIG_ENV}) to check the group file a deployment mounts." + ], + ) + + candidates = [environ] + if not named: + names = _group_names(group_file) + if len(names) > 1: + candidates = [{**environ, GROUP_ENV: name} for name in names] + + issues: list[str] = [] + warnings: list[str] = [] + resolver_logger = logging.getLogger(group_config_module.__name__) + for environment in candidates: + collected = _Collected() + resolver_logger.addHandler(collected) + try: + group = GroupConfig.resolve_at(image_root, environ=environment) + except GroupConfigError as exc: + if str(exc) not in issues: + issues.append(str(exc)) + continue + finally: + resolver_logger.removeHandler(collected) + print(f"[ok] group '{group.name}' resolves to: {', '.join(group.agent_names) or 'no agents'}") + warnings.extend(message for message in collected.messages if message not in warnings) + return issues, warnings, [] + + +def _group_names(group_file: Path) -> list[str]: + """The group names a group file declares, in order and without repeats; empty when it cannot be read. + + Only to know which groups to resolve: everything wrong with the file is the runtime's to say. + """ + try: + document = yaml.safe_load(group_file.read_text(encoding="utf-8")) + except (OSError, yaml.YAMLError): + return [] + groups = document.get("groups") if isinstance(document, dict) else None + if not isinstance(groups, list): + return [] + names: dict[str, None] = {} + for entry in groups: + if isinstance(entry, dict) and str(entry.get("name", "") or "").strip(): + names[str(entry["name"]).strip()] = None + return list(names) + + def _absolute_src_import_warnings(name: str, root: Path) -> list[str]: """Report an agent that imports its own code as the top-level package ``src``. @@ -292,11 +569,7 @@ def _absolute_src_import_warnings(name: str, root: Path) -> list[str]: which is why this is reported here rather than left to the log. A warning, not an issue: a critical agent fails loudly by itself, and a non-critical one does - not stop the image starting. The caller skips agents whose ``src`` *is* the image root's, - where the absolute import resolves to the agent's own code. - - Parsed rather than grepped, so an import named in a docstring or a comment is not reported, - and parsed rather than imported, like everything else this command checks. + not stop the image starting. Parsed rather than grepped or imported. """ found: list[str] = [] for path in sorted((root / "src").rglob("*.py")): diff --git a/src/blueprint/agent_generator/cli/main.py b/src/blueprint/agent_generator/cli/main.py index eb2309c5..203d9aa6 100644 --- a/src/blueprint/agent_generator/cli/main.py +++ b/src/blueprint/agent_generator/cli/main.py @@ -182,7 +182,8 @@ def main() -> None: validate_parser.add_argument( "--group", action="store_true", - help="Validate an image rather than a single agent: the agent map, and every agent it points at.", + help="Validate an image rather than a single agent: the agent map, the group file (when there is one), and " + "every agent the map points at.", ) validate_parser.add_argument( "--agent-map", @@ -191,12 +192,34 @@ def main() -> None: "against that directory, as BLUEPRINT_AGENT_MAP does at runtime. Agent roots are unaffected: they resolve " "against the image root either way.", ) + validate_parser.add_argument( + "--environment", + metavar="NAME", + help="The settings environment to check, as the process selects it: [default], then [NAME], then [global]. " + "Default: DYNACONF_APP_ENVIRONMENT, else 'production' -- what both scaffolded Dockerfiles set. A key set " + "only in another environment's section counts as unset.", + ) + validate_parser.add_argument( + "--group-config", + metavar="PATH", + help="With --group: the group file to resolve, if not BLUEPRINT_GROUP_CONFIG or deployment-groups.yaml in the " + "image root. Relative paths resolve against the image root, as at runtime.", + ) + validate_parser.add_argument( + "--group-name", + metavar="NAME", + help="With --group: resolve only this group of the group file (as BLUEPRINT_GROUP does). Default: " + "BLUEPRINT_GROUP, else every group the file declares.", + ) # Dev command dev_parser = subparsers.add_parser( "dev", help="Start development server", - description="Run this project's agents with hot reload, under the namespaces they deploy under", + description="Serve with hot reload. In an image directory (an agents.toml here) the image's agents are " + "hosted under their namespaces, as the group entry point hosts them. In an agent directory the agent is " + "served alone, at the root namespace, as its own Dockerfile serves it -- unless --name asks for the " + "namespace a group image would give it.", ) dev_parser.add_argument( "--name", diff --git a/src/blueprint/agent_generator/docs/guides/cli/validate.md b/src/blueprint/agent_generator/docs/guides/cli/validate.md index d70e2d1c..9bbf9b00 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/validate.md +++ b/src/blueprint/agent_generator/docs/guides/cli/validate.md @@ -1,56 +1,116 @@ # asbs validate -Validate the project structure and configuration. Reads files only -- it never imports the -project -- and reports what it finds in three grades: **issues** (the project will not start, exit -status 1), **warnings** (it will start, and something is missing) and **notices** (a decision the -framework must not make for you). +Check a project -- or, with `--group`, an image -- for what its process would refuse or warn +about at startup, before anything is deployed. It reads and parses files; it does not import or +build the project. The one exception is `nats_connection_source`: finding that module imports its +parent packages, as the import at startup would (the module itself is not executed). + +Findings come in three grades: **issues** (the process will not start, exit status 1), +**warnings** (it starts, and something is ignored or logged as a warning) and **notices** (a +decision the framework must not make for you). ```bash -asbs validate [] +asbs validate [] [--environment NAME] +asbs validate --group [] [--agent-map PATH] [--group-config PATH] [--group-name NAME] [--environment NAME] ``` -## Checks Performed - -Project shape: +## Which settings are checked -- Required directories (`src/`, `tests/`) and files (`settings.toml`, `pyproject.toml`) exist -- `src/main.py` exists and uses `AppBuilder` -- `.secrets.toml.example` and `.secrets.toml` are present -- A `Dockerfile` is present +Settings are read the way the process reads them, for **one environment**: -Group readiness -- what this project must state before it can be hosted beside another agent: +- the target environment is `--environment`, else `DYNACONF_APP_ENVIRONMENT` (or + `_APP_ENVIRONMENT` with a declared `envvar_prefix`), else **`production`** -- what both + scaffolded Dockerfiles set in the image that is deployed. Use `--environment development` for + what `asbs dev` runs. +- the process's own `settings.toml` and `.secrets.toml` are loaded through Dynaconf in environment + mode: `[default]`, then the target environment's section, then `[global]`. A key set only in + another environment's section counts as **unset**, and so does a key written at the top level + outside any section -- the process loads nothing from there, and that is reported as a warning + (`envvar_prefix` and `app_environment` are exempt: they are read from the top level). +- environment overrides in the shell running the command (`DYNACONF_`, + `DYNACONF___`, or the declared prefix) count, as they do for the pod. +- an agent in a group reads its own scope first -- the image's `[default.]`, its own + `.secrets.toml`, its own `settings.toml`, each layered for the target environment -- and then + the image's keys. The keys the merge drops from an agent's files (see below) resolve to the + image's value, which is what the agent then reads. -- `agents.toml` exists; without it the project cannot be run by - `python -m blueprint.agents.entrypoint`, and the three changes that make it hostable are named -- Every `[agents.]` entry has a `module` written as `"package.module:attribute"` -- Every agent name is a legal namespace (`[a-z][a-z0-9_]*` -- no dashes), because it becomes the - queue group, the durable, the cache partition and the telemetry `service.name` -- Every declared module exists in the project and assigns the attribute the map names -- Once there is more than one agent: each ships its own `settings.toml` beside its declaration, - and declares no process-scope key (`app_port`, `event_bus`, `envvar_prefix`, ...) there, since - one process binds one port and speaks one bus +No value from a `.secrets.toml` is ever printed; only key names are. -Schedulers: +## Checks performed -- `scheduler_mode` is set when `src/schedulers/` holds anything, and is one of `in_process` or - `event` -- it has no default, and `build()` fails without it -- In `event` mode, `event_bus` is set; and a notice that **nothing in this project generates the - `CronJob`** that must publish the tick. A scheduler waiting for a tick nobody publishes reports - itself healthy and never runs, which nothing else reports -- In `in_process` mode, a notice when `src/main.py` declares no cache: each tick is claimed in the - agent's own cache so that one replica runs it, and with no cache every replica runs every tick +Project shape (`asbs validate` only): -Delivery: +- Required directories (`src/`, `tests/`) and files (`settings.toml`, `pyproject.toml`) exist +- `src/main.py` exists and uses `AppBuilder` +- `.secrets.toml.example` and `.secrets.toml` are present (an undotted `secrets.toml` is read by + nothing and is reported as the rename it needs) +- A `Dockerfile` is present -- A notice when handlers exist and `idempotency_enabled` is not declared either way. Delivery is +The agent map: + +- No `agents.toml` is the right shape for an agent and gets a notice: the map belongs to the + image that hosts the agent, never to the agent itself. +- An `agents.toml` with entries makes the directory an image, and it is checked by the + `--group` rules below -- every entry needs `root`, and an agent's `settings.toml` is read from + its root, next to the agent's `src/` (one under `src/` is refused by the runtime's layout + check). An empty or unreadable map is an issue. + +Schedulers (per agent with `--group`): + +- `scheduler_mode` is set for the target environment when `src/schedulers/` holds anything, and is + `in_process` or `event` (read as the runtime reads it: trimmed, case-insensitive) -- it has no + default, and `build()` fails without it +- every literal `crontab="..."` passes the runtime's `validate_crontab` in that mode: five fields, + no day `7`, and in `event` mode no day of the week given by number (`0` is Monday to the + blueprint and Sunday to an external cron -- use `mon-fri`, `sun`) +- in `in_process` mode, `scheduler_timezone` is an IANA name (`Europe/Berlin`, `UTC`) +- in `event` mode, `event_bus` is one that delivers a tick (`dapr` or `nats`); a notice when none is + set (the deployment may set it), and a notice that **nothing in this project generates the + `CronJob`** that must publish the tick -- a scheduler waiting for a tick nobody publishes reports + itself healthy and never runs +- in `in_process` mode, a notice when `src/main.py` declares no cache (every replica then runs + every tick), and a notice when the cache is not Redis: a disk cache's claim holds within one + process only, so replicas sharing its directory can each run the same tick + +Delivery (per agent with `--group`), for an agent with handlers or an event-mode scheduler: + +- A notice when `idempotency_enabled` is not set for the target environment. Delivery is at-least-once, so the decision is the author's to make and the framework will not make it -- A warning, with file and line, for code under `src/` that catches `asyncio.CancelledError` without - re-raising it: a bare `except:`, `except BaseException`, `except asyncio.CancelledError` (alone or - in a tuple) whose body raises nothing, or `contextlib.suppress(...)` naming one of them. When a run - exceeds `nats_handler_timeout` it is cancelled; code that swallows that keeps working past the - limit, holding its slot, and when it returns the delivery is nak'd and redelivered anyway -- what - it finished may run twice. `except Exception` does not catch a cancellation and is fine. Checked - for every agent with `--group` too. +- With `idempotency_enabled = true` (read with the runtime's `parse_bool`): `idempotency_ttl` is an + integer above 0, and `src/main.py` declares `.with_cache()` -- the markers live in the agent's + cache. Either missing fails startup +- Warnings the handler chain logs at startup: dedup with `nats_heartbeat_enabled = false`, and dedup + under Dapr, which has no heartbeat; a notice when the dedup cache is not Redis +- A warning when handlers exist and no usable `event_bus` (`dapr`, `nats`, `sessions`) is set: + event handling is then disabled, and the runtime only logs it +- With `--group` and `event_bus = "dapr"`: a warning for a topic two agents declare (literal + `get_subscribed_topics` returns) while one of them does not deduplicate -- Dapr delivers it once + for both, so one agent's retry runs it again in the other +- A warning, with file and line, for code under `src/` that catches `asyncio.CancelledError` + without re-raising it: a bare `except:`, `except BaseException`, `except asyncio.CancelledError` + (alone or in a tuple) whose body raises nothing, or `contextlib.suppress(...)` naming one of them. + When a run exceeds `nats_handler_timeout` it is cancelled; code that swallows that keeps working + past the limit, holding its slot, and when it returns the delivery is nak'd and redelivered + anyway. `except Exception` does not catch a cancellation and is fine + +NATS (per agent with `--group`): + +- The delivery keys are parsed with the client's own parsers: `nats_max_concurrent_runs`, + `nats_extra_runs_per_process`, `nats_handler_timeout`, `nats_connections_readiness`, + `nats_unclaimed_subjects`, and `nats_connection_source` (form, and its module found). Checked + whatever `event_bus` the files say, because the deployment can set it; a value from the image is + reported once, an agent's own value under the agent's name +- With `event_bus = "nats"`, for an agent that consumes or publishes: `nats_url` is set outside + `development` (a `DYNACONF_NATS_URL` in the environment counts), `nats_heartbeat_enabled` is a + boolean, and one `nats_durable_name` does not serve several topics under JetStream +- Standalone, the queue group (`nats_queue_group`, else `app_name`) can appear in a subject: no + whitespace, `*` or `>`. A grouped agent's queue group is its name, which is checked as a + namespace + +Process keys: + +- `event_loop_debug` is a boolean (read with the runtime's `parse_bool`); anything else fails + startup ## Example @@ -59,28 +119,45 @@ asbs validate ``` ``` -Validating Blueprint Agents project: /work/my-ai-service +Validating Blueprint Agents project: /work/orders +Environment: production (choose another with --environment) -[ok] Found agents.toml (1 agent(s): my_ai_service) +[ok] Found src/ +[ok] Found tests/ +[ok] Found settings.toml +... ============================================================ -Notices (1): - - 'scheduler_mode' is 'event', so no timer runs in this process: each tick - arrives as an event on '.scheduler.', published by an external - CronJob. ... +Notices (2): + - No agents.toml here, which is right for an agent: the map says which agents an *image* + contains, ... + - Event deduplication is off ('idempotency_enabled' is not set), so every handler in + this project can be run more than once for the same event. ... + +Warnings (1): + - This project has event handlers registered but no valid event_bus is configured for + 'production' ('dapr', 'nats', 'sessions'). Event handling will be disabled -- the runtime + only logs this. + +[ok] Validation passed with warnings. ``` +That is a project fresh from `asbs setup`: it starts, and its handler receives nothing until an +`event_bus` is set. + --- ## asbs validate --group -Validates an *image* rather than a single agent: the agent map, and every agent directory it -points at. +Validates an *image* rather than a single agent: the agent map, the group file when there is one, +and every agent directory the map points at. ```bash -asbs validate --group # map at the image root -asbs validate --group --agent-map deploy/agents.toml # map kept elsewhere +asbs validate --group # map at the image root +asbs validate --group --agent-map deploy/agents.toml # map kept elsewhere +asbs validate --group --group-config deploy/finance.yaml # check the group file a deployment mounts +asbs validate --group --group-name finance # one group of a multi-group file ``` The directory argument is the **image root** -- what agent `root` values resolve against, and what @@ -92,16 +169,48 @@ will. It checks, per agent: -- `root` and `module` are both present -- neither is derived from the other +- the name is a legal namespace: `[a-z][a-z0-9_]*`, no dashes, and none of the reserved names + `cache`, `event_publishing`, `runtime`, `runtimes` -- it becomes the queue group, the durable, the + cache partition, the telemetry `service.name` and the `/api/` prefix +- `root` and `module` are both present -- neither is derived from the other; `module` is written as + `"package.module:attribute"` - `root` resolves to a directory, inside the image, not shared with another agent -- no file sits where the framework will not read it (a `settings.toml` under `src/`, an - `agents.toml` inside an agent) +- the module is a file of the image that assigns the attribute (a module whose top-level package is + installed outside the image, as a distribution, is not looked into) +- no file sits where the framework will not read it (a `settings.toml` or `.secrets.toml` under + `src/`, an `agents.toml` inside an agent) - which `settings.toml` each agent actually reads, printed, so "is it picking mine up?" is answerable without starting the process -- process-wide keys left in an agent's settings, which are dropped before the merge -- whether the map key matches the directory name, and the `asbs dev --name` that gives the image's routes +- the keys the merge drops from an agent's `settings.toml` **and** `.secrets.toml`: process-wide + keys (`app_port`, `event_bus`, `log_level`, `envvar_prefix`, ...) and deployment identity + (`hostname`, `pod_name`, `blueprint_group`). Reported in any section, which is stricter than the + merge: a section inactive here is active in another deployment +- an agent file that scopes keys under the agent's own name (`[default.]`), which the merge + refuses, and an image key of an agent's name that is not a table, which it refuses too +- everything under "Schedulers", "Delivery" and "NATS" above, on that agent's resolved settings +- whether the map key matches the directory name, and the `asbs dev --name` that gives the image's + routes +- imports of the agent's own code as the top-level package `src`, which work standalone and fail + in a group + +The group file: + +- read from `--group-config`, else `BLUEPRINT_GROUP_CONFIG`, else `deployment-groups.yaml` in the + image root, and resolved by the runtime's own `GroupConfig` with the map above and whichever of + `BLUEPRINT_GROUP`, `BLUEPRINT_AGENTS` and `BLUEPRINT_CRITICAL_AGENTS` the environment sets + (`--group-name` wins over `BLUEPRINT_GROUP`). Its refusals are issues, in its own words: an + `agents` or `critical_agents` that is not a list, a group name declared twice, a critical name the + group does not run, an agent the image does not contain, a group with no agents +- without a name, every group of a multi-group file is resolved in turn +- a non-critical agent missing from the map is a warning: the process skips it +- with no group file and no `BLUEPRINT_GROUP`/`BLUEPRINT_AGENTS`, nothing is resolved and a notice + says so -- which agents a process runs is the deployment's decision, made at container start + +An empty agent map -- what `asbs setup --group` writes -- is an issue: an image with no agents +refuses to start. Exit status is 1 when anything would stop the image starting, 0 otherwise. -Most of these were, until recently, things the process did silently: none of them stops a pod -starting and passing its probes, which is what made them expensive to find. +Most of these were, until recently, things the process did silently or reported only in its log: +none of them stops a pod starting and passing its probes, which is what made them expensive to +find. diff --git a/src/blueprint/agent_generator/generator/part_generators/part_generator_base.py b/src/blueprint/agent_generator/generator/part_generators/part_generator_base.py index 5a8277f0..9d8bd644 100644 --- a/src/blueprint/agent_generator/generator/part_generators/part_generator_base.py +++ b/src/blueprint/agent_generator/generator/part_generators/part_generator_base.py @@ -49,8 +49,9 @@ def agent_namespace(cls, config: dict[str, Any]) -> str: has exactly one agent has no second name to give it. The agent itself never stores this: whoever hosts it supplies the name -- a group - image's agent map, a single-agent image's Dockerfile, or ``asbs dev``. It is derived - here only to write those, and to tell the author what the name will be. + image's agent map, or ``asbs dev --name``. Served alone (its own Dockerfile, or + ``asbs dev`` without ``--name``) it runs at the root namespace and has no name at all. + It is derived here only to tell the author what the name will be in a group. Raises: ValueError: if the project name does not survive the derivation as a legal diff --git a/src/blueprint/agent_generator/generator/part_generators/pyproject_part_generator.py b/src/blueprint/agent_generator/generator/part_generators/pyproject_part_generator.py index 2f6658fb..a26c7c32 100644 --- a/src/blueprint/agent_generator/generator/part_generators/pyproject_part_generator.py +++ b/src/blueprint/agent_generator/generator/part_generators/pyproject_part_generator.py @@ -53,9 +53,10 @@ def _pyproject(self) -> str: [tool.pytest.ini_options] testpaths = ["tests"] -# The generated tests import `src.main`, which is how agents.toml names the declaration and how -# the container's entry point imports it. Without the project root on the path, the first pytest -# run in a new project fails on the import rather than on anything the author wrote. +# The generated tests import `src.main`, the module this agent's own Dockerfile serves (a group +# image's agents.toml names the same file by its path from the image root). Without the project +# root on the path, the first pytest run in a new project fails on the import rather than on +# anything the author wrote. pythonpath = ["."] asyncio_mode = "auto" """ diff --git a/src/blueprint/agent_generator/generator/part_generators/tests_part_generator.py b/src/blueprint/agent_generator/generator/part_generators/tests_part_generator.py index db4a4bd9..df01d87d 100644 --- a/src/blueprint/agent_generator/generator/part_generators/tests_part_generator.py +++ b/src/blueprint/agent_generator/generator/part_generators/tests_part_generator.py @@ -39,8 +39,9 @@ def to_py_file_name(self) -> str: def _conftest(self) -> str: """Put the project root on the path, so the tests need no pytest configuration at all. - ``test_declaration.py`` imports ``src.main`` -- the same import ``agents.toml`` names and - the container entry point performs -- which needs the project root importable. That can + ``test_declaration.py`` imports ``src.main`` -- the module this agent's own Dockerfile + serves, and the file a group image's map names by its path -- which needs the project root + importable. That can come from ``pythonpath`` in ``pyproject.toml``, but a scaffolded project is scaffolded *into* a project that already exists and already has a ``pyproject.toml`` of its own, and editing somebody's build configuration to make generated tests run is not this tool's @@ -48,8 +49,9 @@ def _conftest(self) -> str: """ return '''"""Make the project root importable, so `from src.main import agent` resolves. -`src.main` is what `agents.toml` names and what `python -m blueprint.agents.entrypoint` imports, -so the tests import it the same way the runtime does rather than a way of their own. +`src.main` is what this agent's own Dockerfile serves (`uvicorn src.main:create_app --factory`). +A group image's `agents.toml` names the same file by its path from the image root +(`agents..src.main:agent`); either way it is one declaration, imported as a module. """ import sys @@ -79,24 +81,43 @@ def _declaration_test(self) -> str: namespace exists, so it belongs to the root for ever. """ +import importlib +import sys + +import pytest + from blueprint.agents.app_builder import AppBuilder -from src.main import agent + +@pytest.fixture +def agent() -> AppBuilder: + """``src.main`` as importing it leaves it, whatever ran before in this session. + + Imported afresh, because ``create_app()`` builds the module's own ``agent`` -- so a test that + served the application earlier in the same run would otherwise hand these tests a built one. + The module already imported is put back, so nothing else sees a difference. + """ + imported = sys.modules.pop("src.main", None) + try: + return importlib.import_module("src.main").agent + finally: + if imported is not None: + sys.modules["src.main"] = imported -def test_main_declares_an_unbuilt_builder() -> None: +def test_main_declares_an_unbuilt_builder(agent: AppBuilder) -> None: assert isinstance(agent, AppBuilder) assert not agent.is_built, "main.py built the application on import; the host builds it" -def test_nothing_is_constructed_on_import() -> None: +def test_nothing_is_constructed_on_import(agent: AppBuilder) -> None: """A declaration records; it does not create. Instances here would carry the root namespace.""" constructed = [declaration.kind for declaration in agent.declarations if declaration.is_built] assert not constructed, f"main.py passes already-built {{constructed}} to the builder; pass the class instead" -def test_every_component_is_declared() -> None: +def test_every_component_is_declared(agent: AppBuilder) -> None: """Rename or remove a component and this is what tells you main.py was not updated.""" kinds = [declaration.kind for declaration in agent.declarations] @@ -104,7 +125,7 @@ def test_every_component_is_declared() -> None: assert "handler" in kinds -def test_the_services_this_project_ships_are_declared() -> None: +def test_the_services_this_project_ships_are_declared(agent: AppBuilder) -> None: declared = {{ getattr(declaration.target, "__name__", type(declaration.target).__name__) for declaration in agent.declarations diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index 3e32a380..03010477 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -108,6 +108,14 @@ class ConfigError(Exception): """ +AGENT_REFUSED_KEYS = PROCESS_SCOPE_KEYS | DEPLOYMENT_IDENTITY_KEYS +"""Every key an agent's own settings file cannot set: :data:`PROCESS_SCOPE_KEYS` and :data:`DEPLOYMENT_IDENTITY_KEYS`. + +:meth:`Config.merge_agent_settings` drops each one with a WARNING. Named once so that ``asbs +validate`` reports exactly the keys the merge drops. +""" + + DEFAULT_SETTINGS_FILES = ["settings.toml", ".secrets.toml"] """The settings files the framework loads when the application names none. @@ -166,6 +174,58 @@ class ConfigError(Exception): """ +def environment_section_names(documents: list[dict[str, Any]]) -> frozenset[str]: + """Every table name that is an environment section to a process, ``default`` and ``global`` excluded. + + The conventional ones, and every top-level table of the process's own settings files: in + environment mode Dynaconf reads each of those as an environment, so an agent's table of the + same name is one too. Shared with ``asbs validate``, which layers files the way the merge does. + + Args: + documents: The process's own settings files, parsed. + """ + names = set(CONVENTIONAL_ENVIRONMENTS) + for document in documents: + names.update(str(key).lower() for key, value in document.items() if isinstance(value, dict)) + return frozenset(names - {"default", "global"}) + + +def layer_settings_document(document: dict[str, Any], environment: str, environment_names: frozenset[str]) -> dict[str, Any]: + """Flatten an agent's settings file for one environment, the way Dynaconf flattens the process's own. + + Three layers, lowest first: keys written at the top level, ``[default]``, and the section for + ``environment``. ``[global]`` is applied last, as Dynaconf applies it. Section names are + matched case-insensitively, again as Dynaconf matches them. A table that is not an environment + section (``[cache]`` beside ``[default]``) is a value and kept; an environment section that is + not active is dropped. What :meth:`Config.merge_agent_settings` merges, and what ``asbs + validate`` reads an agent's file through. + + Args: + document: The parsed file. + environment: The environment in force, lower case. + environment_names: What counts as an environment section; see :func:`environment_section_names`. + """ + sections = {str(key).lower(): value for key, value in document.items() if hasattr(value, "items")} + layered: dict[str, Any] = {key: value for key, value in document.items() if not hasattr(value, "items")} + active = ("default", environment, "global") + for section in active: + values = sections.get(section) + if values: + layered.update({str(key): value for key, value in values.items()}) + # A table the file wrote at the top level is a value, not a section: [cache] beside + # [default] is this agent's cache configuration. An environment section that is not + # active is neither: it is dropped, as Dynaconf drops the process's own. It was kept as a + # key, so every agent carried its [production] table as 'production' in development (S13). + for name, values in sections.items(): + if name in active: + continue + if name in environment_names: + logger.debug("Agent settings: section [%s] is for another environment than '%s'; dropped", name, environment) + continue + layered.setdefault(name, values) + return layered + + class Config: """A class to manage the application's configuration using dynaconf.""" @@ -186,7 +246,7 @@ def __init__( Raw access via ``self.settings`` remains unscoped. Which environment variables count as overrides is decided here too, before the tree is - built: see :meth:`_resolve_envvar_prefix`. The prefix is a property of the process, not + built: see :meth:`resolve_envvar_prefix`. The prefix is a property of the process, not of a namespace, so a view built by :meth:`for_namespace` shares it. """ @@ -218,7 +278,7 @@ def __init__( temp_settings = Dynaconf( settings_files=settings_files, environments=False, load_dotenv=False, merge_enabled=True, root_path=root_path ) - self._envvar_prefix = self._resolve_envvar_prefix(temp_settings) + self._envvar_prefix = self.resolve_envvar_prefix(temp_settings) if self._envvar_prefix != DEFAULT_ENVVAR_PREFIX: # Repeat the pass through the resolved prefix. Without this, `_APP_ENVIRONMENT` # is invisible to the only read that consumes it: the second pass would load the @@ -315,7 +375,7 @@ def __init__( self._settings[key] = value @staticmethod - def _resolve_envvar_prefix(bootstrap_settings: Any) -> str | bool: + def resolve_envvar_prefix(bootstrap_settings: Any) -> str | bool: """Decide which prefix environment overrides must carry, before the real tree is loaded. Precedence, highest first: the :data:`ENVVAR_PREFIX_OVERRIDE` environment variable, the @@ -696,44 +756,19 @@ def _layer_fragment(self, document: dict[str, Any]) -> dict[str, Any]: Args: document: The parsed file. """ - sections = {str(key).lower(): value for key, value in document.items() if hasattr(value, "items")} - layered: dict[str, Any] = {key: value for key, value in document.items() if not hasattr(value, "items")} - active = ("default", self._environment, "global") - for section in active: - values = sections.get(section) - if values: - layered.update({str(key): value for key, value in values.items()}) - # A table the file wrote at the top level is a value, not a section: [cache] beside - # [default] is this agent's cache configuration. An environment section that is not - # active is neither: it is dropped, as Dynaconf drops the process's own. It was kept as a - # key, so every agent carried its [production] table as 'production' in development (S13). - environments = self._environment_names() - for name, values in sections.items(): - if name in active: - continue - if name in environments: - logger.debug("Agent settings: section [%s] is for another environment than '%s'; dropped", name, self._environment) - continue - layered.setdefault(name, values) - return layered + return layer_settings_document(document, self._environment, self._environment_names()) def _environment_names(self) -> frozenset[str]: - """Every table name that is an environment section to this process, ``default`` and ``global`` excluded. - - The conventional ones, and every top-level table of the process's own settings files: in - environment mode Dynaconf reads each of those as an environment, so a fragment table of the - same name is one too. - """ - names = set(CONVENTIONAL_ENVIRONMENTS) + """Every table name that is an environment section to this process; see :func:`environment_section_names`.""" + documents: list[dict[str, Any]] = [] for path in self._settings_files: if path.suffix != ".toml" or not path.is_file(): continue try: - document = tomllib.loads(path.read_text(encoding="utf-8")) + documents.append(tomllib.loads(path.read_text(encoding="utf-8"))) except (OSError, tomllib.TOMLDecodeError): continue - names.update(str(key).lower() for key, value in document.items() if isinstance(value, dict)) - return frozenset(names - {"default", "global"}) + return environment_section_names(documents) @staticmethod def _refuse_self_scoped_fragment(namespace: str, path: Path, fragment: dict[str, Any]) -> None: @@ -777,7 +812,7 @@ def _drop_process_scope_keys(self, namespace: str, path: Path, fragment: dict[st only actionable next to the value that is -- except for a secrets file, whose values are never logged, and the process's then neither. """ - refused = PROCESS_SCOPE_KEYS | DEPLOYMENT_IDENTITY_KEYS + refused = AGENT_REFUSED_KEYS kept: dict[str, Any] = {} for key, value in fragment.items(): if str(key).lower() not in refused: diff --git a/src/blueprint/agents/group_config.py b/src/blueprint/agents/group_config.py index 01b56385..2ee500ea 100644 --- a/src/blueprint/agents/group_config.py +++ b/src/blueprint/agents/group_config.py @@ -198,8 +198,29 @@ def resolve(cls, config: Config, *, environ: dict[str, str] | None = None) -> "G malformed, if a named group is absent, or if an agent is not in the agent map and is critical. """ + return cls.resolve_at(config.get_package_root(), environ=environ) + + @classmethod + def resolve_at(cls, root: Path, *, environ: dict[str, str] | None = None) -> "GroupConfig": + """Resolve the group for the image at ``root`` -- what :meth:`resolve` does, given the root itself. + + The whole resolution needs nothing from the configuration but the directory relative + paths resolve against, so this is the same code with that directory passed in. It is what + ``asbs validate --group`` runs against a stub environment, so the validator reports the + refusals the process would start with, in the process's own words. + + Args: + root: The image root: where the group file and the agent map are looked for by default, + and what every agent ``root`` resolves against. + environ: The environment to read. Defaults to the process environment. + + Returns: + The resolved group. + + Raises: + GroupConfigError: as :meth:`resolve`. + """ env = os.environ if environ is None else environ - root = config.get_package_root() declared = cls._read_group_file(env, root) name, agent_names, critical_names = cls._apply_env_overrides(env, declared) diff --git a/tests/unit/agent_generator/cli/commands/test_create_components.py b/tests/unit/agent_generator/cli/commands/test_create_components.py new file mode 100644 index 00000000..3d54d0f2 --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_create_components.py @@ -0,0 +1,112 @@ +"""What ``asbs create handler``, ``asbs create service`` and ``asbs setup`` write and print. + +``create handler --event-type X`` took X for a docstring only, while the generated handler reads +``.input_event_type`` from the settings at startup -- a key nothing wrote. It is written +now, the way ``create agent`` writes its runtime's block, and read back here through the +validator's view of the settings, which layers them as the process does. +""" + +import sys +from argparse import Namespace +from pathlib import Path + +import pytest + +from blueprint.agent_generator.cli.commands import setup +from blueprint.agent_generator.cli.commands.create import create_handler, create_service +from blueprint.agent_generator.cli.commands.validate import ProcessSettings + + +@pytest.fixture +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + (tmp_path / "settings.toml").write_text('[default]\napp_name = "the-project"\n', encoding="utf-8") + monkeypatch.chdir(tmp_path) + return tmp_path + + +def _handler(event_type: str = "order.placed") -> Namespace: + return Namespace(name="OrderPlaced", event_type=event_type, priority=10, output_dir="src/handlers") + + +class TestCreateHandler: + def test_the_event_type_is_written_where_the_handler_reads_it(self, project: Path, capsys: pytest.CaptureFixture[str]) -> None: + create_handler(_handler()) + capsys.readouterr() + + source = (project / "src" / "handlers" / "order_placed_handler.py").read_text(encoding="utf-8") + assert 'self.config.get("order_placed_handler"' in source, "the generated handler reads this section" + view = ProcessSettings.load(project, "production").root_view() + assert view.get("order_placed_handler.input_event_type") == "order.placed" + + def test_an_existing_section_is_left_alone(self, project: Path, capsys: pytest.CaptureFixture[str]) -> None: + settings = project / "settings.toml" + settings.write_text('[default]\napp_name = "p"\n\n[default.order_placed_handler]\ninput_event_type = "mine"\n', encoding="utf-8") + + create_handler(_handler()) + capsys.readouterr() + + assert settings.read_text(encoding="utf-8").count("[default.order_placed_handler]") == 1 + assert ProcessSettings.load(project).root_view().get("order_placed_handler.input_event_type") == "mine" + + +class TestCreateService: + def test_the_docstring_names_the_service_not_a_placeholder(self, project: Path, capsys: pytest.CaptureFixture[str]) -> None: + create_service(Namespace(name="Invoice", output_dir="src/services")) + capsys.readouterr() + + source = next((project / "src" / "services").glob("*.py")).read_text(encoding="utf-8") + assert "cli_generated" not in source + + +class TestSetupPrintsWhatItWrites: + def test_every_file_written_at_the_top_is_in_the_printed_tree(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + setup.run(Namespace(project_name="Demo", output_dir=str(tmp_path), overwrite=False, verbose=False, group=False)) + out = capsys.readouterr().out + tree = out.split("Project structure:")[1].split("Next steps:")[0] + + written = sorted(path.name for path in tmp_path.iterdir() if path.name != "__pycache__") + missing = [name for name in written if f" {name}" not in tree and f" {name}/" not in tree] + assert not missing, f"setup wrote {missing} and its tree does not show them" + + +@pytest.mark.skipif(sys.platform == "emscripten", reason="needs a subprocess") +def test_the_generated_declaration_test_passes_after_the_app_was_built(tmp_path: Path) -> None: + """Guide item: building the app in the same pytest session used to fail test_declaration.""" + import subprocess + + setup.run(Namespace(project_name="Demo", output_dir=str(tmp_path), overwrite=False, verbose=False, group=False)) + (tmp_path / "tests" / "test_0_builds_first.py").write_text( + "from src.main import create_app\n\n\ndef test_build() -> None:\n create_app()\n", encoding="utf-8" + ) + result = subprocess.run( + [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "tests/test_0_builds_first.py", "tests/test_declaration.py"], + cwd=tmp_path, + capture_output=True, + text=True, + timeout=300, + ) + assert result.returncode == 0, result.stdout[-3000:] + result.stderr[-3000:] + + +@pytest.mark.skipif(sys.platform == "emscripten", reason="needs a subprocess") +def test_a_fresh_project_starts_the_way_its_container_does(tmp_path: Path) -> None: + """``asbs setup`` must produce a project that starts as generated. + + Its handler reads ``input_event_type``, which ``setup`` does not write, so a stricter startup + check there stops every new project (N18). Started in production, as both Dockerfiles do, + through ``create_app()`` and the lifespan; a subprocess keeps its configuration out of this one. + """ + import os + import subprocess + + setup.run(Namespace(project_name="Demo", output_dir=str(tmp_path), overwrite=False, verbose=False, group=False)) + script = "from fastapi.testclient import TestClient\nfrom src.main import create_app\n\nwith TestClient(create_app()):\n pass\n" + result = subprocess.run( + [sys.executable, "-c", script], + cwd=tmp_path, + env={**os.environ, "DYNACONF_APP_ENVIRONMENT": "production"}, + capture_output=True, + text=True, + timeout=300, + ) + assert result.returncode == 0, result.stdout[-3000:] + result.stderr[-3000:] diff --git a/tests/unit/agent_generator/cli/commands/test_create_scheduler.py b/tests/unit/agent_generator/cli/commands/test_create_scheduler.py index f3daa346..f3f5ec0c 100644 --- a/tests/unit/agent_generator/cli/commands/test_create_scheduler.py +++ b/tests/unit/agent_generator/cli/commands/test_create_scheduler.py @@ -60,3 +60,17 @@ def test_tick_does_not_swallow_its_own_failure(self, scaffold: str) -> None: def test_scheduler_mode_is_explained(self, scaffold: str) -> None: assert "scheduler_mode" in scaffold + + def test_a_disk_cache_is_not_said_to_coordinate_replicas(self, scaffold: str) -> None: + assert "within one process" in " ".join(scaffold.split()) + + +class TestTheCrontabIsCheckedBeforeWriting: + @pytest.mark.parametrize("cron", ["every hour", "0 0 * * 7", "0 0 0 * * *"]) + def test_an_expression_the_runtime_refuses_writes_nothing(self, tmp_path: Path, cron: str, capsys: pytest.CaptureFixture[str]) -> None: + with pytest.raises(SystemExit) as exit_info: + create_scheduler(Namespace(name="cleanup", output_dir=str(tmp_path), cron=cron)) + + assert exit_info.value.code == 1 + assert not (tmp_path / "cleanup_scheduler.py").exists() + assert "crontab" in capsys.readouterr().err diff --git a/tests/unit/agent_generator/cli/commands/test_dev.py b/tests/unit/agent_generator/cli/commands/test_dev.py index 53500dfb..7fa350db 100644 --- a/tests/unit/agent_generator/cli/commands/test_dev.py +++ b/tests/unit/agent_generator/cli/commands/test_dev.py @@ -116,3 +116,14 @@ def test_neither_file_is_an_error(self, tmp_path: Path) -> None: _run(tmp_path) assert exit_info.value.code == 1 + + +class TestTheDevName: + """The name comes from --name only: without it an agent directory is served alone, at the root.""" + + def test_the_requested_name_is_normalised_into_a_namespace(self) -> None: + assert dev._dev_agent_name("Order-EU") == "order_eu" + + def test_a_name_that_cannot_be_a_namespace_stops(self) -> None: + with pytest.raises(SystemExit): + dev._dev_agent_name("1orders") diff --git a/tests/unit/agent_generator/cli/commands/test_validate.py b/tests/unit/agent_generator/cli/commands/test_validate.py index c903efb0..fd535e00 100644 --- a/tests/unit/agent_generator/cli/commands/test_validate.py +++ b/tests/unit/agent_generator/cli/commands/test_validate.py @@ -30,9 +30,15 @@ def test_opting_out_explicitly_also_silences_it(self, tmp_path: Path) -> None: project = _project(tmp_path, "[default]\nidempotency_enabled = false\n") assert _idempotency_notice(project) is None - def test_top_level_key_without_an_environment_table_counts(self, tmp_path: Path) -> None: + def test_a_top_level_key_outside_any_section_is_not_a_decision(self, tmp_path: Path) -> None: + """The process loads [default], [] and [global] only, so the key above them is read by nothing.""" project = _project(tmp_path, "idempotency_enabled = true\nidempotency_ttl = 60\n") - assert _idempotency_notice(project) is None + assert _idempotency_notice(project) == IDEMPOTENCY_NOTICE + + def test_a_decision_made_only_for_another_environment_does_not_count(self, tmp_path: Path) -> None: + project = _project(tmp_path, "[development]\nidempotency_enabled = false\n") + assert _idempotency_notice(project) == IDEMPOTENCY_NOTICE + assert _idempotency_notice(project, "development") is None def test_a_project_with_no_handlers_is_not_notified(self, tmp_path: Path) -> None: project = _project(tmp_path, '[default]\napp_name = "demo"\n', with_handler=False) diff --git a/tests/unit/agent_generator/cli/commands/test_validate_group.py b/tests/unit/agent_generator/cli/commands/test_validate_group.py index f8d721dd..32c52abd 100644 --- a/tests/unit/agent_generator/cli/commands/test_validate_group.py +++ b/tests/unit/agent_generator/cli/commands/test_validate_group.py @@ -15,7 +15,7 @@ import pytest -from blueprint.agent_generator.cli.commands.validate_group import _agent_map_path, _findings +from blueprint.agent_generator.cli.commands.validate_group import _agent_map_path, image_findings MAP_ENV = "BLUEPRINT_AGENT_MAP" @@ -38,7 +38,7 @@ def test_the_scaffolded_layout_has_the_map_at_the_image_root(self, tmp_path: Pat _agent_dir(tmp_path / "agents" / "orders") (tmp_path / "agents.toml").write_text(_map_text("agents/orders"), encoding="utf-8") - issues, _, _ = _findings(tmp_path, _agent_map_path(tmp_path, None)) + issues, _, _ = image_findings(tmp_path, _agent_map_path(tmp_path, None)) assert issues == [] @@ -52,12 +52,12 @@ def test_a_map_below_the_image_root_still_resolves_roots_against_that_root(self, encoding="utf-8", ) - issues, _, _ = _findings(tmp_path, _agent_map_path(tmp_path, "deploy/agents.toml")) + issues, _, _ = image_findings(tmp_path, _agent_map_path(tmp_path, "deploy/agents.toml")) assert issues == [], "Resolving the root against deploy/ rather than the image root is the defect." def test_an_absent_map_names_the_flag_that_points_at_one(self, tmp_path: Path) -> None: - issues, _, _ = _findings(tmp_path, _agent_map_path(tmp_path, None)) + issues, _, _ = image_findings(tmp_path, _agent_map_path(tmp_path, None)) assert len(issues) == 1 assert "--agent-map" in issues[0], "A reader whose map is elsewhere needs to be told there is a way to say so." @@ -70,7 +70,7 @@ def test_a_root_outside_the_image_is_still_refused(self, tmp_path: Path) -> None image.mkdir() (image / "agents.toml").write_text(_map_text("../outside"), encoding="utf-8") - issues, _, _ = _findings(image, _agent_map_path(image, None)) + issues, _, _ = image_findings(image, _agent_map_path(image, None)) assert any("outside the image" in issue for issue in issues) @@ -119,7 +119,7 @@ def test_an_absolute_src_import_is_a_warning_naming_file_and_line(self, tmp_path {"main.py": "from src.services.order_service import OrderService\nagent = None\n", "api/routes.py": "import src.models\n"}, ) - issues, warnings, _ = _findings(image, _agent_map_path(image, None)) + issues, warnings, _ = image_findings(image, _agent_map_path(image, None)) assert issues == [], "Both styles are legitimate standalone; this must not claim the image cannot start." found = [w for w in warnings if "imports its own code as 'src'" in w] @@ -130,21 +130,21 @@ def test_an_absolute_src_import_is_a_warning_naming_file_and_line(self, tmp_path def test_relative_imports_are_not_reported(self, tmp_path: Path) -> None: image = self._image_with(tmp_path, {"main.py": "from .services.order_service import OrderService\nagent = None\n"}) - _, warnings, _ = _findings(image, _agent_map_path(image, None)) + _, warnings, _ = image_findings(image, _agent_map_path(image, None)) assert not any("imports its own code as 'src'" in w for w in warnings) def test_a_name_in_a_docstring_or_comment_is_not_an_import(self, tmp_path: Path) -> None: image = self._image_with(tmp_path, {"main.py": '"""Once: from src.x import Y."""\n# import src\nagent = None\n'}) - _, warnings, _ = _findings(image, _agent_map_path(image, None)) + _, warnings, _ = image_findings(image, _agent_map_path(image, None)) assert not any("imports its own code as 'src'" in w for w in warnings) def test_a_package_merely_starting_with_src_is_not_reported(self, tmp_path: Path) -> None: image = self._image_with(tmp_path, {"main.py": "import srcutils\nfrom srclib.x import Y\nagent = None\n"}) - _, warnings, _ = _findings(image, _agent_map_path(image, None)) + _, warnings, _ = image_findings(image, _agent_map_path(image, None)) assert not any("imports its own code as 'src'" in w for w in warnings) @@ -154,14 +154,14 @@ def test_an_agent_whose_src_is_the_image_roots_is_not_reported(self, tmp_path: P (tmp_path / "src" / "main.py").write_text("from src.services import x\nagent = None\n", encoding="utf-8") (tmp_path / "agents.toml").write_text(_map_text(".", "src.main:agent"), encoding="utf-8") - _, warnings, _ = _findings(tmp_path, _agent_map_path(tmp_path, None)) + _, warnings, _ = image_findings(tmp_path, _agent_map_path(tmp_path, None)) assert not any("imports its own code as 'src'" in w for w in warnings) def test_a_long_list_is_summarised(self, tmp_path: Path) -> None: image = self._image_with(tmp_path, {"main.py": "".join(f"import src.m{i}\n" for i in range(8)) + "agent = None\n"}) - _, warnings, _ = _findings(image, _agent_map_path(image, None)) + _, warnings, _ = image_findings(image, _agent_map_path(image, None)) found = [w for w in warnings if "imports its own code as 'src'" in w] assert "and 3 more" in found[0] @@ -185,7 +185,7 @@ def _image(tmp_path: Path, agent_settings: str, image_settings: str = "") -> Pat def test_a_scheduler_without_a_mode_is_an_issue(self, tmp_path: Path) -> None: image = self._image(tmp_path, '[default]\nmodel_name = "x"\n') - issues, _, _ = _findings(image, image / "agents.toml") + issues, _, _ = image_findings(image, image / "agents.toml") assert any("Agent 'orders'" in issue and "no 'scheduler_mode'" in issue for issue in issues) @@ -193,7 +193,7 @@ def test_the_images_event_bus_serves_an_agents_event_mode(self, tmp_path: Path) """scheduler_mode from the agent's file, event_bus from the image's -- where a process key lives.""" image = self._image(tmp_path, '[default]\nscheduler_mode = "event"\n', '[default]\nevent_bus = "nats"\n') - issues, _, notices = _findings(image, image / "agents.toml") + issues, _, notices = image_findings(image, image / "agents.toml") assert not [issue for issue in issues if "scheduler" in issue] assert any("CronJob" in notice for notice in notices) diff --git a/tests/unit/agent_generator/cli/commands/test_validate_group_gates.py b/tests/unit/agent_generator/cli/commands/test_validate_group_gates.py index 2a76f2fb..977ec43a 100644 --- a/tests/unit/agent_generator/cli/commands/test_validate_group_gates.py +++ b/tests/unit/agent_generator/cli/commands/test_validate_group_gates.py @@ -4,17 +4,27 @@ and a tool that rewrites it either guesses at intent or fails on anything hand-edited. A checklist plus a validate that names what is missing is the honest shape, so what these tests hold is that each thing it can name, it does. + +A project holding an `agents.toml` with entries is an image, and is checked by the rules the group +entry point applies (audit 3f): every entry needs a `root`, and an agent's settings are read from +beside its root's `src` -- never from beside the declaration module. """ from pathlib import Path import pytest -from blueprint.agent_generator.cli.commands.validate import _group_findings +from blueprint.agent_generator.cli.commands.validate import NO_AGENT_MAP_NOTICE, ProcessSettings, _group_findings, root_findings DECLARATION = "from blueprint.agents.app_builder import AppBuilder\n\nagent = AppBuilder()\n" +@pytest.fixture(autouse=True) +def _no_ambient_overrides(monkeypatch: pytest.MonkeyPatch) -> None: + for name in ("DYNACONF_APP_ENVIRONMENT", "DYNACONF_SCHEDULER_MODE", "DYNACONF_EVENT_BUS", "BLUEPRINT_AGENTS", "BLUEPRINT_GROUP"): + monkeypatch.delenv(name, raising=False) + + def _project(tmp_path: Path, *, agent_map: str | None = None, settings: str | None = None, main: str | None = DECLARATION) -> Path: """Build the smallest project shape the group gates look at.""" if main is not None: @@ -27,8 +37,18 @@ def _project(tmp_path: Path, *, agent_map: str | None = None, settings: str | No return tmp_path -def _agent(name: str = "orders", module: str = "src.main:agent") -> str: - return f'[agents.{name}]\nmodule = "{module}"\n' +def _agent_dir(project: Path, name: str, settings: str = '[default]\nmodel_name = "x"\n') -> Path: + root = project / "agents" / name + (root / "src").mkdir(parents=True, exist_ok=True) + (root / "src" / "main.py").write_text(DECLARATION, encoding="utf-8") + (root / "settings.toml").write_text(settings, encoding="utf-8") + return root + + +def _agent(name: str = "orders", module: str | None = None, root: str | None = None) -> str: + module = module if module is not None else f"agents.{name}.src.main:agent" + root = root if root is not None else f"agents/{name}" + return f'[agents.{name}]\nroot = "{root}"\nmodule = "{module}"\n' class TestTheAgentMap: @@ -40,12 +60,15 @@ def test_an_agent_without_one_is_not_told_to_add_one(self, tmp_path: Path) -> No assert not issues, "A project deployed on its own is not broken, so this is never an issue." assert warnings == [] - assert len(notices) == 1 + assert notices == [NO_AGENT_MAP_NOTICE] assert "belongs to the image" in notices[0] assert "asbs validate --group" in notices[0] def test_a_well_formed_map_passes_silently(self, tmp_path: Path) -> None: - issues, warnings, _ = _group_findings(_project(tmp_path, agent_map=_agent())) + project = _project(tmp_path, agent_map=_agent()) + _agent_dir(project, "orders") + + issues, warnings, _ = _group_findings(project) assert (issues, warnings) == ([], []) @@ -60,88 +83,83 @@ def test_a_map_with_no_agents_is_reported(self, tmp_path: Path) -> None: assert "declares no [agents.] entries" in issues[0] + def test_an_entry_without_a_root_is_reported(self, tmp_path: Path) -> None: + """Audit 3f: the runtime requires it, and this did not.""" + project = _project(tmp_path, agent_map='[agents.orders]\nmodule = "agents.orders.src.main:agent"\n') + _agent_dir(project, "orders") + + issues, _, _ = _group_findings(project) + + assert any("has no 'root'" in issue for issue in issues) + def test_an_entry_without_a_module_is_reported(self, tmp_path: Path) -> None: - issues, _, _ = _group_findings(_project(tmp_path, agent_map="[agents.orders]\ncritical = true\n")) + project = _project(tmp_path, agent_map='[agents.orders]\nroot = "agents/orders"\ncritical = true\n') + _agent_dir(project, "orders") + + issues, _, _ = _group_findings(project) - assert "has no 'module'" in issues[0] + assert "has no usable 'module'" in issues[0] def test_a_module_that_names_no_attribute_is_reported(self, tmp_path: Path) -> None: - issues, _, _ = _group_findings(_project(tmp_path, agent_map=_agent(module="src.main"))) + project = _project(tmp_path, agent_map=_agent(module="agents.orders.src.main")) + _agent_dir(project, "orders") + + issues, _, _ = _group_findings(project) - assert "does not say which attribute" in issues[0] + assert "has no usable 'module'" in issues[0] def test_a_name_that_cannot_be_a_namespace_is_reported(self, tmp_path: Path) -> None: """It becomes a queue group, a durable, a cache partition and a service.name.""" - issues, _, _ = _group_findings(_project(tmp_path, agent_map=_agent(name="order-eu"))) + issues, _, _ = _group_findings(_project(tmp_path, agent_map='[agents.order-eu]\nroot = "x"\nmodule = "x.src.main:agent"\n')) assert "cannot be a namespace" in issues[0] - def test_a_module_that_is_not_in_the_project_is_reported(self, tmp_path: Path) -> None: - issues, _, _ = _group_findings(_project(tmp_path, agent_map=_agent(module="src.nowhere:agent"))) + def test_a_module_that_is_not_in_the_image_is_reported(self, tmp_path: Path) -> None: + project = _project(tmp_path, agent_map=_agent(module="agents.orders.src.nowhere:agent")) + _agent_dir(project, "orders") - assert "is not a module in this project" in issues[0] + issues, _, _ = _group_findings(project) + + assert "is not a module in this image" in issues[0] def test_a_module_that_declares_no_such_attribute_is_reported(self, tmp_path: Path) -> None: """The attribute is the AppBuilder the host builds; without it the process never starts.""" - issues, _, _ = _group_findings(_project(tmp_path, agent_map=_agent(module="src.main:registration"))) + project = _project(tmp_path, agent_map=_agent(module="agents.orders.src.main:registration")) + _agent_dir(project, "orders") + + issues, _, _ = _group_findings(project) assert "assigns no 'registration'" in issues[0] def test_a_package_declaration_resolves_too(self, tmp_path: Path) -> None: - package = tmp_path / "src" / "orders" - package.mkdir(parents=True) - (package / "__init__.py").write_text(DECLARATION, encoding="utf-8") + project = _project(tmp_path, agent_map=_agent(module="agents.orders.src:agent")) + root = _agent_dir(project, "orders") + (root / "src" / "__init__.py").write_text(DECLARATION, encoding="utf-8") - issues, _, _ = _group_findings(_project(tmp_path, agent_map=_agent(module="src.orders:agent"))) + issues, _, _ = _group_findings(project) assert issues == [] class TestSettingsThatWillNotSurviveGrouping: - """An agent's settings are read from its declaration's directory, and scoped to it.""" - - def test_a_project_hosted_alone_is_not_told_about_scoping(self, tmp_path: Path) -> None: - """Its settings.toml *is* the process's own file, so neither rule applies to it yet.""" - project = _project(tmp_path, agent_map=_agent(), settings="[default]\napp_port = 8000\n") - - _, warnings, _ = _group_findings(project) - - assert warnings == [] - - def test_an_agent_shipping_no_settings_of_its_own_is_told_where_they_go(self, tmp_path: Path) -> None: - project = _project(tmp_path, agent_map=_agent() + _agent(name="billing", module="src.billing:agent")) - (tmp_path / "src" / "billing").mkdir() - (tmp_path / "src" / "billing" / "__init__.py").write_text(DECLARATION, encoding="utf-8") - - _, warnings, _ = _group_findings(project) - - assert len(warnings) == 2 - assert all("ships no settings of its own" in warning for warning in warnings) + """An agent's settings are read from beside its root's src, and scoped to it.""" - def test_a_declaration_at_the_project_root_keeps_the_process_settings_file(self, tmp_path: Path) -> None: - """`main:agent` puts the agent's settings file where the process's own already is.""" - project = _project(tmp_path, agent_map=_agent(module="main:agent") + _agent(name="billing", module="src.billing:agent")) - (tmp_path / "main.py").write_text(DECLARATION, encoding="utf-8") - (tmp_path / "settings.toml").write_text("[default]\napp_port = 8000\n", encoding="utf-8") - billing = tmp_path / "src" / "billing" - billing.mkdir(parents=True) - (billing / "__init__.py").write_text(DECLARATION, encoding="utf-8") - (billing / "settings.toml").write_text('[default]\nmodel_name = "y"\n', encoding="utf-8") + def test_settings_beside_the_declaration_are_refused(self, tmp_path: Path) -> None: + """Audit 3f: they used to be looked for next to the declaration, under src/ -- where the runtime refuses them.""" + project = _project(tmp_path, agent_map=_agent()) + root = _agent_dir(project, "orders") + (root / "settings.toml").unlink() + (root / "src" / "settings.toml").write_text('[default]\nmodel_name = "x"\n', encoding="utf-8") - _, warnings, _ = _group_findings(project) + issues, _, _ = _group_findings(project) - assert warnings == [], "The merge leaves the process's own settings file at the root rather than scoping it." + assert any("'settings.toml'" in issue and "not where it is read from" in issue for issue in issues) - def test_a_process_scope_key_in_a_fragment_is_named(self, tmp_path: Path) -> None: + def test_a_process_scope_key_in_an_agents_settings_is_named(self, tmp_path: Path) -> None: """One process binds one port and speaks one bus, so these are dropped at startup.""" - project = _project(tmp_path, agent_map=_agent() + _agent(name="billing", module="src.billing:agent")) - (tmp_path / "src" / "settings.toml").write_text( - '[default]\napp_port = 8000\nevent_bus = "nats"\nmodel_name = "x"\n', encoding="utf-8" - ) - billing = tmp_path / "src" / "billing" - billing.mkdir() - (billing / "__init__.py").write_text(DECLARATION, encoding="utf-8") - (billing / "settings.toml").write_text('[default]\nmodel_name = "y"\n', encoding="utf-8") + project = _project(tmp_path, agent_map=_agent() + _agent("billing")) + _agent_dir(project, "orders", '[default]\napp_port = 8000\nevent_bus = "nats"\nmodel_name = "x"\n') + _agent_dir(project, "billing", '[default]\nmodel_name = "y"\n') _, warnings, _ = _group_findings(project) @@ -161,42 +179,45 @@ def _with_scheduler(self, project: Path) -> Path: (schedulers / "cleanup_scheduler.py").write_text("# scheduler", encoding="utf-8") return project + @staticmethod + def _findings(project: Path) -> tuple[list[str], list[str], list[str]]: + return root_findings(project, ProcessSettings.load(project)) + def test_a_project_with_no_schedulers_is_asked_nothing(self, tmp_path: Path) -> None: - issues, _, notices = _group_findings(_project(tmp_path, agent_map=_agent())) + issues, _, notices = self._findings(_project(tmp_path, settings="[default]\n")) assert (issues, notices) == ([], []) def test_a_scheduler_without_a_mode_is_an_issue(self, tmp_path: Path) -> None: """It has no default because neither value is safe to inherit, so build() fails.""" - project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings='[default]\napp_name = "demo"\n')) + project = self._with_scheduler(_project(tmp_path, settings='[default]\napp_name = "demo"\n')) - issues, _, _ = _group_findings(project) + issues, _, _ = self._findings(project) assert "no 'scheduler_mode'" in issues[0] def test_an_unknown_mode_is_an_issue(self, tmp_path: Path) -> None: - project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings='[default]\nscheduler_mode = "cron"\n')) + project = self._with_scheduler(_project(tmp_path, settings='[default]\nscheduler_mode = "cron"\n')) - issues, _, _ = _group_findings(project) + issues, _, _ = self._findings(project) assert "must be one of" in issues[0] def test_event_mode_says_that_nothing_here_publishes_the_tick(self, tmp_path: Path) -> None: """The silent-failure case: a scheduler waiting for a tick nobody publishes is healthy.""" - settings = '[default]\nscheduler_mode = "event"\nevent_bus = "nats"\n' - project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings=settings)) + settings = '[default]\nscheduler_mode = "event"\nevent_bus = "nats"\nnats_url = "nats://b:4222"\napp_name = "demo"\n' + project = self._with_scheduler(_project(tmp_path, settings=settings)) - issues, _, notices = _group_findings(project) + issues, _, notices = self._findings(project) assert issues == [] - assert len(notices) == 1 - assert "CronJob" in notices[0] + assert any("CronJob" in notice for notice in notices) def test_event_mode_without_a_bus_in_this_file_is_a_notice(self, tmp_path: Path) -> None: """S27 -- event_bus is a process-scope key: the group's settings or the environment may set it.""" - project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings='[default]\nscheduler_mode = "event"\n')) + project = self._with_scheduler(_project(tmp_path, settings='[default]\nscheduler_mode = "event"\n')) - issues, _, notices = _group_findings(project) + issues, _, notices = self._findings(project) assert issues == [] assert any("no 'event_bus' is set" in notice for notice in notices) @@ -204,18 +225,18 @@ def test_event_mode_without_a_bus_in_this_file_is_a_notice(self, tmp_path: Path) def test_event_mode_on_a_bus_that_cannot_deliver_a_tick_is_an_issue(self, tmp_path: Path) -> None: """S27 (a) -- the runtime needs a topic transport; 'sessions' is present but delivers no tick.""" settings = '[default]\nscheduler_mode = "event"\nevent_bus = "sessions"\n' - project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings=settings)) + project = self._with_scheduler(_project(tmp_path, settings=settings)) - issues, _, _ = _group_findings(project) + issues, _, _ = self._findings(project) assert any("'event_bus' is 'sessions', which cannot deliver a tick" in issue for issue in issues) def test_the_mode_is_read_as_the_runtime_reads_it(self, tmp_path: Path) -> None: """S27 (e) -- 'Event' runs; validate refused it.""" - settings = '[default]\nscheduler_mode = " Event "\nevent_bus = "nats"\n' - project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings=settings)) + settings = '[default]\nscheduler_mode = " Event "\nevent_bus = "nats"\nnats_url = "nats://b:4222"\napp_name = "demo"\n' + project = self._with_scheduler(_project(tmp_path, settings=settings)) - issues, _, _ = _group_findings(project) + issues, _, _ = self._findings(project) assert issues == [] @@ -223,27 +244,28 @@ def test_an_environment_override_counts(self, tmp_path: Path, monkeypatch: pytes """S27 (c) -- a value the deployment supplies is not missing.""" monkeypatch.setenv("DYNACONF_SCHEDULER_MODE", "event") monkeypatch.setenv("DYNACONF_EVENT_BUS", "nats") - project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings='[default]\napp_name = "demo"\n')) + monkeypatch.setenv("DYNACONF_NATS_URL", "nats://b:4222") + project = self._with_scheduler(_project(tmp_path, settings='[default]\napp_name = "demo"\n')) - issues, _, notices = _group_findings(project) + issues, _, notices = self._findings(project) assert issues == [] assert not any("no 'event_bus'" in notice for notice in notices) def test_in_process_mode_without_a_cache_says_every_replica_runs_every_tick(self, tmp_path: Path) -> None: settings = '[default]\nscheduler_mode = "in_process"\n' - project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings=settings)) + project = self._with_scheduler(_project(tmp_path, settings=settings)) - _, _, notices = _group_findings(project) + _, _, notices = self._findings(project) assert len(notices) == 1 assert "every replica runs every tick" in notices[0] - def test_in_process_mode_with_a_cache_is_quiet(self, tmp_path: Path) -> None: - settings = '[default]\nscheduler_mode = "in_process"\n' + def test_in_process_mode_with_a_redis_cache_is_quiet(self, tmp_path: Path) -> None: + settings = '[default]\nscheduler_mode = "in_process"\n[default.cache]\nbackend = "redis"\n' main = "agent = AppBuilder().with_cache()\n" - project = self._with_scheduler(_project(tmp_path, agent_map=_agent(), settings=settings, main=main)) + project = self._with_scheduler(_project(tmp_path, settings=settings, main=main)) - _, _, notices = _group_findings(project) + _, _, notices = self._findings(project) assert notices == [] diff --git a/tests/unit/agent_generator/cli/commands/test_validate_group_runtime.py b/tests/unit/agent_generator/cli/commands/test_validate_group_runtime.py new file mode 100644 index 00000000..4382d3a9 --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_validate_group_runtime.py @@ -0,0 +1,279 @@ +"""`asbs validate --group` reports what the image's process refuses or warns about at startup. + +The group file is resolved by the runtime's own ``GroupConfig.resolve_at`` against a stub +environment, so its refusals arrive in the runtime's words. The per-agent checks run on each +agent's resolved view: its own scope (the image's ``[default.]``, its ``.secrets.toml``, its +``settings.toml``), then the image's root keys -- the order ``Config`` resolves them in. +""" + +from pathlib import Path + +import pytest + +from blueprint.agent_generator.cli.commands.validate_group import image_findings + +DECLARATION = "from blueprint.agents.app_builder import AppBuilder\n\nagent = AppBuilder()\n" +CACHED = "from blueprint.agents.app_builder import AppBuilder\n\nagent = AppBuilder().with_cache()\n" + + +@pytest.fixture(autouse=True) +def _no_ambient_group(monkeypatch: pytest.MonkeyPatch) -> None: + for name in ( + "BLUEPRINT_GROUP", + "BLUEPRINT_AGENTS", + "BLUEPRINT_CRITICAL_AGENTS", + "BLUEPRINT_GROUP_CONFIG", + "BLUEPRINT_AGENT_MAP", + "DYNACONF_APP_ENVIRONMENT", + "DYNACONF_NATS_URL", + ): + monkeypatch.delenv(name, raising=False) + + +def _agent(image: Path, name: str, *, settings: str = '[default]\nmodel_name = "x"\n', main: str = DECLARATION) -> Path: + root = image / "agents" / name + (root / "src").mkdir(parents=True, exist_ok=True) + (root / "src" / "main.py").write_text(main, encoding="utf-8") + (root / "settings.toml").write_text(settings, encoding="utf-8") + return root + + +def _image(tmp_path: Path, *names: str, image_settings: str = '[default]\napp_name = "group"\n') -> Path: + entries = "".join(f'[agents.{name}]\nroot = "agents/{name}"\nmodule = "agents.{name}.src.main:agent"\n' for name in names) + (tmp_path / "agents.toml").write_text(entries, encoding="utf-8") + (tmp_path / "settings.toml").write_text(image_settings, encoding="utf-8") + for name in names: + if not (tmp_path / "agents" / name).is_dir(): + _agent(tmp_path, name) + return tmp_path + + +def _findings(image: Path, **kwargs: object) -> tuple[list[str], list[str], list[str]]: + return image_findings(image, image / "agents.toml", **kwargs) # type: ignore[arg-type] + + +class TestTheAgentMap: + def test_an_empty_map_is_an_issue(self, tmp_path: Path) -> None: + """Audit 1e: a warning, for an image that cannot start.""" + (tmp_path / "agents.toml").write_text("# nothing yet\n", encoding="utf-8") + + issues, _, _ = _findings(tmp_path) + + assert any("declares no [agents.] entries" in issue for issue in issues) + + def test_a_module_missing_from_the_image_is_an_issue(self, tmp_path: Path) -> None: + image = _image(tmp_path, "orders") + (image / "agents.toml").write_text( + '[agents.orders]\nroot = "agents/orders"\nmodule = "agents.orders.src.nowhere:agent"\n', encoding="utf-8" + ) + + issues, _, _ = _findings(image) + + assert any("is not a module in this image" in issue for issue in issues) + + def test_a_module_that_assigns_no_such_attribute_is_an_issue(self, tmp_path: Path) -> None: + image = _image(tmp_path, "orders") + (image / "agents.toml").write_text( + '[agents.orders]\nroot = "agents/orders"\nmodule = "agents.orders.src.main:registration"\n', encoding="utf-8" + ) + + issues, _, _ = _findings(image) + + assert any("assigns no 'registration'" in issue for issue in issues) + + +class TestTheGroupFile: + """Audit 1a-1d: the group file was never read.""" + + def _with_groups(self, tmp_path: Path, groups: str) -> Path: + image = _image(tmp_path, "orders", "billing") + (image / "deployment-groups.yaml").write_text(groups, encoding="utf-8") + return image + + def test_no_group_file_and_no_environment_is_a_notice_not_an_issue(self, tmp_path: Path) -> None: + issues, _, notices = _findings(_image(tmp_path, "orders")) + + assert issues == [] + assert any("No group file" in notice for notice in notices) + + def test_a_well_formed_file_passes(self, tmp_path: Path) -> None: + image = self._with_groups(tmp_path, "groups:\n - name: finance\n agents: [orders, billing]\n critical_agents: [orders]\n") + + issues, warnings, _ = _findings(image) + + assert (issues, warnings) == ([], []) + + def test_a_scalar_agent_list_is_an_issue(self, tmp_path: Path) -> None: + image = self._with_groups(tmp_path, "groups:\n - name: finance\n agents: orders\n") + + issues, _, _ = _findings(image) + + assert any("must be a list of agent names" in issue for issue in issues) + + def test_a_duplicate_group_name_is_an_issue(self, tmp_path: Path) -> None: + image = self._with_groups(tmp_path, "groups:\n - name: a\n agents: [orders]\n - name: a\n agents: [billing]\n") + + issues, _, _ = _findings(image) + + assert any("more than once" in issue for issue in issues) + + def test_an_unknown_critical_name_is_an_issue(self, tmp_path: Path) -> None: + image = self._with_groups(tmp_path, "groups:\n - name: finance\n agents: [orders]\n critical_agents: [ordres]\n") + + issues, _, _ = _findings(image) + + assert any("'critical_agents'" in issue and "ordres" in issue for issue in issues) + + def test_a_critical_agent_missing_from_the_map_is_an_issue(self, tmp_path: Path) -> None: + image = self._with_groups(tmp_path, "groups:\n - name: finance\n agents: [orders, shipping]\n") + + issues, _, _ = _findings(image) + + assert any("names agent 'shipping', which this image does not contain" in issue for issue in issues) + + def test_a_non_critical_agent_missing_from_the_map_is_a_warning(self, tmp_path: Path) -> None: + image = self._with_groups(tmp_path, "groups:\n - name: finance\n agents: [orders, shipping]\n critical_agents: [orders]\n") + + issues, warnings, _ = _findings(image) + + assert issues == [] + assert any("'shipping'" in warning and "skipped" in warning for warning in warnings) + + def test_an_empty_group_is_an_issue(self, tmp_path: Path) -> None: + image = self._with_groups(tmp_path, "groups:\n - name: finance\n agents: []\n") + + issues, _, _ = _findings(image) + + assert any("No agents were resolved" in issue for issue in issues) + + def test_every_group_of_a_multi_group_file_is_checked(self, tmp_path: Path) -> None: + image = self._with_groups(tmp_path, "groups:\n - name: a\n agents: [orders]\n - name: b\n agents: [nobody]\n") + + issues, _, _ = _findings(image) + + assert len(issues) == 1 + assert "Group 'b'" in issues[0] + + def test_a_group_name_restricts_the_check_to_that_group(self, tmp_path: Path) -> None: + image = self._with_groups(tmp_path, "groups:\n - name: a\n agents: [orders]\n - name: b\n agents: [nobody]\n") + + issues, _, _ = _findings(image, group_name="a") + + assert issues == [] + + def test_the_file_can_be_named_explicitly(self, tmp_path: Path) -> None: + image = _image(tmp_path, "orders") + (image / "deploy").mkdir() + (image / "deploy" / "finance.yaml").write_text("groups:\n - name: finance\n agents: orders\n", encoding="utf-8") + + issues, _, _ = _findings(image, group_config="deploy/finance.yaml") + + assert any("must be a list of agent names" in issue for issue in issues) + + def test_an_agent_list_from_the_environment_is_resolved_too(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("BLUEPRINT_AGENTS", "orders,shipping") + + issues, _, _ = _findings(_image(tmp_path, "orders")) + + assert any("'shipping'" in issue for issue in issues) + + +class TestSettingsTheMergeDrops: + """Audit 3b/3d: what the merge refuses or drops, including the agent's .secrets.toml.""" + + def test_a_deployment_identity_key_in_an_agent_file_is_warned(self, tmp_path: Path) -> None: + image = _image(tmp_path, "orders") + (image / "agents" / "orders" / "settings.toml").write_text('[default]\nhostname = "pod-1"\n', encoding="utf-8") + + _, warnings, _ = _findings(image) + + assert any("hostname" in warning for warning in warnings) + + def test_a_process_key_in_an_agent_secrets_file_is_warned_without_its_value(self, tmp_path: Path) -> None: + image = _image(tmp_path, "orders") + (image / "agents" / "orders" / ".secrets.toml").write_text( + '[default]\napp_port = 9000\nmodel_api_key = "s3cr3t"\n', encoding="utf-8" + ) + + _, warnings, _ = _findings(image) + + found = [warning for warning in warnings if "app_port" in warning] + assert found and ".secrets.toml" in found[0] + assert not any("s3cr3t" in warning or "9000" in warning for warning in warnings) + + def test_a_secrets_file_scoped_under_the_agents_own_name_is_an_issue(self, tmp_path: Path) -> None: + image = _image(tmp_path, "orders") + (image / "agents" / "orders" / ".secrets.toml").write_text('[default.orders]\nmodel_api_key = "x"\n', encoding="utf-8") + + issues, _, _ = _findings(image) + + assert any("scopes its own settings under its own name" in issue and ".secrets.toml" in issue for issue in issues) + + def test_an_image_key_named_like_an_agent_that_is_not_a_table_is_an_issue(self, tmp_path: Path) -> None: + image = _image(tmp_path, "orders", image_settings='[default]\napp_name = "group"\norders = "scalar"\n') + + issues, _, _ = _findings(image) + + assert any("cannot have settings of its own" in issue for issue in issues) + + +class TestPerAgentRuntimeChecks: + def test_an_image_nats_value_the_runtime_refuses_is_an_issue(self, tmp_path: Path) -> None: + """Audit 12f: '--group' parsed no NATS key at all.""" + image = _image(tmp_path, "orders", image_settings='[default]\napp_name = "group"\nnats_handler_timeout = -1\n') + + issues, _, _ = _findings(image) + + assert len([issue for issue in issues if "nats_handler_timeout" in issue]) == 1, "reported once, not per agent" + + def test_an_agent_nats_value_is_reported_for_that_agent(self, tmp_path: Path) -> None: + image = _image(tmp_path, "orders") + (image / "agents" / "orders" / "settings.toml").write_text("[default]\nnats_max_concurrent_runs = 0\n", encoding="utf-8") + + issues, _, _ = _findings(image) + + assert any(issue.startswith("Agent 'orders'") and "nats_max_concurrent_runs" in issue for issue in issues) + + def test_dedup_without_a_ttl_in_an_agent_is_an_issue(self, tmp_path: Path) -> None: + image = _image(tmp_path, "orders") + _agent(image, "orders", settings="[default]\nidempotency_enabled = true\n", main=CACHED) + (image / "agents" / "orders" / "src" / "handlers").mkdir() + (image / "agents" / "orders" / "src" / "handlers" / "order_handler.py").write_text("# h\n", encoding="utf-8") + + issues, _, _ = _findings(image) + + assert any("Agent 'orders'" in issue and "'idempotency_ttl' is not set" in issue for issue in issues) + + def test_nats_without_a_url_is_an_issue_per_consuming_agent(self, tmp_path: Path) -> None: + image = _image(tmp_path, "orders", image_settings='[default]\napp_name = "group"\nevent_bus = "nats"\n') + (image / "agents" / "orders" / "src" / "handlers").mkdir() + (image / "agents" / "orders" / "src" / "handlers" / "order_handler.py").write_text("# h\n", encoding="utf-8") + + issues, _, _ = _findings(image) + + assert any("Agent 'orders'" in issue and "'nats_url' is not set" in issue for issue in issues) + + def test_a_shared_dapr_topic_without_dedup_is_warned(self, tmp_path: Path) -> None: + """Audit 6: the runtime warns at startup that one retry redelivers to every agent.""" + image = _image(tmp_path, "orders", "billing", image_settings='[default]\napp_name = "group"\nevent_bus = "dapr"\n') + source = "class H:\n def get_subscribed_topics(self) -> list[str]:\n return ['invoices']\n" + for name in ("orders", "billing"): + (image / "agents" / name / "src" / "handlers").mkdir() + (image / "agents" / name / "src" / "handlers" / "invoice_handler.py").write_text(source, encoding="utf-8") + + _, warnings, _ = _findings(image) + + assert any("Topic 'invoices' is declared by agents" in warning for warning in warnings) + + def test_an_agents_crontab_is_checked_in_its_mode(self, tmp_path: Path) -> None: + image = _image(tmp_path, "orders") + _agent(image, "orders", settings='[default]\nscheduler_mode = "in_process"\n', main=CACHED) + schedulers = image / "agents" / "orders" / "src" / "schedulers" + schedulers.mkdir() + (schedulers / "nightly_scheduler.py").write_text( + "class S:\n def __init__(self):\n super().__init__(crontab='0 0 * * 7')\n", encoding="utf-8" + ) + + issues, _, _ = _findings(image) + + assert any("Agent 'orders'" in issue and "names day 7" in issue for issue in issues) diff --git a/tests/unit/agent_generator/cli/commands/test_validate_nats.py b/tests/unit/agent_generator/cli/commands/test_validate_nats.py index e9da4d5e..d41cb73c 100644 --- a/tests/unit/agent_generator/cli/commands/test_validate_nats.py +++ b/tests/unit/agent_generator/cli/commands/test_validate_nats.py @@ -51,10 +51,16 @@ def test_a_value_startup_would_refuse_is_an_issue_naming_the_key(self, tmp_path: assert len(findings) == 1 assert named in findings[0] - def test_a_key_in_an_agent_section_is_checked_too(self, tmp_path: Path) -> None: - findings = _nats_findings(_project(tmp_path, "[orders]\nnats_max_concurrent_runs = 0\n")) + def test_a_key_in_the_target_environment_section_is_checked(self, tmp_path: Path) -> None: + findings = _nats_findings(_project(tmp_path, "[production]\nnats_max_concurrent_runs = 0\n")) assert findings and "nats_max_concurrent_runs" in findings[0] + def test_a_key_in_another_environment_section_is_not(self, tmp_path: Path) -> None: + """'[orders]' in the process's own file is an environment named orders to Dynaconf, not a scope.""" + assert _nats_findings(_project(tmp_path, "[orders]\nnats_max_concurrent_runs = 0\n")) == [] + assert _nats_findings(_project(tmp_path, "[development]\nnats_max_concurrent_runs = 0\n")) == [] + assert _nats_findings(_project(tmp_path, "[development]\nnats_max_concurrent_runs = 0\n"), "development") != [] + class TestConnectionSource: def test_a_path_without_an_attribute_is_an_issue(self, tmp_path: Path) -> None: diff --git a/tests/unit/agent_generator/cli/commands/test_validate_runtime_parity.py b/tests/unit/agent_generator/cli/commands/test_validate_runtime_parity.py new file mode 100644 index 00000000..8609280e --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_validate_runtime_parity.py @@ -0,0 +1,317 @@ +"""`asbs validate` reports what the runtime refuses or warns about at startup, on the runtime's terms. + +Each test here pins one disagreement the audit found between the validator and a process started +from the same files: a verdict of "valid" for a project whose production pod would not start, or a +warning the pod logs that the validator never mentioned. The validator reads files only, so every +rule is the runtime's own function wherever one exists (``validate_crontab``, ``parse_bool``, +``layer_settings_document``, ``validate_subject_segment``, Dynaconf's environment layering). +""" + +from pathlib import Path + +import pytest + +from blueprint.agent_generator.cli.commands.validate import ( + IDEMPOTENCY_NOTICE, + ProcessSettings, + root_findings, +) + +CACHED = "from blueprint.agents.app_builder import AppBuilder\n\nagent = AppBuilder().with_cache()\n" +UNCACHED = "from blueprint.agents.app_builder import AppBuilder\n\nagent = AppBuilder()\n" + + +@pytest.fixture(autouse=True) +def _no_ambient_overrides(monkeypatch: pytest.MonkeyPatch) -> None: + """The validator reads the environment as the process does; a developer's shell must not leak in.""" + for name in ("DYNACONF_APP_ENVIRONMENT", "DYNACONF_NATS_URL", "DYNACONF_EVENT_BUS", "DYNACONF_SCHEDULER_MODE"): + monkeypatch.delenv(name, raising=False) + + +def _project( + tmp_path: Path, + settings: str, + *, + main: str = UNCACHED, + handler: bool = False, + scheduler: str | None = None, + handler_source: str = "# handler\n", +) -> Path: + (tmp_path / "src").mkdir(exist_ok=True) + (tmp_path / "src" / "main.py").write_text(main, encoding="utf-8") + (tmp_path / "settings.toml").write_text(settings, encoding="utf-8") + if handler: + (tmp_path / "src" / "handlers").mkdir(exist_ok=True) + (tmp_path / "src" / "handlers" / "order_handler.py").write_text(handler_source, encoding="utf-8") + if scheduler is not None: + (tmp_path / "src" / "schedulers").mkdir(exist_ok=True) + (tmp_path / "src" / "schedulers" / "nightly_scheduler.py").write_text(scheduler, encoding="utf-8") + return tmp_path + + +def _findings(project: Path, environment: str | None = None) -> tuple[list[str], list[str], list[str]]: + return root_findings(project, ProcessSettings.load(project, environment)) + + +def _scheduler(crontab: str) -> str: + return ( + "from blueprint.agents.io.api.scheduling.scheduler import SchedulerBase\n\n\n" + "class NightlyScheduler(SchedulerBase):\n" + " def __init__(self) -> None:\n" + f' super().__init__(crontab="{crontab}")\n\n' + " async def tick(self) -> None:\n" + " pass\n" + ) + + +class TestTheTargetEnvironment: + """Audit 3a: a key in any section counted, so a production pod failed on a 'valid' project.""" + + def test_the_default_target_is_production_what_both_dockerfiles_set(self, tmp_path: Path) -> None: + assert ProcessSettings.load(_project(tmp_path, "[default]\n")).environment == "production" + + def test_a_scheduler_mode_set_only_for_development_is_missing_in_production(self, tmp_path: Path) -> None: + project = _project(tmp_path, '[development]\nscheduler_mode = "in_process"\n', scheduler=_scheduler("0 * * * *")) + + issues, _, _ = _findings(project) + + assert any("no 'scheduler_mode'" in issue for issue in issues) + + def test_the_same_project_is_valid_for_development(self, tmp_path: Path) -> None: + project = _project(tmp_path, '[development]\nscheduler_mode = "in_process"\n', scheduler=_scheduler("0 * * * *")) + + issues, _, _ = _findings(project, "development") + + assert not [issue for issue in issues if "scheduler_mode" in issue] + + def test_the_environment_variable_selects_the_section_when_no_option_does( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.setenv("DYNACONF_APP_ENVIRONMENT", "development") + project = _project(tmp_path, '[development]\nscheduler_mode = "in_process"\n', scheduler=_scheduler("0 * * * *")) + + assert ProcessSettings.load(project).environment == "development" + issues, _, _ = _findings(project) + assert not [issue for issue in issues if "scheduler_mode" in issue] + + def test_a_top_level_key_outside_any_section_is_read_by_nothing(self, tmp_path: Path) -> None: + """Dynaconf in environment mode loads [default], [] and [global] -- nothing else.""" + settings = ProcessSettings.load(_project(tmp_path, 'idempotency_enabled = true\nenvvar_prefix = "DYNACONF"\n[default]\n')) + + warnings = settings.unread_key_warnings() + + assert len(warnings) == 1 + assert "idempotency_enabled" in warnings[0] + assert "envvar_prefix" not in warnings[0], "The prefix must be a top-level key; it is read there." + assert settings.root_view().get("idempotency_enabled") is None + + def test_a_nats_value_in_an_inactive_section_is_not_checked(self, tmp_path: Path) -> None: + project = _project(tmp_path, "[development]\nnats_handler_timeout = -1\n") + + issues, _, _ = _findings(project) + + assert not [issue for issue in issues if "nats_handler_timeout" in issue] + + +class TestDeduplication: + """Audit 5a/5b: dedup without a ttl or a cache failed startup and validated clean.""" + + def test_the_notice_names_the_cache(self) -> None: + assert ".with_cache()" in IDEMPOTENCY_NOTICE + + def test_enabled_without_a_ttl_is_an_issue(self, tmp_path: Path) -> None: + project = _project(tmp_path, "[default]\nidempotency_enabled = true\n", main=CACHED, handler=True) + + issues, _, _ = _findings(project) + + assert any("'idempotency_ttl' is not set" in issue for issue in issues) + + @pytest.mark.parametrize("ttl", ["0", "-5", '"soon"']) + def test_a_ttl_the_runtime_refuses_is_an_issue(self, tmp_path: Path, ttl: str) -> None: + project = _project(tmp_path, f"[default]\nidempotency_enabled = true\nidempotency_ttl = {ttl}\n", main=CACHED, handler=True) + + issues, _, _ = _findings(project) + + assert any("idempotency_ttl" in issue for issue in issues) + + def test_enabled_without_a_cache_is_an_issue(self, tmp_path: Path) -> None: + project = _project(tmp_path, "[default]\nidempotency_enabled = true\nidempotency_ttl = 60\n", handler=True) + + issues, _, _ = _findings(project) + + assert any(".with_cache()" in issue for issue in issues) + + def test_a_complete_opt_in_is_clean(self, tmp_path: Path) -> None: + project = _project(tmp_path, "[default]\nidempotency_enabled = true\nidempotency_ttl = 60\n", main=CACHED, handler=True) + + issues, warnings, _ = _findings(project) + + assert issues == [] + assert not [warning for warning in warnings if "deduplicates" in warning] + + def test_a_non_boolean_switch_is_an_issue(self, tmp_path: Path) -> None: + project = _project(tmp_path, '[default]\nidempotency_enabled = "maybe"\n', main=CACHED, handler=True) + + issues, _, _ = _findings(project) + + assert any("must be a boolean" in issue for issue in issues) + + def test_dedup_without_the_nats_heartbeat_is_warned(self, tmp_path: Path) -> None: + settings = ( + '[default]\nidempotency_enabled = true\nidempotency_ttl = 60\nevent_bus = "nats"\nnats_heartbeat_enabled = false\n' + 'nats_url = "nats://broker:4222"\napp_name = "demo"\n' + ) + project = _project(tmp_path, settings, main=CACHED, handler=True) + + _, warnings, _ = _findings(project) + + assert any("'nats_heartbeat_enabled = false'" in warning for warning in warnings) + + def test_dedup_under_dapr_is_warned(self, tmp_path: Path) -> None: + settings = '[default]\nidempotency_enabled = true\nidempotency_ttl = 60\nevent_bus = "dapr"\n' + project = _project(tmp_path, settings, main=CACHED, handler=True) + + _, warnings, _ = _findings(project) + + assert any("under Dapr, which has no heartbeat" in warning for warning in warnings) + + def test_dedup_on_a_disk_cache_says_the_claim_holds_in_one_process(self, tmp_path: Path) -> None: + project = _project(tmp_path, "[default]\nidempotency_enabled = true\nidempotency_ttl = 60\n", main=CACHED, handler=True) + + _, _, notices = _findings(project) + + assert any("within one process" in notice and "redis" in notice for notice in notices) + + def test_dedup_on_redis_has_no_such_notice(self, tmp_path: Path) -> None: + settings = '[default]\nidempotency_enabled = true\nidempotency_ttl = 60\n[default.cache]\nbackend = "redis"\n' + project = _project(tmp_path, settings, main=CACHED, handler=True) + + _, _, notices = _findings(project) + + assert not [notice for notice in notices if "within one process" in notice] + + +class TestSchedulerExpressions: + """Audit 4a/4c: a crontab or timezone the runtime refuses validated clean.""" + + def test_day_seven_is_an_issue_in_either_mode(self, tmp_path: Path) -> None: + project = _project(tmp_path, '[default]\nscheduler_mode = "in_process"\n', main=CACHED, scheduler=_scheduler("0 0 * * 7")) + + issues, _, _ = _findings(project) + + assert any("names day 7" in issue for issue in issues) + + def test_a_numeric_weekday_in_event_mode_is_an_issue(self, tmp_path: Path) -> None: + settings = '[default]\nscheduler_mode = "event"\nevent_bus = "nats"\nnats_url = "nats://b:4222"\napp_name = "demo"\n' + project = _project(tmp_path, settings, scheduler=_scheduler("0 0 * * 1")) + + issues, _, _ = _findings(project) + + assert any("gives the day of the week by number" in issue for issue in issues) + + def test_a_numeric_weekday_in_process_is_fine(self, tmp_path: Path) -> None: + project = _project(tmp_path, '[default]\nscheduler_mode = "in_process"\n', main=CACHED, scheduler=_scheduler("0 0 * * 1")) + + issues, _, _ = _findings(project) + + assert issues == [] + + def test_an_expression_that_is_not_cron_is_an_issue(self, tmp_path: Path) -> None: + project = _project(tmp_path, '[default]\nscheduler_mode = "in_process"\n', main=CACHED, scheduler=_scheduler("every hour")) + + issues, _, _ = _findings(project) + + assert any("not a valid cron expression" in issue for issue in issues) + + def test_a_timezone_that_is_not_iana_is_an_issue_in_process(self, tmp_path: Path) -> None: + settings = '[default]\nscheduler_mode = "in_process"\nscheduler_timezone = "Mars/Olympus"\n' + project = _project(tmp_path, settings, main=CACHED, scheduler=_scheduler("0 * * * *")) + + issues, _, _ = _findings(project) + + assert any("not an IANA timezone name" in issue for issue in issues) + + def test_a_valid_timezone_is_fine(self, tmp_path: Path) -> None: + settings = '[default]\nscheduler_mode = "in_process"\nscheduler_timezone = "Europe/Berlin"\n' + project = _project(tmp_path, settings, main=CACHED, scheduler=_scheduler("0 * * * *")) + + issues, _, _ = _findings(project) + + assert issues == [] + + def test_in_process_on_a_disk_cache_does_not_promise_one_replica(self, tmp_path: Path) -> None: + project = _project(tmp_path, '[default]\nscheduler_mode = "in_process"\n', main=CACHED, scheduler=_scheduler("0 * * * *")) + + _, _, notices = _findings(project) + + assert any("within one process" in notice for notice in notices) + + +class TestTransport: + """Audit 12a and 15: an unset nats_url outside development, and handlers with no bus.""" + + def test_handlers_without_an_event_bus_are_warned(self, tmp_path: Path) -> None: + project = _project(tmp_path, '[default]\napp_name = "demo"\n', handler=True) + + _, warnings, _ = _findings(project) + + assert any("no valid event_bus" in warning for warning in warnings) + + def test_nats_without_a_url_in_production_is_an_issue(self, tmp_path: Path) -> None: + project = _project(tmp_path, '[default]\napp_name = "demo"\nevent_bus = "nats"\n', handler=True) + + issues, _, _ = _findings(project) + + assert any("'nats_url' is not set" in issue for issue in issues) + + def test_nats_without_a_url_in_development_falls_back(self, tmp_path: Path) -> None: + project = _project(tmp_path, '[default]\napp_name = "demo"\nevent_bus = "nats"\n', handler=True) + + issues, _, _ = _findings(project, "development") + + assert not [issue for issue in issues if "nats_url" in issue] + + def test_a_url_from_the_environment_counts(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("DYNACONF_NATS_URL", "nats://broker:4222") + project = _project(tmp_path, '[default]\napp_name = "demo"\nevent_bus = "nats"\n', handler=True) + + issues, _, _ = _findings(project) + + assert not [issue for issue in issues if "nats_url" in issue] + + def test_a_non_boolean_heartbeat_is_an_issue(self, tmp_path: Path) -> None: + settings = '[default]\napp_name = "demo"\nevent_bus = "nats"\nnats_url = "nats://b:4222"\nnats_heartbeat_enabled = "false"\n' + project = _project(tmp_path, settings, handler=True) + + issues, _, _ = _findings(project) + + assert any("'nats_heartbeat_enabled' must be true or false" in issue for issue in issues) + + def test_an_app_name_that_cannot_be_a_queue_group_is_an_issue(self, tmp_path: Path) -> None: + settings = '[default]\napp_name = "My Service"\nevent_bus = "nats"\nnats_url = "nats://b:4222"\n' + project = _project(tmp_path, settings, handler=True) + + issues, _, _ = _findings(project) + + assert any("The queue group (from 'app_name')" in issue for issue in issues) + + def test_one_durable_name_for_several_topics_is_an_issue(self, tmp_path: Path) -> None: + settings = ( + '[default]\napp_name = "demo"\nevent_bus = "nats"\nnats_url = "nats://b:4222"\nnats_use_jetstream = true\n' + 'nats_durable_name = "orders"\n' + ) + source = ( + "class OrderHandler:\n def get_subscribed_topics(self) -> list[str]:\n return ['orders.created', 'orders.paid']\n" + ) + project = _project(tmp_path, settings, handler=True, handler_source=source) + + issues, _, _ = _findings(project) + + assert any("'nats_durable_name' is set to 'orders' but 2 topics" in issue for issue in issues) + + def test_an_invalid_loop_debug_value_is_an_issue(self, tmp_path: Path) -> None: + project = _project(tmp_path, '[default]\nevent_loop_debug = "sometimes"\n') + + issues, _, _ = _findings(project) + + assert any("event_loop_debug" in issue for issue in issues) diff --git a/tests/unit/agent_generator/cli/test_generator_text.py b/tests/unit/agent_generator/cli/test_generator_text.py new file mode 100644 index 00000000..a6fd39a8 --- /dev/null +++ b/tests/unit/agent_generator/cli/test_generator_text.py @@ -0,0 +1,61 @@ +"""What the generator writes and prints must not contradict the runtime. + +Each of these held a sentence the runtime disproved: a disk cache "so one replica runs it" (its +claim holds within one process), dedup that needed only two keys (it needs ``.with_cache()`` too), +a ``debug`` key nothing reads, and a group Dockerfile calling a standalone agent "a group of one". +""" + +import sys +from pathlib import Path + +import pytest + +from blueprint.agent_generator.cli import main as cli_main +from blueprint.agent_generator.cli.commands import group_setup + +BASE_FILES = Path(cli_main.__file__).resolve().parent.parent / "base_files" + + +def _text(relative: str) -> str: + return (BASE_FILES / relative).read_text(encoding="utf-8") + + +class TestSettingsTemplate: + def test_the_dedup_comment_names_the_cache(self) -> None: + assert ".with_cache()" in _text("settings.txt").split("# idempotency_enabled")[0] + + def test_it_writes_no_key_nothing_reads(self) -> None: + assert "debug = true" not in _text("settings.txt") + + def test_a_disk_cache_is_not_said_to_coordinate_replicas(self) -> None: + text = " ".join(_text("settings.txt").split()) + assert "within one process" in text + assert "Redis" in text + + +class TestHandlerTemplate: + def test_the_dedup_comment_names_the_cache(self) -> None: + assert ".with_cache()" in _text("src/handlers/handler.txt") + + +class TestGroupFiles: + def test_the_group_dockerfile_does_not_call_a_standalone_agent_a_group(self) -> None: + assert "a standalone agent is a group of one" not in _text("group_Dockerfile") + + def test_the_group_dockerfile_says_where_an_agents_secrets_are_mounted(self) -> None: + assert "/app//.secrets.toml" in _text("group_Dockerfile") + + def test_the_group_settings_do_not_promise_one_replica_on_disk(self) -> None: + text = " ".join(group_setup.GROUP_SETTINGS.split()) + assert "within one process" in text + + +class TestDevHelp: + def test_the_description_says_an_agent_directory_is_served_alone( + self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] + ) -> None: + monkeypatch.setattr(sys, "argv", ["asbs", "dev", "--help"]) + with pytest.raises(SystemExit): + cli_main.main() + out = " ".join(capsys.readouterr().out.split()) + assert "alone" in out and "root namespace" in out From b032f0f1091a023cd23a97074f7434ba76dae801 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Tue, 20 Oct 2026 12:40:05 +0200 Subject: [PATCH 127/133] docs: docs, skills and the grouping spec match the code after the review fixes A read-only audit compared every user doc, the claude_docs skills, README, AGENTS, CONTRIBUTE and the grouping spec with the code after steps 1-21; each stale statement was corrected (shared volume, non-deterministic order, debug mode, disk-cache atomicity, declaration order, the standalone shape, the agent map). The spec records D23: deterministic NATS faults fail early in every agent; a missing binding-mode stream or consumer is deferred and listed under Known issues in the CHANGELOG. The CHANGELOG also describes the validator's new reading of settings. AGENTS.md cites the concept docs by their full path again. Plan: docs/plans/2026-10-16-pr96-review-fixes.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- AGENTS.md | 14 +- CHANGELOG.md | 95 +++-- CONTRIBUTE.md | 13 +- README.md | 39 +- docs/specs/2026-08-28-multi-agent-grouping.md | 348 +++++++++++++----- .../agent_generator/claude_docs/CLAUDE.md | 22 +- .../claude_docs/agents/blueprint-builder.md | 8 +- .../skills/blueprint-config/SKILL.md | 7 +- .../skills/blueprint-deployment/SKILL.md | 5 +- .../skills/blueprint-events/SKILL.md | 3 +- .../skills/blueprint-migration/SKILL.md | 5 +- .../skills/blueprint-multi-agent/SKILL.md | 23 +- .../skills/blueprint-testing/SKILL.md | 5 +- .../skills/blueprint-troubleshooting/SKILL.md | 7 +- .../agent_generator/docs/components/agents.md | 38 +- .../docs/components/event-handlers.md | 21 +- .../docs/components/rest-apis.md | 34 +- .../docs/components/schedulers.md | 129 ++++--- .../docs/components/services.md | 47 ++- .../docs/concepts/architecture.md | 6 +- .../agent_generator/docs/concepts/caching.md | 26 +- .../docs/concepts/configuration.md | 95 +++-- .../docs/concepts/event-processing.md | 18 +- .../docs/concepts/observability.md | 19 +- .../docs/guides/cli-reference.md | 2 +- .../agent_generator/docs/guides/cli/create.md | 110 ++++-- .../agent_generator/docs/guides/cli/dev.md | 46 ++- .../agent_generator/docs/guides/cli/naming.md | 2 +- .../agent_generator/docs/guides/cli/setup.md | 34 +- .../agent_generator/docs/guides/deployment.md | 73 ++-- .../docs/guides/multi-agent-migration.md | 9 +- .../docs/guides/multi-agent-setup.md | 65 ++-- .../agent_generator/docs/guides/testing.md | 197 +++++----- .../docs/guides/troubleshooting.md | 273 +++++++------- .../agent_generator/docs/reference/api.md | 38 +- .../docs/reference/configuration-keys.md | 63 +++- .../agent_generator/docs/reference/models.md | 19 +- 37 files changed, 1249 insertions(+), 709 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7293ac78..c7668808 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,9 +35,11 @@ scaffolder that generates projects against it. Inside the framework: | `config/` | `Config` (Dynaconf), the logging manager | | `models/` | Pydantic models: events, configuration, API payloads, status | -Prose for users lives in `docs/`: `src/blueprint/agent_generator/docs/concepts/architecture.md` for the assembly model, -`src/blueprint/agent_generator/docs/concepts/event-processing.md` for the dispatch pipeline, `src/blueprint/agent_generator/docs/concepts/configuration.md` -for settings, `docs/guides/` for deployment, testing and the CLI. Specifications and plans are in +Prose for users lives in `src/blueprint/agent_generator/docs/`: +`src/blueprint/agent_generator/docs/concepts/architecture.md` for the assembly model, +`src/blueprint/agent_generator/docs/concepts/event-processing.md` for the dispatch pipeline, +`src/blueprint/agent_generator/docs/concepts/configuration.md` for settings, +`src/blueprint/agent_generator/docs/guides/` for deployment, testing and the CLI. Specifications and plans are in `docs/specs/` and `docs/plans/`; a feature's changelog beside its plan is the running record of what was done and why. @@ -105,8 +107,10 @@ is simply absent from that surface, and only in the deployment shape nobody test `Component.configure`'s "already set" error, which names neither the builder nor the second call and sends the reader into framework internals. -**Group policy belongs to the collector.** Standalone stays permissive; the group refuses what it -cannot honour, at assembly, naming the agent and the fix. *Failure:* restrictions scattered into +**Group policy belongs to the collector.** The host refuses what a group cannot honour, at +assembly, naming the agent and the fix -- a group, and `build(config)` (what `create_app()` calls), +because a declaration served alone is the shape a group hosts. Only the old +`AppBuilder(config)...build()` shape stays permissive. *Failure:* restrictions scattered into the builder punish the single-agent case for constraints that only a group has. ### Namespaces and isolation diff --git a/CHANGELOG.md b/CHANGELOG.md index ac1564e7..31bbb382 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,7 @@ Full migration path, including the one decision to get right before the first de - `/api///trigger` becomes `/api//scheduler//trigger`. - Cache endpoints stay at `/api//cache/*`. - Every operation of a grouped agent is tagged with exactly the agent's name, replacing declared - tags and tagging untagged ones. In 0.9.0 an agent was split into `.` groups + tags and tagging untagged ones. In the 0.9.0 alphas an agent was split into `.` groups interleaved with other agents', and its untagged routes sat under "default" beside everyone else's. - `nats`, `cache` and `scheduler` under `/api//` are reserved: a grouped agent's own route @@ -47,7 +47,7 @@ Full migration path, including the one decision to get right before the first de defaults for deployments that had configured nothing. `nats_ack_wait`, `nats_max_ack_pending` and `nats_max_deliver` are now applied only when set; unset, the server's default stands (NATS: 30 s, 1000, unlimited). With `nats_max_deliver` unset, a message that keeps failing is retried without - limit and never dead-lettered, as before 0.9.0 -- set it to bound retries. Consumers that already + limit and never dead-lettered, as in 0.8 -- set it to bound retries. Consumers that already exist keep their settings, and an unset key is not reported as a difference. - **`ClientBase.subscribe()` callbacks take the delivery subject.** The contract is now `DeliveryCallback = Callable[[CloudEvent, str], Awaitable[None]]` (in `clients/client_base.py`): @@ -63,20 +63,20 @@ Full migration path, including the one decision to get right before the first de - **A process in development mode logs a WARNING at startup** that it is not suitable for production. `app_environment` defaults to `"development"`, so a deployment that sets nothing now says so in its own log. -- **`root` is required in `agents.toml`.** Every existing entry needs one line added; a map - without it refuses to start rather than guessing. For an image that copied one agent to `/app`, - that is `root = "."`. -- **The standalone image no longer runs the group entry point.** It serves +- **`root` is required in `agents.toml`.** Every entry of a map written for a 0.9.0 alpha needs + one line added; a map without it refuses to start rather than guessing. For an image that copied + one agent to `/app`, that is `root = "."`. +- **The standalone image does not run the group entry point** (the 0.9.0 alphas' did). It serves `src.main:create_app` directly. An existing project keeps working: `uvicorn src.main:app` is still served for a pre-split `main.py`, and a project that wants the old command can keep it. - **`agents.toml` inside an agent is refused unconditionally**, with no exception for an agent - mapped at the image root. That shape only existed to let a standalone agent be a group of one, - which it no longer has to be. -- **`asbs setup` no longer writes `agents.toml` into an agent.** The map says which agents an - *image* contains, which is a packaging decision -- an agent carrying one is an agent that knows - whether it is running alone. The single-agent `Dockerfile` writes a one-agent map into its own - image instead. Existing projects keep working; delete the file when the agent joins a group, - where it is refused. + mapped at the image root. That shape only existed in the 0.9.0 alphas, to let a standalone agent + be a group of one, which it no longer has to be. +- **`asbs setup` writes no `agents.toml` into an agent** (the 0.9.0 alphas did). The map says which + agents an *image* contains, which is a packaging decision -- an agent carrying one is an agent + that knows whether it is running alone. The single-agent `Dockerfile` reads no map either: it + serves `create_app()` at the root. An agent scaffolded by an alpha should delete the file; in a + group it is refused. - **The `src//main.py` group layout is retired.** An agent is now the same directory alone or in a group -- `/settings.toml` beside `/src/` -- which is what lets it move between repositories untouched. Multi-agent grouping has only ever shipped in 0.9.0 alphas, so @@ -85,8 +85,9 @@ Full migration path, including the one decision to get right before the first de `agent_namespace` helper moved to `PartGeneratorBase`. 1. **`scheduler_mode` is required.** A project that registers a scheduler and does not set it fails - at `build()`, with an error naming both values and what each costs. `"in_process"` reproduces - today's behaviour exactly and is the no-op migration; `"event"` is the one that fixes #73. + at `build()`, with an error naming both values and what each costs. `"in_process"` keeps 0.8's + in-process timer and is the smallest migration (it now claims each tick, see 13); `"event"` is + the one that fixes #73. Defaulting the key would either keep firing a timer per replica or silently stop ticking a service with no broker, and neither is safe to inherit. 2. **A subject-unsafe `app_name` or `nats_queue_group` now fails at startup** instead of being @@ -119,8 +120,9 @@ Full migration path, including the one decision to get right before the first de 7. **Four declaration surfaces are deleted**: `AgentRegistration`, `RegisteredComponent`, `NamespaceBuilder`, and `AppBuilder.with_namespace` / `with_registration`. `AppBuilder` is the one declaration surface; `AgentGroup` collects named declarations into a process. Passing an - already-built component instance (`with_service(MyService())`) still works for a single standalone - agent and is refused in a group — pass the class, or a zero-argument factory. + already-built component instance (`with_service(MyService())`) still works in the old + `AppBuilder(config)...build()` shape, and is refused by `build(config)` -- what `create_app()` + calls -- and in a group: pass the class, or a zero-argument factory. 8. **`ClientBase.subscribe` changed from `(topic, callback)` to `(topic_callbacks)`**, and `EventHandlingBase.subscribe` and `POST /nats/subscribe/{topic}` are removed. This affects third-party transport implementations; both in-repo clients are updated. @@ -151,7 +153,8 @@ Full migration path, including the one decision to get right before the first de 13. **A scheduler tick runs in one replica, not in every one.** Before, every replica -- and every worker -- ran its own timer and each ran every tick. Now `scheduler_mode = "event"` delivers the tick through the queue group to one replica, and `"in_process"` claims each tick in the cache so - one replica runs it. A deployment that relied on every replica running a tick in parallel -- a + one replica runs it -- across replicas only on a Redis cache, since a disk cache's claim holds + within one process. A deployment that relied on every replica running a tick in parallel -- a per-pod cleanup, say -- now runs it once per tick; register the cache per pod, or do the per-pod work outside the scheduler. Without a registered cache, `"in_process"` still runs every tick in every replica, and says so with a WARNING at startup where it used to log an INFO. @@ -275,8 +278,9 @@ Full migration path, including the one decision to get right before the first de and a group Dockerfile -- and creates no agent. - **`asbs validate --group`** validates an image: every `root`, each agent's layout, misplaced files, process-wide keys left in an agent, and which `settings.toml` each agent actually reads. -- **`asbs dev --name`**, and `asbs dev` no longer needs an `agents.toml` in an agent's directory. - It writes the one-agent map outside the project for that run. +- **`asbs dev --name`** serves an agent directory under the namespace a group image would give it, + writing the one-agent map outside the project for that run. Without `--name`, an agent directory + is served alone at the root through its `create_app()`; it needs no `agents.toml`. - **The documentation ships inside the package.** The user-facing guides moved from the repository root to `src/blueprint/agent_generator/docs/` and are now installed with the wheel, so a @@ -310,8 +314,9 @@ Full migration path, including the one decision to get right before the first de - **Per-agent observability.** `service.name` per agent, `blueprint_namespace_up{agent}`, a readiness entry and health checks attributed per agent, `blueprint.scheduler.tick_age_seconds`, `blueprint.events.dead_lettered`, `blueprint.events.unhandled` and `blueprint.events.duplicate`. -- **`CacheService.claim`** — set-if-absent, atomic on both backends (`add` on disk, `SET NX EX` on - Redis). This is the compare-and-set primitive the deduplication work flagged as missing. +- **`CacheService.claim`** — set-if-absent: atomic on Redis (`SET NX EX`), and on disk (`add`) + atomic within one process only. This is the compare-and-set primitive the deduplication work + flagged as missing. - **Named caches.** `with_cache(name=...)`, `/cache/*` endpoints take `?name=`, and `/readiness` gains a `cache:` entry per named cache. - **Opt-in event deduplication** — `idempotency_enabled` and a required `idempotency_ttl`. Off by @@ -320,13 +325,13 @@ Full migration path, including the one decision to get right before the first de with `nats_publish_subjects` for subjects not already in `event_publishing.topic_mapping`. Unset, it follows `nats_use_jetstream`, so nothing existing changes. - **`run_app`**, so a project can serve itself from its own settings. -- **Scaffolding**: `asbs setup` now writes `agents.toml`, a `pyproject.toml` and two tests, so +- **Scaffolding**: `asbs setup` now writes a `pyproject.toml` and two tests, so `asbs setup` → `pytest` → `asbs validate` closes; `asbs validate` reports what a project has not said about grouping and about idempotency; the CLI no longer crashes on a Windows console. - New config keys: `event_client_drain_timeout`, `dapr_pubsub_name`, `dapr_declarative_subscriptions`, `idempotency_enabled`, `idempotency_ttl`, `scheduler_mode`, `event_publishing_enabled`, `nats_publish_mode`, `nats_publish_subjects`. All default to current - behaviour except `scheduler_mode`, which is required — see below. + 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. @@ -380,9 +385,10 @@ Full migration path, including the one decision to get right before the first de - **`diskcache-rs` 0.4.10 is the minimum, and a disk cache's claim is documented as per-process** (S23). 0.4.9 and earlier refused a second process the cache directory ("Database already open"). 0.4.10 lets several open it, but its set-if-absent is not atomic between them: four processes - claiming one key at once each won in 297 of 300 rounds. Deduplication and the in-process tick - claim therefore hold across replicas, and across several `app_workers`, only with Redis; the docs no - longer say "a disk cache on a shared volume". + claiming one key at once each won in 297 of 300 rounds. A disk cache's claim therefore holds + within one process: replicas sharing a cache directory (or `uvicorn --workers N` run by hand) can + both win one deduplication marker or one in-process tick, and a claim across replicas needs + Redis. The docs no longer say "a disk cache on a shared volume". - **A standalone application written for 0.8 builds again** (S20). Three 0.8 shapes were refused or changed: @@ -495,6 +501,18 @@ Full migration path, including the one decision to get right before the first de a tick, reports a missing `event_bus` as a notice (it is a process-wide key and may be set elsewhere), and `--group` runs the scheduler checks per agent. +- **`asbs validate` reads settings the way the process does, for one environment.** The target is + `--environment`, else `DYNACONF_APP_ENVIRONMENT` (or `_APP_ENVIRONMENT`), else + `production` -- what the scaffolded Dockerfiles set; use `--environment development` for what + `asbs dev` runs. A key set only in another environment's section counts as unset, and a key + written outside any section is warned about (the process loads none of them). Each agent's + `.secrets.toml` and `settings.toml` are layered as the runtime layers them, and `--group` + resolves the group file as the runtime does (`--group-config`, `--group-name`). Newly reported: + crontab and timezone errors, deduplication without a ttl or a cache, a missing `nats_url` + outside development, a non-boolean heartbeat or `event_loop_debug`, an empty agent map, and the + runtime's group-file refusals in its own words. Of 19 cases measured on fresh scaffolds where the + process refuses to start or warns, the validator used to report 1; it reports all 19. + - **A grouped scheduler's tick subject and trigger route name the agent once.** Both were built from the scheduler's qualified name, so the subject was `orders.scheduler.orders_nightly` and the route `/api/orders/scheduler/orders_nightly/trigger`; they are now `orders.scheduler.nightly` and @@ -700,8 +718,9 @@ Full migration path, including the one decision to get right before the first de same value to `build()` as a keyword as well is refused. - **Event deduplication claims atomically.** The handler chain checked for the marker with `exists()` and then wrote it with `set()`, so two replicas handed the same event at the same moment - both passed the check and both dispatched. It now uses the cache's atomic `claim()`, which already - existed for the scheduler's tick claim. + both passed the check and both dispatched. It now uses the cache's `claim()`, which already + existed for the scheduler's tick claim -- atomic across replicas on Redis, and within one process + on a disk cache. - **A handler result that fails to publish fails the delivery.** `publish_handler_event` caught every exception and logged a WARNING, so the inbound event was acknowledged and the handler's output was lost. The failure now naks the event -- the handler runs again on redelivery -- and the @@ -808,7 +827,8 @@ Full migration path, including the one decision to get right before the first de consistently. Configurable via `event_client_max_retries` and `event_client_retry_delay`. - **Schedulers no longer fire duplicate cron ticks under multiple replicas or workers** (#73). `scheduler_mode = "event"` delivers the tick as an ordinary event, so the queue group picks one - replica; `"in_process"` claims each tick in the shared cache so one replica runs it. + replica; `"in_process"` claims each tick in the shared cache so one replica runs it (across + replicas, a Redis cache: a disk cache's claim holds within one process). - **Schedulers no longer start twice** (#43), on both causes: a second `build()` pass no longer starts a second timer, and `SchedulerBase` sitting in the REST-API lifespan loop as well as the scheduler loop no longer creates two `AsyncIOScheduler` instances per scheduler. The manual @@ -867,6 +887,16 @@ Full migration path, including the one decision to get right before the first de operational task the framework does not perform. - `size` in the cache statistics counts TTL metadata entries, so a cache holding two values reports `4`. Documented as-is rather than changed, because a reported metric is somebody's dashboard. +- **A named connection whose binding names a stream that does not exist is retried, not refused.** + It reads `retrying` in `.nats_client:connections` and stops nothing else. With + `manage_consumer = false` the client sends no JetStream request, so a missing consumer is not + detected at all: the binding reads as bound and receives nothing. Whether either becomes fatal -- + at once, or after a grace period for provisioning -- is still open. +- **A disk cache's claim holds within one process only.** Two processes on one cache directory -- + replicas sharing a cache directory, or `uvicorn --workers N` run by hand -- can both win one + deduplication marker or one in-process tick, with no error raised (diskcache-rs 0.4.10). A claim + across replicas needs Redis. How this is resolved -- an OS file lock around the claim, or a startup + warning -- is still open. ### Upgrading a standalone agent from 0.8 @@ -890,8 +920,9 @@ What the code sees change: - **Components are constructed by `build()`, not by the `with_*()` call.** `with_handler(MyHandler)` records the class; `build()` constructs it, in declaration order. Code that looked a component up in the registry between a `with_*()` call and `build()` finds nothing, and an error a constructor - raises -- a missing configuration key, say -- is raised by `build()`. An instance passed to - `with_*()` is the caller's own and is used as it is. + raises -- a missing configuration key, say -- is raised by `build()`. In 0.8's + `AppBuilder(config)...build()` shape an instance passed to `with_*()` is the caller's own and is + used as it is; `build(config)` and a group refuse instances (Breaking 7). ### Rolling back to 0.8 diff --git a/CONTRIBUTE.md b/CONTRIBUTE.md index d8c204e2..9f4390de 100644 --- a/CONTRIBUTE.md +++ b/CONTRIBUTE.md @@ -56,13 +56,16 @@ This installs: ### Run All Tests ```bash -python pytest tests/ +python -m pytest tests/ ``` ### Run Tests with Coverage +`--cov` comes from `pytest-cov`, which no extra of this package installs: + ```bash -python pytest tests/ --cov=blueprint.agents --cov-report=html +pip install pytest-cov +python -m pytest tests/ --cov=blueprint.agents --cov-report=html ``` This generates an HTML coverage report in `htmlcov/index.html`. @@ -70,7 +73,7 @@ This generates an HTML coverage report in `htmlcov/index.html`. ### Run Tests for a Specific Module ```bash -python pytest tests/unit/test_agent_builder.py +python -m pytest tests/unit/agents/agent/test_agent_builder.py ``` ### Run Tests in Watch Mode (with pytest-watch) @@ -96,7 +99,7 @@ pytest tests/ -v ### Run a Specific Test ```bash -pytest tests/unit/test_agent_builder.py::TestAgentBuilder::test_with_model_sets_model_name -v +pytest tests/unit/agents/agent/test_agent_builder.py::TestFluentSetters::test_with_tool_appends -v ``` ## Building the Package Locally @@ -142,7 +145,7 @@ You should see entries like: blueprint/agents/__init__.py blueprint/agents/agent/__init__.py blueprint/agents/agent/agent_builder.py -blueprint/agents/api/__init__.py +blueprint/agents/app_builder.py blueprint/agents/config/__init__.py ... ``` diff --git a/README.md b/README.md index ef2c80f3..61d90d2d 100644 --- a/README.md +++ b/README.md @@ -29,20 +29,22 @@ Blueprint Agents gives you a component-based toolkit for building intelligent mi # Install the framework pip install avs-blueprint-agents -# Scaffold a new project +# Scaffold a new project -- asbs setup writes into the current directory +mkdir my-agent && cd my-agent asbs setup my-agent # Start developing -cd my-agent pip install -e . asbs dev ``` Your service is now running at `http://localhost:8000` with interactive API docs at `/docs`, -and this agent's routes under `/api/my-agent`. +and this agent's routes under `/api` -- served alone, at the root. `asbs dev --name my_agent` +serves it under the namespace a group image would give it, with its routes under `/api/my_agent`. -`asbs setup` writes your project's `main.py` as a **declaration** -- an `AppBuilder` that is never built -- -plus an `agents.toml` naming it. That is what lets the same project run on its own and be hosted +`asbs setup` writes your project's `main.py` as a **declaration** -- an `AppBuilder` that is never +built -- and a `create_app()` that builds it. It writes no `agents.toml`: that map belongs to an +image that hosts several agents. That is what lets the same project run on its own and be hosted alongside other agents without changing a line. See [Running one agent, or several](#running-one-agent-or-several). @@ -118,9 +120,9 @@ Blueprint Agents uses five composable component types, wired together with the ` ```python from blueprint.agents import AppBuilder -from src.handlers.order_handler import OrderHandler -from src.services.order_service import OrderService -from src.api.routes import OrderApi +from .handlers.order_handler import OrderHandler +from .services.order_service import OrderService +from .api.routes import OrderApi agent = ( AppBuilder() @@ -138,7 +140,8 @@ Two things about that chain are worth knowing up front: each component is built in. - **Pass classes, not instances.** `with_rest_api(OrderApi)` rather than `with_rest_api(OrderApi())`. An instance created on the `with_*` line exists before any namespace does, so it belongs to the - process root for ever. Instances still work for a single standalone agent; a group refuses them. + process root for ever. A group refuses them, and so do `agent.build(config)` and the + `create_app()` that calls it; only the old `AppBuilder(config)...build()` shape still accepts them. ### The Five Components @@ -190,14 +193,17 @@ before this existed. Nothing reads `agents.toml` unless you run the entry point. ### Hosted in a group -Name each agent and the module its declaration lives in, in `agents.toml`: +Name each agent, its directory (`root`, relative to the image root) and the module its +declaration lives in, in the image's `agents.toml`. Both keys are required: ```toml [agents.orders] -module = "src.main:agent" +root = "agents/orders" +module = "agents.orders.src.main:agent" [agents.billing] -module = "billing.main:agent" +root = "agents/billing" +module = "agents.billing.src.main:agent" ``` The image contains those agents; the **deployment** decides which of them a given process runs: @@ -321,14 +327,17 @@ See the [Configuration Reference](https://github.com/bechtleav360/AVS.AI.Bluepri The `asbs` CLI scaffolds projects and components: ```bash -asbs setup # Create a new project +asbs setup # Create a new agent, in the current directory +asbs setup --group # Create an image's files (agent map, group Dockerfile) asbs create handler [--event-type ] # Add an event handler asbs create service # Add a business service asbs create api # Add a REST API asbs create agent # Add an AI agent asbs create scheduler [--cron ] # Add a scheduler -asbs validate # Validate project structure -asbs dev [--port ] # Run development server +asbs validate [--group] # Validate one agent, or a whole image +asbs dev [--name ] [--port ] # Run development server +asbs docs [] [--cat] # Locate the bundled documentation +asbs claude # Install the Claude Code files into a project ``` See the full [CLI Reference](https://github.com/bechtleav360/AVS.AI.Blueprint.AgenticService/blob/develop/src/blueprint/agent_generator/docs/guides/cli-reference.md). diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md index bc3bba8a..93df9539 100644 --- a/docs/specs/2026-08-28-multi-agent-grouping.md +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -8,6 +8,7 @@ | **Related** | #33 (lazy heavy imports), #34 / #74 (dependency slimming), #36 (concurrency bounds + benchmark), #43 (scheduler double-start), #6 (config service) | | **Amended by** | `docs/plans/2026-09-10-builder-unification.md` -- decided 2026-09-10, folded into sec. 2, 4, 5.3, 8, 9, 10 and 11 below. | | **Amended by** | `docs/plans/2026-09-28-grouped-http-surface.md` -- decided 2026-09-28, folded into sec. 10 and 11.2 below. | +| **Amended by** | PR #96 review, 2026-10-19 -- brought in line with the implementation: C1 (root/agent durable clash), C2 (resolved group, per-provider metric readers, declared OTel keys), C4 (pause instead of close), sec. 2 and 11 (standalone agents at the root), 4.1 and 9 (`AgentGroup.resolve` / `from_config` / `assemble`), 4.2 (handler order restored, not refused), 5.1 (further group-file refusals), 5.3 (config refusals; process-scope keys dropped with a WARNING), 6 (resolved group; history), 7.1 and 7.2 (history; `SKIPPED`; ``; `max_deliver` optional), 7.4 (dedup key), 7.5 (no default mode; claim atomic on Redis only; slot from the fire time; crontab rules; `scheduler_timezone`), 9.1 (no agent left), 10 (instances refused by `build(config)`), 11.1 (`event_loop_debug`, watchdog), 12 (claim criteria scoped to Redis). Each change is marked in place. | | **Deferred out of** | `docs/plans/2026-09-10-config-validation-unification.md` -- configuration validation is not part of this feature. | Requirement keywords (**MUST**, **MUST NOT**, **SHOULD**, **MAY**) are used in the RFC 2119 sense. @@ -46,7 +47,7 @@ into processes a deployment-time parameter rather than a code-time one. | Term | Meaning | |---|---| | **Agent** | A unit of business capability: handlers, services, prompts, optionally a REST API and scheduler. Authored as one directory. | -| **Namespace** | The registry partition an agent's components live in. Equal to the agent name. `""` is the root namespace and means "pre-migration single-agent app". | +| **Namespace** | The registry partition an agent's components live in. Equal to the agent name. `""` is the root namespace: where a standalone application runs -- a pre-migration single-agent app, or any agent served on its own (sec. 11). *(Amended 2026-10-19, PR #96 review: a scaffolded agent served standalone runs at the root too.)* | | **Group** | The set of agents loaded into one process, and therefore into one pod. | | **Declaration** | An `AppBuilder` whose `build()` has not been called -- component classes recorded without instantiation. | | **Root** | Namespace `""`, holding process-wide shared components. | @@ -67,9 +68,10 @@ other deployment identifier. - Queue group: `namespace`, or `nats_queue_group` (default `app_name`) when the namespace is `""`. It **MUST NOT** be the empty string. -- JetStream durable: `f"{namespace}-{topic}-durable"`, or the configured `nats_durable_name` - when the namespace is `""`. Only the topic is rewritten to suit a consumer name; the namespace - reaches it as declared. +- JetStream durable: `f"{namespace}-{topic}-durable"`; when the namespace is `""`, the configured + `nats_durable_name` (one topic only), else `f"{topic}-durable"`. Only the topic is rewritten to + suit a consumer name; the namespace reaches it as declared. *(Amended 2026-10-19, PR #96 + review: the root's bare form stated.)* - Namespace alphabet: a namespace **MUST** be `""` or match `[a-z][a-z0-9_]*`, and **MUST** be validated where it enters the framework rather than by each consumer of it. It becomes a registry key prefix, a queue group, part of a durable name and a telemetry `service.name`, and @@ -78,6 +80,13 @@ other deployment identifier. - `-` is the separator in the durable name above. With it allowed, namespace `orders-eu` on topic `created` and namespace `orders` on topic `eu-created` produce one durable name, so two agents would bind one JetStream consumer and consume each other's events. + The exclusion separates agents from each other, not the root from an agent: the root's bare + `f"{topic}-durable"` has no namespace segment, so root topic `orders-created` and agent + `orders` on topic `created` still derive one name (`orders-created-durable`). That clash + **MUST** fail rather than share a consumer: the client refuses to bind a durable whose filter + is another subject (`JetStreamBindingError`), naming the consumer and the fix. *(Amended + 2026-10-19, PR #96 review: the root/agent clash is not prevented by the alphabet, and is + refused at bind.)* - `<` and `>` keep the sec. 6 connection-name placeholders unforgeable. `>` is a NATS wildcard and illegal in a consumer name in any case. @@ -95,7 +104,9 @@ Two rewrites are permitted, and only these: - The **topic** portion of a durable name. Dots are idiomatic in subjects and illegal in consumer names, so there is no alternative; it is bounded by the requirement that two topics resolving to - one durable name is an error, and the mapping is documented. + one durable name is an error, and the mapping is documented. Within one client the clash is + refused when the durables are resolved; between the root and an agent it is refused at bind + (above). *(Amended 2026-10-19, PR #96 review.)* - The **connection name** (sec. 6), which exists for attribution and which C1 forbids anything from deriving from, so no external party can depend on its spelling. @@ -110,12 +121,33 @@ namespace-owned in phase 2. ### C2 -- Telemetry identity derives from the agent Each namespace **MUST** have its own `TracerProvider` and `MeterProvider` with -`Resource({"service.name": , "deployment.group": , "service.instance.id": })`. -All providers **SHOULD** share one exporter and one `BatchSpanProcessor`. +`Resource({"service.name": , "deployment.group": , "service.instance.id": })`, +subject to the declared keys below. `` is the group the process resolved -- +`BLUEPRINT_GROUP`, or the one group a group file declares -- and `deployment.group` is absent when +no group was resolved; `service.instance.id` is absent when the pod cannot be determined. +*(Amended 2026-10-19, PR #96 review: the group is the resolved one, not only the variable, and the +resource carries no placeholders.)* + +All providers share one `BatchSpanProcessor` per exporter. Metric readers cannot be shared -- the +SDK binds a reader to the provider that registered it -- so each provider has its own reader over +the one shared metric exporter. The shared processor and exporter count the providers holding them +and are shut down by the last one; shutdown runs the agents' providers first and the root's last, +because the root's is the global provider. *(Amended 2026-10-19, PR #96 review: replaces "SHOULD +share one exporter and one `BatchSpanProcessor`"; per-provider readers and reference-counted +shutdown as implemented.)* When the namespace is `""`, the provider **MUST** use `otel_service_name` from config, reproducing current behaviour exactly (`io/telemetry/telemetry.py:39-41`). +**Keys the deployment declares.** *(Amended 2026-10-19, PR #96 review: describes the current +behaviour; decision D23 (c) in `docs/plans/2026-10-16-pr96-review-fixes.md` is open and may change +it.)* A key set in `OTEL_RESOURCE_ATTRIBUTES` or by `OTEL_SERVICE_NAME` is used as declared and +replaces the framework's value, on every provider. The one exception is `OTEL_SERVICE_NAME` in a +group: every agent's provider keeps `service.name = `, the root's provider takes the +declared name, and one startup WARNING names the value and says it applies to the root only. A +`service.name` given only in `OTEL_RESOURCE_ATTRIBUTES` is not excepted, so it currently names +every agent of a group alike. + ### C3 -- Liveness is never namespace-dependent The liveness probe **MUST** reflect only process and event-loop health. A degraded namespace @@ -140,7 +172,13 @@ generalises this to every path that stops a namespace serving, not only the ones Readiness gates HTTP only; a not-ready pod still holds subscriptions. A namespace that becomes degraded **MUST** stop consuming its events so they redeliver to a healthy replica. With -per-namespace transports (sec. 6) this is closing that namespace's client. +per-namespace transports (sec. 6) this is pausing that namespace's consumption, not closing its +client: its NATS client drains its own subscriptions and keeps its connection open, its sessions +job stream (`SessionsBus`) is paused likewise, and both resume when the namespace's health checks +pass again. A JetStream delivery that still reaches a paused namespace is nak'd without running; +under Dapr the event is not offered to the paused agent and is answered `RETRY`. *(Amended +2026-10-19, PR #96 review: paused and resumed rather than closed -- a closed client reports +unhealthy for ever, so the pause could never end, and publishing stays available.)* ### C5 -- Configuration is namespace-scoped @@ -191,7 +229,10 @@ What remains available is attribution, so attribution is normative: indistinguishable across a group's agents, and the grouping dial cannot be turned in response. - **Blocked loop.** The dev-mode slow-callback threshold (sec. 11.1) **SHOULD** also run in production at a higher threshold, logging the namespace of the executing handler. This is the one - group-wide failure class that is detectable from inside the process. + group-wide failure class that is detectable from inside the process. *(Amended 2026-10-19, PR #96 + review: met by the loop watchdog, on by default in every environment; it names the agents with + work in flight, since the blocking callback has returned by the time it runs. asyncio's debug + mode is opt-in, sec. 11.1.)* Grouping removes the pod restart that used to serve as the alert, so the alert **MUST** be emitted deliberately rather than inferred from a restart. @@ -202,22 +243,30 @@ deliberately rather than inferred from a restart. ### 4.1 New +*(Amended 2026-10-19, PR #96 review: the names as implemented. `AgentGroup(config)` / +`.add()` / `.with_group()` / `.from_group()` / `.build()` became a constructor over named +declarations, `from_config`, `resolve` and `assemble`.)* + ```python class AgentGroup: - """Collects one declaration per agent and wires them into a single application.""" - def __init__(self, config: Config) -> None: ... - def add(self, namespace: str, agent: AppBuilder) -> "AgentGroup" - def with_group(self, group: GroupConfig) -> "AgentGroup" # import each module, add each - def build(self) -> FastAPI + """The agents one process hosts, and the single application they become.""" + def __init__(self, name: str, agents: Mapping[str, AppBuilder], *, + settings=None, secrets=None, roots=None, critical=None) -> None: ... + + @classmethod + def resolve(cls, config: Config) -> "AgentGroup" # GroupConfig.resolve + from_config @classmethod - def from_group(cls, config: Config) -> "AgentGroup" # resolve + with_group + def from_config(cls, group: GroupConfig) -> "AgentGroup" # import each module the group names + + def assemble(self, config: Config) -> FastAPI # one root builder, one build() class GroupConfig: """Resolved group composition. A value object; performs no I/O once constructed.""" name: str - agents: tuple[AgentSpec, ...] # name, critical flag, module path + agents: tuple[AgentSpec, ...] # name, module path, root, critical flag + image_root: Path # No cache list: an agent may use only the caches it declared itself (sec. 8). @classmethod @@ -228,15 +277,19 @@ class GroupConfig: def run_app(app: FastAPI, config: Config) -> None: ... ``` -`GroupConfig.resolve` is the only member that reads the environment or the filesystem. -`AgentGroup.with_group` **MUST NOT** read either -- importing the agent modules a `GroupConfig` -names is not a configuration read -- so tests can construct a `GroupConfig` literally. +`GroupConfig.resolve` is the only member that reads the environment, the group file or the agent +map. `AgentGroup.from_config` **MUST NOT** read the environment -- importing the agent modules a +`GroupConfig` names is not a configuration read -- so tests can construct a `GroupConfig` +literally. *(Amended 2026-10-19, PR #96 review: `from_config` replaces `with_group`; besides the +imports it checks each agent's directory layout and whether `settings.toml` / `.secrets.toml` +exist there, and `assemble` reads those files, sec. 5.3.)* **Collection is its own class, and `AppBuilder` MUST NOT know it can be collected.** An `AppBuilder` never absorbs another builder and exposes no group concept; `AgentGroup` constructs its own and replays what each agent recorded. This is what keeps one fluent surface honest: the group's restrictions belong to the thing imposing them, so `AppBuilder` stays permissive and every -refusal in sec. 4.2 is raised by `AgentGroup`. +refusal in sec. 4.2 is raised by `AgentGroup` -- except the instance refusal, which +`AppBuilder.build(config)` applies too (sec. 10). *(Amended 2026-10-19, PR #96 review.)* ### 4.2 Changed @@ -270,8 +323,9 @@ needs to exist. and no `namespace` parameter on any `with_*` method: standalone has no namespace to name, and an agent's name lives only in the group configuration (sec. 11). -**Configuration resolution order, highest first:** `build(config)`, then `AppBuilder(config)`, then -the default settings files. `AgentGroup` **MUST** refuse a builder that carries its own +**Configuration resolution:** `build(config)` or `AppBuilder(config)` -- giving both **MUST** be +refused -- else the default settings files. *(Amended 2026-10-19, PR #96 review: `build()` raises +when a configuration is given twice; there is no precedence between the two.)* `AgentGroup` **MUST** refuse a builder that carries its own configuration -- one process has one settings tree and one port -- and **MUST** wire each agent with that agent's own scoped view (C5). @@ -295,7 +349,12 @@ collected. source line, a class during `build()`, so an instance recorded *after* a class would register *before* it -- which can flip equal-priority handler tie-breaking, resolved by registration order today. `build()` knows both the recorded order and which entries were instances, and **MUST** -raise on that combination rather than silently reordering. +register the handlers in declaration order: after the replay it puts them back into the +registry slots they already hold, in the order they were declared, so nothing else the registry +holds moves. *(Amended 2026-10-19, PR #96 review: replaces "MUST raise on that combination rather +than silently reordering" -- restoring the declared order keeps tie-breaking as written without +refusing a valid declaration. The case arises only where instances are accepted -- `AppBuilder(config).build()`, +or `build()` with no argument; `build(config)` and a group refuse instances.)* **`with_cache` is the one place where the obvious design breaks compatibility.** The current signature is `with_cache(enabled: bool = True, enable_locking: bool = True)` @@ -335,6 +394,14 @@ routed through Dynaconf. Hence the `BLUEPRINT_` prefix rather than Dynaconf's `D **Precedence: environment variables override the file, key by key.** The resolved value of every key, and its source, **MUST** be logged at startup. +Resolution **MUST** fail with `GroupConfigError`, naming the file or variable and the fix, when: +a group file declares one group name more than once; `agents` or `critical_agents` in the file +is not a list (a scalar is refused, not split); a group names one agent twice; or the critical +names (`critical_agents` / `BLUEPRINT_CRITICAL_AGENTS`) include an agent the group does not run +-- once critical names are given, every agent they do not name is non-critical, so a misspelt +name would make the whole group non-critical. *(Amended 2026-10-19, PR #96 review: refusals as +implemented.)* + Both mechanisms **MUST** be supported; neither is preferred. The file suits ConfigMap mounts and local development, env vars suit `docker run` and CI, and env values live in the pod template so changing them triggers a rolling update on their own. @@ -368,14 +435,34 @@ plain top-level keys in their own directory's `settings.toml` (`model_name = ".. resolves it, without the author knowing the scope exists. An agent may therefore set any key for itself, and **MUST NOT** be able to change what another -agent or the process sees. There is consequently no collision to report: a fragment and a root key -never occupy the same slot, and a default restated in an agent's fragment is simply that agent's -own value. - -Process-scope keys in an agent fragment **MUST** raise at startup, from an explicit list -(`app_port`, `event_bus`, `envvar_prefix`, `nats_stream_name`). Scoped, such a key is read by -nothing and reported by nothing -- C7's failure mode in configuration form -- and its author has -no way to discover that the value they set is inert. +agent or the process sees. A fragment and a root key never occupy the same slot, and a default +restated in an agent's fragment is simply that agent's own value. Where a slot *could* be +shared, the framework **MUST** refuse rather than merge or resolve, naming the agent and the key: +*(Amended 2026-10-19, PR #96 review: replaces "there is consequently no collision to report" -- +these cases exist and are refused.)* + +- a root key named like the agent whose value is not a section -- merging the fragment would + replace that value for the whole process (`ConfigError`); +- an agent named like a configuration section the process shares (`cache`, `event_publishing`, + `runtimes`, `runtime`) -- refused by namespace validation, since its fragment would be merged + into that shared section; +- a bare key naming another agent, read through an agent's view -- at the root it is that agent's + whole section (`ValueError`), as is a dotted key outside the shared nested sections; +- a fragment that scopes its keys under the agent's own name (`[default.]`), which would + nest as `..*` and be read by nothing (`ConfigError`). + +Process-scope keys in an agent fragment **MUST** be dropped at startup with a WARNING per key +naming the agent, the key, the file and the value the process uses instead (a secrets file's +values are not logged), from an explicit list: `PROCESS_SCOPE_KEYS` (`app_port`, `app_host`, +`app_workers`, `app_environment`, `envvar_prefix`, `event_bus`, `log_level`, `log_format`, +`suppress_noisy_loggers`, `health_check_interval_seconds`, `startup_retry_interval_seconds`, +`readiness_policy`, `dot_placeholder`, `nats_stream_name`, `nats_connection_source`, +`nats_extra_runs_per_process`) plus the deployment-identity keys (`blueprint_group`, `pod_name`, +`hostname`). Scoped, such a key is read by nothing and reported by nothing -- C7's failure mode +in configuration form -- and the WARNING is what lets its author discover that the value they set +is inert. *(Amended 2026-10-19, PR #96 review: replaces "MUST raise" -- every example project +declares `app_port` and `app_environment` in its settings file, so raising would bar any existing +project from a group until edited; the list is longer than the four keys first named.)* What happens when a *required* key is absent is deliberately not specified here. It is `docs/plans/2026-09-10-config-validation-unification.md`, kept out of this feature so that the @@ -406,10 +493,10 @@ to the namespace model. This is justified by three things, in order of weight: 2. **Slow-consumer disconnects are confined.** The broker kicks a connection whose pending buffer overflows. Shared, one flooding agent takes down the group's transport and triggers a re-subscribe storm across all namespaces (`clients/io/nats_client.py:265-280`). -3. **Attribution.** `nats.connect()` is currently called with no `name=` - (`clients/io/nats_client.py:93`), so every connection this framework opens is anonymous in - `/connz`. Per-namespace named connections make a pod's contents legible in connection-oriented - tooling. +3. **Attribution.** When this spec was written, `nats.connect()` was called with no `name=`, so + every connection the framework opened was anonymous in `/connz`. Per-namespace named + connections make a pod's contents legible in connection-oriented tooling. *(Amended + 2026-10-19, PR #96 review: implemented; the defect is history.)* **Durability is not among the three, and the topology MUST NOT be justified by it.** JetStream pending state lives on the server, keyed by consumer and stream sequence; an ack is a message @@ -426,9 +513,10 @@ separate process (#32). Protecting a few MB with a knob nobody should use is not maintenance surface. 100 agents at 2 replicas is ~200 connections, which is not a practical constraint against a self-operated broker's default `max_connections`. The number **SHOULD** be checked before a large rollout only where the cap is issued externally per account -- a managed -broker, or an operator-mode account whose JWT carries a `conn` limit set by someone else. No such -authentication is currently wired: `nats.connect()` is called with URL and reconnect parameters -only (`clients/io/nats_client.py:93`). +broker, or an operator-mode account whose JWT carries a `conn` limit set by someone else. Such +authentication is wired: user and password, token, an nkey seed and a credentials file +(`nats_creds_file`) reach `nats.connect()`. *(Amended 2026-10-19, PR #96 review: "no such +authentication is currently wired" is history.)* A namespace that neither subscribes to anything nor publishes anything **MUST NOT** be given a client. A pure-scheduler agent on `scheduler_mode = "in_process"` that does not opt into publishing @@ -438,13 +526,17 @@ deployment may have no access to. The cost argument above justifies a connection that uses one*; it does not justify one per namespace that does not. Connection name **MUST** be `f"{namespace}.{group}.{pod}"`, and **MUST NOT** feed C1 naming. -**Exception -- a standalone agent** (namespace `""` and no `BLUEPRINT_GROUP`): the name **MUST** be +**Exception -- a standalone agent** (namespace `""` and no resolved group): the name **MUST** be the pod alone, and **MUST** be omitted when the pod cannot be determined. Neither a namespace nor a group exists for it, and `..` would imply a grouping that is not there; an -omitted name is what a standalone agent sent before this feature. The root of a *grouped* process -keeps the full form. +omitted name is what a standalone agent sent before this feature. The root of a process whose +group is named keeps the full form. +The group is the one the process resolved: `BLUEPRINT_GROUP`, or the one group a group file +declares when the variable is unset. *(Amended 2026-10-19, PR #96 review: the resolved group, not +only the variable -- a group named by the file alone reached neither the connection name nor the +telemetry resource.)* An absent segment **MUST** be filled with a placeholder rather than left empty -- `` for the -root namespace, `` for an unset `BLUEPRINT_GROUP`, `` when the replica +root namespace, `` when no group was resolved, `` when the replica cannot be identified -- so all three positions always carry a value, a name never degenerates into `..pod-7`, and "no group" stays distinguishable from a group whose name happens to be empty. @@ -464,8 +556,10 @@ introduced to remove. Two rules give that: `EventPublishingService` **MUST** publish on its own namespace's client; otherwise outbound traffic is unattributable and reason 3 is defeated. -Per-namespace clients also make C4 a client close rather than selective unsubscription, and give +Per-namespace clients also make C4 a per-client pause -- the client drains its own subscriptions +and keeps its connection -- rather than selective unsubscription on a shared client, and give `ClientHealthChecker` per-agent health entries that feed `readiness_policy = "critical"` directly. +*(Amended 2026-10-19, PR #96 review: a pause, not a close; see C4.)* --- @@ -476,23 +570,28 @@ Per-namespace clients also make C4 a client close rather than selective unsubscr With N replicas of a group, exactly one replica **MUST** process any given event. Core NATS subscriptions **MUST** pass a queue group; JetStream consumers **MUST** share a durable per C1. -The current code does neither: `nats_client.py:250` subscribes with no `queue=`, and JetStream is -off by default (`nats_client.py:102`). Setting `replicas: 2` today therefore doubles every side -effect and every inference bill. This is a defect independent of grouping (see #20, #35). +When this spec was written the code did neither: core subscriptions passed no `queue=`, so +`replicas: 2` doubled every side effect and every inference bill -- a defect independent of +grouping (see #20, #35). Core subscriptions now pass the queue group (C1) and JetStream consumers +share their durable with a deliver group; JetStream stays off by default (`nats_use_jetstream`). +*(Amended 2026-10-19, PR #96 review: the defect is history.)* ### 7.2 Acknowledgement -`nats_client.py:242-247` subscribes with `manual_ack=True` and **no `msg.ack()` call exists -anywhere in the codebase**, so every JetStream message redelivers until `max_deliver`. Already a -defect at one replica. +When this spec was written, JetStream subscriptions used `manual_ack=True` and **no `msg.ack()` +call existed anywhere in the codebase**, so every JetStream message redelivered until +`max_deliver` -- already a defect at one replica. Every JetStream delivery is now settled +(`ack`, `nak` or `term`) per the table below. *(Amended 2026-10-19, PR #96 review: the defect is +history.)* **Decision: ack after the handler completes.** The alternative (ack first) converts a connection blip from duplicate work into *lost* work, which is worse for expensive, side-effecting inference. Consequently at-least-once is permanent, and sec. 7.4 applies. **The contract is that a normal return acknowledges and a raised exception does not.** -`ProcessingStatus` carries no failure value -- it is `PROCESSED` or `NO_HANDLER_FOUND` -- so every -failure already reaches the transport as an exception. The transport edge **MUST NOT** inspect +`ProcessingStatus` carries no failure value -- it is `PROCESSED`, `NO_HANDLER_FOUND` or `SKIPPED` +-- so every failure already reaches the transport as an exception. *(Amended 2026-10-19, PR #96 +review: `SKIPPED` added, see below.)* The transport edge **MUST NOT** inspect `ProcessingResult` to decide acknowledgement: `ProcessingResult` is a reporting object and **MUST** remain independent of delivery control. @@ -507,8 +606,9 @@ remain independent of delivery control. **`NO_HANDLER_FOUND` MUST acknowledge.** An event that matches no handler's conditions has nothing to do, and redelivery cannot make a handler appear: a nak is a pointless loop until `max_deliver`, -and under a queue group a loop that visits every replica in turn. `dapr.py:75` returns `RETRY` for -this case today and **MUST** change. +and under a queue group a loop that visits every replica in turn. When this spec was written the +Dapr endpoint returned `RETRY` for this case; it now answers `SUCCESS`. *(Amended 2026-10-19, +PR #96 review: the defect is history.)* **An unmatched event is acknowledged, and it is reported as a probable misconfiguration (changed 2026-10-15).** Deciding there is nothing to do is the handler's job: a handler that is @@ -524,7 +624,11 @@ because "nothing to do" could only be said by declining; the chain logged a WARN It **MUST** be counted per namespace and topic, for one purpose: the *proportion* of received events a namespace declines is how a too-broad subscription shows up (sec. 7.7). A high count is a -question about the subject filter, not about the handler. +question about the subject filter, not about the handler. Under Dapr, a topic the agent did not +declare is counted under the topic label `` (every topic is, with +`dapr_declarative_subscriptions`), and the real topic stays in the log line; the same label +applies to the duplicate and skipped counters. *(Amended 2026-10-19, PR #96 review: the label is +what keeps a caller-chosen URL path from minting one time series per request.)* **A skip is the selected handler's own "nothing to do" (added 2026-10-15).** A handler that is responsible for an event -- `can_handle_event` routed it there -- and finds that this particular @@ -537,12 +641,17 @@ with the reason as message. **Both transports MUST map the same outcome to the same disposition.** Dapr's response dict *is* its acknowledgement, so the table above is normative for `dapr.py` and -`event_handling_base.handle_event` exactly as it is for `nats_client.py`. They disagree in two -places today: `NO_HANDLER_FOUND` as above, and `CriticalHandlerError`, which `dapr.py:102` retries --- a critical error is not made less critical by being delivered again. - -`max_deliver` and a dead-letter destination **MUST** be configured, because nak on an unexpected -exception otherwise redelivers indefinitely. +`event_handling_base.handle_event` exactly as it is for `nats_client.py`. When this spec was +written they disagreed in two places: `NO_HANDLER_FOUND` as above, and `CriticalHandlerError`, +which the Dapr endpoint retried -- a critical error is not made less critical by being delivered +again. Both now map per the table. *(Amended 2026-10-19, PR #96 review: the defect is history.)* + +`max_deliver` **SHOULD** be configured, because nak on an unexpected exception otherwise +redelivers indefinitely. `nats_max_deliver` is optional: unset, the server's default applies +(NATS: unlimited) and nothing is ever dead-lettered; `-1` asks for unlimited explicitly and is +warned about at startup. The dead-letter destination needs no configuration: it defaults to +`.dead-letter` (sec. 5.2). *(Amended 2026-10-19, PR #96 review: replaces "MUST be +configured" -- the framework sets no consumer limits a deployment did not configure, sec. 5.2.)* The nak on the last delivery `max_deliver` permits **MUST** be rendered as a dead letter followed by a term, not as a nak. The broker will not redeliver it, so a nak there differs from a term only @@ -587,8 +696,15 @@ Whether deduplication is *correct* depends on the product built on the blueprint operations are naturally idempotent, others need business-level reconciliation the framework cannot see. The framework therefore **MUST NOT** silently enforce dedup, and **MUST**: -- provide an opt-in dedup mechanism keyed on the CloudEvent `id`, backed by the namespace's cache - with a TTL, applied in the handler chain before dispatch (`idempotency_enabled`); +- provide an opt-in dedup mechanism keyed on the CloudEvent `(source, id)` -- plus the connection + name for a delivery from a named connection (`nats_connection`) -- backed by the namespace's + cache with a TTL, applied in the handler chain before dispatch (`idempotency_enabled`). The + marker is claimed atomically before dispatch and kept only when the delivery is acknowledged + as a success; every other outcome releases it so the redelivery can run, and only the delivery + that won the claim releases it, never a duplicate. *(Amended 2026-10-19, PR #96 review: an `id` + is unique only within a source, and the same producer behind two connections emits the same + ids for different data; marker lifetime as implemented. Atomic across processes on Redis only, + sec. 7.5.)* - **flag the requirement explicitly to the agent author** -- a comment in the scaffolded handler, a line in the generated README, and an `asbs validate` notice when a handler is registered with `idempotency_enabled = false`. The author must make a decision, not inherit a default silently. @@ -603,7 +719,7 @@ Two modes, selected by `scheduler_mode`: | Mode | Behaviour | |---|---| -| `"event"` | **Default.** No in-process timer. An external scheduler (Kubernetes `CronJob`) publishes an event; the agent handles it through its normal event path. | +| `"event"` | No in-process timer. *(Amended 2026-10-19, PR #96 review: "Default" removed -- neither mode is the default, below.)* An external scheduler (Kubernetes `CronJob`) publishes an event; the agent handles it through its normal event path. | | `"in_process"` | `AsyncIOScheduler` in every replica, with each tick claimed in the shared cache so one replica runs it. For un-orchestrated Docker and local development. | `scheduler_mode` **MUST NOT** have a default: registering a scheduler without it **MUST** fail @@ -641,19 +757,30 @@ Because manifests belong to a deployment group rather than to a single project o serves the platform (sec. 6, and the entrypoint model), the generator's input **SHOULD** be the group's agent map rather than one project's source tree. -Independently of the manifest, the declared crontab **MUST** be validated in `"event"` mode. That -mode builds no `CronTrigger`, so nothing else parses the expression, and an invalid one otherwise -presents as a scheduler that reports itself healthy and never ticks. It **MUST** be the five -standard cron fields: an external scheduler reads those, and apscheduler's extensions -- a leading -seconds field in particular -- are not portable to one. +Independently of the manifest, the declared crontab **MUST** be validated in both modes, before +the port is bound. `"event"` mode builds no `CronTrigger`, so nothing else parses the expression, +and an invalid one otherwise presents as a scheduler that reports itself healthy and never ticks; +`"in_process"` mode parses it only at startup and does not read it as an external cron would. It +**MUST** be the five standard cron fields: an external scheduler reads those, and apscheduler's +extensions -- a leading seconds field in particular -- are not portable to one. + +The day of the week is numbered as apscheduler numbers it, `0` = Monday to `6` = Sunday, which +disagrees with a standard cron (`0` = Sunday) on every number. Day `7` **MUST** be refused in both +modes (Sunday to cron, nothing to apscheduler). In `"event"` mode, where an external cron fires +the tick, a day of the week given by number -- including `*/n`, which steps from day `0` -- **MUST** +be refused: names (`mon-fri`, `sun`) read the same to both. *(Amended 2026-10-19, PR #96 review: +replaces "validated in `"event"` mode" -- validation runs in both modes, and the weekday rules are +added.)* **In-process coordination is a per-tick claim, not a leader lease.** An earlier form of this section called for a NATS KV or cache-backed leader lease. A slot claim satisfies the same requirement and is preferred, because it removes rather than answers the failover question: every replica's timer fires, each tries to store a marker keyed on `(scheduler, minute)` in the agent's -own cache -- shared across that agent's replicas, and per sec. 8 invisible to every other agent, so -two agents each running a scheduler of the same name cannot claim each other's slots -- and the -replica that stores it runs the tick. Nothing is elected and nothing is held, so there +own cache -- shared across that agent's replicas when the cache is Redis, and per sec. 8 invisible +to every other agent, so two agents each running a scheduler of the same name cannot claim each +other's slots -- and the replica that stores it runs the tick. *(Amended 2026-10-19, PR #96 +review: a disk cache is not shared across processes in a way the claim can rely on, below.)* +Nothing is elected and nothing is held, so there is no renewal task to schedule (and therefore none to leak, C7), no lease left behind by a replica that dies holding one, and no takeover bound to specify -- the next slot is claimed from scratch by whoever is alive. @@ -662,11 +789,22 @@ The claim **MUST** use a set-if-absent primitive rather than a read followed by `CacheService.claim`. Two replicas racing on an `exists`-then-`set` pair both pass the check and both tick, which is the failure this mechanism exists to prevent. +`CacheService.claim` is atomic across processes only on the Redis backend. A disk cache's claim +holds within one process: processes sharing one cache directory -- replicas on a shared volume, +or `uvicorn --workers N` run by hand -- can each win the same key. Coordinating replicas therefore +needs Redis. *(Amended 2026-10-19, PR #96 review: measured with diskcache-rs 0.4.10, several +processes on one directory each won one key; how to proceed beyond documenting it is open, D22.)* + The key **MUST** be derived from the scheduled slot rather than from the scheduler alone. Cron granularity is one minute, so replicas firing for the same scheduled time derive the same key and the next scheduled time derives a different one -- which is what keeps set-if-absent sufficient. -Replicas whose clocks differ enough to straddle a minute boundary derive different slots and both -tick; sec. 7.4 covers that, as it covers every other repeat. +The slot is the trigger's latest scheduled fire time at or before the current time, as a UTC +minute, not the clock at run time: a run that starts late, or on a replica whose clock is a little +ahead, still claims the slot it was scheduled for, and fire times that passed without a run are +walked over rather than claimed late. Without a trigger, or before its first fire time, the clock +decides. Clock skew therefore splits a slot only when it outlasts the marker (300 s); sec. 7.4 +covers that, as it covers every other repeat. *(Amended 2026-10-19, PR #96 review: replaces the +clock-minute key, whose straddle of a minute boundary let two replicas both tick.)* With no cache registered there is nothing to claim with. The timer **MUST** still run -- the mode exists for local development, where requiring a cache would be gratuitous -- and startup **MUST** @@ -676,7 +814,11 @@ Neither mode is exactly-once: `CronJob` is at-least-once (controller restart, mi `startingDeadlineSeconds`), and a claim fails open when the cache is unreachable, so every replica ticks. Sec. 7.4 therefore applies in both modes. `concurrencyPolicy: Forbid` **SHOULD** be set, and `CronJob` `timeZone` **MUST** be reconciled with apscheduler's timezone handling so the two modes -do not diverge. +do not diverge. The reconciliation point is the opt-in `scheduler_timezone` (an IANA name, per +namespace): the `"in_process"` timer runs in it, and unset it keeps the host's local time as +before. In `"event"` mode the external cron's own timezone decides and the key changes nothing, +so the deployment sets `CronJob` `timeZone` to the same zone. *(Amended 2026-10-19, PR #96 review: +how the reconciliation is done; CronJob generation is deferred, sec. 12.)* **Publishing and consuming are separate decisions.** A scheduler that emits a result event is a legitimate shape and **MUST NOT** require the agent to consume anything: an application that opts @@ -725,7 +867,8 @@ publishing, so publisher and consumer cannot drift. Two rules keep this non-breaking, and both are load-bearing, because **no handler in the framework or in any scaffolded project declares anything today**: `get_subscribed_topics()` is overridden -nowhere, the generated handler template selects purely inside `can_handle_event`, and +only by the framework's own `SchedulerTickHandler`, the generated handler template selects purely +inside `can_handle_event`, and `nats_subscriptions` appears in no generated settings file. Any design that treats declarations as authoritative therefore describes an empty set. @@ -790,10 +933,15 @@ cache in the root namespace. 1. `GroupConfig.resolve(config)` -- file, then env overrides; log provenance. 2. Validate every agent name against the in-image agent map. Fail with the group and the missing agent named. -3. Import each agent module lazily; read its module-level `registration`. -4. `AgentGroup(config).with_group(group)` -- one recorded declaration added per agent. -5. `build()`, then `run_app(app, config)`. Every component is constructed here, inside its own - namespace scope; steps 1-4 construct nothing. +3. Import each agent module lazily; read the declaration the agent map names + (`module = "pkg.mod:attribute"`). +4. `AgentGroup.from_config(group)` -- one unbuilt declaration per agent. Steps 1-4 together are + `AgentGroup.resolve(config)`. +5. `assemble(config)`, then `run_app(app, config)`. Every component is constructed here, inside + its own namespace scope; steps 1-4 construct nothing. + +*(Amended 2026-10-19, PR #96 review: `with_group` / `build()` are `from_config` / `assemble()`, sec. +4.1; the declaration's attribute name comes from the agent map.)* Resolution **MUST** complete before the first `Component.__init__`, because namespace injection happens through a `ContextVar` read during construction. No incremental resolution. @@ -808,6 +956,10 @@ There is no partial build: one process, one `build()`. The `critical` flag is th | Agent missing from the agent map | exit non-zero | log ERROR, skip | | Module import raises | exit non-zero | log ERROR, skip | | `on_startup` raises | exit non-zero | mark namespace down, pause consumers (C4), continue; retry (below) | +| No agent left after the skips above | exit non-zero | exit non-zero | + +*(Amended 2026-10-19, PR #96 review: last row added -- a pod with no agent passes its probes while +it consumes nothing, which is the failure criticality exists to prevent.)* Exit **MUST** happen before the port is bound, so Kubernetes crash-loops with a readable message rather than reporting a healthy pod that is silently short-staffed. @@ -842,7 +994,7 @@ change, and `uvicorn src.main:app` as its entrypoint. Specifically: | Concern | Guarantee | |---|---| | `AppBuilder` fluent API | Unchanged. `AppBuilder(config)...build()` behaves as today, and no `namespace` parameter is added to anything. | -| Passing a constructed instance to `with_*` | Unchanged standalone; refused only when the builder is collected into a group (sec. 4.2). | +| Passing a constructed instance to `with_*` | Unchanged for an application that builds itself (`AppBuilder(config)...build()`, or `build()` with no argument). Refused when the builder is collected into a group (sec. 4.2), and by `build(config)` -- which the scaffolded `create_app()` calls -- because a declaration built by a host has the shape a group hosts. *(Amended 2026-10-19, PR #96 review: was "refused only in a group".)* | | Component construction timing | Deferred to `build()`. Reading a component out of the registry between `with_*` calls was never supported -- collaborators resolve in `on_startup` -- and now breaks. | | `with_health_checker` keys | Bare name at the root, so an existing readiness payload is unchanged; qualified per agent in a group. | | OpenAPI tags and paths | Unchanged at the root: tags as the framework and the developer declare them, untagged routes under "default", every path as served today. Rewritten only per agent in a group (sec. 11.2). | @@ -898,20 +1050,26 @@ nothing else: ```python def create_app(): # uvicorn src.main:create_app --factory --reload - return agent.build() + return agent.build(Config(settings_files=["settings.toml", ".secrets.toml"], root_path=...)) ``` The component list appears **once** either way. The dual-branch `main.py` of an earlier draft -- the same components repeated under `if __name__ == "__main__"` and `else:` -- **MUST NOT** be used; two copies to keep in sync is itself a leak of the grouping model. -`asbs dev agents/` runs one agent as a group of one, using its **real** namespace. Local -routes are therefore `/api/order/orders/{id}`, identical to production, and local consumer -identity is the production queue group. A dev mode that ran at `namespace=""` would give every -developer local URLs and integration tests that differ from production. +`asbs dev` in an image directory (one with an `agents.toml`) hosts that image's agents under +their **real** namespaces, as the deployment does. In an agent directory it serves the agent on +its own, at the root namespace, as the agent's own Dockerfile and `create_app()` do; `asbs dev +--name ` serves it as a group of one under that namespace instead, so local routes are +`/api//...` and local consumer identity is the production queue group, identical to a +grouped deployment. -Consequently `namespace=""` is reserved for pre-migration agents. Every newly scaffolded agent -**MUST** have a real namespace in every environment. +An agent therefore runs at its real namespace wherever a group hosts it, and at the root when it +is served on its own. `namespace=""` is not reserved for pre-migration agents. *(Amended +2026-10-19, PR #96 review: replaces "`asbs dev agents/` runs one agent as a group of one" +and "every newly scaffolded agent MUST have a real namespace in every environment" -- an agent +directory carries no name of its own, the name comes from whoever hosts it, and `--name` +reproduces the grouped shape locally.)* ### 11.1 What cannot be hidden @@ -920,7 +1078,7 @@ mechanically, because a rule that cannot be violated locally will not be followe | Mistake | Detection | |---|---| -| Blocking the event loop | dev mode sets `loop.set_debug(True)` with a slow-callback threshold; production **SHOULD** keep a higher-threshold watchdog that names the executing namespace (C7) | +| Blocking the event loop | `event_loop_debug = true` (read as a boolean, in any environment; off unless set) sets `loop.set_debug(True)` with a slow-callback threshold; otherwise a loop watchdog, on by default in every environment, reports a block above its threshold and names the agents with work in flight (C7) *(Amended 2026-10-19, PR #96 review: debug mode is no longer on by default in development -- its overhead is too high to be a default)* | | Module-level side effects (clients built at import, `basicConfig()`) | CI: import each agent module, assert the registry is empty and the root logger has no handlers | | Non-idempotent handlers | explicit flag at scaffold time and in `asbs validate` (sec. 7.4) | @@ -991,9 +1149,11 @@ unticked box is not done, and says why. - [x] File-only, env-only and combined resolution produce identical groups; env overrides the file key by key -- `tests/unit/agents/test_group_config.py`: `TestFromTheGroupFile`, `TestFromTheEnvironmentAlone`, `TestPrecedence`. -- [x] `CacheService.claim` is set-if-absent on both backends: of N concurrent callers on one key - exactly one is told it stored the value (sec. 7.5) -- `TestClaim` in both - `test_disk_cache_service.py` and `test_redis_cache_service.py`. +- [x] `CacheService.claim` is set-if-absent: of N concurrent callers on one key exactly one is + told it stored the value (sec. 7.5) -- `TestClaim` in both `test_disk_cache_service.py` and + `test_redis_cache_service.py`. Across processes this holds on Redis only; the disk + backend's claim holds within one process. *(Amended 2026-10-19, PR #96 review: scoped to + Redis.)* - [x] An `"in_process"` scheduler with no cache still ticks, and warns at startup that its ticks are uncoordinated (sec. 7.5) -- `test_without_a_cache_every_replica_ticks` and `test_in_process_mode_without_a_cache_says_every_replica_runs_every_tick`. @@ -1032,8 +1192,10 @@ unticked box is not done, and says why. `tests/integration/test_grouped_agents.py` is the version that settles it. - [~] Two replicas of a two-agent group: each event processed exactly once per agent. Whether a queue group merges overlapping subscriptions is the broker's behaviour, not ours. -- [~] Cron fires once across three replicas in both `scheduler_mode` values (#73). The claim is - atomic on both cache backends by unit test; three real replicas contending is not. +- [~] Cron fires once across three replicas in both `scheduler_mode` values (#73) -- in + `"in_process"` mode with a Redis cache. The claim is atomic on Redis by unit test; three + real replicas contending is not. On a disk cache the claim does not hold across processes + (sec. 7.5). *(Amended 2026-10-19, PR #96 review: scoped to Redis.)* ### Not done diff --git a/src/blueprint/agent_generator/claude_docs/CLAUDE.md b/src/blueprint/agent_generator/claude_docs/CLAUDE.md index 88781e51..57039147 100644 --- a/src/blueprint/agent_generator/claude_docs/CLAUDE.md +++ b/src/blueprint/agent_generator/claude_docs/CLAUDE.md @@ -80,7 +80,8 @@ def create_app(): ``` - Never build the `AgentBuilder` yourself and never pass an instance to a `with_*` call: a group - refuses instances, because a component constructed on that line exists before any namespace does. + and `create_app()` (`agent.build(config)`) refuse instances, because a component constructed on + that line exists before any namespace does. - Keep one registration per line in dependency order (services, agents, handlers, APIs, schedulers) -- `asbs create` rewrites the chain line by line. @@ -115,7 +116,7 @@ class OrderHandler(EventHandlerBase): stops, the delivery is acknowledged, the reason is logged at INFO, nothing is published. `None` → the event is offered to the next handler; if none takes it, the framework logs "No handler processed event". -- **Delivery is at-least-once.** The same event can reach `handle_event` more than once (lost ack, pod restart, rolling deploy). The *service* must be safe to repeat (check before you act, upsert rather than insert), or set `idempotency_enabled = true` **and** `idempotency_ttl = ` in `settings.toml` -- the framework then skips an event whose id and source it has already dispatched, within that window. Off by default on purpose: only you know whether replaying your side effects is acceptable. +- **Delivery is at-least-once.** The same event can reach `handle_event` more than once (lost ack, pod restart, rolling deploy). The *service* must be safe to repeat (check before you act, upsert rather than insert), or set `idempotency_enabled = true` **and** `idempotency_ttl = ` in `settings.toml` -- the framework then skips an event whose id and source (and named connection, when it came from one) it has already dispatched, within that window. Dedup needs `.with_cache()` -- startup fails without one -- and holds across replicas only on a Redis cache: a disk cache's claim holds within one process, so replicas sharing a cache directory can both win it. Off by default on purpose: only you know whether replaying your side effects is acceptable. - **`self.extract_payload(event, ModelType)`** — validates `event.data` against a Pydantic model and returns a typed instance. Raises `InvalidEventError` if data is missing or invalid (the framework handles this automatically). - **The service gets no CloudEvent and no DTO.** Translate the payload into domain values (ids, domain models) in the handler; that is what lets a REST API call the same service method. - **`context["runtime"]`** holds the agent runtime the chain bound for this handler. It is there for @@ -209,9 +210,9 @@ class CleanupScheduler(SchedulerBase): await self._service.cleanup() ``` -- **Override `on_startup` only if you also call `super().on_startup()`.** The base class is - what starts the timer, wires the tick handler and registers `POST /api//trigger` - (`/api//scheduler//trigger` in a group). +- **Override `on_startup` only if you also call `super().on_startup()`.** `build()` wires the + tick handler and registers `POST /api//trigger` (`/api//scheduler//trigger` + in a group); `super().on_startup()` starts the in-process timer and the tick-age gauge. - **`scheduler_mode` decides what calls `tick()`, and it is required.** It has no default: registering a scheduler without setting it fails at startup, because neither value is safe to inherit silently. `"event"` starts no timer in the process -- the tick arrives as an ordinary @@ -219,8 +220,11 @@ class CleanupScheduler(SchedulerBase): queue group already guarantees that exactly one replica runs it; it needs `event_bus` set to `"dapr"` or `"nats"`. `"in_process"` runs an APScheduler timer in **every** replica and claims each tick in the cache so one replica runs it -- so it needs `.with_cache()` to fire a - tick once. Without a cache every replica runs every tick, and startup says so. -- The crontab stays declared here in both modes; it is what the `CronJob` is generated from. + tick once, and a Redis cache once more than one replica runs it: a disk cache's claim holds + within one process only, so replicas sharing a cache directory can both win a tick. Without a + cache every replica runs every tick, and startup says so. +- The crontab stays declared here in both modes. In `"event"` mode the external `CronJob` must + publish on that schedule; nothing generates it. - **A scheduler that wants to *publish* an event needs `event_publishing_enabled = true`.** Consuming and publishing are separate: a handler implies a transport client, a scheduler does not. The key creates the client and subscribes to nothing, and it needs `event_bus` set. ### AgentRuntime (via AgentBuilder) @@ -312,8 +316,8 @@ asbs create service # Add Service asbs create api # Add RestApi asbs create agent # Add AgentRuntime asbs create scheduler [--cron CRON] # Add Scheduler -asbs validate # Validate project structure -asbs dev [--port 8000] # Run dev server +asbs validate [--group] # Validate one agent, or a whole image +asbs dev [--name NAME] [--port 8000] # Run dev server (--name: under a group namespace) asbs docs [] [--cat] # Locate the framework documentation ``` diff --git a/src/blueprint/agent_generator/claude_docs/agents/blueprint-builder.md b/src/blueprint/agent_generator/claude_docs/agents/blueprint-builder.md index ecc5c5cb..045d3f18 100644 --- a/src/blueprint/agent_generator/claude_docs/agents/blueprint-builder.md +++ b/src/blueprint/agent_generator/claude_docs/agents/blueprint-builder.md @@ -252,7 +252,7 @@ Add to `settings.toml`: 7. **Every public method needs a docstring** 8. **Services contain ALL business logic** — one method per responsibility, not one giant method 9. **Handlers and APIs are thin delegation layers** — `can_handle_event` routes on the envelope only; `handle_event` makes exactly one service call; relevance checks live in the service and come back as `HandlerResult.skipped(reason)`; handlers never call the LLM -13. **No run state on `self`** — components serve concurrent runs; per-event values stay in locals and parameters -10. **Context managers for HTTP clients, files, DB connections** -11. **Secrets in `.secrets.toml`** — never hardcoded -12. **System prompt is static** (no dynamic inputs) — **instruction prompt has dynamic inputs** +10. **No run state on `self`** — components serve concurrent runs; per-event values stay in locals and parameters +11. **Context managers for HTTP clients, files, DB connections** +12. **Secrets in `.secrets.toml`** — never hardcoded +13. **System prompt is static** (no dynamic inputs) — **instruction prompt has dynamic inputs** diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md index 7b0e61b1..2f68652e 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md @@ -41,11 +41,14 @@ These fail at startup rather than guess, so they must be set deliberately: - **`scheduler_mode`** - required once any scheduler is registered. `"in_process"` runs an APScheduler timer in *every* replica and claims each tick through the cache, so it needs - `.with_cache()` or every replica runs every tick. `"event"` starts no timer: the tick arrives as + `.with_cache()` or every replica runs every tick -- on Redis once more than one process runs + it, since a disk cache's claim holds within one process only. `"event"` starts no timer: the tick arrives as an event on `.scheduler.` (`app_name` instead of the agent at the root), so it needs `event_bus` set. - **`idempotency_enabled` and `idempotency_ttl`** - both, or neither. Delivery is at-least-once; deduplication is off by default because only you know whether replaying your side effects is - acceptable. The TTL must outlast the broker redelivery window. + acceptable. The TTL must outlast the broker redelivery window. Dedup needs `.with_cache()` + (startup fails without one), and a Redis cache to hold across replicas: a disk cache's claim + holds within one process. - **`event_publishing_enabled`** - consuming and publishing are separate concerns. A handler implies a transport client; a scheduler does not. diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md index 09186ae1..96f6bc1a 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md @@ -62,7 +62,10 @@ that is short a consumer. ## The two that break under replicas - **Schedulers.** `scheduler_mode = "in_process"` runs a timer in *every* replica and relies on the - cache to claim each tick, so without `.with_cache()` every replica runs every tick. + cache to claim each tick, so without `.with_cache()` every replica runs every tick. Across + replicas the claim holds only on Redis: a disk cache's claim holds within one process, so + replicas sharing a cache directory can both win a tick, and with a per-pod disk cache every + replica runs every tick. `scheduler_mode = "event"` starts no timer at all - an external `CronJob` publishes the tick and the queue group already guarantees one consumer. Read *Schedulers* and *Running more than one replica* together before scaling past one. diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md index 50333fa8..e49a3540 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md @@ -29,7 +29,8 @@ asbs docs components/event-handlers --cat # writing a handler pod restart, a rolling deploy. Either make the service it calls safe to repeat, or set **both** `idempotency_enabled = true` and `idempotency_ttl = `; the framework then skips an event whose id and source it has already dispatched, within that window (per named connection, when the -event came from one). It is off by default on purpose - only you know whether replaying your side +event came from one). It needs `.with_cache()` (startup fails without one), and a Redis cache to +hold across replicas (a disk cache's claim holds within one process). It is off by default on purpose - only you know whether replaying your side effects is acceptable. State your service keeps per event (an "already ingested" marker, a cache entry) is keyed by `context.get("nats_connection")` too: each named connection is its own data source. diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md index 74d8be7a..e63b7ccd 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md @@ -21,7 +21,8 @@ whether the move is actually wanted before starting it. The agent's name in `agents.toml` becomes its queue group, its JetStream durables, its cache directory and Redis prefix, its telemetry `service.name` and its `/api/` route prefix. Renaming it after the first grouped deploy is a consumer migration, not a rename. The alphabet is -`[a-z][a-z0-9_]*` - **no dashes**; a name outside it is refused, never repaired. See +`[a-z][a-z0-9_]*` - **no dashes** - and `cache`, `event_publishing`, `runtimes` and `runtime` are +reserved; a name outside it is refused, never repaired. See `blueprint-multi-agent` for why. ## What changes @@ -41,7 +42,7 @@ Nothing inside the agent's directory moves. Its `settings.toml` stays beside `sr ## Rules that bite - **Classes, not instances.** `with_rest_api(OrderApi())` is built before any namespace exists; a - group refuses it. Pass `OrderApi`. + group refuses it, and so does `create_app()`. Pass `OrderApi`. - **Nothing at import time.** The module is imported into a shared runtime: no client construction, no `logging.basicConfig()`. - **Still serving it alone?** Add `def create_app(): return agent.build(Config(...))` and run diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md index e410ec12..6ce3ac9e 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md @@ -35,7 +35,8 @@ my_agent/ It carries **no `agents.toml`**. The map says which agents an *image* contains; an agent holding one would be an agent that knows whether it is running alone. Whoever hosts it supplies the name: -a group image's map, a single-agent image's Dockerfile, or `asbs dev --name`. +a group image's map, or `asbs dev --name`. A single-agent image's Dockerfile supplies none: it +serves `create_app()` at the root. The image, at the top of the repository: @@ -84,7 +85,8 @@ Renaming it after the first grouped deploy is a **consumer migration** - new dur still pending on the old ones - not a rename. Choose it once, before deploying. The namespace alphabet is **`[a-z][a-z0-9_]*`**: lower case, leading letter, underscores allowed, -**no dashes**. A name outside it is refused, never repaired. The dash is excluded because it +**no dashes**, and not one of the reserved names `cache`, `event_publishing`, `runtimes`, `runtime` +(configuration sections the whole process shares). A name outside it is refused, never repaired. The dash is excluded because it separates the parts of a durable name, so `orders-eu` on topic `created` and `orders` on topic `eu-created` would otherwise produce the same durable and two agents would eat each other's events. @@ -165,10 +167,14 @@ sole group is taken silently whatever it turns out to contain. context. A group file baked into a layer makes the image serve the group that happened to be on disk when it was built, which is the opposite of the point. -If the group cannot be resolved -- nothing naming agents, a group absent from the file, an agent -the image does not contain -- the process prints one line and **exits before binding its port**, -so an orchestrator restarts it with something actionable rather than reporting a healthy replica -that is quietly short a consumer. +If the group cannot be resolved -- nothing naming agents, a group absent from the file, a group +name declared twice in it, `agents` or `critical_agents` written as a scalar instead of a list, a +critical name that is not among the agents the group runs (`BLUEPRINT_AGENTS` included), a +critical agent the image does not contain, or no agent left to run -- the process prints one line +and **exits before binding its port**, so an orchestrator restarts it with something actionable +rather than reporting a healthy replica that is quietly short a consumer. Without +`critical_agents` every agent is critical; a non-critical agent the image lacks is skipped with an +ERROR instead. ## Before promising the move is free @@ -177,5 +183,6 @@ its broker-side identity once, and its cache starts cold. Both are set out under what does not* in `guides/multi-agent-setup` - read that section before telling anyone the migration is invisible, because for a migrated agent it is not. -Run `asbs validate` after migrating. It reads files only, never imports the project, and checks the -namespace alphabet, the agent map and the module attribute. +Run `asbs validate` after migrating. It reads files and starts nothing (it imports only the parent +packages of a configured `nats_connection_source`), and checks the namespace alphabet, the agent +map and the module attribute. diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-testing/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-testing/SKILL.md index 806b4d70..1f1a6002 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-testing/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-testing/SKILL.md @@ -36,8 +36,9 @@ dependencies in `on_startup()`. So a unit test must **call `on_startup()` itself the mock registry - constructing the component is not enough, and a test that skips it will fail on an attribute that production code sets correctly. -Schedulers additionally require `await super().on_startup()` inside any overridden `on_startup`; the -base class is what starts the timer and registers the trigger route. +Schedulers additionally require `await super().on_startup()` inside any overridden `on_startup`; it +starts the in-process timer and the tick-age gauge (`build()` registers the trigger route and the +tick handler). ## Running diff --git a/src/blueprint/agent_generator/claude_docs/skills/blueprint-troubleshooting/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-troubleshooting/SKILL.md index 96fbae72..0562630d 100644 --- a/src/blueprint/agent_generator/claude_docs/skills/blueprint-troubleshooting/SKILL.md +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-troubleshooting/SKILL.md @@ -22,7 +22,8 @@ Provider Issues, Component Registration Errors, Health Check Failures, Cache Iss asbs validate ``` -It reads files only - it never imports the project - and grades what it finds: **issues** (will not +It reads files and starts nothing - the one import is locating a configured +`nats_connection_source`, which imports that module's parent packages - and grades what it finds: **issues** (will not start, exit 1), **warnings** (will start, something is missing), **notices** (a decision the framework will not make for you). It catches most misconfiguration before a stack trace does. @@ -33,8 +34,8 @@ framework will not make for you). It catches most misconfiguration before a stac | `AttributeError` on `self.registry` or `self.config` | Accessed in `__init__`. Resolve in `on_startup()` | | Component not found at runtime | Registered after its dependent. Services go before handlers, agents and APIs | | Scheduler never fires | `scheduler_mode` unset, or an overridden `on_startup` that never calls `await super().on_startup()` | -| Every replica runs every scheduled tick | `scheduler_mode = "in_process"` without `.with_cache()` | -| The same event processed twice | At-least-once delivery. Make it repeatable, or set both `idempotency_enabled` and `idempotency_ttl` | +| Every replica runs every scheduled tick | `scheduler_mode = "in_process"` without `.with_cache()`, or with a disk cache: across replicas the claim needs Redis | +| The same event processed twice | At-least-once delivery. Make it repeatable, or set both `idempotency_enabled` and `idempotency_ttl` with `.with_cache()` (on Redis across replicas) | | Handler never reached | An earlier handler in the priority chain returned a `HandlerResult` and stopped the chain | | Events vanish after a rename | The agent namespace is part of every durable name - see `blueprint-multi-agent` | | Cache fails at startup | The disk backend needs a writable volume; a read-only root filesystem fails immediately | diff --git a/src/blueprint/agent_generator/docs/components/agents.md b/src/blueprint/agent_generator/docs/components/agents.md index 06da738b..9f1f1b77 100644 --- a/src/blueprint/agent_generator/docs/components/agents.md +++ b/src/blueprint/agent_generator/docs/components/agents.md @@ -358,7 +358,10 @@ class TicketService(ServiceBase): self._classifier = None async def on_startup(self) -> None: - self._classifier = self.registry.get_component("ticket_classifier") + self._classifier = self.registry.get_agent("ticket_classifier") + + async def on_shutdown(self) -> None: + pass async def classify_ticket(self, ticket_text: str) -> dict: if self._classifier: @@ -375,8 +378,8 @@ class TicketService(ServiceBase): return { "category": result.output.category, - "confidence": result.data.confidence, - "subcategories": result.data.subcategories, + "confidence": result.output.confidence, + "subcategories": result.output.subcategories, } ``` @@ -445,27 +448,38 @@ Mock the agent runtime to test services and handlers independently of the LLM. import pytest from unittest.mock import AsyncMock, MagicMock +from blueprint.agents.component.component import Component +from blueprint.agents.component.registry import Registry + + +@pytest.fixture +def mock_registry(): + """Install a mock registry for every component constructed while the test runs.""" + registry = MagicMock(spec=Registry) + Component.shared_registry = registry + yield registry + Component.reset_shared_state() + @pytest.fixture def mock_classifier(): classifier = AsyncMock() + classifier.get_prompt = MagicMock(return_value="Classify: {ticket_text}") result = MagicMock() - result.data = MagicMock() - result.data.category = "billing" - result.data.confidence = 0.92 - result.data.subcategories = ["invoice", "payment"] + result.output = MagicMock() + result.output.category = "billing" + result.output.confidence = 0.92 + result.output.subcategories = ["invoice", "payment"] classifier.run.return_value = result classifier.record_metrics = MagicMock() return classifier @pytest.fixture -async def ticket_service(mock_classifier): - mock_registry = MagicMock() +async def ticket_service(mock_registry, mock_classifier): mock_registry.get_agent.return_value = mock_classifier service = TicketService() - service.registry = mock_registry await service.on_startup() return service @@ -481,7 +495,7 @@ async def test_classify_ticket(ticket_service, mock_classifier): @pytest.mark.asyncio -async def test_handler_delegates_to_service(mock_classifier): +async def test_handler_delegates_to_service(mock_registry): mock_service = AsyncMock() mock_service.classify_ticket.return_value = { "category": "technical", @@ -489,11 +503,9 @@ async def test_handler_delegates_to_service(mock_classifier): "subcategories": ["bug"], } - mock_registry = MagicMock() mock_registry.get_service.return_value = mock_service handler = TicketClassificationHandler() - handler.registry = mock_registry await handler.on_startup() event = MagicMock() diff --git a/src/blueprint/agent_generator/docs/components/event-handlers.md b/src/blueprint/agent_generator/docs/components/event-handlers.md index bc528b85..769a6eb2 100644 --- a/src/blueprint/agent_generator/docs/components/event-handlers.md +++ b/src/blueprint/agent_generator/docs/components/event-handlers.md @@ -45,7 +45,7 @@ class MyHandler(EventHandlerBase): ## Priority -The `priority` argument controls execution order. Handlers with a **lower** numeric priority value are evaluated first. If two handlers share the same priority, ordering is non-deterministic. +The `priority` argument controls execution order. Handlers with a **lower** numeric priority value are evaluated first. Handlers of the same priority are asked in the order they were declared, whether passed as a class or as an instance. ```python super().__init__(priority=10) # Runs early @@ -234,8 +234,8 @@ class OrderHandler(EventHandlerBase): ## Registration -Register handlers with `AppBuilder` by passing the **class** -- an instance is refused in a group, -because it would be constructed before any namespace exists. In `src/main.py` (a declaration; see +Register handlers with `AppBuilder` by passing the **class** -- an instance is refused by a group +and by `create_app()`, because it would be constructed before any namespace exists. In `src/main.py` (a declaration; see [agents](agents.md) and the `create_app()` that `asbs setup` writes): ```python @@ -248,7 +248,7 @@ agent = ( ) ``` -Services must be registered before the handlers that depend on them. +The order of the two calls does not matter for resolving: every component is constructed before any `on_startup()` runs, and services are started before handlers. ## Full Example @@ -322,17 +322,21 @@ delivery (nak and redeliver, or terminate for `InvalidEventError`). If the domai ## Testing -Use a mock registry to unit test handlers in isolation. +Use a mock registry to unit test handlers in isolation. A component registers itself when it is constructed and reads `self.registry` from the shared registry, so the fixture installs the mock as that, as the [testing guide](../guides/testing.md) does. ```python import pytest from unittest.mock import AsyncMock, MagicMock + +from blueprint.agents.component.component import Component +from blueprint.agents.component.registry import Registry from blueprint.agents.models.events import GenericCloudEvent @pytest.fixture def mock_registry(): - registry = MagicMock() + """Install a mock registry for every component constructed while the test runs.""" + registry = MagicMock(spec=Registry) invoice_service = AsyncMock() invoice_service.generate_invoice.return_value = { "invoice_id": "INV-TEST", @@ -340,13 +344,14 @@ def mock_registry(): "total": 50.00, } registry.get_service.return_value = invoice_service - return registry + Component.shared_registry = registry + yield registry + Component.reset_shared_state() @pytest.fixture async def handler(mock_registry): h = InvoiceHandler() - h._registry = mock_registry await h.on_startup() return h diff --git a/src/blueprint/agent_generator/docs/components/rest-apis.md b/src/blueprint/agent_generator/docs/components/rest-apis.md index 50c0d275..9f9296af 100644 --- a/src/blueprint/agent_generator/docs/components/rest-apis.md +++ b/src/blueprint/agent_generator/docs/components/rest-apis.md @@ -166,7 +166,7 @@ async def get_order(self, order_id: str): ## Registration -Register API instances with the application builder. `with_rest_api` receives an instance or the class: +Register APIs with the application builder. Pass the **class** (constructor arguments as keyword arguments) or a zero-argument factory: an already-built instance is refused by a group and by `create_app()`, because it was constructed before its agent's namespace existed: ```python from blueprint.agents import AppBuilder @@ -225,6 +225,12 @@ class OrderService(ServiceBase): async def cancel_order(self, order_id: str) -> dict: ... + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + # --- API --- @@ -238,6 +244,9 @@ class OrderApi(RestApiBase): async def on_startup(self) -> None: self._order_service = self.registry.get_service(OrderService) + async def on_shutdown(self) -> None: + pass + @RestApiBase.post( "/orders", response_model=OrderResponse, @@ -322,13 +331,23 @@ Use FastAPI's `TestClient` or `httpx.AsyncClient` for integration tests. For uni ```python import pytest from unittest.mock import AsyncMock, MagicMock -from fastapi.testclient import TestClient +from fastapi import HTTPException + +from blueprint.agents.component.component import Component +from blueprint.agents.component.registry import Registry @pytest.fixture -def order_api(): - api = OrderApi() - mock_registry = MagicMock() +def mock_registry(): + """Install a mock registry for every component constructed while the test runs.""" + registry = MagicMock(spec=Registry) + Component.shared_registry = registry + yield registry + Component.reset_shared_state() + + +@pytest.fixture +async def order_api(mock_registry): mock_service = AsyncMock() mock_service.create_order.return_value = { @@ -346,13 +365,13 @@ def order_api(): mock_service.list_orders.return_value = [] mock_registry.get_service.return_value = mock_service - api.registry = mock_registry + api = OrderApi() + await api.on_startup() return api @pytest.mark.asyncio async def test_create_order(order_api): - await order_api.on_startup() request = CreateOrderRequest( customer_id="CUST-1", items=[{"sku": "A", "quantity": 1, "unit_price": 99.99}], @@ -364,7 +383,6 @@ async def test_create_order(order_api): @pytest.mark.asyncio async def test_get_order_not_found(order_api): - await order_api.on_startup() order_api._order_service.get_order.return_value = None with pytest.raises(HTTPException) as exc_info: diff --git a/src/blueprint/agent_generator/docs/components/schedulers.md b/src/blueprint/agent_generator/docs/components/schedulers.md index d053d0e1..0cebf40b 100644 --- a/src/blueprint/agent_generator/docs/components/schedulers.md +++ b/src/blueprint/agent_generator/docs/components/schedulers.md @@ -1,6 +1,6 @@ # Schedulers -Schedulers run background tasks on a cron-based schedule using APScheduler. They extend RestApiBase, giving them full REST endpoint and registry access in addition to timed execution. +Schedulers run background tasks on a cron schedule. What fires the tick is set by `scheduler_mode`: an external scheduler publishing an event, or an APScheduler timer inside the process (see [Scheduler mode](#scheduler-mode)). They extend RestApiBase, giving them full REST endpoint and registry access in addition to timed execution. ## Import @@ -37,12 +37,15 @@ class MyScheduler(SchedulerBase): ## Constructor -The `crontab` parameter accepts a standard five-field cron expression: +The `crontab` parameter accepts a standard five-field cron expression. `topic` (keyword-only, optional) replaces the derived tick subject in event mode -- for ticks already published on a subject someone else owns: ```python super().__init__(crontab="*/5 * * * *") +super().__init__(crontab="0 2 * * *", topic="ops.nightly.cleanup") ``` +The crontab is declared in both modes and checked at startup in both: it must be a valid expression with exactly five fields (no seconds or year field), with the day-of-week rules below. + ## Cron Expression Reference A cron expression consists of five fields separated by spaces: @@ -73,7 +76,54 @@ A cron expression consists of five fields separated by spaces: runs the `in_process` timer. A standard cron -- the `CronJob` that fires an `event`-mode tick -- counts `0` as Sunday, so write days as names (`mon`, `mon-fri`, `sun`), which both read the same. `7` is refused, and in `event` mode so is any day given by number. The `in_process` timer runs in the -host's local time unless `scheduler_timezone` names one (`"UTC"`, `"Europe/Berlin"`). +host's local time unless `scheduler_timezone` names one (`"UTC"`, `"Europe/Berlin"`); a value +that is not an IANA timezone name fails startup. In `event` mode the key changes nothing -- the +external scheduler's own timezone decides. + +## Scheduler mode + +`scheduler_mode` has **no default**: registering a scheduler without it fails at startup, and so +does any value other than the two below (read trimmed and lower-cased, so `"Event"` is accepted). +Which mode is right depends on the deployment -- whether an orchestrator and a broker exist, how +many replicas run -- so the configuration states it. It is read through the agent's own +configuration view, so in a group each agent may set its own. + +```toml +[default] +scheduler_mode = "event" # or "in_process" +``` + +| Mode | What fires the tick | Needs | +|---|---|---| +| `event` | Something outside the process publishes an event on the scheduler's tick subject. No timer runs in the process. | `event_bus = "nats"` or `"dapr"` | +| `in_process` | An APScheduler timer in every replica, each tick claimed in the cache so one runs it. | `.with_cache()`; Redis when more than one replica runs | + +### `event` + +The tick arrives as an ordinary event on the subject `.scheduler.`, where `` +is the agent's namespace (standalone: `app_name`) and `` the scheduler's own name, without +the agent -- `orders.scheduler.data_sync_scheduler`. `topic=` replaces it. The subject is checked, +not repaired: a namespace, `app_name`, scheduler name or `topic` with whitespace or a wildcard fails +startup, because a rewritten subject would leave the publisher sending to one nobody subscribes to. + +The framework registers a tick handler for that subject, so the queue group delivers each tick to +exactly one replica, and deduplication, telemetry and acknowledgement apply as to any event. +**Nothing generates the publisher.** An external scheduler -- a Kubernetes `CronJob`, for +example -- has to publish on that subject on the declared crontab; the crontab in the code is the +contract it follows. An `event_bus` that cannot carry a topic subscription (unset, or `sessions`) +fails startup. + +### `in_process` + +Every replica's timer fires, and each one claims the tick in the agent's default cache before +running it. The claim key is the scheduler and the minute the tick was scheduled for (in UTC), +held for five minutes; the replica that stores it runs the tick and the others skip it. + +**The claim picks one winner across replicas only on Redis.** A disk cache's claim holds within +one process: with a disk cache per pod every replica runs every tick, and replicas sharing one +cache directory (or `uvicorn --workers N` run by hand) can both win a tick. With no cache +declared there is nothing to claim with: every replica runs every tick, and startup logs a +WARNING. A cache that fails while claiming fails open, so the tick runs. ## Abstract Method: tick @@ -89,15 +139,15 @@ The method must be async. If the work is CPU-bound, offload it to a thread or pr ## Lifecycle -SchedulerBase manages the APScheduler lifecycle automatically: +SchedulerBase manages its lifecycle automatically: -- **on_startup()**: The APScheduler job is created and started. Override this method to resolve service dependencies (call `super().on_startup()` if you override). -- **on_shutdown()**: APScheduler is shut down gracefully, waiting for any in-progress tick to complete. +- **on_startup()**: In `in_process` mode the APScheduler job is created and started; in `event` mode no timer starts and the tick waits for its event. Both modes register the `blueprint.scheduler.tick_age_seconds` gauge here. Override this method to resolve service dependencies, and call `super().on_startup()` -- without it the scheduler is registered and never runs. +- **on_shutdown()**: APScheduler, where one runs, is shut down gracefully, waiting for any in-progress tick to complete. ```python async def on_startup(self) -> None: self._sync_service = self.registry.get_service(SyncService) - await super().on_startup() # Starts the APScheduler job + await super().on_startup() # Starts the in_process timer, if that is the mode async def on_shutdown(self) -> None: await super().on_shutdown() # Waits for in-flight tick, then stops @@ -122,7 +172,7 @@ In a group, the trigger moves under the agent's reserved `scheduler` segment: the agent -- `/api/order/scheduler/data_sync_scheduler/trigger` -- because the path names the agent already. -This is useful for testing, debugging, and on-demand execution without waiting for the next cron interval. +This is useful for testing, debugging, and on-demand execution without waiting for the next cron interval. The trigger runs the tick at once in the replica that answers the request, in both modes and without a claim. ## Accessing Registry and Config @@ -130,14 +180,14 @@ Since SchedulerBase extends RestApiBase, which extends Component, you have full ```python async def tick(self) -> None: - threshold = self.config.get("cleanup_threshold_hours", 24) - cache = self.registry.cache_service - await cache.evict_older_than(hours=threshold) + namespace = self.config.get("report_cache_namespace", "reports") + cache = self.registry.cache_service # synchronous: not awaited + cache.clear(namespace=namespace) ``` ## Registration -Register scheduler instances with the application builder. Note that `with_scheduler` receives an instance or a class: +Register the scheduler with the application builder. Pass the **class** (constructor arguments as keyword arguments) or a zero-argument factory: an already-built instance is refused by a group and by `create_app()`, because it was constructed before its agent's namespace existed: ```python from blueprint.agents import AppBuilder @@ -172,6 +222,9 @@ class ExternalApiClient(ServiceBase): async def on_startup(self) -> None: self._base_url = self.config.get("external_api_url") + async def on_shutdown(self) -> None: + pass + async def fetch_product_catalog(self) -> list[dict]: """Retrieve the latest product catalog from the external API.""" # In production, use httpx or aiohttp here @@ -193,6 +246,9 @@ class CatalogService(ServiceBase): self._api_client = self.registry.get_service(ExternalApiClient) self._cache = self.registry.cache_service + async def on_shutdown(self) -> None: + pass + async def sync_catalog(self) -> int: """Fetch the remote catalog and update the local cache. @@ -204,7 +260,7 @@ class CatalogService(ServiceBase): products = await self._api_client.fetch_product_catalog() for product in products: - await self._cache.set( + self._cache.set( # the cache is synchronous: not awaited f"product:{product['sku']}", product, ttl=3600, # 1 hour TTL @@ -216,7 +272,7 @@ class CatalogService(ServiceBase): async def get_product(self, sku: str) -> dict | None: """Retrieve a product from cache.""" assert self._cache is not None - return await self._cache.get(f"product:{sku}") + return self._cache.get(f"product:{sku}") # --- Scheduler --- @@ -258,18 +314,30 @@ agent = ( With this configuration: -- The `CatalogSyncScheduler.tick()` method runs every 15 minutes. +- The `CatalogSyncScheduler.tick()` method runs every 15 minutes -- fired by the in-process timer or by an external publisher on `.scheduler.catalog_sync_scheduler`, as `scheduler_mode` says. - Manual triggering is available at `POST /api/catalog_sync_scheduler/trigger`. - The scheduler delegates all logic to `CatalogService`, which in turn uses `ExternalApiClient` and the cache. ## Testing -Test the scheduler's `tick()` method by mocking the service dependency. The APScheduler internals do not need to be tested directly. +Test the scheduler's `tick()` method by mocking the service dependency. The APScheduler internals do not need to be tested directly. A component registers itself when it is constructed, so install a mock registry for the test, as the [testing guide](../guides/testing.md) does: ```python import pytest from unittest.mock import AsyncMock, MagicMock +from blueprint.agents.component.component import Component +from blueprint.agents.component.registry import Registry + + +@pytest.fixture +def mock_registry(): + """Install a mock registry for every component constructed while the test runs.""" + registry = MagicMock(spec=Registry) + Component.shared_registry = registry + yield registry + Component.reset_shared_state() + @pytest.fixture def mock_catalog_service(): @@ -279,13 +347,9 @@ def mock_catalog_service(): @pytest.fixture -async def scheduler(mock_catalog_service): - mock_registry = MagicMock() - mock_registry.get_service.return_value = mock_catalog_service - +def scheduler(mock_registry, mock_catalog_service): sched = CatalogSyncScheduler() - sched.registry = mock_registry - # Resolve dependencies without starting APScheduler + # Inject the dependency directly instead of running on_startup(), so no timer starts sched._catalog_service = mock_catalog_service return sched @@ -301,25 +365,4 @@ async def test_tick_handles_errors(scheduler, mock_catalog_service): mock_catalog_service.sync_catalog.side_effect = ConnectionError("API down") # tick should not propagate the exception await scheduler.tick() # Logs the error, does not raise - - -@pytest.fixture -def mock_registry_for_integration(): - registry = MagicMock() - - mock_api_client = AsyncMock() - mock_api_client.fetch_product_catalog.return_value = [ - {"sku": "TEST-1", "price": 10.0, "stock": 5}, - ] - - mock_cache = AsyncMock() - mock_cache.get.return_value = None - - registry.get_service.side_effect = lambda cls: { - ExternalApiClient: mock_api_client, - CatalogService: None, # Will be created fresh - }.get(cls) - registry.cache_service = mock_cache - - return registry ``` diff --git a/src/blueprint/agent_generator/docs/components/services.md b/src/blueprint/agent_generator/docs/components/services.md index 59b8e5c5..67791000 100644 --- a/src/blueprint/agent_generator/docs/components/services.md +++ b/src/blueprint/agent_generator/docs/components/services.md @@ -80,7 +80,7 @@ async def on_startup(self) -> None: self._cache = self.registry.cache_service ``` -The cache service is always available once the application has started. Use it for in-memory or distributed caching depending on your deployment configuration. +The cache exists only when the application declares one with `.with_cache()`; without it `cache_service` raises. Its backend is a local disk store or Redis, chosen by configuration, and its interface is synchronous -- see [caching](../concepts/caching.md). ## Accessing Configuration @@ -111,7 +111,7 @@ agent = ( ) ``` -Note that `with_service` receives the **class**: a group refuses an instance, because it would be constructed before any namespace exists. +Note that `with_service` receives the **class**: a group and `create_app()` refuse an instance, because it would be constructed before any namespace exists. ## Best Practices @@ -156,6 +156,9 @@ class PricingService(ServiceBase): async def on_startup(self) -> None: self._discount_threshold = self.config.get("discount_threshold", 100.0) + async def on_shutdown(self) -> None: + pass + def calculate_total(self, items: list[OrderItem]) -> float: subtotal = sum(item.quantity * item.unit_price for item in items) if subtotal >= self._discount_threshold: @@ -175,7 +178,10 @@ class OrderService(ServiceBase): async def on_startup(self) -> None: self._pricing = self.registry.get_service(PricingService) self._summarizer = self.registry.get_agent("order_summarizer") - self._cache = self.registry.cache_service + self._cache = self.registry.cache_service # needs .with_cache() + + async def on_shutdown(self) -> None: + pass async def create_order(self, customer_id: str, items: list[dict]) -> Order: """Create a new order with calculated pricing.""" @@ -193,14 +199,14 @@ class OrderService(ServiceBase): # Cache the order for quick retrieval if self._cache: - await self._cache.set(f"order:{order.order_id}", order.model_dump()) + self._cache.set(f"order:{order.order_id}", order.model_dump()) # synchronous return order async def get_order(self, order_id: str) -> Order | None: """Retrieve an order, checking cache first.""" if self._cache: - cached = await self._cache.get(f"order:{order_id}") + cached = self._cache.get(f"order:{order_id}") if cached: return Order(**cached) return None @@ -211,7 +217,7 @@ class OrderService(ServiceBase): result = await self._summarizer.run( f"Summarize this order: {order.model_dump_json()}" ) - return result.data + return result.output def _generate_id(self) -> str: import uuid @@ -220,32 +226,39 @@ class OrderService(ServiceBase): ## Testing -Services are straightforward to test because they are plain Python classes. Mock the registry and any dependencies. +Services are straightforward to test because they are plain Python classes. Mock the registry and any dependencies. A component registers itself when it is constructed and reads `self.registry` from the shared registry, so install a mock one for the test, as the [testing guide](../guides/testing.md) does: ```python import pytest from unittest.mock import AsyncMock, MagicMock +from blueprint.agents.component.component import Component +from blueprint.agents.component.registry import Registry + @pytest.fixture -def pricing_service(): - service = PricingService() - service.config = MagicMock() - service.config.get.return_value = 100.0 - return service +def mock_registry(): + """Install a mock registry for every component constructed while the test runs.""" + registry = MagicMock(spec=Registry) + Component.shared_registry = registry + yield registry + Component.reset_shared_state() + + +@pytest.fixture +def pricing_service(mock_registry): + # on_startup() would read discount_threshold from config; the constructor default (100.0) is enough here + return PricingService() @pytest.fixture -async def order_service(pricing_service): - mock_registry = MagicMock() +async def order_service(mock_registry, pricing_service): mock_registry.get_service.return_value = pricing_service mock_registry.get_agent.return_value = AsyncMock() - mock_registry.cache_service = AsyncMock() + mock_registry.cache_service = MagicMock() # the cache interface is synchronous mock_registry.cache_service.get.return_value = None service = OrderService() - service.registry = mock_registry - await pricing_service.on_startup() await service.on_startup() return service diff --git a/src/blueprint/agent_generator/docs/concepts/architecture.md b/src/blueprint/agent_generator/docs/concepts/architecture.md index 2596d3dd..31016c13 100644 --- a/src/blueprint/agent_generator/docs/concepts/architecture.md +++ b/src/blueprint/agent_generator/docs/concepts/architecture.md @@ -58,11 +58,11 @@ def create_app(): ### Builder Methods Every `with_*` call records; nothing is constructed until `build()`. Components are passed as -**classes** -- a group refuses an instance, because it would exist before any namespace does. +**classes** -- a group and `create_app()` refuse an instance, because it would exist before any namespace does. - `.with_service(ServiceClass)` -- Register a service. Services start before handlers and agents, so they are available for dependency resolution. - `.with_agent(agent_builder, name="...")` -- Register an AI agent runtime from an unbuilt `AgentBuilder`. The name is the registry key services resolve it by. -- `.with_handler(HandlerClass)` -- Register an event handler. Handlers are sorted by priority at runtime. +- `.with_handler(HandlerClass)` -- Register an event handler. Handlers are sorted by priority at runtime; equal priorities keep declaration order. - `.with_rest_api(ApiClass)` -- Register a REST API module. Routes are mounted on the shared FastAPI instance. - `.with_scheduler(SchedulerClass)` -- Register a scheduled task. Schedulers start after the APIs and stop before them. - `.with_cache()` -- Enable the built-in cache service. Once enabled, it is accessible through the registry. @@ -98,7 +98,7 @@ class EmbeddingService(ServiceBase): |---|---| | `self.registry.get_service(ServiceClass)` | Resolve a service instance by its class type | | `self.registry.get_agent(name)` | Resolve an agent runtime by its registered name | -| `self.registry.cache_service` | Access the shared cache service instance | +| `self.registry.cache_service` | This agent's default cache (declared with `.with_cache()`) | ## Component Lifecycle diff --git a/src/blueprint/agent_generator/docs/concepts/caching.md b/src/blueprint/agent_generator/docs/concepts/caching.md index de9c02bb..54352f10 100644 --- a/src/blueprint/agent_generator/docs/concepts/caching.md +++ b/src/blueprint/agent_generator/docs/concepts/caching.md @@ -75,7 +75,11 @@ class DeduplicationHandler(EventHandlerBase): ``` **The cache interface is synchronous.** `get`, `set` and the rest are ordinary methods; they are -not awaited, even inside `async def`. Operations are sub-millisecond on both backends. +not awaited, even inside `async def`, and they block the thread that calls them. On disk that is +short. On Redis a call waits for the server, and one that stops answering holds the call until +`redis_socket_timeout` (redis-py's own default, 5 s, when unset). The framework's own claims -- event +deduplication and the scheduler tick -- run in a worker thread for that reason; a component calling +the cache from `async def` blocks the event loop for as long as the call takes. `self.registry` answers for the component's own agent, so `get_cache("sessions")` reaches this agent's `sessions` cache and cannot reach anyone else's. @@ -100,12 +104,17 @@ agent's `sessions` cache and cannot reach anyone else's. `exists` followed by `set` is not a lock. Two callers racing on the same key both pass the `exists` check before either `set` lands, and both then believe they hold it. `claim` is the set-if-absent primitive that closes the race -- `SET NX EX` on Redis, `add` on a lock-protected -disk cache -- and it is what event deduplication and the scheduler tick use to pick one winner -among several replicas. +disk cache -- and it is what event deduplication and the scheduler tick use to pick one winner. + +**How far a claim holds depends on the backend.** On Redis it is atomic across every process that +shares the server, so it picks one winner among replicas. On disk it is atomic between the threads +of one process only. Several processes may open one directory -- replicas sharing a cache volume, or +`uvicorn --workers N` run by hand -- and see each other's entries, but two of them claiming one key +at the same moment can both win. A claim that must hold across replicas needs the Redis backend. ```python if not self.cache.claim(event.id, "processing", namespace="dedup", ttl=600): - return None # another replica got there first + return None # another caller got there first ``` ### Keys and namespaces @@ -194,7 +203,7 @@ default_ttl = 3600 # seconds | `eviction_policy` | `str` | `"least-recently-used"` | disk | | `default_ttl` | `int` | `3600` | both | | `key_prefix` | `str` | `""` | redis | -| `redis_url` | `str \| None` | `redis://localhost:6379/0` | redis | +| `redis_url` | `str \| None` | unset -- connects to `redis://localhost:6379/0` | redis | | `redis_password` | `str \| None` | `None` | redis -- read it from a secrets file | | `redis_db` | `int` | `0` | redis | | `redis_tls` | `bool` | `false` | redis | @@ -221,9 +230,10 @@ key_prefix = "orders-api" ### Disk (default) Backed by `diskcache-rs`, a Rust implementation of the diskcache format. Persists to -`cache_dir`, survives restarts, and uses file-based locking so replicas sharing one mounted -directory can read and write it safely. Nothing has to be installed and nothing has to be -configured. +`cache_dir`, survives restarts, and needs nothing installed or configured. Several processes may +open one directory (a volume shared by replicas, or `uvicorn --workers N` run by hand) and they see each +other's entries, but a `claim` is not atomic between them -- see +[`claim`](#claim-deciding-which-process-does-the-work). ### Redis diff --git a/src/blueprint/agent_generator/docs/concepts/configuration.md b/src/blueprint/agent_generator/docs/concepts/configuration.md index 49162480..10ccd953 100644 --- a/src/blueprint/agent_generator/docs/concepts/configuration.md +++ b/src/blueprint/agent_generator/docs/concepts/configuration.md @@ -1,6 +1,6 @@ # Configuration -Blueprint Agents uses a layered configuration system built on Dynaconf. Configuration is loaded from TOML files, with support for environment variable interpolation, environment-specific overrides, and structured sections for each framework subsystem. +Blueprint Agents uses a layered configuration system built on Dynaconf. Configuration is loaded from TOML files, with environment variable overrides, environment-specific sections, and structured sections for each framework subsystem. ## Config Class @@ -33,46 +33,48 @@ A separate file for sensitive values such as API keys, connection strings, and c ```toml [default] -openai_api_key = "sk-..." -database_connection_string = "postgresql://user:pass@host/db" +model_api_key = "YOUR_API_KEY_HERE" +database_connection_string = "postgresql://USER:PASSWORD@HOST/DB" ``` -## Environment Variable Interpolation +## Values from the Environment -Any value in a TOML file can reference an environment variable using the `${ENV_VAR}` syntax. This is useful for deployment environments where secrets are injected through the platform. +The framework does **no** `${ENV_VAR}` interpolation: `nats_url = "${NATS_URL}"` is read as that +literal string. There are two ways to take a value from the environment: + +- **Override the key.** `DYNACONF_` replaces the key outright (`DYNACONF_NATS_URL`, + `DYNACONF_MODEL_API_KEY`); an `envvar_prefix` adds a second spelling. See + [configuration keys](../reference/configuration-keys.md) for the prefix and for nested keys. +- **Dynaconf's `@format` token**, inside the file: ```toml [default] -openai_api_key = "${OPENAI_API_KEY}" -nats_url = "${NATS_URL}" -database_url = "${DATABASE_URL}" +nats_url = "@format {env[NATS_URL]}" ``` -If the environment variable is not set, Dynaconf will raise an error at startup. - ## Configuration Sections ### AI Runtime Configuration -Each registered agent runtime has its own configuration block under `[default.runtimes.]`. The name must match the name used in `.with_agent(name, ...)`. +Each agent runtime has its own configuration block under `[default.runtimes.]`. The name must match the `runtime_name` given to `AgentBuilder`. A key the block leaves out falls back to the same key at the top level, so a shared `model_api_key` can live once in `.secrets.toml`. ```toml [default.runtimes.summarizer] model_provider = "openai" model_name = "gpt-4o" -model_api_key = "${OPENAI_API_KEY}" model_max_tokens = 4096 model_temperature = 0.3 model_base_url = "https://api.openai.com/v1" [default.runtimes.classifier] -model_provider = "anthropic" -model_name = "claude-sonnet-4-20250514" -model_api_key = "${ANTHROPIC_API_KEY}" +model_provider = "openai" +model_name = "gpt-4o-mini" model_max_tokens = 2048 model_temperature = 0.0 ``` +`model_provider` is `"openai"` or `"vllm"`; any other value is refused when the runtime is built. + ### Cache Configuration Settings for the built-in disk cache service, under `[default.cache]`. @@ -138,7 +140,7 @@ class StorageService(ServiceBase): ### AI Runtime Configuration -Use `get_ai_config()` to retrieve the full configuration block for a named runtime. This returns a structured object with all model-related settings. +Use `get_ai_config()` to retrieve the full configuration block for a named runtime. This returns an `AIConfig` with the model settings, the top-level fallback already applied. ```python from blueprint.agents.services.service_base import ServiceBase @@ -148,10 +150,10 @@ class ModelService(ServiceBase): async def on_startup(self) -> None: ai_config = self.config.get_ai_config("summarizer") - provider = ai_config.model_provider # "openai" - model = ai_config.model_name # "gpt-4o" - max_tokens = ai_config.model_max_tokens # 4096 - temperature = ai_config.model_temperature # 0.3 + provider = ai_config.provider # "openai" + model = ai_config.model_name # "gpt-4o" + max_tokens = ai_config.max_tokens # 4096 + temperature = ai_config.temperature # 0.3 ``` ### Cache Configuration @@ -168,27 +170,23 @@ print(cache_config.default_ttl) # 3600 ## Validation -Configuration is validated automatically when `AppBuilder.build()` is called. If required settings are missing or have invalid types, a `ConfigError` is raised with a descriptive message. +There is no schema check up front. Each part of the framework checks what it reads, when it reads it -- most of it in `AppBuilder.build()` and during startup -- and fails with a message naming the key. `Config(...)` itself raises `ConfigError` (`blueprint.agents.config.config`) for what it checks on load -- an `app_port` outside 1-65535, a `vllm` default runtime without an API key -- and so does an agent's settings file that cannot be read; a runtime without a model name or provider raises `ValueError` from `build()`. ```python from blueprint.agents import AgentBuilder, AppBuilder, Config +from blueprint.agents.config.config import ConfigError summarizer = AgentBuilder(runtime_name="summarizer").with_model_from_config() agent = AppBuilder().with_agent(summarizer, name="summarizer") try: app = agent.build(Config(settings_files=["settings.toml"])) -except ConfigError as e: - # e.g., "Missing required config: default.runtimes.summarizer.model_provider" +except (ConfigError, ValueError) as e: + # e.g., "No model name for runtime agent 'summarizer' configured" print(f"Configuration error: {e}") ``` -Validation checks include: - -- Required fields for each registered runtime (model_provider, model_name) -- Valid event bus selection ("dapr" or "nats") -- Topic mappings exist for all declared published event types -- Cache configuration is present when `.with_cache()` is used +Among the checks: each runtime's model name and provider; `event_bus` (`"dapr"`, `"nats"` or `"sessions"`) against what the application needs, such as a transport that can carry a scheduler's tick; `scheduler_mode` where a scheduler is registered; `idempotency_ttl` and a cache where deduplication is on. `asbs validate` runs the static ones without starting anything -- see [validate](../guides/cli/validate.md). ## Full Example settings.toml @@ -213,17 +211,16 @@ default_pubsub_name = "pubsub" "document.error" = "documents-errors" # AI runtimes +# model_api_key lives in .secrets.toml, or comes from DYNACONF_MODEL_API_KEY [default.runtimes.summarizer] model_provider = "openai" model_name = "gpt-4o" -model_api_key = "${OPENAI_API_KEY}" model_max_tokens = 4096 model_temperature = 0.3 [default.runtimes.classifier] -model_provider = "anthropic" -model_name = "claude-sonnet-4-20250514" -model_api_key = "${ANTHROPIC_API_KEY}" +model_provider = "openai" +model_name = "gpt-4o-mini" model_max_tokens = 2048 model_temperature = 0.0 @@ -254,13 +251,30 @@ my_agent/ In a group, the image's `agents.toml` states that directory with `root`, and the file is merged under the agent's own scope -- so the agent keeps writing plain keys and never learns that a -scope exists. It is **stated, never derived**: a root guessed from where the declaration module +scope exists. The agent's `.secrets.toml` beside it is merged the same way, first, so a key both +files set takes the secrets file's value; no value from it is ever logged. What the group's own +configuration already says for the agent -- a `[default.]` section in the image's +settings, or an environment override such as `DYNACONF___` -- wins over both. It is **stated, never derived**: a root guessed from where the declaration module happens to sit is right for one layout and silently wrong for every other, and an agent whose settings file was looked for in the wrong place does not fail. It runs on the group's defaults and says nothing. A `settings.toml` inside `src/` is **refused**, not ignored, for that reason. +### Names an agent cannot have + +An agent's settings live under its name at the top of the tree, so a few names are taken: + +- **`cache`, `event_publishing`, `runtimes` and `runtime`** -- the sections the whole process + shares. An agent of that name is refused. +- **A plain key of the group's own configuration.** If the image's settings set `orders = "..."` + as a value rather than a section, an agent called `orders` with settings of its own is refused + at merge, because merging would replace that value for the whole process. + +And through its configuration view an agent reads only its own keys and the shared ones: a bare +key that is another agent's name (`self.config.get("billing")`) raises instead of returning that +agent's section, and so does a dotted key outside the shared sections. + ### The file must not name its own agent It *becomes* that agent's scope when merged, so a section named after the agent nests twice: @@ -271,15 +285,22 @@ It *becomes* that agent's scope when merged, so a section named after the agent Refused at merge, and reported by `asbs validate --group`. Write the keys at the top level or under a plain `[default]`; that form resolves standalone as well, because a scoped lookup falls back to -the root key. Other top-level tables are untouched -- `[cache]` is this agent's cache -configuration, not a scope. +the root key. + +Environment sections are layered as Dynaconf layers the process's own: top-level keys, then +`[default]`, then the section of the active environment, then `[global]`. A table is an environment +section when it is named `development`, `production`, `staging`, `testing` or `test`, or after a +top-level table of the process's own settings files; one for another environment is dropped. Any +other top-level table is a value -- `[cache]` is this agent's cache configuration, not a scope. ### Keys an agent cannot set Some keys describe the *process*, and one process has one of each: `app_port`, `app_host`, `app_workers`, `app_environment`, `envvar_prefix`, `event_bus`, `log_level`, `log_format`, `suppress_noisy_loggers`, `health_check_interval_seconds`, `startup_retry_interval_seconds`, -`readiness_policy`, `nats_stream_name`. +`readiness_policy`, `dot_placeholder`, `nats_stream_name`, `nats_connection_source`, +`nats_extra_runs_per_process`. The deployment's identity (`blueprint_group`, `pod_name`, +`hostname`) is dropped the same way. They belong in the image's own `settings.toml`, beside `agents.toml`. Set in an agent's file they are dropped before the merge, with a warning naming the value the process uses instead -- diff --git a/src/blueprint/agent_generator/docs/concepts/event-processing.md b/src/blueprint/agent_generator/docs/concepts/event-processing.md index a288cea8..9e3fa795 100644 --- a/src/blueprint/agent_generator/docs/concepts/event-processing.md +++ b/src/blueprint/agent_generator/docs/concepts/event-processing.md @@ -297,7 +297,7 @@ lost -- nothing redelivers it and nothing records it. |---------|-------------| | The handler chain returned and every result was published, including "no handler matched" | `ack` | | A result could not be published | `nak` -- the handler runs again on redelivery; with deduplication on, its marker is released first | -| `RetryableHandlerError`, or any unexpected exception | `nak` -- redelivered after `nats_ack_wait` | +| `RetryableHandlerError`, or any unexpected exception | `nak` -- redelivered at once, not after `nats_ack_wait` | | `InvalidEventError` or `CriticalHandlerError` | dead-lettered, then `term` | | The payload is not a parseable CloudEvent | dead-lettered, then `term` | | The last delivery `nats_max_deliver` allows failed again (only when `nats_max_deliver` is set) | dead-lettered, then `term` | @@ -338,9 +338,15 @@ for immediate redelivery, up to `nats_max_deliver` attempts. Whether the limit w the run's own timer: a `TimeoutError` raised by the handler is an ordinary failure. An existing consumer is never rewritten. Its filter subject and deliver group are broker-side -state that the stream's redelivery bookkeeping hangs off, so changing them is a migration: the -client logs which settings differ and keeps consuming with the ones the broker already has. Apply -new values by deleting the consumer during a maintenance window. +state that the stream's redelivery bookkeeping hangs off, so changing them is a migration. A +consumer whose deliver group, `ack_wait`, `max_ack_pending` or `max_deliver` differs from the +configuration is kept: the client logs a WARNING naming the differences and consumes with the +values the broker already has. Apply new values by deleting the consumer during a maintenance +window. A consumer of that durable name whose filter is **another subject** is not bound at all, +because it belongs to another subscription: the client raises `JetStreamBindingError` into the +connection's retry loop and keeps retrying. A root topic and an agent's topic can derive one +durable name (root `orders-created`, agent `orders` on `created`); rename one of the topics, or +delete the consumer if it is stale. ## Broker Startup Resilience @@ -375,7 +381,9 @@ event_client_retry_delay = 2.0 | `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. +Under NATS the first connect of each attempt is bounded even with unlimited reconnects (`nats_max_reconnect_attempts = -1`, the default), so an absent broker fails the attempt instead of holding it for ever, and the retry loop decides what follows. Once connected, `nats_max_reconnect_attempts` governs reconnects. + +When all retries are exhausted (i.e. `event_client_max_retries >= 0` and the limit is reached), one `ERROR` line names the agent and the error, with credentials redacted and no traceback. The application remains live but permanently not-ready. ### Kubernetes probe recommendations diff --git a/src/blueprint/agent_generator/docs/concepts/observability.md b/src/blueprint/agent_generator/docs/concepts/observability.md index 03016c2e..6fdd89b7 100644 --- a/src/blueprint/agent_generator/docs/concepts/observability.md +++ b/src/blueprint/agent_generator/docs/concepts/observability.md @@ -43,7 +43,7 @@ its own resource: | Attribute | Value | |---|---| | `service.name` | The agent's own name. `otel_service_name` for the root namespace. | -| `deployment.group` | `BLUEPRINT_GROUP`. Absent when no group is set -- a single-agent application belongs to none. Set by the framework; no supported API exposes it to an agent (C6). | +| `deployment.group` | The group the process resolved -- `BLUEPRINT_GROUP`, or the one group a mounted group file declares. Absent for a standalone agent and for a group nothing named (`BLUEPRINT_AGENTS` alone). Set by the framework; no supported API exposes it to an agent (C6). | | `service.instance.id` | `POD_NAME`, else `HOSTNAME`, else the host name. When none can be told, the framework sets nothing and the OpenTelemetry SDK's own default applies. | **What the deployment declares wins.** A key set in `OTEL_RESOURCE_ATTRIBUTES` (or @@ -122,6 +122,8 @@ An exception propagating out of the method sets the span status to `ERROR` befor | `blueprint.events.skipped` | counter | Events whose responsible handler returned `HandlerResult.skipped` -- the agent's own relevance rule, not a too-broad subscription. Carries `agent` and `topic`. | | `blueprint.nats.connection.bound` | gauge | `1` while a named NATS connection is bound and delivering, `0` otherwise. Carries `agent` and `connection`. | | `blueprint.nats.connection.permission_violations` | counter | Permission violations the broker reported on a named connection. Carries `agent` and `connection`. | +| `blueprint.events.dead_lettered` | counter | NATS deliveries the framework gave up on. Carries `agent`, `reason` (`terminal-failure` or `deliveries-exhausted`) and `kept` (whether the payload reached the dead-letter subject). | +| `blueprint.scheduler.tick_age_seconds` | gauge | Seconds since a scheduler last ticked, `-1` before its first tick. Carries `scheduler`, `agent` and `mode`. See [schedulers.md](../components/schedulers.md). | | `llm.tokens.count` | counter | Tokens consumed, by an agent's model calls. | | `llm.response.latency` | histogram | Model call duration. | @@ -131,7 +133,7 @@ counted as ``; a declared one keeps its name. With `dapr_declarative the framework knows no topic list, and every topic counts as ``. The real topic stays in the log line. Under NATS every topic is one the agent subscribed, so the label is always the name. -The first two are recorded on the agent's own meter provider, so they arrive with that agent's +`blueprint.namespace.up` and `blueprint.namespace.inflight` are recorded on the agent's own meter provider, so they arrive with that agent's `service.name` as well as with the `agent` attribute -- a dashboard can group on either, and one of them survives a collector that drops resource attributes. @@ -251,9 +253,10 @@ Two agents may both call theirs `database`; they appear as `orders.database` and `billing.database`. Two checks that would still collide on one entry name are refused at registration rather than silently reduced to one. -The framework registers checks of its own: one per transport client, and one per declared cache -(`cache`, or `cache:` for a named one). A check of yours under one of those names replaces -the framework's, with a WARNING at startup -- the way to override a built-in check. +The framework registers checks of its own: one per transport client, one per declared cache +(`cache`, or `cache:` for a named one), and with a `nats_connection_source` one more per +client, `:connections` (below). A check of yours under one of those names replaces the +framework's, with a WARNING at startup -- the way to override a built-in check. ### Named NATS connections @@ -294,8 +297,10 @@ mechanisms. removed the pod restart that used to be the alert, so the alert is emitted deliberately. 2. **It stops consuming.** Readiness gates HTTP only -- a pod removed from service rotation still holds its subscriptions -- so for an event-driven agent the probe alone changes nothing. Under - NATS the agent's subscriptions are drained, which lets already-queued messages finish and - acknowledge while new ones go to a healthy replica. Under Dapr the sidecar delivers whatever + NATS the agent's subscriptions are drained: runs already in progress finish and acknowledge, + and new deliveries go to a healthy replica. A JetStream delivery that still reaches the paused + agent is nak'd at once, so it redelivers elsewhere; Core NATS cannot nak, so what the drain + lets through still runs. Under Dapr the sidecar delivers whatever the application thinks, so the fan-out answers `RETRY` for that agent without dispatching. Under `event_bus = "sessions"` the job stream is closed, so the agent's jobs stay pending for a healthy replica; jobs already running finish. The connection is kept open, because a closed client reports itself unhealthy for ever and the diff --git a/src/blueprint/agent_generator/docs/guides/cli-reference.md b/src/blueprint/agent_generator/docs/guides/cli-reference.md index ce85ca9b..53c4318d 100644 --- a/src/blueprint/agent_generator/docs/guides/cli-reference.md +++ b/src/blueprint/agent_generator/docs/guides/cli-reference.md @@ -57,7 +57,7 @@ asbs create agent # Add AgentRuntime asbs create scheduler [--cron CRON] # Add Scheduler asbs validate # Validate project structure asbs validate --group [--agent-map PATH] # Validate an image and every agent it maps -asbs dev [--port 8000] # Run dev server +asbs dev [--name AGENT] [--port 8000] # Run dev server (alone, or under AGENT) asbs docs [topic] [--cat] # Read the packaged documentation asbs claude [--overwrite] # Install Claude Code resources ``` diff --git a/src/blueprint/agent_generator/docs/guides/cli/create.md b/src/blueprint/agent_generator/docs/guides/cli/create.md index cc884a54..f8fa0d8f 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/create.md +++ b/src/blueprint/agent_generator/docs/guides/cli/create.md @@ -18,7 +18,7 @@ asbs create handler [--event-type ] [--priority ] [--output-di | Flag | Description | Default | |-------------------------|----------------------------------------------------|------------------| -| `--event-type ` | The event type this handler will respond to | (prompt) | +| `--event-type ` | The event type, named in the handler's description | (prompt) | | `--priority ` | Handler priority (lower numbers execute first) | `10` | | `--output-dir ` | Where the handler module is written | `src/handlers` | @@ -61,32 +61,44 @@ Handlers with lower priority numbers execute first in the chain. #### Handler Generated Code -The generated handler includes: +The generated handler includes (docstrings and comments shortened): ```python +from typing import Any + from blueprint.agents.handler import EventHandlerBase +from blueprint.agents.models import GenericCloudEvent, HandlerResult + class OrderPlacedHandler(EventHandlerBase): def __init__(self) -> None: super().__init__(priority=10) + self._input_event_type: str = "" async def on_startup(self) -> None: - # Initialize resources from registry - pass + # Reads [default.order_placed_handler] input_event_type, which `create handler` writes + self._input_event_type = self.config.get("order_placed_handler", {}).get("input_event_type", ) + if self._input_event_type == "": + raise ValueError("input_event_type is not set in config") async def on_shutdown(self) -> None: - # Clean up resources - pass + """Clean up handler resources on shutdown.""" async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: - return event.type == "order.placed" + # Example: + # return event.type == "order.placed" + raise NotImplementedError() async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | None: - # Return None to pass to next handler - # Return HandlerResult(...) to publish and stop chain - return None + # Return a HandlerResult to publish, HandlerResult.skipped("reason") when there is + # nothing to do, or None to offer the event to the next handler. + raise NotImplementedError() ``` +`--event-type` goes into the generated description and into `settings.toml` as +`[default.] input_event_type`; an existing section of that name is left alone. Routing is +still yours to write in `can_handle_event`. + --- ## asbs create service @@ -140,28 +152,30 @@ The generated service includes: ```python from blueprint.agents.services import ServiceBase +from pydantic import BaseModel + + class InvoiceProcessorService(ServiceBase): + def __init__(self) -> None: + super().__init__() + async def on_startup(self) -> None: - # Initialize resources, fetch dependencies from registry - # Example: self._cache = self.registry.cache_service - # Example: self._agent = self.registry.get_agent("analyzer") - pass + """Initialize the service by getting dependencies from the registry.""" async def on_shutdown(self) -> None: - # Clean up resources - pass + """Clean up service resources on shutdown.""" - async def process(self, data: dict) -> dict: - """Process invoice data. + async def process(self, base_model: BaseModel) -> BaseModel: + """This method contains business logic of this microservice. Args: - data: Invoice information + base_model (BaseModel): The incoming data, parsed into the domain input model. Returns: - Processing result + BaseModel: The processed data parsed into the domain output model. """ - # TODO: Implement business logic - pass + + raise NotImplementedError() ``` --- @@ -229,19 +243,26 @@ Creates: #### API Generated Code -The generated API includes: +The generated API includes (bodies shortened): ```python """REST API for order_management operations.""" from fastapi import HTTPException, status + from blueprint.agents.io.api.rest_api_base import RestApiBase -from src.models.order_management.dto import OrderManagementRequest, OrderManagementResponse + +from ..models.order_management.dto import OrderManagementRequest, OrderManagementResponse + class OrderManagementApi(RestApiBase): + def __init__(self) -> None: + super().__init__() + self._service = None + async def on_startup(self) -> None: - # Initialize dependencies from registry - # Example: self._service = self.registry.get_service(OrderService) + # TODO: Get services from registry + # Example: self._service = self.registry.get_service("some_service") pass async def on_shutdown(self) -> None: @@ -311,7 +332,7 @@ separate module to hold. 2. **Instruction prompt** (`src/prompts/_instruction.prompt`) -- a template with `{placeholders}` for runtime input, with example content 3. **Settings** (`settings.toml`) -- a `[default.runtimes.]` section and a - `[default.runtimes..models]` section beneath it + `[default.runtimes..model_settings]` section beneath it ### Auto-Registration @@ -364,7 +385,7 @@ model_name = "gpt-5-mini" model_temperature = 0.7 model_max_tokens = 2000 -[default.runtimes.document_analyzer_agent.models] +[default.runtimes.document_analyzer_agent.model_settings] openai_reasoning_effort = "low" openai_reasoning_summary = "detailed" ``` @@ -399,7 +420,9 @@ asbs create scheduler [--cron ] [--output-dir ] A registered scheduler with no `scheduler_mode` in `settings.toml` fails at `build()`. The key has no default because neither value is safe to inherit: `in_process` runs a timer in every replica and -claims each tick in the agent's own cache, so it needs `.with_cache()`; `event` starts no timer at +claims each tick in the agent's own cache, so it needs `.with_cache()` -- and a Redis cache once +more than one replica runs it, since a disk cache's claim holds within one process only; `event` +starts no timer at all and waits for a tick published by an external `CronJob`, so it needs `event_bus` -- and nothing in this project generates that `CronJob`. `asbs validate` reports both. @@ -465,14 +488,16 @@ Creates a scheduler that runs daily at 2:00 AM. #### Scheduler Generated Code -The generated scheduler includes: +The generated scheduler includes (docstrings shortened): ```python """Scheduler for cleanup operations.""" import logging + from blueprint.agents.io.api.scheduling.scheduler import SchedulerBase + logger = logging.getLogger(__name__) @@ -480,23 +505,28 @@ class CleanupScheduler(SchedulerBase): """Scheduler for cleanup operations.""" def __init__(self) -> None: - """Initialize the scheduler.""" + """Declare the schedule; 'scheduler_mode' in settings.toml decides what calls tick().""" super().__init__(crontab="0 2 * * *") async def on_startup(self) -> None: - """Initialize the scheduler.""" + """Resolve dependencies, then let the base class wire the scheduler.""" + # TODO: Get services from registry - # Example: self._service = self.registry.get_service(CleanupService) + # Example: self._service = self.registry.get_service(MyService) + + # Required. The base class starts the timer (in_process mode), wires the tick + # handler (event mode) and registers the manual trigger route. Drop this call + # and the scheduler is registered but never runs. + await super().on_startup() async def on_shutdown(self) -> None: """Cleanup when shutting down.""" + await super().on_shutdown() + async def tick(self) -> None: - """Execute scheduled task.""" - try: - # TODO: Implement your scheduled task here - # Example: await self._service.cleanup() - except Exception as e: - logger.exception("Error during %s scheduler tick: %s", __name__, e) - raise + """Execute scheduled task. Let exceptions out: in event mode they decide the delivery.""" + + # TODO: Implement your scheduled task here + # Example: await self._service.do_work() ``` diff --git a/src/blueprint/agent_generator/docs/guides/cli/dev.md b/src/blueprint/agent_generator/docs/guides/cli/dev.md index 0845e519..7720102c 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/dev.md +++ b/src/blueprint/agent_generator/docs/guides/cli/dev.md @@ -1,29 +1,34 @@ # asbs dev -Run this project's agents in development mode with hot reload, **under the namespaces they are -deployed under**. A development server at the root namespace would serve `/api/orders/{id}` where -production serves `/api/order/orders/{id}`, and would consume under a different queue group, so -every local URL and every local integration test would differ from the deployed one. - -With an `agents.toml`, it serves the group through -`uvicorn blueprint.agents.entrypoint:create_group_app --factory --reload`. Without one -- a project -written before the agent map, which builds its own application -- it serves `src.main:app` exactly -as it always did. +Run this project's agents in development mode with hot reload. What it serves depends on the +directory it is run in: + +- **An image directory** (one with an `agents.toml`): the agents the map names, under their + namespaces, through `uvicorn blueprint.agents.entrypoint:create_group_app --factory --reload` -- + the routes and queue groups a grouped deployment has. +- **An agent directory** (no `agents.toml`): the agent alone, at the root namespace, through + `uvicorn src.main:create_app --factory --reload` -- as its own Dockerfile serves it -- unless + `--name` gives it the namespace a group image would (see + [Running a single agent](#running-a-single-agent)). A project from before the declaration split, + whose `src/main.py` builds its own `app` and defines no `create_app`, is served as + `src.main:app`, as it always was. ```bash -asbs dev [--agents ] [--host ] [--port ] +asbs dev [--name ] [--agents ] [--host ] [--port ] ``` ## Options | Flag | Description | Default | |--------------------|-------------------------------------------------------------|------------------| -| `--agents ` | Comma-separated agents to host | every agent in `agents.toml` | +| `--name ` | Serve the agent in this directory under that name, as a group image would | served on its own, at the root | +| `--agents ` | Comma-separated agents to host, in an image directory | every agent in `agents.toml` | | `--host ` | Host to bind the server to | `127.0.0.1` | | `--port ` | Port to bind the server to | `8000` | -`BLUEPRINT_GROUP` or `BLUEPRINT_AGENTS` already set in the environment always wins: a developer -reproducing a particular deployment is not overridden by a default read out of the agent map. +`BLUEPRINT_GROUP` or `BLUEPRINT_AGENTS` already set in the environment always wins over the map +and `--agents`: a developer reproducing a particular deployment is not overridden by a default +read out of the agent map. ## Example @@ -31,13 +36,20 @@ reproducing a particular deployment is not overridden by a default read out of t asbs dev --port 9000 ``` +In an agent directory: + ``` -INFO: Blueprint Agents dev server starting... -INFO: Uvicorn running on http://0.0.0.0:9000 (Press CTRL+C to quit) -INFO: Started reloader process +Serving this agent on its own (src.main:create_app), at the root namespace. +Use --name to serve it under the namespace a group image would give it. +Starting development server on 127.0.0.1:9000 +Press Ctrl+C to stop + +INFO: Uvicorn running on http://127.0.0.1:9000 (Press CTRL+C to quit) +INFO: Started reloader process [...] ``` -The development server watches for file changes in the `src/` directory and automatically restarts when modifications are detected. +uvicorn's reloader watches the directory `asbs dev` was started in and restarts the server when a +file changes. --- diff --git a/src/blueprint/agent_generator/docs/guides/cli/naming.md b/src/blueprint/agent_generator/docs/guides/cli/naming.md index 312eaba9..cc9a272d 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/naming.md +++ b/src/blueprint/agent_generator/docs/guides/cli/naming.md @@ -78,6 +78,6 @@ If auto-registration fails (e.g., `src/main.py` not found), the CLI displays a c $ asbs create handler order_placed ✓ Created handler: src/handlers/order_placed_handler.py ✓ Auto-registered in src/main.py - - Added import: from src.handlers.order_placed_handler import OrderPlacedHandler + - Added import: from .handlers.order_placed_handler import OrderPlacedHandler - Added registration: .with_handler(OrderPlacedHandler) ``` diff --git a/src/blueprint/agent_generator/docs/guides/cli/setup.md b/src/blueprint/agent_generator/docs/guides/cli/setup.md index 5e00972c..815f3234 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/setup.md +++ b/src/blueprint/agent_generator/docs/guides/cli/setup.md @@ -4,29 +4,37 @@ Scaffold a complete Blueprint Agents project with all required directories and c ```bash asbs setup [--output-dir ] [--overwrite] [--verbose] +asbs setup --group [--output-dir ] [--overwrite] ``` ## Arguments | Argument | Description | Required | |----------------|------------------------------------|----------| -| `project-name` | Name of the project to create | Yes | +| `project-name` | The agent's name | Yes, unless `--group` | ## Options | Flag | Description | Default | |-----------------------|--------------------------------------------------------|---------| -| `--output-dir ` | Parent directory the project is created in | `.` | +| `--group` | Write the image's files instead of an agent; see [below](#asbs-setup---group) | off | +| `--output-dir ` | Directory to scaffold into -- the project itself; it must exist | `.` | | `--overwrite` | Overwrite existing files instead of refusing | off | | `--verbose`, `-v` | Debug-level logging from the generator | off | -The project name is normalised to a class name (`order-processor` gives `OrderProcessor/`), and the -agent's namespace is that name in snake case (`order_processor`). +The project is written **into** the output directory, not into a subdirectory named after it: +create the directory first and run `asbs setup` inside it. A directory that already holds `src/` +or `settings.toml` is refused unless `--overwrite` is given. + +The project name is normalised to a class name prefix (`order-processor` gives `OrderProcessor`), +and the agent's namespace is that name in snake case (`order_processor`). The namespace is checked +before anything is written: a name whose snake case does not match `[a-z][a-z0-9_]*`, or that is +one of the reserved names `cache`, `event_publishing`, `runtimes` and `runtime`, is refused. ## Generated Project Structure ``` -/ +/ src/ main.py # the declaration: agent = AppBuilder()... api/ @@ -34,18 +42,21 @@ agent's namespace is that name in snake case (`order_processor`). models// # dto.py, domain_models.py, mapper.py prompts/ services/ + tests/ # conftest.py, test_declaration.py, test_mapper.py settings.toml .secrets.toml # git-ignored .secrets.toml.example # committed, so the keys to fill in are known + pyproject.toml # only if the directory has none Dockerfile + .dockerignore .gitignore ``` There is no `agents.toml`. The agent map says which agents an *image* contains, which is a packaging decision -- an agent that carried one would be an agent that knows whether it is running -alone. The generated `Dockerfile` writes a one-agent map into its own image; a group image maps it -in the repository's `agents.toml`; `asbs dev --name` supplies it while developing. `asbs validate ---group` refuses one found inside an agent. +alone. The generated `Dockerfile` needs none: it serves `create_app()` directly, at the root +namespace. A group image maps the agent in the repository's `agents.toml`; `asbs dev --name` +supplies a name while developing. `asbs validate --group` refuses a map found inside an agent. A `pyproject.toml` is written only if the directory has none: `asbs` runs from the project's own environment, so by then there is usually one already, with somebody's dependencies in it. @@ -53,6 +64,7 @@ environment, so by then there is usually one already, with somebody's dependenci ## Example ```bash +mkdir my-ai-service && cd my-ai-service asbs setup my-ai-service ``` @@ -81,11 +93,11 @@ agent = ( Components are registered as **classes**, not instances: a component constructed on the `with_*` line is constructed before any namespace exists and belongs to the root for ever, which is why a -group refuses one. +group refuses one, and so does `create_app()`. **`asbs setup` writes no `agents.toml`, and that is deliberate.** The map says which agents an *image* contains, so an agent carrying one would be an agent that knows whether it is running -alone -- and `asbs validate` refuses one found inside an agent. The project is run with `uvicorn +alone -- and `asbs validate --group` refuses one found inside an agent. The project is run with `uvicorn src.main:create_app --factory`, which needs no map, no group and no namespace. Whoever hosts it supplies the name. To host this directory in a group, add it to the **image's** @@ -118,7 +130,9 @@ asbs setup --group agents.toml # empty: this image contains no agents yet settings.toml # the process: app_port, app_host, event_bus, log_level Dockerfile # the group image +.dockerignore # keeps every agent's .secrets.toml and the group file out of the image .gitignore +pyproject.toml # the image's dependencies; only if the directory has none ``` No agent is created and none is named, because which agents an image contains is decided one diff --git a/src/blueprint/agent_generator/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md index 7aeb631f..f24611e8 100644 --- a/src/blueprint/agent_generator/docs/guides/deployment.md +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -11,7 +11,8 @@ Two things shape everything below, and both are recent: - **More than one replica is now safe**, under conditions this guide states. Core NATS subscriptions join a queue group, JetStream consumers are durable and share a deliver group, every delivery is acknowledged, naked or terminated explicitly, a cron tick fires once across replicas - in both scheduler modes, and event deduplication is available. What you have to decide is listed + in both scheduler modes (in `in_process` mode only on a shared Redis cache), and event + deduplication is available. What you have to decide is listed under [Running more than one replica](#running-more-than-one-replica). > **The delivery behaviour is tested against a real NATS server** (`tests/integration`, a @@ -31,38 +32,41 @@ writes a single-agent image that serves one declaration directly -- `uvicorn src the one below. The same agent directory is built by either without editing a line; what differs is what gets copied and what serves it. -The group image's production stage: +The group image's runtime stage, as `asbs setup --group` writes it (comments shortened): ```dockerfile -FROM python:3.13-slim-bookworm AS final +FROM python:3.13-slim-bookworm AS runtime + +RUN useradd --create-home --shell /bin/bash appuser WORKDIR /app COPY --from=builder /usr/local/lib/python3.13/site-packages /usr/local/lib/python3.13/site-packages COPY --from=builder /usr/local/bin /usr/local/bin -COPY --chown=appuser:appuser src ./src + +# The agents, each in the directory its entry in agents.toml points at with `root`. +COPY --chown=appuser:appuser agents ./agents COPY --chown=appuser:appuser settings.toml ./ COPY --chown=appuser:appuser agents.toml ./ # The disk cache backend writes here and cannot create it itself: WORKDIR made /app root-owned. RUN mkdir -p /app/.cache && chown -R appuser:appuser /app/.cache -ENV PYTHONPATH="/app/src" \ - DYNACONF_APP_ENVIRONMENT="production" \ +ENV DYNACONF_APP_ENVIRONMENT="production" \ PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 USER appuser +EXPOSE 8000 + HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ CMD ["python", "-c", "import sys, urllib.request; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/health/live', timeout=4).status == 200 else 1)"] -EXPOSE 8000 - ENTRYPOINT ["python", "-m", "blueprint.agents.entrypoint"] ``` -Three things about it are load-bearing: +Five things about it are load-bearing: - **`agents.toml` is copied in; the group file is not.** The map says what the image *contains*, and changes only when an agent is added or removed -- which is a rebuild anyway. Which agents a @@ -74,10 +78,14 @@ Three things about it are load-bearing: this process's group, builds it and serves it. A project from before the split, whose `main.py` builds its own application, keeps `uvicorn src.main:app` and keeps working. - **`.secrets.toml` is never copied in.** Mount it, or supply the values as environment variables. + The `agents/` tree is copied whole, so it is the `.dockerignore` that `asbs setup --group` writes + that keeps each agent's own `.secrets.toml` out of the image. - **`app_environment` defaults to `development`, and a deployment sets `production` itself.** The variable is `DYNACONF_APP_ENVIRONMENT` (`_APP_ENVIRONMENT` with a custom `envvar_prefix`); - `DYNACONF_ENVIRONMENT` selects nothing. Left at `development`, a process falls back to a localhost - broker when `nats_url` is unset, logs as in development and runs asyncio in debug mode. + `DYNACONF_ENVIRONMENT` selects nothing. Left at `development`, a process logs a WARNING at startup + that it runs in development mode, falls back to a localhost broker (with a WARNING) when + `nats_url` is unset, and serves one uvicorn worker at log level `debug`. Asyncio debug mode is + not part of it: that is `event_loop_debug`, off unless set. - **The health check is Python, not `curl`:** the slim base image has no `curl`, so a `curl` check fails for ever and the container never turns healthy. @@ -344,7 +352,7 @@ scaling out and regrouping are independent of each other. | Outcome | Disposition | |---|---| | Handled, skipped (`HandlerResult.skipped`), or no handler matched it | **ack** -- none of them is a failure | -| A retryable failure | **nak**, redelivered after `nats_ack_wait` | +| A retryable failure | **nak**, redelivered at once (no delay is set) | | A run that exceeded `nats_handler_timeout` | cancelled and **nak**'d for immediate redelivery | | A poison payload, or a `CriticalHandlerError` | **term**, and dead-lettered | | `nats_max_deliver` attempts exhausted | dead-lettered | @@ -356,7 +364,7 @@ setting on its own. `in_progress` every third of it (`nats_heartbeat_enabled`, on by default), so a long run is not redelivered while it runs. What the heartbeat does not cover is a message that is still waiting in the client's queue -- bound that with `nats_max_ack_pending`. With the heartbeat switched off, - `nats_ack_wait` must exceed your p99 handler duration. + `nats_ack_wait` must exceed your p99 handler duration (and dedup warns at startup; see below). - **`nats_handler_timeout`** bounds a single run; set it above the longest legitimate run. - **`nats_max_ack_pending`** is the in-flight limit **across every replica sharing the consumer**, not per replica. Set it deliberately: it decides how many messages all replicas together work on @@ -393,9 +401,15 @@ prevent. Too long only costs cache entries. If you raise `nats_ack_wait` or `nat raise this with them. Two limits to know: dedup needs the agent to declare `with_cache()` -- the marker lives in that -agent's own cache -- and the claim is atomic only across replicas that share a Redis cache. A disk -cache's claim holds within one process: two processes on one directory -- several `app_workers`, or -replicas on a shared volume -- can both win it, so they can both run one event or one tick. +agent's own cache, and without one startup fails -- and the claim is atomic only across replicas +that share a Redis cache. A disk cache's claim holds within one process: replicas sharing a cache +directory (or `uvicorn --workers N` run by hand) can both win it, so they can both run one event or +one tick. + +A marker has no "in progress" state, so dedup relies on the broker not redelivering a run that is +still going. Where nothing guarantees that -- NATS with `nats_heartbeat_enabled = false`, or Dapr, +which has no heartbeat -- the agent logs a WARNING at startup: keep runs well under `nats_ack_wait` +or the sidecar's app-call timeout. **Grouped Dapr is the exception that wants dedup on.** A group has one Dapr endpoint: it publishes the union of every agent's topics and fans each delivery out to the agents that declared it, and the @@ -457,13 +471,15 @@ timer beside a neighbour driven by external ticks. ### `scheduler_mode = "in_process"` An APScheduler timer runs in every replica, and each tick is **claimed** in the agent's own cache -- -a marker keyed on `(scheduler, minute)` -- so the replica that stores it runs the tick and the rest -do not. Nothing is elected and nothing is held, so there is no lease to renew and none to be left -behind by a replica that dies. +a marker keyed on the scheduler and the minute the tick was scheduled for (not the clock when it +ran) -- so the replica that stores it runs the tick and the rest do not. Nothing is elected and +nothing is held, so there is no lease to renew and none to be left behind by a replica that dies. -It needs `.with_cache()` on that agent. Without one the claim has nowhere to go and **every replica -runs every tick**; the framework logs this at startup and `asbs validate` reports it. Right for local -development, plain Docker, and a single-replica deployment. +It needs `.with_cache()` on that agent, and a Redis cache shared by the replicas. Without a cache the +claim has nowhere to go and **every replica runs every tick**; the framework logs this at startup and +`asbs validate` reports it. A disk cache's claim holds within one process only, so with a per-pod +disk cache every replica runs every tick too. Right for local development, plain Docker, and a +single-replica deployment. ### `scheduler_mode = "event"` @@ -695,7 +711,8 @@ docker run \ Getting this wrong is quiet: `DYNACONF_APP__PORT` creates a nested `app.port` that nothing reads, and the process keeps its default. Most of the framework's own keys are **flat** -- `app_port`, `log_level`, `log_format`, `event_bus`, `nats_url`, `model_provider`, `idempotency_enabled`, -`scheduler_mode`, `readiness_policy`. The sectioned ones are `cache.*` and `runtimes..*`. +`scheduler_mode`, `readiness_policy`. The sectioned ones are `cache.*`, `event_publishing.*` and +`runtimes..*` (with its legacy singular `runtime..*`). #### Choosing your own prefix @@ -791,10 +808,12 @@ stringData: Later sources override earlier ones: 1. `settings.toml` -- base configuration, baked into the image -2. each agent's own `settings.toml`, merged under that agent's scope -- filling gaps only, so the - group's file and any `DYNACONF___KEY` win over it -3. `.secrets.toml` -- local development only; never copied into the image -4. environment variables -- the ConfigMap and Secret above +2. `.secrets.toml` beside it -- mounted at runtime, never copied into the image +3. environment variables -- the ConfigMap and Secret above + +Each agent's own files are merged under that agent's scope after these, filling gaps only -- so +everything above, `DYNACONF___KEY` included, wins over them. Its `.secrets.toml` is merged +first and so wins over its `settings.toml`; no value from it is logged. --- diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md index f52d72f3..dc8297c3 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md @@ -61,7 +61,7 @@ belong to the process that hosts the declaration. If you are passing **instances** anywhere -- `with_rest_api(OrderApi())` -- change them to classes. An instance is constructed at that line, before any namespace exists, so it belongs to the root for -ever; a group refuses one at assembly and names the agent and the fix. +ever; a group refuses one at assembly and names the agent and the fix, and so does `create_app()`. ## 2. `Dockerfile` -- one command @@ -76,6 +76,10 @@ and copy the map into the image beside your settings: COPY --chown=appuser:appuser agents.toml ./ ``` +If the `Dockerfile` sets `DYNACONF_ENVIRONMENT`, rename it to `DYNACONF_APP_ENVIRONMENT` +(`_APP_ENVIRONMENT` with your own `envvar_prefix`). `DYNACONF_ENVIRONMENT` selects +nothing, so an image that sets only it runs in `development`. + **That command is not sufficient on its own, and copying the map does not complete it.** Where `uvicorn src.main:app` named the application it served, the entry point has to be *told* which agents to run, and the map says only which ones the image contains. A container given neither @@ -225,7 +229,8 @@ asbs validate --group . --agent-map deploy/agents.toml `--group` resolves every `root`, reports which `settings.toml` each agent actually reads, refuses a file sitting where the framework will not look for it, and names process-wide keys left in an -agent. Neither imports your project. +agent. Neither runs your project: `--group` imports none of it, and plain `asbs validate` imports +only the parent packages of a `nats_connection_source`, to find that module. ## One declaration, three ways to run it diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md index 9e974ae6..3804b218 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md @@ -15,15 +15,13 @@ a runtime setting rather than an architectural commitment. --- ---- - ## Read this first: which of the two are you doing? Everything below splits along one question, and the answers differ in ways that matter: | | You are here if | What changes | |---|---|---| -| **A. A new project** | You are running `asbs setup` today | Nothing to migrate. Your agent has a real namespace from the first run | +| **A. A new project** | You are running `asbs setup` today | Nothing to migrate. The same directory runs on its own or in a group image without editing a line | | **B. An existing single-agent project** | You have a `main.py` that builds and serves an application | Three files change, and your **broker-side identity changes once** -- see [Migrating an Existing Agent into a Group](multi-agent-migration.md) | A third answer is legitimate and costs nothing: **do nothing.** An existing project that is @@ -34,8 +32,8 @@ deployed on its own keeps working, unchanged, indefinitely. There is no deprecat ## A. A new project ```bash -asbs setup order-processor -cd OrderProcessor +mkdir order-processor && cd order-processor +asbs setup order-processor # writes into the current directory ``` Two of the files it writes are what make the project hostable: @@ -62,7 +60,8 @@ There is no `Config` and no `build()`. Every `with_*` call *records* what the ag nothing is constructed until whoever hosts this file calls `build()`, which is what lets the same file be served alone and be hosted beside other agents. Note that components are registered as **classes**, not instances: a component constructed on the `with_*` line is constructed before any -namespace exists and belongs to the root for ever, which is why a group refuses one. +namespace exists and belongs to the root for ever, which is why a group refuses one, and so does +`create_app()`. **The agent carries no `agents.toml`, and that is the point.** @@ -75,7 +74,7 @@ Whoever hosts the agent supplies its name: | Host | Where the name comes from | |---|---| -| Its own `Dockerfile` | a one-agent map written into the image, with `root = "."` | +| Its own `Dockerfile` | nobody: it serves `create_app()` at the root namespace | | A group image | an entry in the repository's `agents.toml` | | `asbs dev` | `--name`; without it the agent is served on its own, at the root namespace | @@ -86,19 +85,21 @@ instead, which reads that image's map, works out this process's group, and serve ### Running it ```bash -asbs dev # every agent in agents.toml, with hot reload -asbs dev --agents order_processor -asbs validate # what this project has not said yet +asbs dev # this agent alone, at the root namespace, with hot reload +asbs dev --name order_processor # under the namespace a group image gives it +asbs validate # what this project has not said yet ``` -In an image directory `asbs dev` runs your agents under their **real** namespaces, so a local route is -`/api/order_processor/orders/{id}` -- byte-identical to production -- and the local consumer -identity is the production queue group. A development server at the root namespace would give every -developer URLs and integration tests that differ from the deployed ones, in a way nothing reports. +Without `--name`, an agent directory is served the way its own `Dockerfile` serves it: at the root +namespace, with the routes the API declares. With `--name`, or in an image directory (one with an +`agents.toml`, where `--agents` picks a subset), `asbs dev` runs agents under their **real** +namespaces, so a local route is `/api/order_processor/orders/{id}` -- byte-identical to a grouped +deployment -- and the local consumer identity is the production queue group. Develop with the +shape you deploy: root routes and URLs differ from grouped ones, in a way nothing reports. ```bash docker build -t order-processor . -docker run -e BLUEPRINT_AGENTS=order_processor -p 8000:8000 order-processor +docker run -p 8000:8000 order-processor ``` ### Adding a second agent to the same image @@ -114,7 +115,8 @@ asbs setup --group ``` That writes the image's files and nothing else: an empty `agents.toml`, a `settings.toml` for -the process-wide keys, and a group `Dockerfile`. No agent is created and none is named. +the process-wide keys, a group `Dockerfile`, `.gitignore`, `.dockerignore`, and a `pyproject.toml` +unless one is already there. No agent is created and none is named. Then each agent, in its own directory, at whatever depth suits the repository: @@ -409,9 +411,9 @@ Whichever shape, the file must stay out of the build context -- see the scaffold `.dockerignore`, which excludes the default name and says why a different path needs a line of its own. -If the group cannot be resolved -- no agents named, a group that is not in the file, an agent the -image does not contain -- the process **stops before binding its port** and prints one line saying -which. Kubernetes then crash-loops the pod with something an operator can act on, rather than +If the group cannot be resolved -- no agents named, a group that is not in the file, a critical +agent the image does not contain -- the process **stops before binding its port** and prints one +line saying which. A non-critical agent the image lacks is skipped with an ERROR instead. Kubernetes then crash-loops the pod with something an operator can act on, rather than reporting a healthy replica that is quietly short one consumer. ### What agent code can see of all this @@ -433,15 +435,27 @@ If you would rather write the composition yourself than use the entry point -- a that wants its own `main.py` -- `AgentGroup` is the class that does it: ```python +from pathlib import Path + from blueprint.agents import AgentGroup, Config -from src.order.main import agent as order -from src.billing.main import agent as billing +from agents.order.src.main import agent as order +from agents.billing.src.main import agent as billing -config = Config(settings_files=["settings.toml"]) -app = AgentGroup("checkout", {"order": order, "billing": billing}).assemble(config) +config = Config(settings_files=["settings.toml", ".secrets.toml"]) +app = AgentGroup( + "checkout", + {"order": order, "billing": billing}, + settings={"order": Path("agents/order/settings.toml"), "billing": Path("agents/billing/settings.toml")}, + roots={"order": Path("agents/order"), "billing": Path("agents/billing")}, +).assemble(config) ``` +A group constructed this way reads only the files it is given: without `settings=`, `secrets=` and +`roots=` no agent's own `settings.toml` or `.secrets.toml` is merged and each agent's prompts are +looked for under the process's working directory. `AgentGroup.resolve(config)` is what the entry +point uses, and it takes all three from the map. + `AgentGroup` is a different class from `AppBuilder` on purpose: an `AppBuilder` never absorbs another builder and never learns it can be collected, so every refusal a group has to make lives in the class that imposes it, and the single-agent case is not punished for the group's constraints. @@ -464,8 +478,9 @@ the pause would latch and a transient fault would take the agent off its topics **Schedulers.** `scheduler_mode` resolves per agent, so one agent may run an in-process timer beside a neighbour driven by external ticks. Both modes need something of the agent's own: `in_process` -claims each tick in a cache **that agent declared**, and `event` needs `event_bus`, which is the -group's to set. +claims each tick in a cache **that agent declared** -- a Redis cache once more than one process runs +it, since a disk cache's claim holds within one process only -- and `event` needs `event_bus`, +which is the group's to set. **Dapr.** A group has one Dapr endpoint, which publishes the union of every agent's topics and fans each delivery out to the agents that declared it; the single acknowledgement is their combination. diff --git a/src/blueprint/agent_generator/docs/guides/testing.md b/src/blueprint/agent_generator/docs/guides/testing.md index e87728f0..588f9913 100644 --- a/src/blueprint/agent_generator/docs/guides/testing.md +++ b/src/blueprint/agent_generator/docs/guides/testing.md @@ -50,46 +50,48 @@ tests/ ## Creating a Mock Registry -Many components depend on the service registry to access other services. Create a reusable mock registry fixture in `tests/conftest.py`: +Many components depend on the registry to access other services. A component's `registry` is a +read-only property that reads the class-level shared registry, so a mock is installed there -- +before the component under test is constructed -- and removed afterwards. Create a reusable fixture +in `tests/conftest.py`: ```python import pytest -from unittest.mock import AsyncMock, MagicMock +from unittest.mock import MagicMock +from blueprint.agents.component.component import Component +from blueprint.agents.component.registry import Registry -@pytest.fixture -def mock_registry(): - """Create a mock registry with common services pre-configured.""" - registry = MagicMock() - registry.get_service = MagicMock() - - # Pre-configure commonly needed services - mock_cache = AsyncMock() - mock_cache.get = AsyncMock(return_value=None) - mock_cache.set = AsyncMock() - registry.get_service.side_effect = lambda name: { - "cache": mock_cache, - }.get(name) - return registry +@pytest.fixture +def mock_cache(): + """A stand-in for the agent's cache. The cache API is synchronous, so MagicMock, not AsyncMock.""" + cache = MagicMock() + cache.get.return_value = None + return cache @pytest.fixture -def mock_cache(mock_registry): - """Access the mock cache service from the registry.""" - return mock_registry.get_service("cache") +def mock_registry(mock_cache): + """Install a mock registry for every component constructed while the test runs.""" + registry = MagicMock(spec=Registry) + registry.get_cache.return_value = mock_cache + Component.shared_registry = registry + yield registry + Component.reset_shared_state() ``` -To add additional mock services, extend the dictionary in the `side_effect` lambda: +To add mock services, answer `get_service` by name: ```python -mock_llm = AsyncMock() -mock_llm.generate = AsyncMock(return_value="LLM response") +from unittest.mock import AsyncMock -registry.get_service.side_effect = lambda name: { - "cache": mock_cache, - "llm_provider": mock_llm, -}.get(name) +mock_pricing = AsyncMock() +mock_pricing.quote = AsyncMock(return_value=49.99) + +mock_registry.get_service.side_effect = lambda name, namespace=None: { + "pricing_engine": mock_pricing, +}[name] ``` --- @@ -98,12 +100,12 @@ registry.get_service.side_effect = lambda name: { ### Testing Event Handlers -Event handlers have two key methods to test: `can_handle_event` for routing logic and `handle_event` for processing logic. +Event handlers have two key methods to test: `can_handle_event` for routing logic and `handle_event` for processing logic. Both take the event, a `CloudEvent`, and the processing context. ```python # tests/unit/test_handlers.py import pytest -from unittest.mock import AsyncMock, MagicMock +from blueprint.agents.models.events import create_cloud_event from src.handlers.order_processor import OrderProcessorHandler @@ -111,29 +113,27 @@ class TestOrderProcessorHandler: @pytest.fixture def handler(self, mock_registry): - handler = OrderProcessorHandler() - handler.registry = mock_registry - return handler + return OrderProcessorHandler() async def test_can_handle_matching_event(self, handler): - event = {"type": "order.created", "data": {"order_id": "123"}} - result = await handler.can_handle_event(event) + event = create_cloud_event("order.created", {"order_id": "123"}) + result = await handler.can_handle_event(event, {}) assert result is True async def test_cannot_handle_non_matching_event(self, handler): - event = {"type": "user.updated", "data": {}} - result = await handler.can_handle_event(event) + event = create_cloud_event("user.updated", {}) + result = await handler.can_handle_event(event, {}) assert result is False async def test_handle_event_processes_order(self, handler): - event = {"type": "order.created", "data": {"order_id": "123", "total": 99.99}} - result = await handler.handle_event(event) + event = create_cloud_event("order.created", {"order_id": "123", "total": 99.99}) + result = await handler.handle_event(event, {}) assert result["status"] == "processed" async def test_handle_event_with_missing_data(self, handler): - event = {"type": "order.created", "data": {}} + event = create_cloud_event("order.created", {}) with pytest.raises(ValueError, match="order_id is required"): - await handler.handle_event(event) + await handler.handle_event(event, {}) ``` ### Testing Services @@ -143,7 +143,6 @@ Services typically interact with caches, external APIs, or other services. Mock ```python # tests/unit/test_services.py import pytest -from unittest.mock import AsyncMock, MagicMock, patch from src.services.pricing_engine import PricingEngineService @@ -151,9 +150,7 @@ class TestPricingEngineService: @pytest.fixture def service(self, mock_registry): - svc = PricingEngineService() - svc.registry = mock_registry - return svc + return PricingEngineService() async def test_calculate_price_with_no_cache(self, service, mock_cache): mock_cache.get.return_value = None @@ -185,7 +182,6 @@ Use `httpx.AsyncClient` with the FastAPI test client to test API endpoints witho # tests/unit/test_apis.py import pytest from httpx import AsyncClient, ASGITransport -from unittest.mock import AsyncMock, MagicMock from fastapi import FastAPI from src.api.product_catalog import ProductCatalogApi @@ -197,8 +193,7 @@ class TestProductCatalogApi: """Create a FastAPI app with the API routes registered.""" app = FastAPI() api = ProductCatalogApi() # wires its decorated routes on construction - api.registry = mock_registry - app.include_router(api.router) + app.include_router(api.router) # mounted bare: the application would add /api return app @pytest.fixture @@ -275,72 +270,82 @@ class TestResearchAssistantAgent: Integration tests verify that the full application starts correctly and that endpoints respond as expected. +### The application fixture + +`src/main.py` declares the agent; `create_app()` builds it. A declaration builds **once per +process** -- a second `create_app()` raises `RuntimeError: This AppBuilder has already been built` +-- so build the application once per test session, in `tests/integration/conftest.py`, and share +it. `TestClient` used as a context manager runs the application's startup and shutdown, which is +what initialises the health checks; an `httpx.ASGITransport` client does not, and `/health/ready` +then answers `503` with `Health check cache not initialized`. + +Run the integration tests in a pytest run of their own (`pytest tests/integration/`): once the +application is built, the declaration reads as built for the rest of the process, and the +generated `tests/test_declaration.py` asserts that it is not. + +```python +# tests/integration/conftest.py +import pytest +from fastapi.testclient import TestClient + +from src.main import create_app + + +@pytest.fixture(scope="session") +def client(): + with TestClient(create_app()) as client: + yield client +``` + ### Testing the Full Application ```python # tests/integration/test_app.py -import pytest -from httpx import AsyncClient, ASGITransport -from src.main import app -class TestAppIntegration: +def test_health_liveness(client): + response = client.get("/health/live") + assert response.status_code == 200 + assert response.json()["status"] == "UP" - @pytest.fixture - async def client(self): - transport = ASGITransport(app=app) - async with AsyncClient(transport=transport, base_url="http://test") as client: - yield client - async def test_health_liveness(self, client): - response = await client.get("/health/live") - assert response.status_code == 200 - assert response.json()["status"] == "UP" +def _readiness_body(response): + # 200 returns the payload; 503 (any check unhealthy -- no reachable model or broker in a + # test environment, say) returns the same payload under "detail". + assert response.status_code in (200, 503) + return response.json() if response.status_code == 200 else response.json()["detail"] - async def test_health_readiness(self, client): - # 503 when any check is unhealthy, and the body is the same shape either way. - response = await client.get("/health/ready") - assert response.status_code == 200 - data = response.json() - assert data["status"] == "UP" - assert "components" in data - - async def test_readiness_has_no_group_fields(self, client): - # A standalone agent's payload is status and components; "policy" and "namespaces" - # appear only when the process hosts a group of agents. - response = await client.get("/health/ready") - assert set(response.json()) == {"status", "components"} + +def test_health_readiness(client): + body = _readiness_body(client.get("/health/ready")) + assert "components" in body + + +def test_readiness_has_no_group_fields(client): + # A standalone agent's payload is status and components; "policy" and "namespaces" + # appear only when the process hosts a group of agents. + body = _readiness_body(client.get("/health/ready")) + assert set(body) == {"status", "components"} ``` ### Testing Endpoint Behavior +Served on its own, an agent's routes are under `/api`, as its API declares them: + ```python # tests/integration/test_endpoints.py -import pytest -from httpx import AsyncClient, ASGITransport -from src.main import app - -class TestEndpoints: - @pytest.fixture - async def client(self): - transport = ASGITransport(app=app) - async with AsyncClient(transport=transport, base_url="http://test") as client: - yield client - - async def test_product_lifecycle(self, client): - # Create a product - create_response = await client.post( - "/products", json={"name": "Widget", "price": 9.99} - ) - assert create_response.status_code == 200 +def test_product_lifecycle(client): + # Create a product + create_response = client.post("/api/products", json={"name": "Widget", "price": 9.99}) + assert create_response.status_code == 200 - # Verify it appears in the list - list_response = await client.get("/products") - assert list_response.status_code == 200 - products = list_response.json()["products"] - assert len(products) > 0 + # Verify it appears in the list + list_response = client.get("/api/products") + assert list_response.status_code == 200 + products = list_response.json()["products"] + assert len(products) > 0 ``` --- @@ -350,8 +355,8 @@ class TestEndpoints: ### Basic Test Execution ```bash -# Run all tests -pytest +# Run everything but the integration tests, which want a run of their own (see above) +pytest --ignore=tests/integration # Run with verbose output pytest -v diff --git a/src/blueprint/agent_generator/docs/guides/troubleshooting.md b/src/blueprint/agent_generator/docs/guides/troubleshooting.md index 3da47f84..e701a9ab 100644 --- a/src/blueprint/agent_generator/docs/guides/troubleshooting.md +++ b/src/blueprint/agent_generator/docs/guides/troubleshooting.md @@ -64,24 +64,25 @@ pip install avs-blueprint-agents==0.6.0a3 \ ### ConfigError on Startup -**Symptom:** Application crashes immediately with a `ConfigError` or `ValidationError`. +**Symptom:** Application crashes immediately with a `ConfigError`. ``` -blueprint.agents.exceptions.ConfigError: Missing required configuration: 'app.name' +blueprint.agents.config.config.ConfigError: Invalid app port: 70000 ``` -**Cause:** Required settings are missing from `settings.toml` or have not been provided via environment variables. +**Cause:** A setting failed validation at startup -- an `app_port` outside 1-65535, the `vllm` +provider without `model_api_key`, an agent settings file that cannot be parsed, an invalid +`envvar_prefix`. The message names the key or the file. -**Solution:** Verify that `settings.toml` contains all required keys: +**Solution:** Correct the setting the message names. The framework's keys are **flat** keys under +`[default]`, not tables of their own: ```toml -[app] -name = "my-ai-service" -port = 8000 - -[llm] -provider = "openai" -model = "gpt-4" +[default] +app_name = "my-ai-service" +app_port = 8000 +model_provider = "openai" +model_name = "gpt-4.1-mini" ``` Check which settings are required by running validation: @@ -99,10 +100,13 @@ asbs validate **Solution:** Check the component's documentation or source code for required settings. Use Dynaconf environment variable overrides if you cannot modify `settings.toml`: ```bash -export DYNACONF_LLM__API_KEY="sk-..." -export DYNACONF_LLM__PROVIDER="openai" +export DYNACONF_MODEL_API_KEY="sk-..." +export DYNACONF_MODEL_PROVIDER="openai" ``` +A top-level key takes one underscore after the prefix; `__` is nesting, so `DYNACONF_LLM__API_KEY` +would create an `llm.api_key` that nothing reads. + ### Invalid Port Configuration **Symptom:** Server fails to bind on startup. @@ -116,8 +120,8 @@ export DYNACONF_LLM__PROVIDER="openai" **Solution:** Use a non-privileged port in `settings.toml`: ```toml -[app] -port = 8000 +[default] +app_port = 8000 ``` Or check for port conflicts: @@ -182,7 +186,9 @@ In Kubernetes, verify the NATS service is deployed and the Dapr component config **Refused against `localhost:4222` inside a pod?** The process is in development mode: `app_environment` is unset or `"development"`, and `nats_url` is unset, so it fell back to localhost. The log says so twice -- a WARNING that the service is running in development mode, and one naming the fallback. Set `app_environment` -and `nats_url` for the deployment. +and `nats_url` for the deployment. An image that sets only `DYNACONF_ENVIRONMENT` (the variable older +Dockerfiles used) stays in development: that variable selects nothing, and has to be renamed to +`DYNACONF_APP_ENVIRONMENT` (`_APP_ENVIRONMENT` with your own `envvar_prefix`). ### `'nats_url' is not set` on Startup @@ -212,21 +218,41 @@ enabled for the account the connection authenticates as. **Solution:** Enable JetStream for that server and account, or set `nats_use_jetstream = false` if the agent is meant to run on Core NATS. The framework does not fall back on its own. +### `JetStreamBindingError`: a consumer that `belongs to another subscription` + +**Symptom:** One topic of an agent never receives events, and the log repeats: + +``` +JetStreamBindingError: JetStream consumer 'orders-created-durable' on stream ... filters 'orders-created', not 'created', so it belongs to another subscription and is not bound. ... +``` + +**Cause:** A durable of that name already exists on the stream for another subject. A root topic and +an agent's topic can derive one durable name -- root topic `orders-created` and agent `orders` on +topic `created` both give `orders-created-durable`. The framework never rebinds or rewrites a +consumer that filters another subject, and keeps retrying the binding. + +**Solution:** Rename one of the two topics, or delete the consumer if it is stale. + ### Topic Mapping Mismatches **Symptom:** Events are published but handlers never receive them. -**Cause:** The topic name in the handler's `event_type` does not match the topic used by the publisher. +**Cause:** The topic the handler subscribes to, or the event type it accepts, does not match what the +publisher sends. -**Solution:** Verify that the event types match exactly between publisher and subscriber: +**Solution:** Verify that topic and event type match exactly between publisher and subscriber: ```python -# Publisher -await event_bus.publish(topic="order.created", data=order_data) +# Publisher (EventPublishingService) +await publisher.publish_event(event, topic="order.created") -# Handler -- event_type must match exactly +# Handler -- the subscribed topic and the accepted type must match exactly class OrderHandler(EventHandlerBase): - event_type = "order.created" # Must match the publish topic + def get_subscribed_topics(self) -> list[str]: + return ["order.created"] + + async def can_handle_event(self, event, context) -> bool: + return event.type == "order.created" ``` Check the Dapr subscription configuration to ensure topic mappings are correct. @@ -237,25 +263,26 @@ Check the Dapr subscription configuration to ensure topic mappings are correct. ### Missing API Key -**Symptom:** Agent calls fail with an authentication error. +**Symptom:** Startup or the first agent call fails with an authentication error from the provider's +client, for the `openai` provider: ``` -AuthenticationError: No API key provided. Set DYNACONF_LLM__API_KEY or add it to .secrets.toml. +openai.OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable ``` -**Cause:** The LLM provider API key is not configured. +**Cause:** `model_api_key` is not configured. -**Solution:** Set the API key in `.secrets.toml` (for local development) or via an environment variable (for production): +**Solution:** Set it in `.secrets.toml` (for local development) or via an environment variable (for production): ```toml # .secrets.toml (local only -- do not commit) -[llm] -api_key = "sk-..." +[default] +model_api_key = "YOUR_API_KEY_HERE" ``` ```bash # Environment variable -export DYNACONF_LLM__API_KEY="sk-..." +export DYNACONF_MODEL_API_KEY="YOUR_API_KEY_HERE" ``` ### Invalid Model Name @@ -271,9 +298,9 @@ InvalidRequestError: The model 'gpt-5-turbo' does not exist **Solution:** Verify the model name against the provider's documentation: ```toml -[llm] -provider = "openai" -model = "gpt-4" # Use a valid model identifier +[default] +model_provider = "openai" +model_name = "gpt-4.1-mini" # Use a valid model identifier ``` ### Timeout Errors @@ -281,16 +308,16 @@ model = "gpt-4" # Use a valid model identifier **Symptom:** LLM calls fail intermittently with timeout errors. ``` -TimeoutError: Request timed out after 30.0 seconds +openai.APITimeoutError: Request timed out. ``` **Cause:** The LLM provider is taking longer than the configured timeout to respond. This is common with complex prompts or during high provider load. -**Solution:** Increase the timeout in configuration: +**Solution:** Increase the timeout in configuration (unset, the provider SDK's own default applies): ```toml -[llm] -timeout = 60 # seconds +[default] +model_timeout = 60 # seconds, per model request ``` Alternatively, consider breaking complex prompts into smaller steps or implementing retry logic in your service. @@ -300,18 +327,17 @@ Alternatively, consider breaking complex prompts into smaller steps or implement **Symptom:** Application raises an error about an unsupported LLM provider. ``` -ValueError: LLM provider 'anthropic_legacy' is not supported +ValueError: Unsupported provider: 'anthropic'. Supported: ['vllm', 'openai'] ``` -**Cause:** The provider name in configuration does not match any registered provider. +**Cause:** `model_provider` names a provider the framework has no client for. **Solution:** Use a supported provider name: ```toml -[llm] -provider = "openai" # OpenAI API -# provider = "azure" # Azure OpenAI -# provider = "anthropic" # Anthropic Claude +[default] +model_provider = "openai" # OpenAI API +# model_provider = "vllm" # a vLLM server at model_base_url; model_api_key is required ``` --- @@ -323,19 +349,21 @@ provider = "openai" # OpenAI API **Symptom:** Application fails to start with a duplicate registration error. ``` -RegistrationError: Component 'order_handler' is already registered +ValueError: Component with name order_handler already exists ``` -**Cause:** Two components share the same `name` attribute. +**Cause:** Two components resolve to the same registry name. A component is named after its class +(`OrderHandler` becomes `order_handler`) unless its `with_*` call passes `name=`, so registering one +class twice, or passing one `name=` twice, collides. In a group the message names the agent too. -**Solution:** Ensure every component has a unique `name`: +**Solution:** Give the second registration a name of its own: ```python -class OrderCreatedHandler(EventHandlerBase): - name = "order_created_handler" # Must be unique - -class OrderUpdatedHandler(EventHandlerBase): - name = "order_updated_handler" # Must be unique +agent = ( + AppBuilder() + .with_service(PricingService) + .with_service(PricingService, name="eu_pricing_service") # a second instance, its own name +) ``` Run validation to detect duplicates: @@ -344,47 +372,35 @@ Run validation to detect duplicates: asbs validate ``` -### Missing Dependencies in on_startup +### Looking Up Components in __init__ -**Symptom:** A service raises a `KeyError` or `None` reference when trying to access another service during startup. +**Symptom:** A service fails when trying to access another service during construction. ``` -KeyError: 'pricing_engine' +ValueError: Component with name pricing_engine does not exist ``` -**Cause:** The service is trying to access a dependency from the registry before that dependency has been registered and started. +**Cause:** The service is looking up a dependency before that dependency has been constructed and +registered. Components are constructed one by one in declaration order inside `build()`, so a +lookup in `__init__()` finds only the components declared before this one. -**Solution:** Access dependencies from the registry only within `on_startup()` or during request handling, not in `__init__()`. The framework calls `on_startup()` after all components are registered: +**Solution:** Access dependencies from the registry only within `on_startup()` or during request +handling, not in `__init__()`. The framework calls `on_startup()` after all components are +registered: ```python class OrderService(ServiceBase): - name = "order_service" + def __init__(self): + super().__init__() + self.pricing = None # Do NOT look up other components here async def on_startup(self) -> None: # Safe -- all components are registered by this point self.pricing = self.registry.get_service("pricing_engine") -``` - -### Accessing Registry in __init__ + self.cache = self.registry.get_cache() # only if the agent declares .with_cache() -**Symptom:** `AttributeError: 'NoneType' object has no attribute 'get_service'` during component construction. - -**Cause:** The registry is not available during `__init__()`. It is injected after construction. - -**Solution:** Move all registry access to `on_startup()`: - -```python -class MyService(ServiceBase): - name = "my_service" - - def __init__(self): - # Do NOT access self.registry here -- it is not set yet - self._client = None - - async def on_startup(self) -> None: - # Registry is available here - cache = self.registry.get_service("cache") - self._client = await self._create_client() + async def on_shutdown(self) -> None: + pass ``` --- @@ -397,25 +413,24 @@ class MyService(ServiceBase): ```json { - "status": "unhealthy", - "components": { - "llm_provider": {"status": "unhealthy", "error": "Connection refused"} + "detail": { + "status": "DOWN", + "components": { + "nats_client": {"status": "unhealthy", "message": "Unhealthy: ..."} + } } } ``` -**Cause:** The external service that the health checker is testing is unreachable. +The probe answers `503`, and the payload is wrapped in `detail`. -**Solution:** Verify the external service is running and accessible from the application. Check network policies and firewall rules in Kubernetes. Review the health checker configuration: +**Cause:** The external service behind that entry is unreachable. The framework registers one entry +per client (named after the client), one per cache (`cache`, `cache:`) and one per NATS client +with named connections (`:connections`); in a group each is prefixed with the agent +(`orders.nats_client`). -```python -# Verify the health check endpoint is correct -health_checker = ClientHealthChecker( - name="llm_provider", - url="https://api.openai.com/v1/models", - timeout=5 -) -``` +**Solution:** Verify the external service is running and accessible from the application. Check +network policies and firewall rules in Kubernetes. The entry's `message` is the client's own report. ### Custom Health Checkers @@ -424,41 +439,52 @@ health_checker = ClientHealthChecker( **Solution:** Implement a custom health checker and register it with the application: ```python -from blueprint.agents.health import HealthCheckerBase +from blueprint.agents import AppBuilder +from blueprint.agents.io.api.actuators.health import HealthCheckerBase +from blueprint.agents.models.api import ComponentHealth class DatabaseHealthChecker(HealthCheckerBase): - name = "database" + def __init__(self, db): + self._db = db - async def check(self) -> dict: + async def health_check(self) -> ComponentHealth: try: - await self.db.ping() - return {"status": "healthy"} + await self._db.ping() + return ComponentHealth(status="healthy", message="database reachable") except Exception as e: - return {"status": "unhealthy", "error": str(e)} + return ComponentHealth(status="unhealthy", message=str(e)) + + +agent = AppBuilder().with_health_checker("database", DatabaseHealthChecker(db)) ``` +A check named like a built-in entry (`cache`, say) replaces it, with a WARNING; two of your own +checks under one name are refused at startup. + --- ## Cache Issues ### Permission Errors on Cache Directory -**Symptom:** Cache operations fail with permission errors. +**Symptom:** Startup fails because the cache directory cannot be created. ``` -PermissionError: [Errno 13] Permission denied: '/app/.cache/data.db' +RuntimeError: Cache directory '.cache/blueprint' could not be created (Permission denied). ... ``` -**Cause:** The application process does not have write permissions to the cache directory. +**Cause:** The application process does not have write permissions where the cache directory +(`cache.cache_dir`) is. -**Solution:** In Docker, ensure the cache directory is writable: +**Solution:** In Docker, create the directory at build time and hand it to the user the process runs +as, as the generated `Dockerfile` does: ```dockerfile -RUN mkdir -p /app/.cache && chmod 777 /app/.cache +RUN mkdir -p /app/.cache && chown -R appuser:appuser /app/.cache ``` -In Kubernetes, use an `emptyDir` volume: +With a read-only root filesystem, mount an `emptyDir` volume there: ```yaml volumes: @@ -482,9 +508,9 @@ OSError: [Errno 28] No space left on device **Solution:** Configure a cache size limit in `settings.toml`: ```toml -[cache] -max_size_mb = 500 -ttl = 3600 # Entries expire after 1 hour +[default.cache] +size_limit = 500_000_000 # bytes; the default is 1 GB +default_ttl = 3600 # seconds an entry lives unless set() gives a ttl ``` In Kubernetes, set a size limit on the `emptyDir` volume: @@ -505,15 +531,15 @@ volumes: **Solution:** Reduce the TTL or clear the cache manually: ```toml -[cache] -ttl = 300 # 5 minutes +[default.cache] +default_ttl = 300 # 5 minutes ``` -To clear the cache programmatically: +To clear the cache programmatically (the cache API is synchronous): ```python -cache = self.registry.get_service("cache") -await cache.clear() +cache = self.registry.get_cache() +cache.clear() ``` --- @@ -545,31 +571,32 @@ With `asyncio_mode = "auto"`, all async test functions are detected automaticall **Cause:** The registry was not mocked or injected into the component under test. -**Solution:** Create a mock registry fixture and assign it to the component: +**Solution:** `registry` is a read-only property that reads the class-level shared registry, so +install the mock there before the component is constructed, and reset it afterwards: ```python import pytest -from unittest.mock import MagicMock, AsyncMock +from unittest.mock import MagicMock + +from blueprint.agents.component.component import Component +from blueprint.agents.component.registry import Registry @pytest.fixture def mock_registry(): - registry = MagicMock() - mock_cache = AsyncMock() - mock_cache.get = AsyncMock(return_value=None) - mock_cache.set = AsyncMock() - registry.get_service = MagicMock(side_effect=lambda name: { - "cache": mock_cache, - }.get(name)) - return registry + registry = MagicMock(spec=Registry) + mock_cache = MagicMock() # the cache API is synchronous + mock_cache.get.return_value = None + registry.get_cache.return_value = mock_cache + Component.shared_registry = registry + yield registry + Component.reset_shared_state() @pytest.fixture def my_service(mock_registry): from src.services.my_service import MyService - svc = MyService() - svc.registry = mock_registry - return svc + return MyService() ``` ### Missing pytest-asyncio diff --git a/src/blueprint/agent_generator/docs/reference/api.md b/src/blueprint/agent_generator/docs/reference/api.md index 8904f7f0..8d446624 100644 --- a/src/blueprint/agent_generator/docs/reference/api.md +++ b/src/blueprint/agent_generator/docs/reference/api.md @@ -36,7 +36,7 @@ AppBuilder(config: Config | None = None) | `with_rest_api(api, *, name=None)` | `AppBuilder` | Register a REST API controller. | | `with_scheduler(scheduler, *, name=None)` | `AppBuilder` | Register a scheduled task. | | `with_cache(enabled=True, enable_locking=True, *, name="default")` | `AppBuilder` | Declare a cache; call again with another `name` for several. | -| `with_health_checker(name, checker)` | `AppBuilder` | Add a named health-check probe. | +| `with_health_checker(name, checker)` | `AppBuilder` | Add a named health-check probe. A name a built-in check uses (`cache`, `cache:`, a client's name, `:connections`) replaces the built-in, with a WARNING; two of the application's own that land on one readiness entry are refused. | | `build(config=None)` | `FastAPI` | Construct everything declared and return the FastAPI application. Single use. | ### Usage @@ -56,8 +56,10 @@ agent = ( # src/main.py: a declaration app = agent.build(Config(settings_files=["settings.toml", ".secrets.toml"])) # what create_app() does ``` -Components are registered as **classes**: a group refuses an instance, because it would be -constructed before any namespace exists. +Components are registered as **classes** (constructor arguments as keyword arguments) or +zero-argument factories: a group and `build(config)` -- what `create_app()` calls -- refuse an +instance, because it would be constructed before any namespace exists. Only the older +`AppBuilder(config)...build()` form, which carries its own configuration, still accepts one. --- @@ -204,10 +206,10 @@ EventHandlerBase(priority=100) ```python class MyHandler(EventHandlerBase): - def can_handle_event(self, event, context): + async def can_handle_event(self, event, context): return event.type == "my.event.v1" - def handle_event(self, event, context): + async def handle_event(self, event, context): # process event return HandlerResult(event_type="my.result.v1", data={"ok": True}) ``` @@ -230,8 +232,8 @@ ServiceBase() | Member | Type | Description | |--------|------|-------------| -| `self.registry` | `Registry` | Access to the shared component registry. | -| `self.config` | `Config` | Application configuration. | +| `self.registry` | `Registry` | The component registry, as a view for this component's agent (the registry itself at the root). | +| `self.config` | `Config` | Application configuration, as a view for this component's agent. | | `on_startup()` | method | Called when the application starts. Override for initialization logic. | | `on_shutdown()` | method | Called when the application shuts down. Override for cleanup logic. | @@ -307,12 +309,16 @@ Base class for cron-scheduled tasks. Each scheduler automatically exposes a manu ### Constructor ```python -SchedulerBase(crontab: str) +SchedulerBase(crontab: str, *, topic: str | None = None) ``` | Parameter | Type | Description | |-----------|------|-------------| -| `crontab` | `str` | Cron expression defining the schedule (e.g., `"*/5 * * * *"`). | +| `crontab` | `str` | Five-field cron expression defining the schedule (e.g., `"*/5 * * * *"`). The day of the week counts `0` as Monday; `7` is refused, and in `event` mode so is a day given by number -- use names. | +| `topic` | `str \| None` | Replaces the derived tick subject `.scheduler.` in `event` mode. | + +`scheduler_mode` (`"event"` or `"in_process"`) is required and has no default. See +[schedulers](../components/schedulers.md). ### Abstract Methods @@ -339,17 +345,23 @@ served at `/api/{name}/trigger` standalone and at `/api//scheduler/{name} Central component registry. Provides lookup for services, agents, and other components by name or class. +A component's `self.registry` is a **view** for its own agent (the registry itself at the root). +On a view an omitted `namespace` means this agent: its own component first, then the root's. On +the registry itself it means every agent. A view may name its own namespace or the root +(`namespace=""`); naming another agent raises. + ### Methods | Method | Returns | Description | |--------|---------|-------------| -| `get_service(name_or_class)` | `ServiceBase` | Retrieve a registered service by name (str) or class. | -| `get_agent(name)` | `AgentRuntime` | Retrieve a registered agent by name. | -| `get_component(name_or_class)` | `Component` | Retrieve any registered component by name or class. | +| `get_service(name_or_class, namespace=None)` | `ServiceBase` | Retrieve a registered service by name (str) or class. | +| `get_agent(name, namespace=None)` | `AgentRuntime` | Retrieve a registered agent by name. | +| `get_component(name_or_class, namespace=None)` | `Component` | Retrieve any registered component by name or class. | +| `get_cache(name="default", *, namespace=None)` | `CacheService` | The agent's cache declared under `name`. No fallback to another name, the root or a neighbour: an undeclared name raises. | ### Properties | Property | Type | Description | |----------|------|-------------| -| `cache_service` | `CacheService` | The shared cache service instance. | +| `cache_service` | `CacheService` | The agent's default cache, as `get_cache()`. Raises when the agent declared none. | | `correlation_context` | `CorrelationContext` | The current correlation/trace context. | diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index ddf765fb..b312ad94 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -2,7 +2,7 @@ Complete reference for all `settings.toml` configuration keys in the Blueprint Agents framework. -Settings are loaded from `settings.toml` (and optional environment-specific overrides). Environment variables can override any key using the prefix `BLUEPRINT_` with double-underscore separators (e.g., `BLUEPRINT_APP_PORT=9000`). +Settings are loaded from `settings.toml` (and optional environment-specific overrides). Environment variables can override any key using the prefix `DYNACONF_`, with double underscores for nesting (e.g., `DYNACONF_APP_PORT=9000`, `DYNACONF_CACHE__BACKEND=redis`). An `envvar_prefix` adds a second spelling beside it and wins for the same key; `DYNACONF_` keeps working. The `BLUEPRINT_` variables below are a separate set, read by the framework directly. --- @@ -14,7 +14,7 @@ Top-level application settings. |-----|------|---------|-------------| | `app_name` | `str` | `"agent_blueprint"` | Application name. Used in logging, health checks, and OpenTelemetry service identification. | | `app_port` | `int` | `8000` | HTTP port the application listens on. | -| `app_environment` | `str` | `"development"` | Deployment environment identifier (e.g., `"development"`, `"staging"`, `"production"`). `"development"` enables development fallbacks such as the localhost default for `nats_url`, and the process logs a WARNING at startup that it is not suitable for production. Being the default, a deployment that sets nothing runs in development mode: set it to anything else to deploy. | +| `app_environment` | `str` | `"development"` | Deployment environment identifier (e.g., `"development"`, `"staging"`, `"production"`), which also selects the settings section that is layered over `[default]`. Set it with `DYNACONF_APP_ENVIRONMENT` or as a top-level key of the settings file, above every section: inside `[default]` it selects nothing. `DYNACONF_ENVIRONMENT` is not read. `"development"` enables development fallbacks such as the localhost default for `nats_url`, and the process logs a WARNING at startup that it is not suitable for production. Being the default, a deployment that sets nothing runs in development mode: set it to anything else to deploy. | | `log_level` | `str` | `"INFO"` | Root log level. One of `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`. | | `log_format` | `str` | `"text"` | Log output format. `"text"` for human-readable, `"json"` for structured JSON logging. | | `startup_retry_interval_seconds` | `float` | `30` | Seconds between attempts to start again the components of a non-critical agent whose `on_startup` raised. The agent stays out of service, shown with a `reason` in `/health/ready`, until every failed component starts; it is retried indefinitely and never ends the process. Must be positive; startup fails otherwise. Process scope. | @@ -27,7 +27,7 @@ Settings for the event bus transport layer. | Key | Type | Default | Description | |-----|------|---------|-------------| -| `event_bus` | `str` | `""` | Event bus implementation. Set to `"dapr"` for Dapr pub/sub or `"nats"` for NATS. Empty string disables the event bus. | +| `event_bus` | `str` | `""` | Event bus implementation. Set to `"dapr"` for Dapr pub/sub, `"nats"` for NATS, or `"sessions"` for the sessions service's job stream (which carries no topics). Empty string disables the event bus. Process scope. | | `nats_url` | `str` | none -- `"nats://localhost:4222"` in development only | NATS server URL. Only used when `event_bus = "nats"`. Unset, a process with `app_environment = "development"` connects to localhost and logs a WARNING saying so; in any other environment startup fails naming this key, because `localhost` is almost always wrong in a container and a client pointed at it retries forever while the pod looks healthy. A broker in the same pod is the exception: set `nats_url` to it explicitly. | | `nats_user` / `nats_password` | `str` | unset | Username and password for the NATS connection. Set both or neither. Put the password in `.secrets.toml` or the environment, never in `nats_url`: a URL carrying credentials is itself a secret. Only used when `event_bus = "nats"`. | | `nats_token` | `str` | unset | Token authentication for the NATS connection. | @@ -68,20 +68,22 @@ Settings for the event bus transport layer. These are read straight from the environment, not from `settings.toml`, and carry the `BLUEPRINT_` prefix rather than Dynaconf's. They describe *where* the process runs, so they -are used for the NATS connection name and for nothing else: no queue group, durable name or -dead-letter subject may be derived from them, or moving an agent between deployments would -change which broker-side consumer it is. +are used for attribution only -- the NATS connection name, the telemetry resource +(`deployment.group`, `service.instance.id`) and the agent-down log lines -- and for nothing else: +no queue group, durable name or dead-letter subject may be derived from them, or moving an agent +between deployments would change which broker-side consumer it is. | Variable | Default | Description | |-----|---------|-------------| -| `BLUEPRINT_GROUP` | `` in the connection name | Deployment group this process was started as. Appears in the middle position of the NATS connection name, which is `..`. A standalone agent -- no namespace, no group -- is named after its pod alone, and sends no name if the pod cannot be determined. | +| `BLUEPRINT_GROUP` | `` in the connection name | Names the group to load. The group resolved at startup -- `BLUEPRINT_GROUP`, or the only group a `BLUEPRINT_GROUP_CONFIG` file declares; with `BLUEPRINT_AGENTS` alone, `` -- appears in the middle position of the NATS connection name, which is `..`. A standalone agent -- no namespace, no group -- is named after its pod alone, and sends no name if the pod cannot be determined. | | `POD_NAME` | -- | Replica identity, preferred over `HOSTNAME` because a deployment can set it explicitly through the Kubernetes downward API. Appears in the last position of the connection name. | | `HOSTNAME` | the host name, else `` | Used when `POD_NAME` is unset; the kubelet sets it to the pod name. | Every NATS connection is named `..`, which is what makes a pod's contents legible in the broker's `/connz` output. A single-agent application -- no namespace and no -group -- is named after its pod alone, and sends no name if the pod cannot be determined; the root -of a grouped process is `..`. +group -- is named after its pod alone, and sends no name if the pod cannot be determined. So is +the root of a group nothing named (`BLUEPRINT_AGENTS` alone), whose agents are +`..`; the root of a named group is `..`. These variables are read by the framework, not through `Config`. An agent in a group cannot read `blueprint_group`, `pod_name` or `hostname` through its configuration -- `get()` raises -- so that no @@ -109,6 +111,7 @@ from, so it is validated once, where it enters the framework, and never rewritte | No `.`, `*`, `>` | Subject separator and wildcards; illegal in a NATS consumer name. | | No `<`, `>` | Reserved for the connection-name placeholders above. | | No surrounding whitespace | Not trimmed for you: the trimmed and untrimmed forms would be one agent registered under one name and subscribed under another. | +| Not `cache`, `event_publishing`, `runtimes` or `runtime` | Configuration sections the whole process shares. An agent's settings live under its name, so an agent of one of these names would write into that shared section. | An illegal namespace fails in `Component.__init__` -- before the registry name is derived and before registration, and for every component including those that never register. It is not @@ -141,7 +144,7 @@ effects is acceptable is a property of the product, not of the framework. | Key | Type | Default | Description | |-----|------|---------|-------------| -| `idempotency_enabled` | `bool` | `false` | Skip an event whose `id` and `source` were already dispatched within the window -- on the same named connection, when it came from one (each connection is a data source of its own). Requires `idempotency_ttl` and a registered cache (`.with_cache()`); startup fails if either is missing, rather than leaving deduplication silently off. The claim is the cache's atomic set-if-absent, so replicas sharing a Redis cache cannot both dispatch the same event. A disk cache's claim holds within one process only -- several `app_workers` or replicas on a shared volume can both win it -- and a cache error fails open. | +| `idempotency_enabled` | `bool` | `false` | Skip an event whose `id` and `source` were already dispatched within the window -- on the same named connection, when it came from one (each connection is a data source of its own). Requires `idempotency_ttl` and a registered cache (`.with_cache()`); startup fails if either is missing, rather than leaving deduplication silently off. The claim is the cache's atomic set-if-absent, so replicas sharing a Redis cache cannot both dispatch the same event. A disk cache's claim holds within one process only -- replicas sharing a cache directory (or `uvicorn --workers N` run by hand) can both win it -- and a cache error fails open. A marker cannot tell a running delivery from a finished one, so startup logs a WARNING where a run can outlast its delivery: with `nats_heartbeat_enabled = false`, and under Dapr, which has no heartbeat. | | `idempotency_ttl` | `int` | -- | Seconds a processed event is remembered. No default on purpose -- it must outlast the broker's redelivery window (`nats_ack_wait` * `nats_max_deliver` on JetStream, the component's retry policy under Dapr), and a window that expires before the last redelivery looks exactly like deduplication not working. | --- @@ -151,7 +154,7 @@ effects is acceptable is a property of the product, not of the framework. | Key | Type | Default | Description | |-----|------|---------|-------------| | `scheduler_timezone` | `str` | unset -- the host's local time | The IANA timezone the `in_process` timer reads its crontab in (`"UTC"`, `"Europe/Berlin"`). An unknown name fails startup. In `event` mode the external cron's own timezone decides and this key changes nothing. | -| `scheduler_mode` | `str` | -- (**required** when a scheduler is registered) | Where a scheduler's tick comes from. `"event"` starts no in-process timer: the tick arrives as an ordinary event on the scheduler's own topic (`.scheduler.`, with `app_name` for a scheduler at the root and the scheduler's name without the agent, unless overridden with `topic=` in the scheduler's constructor), published by an external `CronJob`, so the queue group already picks exactly one replica and nothing is elected -- it requires `event_bus` to be `"dapr"` or `"nats"`, since `"sessions"` cannot deliver a topic. `"in_process"` runs an APScheduler timer inside every replica and coordinates them through the registered cache: each tick is claimed under a key derived from the scheduler and the scheduled minute, and only the replica that stores the marker runs it. Intended for local development and un-orchestrated Docker, where no `CronJob` exists. **With no cache registered the ticks cannot be coordinated and every replica runs every tick**; startup warns about it. **No default:** neither value is safe to inherit silently, and which one applies depends on the deployment (is a broker reachable, does more than one replica run, is there an orchestrator at all) rather than on the code, so the author states it -- the same reasoning as `idempotency_ttl`. An absent, empty or unrecognised value fails startup. | +| `scheduler_mode` | `str` | -- (**required** when a scheduler is registered) | Where a scheduler's tick comes from. `"event"` starts no in-process timer: the tick arrives as an ordinary event on the scheduler's own topic (`.scheduler.`, with `app_name` for a scheduler at the root and the scheduler's name without the agent, unless overridden with `topic=` in the scheduler's constructor), published by an external `CronJob`, so the queue group already picks exactly one replica and nothing is elected -- it requires `event_bus` to be `"dapr"` or `"nats"`, since `"sessions"` cannot deliver a topic. `"in_process"` runs an APScheduler timer inside every replica and coordinates them through the registered cache: each tick is claimed under a key derived from the scheduler and the scheduled minute, and only the replica that stores the marker runs it -- across replicas only on a Redis cache; a disk cache's claim holds within one process, so with a disk cache per pod every replica runs every tick. Intended for local development and un-orchestrated Docker, where no `CronJob` exists. **With no cache registered the ticks cannot be coordinated and every replica runs every tick**; startup warns about it. **No default:** neither value is safe to inherit silently, and which one applies depends on the deployment (is a broker reachable, does more than one replica run, is there an orchestrator at all) rather than on the code, so the author states it -- the same reasoning as `idempotency_ttl`. An absent, empty or unrecognised value fails startup. | --- @@ -205,14 +208,22 @@ Top-level settings for prompt file resolution. Section: `[default.cache]` -Disk cache settings used when `with_cache()` is enabled on the `AppBuilder`. +Cache settings used when `with_cache()` is enabled on the `AppBuilder`. In a group an agent may set its own under `[default..cache]`. See [caching](../concepts/caching.md). | Key | Type | Default | Description | |-----|------|---------|-------------| -| `cache_dir` | `str` | `".cache/blueprint"` | Directory for cache storage. | -| `size_limit` | `int` | `1000000000` | Maximum cache size in bytes (default ~1 GB). | -| `eviction_policy` | `str` | `"least-recently-used"` | Cache eviction policy. | -| `default_ttl` | `int` | `3600` | Default time-to-live for cache entries in seconds. | +| `backend` | `str` | `"disk"` | `"disk"` or `"redis"`. Redis needs the `redis` extra. | +| `cache_dir` | `str` | `".cache/blueprint"` | Directory for cache storage. Disk only. | +| `size_limit` | `int` | `1000000000` | Maximum cache size in bytes (default ~1 GB). Disk only. | +| `eviction_policy` | `str` | `"least-recently-used"` | Cache eviction policy. Disk only. | +| `default_ttl` | `int` | `3600` | Default time-to-live for cache entries in seconds. Both backends. | +| `key_prefix` | `str` | `""` | Prefix of every Redis key, keeping services apart in a shared Redis. | +| `redis_url` | `str` | unset -- `"redis://localhost:6379/0"` | Redis connection URL. | +| `redis_password` | `str` | unset | Redis password. Put it in `.secrets.toml` or the environment. | +| `redis_db` | `int` | `0` | Redis database index. | +| `redis_tls` | `bool` | `false` | Connect with TLS (`rediss://`). | +| `redis_socket_timeout` | `float` | unset -- redis-py's own, 5 s | Seconds a Redis call may block, the connect included. | +| `fallback_to_local` | `bool` | `false` | Use a disk cache when Redis is not installed or does not answer at startup; otherwise startup fails. | --- @@ -224,7 +235,7 @@ OpenTelemetry and tracing settings. |-----|------|---------|-------------| | `otel_enabled` | `bool` | `false` | Enable OpenTelemetry tracing and metrics export. | | `otel_endpoint` | `str` | -- | OTLP collector endpoint URL (e.g., `"http://localhost:4317"`). | -| `otel_service_name` | `str` | -- | Service name reported to the OTLP collector. Defaults to `app_name` if not set. | +| `otel_service_name` | `str` | `app_name` | `service.name` of the root namespace -- a standalone application's whole telemetry. Every agent of a group reports its own name instead, and in a group `OTEL_SERVICE_NAME` names the root only, with a WARNING at startup. See [observability](../concepts/observability.md). | | `token_metrics_enabled` | `bool` | `true` | Record LLM token usage and response latency to OpenTelemetry. Only takes effect when `otel_enabled` is also `true`. | --- @@ -239,6 +250,22 @@ Additional logging behavior settings. --- +## Health and Diagnostics + +| Key | Type | Default | Description | +|-----|------|---------|-------------| +| `readiness_policy` | `str` | `"all"` | Which agents gate `/health/ready`: `"all"`, `"critical"` (only the agents the group flagged critical) or `"any"` (ready while one is up). The root gates readiness under every policy. Any other value fails startup. Process scope. | +| `health_check_interval_seconds` | `int` | `30` | Seconds between health polls; readiness and an agent's pause or resume follow the latest poll. Process scope. | +| `event_loop_debug` | `bool` | `false` | asyncio debug mode, which names a blocking callback and its source. Off unless set, in every environment; with it on, the watchdog does not run. Read as a boolean (`"false"` from the environment means false); any other value fails startup. | +| `event_loop_slow_callback_seconds` | `float` | `0.2` | Debug mode's threshold for reporting a callback. | +| `event_loop_watchdog_enabled` | `bool` | `true` | The watchdog that reports a blocked loop and the agents that had work in flight, when debug mode is off. | +| `event_loop_watchdog_interval_seconds` | `float` | `1.0` | How often the watchdog wakes. | +| `event_loop_block_threshold_seconds` | `float` | `1.0` | Lag the watchdog reports. | + +See [observability](../concepts/observability.md) for the readiness payload and the loop watchdog. + +--- + ## Example settings.toml ```toml @@ -264,7 +291,7 @@ nats_stream_name = "EVENTS" nats_ack_wait = 300.0 # must exceed the p99 handler duration nats_max_ack_pending = 16 # outstanding messages across all replicas nats_max_deliver = 5 # attempts before the message is dead-lettered -nats_max_concurrent_runs = 8 # deliveries one process handles at once (unset: one per subscription) +nats_max_concurrent_runs = 8 # deliveries one (agent, connection) pair runs at once (unset: one per subscription) # nats_dead_letter_subject = "my_agent_service.dead-letter" # defaults to .dead-letter # Event deduplication (off by default; both keys are needed to turn it on) diff --git a/src/blueprint/agent_generator/docs/reference/models.md b/src/blueprint/agent_generator/docs/reference/models.md index f9d60557..5b550a93 100644 --- a/src/blueprint/agent_generator/docs/reference/models.md +++ b/src/blueprint/agent_generator/docs/reference/models.md @@ -82,14 +82,22 @@ Model provider and runtime settings resolved from a `[default.runtimes.]` **Module:** `blueprint.agents.models.config` -Disk cache settings. +Cache settings, for the disk and the Redis backend. | Field | Type | Default | Description | |-------|------|---------|-------------| -| `cache_dir` | `str` | `".cache/blueprint"` | Directory for cache files. | -| `size_limit` | `int` | `1000000000` | Maximum cache size in bytes. | -| `eviction_policy` | `str` | `"least-recently-used"` | Eviction strategy. | +| `backend` | `str` | `"disk"` | `"disk"` or `"redis"`. | +| `cache_dir` | `str` | `".cache/blueprint"` | Directory for cache files. Disk only. | +| `size_limit` | `int` | `1000000000` | Maximum cache size in bytes. Disk only. | +| `eviction_policy` | `str` | `"least-recently-used"` | Eviction strategy. Disk only. | | `default_ttl` | `int` | `3600` | Default entry TTL in seconds. | +| `key_prefix` | `str` | `""` | Prefix of every Redis key. | +| `redis_url` | `str \| None` | `None` | Redis connection URL; `None` connects to `redis://localhost:6379/0`. | +| `redis_password` | `str \| None` | `None` | Redis password. | +| `redis_db` | `int` | `0` | Redis database index. | +| `redis_tls` | `bool` | `False` | Connect with TLS. | +| `fallback_to_local` | `bool` | `False` | Use a disk cache when Redis is unavailable at startup. | +| `redis_socket_timeout` | `float \| None` | `None` | Seconds a Redis call may block, the connect included; `None` keeps redis-py's default (5 s). | --- @@ -116,7 +124,8 @@ OpenTelemetry and logging configuration. |-------|------|---------|-------------| | `otel_enabled` | `bool` | `False` | Whether OpenTelemetry export is enabled. | | `otel_endpoint` | `str \| None` | `None` | OTLP collector endpoint. | -| `otel_service_name` | `str \| None` | `None` | Service name for telemetry. | +| `otel_service_name` | `str` | `"agent-service"` | Service name for telemetry. `Config.get_observability_config()` fills it with `otel_service_name`, else `app_name`, for the root, and with the agent's name for an agent. | +| `token_metrics_enabled` | `bool` | `True` | Whether token usage and latency metrics are recorded. | | `log_level` | `str` | `"INFO"` | Log level for the application. | --- From 4c10274fe9aac6adc2830d1c717bd56d3cceff8c Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Tue, 20 Oct 2026 12:40:06 +0200 Subject: [PATCH 128/133] docs(plan): the PR #96 review-fix plan and its records Findings M1-M12, S1-S27, N1-N20 with their verification, the steps and what each one did, and the decisions D1-D23. Open: step 22 (D23, N12, N15, N16, N19), N18 (the generated handler's event type) and D22 (disk-cache claim across processes). Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/plans/2026-10-16-pr96-review-fixes.md | 314 +++++++++++++++++++++ 1 file changed, 314 insertions(+) create mode 100644 docs/plans/2026-10-16-pr96-review-fixes.md diff --git a/docs/plans/2026-10-16-pr96-review-fixes.md b/docs/plans/2026-10-16-pr96-review-fixes.md new file mode 100644 index 00000000..f620e6a9 --- /dev/null +++ b/docs/plans/2026-10-16-pr96-review-fixes.md @@ -0,0 +1,314 @@ +# PR #96 review fixes -- verification and plan + +**Status:** steps 1-21 implemented 2026-10-19 (not committed yet), each marked **Done** below with what ran +live; final run with containers recorded in the feature changelog. Open: D21 (N12) and the way forward +on D22 (N13); everything else in "Decisions" is settled. +**Base:** `81f6bf2` (head of `feature/multi-agent-namespaces`, unchanged since the reviews). +**Sources:** pajoma's review (2026-10-15, CHANGES_REQUESTED, 3 blockers), Develebook's review +(2026-10-16, 12 must-fix / 27 should-fix / 9 nits, inline), solicho's leftovers (2026-09-14/16). +Earlier comments (version bump, retarget to `develop`, #97) are resolved. + +Every step below is one reviewable change under the multi-agent-grouping rules in `CLAUDE.md`: +one step, report with the code walkthrough, record it in +`docs/plans/2026-08-28-multi-agent-grouping-changelog.md`, then stop. NATS, Redis, Dapr and +Dockerfile steps get a live run in WSL before they are reported as done. + +--- + +## 1. Verification result + +Every finding was re-checked against `81f6bf2`: by reading the code, and for most by a throwaway +reproduction (fakes, fakeredis, InMemoryMetricReader, APScheduler/croniter, Docker in WSL). +Verdicts: **C** confirmed, **P** partly, **R** refuted. "SA" = also affects standalone agents. + +### Blockers (pajoma) + +| # | Finding | Verdict | SA | Step | +|---|---|---|---|---| +| B1 | Dedup marker survives `CancelledError` (handler timeout, shutdown) -> redelivery ACK'd unrun | C (repro) | yes | 1 | +| B2 | `dapr.py:46` logs `RequestValidationError` incl. payload values at ERROR | C (repro) | yes | 2 | +| B3 | Internal product name / tenant subject prefix in 6 tracked files, 8 branch commits, public repo | C | -- | 3 | + +B3 detail: the name is absent from `develop`; it entered on this branch (plan `2026-10-14-named-connections.md`, +`tests/integration/{nats-accounts.conf,connection_source.py}`, three unit tests under +`tests/unit/agents/clients/io/`, and the feature changelog history). The branch is pushed, so the name is +already public. References to sibling repositories (`docs/specs/2026-08-24-...`, `sessions_bus.py`, +`key_provider.py`) predate the branch and are on `develop` too. + +### Must-fix (Develebook) + +| # | Finding | Verdict | SA | Step | +|---|---|---|---|---| +| M1 | JetStream reconnect re-subscribes although nats-py replays `_subs` -> orphaned duplicate subs | C (nats-py 2.15 read) | yes | 4 | +| M2 | Failed `resume_consumption` never retried; health stays green | C | yes | 5 | +| M3 | Superseded named binding keeps consuming after change-change / change-remove | C (code) | named conns | 6 | +| M4 | Subscribe permission violation reads as "bound", never rebinds | C (nats-py read) | named conns | 6 | +| M5 | Agent's own `.secrets.toml` never loaded in a group | C (repro) | no | 8 | +| M6 | Clearing the root Redis cache deletes every agent's/named cache; `key_prefix=""` -> whole DB | C (fakeredis) | yes (named caches) | 12 | +| M7 | `critical_agents` typo -> all non-critical; scalar YAML; zero-agent pod READY | C (repro) | no | 7 | +| M8 | Grouped event-mode tick handler registered in root namespace (C1) | C (repro) | no | 10 | +| M9 | Grouped tick subject / trigger route repeat the agent name; docs disagree | C (repro) | no | 10 | +| M10 | `group_Dockerfile` HEALTHCHECK uses `curl`, absent in slim image | C (WSL) | no | 14 | +| M11 | Dedup marker stays claimed when post-dispatch processing fails | C (repro) | yes | 1 | +| M12 | `/status/env` masker leaks (`/?#` in password, query tokens, `AccountKey=`) and 500s on `${PORT}` | C (repro) | yes | 13 | + +### Should-fix and nits + +| # | Finding | Verdict | SA | Step | +|---|---|---|---|---| +| S1 | Durable clash root `orders-created` vs agent `orders`+`created`; drift only warns | C | yes | 18 | +| S2 | Binding mode plain `subscribe` receives JetStream status/flow-control messages | C (mechanism) | named conns | 6 | +| S3 | `ConnectionSpec.tls` in `__eq__` -> every notify rebinds every `tls://` link | C (repro) | named conns | 6 | +| S4 | `_Link.connect_options` default repr leaks password/token/nkey | C (repro) | yes | 2 | +| S5 | Dapr fan-out hands the same `CloudEvent` to every agent; no shared-topic warning | C | no | 16 | +| S6 | Marker has no in-progress state: concurrent duplicate is ACK'd | C (repro) | yes | 15 | +| S7 | Sync redis-py claim/delete on the event loop | P: redis-py 8.1 has 5 s timeouts, `>=5.0` pin allows None | yes | 15 | +| S8 | Dapr returns `str(exc)` in response body (develop: fixed text) | C | yes | 2 | +| S9 | Unbounded `topic` label cardinality via `/events/` | C (5000 points measured) | yes | 16 | +| S10 | `SessionsJobHandler` auto-declares its type, narrowing widened `can_handle_event` | C | yes | 19 | +| S11 | Bare key equal to another agent's namespace returns its section through a view | C (repro) | no | 8 | +| S12 | Namespaces not reserved against shared sections / root scalars | C (weaker than claimed: fill-missing keeps a set root value) | no | 8 | +| S13 | Fragments layered for first-pass `app_environment`, not the env Dynaconf loads | C (repro) | no | 8 | +| S14 | `DYNACONF_ENVIRONMENT` in scaffold Dockerfiles selects nothing | C (repro; predates PR, matters since #89) | yes | 14 | +| S15 | `_` separator ambiguity; qualified registry hit has no ownership check | C (code) | no | 9 | +| S16 | Registry mutation methods unguarded on views | C (code) | no | 9 | +| S17 | Bound methods / closures pass `is_shareable` | C (repro) | no | 9 | +| S18 | C4 missing for `event_bus = "sessions"` | C | no (no C4 on develop) | 5 | +| S19 | `deployment_group()` ignores the group resolved from the file | C | no | 20 | +| S20 | Undocumented standalone breaks: built-in health check name, handler class+instance, deferred construction | C (vs develop) | yes | 19 | +| S21 | `event_loop_debug` on by default in "development" (the default env) | C | yes | 19 | +| S22 | One OTLP exporter (and one BatchSpanProcessor) shared, closed by first provider shutdown | C (repro) | no | 17 | +| S23 | diskcache_rs exclusive lock vs "atomic across processes" docs | P: true for <=0.4.9 (redb), false for 0.4.10 (sqlite); pin `>=0.4.4` | yes | 20 | +| S24 | Crontab dialect: APScheduler Mon=0 vs croniter Sun=0; `7` rejected; host timezone | C (APS 3.11.3; predates PR) | yes | 11 | +| S25 | Scheduler `_started` set before success -> recovery reports success without timer | C (code) | partly | 11 | +| S26 | Second scheduler's tick-age gauge dropped | C (InMemoryMetricReader) | yes | 11 | +| S27 | `asbs validate` scheduler checks differ from runtime (a-e) | C (all five) | yes | 11 | +| N1 | Shutdown aborted by a failed recovery task (more than a nit); `actuator.on_shutdown` unguarded | C; `_loop_watchdog.stop()` part **R** | yes | 19 | +| N2 | Duplicate group names last-wins; scalar `agents` | C (repro) | no | 7 | +| N3 | Raw `exc` in NATS WARNING/ERROR logs | P: defensive, no real nats-py text with password found | yes | 2 | +| N4 | `pause_consumption` waits on `_change_lock`; `message_handler` has no paused gate | C | named conns | 4 | +| N5 | Dapr TERM+ACK answers SUCCESS with a reason; `route_class` applies to the whole router | C (repro) | yes | 16 | +| N6 | `asbs dev` without `--name` serves root, messages say otherwise | C | msgs only | 14 | +| N7 | `asbs setup` validates the name after writing the project | C (repro) | yes | 14 | +| N8 | `settings.txt` comment token `app_name` substituted | C | yes | 14 | +| N9 | Scheduler template docstring wrong; `asbs create service` misses imports (older) | C | yes | 14 | +| N10 | "Created JetStream consumer" INFO formats `ack_wait` with `%.1f`; unset `nats_ack_wait` is `None`, so the line is lost as a logging error | C (live, found in step 2) | yes | 18 | +| N11 | Startup against an unreachable broker did not return within 6 s (only nats-py's own "encountered error" was logged) | observed live in step 2, not analysed; check against the `max_reconnect_attempts=-1` connect | yes | 4 | +| N12 | An agent whose own subscription keeps failing reports ready: the failure degrades it, C4 pauses it, and a paused client reports healthy by design, so after one poll readiness is UP while `_retry_resume` keeps failing (backoff 5 s, 10 s, ...) and nothing is consumed | C (live, found in step 18; any persistent subscribe failure, not only S1) | open -- needs a decision on C4, see below | -- | +| N13 | `DiskCacheService.claim` is not atomic across processes: diskcache-rs 0.4.10's `add` lets several processes on one directory win one key (297 of 300 rounds, 4 processes, no error); 0.4.9 refused a second process the directory | C (live, step 20) | docs corrected; fix open as D22 | -- | +| N14 | M4's refusal check raced: nats-py 2.15 writes PING straight to the transport while the SUB still waits for the flusher, so the PONG could come back before the broker saw the SUB and the binding read as bound (`TestARefusedSubscriptionIsNotBound` failed 3 of 9 runs on the step-21 code, 1 of 2 on step 17, 0 of 2 on step 6) | C (live, final run) | **Fixed 2026-10-19**: two round trips in `_bind`; 8 of 8 runs green | -- | +| N15 | `app_environment` inside `[default]` makes `Config.get("app_environment")` answer the configured value while Dynaconf loads the default section, so a development check can read the wrong environment (found by the docs agent with a probe; the docs now say the key selects only at top level or through `DYNACONF_APP_ENVIRONMENT`) | P (probe, not re-checked) | open -- check and decide in step 22 | -- | +| N16 | `.otel_service_name` is resolved by `Config._resolve_service_name` but never reaches the resource: `TelemetryManager._configure_namespace` sets `service.name` to the namespace for every agent | C (code read by the docs agent) | open -- belongs with D23 (c) in step 22 | -- | +| N17 | `handler_chain._warn_without_a_heartbeat` compared `nats_heartbeat_enabled is False`, so `"false"` from an environment variable did not warn | C (unit test failed before) | **Fixed 2026-10-19**: read with `parse_bool` | -- | +| N18 | The generated handler's `on_startup` read `.get("input_event_type", )` -- `None` when the key is missing -- and compared it to `""`, so a handler without its event type started anyway (found by the validator agent). Making the check fire stops every fresh scaffold: `asbs setup`'s own handler has no `input_event_type` and does not use it (`can_handle_event` is a stub) -- found live on a scaffold, `ValueError` at startup | C (live, with control) | open -- the fix was withdrawn on 2026-10-20 (owner decision); what the generated handler does with the event type is decided later. `test_a_fresh_project_starts_the_way_its_container_does` keeps a scaffold startable | -- | +| N19 | The validator restates runtime rules that exist only as private methods: dedup policy and heartbeat/Dapr warnings (`HandlerChain`), the timezone check (`SchedulerBase`), the shared-topic grouping (`DaprEventing`), the `nats_url`/heartbeat/durable-count rules (`NatsClient`); pinned by tests, matched live word for word | C (code read) | open -- make them public and call them from the validator in step 22, which edits the same files | -- | +| N20 | `test_design_rules.all_markdown()` walked the whole checkout with `rglob`, `.venv` included, and filtered afterwards -- about 0.6 s per test, 47 s for the module | C (measured) | **Fixed 2026-10-20**: directories pruned before they are entered; same 91 files, 14 s | -- | + +### pajoma warnings/suggestions and solicho leftovers + +| # | Finding | Verdict | Step | +|---|---|---|---| +| W1 | `OTEL_SERVICE_NAME` collapses grouped identity (C2) | C (repro) | 17 | +| W2 | `in_process` claim slot from `datetime.now()` | P: correct, but practically harmless (misfire grace 1 s) | 20 | +| W3 | Omitted `namespace` = all on root registry, own on a view | C, by design; risk only for user root components in groups | 20 | +| W4 | Run slot can leak between acquire and `create_task` | P: theoretical | 18 | +| W5 | `_durable_for` docstring says nothing is renamed (dotted topics are) | C | 18 | +| W6 | Isolation guard keyed by `id(builder)` only | C; decided: document, sharing between agents is fine | 9 | +| T1 | Dedup key not scoped to the named connection -> one tenant's event can suppress another's | C (code, found 2026-10-16) | 1a | +| W7 | Stale xfail paragraph in `test_agent_isolation.py` | C | 21 | +| W8 | Hand-set `version = "0.9.0"` and dated `[0.9.0]` CHANGELOG section vs `AGENTS.md` versioning rule | C | 21 | +| W9 | PR description stale (#89, LICENSE, size), no `Closes`, no AI disclosure, #35 not linked, no rollback note | C | 21 | +| W10 | CI runs only `tests/unit` | C | out of scope (CI, needs services) | +| W11 | `NATSClient` 2,652 lines; transitional test-only members; PR size | C | out of scope (follow-up issue) | + +Overlap with the 2026-09-24 defect list: M1 was item 5 there, S7 item 9. Neither had been fixed. + +--- + +## 2. Steps + +Must-fix and blockers first (steps 1-14), then hardening (15-20), then documentation and PR hygiene (21). + +1. **Dedup bracket** (B1, M11). `EventProcessingService.process_event` / `HandlerChain`: one + `try/except BaseException` from claim to settled result that releases the marker, replacing the + publish-only release. Tests: timeout + dedup, scalar return + dedup, cancel mid-handler. + **Done 2026-10-19** (not committed): also covers a handler that swallows the cancellation; + measured live on JetStream with a control run against the unchanged code. +1a. **Connection isolation** (T1, user requirement 2026-10-16). The blueprint knows no tenants, only + named connections, but no framework-owned state may be shared across connections, because each one + stands for a different data source behind it. Checked: result publishing is refused on named + connections (`_refuse_result_publishing`), dead letters go out on the arrival link, each run has its + own task context. **Gap:** the dedup key is `(source, id)` only (`handler_chain.py:532`), so two + connections delivering the same producer's event id suppress each other. Fix: add the connection + name to the key when the delivery came from a named connection (the default connection keeps + today's key, no migration). Test: two connections, identical `(source, id)`, both handled. Docs: a + section for handler authors -- state that must stay per data source is keyed by the + `nats_connection` context key. M3 (a removed connection still consumed) is the same class, step 6. + **Done 2026-10-19** (not committed): unit tests with a control run, and a broker test on the accounts + broker (`test_dedup_keeps_the_connections_apart`) that fails without the change. +2. **Leaks in logs and responses** (B2, S8, S4, N3). `dapr.py:46` logs `loc`/`type` only; the related + pre-existing ERROR logs in `event_processing_service.py:307/312`; Dapr reason = `exc.reason` or type + name; `_Link.connect_options` `repr=False`; NATS link logs via `_describe_error`. + **Done 2026-10-19** (not committed): also the NATS decode log (same leak as `dapr.py:46`, already on + `develop`) and `_Link.url` (`nats_url` may carry `user:pass@`); `resume_consumption`'s log is left + to step 5. Measured live with a control run; found N10 and N11 on the way. +3. **Internal naming** (B3). Replace with generic names (`acme.agent..`) in the six files. + History: see decision D1. + **Done 2026-10-19** (not committed): also the consuming repository's internal module names in the + named-connections plan; `git grep` finds none of them; `test_named_connections.py` passes on the + accounts broker with the renamed subjects. +4. **JetStream reconnect** (M1, N4; N11 checked here). **Done 2026-10-19** (not committed): N11 was a + hang -- nats-py retries the first connect itself when reconnects are unlimited; the first connect is + now bounded, and connecting while paused re-evaluates health at once. Measured live with a control + run (subscription counts from `/connz`, runs per event, paused runs, startup time). `_on_reconnected` stops re-subscribing under JetStream, re-checks + stream and consumers only; `message_handler` gets a `_consumption_paused` gate (NAK under JetStream). + Replace `test_reconnected_resubscribes_jetstream_topics` with a fake that replays `_subs`. + Live: broker restart in WSL, count subscriptions and deliveries per message. +5. **Resume retry and C4 for sessions** (M2, S18). **Done 2026-10-19** (not committed): the sessions + bus closes its job stream while paused and leaves a job that reaches it pending; the supervisor + pauses it with the IO clients. Live: M2 on JetStream with a control run; the sessions part unit-only + (no sessions service available). Unsubscribe partial subscriptions on failure, then + per D2. `SessionsBus.pause_consumption/resume_consumption`, supervisor includes it. Test supervisor and + client together. +6. **Named bindings** (M3, M4, S2, S3). Retire the `replaces` chain; `flush()` after subscribe and raise + on a matching permission error; `on_reconnected` sets ready only for bound links; drop/answer status + messages in binding mode; `tls` `compare=False`. Live: accounts broker from `tests/integration`. + **Done 2026-10-19** (not committed): four broker tests in `test_named_connections.py`, each failing on + the step-5 code; the live run also found that nats-py lowercases the -ERR line, so the refusal is + matched lowercased. +7. **Group config validation** (M7, N2). Unknown critical names, non-list `agents`/`critical_agents`, + duplicate group names -> `GroupConfigError`; empty resolved group fails at startup; D8. + **Done 2026-10-19** (not committed): unit tests with a control run; the empty group is checked in + `AgentGroup.from_config` (with unknown critical names refused, `resolve` cannot produce one). Live: + with the group image in step 14. +8. **Agent settings merge** (M5, S11, S12, S13). Merge `/.secrets.toml`; reserve shared-section + names and refuse to replace a root scalar; layer fragments for the environment Dynaconf actually + loaded and drop inactive sections; bare-key view refusal per D9. + **Done 2026-10-19** (not committed): the reserved names live in `namespace.py` (an import from the + config package would be a cycle) and a test keeps them equal to `SHARED_NESTED_PREFIXES`; the bare-key + refusal applies only where the root value is a section; `AgentGroup.assemble` declares every agent. + Live: with the group image in step 14. +9. **Registry and sharing guards** (S15, S16, S17, W6). Ownership check on the qualified lookup branch; + `clear`/`clear_components`/`shutdown_executors` refused on views, ownership checks in + `update_component_name`/`get_or_create_executor`; bound methods/closures checked; W6 per D11. + **Done 2026-10-19** (not committed): also `add_component` on a view, and a shared declaration's + factory target; W6 documented in `_refuse_state_shared_between_agents` and the migration guide. + Unit tests fail on the old code; live with the group image (step 14). +10. **Grouped scheduler** (M8, M9). Construct the tick handler under `namespace_scope(self.namespace)`; + topic and trigger route from `base_name`; fix `deployment.md`, `claude_docs/CLAUDE.md`, + `SKILL.md`, `configuration-keys.md`; literal-subject test. CHANGELOG line for alpha users of the + doubled subject. Live: NATS in WSL, publish the documented subject, see the tick. + **Done 2026-10-19** (not committed): also the tick handler's own name; the existing test that encoded + the doubled subject now asserts the base name. Live with a control run. +11. **Scheduler robustness** (S24-S27). `_started` only after success; one tick-age gauge per meter with + a multi-scheduler callback; crontab dialect/timezone per D14/D15; validate shares the runtime's checks. + **Done 2026-10-19** (not committed): `validate_crontab(crontab, mode)` runs in both modes; S27 (a)-(e) + through `normalise_scheduler_mode` / `delivers_ticks`; a missing `event_bus` is a notice. Live: two + in-process schedulers with a real timer and an SDK reader, with a control run. +12. **Redis cache isolation** (M6). Default store's `clear`/`list_namespaces` skip child-store keys + (no key-layout change); WARNING when the default store has `key_prefix=""` and is cleared. + Live: two agents on one Redis in WSL. + **Done 2026-10-19** (not committed): `_owns` (a 64-hex digest after exactly one namespace segment) + filters clear, list_namespaces and list_values; `BLUEPRINT_TEST_REDIS_URL` makes the Redis + integration tests runnable against a throwaway container. Live with a control run. +13. **`/status/env` masker** (M12 + pajoma suggestion). Fail closed on `@` after `://`, query-string + and `Key=` segment masking, port inside `try`, secret-named dicts masked whole, `pass`/`dsn`/`conn` as + `_`-delimited markers. + **Done 2026-10-19** (not committed): also `sig`/`signature` as words (SAS tokens); a secret-named + list of sections is masked whole. Live over HTTP (uvicorn) with a control run. +14. **Scaffold and CLI** (M10, S14, N6-N9). Python HEALTHCHECK in `group_Dockerfile`; environment + variable per D10; validate the name before generating; reword the `settings.txt` comment; correct + the `asbs dev` messages (behaviour unchanged); scheduler template docstring; service template imports. + Live: build the group image in WSL and watch it turn healthy. + **Done 2026-10-19** (not committed): the CLI service uses `BaseModel` (the generator derives the + parameter name from the type, so `dict[str, Any]` produced invalid code). Live: a scaffolded group + image (two agents) built in WSL from the working tree -- healthy after 10 s, environment + `production`; control (the old template): `curl: not found`, never healthy, `development`. The same + image ran the live checks of steps 7 and 8: a critical-name typo exits 1 with the message; an + agent's mounted `.secrets.toml` is merged into that agent only. +15. **Dedup without a heartbeat, Redis calls** (S6, S7). Per D4: document the redelivery-while-running + limit, startup WARNING when dedup runs without a heartbeat; claim/delete via `asyncio.to_thread`; opt-in `redis_socket_timeout` (default unchanged). + **Done 2026-10-19** (not committed): S7 rechecked under the D16 rule -- redis-py 7.0.0 has no default + timeout, 8.0.0 has 5 s (read from the tagged sources), so the floor is now `redis>=8.0.0`. The + scheduler's tick claim moved off the loop too. Live on a paused Redis with a control run. +16. **Dapr hardening** (S5, S9, N5). Deep copy per agent in fan-out; startup WARNING for a shared topic + with dedup off; `` topic label per D6; reason only when not ACK; `route_class` limited + to `/events/{topic}`. + **Done 2026-10-19** (not committed): the copy is made only when more than one agent receives the + delivery. Live: a uvicorn-served group against the Dapr sidecar mock, with a control run. +17. **Telemetry** (S22, W1). Ref-counted exporter and span processor (keeps C2's "share one"); explicit + flush and shutdown in the lifespan, root last; `OTEL_SERVICE_NAME` per D17. + **Done 2026-10-19** (not committed): the providers are built without their own atexit hook; + `shutdown_providers()` runs from the lifespan (in a worker thread) and once from atexit as the + fallback. D17 applies to `OTEL_SERVICE_NAME` only: a `service.name` declared in + `OTEL_RESOURCE_ATTRIBUTES` still names every agent. Live against an OTLP collector with a control run. +18. **NATS leftovers** (S1, W4, W5, N10). Refuse to bind on a `filter_subject` mismatch (no rename); + run-slot release on exception; `_durable_for` docstring; the consumer INFO line renders an unset + `ack_wait`. + **Done 2026-10-19** (not committed): the refusal is a `JetStreamBindingError` from + `_ensure_consumer` (a consumer listing exactly the topic in `filter_subjects` is bound); + `filter_subject` left the drift list. Live against JetStream with a control run; found N12. +19. **Standalone compatibility** (S10, S20, S21, N1). User checker replaces a built-in one with a + WARNING; class and instance handlers register in declaration order; `SessionsJobHandler` declares only + when `can_handle_event` is not overridden; `event_loop_debug` off unless set (`parse_bool`); + shutdown via `gather(..., return_exceptions=True)`, guarded `actuator.on_shutdown`; CHANGELOG entry + for deferred construction. + **Done 2026-10-19** (not committed): `HealthCheckEntry.builtin`; `Registry.reorder` permutes the + declared handlers within the slots they hold (replacing `_check_declaration_order`); + `configure_loop_debug` lost its `development` parameter. Live (standalone app, Core NATS) with a + control run; the SessionsJobHandler and shutdown parts are unit-tested only. +20. **Smaller items** (S19, S23, W2, W3). Publish the resolved group into the deployment identity; + diskcache per D16; floor the in-process slot to the scheduled time; W3 per D7. + **Done 2026-10-19** (not committed): `deployment.publish_deployment_group`, called by + `AgentGroup.resolve`; the tick slot is the trigger's latest fire time at or before now (a cursor + walked forward, misfires passed over). D16's live check failed: diskcache-rs 0.4.10 is not atomic + across processes (N13), so the docs drop the claim and D22 is open. Live in WSL with control runs. +21. **Docs and PR hygiene** (W7, W8, W9, D20). xfail paragraph; CHANGELOG/version per D19; licence back + to develop's state per D20; rollback note + (cache keys, durables, REST paths, metric label); PR description draft (#89, LICENSE, size, `Closes` + lines, #35/#75 link, AI disclosure). The description is posted only after the user has read it. + **Done 2026-10-19** (not committed): xfail paragraph in the past tense (no test is marked any + more); `[0.9.0]` folded into `[Unreleased]` (one section per heading, the 0.9.0 introduction + first, no entry lost: 170 entries before, 169 + 4 rollback points after); `pyproject.toml` at + `0.8.2`, without `license`/`license-files`; `LICENSE` removed and its CHANGELOG entry with it; + "Rolling back to 0.8" in the CHANGELOG. Not touched: README's MIT badge and licence section + (develop has them too, linking a file develop does not have), and develop's MIT classifier, + which this branch had already dropped -- D20 lists the classifier as out. PR description and + the reply to the version-bump comment are drafts, not posted. + +--- + +## 3. Decisions + +### Settled by standing rules (no question needed) + +- S1: refuse to bind on mismatch, keep today's durable names (no consumer migration). +- S7: socket timeouts as an opt-in key, default unchanged ("never change existing defaults"). +- S20: restore develop's behaviour for health check replacement and handler order ("existing agents keep working"). +- S21: `event_loop_debug` off unless set (develop had no debug mode). +- N6: `asbs dev` behaviour unchanged, messages corrected. +- M6: filter child keys rather than moving the default store (no cold cache). +- M9: fixed as a bug; grouped alpha users get a CHANGELOG line. +- D15 (timezone): host-local stays the default; opt-in `scheduler_timezone`. + +### Open, asked one at a time + +| ID | Question | Blocks step | +|---|---|---| +| D1 | B3: replace the names in the tree only, or also rewrite the published branch history? **Decided 2026-10-16: tree only, no history rewrite.** | 3 | +| D2 | M2: after a failed resume, retry in a backoff task, or report unhealthy so the supervisor cycles? **Decided 2026-10-16: backoff task in the client (cancelled by pause/close), readiness unchanged, WARNING per failed attempt.** | 5 | +| D4 | S6: in-progress TTL: opt-in key, derived from handler timeout / `ack_wait`, or document only? **Decided 2026-10-16: no in-progress state. The loss needs a redelivery while the first run is still going, which the heartbeat prevents. Document it, and log a startup WARNING when dedup runs without a heartbeat: NATS with `idempotency_enabled` and `nats_heartbeat_enabled = false`; Dapr with `idempotency_enabled` (Dapr has no heartbeat; the WARNING names the app-call timeout).** | 15 | +| D6 | S9: undeclared topics as ``, a capped set, or drop the `topic` label? **Decided 2026-10-19: `` for every topic the agent did not declare; declared topics keep their name. With `dapr_declarative_subscriptions = true` everything counts as ``, the real name stays in the log line.** | 16 | +| D7 | W3: change "omitted namespace" to mean root everywhere, warn only, or leave? **Decided 2026-10-19: leave the semantics, document them (grouping docs and the `Component.registry` docstring): a root component in a group sees every agent on collection lookups; `namespace=""` asks for the root only. Framework callers depend on "omitted = all" (`dapr.py:216/256`, `event_processing_service.py:66`, `cache.py:63`).** | 20 | +| D8 | M7: `BLUEPRINT_AGENTS` overriding the file -- discard the file's `critical_agents` with a WARNING, or keep and reject unknown names? **Decided 2026-10-16: keep the file's list; a critical name outside the resolved group fails startup.** | 7 | +| D9 | S11: a bare key naming another agent through a view -- `ValueError` or the default? **Decided 2026-10-16: `ValueError`, same rule as the dotted key.** | 8 | +| D10 | S14: scaffold Dockerfiles -- `DYNACONF_APP_ENVIRONMENT="production"`, or remove the line? **Decided 2026-10-19: fixed as a bug. `DYNACONF_APP_ENVIRONMENT="production"` in the production stage of `Dockerfile` and `group_Dockerfile`, `"development"` in the dev stage, a comment that a custom `envvar_prefix` renames the variable, `deployment.md:51` corrected. The docs state plainly that `app_environment` defaults to `development` and a deployment must set `production` itself (what changes: no localhost broker fallback, logging, asyncio debug).** | 14 | +| D11 | W6: refuse one mutable object handed to two separately declared agents, or document it? **Decided 2026-10-16: sharing between agents is allowed and documented. Sharing between tenants is not: see step 1a.** | 9 | +| D14 | S24: fix the crontab dialect as a bug (moves firing days of `in_process` schedulers), or keep and warn? **Decided 2026-10-19: the blueprint's dialect is `0` = Monday ... `6` = Sunday (APScheduler's), so `in_process` firing days do not move. `7` is refused with a clear message in `in_process` and in `validate_crontab` (no croniter pass-through). In `event` mode a numeric day-of-week fails startup: the external CronJob counts `0` = Sunday, so a number is ambiguous; the error says so and asks for names (`mon-fri`, `sun`), which both read the same. Docs: `0` = Monday, examples with names (`0 9 * * mon`, `*/15 9-17 * * mon-fri`; today's `1-5` example means Tue-Sat), a note that an external cron counts differently. CHANGELOG line for event-mode schedulers with numeric weekdays.** | 11 | +| D16 | S23: raise the pin to `diskcache-rs>=0.4.10`, or document disk as per-process only? **Decided 2026-10-19: raise the pin to `diskcache-rs>=0.4.10`. Live in WSL: two processes claim the same key, exactly one wins; "atomic across processes" stays in the docs only if that holds. Drop "a disk cache on a shared volume" for several replicas (`configuration-keys.md:144`, `deployment.md:386`): cross-pod dedup needs Redis, disk covers processes on one host. General rule (user, 2026-10-19): where a dependency's behaviour changed in a way that affects us, adapt to it and raise the minimum version -- S7 is re-checked under this rule in step 15 (which redis-py version brought the default socket timeouts).** | 20 | +| D17 | W1: in a group, ignore `OTEL_SERVICE_NAME` for agents with a WARNING, refuse to start, or document? **Decided 2026-10-19: in a group every agent provider keeps `service.name` = agent name even when `OTEL_SERVICE_NAME` is set, so telemetry stays filterable per agent; the root provider still takes `OTEL_SERVICE_NAME`. One startup WARNING names the value and why it does not apply to the agents. `OTEL_RESOURCE_ATTRIBUTES` stays untouched. Docs: the exception to "declared keys are never replaced". Standalone unchanged.** | 17 | +| D19 | W8: fold `[0.9.0]` into `[Unreleased]` and restore the `develop` version string, or keep as is? **Decided 2026-10-19: this PR follows its own `AGENTS.md` rule -- `[0.9.0] - 2026-09-14` (never released, only `v0.9.0a1..a15`) is folded into `[Unreleased]`, `pyproject.toml` goes back to develop's `0.8.2`; `publish.yml` sets the version from the tag anyway (L43/L66). Reply to SawwR's bump comment with the rule. Follow-up issue, not in this PR: derive the version from git tags with `setuptools-scm` so source installs report it too (drops the `sed` step); the stale `__version__ = "0.3.0"` fallback in `src/blueprint/__init__.py:8` goes with it.** | 21 | +| D20 | Is the MIT licence choice approved by the responsible owner (pajoma F)? Not a code decision. **Decided 2026-10-19: no approval exists. The licence is deferred: this PR goes back to develop's licence state (`LICENSE` from `a9a8f3b` removed, `license`, `license-files` and the MIT classifier out of `pyproject.toml`). Open point for the `develop` -> `main` merge: licence approval by the responsible owner, then add it there. The PR description says so. Already published alphas (`v0.9.0a1..a15`) carry MIT and cannot be changed.** | 21 | +| D21 | N12: a paused client whose own resume keeps failing reports healthy, so readiness is UP while the agent consumes nothing. Options: (a) while paused, report unhealthy once a resume attempt has failed, and let `_retry_resume` keep running through a re-pause (today a pause cancels it, which would then deadlock); (b) leave readiness as it is and add a `blueprint.nats.resume_failures` counter plus the failure in the readiness payload; (c) accept and document. **Open -- owner decision.** Measured (step 18, root topic `orders-created` against a consumer filtering `created`, health interval 2 s): 200 at 0-2 s, 503 at 2.1 s (degraded, paused), 200 from 4.1 s on while paused, resume attempts failing at 5 s and 10 s backoff. | -- | +| D22 | N13: make `DiskCacheService.claim` atomic across processes on one host -- an OS file lock (`fcntl.flock` / `msvcrt.locking`, or the `filelock` package) around the `add` -- or keep the disk cache per-process for claims and warn at startup when dedup or the in-process tick claim runs on a disk cache with `app_workers > 1`? **Decided 2026-10-19: document only, for now** -- the docs say per-process (claim docstring, deployment guide, configuration keys, CHANGELOG Known issues); how to proceed beyond that is to be clarified. | -- | +| D23 | Startup and tenancy faults (owner, 2026-10-19). **Principle: a critical problem or collision found at startup fails the start; a fault caused by a wrong or problematic tenancy is logged CRITICAL and the process exits -- at startup and at runtime, when a `ConnectionSource` change hands it over -- because an operator must notice it.** Critical means deterministic (a retry cannot fix it): durable clash (S1), stream not creatable/updatable (subject overlap), missing JetStream permissions, tenant login refused, tenant deliver subject refused, binding-mode consumer missing or filtering another subject. Transient faults (broker unreachable, connection lost, timeouts) keep retrying; D5 stays for those. Open before implementing: (a) do an agent's own faults respect `critical_agents` (spec sec. 9.1) or always exit; (b) is a missing binding-mode stream fatal or still transient (provisioning); (c) D17 -- refuse `service.name` in `OTEL_RESOURCE_ATTRIBUTES` in a group, and what happens to `OTEL_SERVICE_NAME`. Partly supersedes D21 (N12). **Added (owner, 2026-10-19): a constellation that leaves orphaned agents -- agents that should exist but consume nothing for a non-transient reason (startup latch, final subscription fault, a resume that keeps failing) -- makes the service at least unhealthy, possibly exits.** So D21 is decided in principle: a paused client whose resume keeps failing reports unhealthy. Open: whether "unhealthy" is readiness DOWN or liveness DOWN, and whether it overrides `readiness_policy = "critical"` for a non-critical agent. **Settled (owner, 2026-10-19):** (1) such critical faults set **liveness** DOWN, and each is logged well enough for an operator to act on (what failed, which agent/connection, why it is not transient, what to change); (2) a transient fault stays under `readiness_policy`, an orphaned agent counts regardless of the policy; (3) D17: in a group, a `service.name` declared only through `OTEL_RESOURCE_ATTRIBUTES` (no `OTEL_SERVICE_NAME`), which would name every agent alike, **fails the start**; `OTEL_SERVICE_NAME` alone or together with it stays as implemented (agents keep their names, WARNING). Still open: (a) an agent's own faults vs `critical_agents`, (b) a missing binding-mode stream. **Clarified (owner, 2026-10-19): M agents x N tenants; N = 0 (the source hands over no tenant) is a valid state -- nothing to bind, nothing fails (as implemented: "consumes on 0 named connection(s)").** (b) concerns N >= 1: a tenant handed over whose binding names a stream (or, with `manage_consumer = false`, a consumer) that does not exist. **(b) deferred (owner, 2026-10-19):** whether a missing binding-mode stream -- or, with `manage_consumer = false`, a missing consumer -- is fatal at once or after a grace period depends on whether the tenancy source hands over a tenant only once its stream is provisioned; to be clarified with the tenancy owner. Until then it stays as implemented: retried, visible in readiness only (`.nats_client:connections` reads `retrying`); with `manage_consumer = false` a missing consumer is not detected at all (the client sends no JetStream request). **(a) settled (owner, 2026-10-19): fail early.** A deterministic fault (durable clash, stream not creatable/updatable, missing JetStream permissions) is fatal in every agent, whatever `critical_agents` says: logged CRITICAL, startup fails or liveness goes DOWN. `critical_agents` and `readiness_policy` keep deciding only for faults that may be transient (startup recovery, health). | 22 | From 33fb329244e80af022feeb5c72a0697ee3ab93b0 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Tue, 20 Oct 2026 14:48:03 +0200 Subject: [PATCH 129/133] fix: faults no retry can fix fail early; orphaned agents are unhealthy; telemetry and validator parity Step 22 of the review-fix plan (D23, D21/N12, D17, N15, N16, N19). 22a (D23): a durable that filters another subject, a stream the server refuses, a grant the account lacks, and on a named connection a refused login or deliver subject are DeterministicTransportErrors: never retried, logged CRITICAL with what to change, and fatal in every agent -- at startup the start fails whatever critical_agents says, after it /health/live answers 503 naming the agent (spec C3 amended). A JetStream grant refused before startup used to leave the agent paused for good with nothing logged. A stream another agent of the process created meanwhile (10058) is a race, not a refusal. Named connections read "failed". 22b (N12, D21): a resume that keeps failing or a connection loop that gave up takes liveness DOWN until the agent consumes again; an agent latched down gates readiness under every policy. 22c (D17, N16): a service.name only in OTEL_RESOURCE_ATTRIBUTES fails a group's start; an agent's own otel_service_name reaches its resource. 22d (N15): app_environment reads the environment that was loaded, with a WARNING when the settings say otherwise. 22e (N19): seven startup rules are public runtime functions the validator calls; the validator's heartbeat warning (N17) and the runtime's Dapr shared-topic warning ("false" read as on) had drifted. Live in WSL against the code before this step: durable clash 8 attempts in 4 s and liveness 200 before, one refusal, CRITICAL and liveness 503 now; a refused grant paused the agent silently before, fails the start now. Integration 70 of 71 (the pre-existing redelivery-count failure). New: tests/integration/test_final_faults.py; tenancy faults in test_named_connections.py, whose D5 tests now use an unreachable broker; a conftest guard fails a test whose app sends SIGTERM. Plan: docs/plans/2026-10-16-pr96-review-fixes.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 48 +- docs/plans/2026-10-16-pr96-review-fixes.md | 57 ++- docs/specs/2026-08-28-multi-agent-grouping.md | 59 ++- .../agent_generator/cli/commands/validate.py | 127 ++---- .../cli/commands/validate_group.py | 26 +- .../docs/concepts/event-processing.md | 25 +- .../docs/concepts/observability.md | 36 +- .../agent_generator/docs/guides/deployment.md | 13 +- .../docs/guides/multi-agent-setup.md | 8 +- .../docs/guides/troubleshooting.md | 23 +- .../docs/reference/configuration-keys.md | 6 +- src/blueprint/agents/app_builder.py | 54 ++- .../agents/clients/io/nats_client.py | 423 ++++++++++++++---- src/blueprint/agents/config/config.py | 20 + src/blueprint/agents/group_config.py | 18 +- src/blueprint/agents/handler/handler_chain.py | 162 ++++--- .../agents/io/api/actuators/actuator_api.py | 37 +- .../io/api/actuators/health/health_cache.py | 4 +- .../api/actuators/health/readiness_policy.py | 14 +- src/blueprint/agents/io/api/eventing/dapr.py | 59 ++- .../agents/io/api/scheduling/scheduler.py | 38 +- .../agents/io/telemetry/telemetry.py | 44 +- tests/integration/conftest.py | 16 + tests/integration/connection_source.py | 23 +- tests/integration/test_final_faults.py | 170 +++++++ tests/integration/test_named_connections.py | 89 +++- .../commands/test_validate_runtime_parity.py | 37 ++ .../test_startup_failure_policy.py | 82 +++- .../clients/io/test_nats_binding_mode.py | 4 +- .../agents/clients/io/test_nats_client.py | 207 ++++++++- .../io/test_nats_connection_readiness.py | 22 +- .../clients/io/test_nats_runtime_changes.py | 11 +- tests/unit/agents/config/test_config_init.py | 33 ++ .../api/actuators/health/test_health_cache.py | 5 +- .../actuators/health/test_readiness_policy.py | 13 + .../io/api/actuators/test_actuator_api.py | 25 ++ .../unit/agents/io/api/eventing/test_dapr.py | 21 + .../agents/io/telemetry/test_telemetry.py | 43 +- 38 files changed, 1696 insertions(+), 406 deletions(-) create mode 100644 tests/integration/test_final_faults.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 31bbb382..93a29bdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -173,6 +173,27 @@ Full migration path, including the one decision to get right before the first de unchanged code now reaches the collector, which can add series -- and cost -- to a metrics backend. A project that registered its own `MeterProvider` first keeps it: the SDK refuses a second one and the framework's is not installed. +18. **A broker fault no retry can fix fails the agent, critical or not, and can fail liveness.** A + durable that filters another subject, a stream the server refuses to create or widen, a grant the + account lacks, and on a named connection a refused login or deliver subject used to be retried for + ever (a named connection's missing grant every 60 s) while the agent consumed nothing -- and a + JetStream grant refused to the agent's own connection, found by the health poll before startup, + left the agent paused as degraded for good, with nothing logged. Now each is logged CRITICAL + with what to change and never retried. At startup the start fails, whatever + `critical_agents` says; after startup `GET /health/live` answers `503` naming the agent and the + reason (it was always `200`), so Kubernetes restarts the pod, and the root or a critical agent + also ends the process as before. A degraded agent whose fault may heal still never fails + liveness. A named connection in this state reads `failed`. New exception classes, all + subclasses of `DeterministicTransportError`: `DurableConflictError` (replaces + `JetStreamBindingError` for the clash), `StreamConflictError`, `JetStreamPermissionError`, + `TenancyError`; `JetStreamUnavailableError` is one too. A missing binding-mode stream is still + retried (Known issues). +19. **An orphaned agent takes the pod out, whatever `readiness_policy` says.** An agent latched down + -- its startup failed and recovery retries it, or its transport failed for good -- now gates + readiness under `"critical"` and `"any"` too: it consumes nothing for a reason that is not + transient. And an agent whose resume after a degradation keeps failing, or whose connection loop + gave up (`event_client_max_retries`), fails liveness until it consumes again, logged CRITICAL: it + reported healthy while paused, so readiness read UP while nothing was consumed. ### Added @@ -190,7 +211,8 @@ Full migration path, including the one decision to get right before the first de `ProcessingStatus.SKIPPED`; a REST caller gets `success = true` with the reason as message. - **Per-connection state and `nats_connections_readiness`.** Each agent with named connections gets a readiness entry `.nats_client:connections` listing every connection as `bound`, `connecting`, - `reconnecting`, `retrying` (with the last error, redacted) or `paused`, and any permission violation, + `reconnecting`, `retrying` (with the last error, redacted), `failed` (a tenancy fault no retry + fixes, see Breaking 18) or `paused`, and any permission violation, plus the gauge `blueprint.nats.connection.bound` and the counter `blueprint.nats.connection.permission_violations` (attributes `agent`, `connection`). The new agent-scope key decides whether the entry can fail: `"never"` (default), `"any"` (one bound) or `"all"` (every one @@ -368,6 +390,18 @@ Full migration path, including the one decision to get right before the first de ### Fixed +- **Under Dapr, a shared topic is warned about when `idempotency_enabled` is `"false"`.** The + startup check for a topic two agents declare read the raw value, and the string `"false"` an + environment variable can deliver counts as true, so an agent that does not deduplicate went + unmentioned. It is read like the handler chain reads it now. `asbs validate` applies the runtime's + own functions for this and six other startup rules instead of restating them. + +- **`app_environment` reads the environment that was loaded.** Written inside `[default]` it selects + nothing, yet `Config.get("app_environment")` answered its value: a process that loaded + `[development]` ran its production checks (`nats_url` required) -- or, the other way round, its + development fallbacks. It now answers the loaded environment, and startup logs a WARNING when the + settings say otherwise. + - **With deduplication on, an event cut off by `nats_handler_timeout` is no longer lost.** The run is cancelled and nak'd, but the dedup marker was released only for an `Exception`, and cancellation is not one. The redelivery found the marker, was skipped as a duplicate and @@ -431,7 +465,12 @@ Full migration path, including the one decision to get right before the first de - **In a group, `OTEL_SERVICE_NAME` no longer names every agent alike.** The agents keep their own name as `service.name`; the variable names the root's telemetry, as standalone. Startup logs a - WARNING naming the value. `OTEL_RESOURCE_ATTRIBUTES` is unchanged. + WARNING naming the value. A `service.name` in `OTEL_RESOURCE_ATTRIBUTES` without + `OTEL_SERVICE_NAME` now fails the start of a group, for the same reason; standalone it is used as + declared. +- **An agent's own `otel_service_name` reaches its telemetry.** `[] otel_service_name` was + resolved for the agent and then ignored: its resource always carried the agent's name. It is the + agent's `service.name` now. The root's `otel_service_name` still never applies to an agent. - **Grouped Dapr: each agent gets its own copy of a delivery, and the answer has no stray reason.** The fan-out handed one `CloudEvent` object to every agent declaring the topic, so a change one @@ -557,8 +596,9 @@ Full migration path, including the one decision to get right before the first de - **A named connection whose subscription the broker refuses is no longer reported as bound.** The broker refuses a subscription asynchronously, so `subscribe()` returned and the connection read as - bound and was never retried. A bind now waits for the broker's round trip and retries a refusal as a - permission violation. Measured: `retrying` with `permission_denied` (before: `bound`). + bound and was never retried. A bind now waits for the broker's round trip, and a refusal fails the + connection as a tenancy fault (Breaking 18). Measured when it was still retried: `retrying` with + `permission_denied` (before: `bound`). - **An operator's consumer with `idle_heartbeat` or `flow_control` works in binding mode.** Its status messages reached the handler, were terminated as matching no subject, and an unanswered flow control diff --git a/docs/plans/2026-10-16-pr96-review-fixes.md b/docs/plans/2026-10-16-pr96-review-fixes.md index f620e6a9..802124ae 100644 --- a/docs/plans/2026-10-16-pr96-review-fixes.md +++ b/docs/plans/2026-10-16-pr96-review-fixes.md @@ -1,8 +1,9 @@ # PR #96 review fixes -- verification and plan -**Status:** steps 1-21 implemented 2026-10-19 (not committed yet), each marked **Done** below with what ran -live; final run with containers recorded in the feature changelog. Open: D21 (N12) and the way forward -on D22 (N13); everything else in "Decisions" is settled. +**Status:** steps 1-21 implemented 2026-10-19 and pushed 2026-10-20, each marked **Done** below with +what ran live; final run with containers recorded in the feature changelog. Step 22 done 2026-10-20. +Open: the way forward on D22 (N13), N18, and D23 (b) (a missing binding-mode stream or consumer); +everything else in "Decisions" is settled. **Base:** `81f6bf2` (head of `feature/multi-agent-namespaces`, unchanged since the reviews). **Sources:** pajoma's review (2026-10-15, CHANGES_REQUESTED, 3 blockers), Develebook's review (2026-10-16, 12 must-fix / 27 should-fix / 9 nits, inline), solicho's leftovers (2026-09-14/16). @@ -94,14 +95,14 @@ already public. References to sibling repositories (`docs/specs/2026-08-24-...`, | N9 | Scheduler template docstring wrong; `asbs create service` misses imports (older) | C | yes | 14 | | N10 | "Created JetStream consumer" INFO formats `ack_wait` with `%.1f`; unset `nats_ack_wait` is `None`, so the line is lost as a logging error | C (live, found in step 2) | yes | 18 | | N11 | Startup against an unreachable broker did not return within 6 s (only nats-py's own "encountered error" was logged) | observed live in step 2, not analysed; check against the `max_reconnect_attempts=-1` connect | yes | 4 | -| N12 | An agent whose own subscription keeps failing reports ready: the failure degrades it, C4 pauses it, and a paused client reports healthy by design, so after one poll readiness is UP while `_retry_resume` keeps failing (backoff 5 s, 10 s, ...) and nothing is consumed | C (live, found in step 18; any persistent subscribe failure, not only S1) | open -- needs a decision on C4, see below | -- | +| N12 | An agent whose own subscription keeps failing reports ready: the failure degrades it, C4 pauses it, and a paused client reports healthy by design, so after one poll readiness is UP while `_retry_resume` keeps failing (backoff 5 s, 10 s, ...) and nothing is consumed | C (live, found in step 18; any persistent subscribe failure, not only S1) | **Fixed 2026-10-20** (22b, D21 decided with D23): liveness DOWN while the resume keeps failing; S1 itself is now final (22a) | 22 | | N13 | `DiskCacheService.claim` is not atomic across processes: diskcache-rs 0.4.10's `add` lets several processes on one directory win one key (297 of 300 rounds, 4 processes, no error); 0.4.9 refused a second process the directory | C (live, step 20) | docs corrected; fix open as D22 | -- | | N14 | M4's refusal check raced: nats-py 2.15 writes PING straight to the transport while the SUB still waits for the flusher, so the PONG could come back before the broker saw the SUB and the binding read as bound (`TestARefusedSubscriptionIsNotBound` failed 3 of 9 runs on the step-21 code, 1 of 2 on step 17, 0 of 2 on step 6) | C (live, final run) | **Fixed 2026-10-19**: two round trips in `_bind`; 8 of 8 runs green | -- | -| N15 | `app_environment` inside `[default]` makes `Config.get("app_environment")` answer the configured value while Dynaconf loads the default section, so a development check can read the wrong environment (found by the docs agent with a probe; the docs now say the key selects only at top level or through `DYNACONF_APP_ENVIRONMENT`) | P (probe, not re-checked) | open -- check and decide in step 22 | -- | -| N16 | `.otel_service_name` is resolved by `Config._resolve_service_name` but never reaches the resource: `TelemetryManager._configure_namespace` sets `service.name` to the namespace for every agent | C (code read by the docs agent) | open -- belongs with D23 (c) in step 22 | -- | +| N15 | `app_environment` inside `[default]` makes `Config.get("app_environment")` answer the configured value while Dynaconf loads the default section, so a development check can read the wrong environment (found by the docs agent with a probe; the docs now say the key selects only at top level or through `DYNACONF_APP_ENVIRONMENT`) | C (probe 2026-10-20: [development] loaded, `app_environment` read `production`) | **Fixed 2026-10-20** (22d): `Config.get("app_environment")` answers the loaded environment; a WARNING when the settings say otherwise | 22 | +| N16 | `.otel_service_name` is resolved by `Config._resolve_service_name` but never reaches the resource: `TelemetryManager._configure_namespace` sets `service.name` to the namespace for every agent | C (code read by the docs agent) | **Fixed 2026-10-20** (22c): the agent's view resolves the name the resource carries | 22 | | N17 | `handler_chain._warn_without_a_heartbeat` compared `nats_heartbeat_enabled is False`, so `"false"` from an environment variable did not warn | C (unit test failed before) | **Fixed 2026-10-19**: read with `parse_bool` | -- | | N18 | The generated handler's `on_startup` read `.get("input_event_type", )` -- `None` when the key is missing -- and compared it to `""`, so a handler without its event type started anyway (found by the validator agent). Making the check fire stops every fresh scaffold: `asbs setup`'s own handler has no `input_event_type` and does not use it (`can_handle_event` is a stub) -- found live on a scaffold, `ValueError` at startup | C (live, with control) | open -- the fix was withdrawn on 2026-10-20 (owner decision); what the generated handler does with the event type is decided later. `test_a_fresh_project_starts_the_way_its_container_does` keeps a scaffold startable | -- | -| N19 | The validator restates runtime rules that exist only as private methods: dedup policy and heartbeat/Dapr warnings (`HandlerChain`), the timezone check (`SchedulerBase`), the shared-topic grouping (`DaprEventing`), the `nats_url`/heartbeat/durable-count rules (`NatsClient`); pinned by tests, matched live word for word | C (code read) | open -- make them public and call them from the validator in step 22, which edits the same files | -- | +| N19 | The validator restates runtime rules that exist only as private methods: dedup policy and heartbeat/Dapr warnings (`HandlerChain`), the timezone check (`SchedulerBase`), the shared-topic grouping (`DaprEventing`), the `nats_url`/heartbeat/durable-count rules (`NatsClient`); pinned by tests, matched live word for word | C (code read) | **Fixed 2026-10-20** (22e): seven rules are public runtime functions the validator calls; two drifts found on the way -- the validator's heartbeat warning still compared `is False` (N17), and the runtime's Dapr shared-topic warning read `idempotency_enabled` raw, so `"false"` counted as on | 22 | | N20 | `test_design_rules.all_markdown()` walked the whole checkout with `rglob`, `.venv` included, and filtered afterwards -- about 0.6 s per test, 47 s for the module | C (measured) | **Fixed 2026-10-20**: directories pruned before they are entered; same 91 files, 14 s | -- | ### pajoma warnings/suggestions and solicho leftovers @@ -275,6 +276,46 @@ Must-fix and blockers first (steps 1-14), then hardening (15-20), then documenta (develop has them too, linking a file develop does not have), and develop's MIT classifier, which this branch had already dropped -- D20 lists the classifier as out. PR description and the reply to the version-bump comment are drafts, not posted. +22. **Startup and tenancy faults** (D23, D17, N12/D21, N15, N16, N19). After the review commits were + pushed (2026-10-20), one commit per part: + - **22a Deterministic faults fail early.** A `DeterministicTransportError` family -- JetStream + unavailable (exists), durable clash (S1), stream not creatable/updatable (the server answered), + JetStream permission refused, and the tenancy faults of a named connection (login refused, + deliver subject refused, binding-mode consumer filtering another subject) -- stops the retry + loop and goes to the fatal handler: CRITICAL with what failed, where and what to change; + liveness DOWN; the agent marked down; the root or a critical agent still ends the process as + before. At startup it fails the start whatever `critical_agents` says. Transient faults keep + retrying (D5). Deferred: a missing binding-mode stream/consumer. + - **22b Orphaned agents** (N12, D21 in principle): an agent that should consume and does not for + a non-transient reason makes the service unhealthy regardless of `readiness_policy`. + **Decided 2026-10-20 (owner):** a resume that keeps failing and a connection loop that gave up + take liveness DOWN until the agent consumes again; a latched agent (startup failure, a + non-critical agent's fatal transport fault) gates readiness under every policy, and startup + recovery keeps running. **Done 2026-10-20**; a resume that meets a fault no retry fixes is + reported fatal as well. Not run live: a resume that keeps failing while the agent's checks + pass (no broker-side setup produces it reliably); unit-tested, and the latch case runs through + a real lifespan. + **Done 2026-10-20** (22a, c, d, e; not committed): 22a as described -- not detectable, and so not + implemented, is a binding-mode consumer that filters another subject: with `manage_consumer` the + client rewrites it to the binding, without it the client sends no JetStream request (as for a + missing consumer, D23 (b)). Spec C1, C3 and 9.1 amended. 22c: the start fails on a `service.name` + only in `OTEL_RESOURCE_ATTRIBUTES` in a group; N16 by reading the agent's view. 22d: N15 fixed. + 22e: N19 fixed. Live in WSL (NATS, NATS accounts, Redis), each against the code before step 22 + (`fd1e3f5`) as control: durable clash -- before 8 attempts in 4 s, liveness 200, nothing CRITICAL; + now one, CRITICAL, liveness 503, SIGTERM for a critical agent; JetStream grant refused to the + agent's own connection -- before the agent started and stayed paused for good, liveness 200, + nothing logged (an orphaned agent, 22b); now the start fails with `JetStreamPermissionError`. + Found on the way: two agents of one process sharing a stream race to create it, and the loser's + "stream name already in use" (10058) was first classified as final -- it is a race, the stream is + re-read and widened (the full integration run had ended in pytest's own SIGTERM; a guard in the + integration conftest now fails such a test instead). Integration 70 of 71, the one pre-existing + failure. New integration tests: `test_final_faults.py` (clash, stream, grant) and the tenancy + faults in `test_named_connections.py` (refused login, refused deliver subject); D5's tests now + use an unreachable broker, a fault that may heal. + - **22c `service.name` in a group** (D17): only through `OTEL_RESOURCE_ATTRIBUTES`, without + `OTEL_SERVICE_NAME`, fails the start; N16 (`.otel_service_name` reaches the resource). + - **22d N15** checked and decided; **22e N19** -- the runtime rules the validator restates + become public and the validator calls them. --- @@ -309,6 +350,6 @@ Must-fix and blockers first (steps 1-14), then hardening (15-20), then documenta | D17 | W1: in a group, ignore `OTEL_SERVICE_NAME` for agents with a WARNING, refuse to start, or document? **Decided 2026-10-19: in a group every agent provider keeps `service.name` = agent name even when `OTEL_SERVICE_NAME` is set, so telemetry stays filterable per agent; the root provider still takes `OTEL_SERVICE_NAME`. One startup WARNING names the value and why it does not apply to the agents. `OTEL_RESOURCE_ATTRIBUTES` stays untouched. Docs: the exception to "declared keys are never replaced". Standalone unchanged.** | 17 | | D19 | W8: fold `[0.9.0]` into `[Unreleased]` and restore the `develop` version string, or keep as is? **Decided 2026-10-19: this PR follows its own `AGENTS.md` rule -- `[0.9.0] - 2026-09-14` (never released, only `v0.9.0a1..a15`) is folded into `[Unreleased]`, `pyproject.toml` goes back to develop's `0.8.2`; `publish.yml` sets the version from the tag anyway (L43/L66). Reply to SawwR's bump comment with the rule. Follow-up issue, not in this PR: derive the version from git tags with `setuptools-scm` so source installs report it too (drops the `sed` step); the stale `__version__ = "0.3.0"` fallback in `src/blueprint/__init__.py:8` goes with it.** | 21 | | D20 | Is the MIT licence choice approved by the responsible owner (pajoma F)? Not a code decision. **Decided 2026-10-19: no approval exists. The licence is deferred: this PR goes back to develop's licence state (`LICENSE` from `a9a8f3b` removed, `license`, `license-files` and the MIT classifier out of `pyproject.toml`). Open point for the `develop` -> `main` merge: licence approval by the responsible owner, then add it there. The PR description says so. Already published alphas (`v0.9.0a1..a15`) carry MIT and cannot be changed.** | 21 | -| D21 | N12: a paused client whose own resume keeps failing reports healthy, so readiness is UP while the agent consumes nothing. Options: (a) while paused, report unhealthy once a resume attempt has failed, and let `_retry_resume` keep running through a re-pause (today a pause cancels it, which would then deadlock); (b) leave readiness as it is and add a `blueprint.nats.resume_failures` counter plus the failure in the readiness payload; (c) accept and document. **Open -- owner decision.** Measured (step 18, root topic `orders-created` against a consumer filtering `created`, health interval 2 s): 200 at 0-2 s, 503 at 2.1 s (degraded, paused), 200 from 4.1 s on while paused, resume attempts failing at 5 s and 10 s backoff. | -- | +| D21 | N12: a paused client whose own resume keeps failing reports healthy, so readiness is UP while the agent consumes nothing. Options: (a) while paused, report unhealthy once a resume attempt has failed, and let `_retry_resume` keep running through a re-pause (today a pause cancels it, which would then deadlock); (b) leave readiness as it is and add a `blueprint.nats.resume_failures` counter plus the failure in the readiness payload; (c) accept and document. **Decided 2026-10-20 with D23 -- see 22b.** Measured (step 18, root topic `orders-created` against a consumer filtering `created`, health interval 2 s): 200 at 0-2 s, 503 at 2.1 s (degraded, paused), 200 from 4.1 s on while paused, resume attempts failing at 5 s and 10 s backoff. | -- | | D22 | N13: make `DiskCacheService.claim` atomic across processes on one host -- an OS file lock (`fcntl.flock` / `msvcrt.locking`, or the `filelock` package) around the `add` -- or keep the disk cache per-process for claims and warn at startup when dedup or the in-process tick claim runs on a disk cache with `app_workers > 1`? **Decided 2026-10-19: document only, for now** -- the docs say per-process (claim docstring, deployment guide, configuration keys, CHANGELOG Known issues); how to proceed beyond that is to be clarified. | -- | | D23 | Startup and tenancy faults (owner, 2026-10-19). **Principle: a critical problem or collision found at startup fails the start; a fault caused by a wrong or problematic tenancy is logged CRITICAL and the process exits -- at startup and at runtime, when a `ConnectionSource` change hands it over -- because an operator must notice it.** Critical means deterministic (a retry cannot fix it): durable clash (S1), stream not creatable/updatable (subject overlap), missing JetStream permissions, tenant login refused, tenant deliver subject refused, binding-mode consumer missing or filtering another subject. Transient faults (broker unreachable, connection lost, timeouts) keep retrying; D5 stays for those. Open before implementing: (a) do an agent's own faults respect `critical_agents` (spec sec. 9.1) or always exit; (b) is a missing binding-mode stream fatal or still transient (provisioning); (c) D17 -- refuse `service.name` in `OTEL_RESOURCE_ATTRIBUTES` in a group, and what happens to `OTEL_SERVICE_NAME`. Partly supersedes D21 (N12). **Added (owner, 2026-10-19): a constellation that leaves orphaned agents -- agents that should exist but consume nothing for a non-transient reason (startup latch, final subscription fault, a resume that keeps failing) -- makes the service at least unhealthy, possibly exits.** So D21 is decided in principle: a paused client whose resume keeps failing reports unhealthy. Open: whether "unhealthy" is readiness DOWN or liveness DOWN, and whether it overrides `readiness_policy = "critical"` for a non-critical agent. **Settled (owner, 2026-10-19):** (1) such critical faults set **liveness** DOWN, and each is logged well enough for an operator to act on (what failed, which agent/connection, why it is not transient, what to change); (2) a transient fault stays under `readiness_policy`, an orphaned agent counts regardless of the policy; (3) D17: in a group, a `service.name` declared only through `OTEL_RESOURCE_ATTRIBUTES` (no `OTEL_SERVICE_NAME`), which would name every agent alike, **fails the start**; `OTEL_SERVICE_NAME` alone or together with it stays as implemented (agents keep their names, WARNING). Still open: (a) an agent's own faults vs `critical_agents`, (b) a missing binding-mode stream. **Clarified (owner, 2026-10-19): M agents x N tenants; N = 0 (the source hands over no tenant) is a valid state -- nothing to bind, nothing fails (as implemented: "consumes on 0 named connection(s)").** (b) concerns N >= 1: a tenant handed over whose binding names a stream (or, with `manage_consumer = false`, a consumer) that does not exist. **(b) deferred (owner, 2026-10-19):** whether a missing binding-mode stream -- or, with `manage_consumer = false`, a missing consumer -- is fatal at once or after a grace period depends on whether the tenancy source hands over a tenant only once its stream is provisioned; to be clarified with the tenancy owner. Until then it stays as implemented: retried, visible in readiness only (`.nats_client:connections` reads `retrying`); with `manage_consumer = false` a missing consumer is not detected at all (the client sends no JetStream request). **(a) settled (owner, 2026-10-19): fail early.** A deterministic fault (durable clash, stream not creatable/updatable, missing JetStream permissions) is fatal in every agent, whatever `critical_agents` says: logged CRITICAL, startup fails or liveness goes DOWN. `critical_agents` and `readiness_policy` keep deciding only for faults that may be transient (startup recovery, health). | 22 | diff --git a/docs/specs/2026-08-28-multi-agent-grouping.md b/docs/specs/2026-08-28-multi-agent-grouping.md index 93df9539..fe6e57a9 100644 --- a/docs/specs/2026-08-28-multi-agent-grouping.md +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -9,6 +9,7 @@ | **Amended by** | `docs/plans/2026-09-10-builder-unification.md` -- decided 2026-09-10, folded into sec. 2, 4, 5.3, 8, 9, 10 and 11 below. | | **Amended by** | `docs/plans/2026-09-28-grouped-http-surface.md` -- decided 2026-09-28, folded into sec. 10 and 11.2 below. | | **Amended by** | PR #96 review, 2026-10-19 -- brought in line with the implementation: C1 (root/agent durable clash), C2 (resolved group, per-provider metric readers, declared OTel keys), C4 (pause instead of close), sec. 2 and 11 (standalone agents at the root), 4.1 and 9 (`AgentGroup.resolve` / `from_config` / `assemble`), 4.2 (handler order restored, not refused), 5.1 (further group-file refusals), 5.3 (config refusals; process-scope keys dropped with a WARNING), 6 (resolved group; history), 7.1 and 7.2 (history; `SKIPPED`; ``; `max_deliver` optional), 7.4 (dedup key), 7.5 (no default mode; claim atomic on Redis only; slot from the fire time; crontab rules; `scheduler_timezone`), 9.1 (no agent left), 10 (instances refused by `build(config)`), 11.1 (`event_loop_debug`, watchdog), 12 (claim criteria scoped to Redis). Each change is marked in place. | +| **Amended by** | PR #96 review step 22, 2026-10-20 -- owner decision D23 in `docs/plans/2026-10-16-pr96-review-fixes.md`: C1 (the root/agent clash is not retried), C3 (a transport fault no retry can fix takes liveness DOWN), 9.1 (such a fault fails the start whatever `critical` says). Each change is marked in place. | | **Deferred out of** | `docs/plans/2026-09-10-config-validation-unification.md` -- configuration validation is not part of this feature. | Requirement keywords (**MUST**, **MUST NOT**, **SHOULD**, **MAY**) are used in the RFC 2119 sense. @@ -84,9 +85,10 @@ other deployment identifier. `f"{topic}-durable"` has no namespace segment, so root topic `orders-created` and agent `orders` on topic `created` still derive one name (`orders-created-durable`). That clash **MUST** fail rather than share a consumer: the client refuses to bind a durable whose filter - is another subject (`JetStreamBindingError`), naming the consumer and the fix. *(Amended + is another subject (`DurableConflictError`), naming the consumer and the fix. *(Amended 2026-10-19, PR #96 review: the root/agent clash is not prevented by the alphabet, and is - refused at bind.)* + refused at bind.)* It is not retried: it is a fault no retry can fix (C3, sec. 9.1). + *(Amended 2026-10-20, D23.)* - `<` and `>` keep the sec. 6 connection-name placeholders unforgeable. `>` is a NATS wildcard and illegal in a consumer name in any case. @@ -139,22 +141,41 @@ shutdown as implemented.)* When the namespace is `""`, the provider **MUST** use `otel_service_name` from config, reproducing current behaviour exactly (`io/telemetry/telemetry.py:39-41`). -**Keys the deployment declares.** *(Amended 2026-10-19, PR #96 review: describes the current -behaviour; decision D23 (c) in `docs/plans/2026-10-16-pr96-review-fixes.md` is open and may change -it.)* A key set in `OTEL_RESOURCE_ATTRIBUTES` or by `OTEL_SERVICE_NAME` is used as declared and -replaces the framework's value, on every provider. The one exception is `OTEL_SERVICE_NAME` in a -group: every agent's provider keeps `service.name = `, the root's provider takes the -declared name, and one startup WARNING names the value and says it applies to the root only. A -`service.name` given only in `OTEL_RESOURCE_ATTRIBUTES` is not excepted, so it currently names -every agent of a group alike. +**Keys the deployment declares.** *(Amended 2026-10-19, PR #96 review; and 2026-10-20, decision +D23 (c) in `docs/plans/2026-10-16-pr96-review-fixes.md`.)* A key set in `OTEL_RESOURCE_ATTRIBUTES` or +by `OTEL_SERVICE_NAME` is used as declared and replaces the framework's value, on every provider. +The one exception is `OTEL_SERVICE_NAME` in a group: every agent's provider keeps its own +`service.name`, the root's provider takes the declared name, and one startup WARNING names the value +and says it applies to the root only. A `service.name` given only in `OTEL_RESOURCE_ATTRIBUTES` -- +no `OTEL_SERVICE_NAME` -- **MUST** fail the start of a group, naming both ways out: taken as declared +it would name every agent alike. Standalone it is used as declared. + +An agent's own `service.name` is its name, or `.otel_service_name` when the agent sets one for +itself; the root's `otel_service_name` never applies to an agent. *(Amended 2026-10-20, N16: the +agent's own setting was resolved and never used.)* ### C3 -- Liveness is never namespace-dependent The liveness probe **MUST** reflect only process and event-loop health. A degraded namespace **MUST NOT** cause a liveness failure, because that restarts every agent in the group. -Already satisfied: `io/api/actuators/actuator_api.py:126-143` returns `UP` unconditionally. This -invariant exists to stop the behaviour from being changed, not to change it. +**One exception: a transport fault no retry can fix.** The broker answered, and the answer is final +-- a durable that filters another subject (C1), a stream the server refuses to create or widen, a +grant the account lacks, a tenant's login or deliver subject refused. Such a fault **MUST** take +liveness DOWN, in whichever agent it happens and whatever its `critical` flag, and **MUST** be logged +CRITICAL with what failed, where, why it is final and what to change; `/health/live` answers 503 +naming each such agent and its reason. The agent consumes nothing until someone changes the broker +or the deployment, so the pod is short a consumer for good, and a restart is how the orchestrator +makes an operator look. Restarting the group's other agents is the accepted price. A fault that may +heal -- the broker unreachable, a connection lost, a timeout, a stream not yet provisioned -- stays +a degraded namespace under this invariant and `readiness_policy`. *(Amended 2026-10-20, owner +decision D23: liveness was `UP` unconditionally.)* + +**An orphaned agent also takes liveness DOWN**: one that should consume and does not, for a reason +that does not pass by itself -- its resume after a degradation keeps failing (the client is paused +and so reports healthy), or its connection loop gave up (`event_client_max_retries`). Unlike the +fault above it may still clear, so liveness comes back when the agent consumes again. *(Amended +2026-10-20, N12 / D21, decided with D23.)* Readiness **MUST** follow `readiness_policy`: @@ -164,6 +185,11 @@ Readiness **MUST** follow `readiness_policy`: | `"critical"` | Only namespaces marked `critical` gate readiness. | | `"any"` | Ready while at least one namespace is up. | +Whatever the policy, a namespace latched down (sec. 9.1, and a non-critical agent whose transport +failed for good) **MUST** gate readiness: it consumes nothing for a reason that is not transient, +and a policy that ignores it would report a pod short a consumer as ready. *(Amended 2026-10-20, +N12 / D21: the policy decided for latched namespaces too.)* + A degraded namespace **MUST** be reported as `blueprint_namespace_up{agent="..."} = 0` and an ERROR-level event regardless of policy. Alerting is driven by that signal, not by the probe. C7 generalises this to every path that stops a namespace serving, not only the ones readiness reads. @@ -957,10 +983,16 @@ There is no partial build: one process, one `build()`. The `critical` flag is th | Module import raises | exit non-zero | log ERROR, skip | | `on_startup` raises | exit non-zero | mark namespace down, pause consumers (C4), continue; retry (below) | | No agent left after the skips above | exit non-zero | exit non-zero | +| A transport fault no retry can fix (C3) | exit non-zero | exit non-zero | *(Amended 2026-10-19, PR #96 review: last row added -- a pod with no agent passes its probes while it consumes nothing, which is the failure criticality exists to prevent.)* +*(Amended 2026-10-20, D23: last row added. `critical` decides only for failures that may heal, +which is what the retry below is for; a fault no retry can fix would latch the agent down for good. +Found after startup, such a fault is logged CRITICAL and takes liveness DOWN (C3); the root or a +critical agent also ends the process, as for any fatal transport error.)* + Exit **MUST** happen before the port is bound, so Kubernetes crash-loops with a readable message rather than reporting a healthy pod that is silently short-staffed. @@ -969,7 +1001,8 @@ Every `startup_retry_interval_seconds` (default 30, process scope) the framework again on that namespace's failed components, in their original start order, stopping at the first that raises again. When all of them have started, the mark is released and the namespace's health checks decide from then on. While it is marked, the readiness payload **MUST** report the namespace -`DOWN` with the failure as its reason, whatever its health checks say -- the mark exists because a +`DOWN` with the failure as its reason, whatever its health checks say, and the namespace gates +readiness under every policy (C3) -- the mark exists because a component that failed to start may still pass its check. Terminating instead is not a recovery: a deterministic failure fails the same way after a restart, and the restart takes every healthy namespace in the process down with it. `on_startup` **MUST** therefore be safe to call again after diff --git a/src/blueprint/agent_generator/cli/commands/validate.py b/src/blueprint/agent_generator/cli/commands/validate.py index feb0b417..bea3c1e2 100644 --- a/src/blueprint/agent_generator/cli/commands/validate.py +++ b/src/blueprint/agent_generator/cli/commands/validate.py @@ -15,12 +15,17 @@ from dataclasses import dataclass from pathlib import Path from typing import Any -from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from dynaconf import Dynaconf -from blueprint.agents.clients.io.io_client_base import TOPIC_TRANSPORTS, validate_subject_segment -from blueprint.agents.clients.io.nats_client import CONNECTIONS_READINESS_MODES +from blueprint.agents.clients.io.io_client_base import TOPIC_TRANSPORTS +from blueprint.agents.clients.io.nats_client import ( + CONNECTIONS_READINESS_MODES, + resolve_heartbeat_enabled, + resolve_nats_url, + resolve_root_queue_group, + validate_durable_name, +) from blueprint.agents.clients.io.nats_run_pool import RunLimit from blueprint.agents.config.config import ( AGENT_REFUSED_KEYS, @@ -31,12 +36,14 @@ environment_section_names, layer_settings_document, ) +from blueprint.agents.handler.handler_chain import dedup_redelivery_warning, resolve_idempotency_policy from blueprint.agents.io.api.scheduling.scheduler import ( SCHEDULER_MODE_EVENT, SCHEDULER_MODE_IN_PROCESS, SCHEDULER_MODES, delivers_ticks, normalise_scheduler_mode, + resolve_scheduler_timezone, validate_crontab, ) from blueprint.agents.utils import parse_bool @@ -691,16 +698,11 @@ def scheduler_findings(agent_dir: Path, *, view: SettingsView, settings: Process ) return issues, [], notices - # In process: the timer reads scheduler_timezone, as SchedulerBase reads it at startup. - timezone = str(view.get("scheduler_timezone", "") or "").strip() - if timezone: - try: - ZoneInfo(timezone) - except (ZoneInfoNotFoundError, ValueError): - issues.append( - f"{named}'scheduler_timezone' is {timezone!r}, which is not an IANA timezone name (such as " - "'Europe/Berlin' or 'UTC'). Every in-process scheduler fails to start" - ) + # In process: the timer reads scheduler_timezone, with the runtime's own rule. + try: + resolve_scheduler_timezone(view.get("scheduler_timezone", "")) + except ValueError as exc: + issues.append(f"{named}{exc} Every in-process scheduler fails to start") if not main_declares_a_cache(agent_dir): notices.append( "\n".join( @@ -736,57 +738,23 @@ def _disk_claim_notice(view: SettingsView, named: str, what: str) -> str | None: def dedup_findings(agent_dir: Path, *, view: SettingsView, settings: ProcessSettings, agent: str = "") -> Findings: """The dedup policy a handler chain resolves at startup, and the warnings it logs. - The rules of ``HandlerChain._resolve_idempotency_policy`` and ``_warn_without_a_heartbeat``, - in their own words. Neither is public, and both live in the runtime, so they are restated here - and pinned by tests; the boolean is read with the runtime's ``parse_bool``. + The runtime's own ``resolve_idempotency_policy`` and ``dedup_redelivery_warning`` (N19); a + cache counts when ``src/main.py`` declares one. The policy stops at its first problem, as + startup does. """ if not consumes_events(agent_dir, view): return [], [], [] named = f"Agent '{agent}': " if agent else "" try: - enabled = parse_bool(view.get("idempotency_enabled", False), "idempotency_enabled") + policy = resolve_idempotency_policy(view.get, has_cache=main_declares_a_cache(agent_dir)) except ValueError as exc: - return [f"{named}{exc}"], [], [] - if not enabled: + return [f"{named}{exc} Startup fails"], [], [] + if not policy.enabled: return [], [], [] issues: list[str] = [] - raw_ttl = view.get("idempotency_ttl") - if raw_ttl is None: - issues.append( - f"{named}'idempotency_enabled' is true but 'idempotency_ttl' is not set. It is the number of seconds a " - "processed event is remembered, and it must outlast the broker's redelivery window ('nats_ack_wait' * " - "'nats_max_deliver' on JetStream). Startup fails" - ) - else: - try: - ttl = int(raw_ttl) - except (TypeError, ValueError): - issues.append(f"{named}Config key 'idempotency_ttl' must be an integer number of seconds, got {raw_ttl!r}.") - else: - if ttl <= 0: - issues.append(f"{named}'idempotency_ttl' must be greater than 0, got {ttl}. It is the dedup window, in seconds.") - if not main_declares_a_cache(agent_dir): - issues.append( - f"{named}'idempotency_enabled' is true but src/main.py declares no cache, so there is nowhere to record " - "the events already processed. Add '.with_cache()' to the AppBuilder chain. Startup fails" - ) - - warnings: list[str] = [] - bus = _bus(settings) - label = agent or "" - if bus == "nats" and view.get("nats_heartbeat_enabled", True) is False: - warnings.append( - f"Agent '{label}' deduplicates events with 'nats_heartbeat_enabled = false': a run that outlasts ack_wait " - "is redelivered while it runs, the redelivery is skipped as a duplicate and acknowledged, and if the first " - "run then fails the event is lost. Keep the heartbeat on, or keep runs well under ack_wait." - ) - elif bus == "dapr": - warnings.append( - f"Agent '{label}' deduplicates events under Dapr, which has no heartbeat: a run that outlasts the sidecar's " - "app-call timeout is delivered again while it runs, that delivery is skipped as a duplicate, and if the " - "first run then fails the event is lost. Keep runs well under that timeout." - ) + warning = dedup_redelivery_warning(view.get, agent or "") + warnings = [warning] if warning else [] notices: list[str] = [] if main_declares_a_cache(agent_dir): @@ -827,36 +795,27 @@ def transport_findings(agent_dir: Path, *, view: SettingsView, settings: Process return [], warnings, [] issues: list[str] = [] - environment = str(view.get("app_environment", "development")) - if not str(view.get("nats_url", "") or "").strip() and environment.lower() != "development": - issues.append( - f"{named}'event_bus' is 'nats' but 'nats_url' is not set (app_environment is {environment!r}). Outside " - "development there is no default: localhost is rarely right in a container, and a client pointed at it " - f"retries forever while the pod looks healthy. Set 'nats_url' in the settings or as " - f"{settings.override_variable_prefix}NATS_URL." + try: + resolve_nats_url( + view.get("nats_url", ""), + view.get("app_environment", "development"), + override_variable=f"{settings.override_variable_prefix}NATS_URL", ) - heartbeat = view.get("nats_heartbeat_enabled", True) - if not isinstance(heartbeat, bool): - issues.append(f"{named}'nats_heartbeat_enabled' must be true or false, got {heartbeat!r}.") + except ValueError as exc: + issues.append(f"{named}{exc}") + try: + resolve_heartbeat_enabled(view.get("nats_heartbeat_enabled", True)) + except ValueError as exc: + issues.append(f"{named}{exc}") if not consumes: return issues, warnings, [] if not agent: # A namespaced client's queue group is its namespace; only the root reads these keys. - for key in ("nats_queue_group", "app_name"): - name = str(view.get(key, "") or "").strip() - if not name: - continue - try: - validate_subject_segment(name, source=f"The queue group (from '{key}')", subject=f"{name}.dead-letter") - except ValueError as exc: - issues.append(str(exc)) - break - else: - issues.append( - "NATS subscriptions require a queue group: set 'nats_queue_group' or 'app_name'. Without one every " - "replica processes every message." - ) + try: + resolve_root_queue_group(view.get) + except ValueError as exc: + issues.append(str(exc)) durable = str(view.get("nats_durable_name", "") or "").strip() if durable and view.get("nats_use_jetstream", False) and not view.get("nats_connection_source"): @@ -865,12 +824,10 @@ def transport_findings(agent_dir: Path, *, view: SettingsView, settings: Process if topics is not None: declared = set(topics) | ({str(topic) for topic in subscriptions if topic} if isinstance(subscriptions, list) else set()) count = len(declared) + (len(scheduler_modules(agent_dir)) if _mode(view) == SCHEDULER_MODE_EVENT else 0) - if count > 1: - issues.append( - f"{named}'nats_durable_name' is set to '{durable}' but {count} topics are subscribed. A JetStream " - "durable filters one subject, so one name cannot serve them all. Remove the key to derive a " - "durable per topic." - ) + try: + validate_durable_name(durable, count) + except ValueError as exc: + issues.append(f"{named}{exc}") return issues, warnings, [] diff --git a/src/blueprint/agent_generator/cli/commands/validate_group.py b/src/blueprint/agent_generator/cli/commands/validate_group.py index 54f9720c..8db12502 100644 --- a/src/blueprint/agent_generator/cli/commands/validate_group.py +++ b/src/blueprint/agent_generator/cli/commands/validate_group.py @@ -35,12 +35,13 @@ from blueprint.agents.group_config import ( AGENTS_ENV, CRITICAL_AGENTS_ENV, - DEFAULT_GROUP_CONFIG, GROUP_CONFIG_ENV, GROUP_ENV, GroupConfig, GroupConfigError, + group_file_path, ) +from blueprint.agents.io.api.eventing.dapr import shared_topic_warnings from blueprint.agents.layout import check_agent_layout from ..utils.cancellation_check import swallowed_cancellation_warning, swallowed_cancellations @@ -445,22 +446,9 @@ def _shared_topic_warnings(settings: ProcessSettings, checked: list[_CheckedAgen """ if str(settings.root_view().get("event_bus", "") or "").strip().lower() != "dapr": return [] - sharing: dict[str, list[_CheckedAgent]] = {} - for agent in checked: - for topic in literal_topics(agent.root) or []: - sharing.setdefault(topic, []).append(agent) - warnings = [] - for topic, agents in sharing.items(): - if len(agents) < 2: - continue - repeating = [agent.name for agent in agents if not agent.view.get("idempotency_enabled", False)] - if repeating: - warnings.append( - f"Topic '{topic}' is declared by agents {', '.join(agent.name for agent in agents)}, and Dapr delivers " - f"it once for all of them: a retry asked for by one redelivers it to every one, and {', '.join(repeating)} " - "run it again because 'idempotency_enabled' is off." - ) - return warnings + views = {agent.name: agent.view for agent in checked} + topics = {agent.name: literal_topics(agent.root) or [] for agent in checked} + return shared_topic_warnings(topics, lambda name: views[name].get("idempotency_enabled", False)) class _Collected(logging.Handler): @@ -491,9 +479,7 @@ def group_findings(image_root: Path, agent_map: Path, *, group_config: str | Non group_name: ``--group-name``, which wins over ``BLUEPRINT_GROUP``. """ configured = (group_config or os.environ.get(GROUP_CONFIG_ENV, "") or "").strip() - group_file = Path(configured) if configured else image_root / DEFAULT_GROUP_CONFIG - if not group_file.is_absolute(): - group_file = image_root / group_file + group_file = group_file_path({GROUP_CONFIG_ENV: configured}, image_root) environ = {AGENT_MAP_ENV: str(agent_map), GROUP_CONFIG_ENV: str(group_file)} for variable in (GROUP_ENV, AGENTS_ENV, CRITICAL_AGENTS_ENV): diff --git a/src/blueprint/agent_generator/docs/concepts/event-processing.md b/src/blueprint/agent_generator/docs/concepts/event-processing.md index 9e3fa795..102dcab3 100644 --- a/src/blueprint/agent_generator/docs/concepts/event-processing.md +++ b/src/blueprint/agent_generator/docs/concepts/event-processing.md @@ -343,10 +343,27 @@ consumer whose deliver group, `ack_wait`, `max_ack_pending` or `max_deliver` dif configuration is kept: the client logs a WARNING naming the differences and consumes with the values the broker already has. Apply new values by deleting the consumer during a maintenance window. A consumer of that durable name whose filter is **another subject** is not bound at all, -because it belongs to another subscription: the client raises `JetStreamBindingError` into the -connection's retry loop and keeps retrying. A root topic and an agent's topic can derive one -durable name (root `orders-created`, agent `orders` on `created`); rename one of the topics, or -delete the consumer if it is stale. +because it belongs to another subscription: the client raises `DurableConflictError` and does +not retry it -- the consumer keeps its filter until someone changes it. It is logged CRITICAL and +fails the start, or after startup takes liveness DOWN (see *Faults no retry can fix* below). A root +topic and an agent's topic can derive one durable name (root `orders-created`, agent `orders` on +`created`); rename one of the topics, or delete the consumer if it is stale. + +## Faults no retry can fix + +Most broker faults heal: the broker comes back, the connection is restored, a timeout passes. Those +are retried for as long as it takes (below). Some do not, because the broker answered and its answer +is final: a durable that filters another subject, a stream the server refuses to create or widen, a grant the account lacks, a tenant's login or deliver subject refused. Retrying would only log the same answer forever while the agent consumes nothing. +So the client stops at once and the fault is handled the same way in every agent, critical or not: + +- logged **CRITICAL**, naming the agent, the consumer, stream or connection, why it is final and + what to change; +- **at startup** the start fails, whatever `critical_agents` says; +- **after startup** `/health/live` answers `503` naming the agent, so the orchestrator restarts the + pod, the agent is marked down, and the root or a critical agent also ends the process. + +A binding-mode stream that does not exist yet is not one of them: provisioning may create it later, +so it is retried and shows as `retrying` in readiness. ## Broker Startup Resilience diff --git a/src/blueprint/agent_generator/docs/concepts/observability.md b/src/blueprint/agent_generator/docs/concepts/observability.md index 6fdd89b7..68729dcf 100644 --- a/src/blueprint/agent_generator/docs/concepts/observability.md +++ b/src/blueprint/agent_generator/docs/concepts/observability.md @@ -42,7 +42,7 @@ its own resource: | Attribute | Value | |---|---| -| `service.name` | The agent's own name. `otel_service_name` for the root namespace. | +| `service.name` | The agent's own name, or `.otel_service_name` when the agent sets one for itself. `otel_service_name` for the root namespace. | | `deployment.group` | The group the process resolved -- `BLUEPRINT_GROUP`, or the one group a mounted group file declares. Absent for a standalone agent and for a group nothing named (`BLUEPRINT_AGENTS` alone). Set by the framework; no supported API exposes it to an agent (C6). | | `service.instance.id` | `POD_NAME`, else `HOSTNAME`, else the host name. When none can be told, the framework sets nothing and the OpenTelemetry SDK's own default applies. | @@ -51,8 +51,9 @@ its own resource: attributes the deployment left out, and never replaces a declared one. **One exception:** in a group, `OTEL_SERVICE_NAME` names the root's telemetry only, and every agent keeps its own name as `service.name` -- one name for all of them would make their telemetry impossible to tell apart. -Startup logs a WARNING naming the value. A `service.name` in `OTEL_RESOURCE_ATTRIBUTES` is left as -declared, and gives every agent that name -- the deployment's choice, not the framework's. +Startup logs a WARNING naming the value. A `service.name` in `OTEL_RESOURCE_ATTRIBUTES` without +`OTEL_SERVICE_NAME` fails the start of a group: taken as declared it would give every agent that +name. Remove it there, or set `OTEL_SERVICE_NAME` instead. Standalone it is used as declared. So an agent called `orders` reports `service.name = "orders"` whether it runs alone or beside nineteen others, and a dashboard keyed on it cannot tell which. A single-agent application keeps @@ -149,14 +150,28 @@ the only attribution available is what was emitted *before* the process died. | Endpoint | Answers | |---|---| -| `GET /health/live` | `200` while the process is running. Never namespace-dependent (C3). | +| `GET /health/live` | `200` while the process is running; `503` once an agent hit a transport fault no retry can fix, naming each such agent and why (C3). | | `GET /health/ready` | `200` when the pod should receive traffic, `503` otherwise. Answered from the last poll's result at once, also while a poll is still waiting on a slow check. | | `GET /info`, `/status/env`, `/status/llm`, `/status/build` | Service, configuration, AI-provider and build metadata. | -**Liveness is never namespace-dependent, and that is a rule rather than an accident.** A failing +**A degraded agent never fails liveness, and that is a rule rather than an accident.** A failing liveness probe restarts the pod, and in a group that restarts every agent in it -- reintroducing exactly the blast radius the grouping was paid to remove. So liveness reflects the process and the -event loop, and nothing else. +event loop. + +**The one exception is a transport fault no retry can fix**: a durable that filters another subject, a stream the server refuses to create or widen, a grant the account lacks, a tenant's login or deliver subject refused. The broker answered and the +answer is final, so the agent consumes nothing until someone changes the broker or the deployment. +Such a fault is logged CRITICAL -- what failed, where, why it is final, what to change -- in any +agent, critical or not, and `/health/live` answers `503` with `{"status": "DOWN", "agents": {...}}` +naming each such agent and its reason. The restart is how the orchestrator makes someone look. At +startup the same fault fails the start, whatever `critical_agents` says. A fault that may heal (the +broker unreachable, a lost connection, a timeout, a stream not yet provisioned) is retried and shows +in readiness only. + +**An orphaned agent fails liveness too, until it consumes again**: its resume after a degradation +keeps failing (a paused client reports healthy, so readiness alone would read UP), or its +connection loop gave up after `event_client_max_retries`. It is logged CRITICAL once, and when it +consumes again liveness comes back and a WARNING says so. ### Readiness is a policy @@ -172,7 +187,7 @@ readiness_policy = "critical" # "all" (default) | "critical" | "any" | `any` | Ready while at least one agent is up. | The root namespace gates readiness under every policy: it holds the shared infrastructure, so its -failure is not a partial one. In a single-agent application the root is the whole application, and +failure is not a partial one. An agent latched down -- its startup failed and recovery retries it, or its transport failed for good -- gates readiness under every policy, critical or not: it consumes nothing for a reason that is not transient. In a single-agent application the root is the whole application, and all three policies therefore agree -- which is what makes the key safe to set in a settings file that standalone projects also read. @@ -262,13 +277,14 @@ framework's, with a WARNING at startup -- the way to override a built-in check. With a `nats_connection_source`, each agent's client gets one more entry, `.nats_client:connections`. Its message lists every named connection and how it stands -- -`bound`, `connecting`, `reconnecting`, `retrying` (with the last error, credentials redacted) or -`paused` -- and whether the broker reported a permission violation: +`bound`, `connecting`, `reconnecting`, `retrying` (with the last error, credentials redacted), +`failed` (a tenancy fault no retry fixes: the login or a grant refused; also logged CRITICAL and +failing liveness, above) or `paused` -- and whether the broker reported a permission violation: ```json "orders.nats_client:connections": { "status": "unhealthy", - "message": "1/2 named connection(s) bound, readiness 'all': A=bound, B=retrying (Error: nats: 'Authorization Violation')" + "message": "1/2 named connection(s) bound, readiness 'all': A=bound, B=retrying (OSError: connection refused)" } ``` diff --git a/src/blueprint/agent_generator/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md index f24611e8..342494af 100644 --- a/src/blueprint/agent_generator/docs/guides/deployment.md +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -541,12 +541,17 @@ Two endpoints, and they answer different questions: | Endpoint | Question | Never depends on | |---|---|---| -| `GET /health/live` | Is this process running? | any agent's state | +| `GET /health/live` | Is this process running, and can every agent still consume? | a degraded agent | | `GET /health/ready` | Should this pod receive traffic? | -- | -**Liveness is never agent-dependent, deliberately.** If one degraded agent failed the pod's liveness -probe, Kubernetes would restart every agent in the group, reintroducing exactly the blast radius -grouping was paid to remove. +**A degraded agent never fails liveness, deliberately.** If one did, Kubernetes would restart every +agent in the group, reintroducing exactly the blast radius grouping was paid to remove. + +**A transport fault no retry can fix does**: a durable that filters another subject, a stream the server refuses to create or widen, a grant the account lacks, a tenant's login or deliver subject refused. It is logged CRITICAL with what to change, +in any agent, and `/health/live` answers `503` naming the agent and the reason, so the pod is +restarted and the cause is in its events and logs. Fix the broker or the deployment; a restart alone +meets the same fault again. At startup the same fault fails the start, whatever `critical_agents` +says. Also served, and useful when debugging rather than as probes: `GET /info`, `/status/env`, `/status/llm`, `/status/build`. There is no `/health/detailed`. `/status/env` masks every key that diff --git a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md index 3804b218..a07053ee 100644 --- a/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md @@ -466,9 +466,11 @@ the class that imposes it, and the single-agent case is not punished for the gro **Readiness.** `readiness_policy` decides how a degraded agent affects the pod: `all` (the default -- any degraded agent makes the pod not ready), `critical` (only agents flagged critical in the -group gate it) or `any` (ready while at least one agent is up). Liveness is never agent-dependent: -if one degraded agent failed the pod's liveness probe, Kubernetes would restart every agent in the -group, reintroducing exactly the blast radius grouping was paid to remove. +group gate it) or `any` (ready while at least one agent is up). An agent latched down -- its startup failed and recovery retries it, or its transport failed for good -- gates readiness under every policy, critical or not: it consumes nothing for a reason that is not transient. A degraded agent never fails +liveness: if it did, Kubernetes would restart every agent in the group, reintroducing exactly the +blast radius grouping was paid to remove. A transport fault no retry can fix -- a durable clash, a +stream or grant the broker refuses, a tenant's login refused -- does, in any agent, critical or not: +it is logged CRITICAL with what to change, and the agent would consume nothing until someone does. **Attribution.** Grouping removes the pod restart that used to serve as the alert, so the alert is emitted deliberately instead. Every path that stops an agent serving emits an ERROR-level event diff --git a/src/blueprint/agent_generator/docs/guides/troubleshooting.md b/src/blueprint/agent_generator/docs/guides/troubleshooting.md index e701a9ab..c7f8e865 100644 --- a/src/blueprint/agent_generator/docs/guides/troubleshooting.md +++ b/src/blueprint/agent_generator/docs/guides/troubleshooting.md @@ -218,21 +218,36 @@ enabled for the account the connection authenticates as. **Solution:** Enable JetStream for that server and account, or set `nats_use_jetstream = false` if the agent is meant to run on Core NATS. The framework does not fall back on its own. -### `JetStreamBindingError`: a consumer that `belongs to another subscription` +### `DurableConflictError`: a consumer that `belongs to another subscription` -**Symptom:** One topic of an agent never receives events, and the log repeats: +**Symptom:** One agent never starts, or `/health/live` answers `503` naming it, and the log has a +CRITICAL line: ``` -JetStreamBindingError: JetStream consumer 'orders-created-durable' on stream ... filters 'orders-created', not 'created', so it belongs to another subscription and is not bound. ... +DurableConflictError: Agent 'orders': JetStream consumer 'orders-created-durable' on stream ... filters 'orders-created', not 'created', so it belongs to another subscription and is not bound. ... Not retried: ... ``` **Cause:** A durable of that name already exists on the stream for another subject. A root topic and an agent's topic can derive one durable name -- root topic `orders-created` and agent `orders` on topic `created` both give `orders-created-durable`. The framework never rebinds or rewrites a -consumer that filters another subject, and keeps retrying the binding. +consumer that filters another subject, and does not retry: the consumer keeps its filter until +someone changes it, so the start fails (in every agent, critical or not), or after startup liveness +goes DOWN. **Solution:** Rename one of the two topics, or delete the consumer if it is stale. +### Other faults no retry can fix + +**Symptom:** As above -- CRITICAL in the log, the start fails or `/health/live` answers `503` -- +with `StreamConflictError`, `JetStreamPermissionError` or `TenancyError`. + +**Cause and solution:** the message says which and what to change. `StreamConflictError`: the server +refused to create or widen the agent's stream, usually because another stream already captures one +of its subjects -- give the agent its own subjects or `nats_stream_name`. `JetStreamPermissionError`: +the account lacks a grant the agent needs to consume (the `$JS.API` requests, the deliver subjects) -- +grant it. `TenancyError`: a named connection's login or deliver subject was refused by its broker -- +correct the tenant's credentials or binding, or the account on the broker. + ### Topic Mapping Mismatches **Symptom:** Events are published but handlers never receive them. diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index b312ad94..842b9aef 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -14,7 +14,7 @@ Top-level application settings. |-----|------|---------|-------------| | `app_name` | `str` | `"agent_blueprint"` | Application name. Used in logging, health checks, and OpenTelemetry service identification. | | `app_port` | `int` | `8000` | HTTP port the application listens on. | -| `app_environment` | `str` | `"development"` | Deployment environment identifier (e.g., `"development"`, `"staging"`, `"production"`), which also selects the settings section that is layered over `[default]`. Set it with `DYNACONF_APP_ENVIRONMENT` or as a top-level key of the settings file, above every section: inside `[default]` it selects nothing. `DYNACONF_ENVIRONMENT` is not read. `"development"` enables development fallbacks such as the localhost default for `nats_url`, and the process logs a WARNING at startup that it is not suitable for production. Being the default, a deployment that sets nothing runs in development mode: set it to anything else to deploy. | +| `app_environment` | `str` | `"development"` | Deployment environment identifier (e.g., `"development"`, `"staging"`, `"production"`), which also selects the settings section that is layered over `[default]`. Set it with `DYNACONF_APP_ENVIRONMENT` or as a top-level key of the settings file, above every section: inside `[default]` it selects nothing, and a startup WARNING says so. Read through `Config`, the key always answers the environment that was loaded. `DYNACONF_ENVIRONMENT` is not read. `"development"` enables development fallbacks such as the localhost default for `nats_url`, and the process logs a WARNING at startup that it is not suitable for production. Being the default, a deployment that sets nothing runs in development mode: set it to anything else to deploy. | | `log_level` | `str` | `"INFO"` | Root log level. One of `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`. | | `log_format` | `str` | `"text"` | Log output format. `"text"` for human-readable, `"json"` for structured JSON logging. | | `startup_retry_interval_seconds` | `float` | `30` | Seconds between attempts to start again the components of a non-critical agent whose `on_startup` raised. The agent stays out of service, shown with a `reason` in `/health/ready`, until every failed component starts; it is retried indefinitely and never ends the process. Must be positive; startup fails otherwise. Process scope. | @@ -235,7 +235,7 @@ OpenTelemetry and tracing settings. |-----|------|---------|-------------| | `otel_enabled` | `bool` | `false` | Enable OpenTelemetry tracing and metrics export. | | `otel_endpoint` | `str` | -- | OTLP collector endpoint URL (e.g., `"http://localhost:4317"`). | -| `otel_service_name` | `str` | `app_name` | `service.name` of the root namespace -- a standalone application's whole telemetry. Every agent of a group reports its own name instead, and in a group `OTEL_SERVICE_NAME` names the root only, with a WARNING at startup. See [observability](../concepts/observability.md). | +| `otel_service_name` | `str` | `app_name` | `service.name` of the root namespace -- a standalone application's whole telemetry. Every agent of a group reports its own name instead, or `.otel_service_name` when the agent sets one for itself; the root's value never applies to an agent. In a group `OTEL_SERVICE_NAME` names the root only, with a WARNING at startup, and a `service.name` in `OTEL_RESOURCE_ATTRIBUTES` without it fails the start. See [observability](../concepts/observability.md). | | `token_metrics_enabled` | `bool` | `true` | Record LLM token usage and response latency to OpenTelemetry. Only takes effect when `otel_enabled` is also `true`. | --- @@ -254,7 +254,7 @@ Additional logging behavior settings. | Key | Type | Default | Description | |-----|------|---------|-------------| -| `readiness_policy` | `str` | `"all"` | Which agents gate `/health/ready`: `"all"`, `"critical"` (only the agents the group flagged critical) or `"any"` (ready while one is up). The root gates readiness under every policy. Any other value fails startup. Process scope. | +| `readiness_policy` | `str` | `"all"` | Which agents gate `/health/ready`: `"all"`, `"critical"` (only the agents the group flagged critical) or `"any"` (ready while one is up). The root gates readiness under every policy, and so does an agent latched down (its startup failed, or its transport failed for good). Any other value fails startup. Process scope. | | `health_check_interval_seconds` | `int` | `30` | Seconds between health polls; readiness and an agent's pause or resume follow the latest poll. Process scope. | | `event_loop_debug` | `bool` | `false` | asyncio debug mode, which names a blocking callback and its source. Off unless set, in every environment; with it on, the watchdog does not run. Read as a boolean (`"false"` from the environment means false); any other value fails startup. | | `event_loop_slow_callback_seconds` | `float` | `0.2` | Debug mode's threshold for reporting a callback. | diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index 5cda6c2a..d088bedf 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -39,7 +39,7 @@ from .io.api.utilities.cache import CacheManagementApi from .clients.io.dapr_client import DaprClient from .clients.io.io_client_base import TOPIC_TRANSPORTS -from .clients.io.nats_client import NATSClient +from .clients.io.nats_client import DeterministicTransportError, NATSClient from .clients.io.nats_connections import CONNECTION_SOURCE_KEY, ConnectionSource, load_connection_source from .clients.io.nats_run_pool import RunLimit, RunPool from .services.service_base import ServiceBase @@ -57,6 +57,7 @@ LoopWatchdog, configure_loop_debug, ) +from .io.telemetry.telemetry import TelemetryConfigError from .utils import parse_bool _UNCONSTRUCTED_KINDS = frozenset({"cache", "health_checker"}) @@ -1116,6 +1117,7 @@ def _wire_transport( elif event_bus_type == "nats": client = NATSClient(namespace=namespace) # auto-registers client.set_fatal_handler(self._on_transport_fatal) + client.set_orphan_handler(self._on_orphaned) client.set_health_refresh(self._refresh_health) client.set_connection_source(connection_source) if connection_source is not None: @@ -1357,6 +1359,12 @@ async def _start_component(self, kind: str, component: Any, label: str) -> None: The root is always critical: it holds the shared infrastructure, and there is no "rest of the process" to keep running without it. + **A fault no retry can fix fails the start in every agent** (D23): a + :class:`DeterministicTransportError` is logged CRITICAL and propagates whatever + ``critical_agents`` says. That flag decides only for faults that may heal -- which is what + startup recovery retries -- and a deterministic one would latch the agent down for good + while the pod reported a replica that is silently short a consumer. + Args: kind: What sort of component this is, for the log line. component: The component to start. @@ -1364,12 +1372,19 @@ async def _start_component(self, kind: str, component: Any, label: str) -> None: Raises: Exception: whatever ``on_startup`` raised, when the component belongs to the root or - to a critical agent. + to a critical agent, or when it is a :class:`DeterministicTransportError`. """ try: await component.on_startup() except Exception as exc: namespace = namespace_of(component) + if isinstance(exc, DeterministicTransportError): + logger.critical( + "%s startup failed with a fault no retry can fix, so the start fails whatever 'critical_agents' says: %s", + f"{kind} {label}" if label else kind, + exc, + ) + raise if not namespace or namespace in self._critical_namespaces: logger.error("%s startup failed: %s", f"{kind} {label}" if label else kind, exc, exc_info=True) raise @@ -1398,7 +1413,15 @@ async def _on_transport_fatal(self, namespace: str, error: BaseException) -> Non The process is ended with SIGTERM to itself, so uvicorn runs the normal graceful shutdown -- the other agents drain -- instead of the interpreter stopping mid-flight. + + **A fault no retry can fix also takes liveness DOWN, in every agent** (D23): a + :class:`DeterministicTransportError` -- a durable clash, a stream the server refused, a + missing grant, a tenancy fault -- is logged CRITICAL and the liveness probe answers 503 + naming it, so the orchestrator restarts the pod and an operator sees why. A non-critical + agent is not exempt: ``critical_agents`` decides only for faults that may heal. """ + if isinstance(error, DeterministicTransportError) and self._actuator_api is not None: + self._actuator_api.mark_not_live(namespace, str(error)) if not namespace or namespace in self._critical_namespaces: logger.critical( "Agent '%s' cannot run, and it is %s, so the process is shut down: %s", @@ -1408,8 +1431,32 @@ async def _on_transport_fatal(self, namespace: str, error: BaseException) -> Non ) signal.raise_signal(signal.SIGTERM) return + if isinstance(error, DeterministicTransportError): + logger.critical( + "Agent '%s' cannot run, and no retry can fix it, so liveness is DOWN although the agent is not critical: %s", + namespace, + error, + ) await self._mark_agent_down(namespace, str(error)) + def _on_orphaned(self, namespace: str, reason: str | None) -> None: + """An agent stopped consuming for a reason that does not pass by itself, or consumes again (N12). + + Its resume keeps failing, or its connection loop gave up: the client is paused or done, it + reports healthy by design, and readiness alone would read UP while nothing is consumed. So + liveness goes DOWN, whatever ``critical_agents`` and ``readiness_policy`` say, and comes back + when the agent consumes again -- unlike a fault no retry can fix, this one may still clear. + """ + if self._actuator_api is None: # pragma: no cover - the actuator is started first + return + label = namespace or ROOT_LABEL + if reason is None: + self._actuator_api.clear_orphaned(namespace) + logger.warning("Agent '%s' consumes again; liveness no longer counts it as orphaned", label) + return + self._actuator_api.mark_orphaned(namespace, reason) + logger.critical("Agent '%s' consumes nothing, and the cause does not pass by itself, so liveness is DOWN: %s", label, reason) + @staticmethod def _startup_retry_interval(config: Config) -> float: """Read ``startup_retry_interval_seconds``, refusing a value that is not a positive number. @@ -1593,6 +1640,9 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: # component's first traced call happens after this point. try: self._telemetry_manager.configure_tracing(self.namespaces) + except TelemetryConfigError: + # Telemetry that would misattribute every agent's work fails the start (D17). + raise except Exception as e: logger.warning("Failed to configure OpenTelemetry: %s", e) diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index 716bd96e..a910b934 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -20,6 +20,7 @@ from nats.js import api as js_api from nats.js.client import JetStreamContext from nats.errors import NoRespondersError +from nats.errors import TimeoutError as NatsTimeoutError from nats.js.errors import APIError, NotFoundError from opentelemetry.metrics import CallbackOptions, Counter, Observation from pydantic import ValidationError @@ -53,7 +54,17 @@ class JetStreamBindingError(RuntimeError): """ -class JetStreamUnavailableError(RuntimeError): +class DeterministicTransportError(RuntimeError): + """A transport fault no retry can fix: the broker answered, and the answer is final (D23). + + Never retried by a connection loop. It goes to the fatal handler :class:`AppBuilder` installs, + which logs it CRITICAL and takes the process's liveness DOWN, in every agent -- whatever + ``critical_agents`` says, because a fault that cannot heal is not one a deployment can choose to + run without. The message says what failed, where, why it is final and what to change. + """ + + +class JetStreamUnavailableError(DeterministicTransportError): """The agent declared ``nats_use_jetstream = true`` and the server does not offer JetStream to it. A deployment error, not a transient one: no retry makes a server grow JetStream. It is therefore @@ -62,6 +73,26 @@ class JetStreamUnavailableError(RuntimeError): """ +class DurableConflictError(DeterministicTransportError): + """The durable this agent derives for a topic exists on the broker and filters another subject (S1).""" + + +class StreamConflictError(DeterministicTransportError): + """The server refused to create or widen the agent's stream, e.g. because its subjects overlap another stream's.""" + + +class JetStreamPermissionError(DeterministicTransportError): + """The broker refused this agent's own connection a permission it needs to consume.""" + + +class TenancyError(DeterministicTransportError): + """A named connection the connection source handed over is wrong for the broker it points at. + + A refused login, a refused deliver subject, or a binding-mode consumer that filters another + subject: the tenant's deployment does not match its broker, and only changing one of them helps. + """ + + SERVER_DEFAULT_ACK_WAIT = 30.0 """Seconds: the ``ack_wait`` NATS gives a consumer created without one. @@ -84,9 +115,9 @@ class JetStreamUnavailableError(RuntimeError): PERMISSION_VIOLATIONS_COUNTER = "blueprint.nats.connection.permission_violations" """Permission violations a named connection's broker reported; attributes ``agent`` and ``connection``.""" -PERMISSION_RETRY_SECONDS = 60.0 -"""How often a named connection retries after the broker refused it a permission: a missing grant does -not heal in seconds, so retrying at the normal pace would only fill the log (spec 7.9).""" +STREAM_NAME_IN_USE = 10058 +"""JetStream's ``err_code`` for "stream name already in use with a different configuration": a create +that lost a race against another client creating the same stream, not a refusal.""" CONTROL_MESSAGE_STATUS = "100" """The status a JetStream idle heartbeat and flow control request carry (``nats.js.api.StatusCode.CONTROL_MESSAGE``).""" @@ -103,6 +134,11 @@ class JetStreamUnavailableError(RuntimeError): FatalHandler = Callable[[str, BaseException], Awaitable[None]] """Called once when a client finds, after startup, that its agent cannot run at all: namespace, error.""" +OrphanHandler = Callable[[str, "str | None"], None] +"""Called when an agent stops consuming for a reason that does not pass by itself -- its resume keeps +failing, its connection loop gave up -- with the namespace and why, and with ``None`` once it consumes +again (D23, N12).""" + def redact_url(url: str) -> str: """Return ``url`` without its ``user:password@`` part, for logs and health messages. @@ -121,6 +157,83 @@ def redact_url(url: str) -> str: return urlunsplit(parts._replace(netloc=f"***@{netloc}")) +def resolve_nats_url(url: object, environment: object, *, override_variable: str) -> str: + """Return the broker URL an agent connects to; outside development, refuse to run without one. + + Development falls back to :data:`DEVELOPMENT_NATS_URL`, so a broker on the developer's machine + needs no configuration. Anywhere else there is no fallback: a pod pointed at ``localhost`` + connects to nothing and never says so. Public because ``asbs validate`` applies the same rule + (N19). + + Args: + url: The configured ``nats_url``. + environment: ``app_environment``. + override_variable: The environment variable that sets ``nats_url``, for the message. + + Raises: + ValueError: if ``url`` is unset or empty and ``environment`` is not ``"development"``. + """ + resolved = str(url or "").strip() + if resolved: + return resolved + if str(environment).lower() == "development": + return DEVELOPMENT_NATS_URL + raise ValueError( + f"'event_bus' is 'nats' but 'nats_url' is not set (app_environment is {str(environment)!r}). Outside " + "development there is no default: localhost is rarely right in a container, and a client pointed at it retries " + f"forever while the pod looks healthy. Set 'nats_url' in the group's settings.toml or as {override_variable}." + ) + + +def resolve_heartbeat_enabled(value: object) -> bool: + """Return ``nats_heartbeat_enabled``: whether running JetStream deliveries report ``in_progress`` (N19: shared). + + Raises: + ValueError: if the value is not a boolean -- a string such as ``"false"`` would otherwise + read as true and keep the heartbeat the operator meant to switch off. + """ + if not isinstance(value, bool): + raise ValueError(f"'nats_heartbeat_enabled' must be true or false, got {value!r}.") + return value + + +def resolve_root_queue_group(get: Callable[[str, Any], Any]) -> str: + """Return the root namespace's queue group: ``nats_queue_group``, else ``app_name`` (N19: shared). + + An agent's queue group is its namespace and needs no resolving; see + :meth:`NATSClient._resolve_queue_group` for why the root reads keys at all. + + Args: + get: How to read a key, ``(key, default) -> value``. + + Raises: + ValueError: if neither key yields a name, or the name cannot appear in a subject. + """ + for key in ("nats_queue_group", "app_name"): + name = str(get(key, "") or "").strip() + if not name: + continue + validate_subject_segment(name, source=f"The queue group (from '{key}')", subject=f"{name}.dead-letter") + return name + raise ValueError( + "NATS subscriptions require a queue group: set 'nats_queue_group' or 'app_name'. Without one every replica processes every message." + ) + + +def validate_durable_name(configured: str, topic_count: int) -> None: + """Refuse one ``nats_durable_name`` for several topics (N19: shared). + + Raises: + ValueError: if ``configured`` is set and more than one topic is subscribed. + """ + if configured and topic_count > 1: + raise ValueError( + f"'nats_durable_name' is set to '{configured}' but {topic_count} topics are subscribed. " + "A JetStream durable filters one subject, so one name cannot serve them all. " + "Remove the key to derive a durable per topic." + ) + + DEAD_LETTERED_COUNTER = "blueprint.events.dead_lettered" """Events the framework gave up on, whether or not their payload was kept. @@ -158,8 +271,8 @@ class NamedConnectionState: ``state`` is ``"bound"`` (delivering), ``"connecting"`` (first attempt in progress), ``"reconnecting"`` (the broker was lost; the client reconnects by itself), ``"retrying"`` (an - attempt failed; ``last_error`` says why) or ``"paused"`` (the agent is degraded and consumes - nowhere, C4). + attempt failed; ``last_error`` says why), ``"failed"`` (a tenancy fault no retry fixes; + ``last_error`` says which, D23) or ``"paused"`` (the agent is degraded and consumes nowhere, C4). """ name: str @@ -202,7 +315,8 @@ class _Link: connection_name: str = "" nats_client: NatsClient | None = None js: JetStreamContext | None = None - jetstream_mismatch: JetStreamUnavailableError | None = None + jetstream_mismatch: DeterministicTransportError | None = None + """What the JetStream probe found that no retry fixes: no JetStream, or no grant to use it.""" permission_errors: list[str] = field(default_factory=list) """Permission violations the broker reported through ``error_cb`` since the last attempt.""" closing: bool = False @@ -256,6 +370,8 @@ class _Binding: """Why the last connect-and-bind attempt failed, redacted; ``""`` once it is bound.""" permission_denied: bool = False """The last failed attempt was refused a permission by the broker.""" + failed: bool = False + """A fault no retry fixes stopped this binding's connect loop (D23); ``last_error`` says which.""" def __post_init__(self) -> None: self.idle.set() @@ -394,6 +510,9 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: self._closing = False self._fatal_handler: FatalHandler | None = None self._fatal_reported = False + self._fatal_errors: list[BaseException] = [] + self._orphan_handler: OrphanHandler | None = None + self._orphaned = False self._use_jetstream: bool = False self._publish_via_jetstream: bool = False self._publish_subjects: set[str] = set() @@ -453,11 +572,11 @@ def _connect_options(self, value: dict[str, Any]) -> None: self._link.connect_options = value @property - def _jetstream_mismatch(self) -> JetStreamUnavailableError | None: + def _jetstream_mismatch(self) -> DeterministicTransportError | None: return self._link.jetstream_mismatch @_jetstream_mismatch.setter - def _jetstream_mismatch(self, value: JetStreamUnavailableError | None) -> None: + def _jetstream_mismatch(self, value: DeterministicTransportError | None) -> None: self._link.jetstream_mismatch = value @property @@ -588,6 +707,8 @@ def _state_of(self, binding: _Binding) -> NamedConnectionState: client = binding.link.nats_client if binding.subscriptions_ready: state = "bound" + elif binding.failed: + state = "failed" elif self._consumption_paused: state = "paused" elif client is not None and client.is_reconnecting: @@ -861,10 +982,14 @@ def _start_named_link(self, binding: _Binding) -> None: self._named_tasks[binding] = task async def _run_named_link(self, binding: _Binding) -> None: - """Connect ``binding``'s link and bind, retrying until it works. - - Never gives up: a named connection's stream or account may appear later (provisioning), and - unlike the default connection its absence does not make the agent unready (plan D5). + """Connect ``binding``'s link and bind, retrying until it works -- unless the broker's answer is final. + + A transient fault is retried for ever: a named connection's broker may come back later, and + unlike the default connection its absence does not make the agent unready (plan D5). A + tenancy fault is not (D23): a refused grant or a :class:`DeterministicTransportError` marks the + binding ``failed`` and goes to the fatal handler, because the tenant's deployment does not + match its broker and an operator has to change one of them. A missing stream is still + retried -- provisioning may create it later (D23 (b), deferred). """ delay = float(self.config.get("event_client_retry_delay", 5.0)) attempt = 0 @@ -881,6 +1006,7 @@ async def _run_named_link(self, binding: _Binding) -> None: binding.subscriptions_ready = True binding.last_error = "" binding.permission_denied = False + binding.failed = False self._named_bound_changed(binding) if binding.replaces is not None: # New before old (spec 7.4): only now that this one delivers is the old one retired. @@ -895,19 +1021,17 @@ async def _run_named_link(self, binding: _Binding) -> None: denied = list(binding.link.permission_errors) binding.last_error = self._describe_error(binding.link, exc) binding.permission_denied = bool(denied) - if denied: + if denied and not isinstance(exc, DeterministicTransportError): # The broker reports a missing grant through error_cb and lets the request time # out: that is permanent, not a slow broker (spec 7.9). - logger.error( - "Agent '%s': named connection '%s' was refused a permission (%s); retrying every %.0fs until " - "the deployment grants it", - self.namespace or ROOT_LABEL, - binding.link.name, - "; ".join(denied), - PERMISSION_RETRY_SECONDS, + exc = TenancyError( + f"Agent '{self.namespace or ROOT_LABEL}': named connection '{binding.link.name}' -- the broker " + f"refused a permission ({'; '.join(denied)}). The tenant's account lacks a grant this agent needs " + "to consume: grant it, or correct the binding. Not retried: a missing grant does not appear by itself." ) - await asyncio.sleep(PERMISSION_RETRY_SECONDS) - continue + if isinstance(exc, DeterministicTransportError): + self._fail_named(binding, exc) + return logger.warning( "Agent '%s': named connection '%s' attempt %d failed, retrying in %.1fs: %s", self.namespace or ROOT_LABEL, @@ -918,6 +1042,14 @@ async def _run_named_link(self, binding: _Binding) -> None: ) await asyncio.sleep(delay) + def _fail_named(self, binding: _Binding, error: DeterministicTransportError) -> None: + """Stop treating ``binding`` as one that may still bind: mark it ``failed`` and report the fault (D23).""" + binding.subscriptions_ready = False + binding.failed = True + binding.last_error = self._describe_error(binding.link, error) + self._named_bound_changed(binding) + self._report_fatal(error) + def _on_named_link_done(self, binding: _Binding, task: asyncio.Task[None]) -> None: """Report a named-connection loop that died of anything but its cancellation, naming agent and connection.""" if not task.cancelled() and task.exception() is not None: @@ -964,10 +1096,23 @@ async def on_error(error: Exception) -> None: self._permission_violations.add(1, {"agent": agent, "connection": link.name}) # A refused login lands here too, and only here: with max_reconnect_attempts=-1, # nats.connect() retries it by itself and never returns, so the connect loop sees no - # exception. Recorded so the state reads "retrying" with the reason, not "connecting". + # exception. Recorded so the state reads "retrying" with the reason, not "connecting" -- + # and a refused login is a tenancy fault (D23): the binding fails, once, while nats-py + # keeps trying in case the account is fixed (a later bind clears it). + refused_login = "authorization violation" in str(error).lower() for binding in self._named: - if binding.link is link and not binding.subscriptions_ready: + if binding.link is link and not binding.subscriptions_ready and not binding.failed: binding.last_error = self._describe_error(link, error) + if refused_login: + self._fail_named( + binding, + TenancyError( + f"Agent '{agent}': named connection '{link.name}' -- the broker refused the login " + f"({self._describe_error(link, error)}). The credentials the connection source hands " + "over for this tenant are not accepted by its broker: correct them in the tenant's " + "configuration, or create the account on the broker. Not retried by the framework." + ), + ) logger.error("Agent '%s': error on named connection '%s': %s", agent, link.name, self._describe_error(link, error)) link.nats_client = await nats.connect( @@ -1233,17 +1378,7 @@ def _resolve_queue_group(self) -> str: """ if self.namespace: return self.namespace - - for key in ("nats_queue_group", "app_name"): - name = str(self.config.get(key, "") or "").strip() - if not name: - continue - validate_subject_segment(name, source=f"The queue group (from '{key}')", subject=f"{name}.dead-letter") - return name - raise ValueError( - "NATS subscriptions require a queue group: set 'nats_queue_group' or 'app_name'. " - "Without one every replica processes every message." - ) + return resolve_root_queue_group(self.config.get) # ------------------------------------------------------------------ # Publishing (mode and subjects) @@ -1418,12 +1553,7 @@ def _resolve_durables(self, topics: list[str]) -> dict[str, str]: subscribed, or if two topics sanitise to the same durable name. """ configured = str(self.config.get("nats_durable_name", "") or "").strip() - if configured and len(topics) > 1: - raise ValueError( - f"'nats_durable_name' is set to '{configured}' but {len(topics)} topics are subscribed. " - "A JetStream durable filters one subject, so one name cannot serve them all. " - "Remove the key to derive a durable per topic." - ) + validate_durable_name(configured, len(topics)) if configured and self.namespace: logger.warning( "Namespace '%s' is using the configured durable name '%s'. A durable is broker-side state " @@ -1522,10 +1652,7 @@ def _resolve_heartbeat_enabled(self) -> bool: ValueError: if the value is not a boolean -- a string such as ``"false"`` would otherwise read as true and keep the heartbeat the operator meant to switch off. """ - value = self.config.get("nats_heartbeat_enabled", True) - if not isinstance(value, bool): - raise ValueError(f"'nats_heartbeat_enabled' must be true or false, got {value!r}.") - return value + return resolve_heartbeat_enabled(self.config.get("nats_heartbeat_enabled", True)) def _resolve_handler_timeout(self) -> float | None: """Return ``nats_handler_timeout``: seconds one run may take, or ``None`` for no limit (plan D9). @@ -1615,6 +1742,18 @@ async def on_startup(self) -> None: await self.connect() self._started = True + def set_orphan_handler(self, handler: OrphanHandler) -> None: + """Install what is told when this agent stops consuming for a reason that does not pass by itself, and when it consumes again.""" + self._orphan_handler = handler + + def _report_orphaned(self, reason: str | None) -> None: + """Tell the handler that this agent is orphaned (``reason``) or consumes again (``None``); transitions only.""" + if (reason is not None) == self._orphaned: + return + self._orphaned = reason is not None + if self._orphan_handler is not None: + self._orphan_handler(self.namespace, reason) + def set_fatal_handler(self, handler: FatalHandler) -> None: """Install what is called when this agent turns out, after startup, to be unable to run. @@ -1635,25 +1774,21 @@ def _resolve_nats_url(self) -> str: ValueError: if ``nats_url`` is unset or empty and ``app_environment`` is not ``"development"``. Names the key, the environment, and how to set it. """ - url = str(self.config.get("nats_url", "") or "").strip() - if url: - return url - environment = str(self.config.get("app_environment", "development")) - if environment.lower() == "development": + configured = self.config.get("nats_url", "") + prefix = self.config.envvar_prefix + url = resolve_nats_url( + configured, + self.config.get("app_environment", "development"), + override_variable=f"{prefix}_NATS_URL" if prefix else "NATS_URL", + ) + if not str(configured or "").strip(): logger.warning( "Agent '%s': 'nats_url' is not set, connecting to %s because app_environment is 'development'. " "Set 'nats_url' for any other environment -- there, an unset one fails startup.", self.namespace or ROOT_LABEL, DEVELOPMENT_NATS_URL, ) - return DEVELOPMENT_NATS_URL - prefix = self.config.envvar_prefix - variable = f"{prefix}_NATS_URL" if prefix else "NATS_URL" - raise ValueError( - f"'event_bus' is 'nats' but 'nats_url' is not set (app_environment is {environment!r}). Outside " - "development there is no default: localhost is rarely right in a container, and a client pointed at it retries " - f"forever while the pod looks healthy. Set 'nats_url' in the group's settings.toml or as {variable}." - ) + return url def _resolve_connect_options(self, nats_url: str) -> dict[str, Any]: """Return the credential and inbox arguments for ``nats.connect()`` (M2). @@ -1760,6 +1895,8 @@ async def connect(self) -> None: self._connect_options = self._resolve_connect_options(self._nats_url) nats_url = redact_url(self._nats_url) self._connection_name = self._resolve_connection_name() + # A fresh attempt: what an earlier one was refused must not be read as this one's answer. + self._link.permission_errors.clear() # Unlimited by default: with 5 attempts 2 s apart, an outage of about 10 s closed the # connection for good (review finding #10). _on_closed restarts it either way. reconnect_attempts = self.config.get("nats_max_reconnect_attempts", -1) @@ -1773,6 +1910,7 @@ async def connect(self) -> None: disconnected_cb=self._on_disconnected, reconnected_cb=self._on_reconnected, closed_cb=self._on_closed, + error_cb=self._on_error, **self._connect_options, ) # Read by nats-py on every reconnect attempt, so from here on the configured count governs. @@ -1787,7 +1925,7 @@ async def connect(self) -> None: self._log_connected("with JetStream", nats_url) else: self._log_connected("(Core NATS)", nats_url) - except JetStreamUnavailableError: + except DeterministicTransportError: raise except Exception as e: # Raised, not logged: the retry loop logs each failed attempt, and a caller outside it @@ -1825,15 +1963,25 @@ async def _require_jetstream(self, nats_url: str) -> None: info request is the cheapest call that the server answers only when JetStream is there. A timeout proves nothing either way and stays an ordinary connection failure, retried like - any other. No responders (no JetStream on the server) and an API error (not enabled for the + any other -- unless the broker refused this connection a permission while it waited: a + request whose publish or reply subscription is denied simply times out, and the grant is the + cause (D23). No responders (no JetStream on the server) and an API error (not enabled for the account) are answers, and they are final. + A final answer is kept on the link: found by the health poll that connects before startup, + it fails the agent's startup when :meth:`on_startup` probes again. + Raises: JetStreamUnavailableError: the server answered, and JetStream is not available. + JetStreamPermissionError: the request timed out, and the broker refused this connection a + permission meanwhile. """ + error: DeterministicTransportError try: await self._js.account_info() # type: ignore[union-attr] + return except (NoRespondersError, APIError) as exc: + cause: BaseException = exc error = JetStreamUnavailableError( f"Agent '{self.namespace or ROOT_LABEL}' declares 'nats_use_jetstream = true', but the NATS server at " f"{nats_url} does not offer JetStream to this account ({type(exc).__name__}: {exc}). It is not retried " @@ -1841,17 +1989,42 @@ async def _require_jetstream(self, nats_url: str) -> None: "without anyone deciding it. Enable JetStream on the server or account, or set " "'nats_use_jetstream = false' if Core NATS is intended." ) - await self._nats_client.close() # type: ignore[union-attr] - self._nats_client = None - self._js = None - self._client = None - self._jetstream_mismatch = error - self._report_fatal(error) - raise error from exc + except NatsTimeoutError as exc: + denied = list(self._link.permission_errors) + if not denied: + raise + cause = exc + error = JetStreamPermissionError( + f"Agent '{self.namespace or ROOT_LABEL}': the NATS server at {nats_url} refused this agent's connection a " + f"permission it needs to use JetStream ({'; '.join(denied)}). Grant the account the '$JS.API' requests, " + "the reply inbox ('_INBOX.>' or 'nats_inbox_prefix') and the deliver subjects -- or point the agent at an " + "account that has them. Not retried: a missing grant does not appear by itself." + ) + await self._nats_client.close() # type: ignore[union-attr] + self._nats_client = None + self._js = None + self._client = None + self._jetstream_mismatch = error + self._report_fatal(error) + raise error from cause def _report_fatal(self, error: BaseException) -> None: - """Hand a fatal error found after startup to the installed handler, once.""" - if not self._started or self._fatal_handler is None or self._fatal_reported: + """Hand a fatal error found after startup to the installed handler; the first one only. + + The handler acts once per agent -- the agent is down after that -- but every later fault is + still logged CRITICAL here, so a second tenant failing is not silent. The same error object + is reported once (it can reach this twice: found while connecting, then raised into the loop). + + Before startup has finished nothing is reported here: :meth:`on_startup` raises what it + finds, and the startup failure policy handles it. Started without a handler -- a client + used outside :class:`AppBuilder` -- the error is logged CRITICAL here, so it is never silent. + """ + if not self._started or any(error is seen for seen in self._fatal_errors): + return + self._fatal_errors.append(error) + if self._fatal_reported or self._fatal_handler is None: + logger.critical("Agent '%s' cannot consume, and no retry can fix it: %s", self.namespace or ROOT_LABEL, error) + self._fatal_reported = True return self._fatal_reported = True task = asyncio.ensure_future(self._fatal_handler(self.namespace, error)) @@ -1948,9 +2121,15 @@ async def _try_resume(self, attempt: int, next_delay: float) -> bool: next_delay, self._describe_error(self._link, exc), ) + if isinstance(exc, DeterministicTransportError): + # A clash or a refusal that appeared while the agent was paused: final here too (D23). + self._report_fatal(exc) + # Paused, healthy by design, and consuming nothing: an orphan until a retry succeeds (N12). + self._report_orphaned(f"its resume failed (attempt {attempt}) and is retried: {self._describe_error(self._link, exc)}") return False self._consumption_paused = False self._subscriptions_ready = True + self._report_orphaned(None) logger.info("Agent '%s' resumed consuming: %d subscription(s) restored", self.namespace or ROOT_LABEL, len(self._subscriptions)) return True @@ -2190,6 +2369,7 @@ async def _start_with_retry(self) -> None: delay: float = float(self.config.get("event_client_retry_delay", 5.0)) attempt = 0 while True: + self._link.permission_errors.clear() try: await self._connect_and_subscribe() if self._consumption_paused: @@ -2197,13 +2377,26 @@ async def _start_with_retry(self) -> None: self._subscriptions_ready = True logger.info("NATSClient connected and subscribed successfully") return - except JetStreamUnavailableError: - # Final, not transient: retrying would log the same answer forever. + except DeterministicTransportError as e: + # Final, not transient: retrying would log the same answer forever (D23). self._subscriptions_ready = False + self._report_fatal(e) raise except Exception as e: attempt += 1 self._subscriptions_ready = False + denied = list(self._link.permission_errors) + if denied: + # The broker reports a missing grant through error_cb and lets the request time + # out, so the exception here is only the timeout: the grant is the cause. + error = JetStreamPermissionError( + f"Agent '{self.namespace or ROOT_LABEL}': the NATS server refused this agent's connection a " + f"permission it needs to consume ({'; '.join(denied)}). Grant the account those subjects -- for " + "JetStream that includes the '$JS.API' requests and the deliver subjects -- or point the agent at " + "an account that has them. Not retried: a missing grant does not appear by itself." + ) + self._report_fatal(error) + raise error from e if max_retries != -1 and attempt > max_retries: raise logger.warning("NATSClient attempt %d failed, retrying in %.1fs: %s", attempt, delay, self._describe_error(self._link, e)) @@ -2219,6 +2412,9 @@ def _on_retry_done(self, task: asyncio.Task[None]) -> None: if task.cancelled(): return exc = task.exception() + if isinstance(exc, DeterministicTransportError): + # Not "exhausting retries": it was never retried, and _report_fatal has said so already. + return if exc is not None: # No traceback: its last line is str(exc) again, unredacted (N3). logger.error( @@ -2226,6 +2422,8 @@ def _on_retry_done(self, task: asyncio.Task[None]) -> None: self.namespace or ROOT_LABEL, self._describe_error(self._link, exc), ) + # Nothing retries after this: the agent never consumes again in this process (N12). + self._report_orphaned(f"its connection loop gave up ('event_client_max_retries'): {self._describe_error(self._link, exc)}") async def _connect_and_subscribe(self) -> None: await self.connect() @@ -2297,9 +2495,16 @@ async def _provision_stream(self) -> None: as a warning, leaving the remaining topics uncaptured. Widening is additive -- subjects already on the stream are kept -- so this never - removes a subject an operator added. A failure to update is logged rather than - raised: the consumer that needs the subject fails immediately afterwards, and that - failure names the consumer as well as the stream. + removes a subject an operator added. + + A refusal by the server is final (D23): it answered, and asking again gets the same + answer -- typically subjects that overlap another stream's. It raises + :class:`StreamConflictError` instead of the consumers failing to bind on every attempt. A + failure without an answer (a timeout) stays an ordinary, retried connection failure on + create, and is logged on update, as before. + + Raises: + StreamConflictError: the server refused to create the stream or to add the subjects. """ js = self._nats_client.jetstream() # type: ignore[union-attr] stream = self.config.get("nats_stream_name", "EVENTS") @@ -2308,9 +2513,16 @@ async def _provision_stream(self) -> None: try: info = await js.stream_info(stream) except NotFoundError: - await js.add_stream(name=stream, subjects=sorted(wanted)) - logger.info("Created JetStream stream '%s' with subjects %s", stream, sorted(wanted)) - return + try: + await js.add_stream(name=stream, subjects=sorted(wanted)) + logger.info("Created JetStream stream '%s' with subjects %s", stream, sorted(wanted)) + return + except APIError as exc: + if exc.err_code != STREAM_NAME_IN_USE: + raise self._stream_refused(stream, "create it with subject(s)", sorted(wanted), exc) from exc + # Created between the lookup and the create -- by another agent of this process sharing + # the stream, or by another replica: a race, not a refusal. Widen the one that exists. + info = await js.stream_info(stream) # Not a set difference: a stream an operator provisioned as 'orders.>' already captures # 'orders.created', and asking the server to add the literal is refused as an overlap -- @@ -2324,6 +2536,8 @@ async def _provision_stream(self) -> None: try: await js.update_stream(info.config) logger.info("Added subject(s) %s to existing JetStream stream '%s'", sorted(missing), stream) + except APIError as exc: + raise self._stream_refused(stream, "add subject(s)", sorted(missing), exc) from exc except Exception as exc: logger.error( "JetStream stream '%s' does not carry subject(s) %s and could not be updated (%s); " @@ -2333,6 +2547,15 @@ async def _provision_stream(self) -> None: exc, ) + def _stream_refused(self, stream: str, action: str, subjects: list[str], exc: APIError) -> StreamConflictError: + """The error for a stream the server would not create or widen, naming what to change.""" + return StreamConflictError( + f"Agent '{self.namespace or ROOT_LABEL}': the NATS server refused to {action} {', '.join(subjects)} on " + f"JetStream stream '{stream}' ({exc.description or exc}). Usually another stream already captures one of " + "these subjects: give this agent its own subjects or its own 'nats_stream_name', or provision the stream " + "so it carries them. Not retried: the server gives the same answer until the streams change." + ) + def _consumer_config(self, topic: str, durable: str) -> js_api.ConsumerConfig: """Build the durable consumer this client wants for one topic. @@ -2393,12 +2616,14 @@ async def _ensure_consumer(self, topic: str, durable: str) -> js_api.ConsumerCon if filters != [topic]: # Another subscription's consumer under this name (S1): binding to it would deliver # that subscription's messages here. Not renamed -- the durable's pending state is - # broker-side and belongs to the subscription that made it. - raise JetStreamBindingError( - f"JetStream consumer '{durable}' on stream '{stream}' filters {', '.join(repr(f) for f in filters) or 'nothing'}, " - f"not '{topic}', so it belongs to another subscription and is not bound. A root topic and an agent's " - f"topic can derive one durable name (root 'orders-created' and agent 'orders' on 'created'): rename one " - f"of the topics, or delete the consumer if it is stale." + # broker-side and belongs to the subscription that made it. Not retried either (D23): + # the consumer does not change its filter by itself. + raise DurableConflictError( + f"Agent '{self.namespace or ROOT_LABEL}': JetStream consumer '{durable}' on stream '{stream}' filters " + f"{', '.join(repr(f) for f in filters) or 'nothing'}, not '{topic}', so it belongs to another subscription " + f"and is not bound. A root topic and an agent's topic can derive one durable name (root 'orders-created' " + f"and agent 'orders' on 'created'): rename one of the topics, or delete the consumer if it is stale. " + f"Not retried: the consumer keeps its filter until someone changes it." ) legacy = not info.config.deliver_group @@ -2511,6 +2736,7 @@ async def _bind(self, binding: _Binding) -> None: JetStreamBindingError: the binding manages its consumer and its stream does not exist. The stream belongs to whoever provisions the deployment; it is never created here. + TenancyError: the broker refused the subscription to the deliver subject (D23). """ spec = binding.jetstream if spec is None: @@ -2526,9 +2752,9 @@ async def _bind(self, binding: _Binding) -> None: sub = await client.subscribe(spec.deliver_subject, queue=spec.deliver_group, cb=handler) # The broker refuses a subscription the account may not make asynchronously, through # error_cb, so subscribe() returned and the binding read as bound for good (M4). The round - # trip makes any refusal arrive first; one naming this subject fails the attempt, and the - # connect loop retries it as a permission error. Compared lowercased: nats-py lowercases the - # whole -ERR line, the subject in it included. + # trip makes any refusal arrive first; one naming this subject fails the binding for good + # (D23: a grant the account lacks does not appear by retrying). Compared lowercased: nats-py + # lowercases the whole -ERR line, the subject in it included. # Two round trips, not one: nats-py writes PING straight to the transport while the SUB # still waits in its pending buffer for the flusher task, so the first PONG can come back # before the broker has seen the SUB (measured with nats-py 2.15: the refusal arrived after @@ -2541,7 +2767,12 @@ async def _bind(self, binding: _Binding) -> None: if refused: with contextlib.suppress(Exception): await sub.unsubscribe() - raise PermissionError(f"the broker refused the subscription to '{spec.deliver_subject}': {refused[0]}") + raise TenancyError( + f"Agent '{self.namespace or ROOT_LABEL}': named connection '{binding.link.name}' -- the broker refused " + f"the subscription to deliver subject '{spec.deliver_subject}' ({refused[0]}). The tenant's account is " + "not allowed to receive on it: grant the account that subject, or correct the deliver subject in the " + "binding. Not retried: a missing grant does not appear by itself." + ) binding.subscriptions.append(sub) logger.info( "Agent '%s' bound to consumer '%s' on stream '%s' (deliver subject '%s', group '%s', subjects %s)", @@ -3094,6 +3325,17 @@ async def _on_closed(self) -> None: # Paused or not: the loop connects either way and subscribes only an agent that is not paused. self._start_retry_task() + async def _on_error(self, error: Exception) -> None: + """nats-py's error callback for the default connection: record a permission violation, log every error. + + A grant the account lacks is reported only here -- the request it refused just times out -- + so the connect loop reads this list to tell a missing grant from a slow broker (D23). Set, + it replaces nats-py's own callback, which logged the error with a traceback and no agent. + """ + if "permissions violation" in str(error).lower(): + self._link.permission_errors.append(str(error)) + logger.error("Agent '%s': error on the NATS connection: %s", self.namespace or ROOT_LABEL, self._describe_error(self._link, error)) + async def _on_reconnected(self) -> None: logger.info("NATSClient reconnected") if not self._subscriptions_managed: @@ -3116,6 +3358,11 @@ async def _on_reconnected(self) -> None: # That is re-checked; nothing is re-subscribed. try: await self._ensure_broker_state() + except DeterministicTransportError as e: + # A broker that came back with another subscription's durable, or a stream that can + # no longer be widened: as final after a reconnect as at the first connect (D23). + self._report_fatal(e) + return except Exception as e: logger.error( "Agent '%s': re-checking the JetStream stream and consumers after a reconnect failed: %s", diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index 03010477..b05177a7 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -364,6 +364,19 @@ def __init__( # ENV_FOR_DYNACONF wins over it, and then the root loaded [production] while every agent's # fragment was layered for [development] (S13). self._environment = str(self._settings.current_env or app_env).lower() + configured = self._settings.get("app_environment") + if configured is not None and str(configured).lower() != self._environment: + # Typically `app_environment` written inside [default]: in environment mode it is a key + # of that section, read only after the environment was chosen (N15). + logger.warning( + "The settings say app_environment = %r, but the '%s' environment was loaded: a value inside a " + "section does not select the environment. This process runs as '%s', and 'app_environment' reads " + "that. Select the environment at the top level of settings.toml or with %s_APP_ENVIRONMENT.", + str(configured), + self._environment, + self._environment, + self._envvar_prefix or "DYNACONF", + ) # Replace DOT placeholders dot_placeholder = self._settings.get("dot_placeholder", "") @@ -1122,6 +1135,13 @@ def get(self, key: str, default: Any = None) -> Any: "environment directly." ) + if key.lower() == "app_environment": + # The environment Dynaconf loaded, not what a section of it says (N15): written inside + # [default], the key selects nothing, and answering its value had a development + # process run its production checks -- or the other way round. Every reader means + # "which environment is this", so that is the answer. + return self._environment + env_var = self._scoped_get(key, default) # Convert DynaBox to dict if isinstance(env_var, DynaBox): diff --git a/src/blueprint/agents/group_config.py b/src/blueprint/agents/group_config.py index 2ee500ea..52a9d5f6 100644 --- a/src/blueprint/agents/group_config.py +++ b/src/blueprint/agents/group_config.py @@ -45,6 +45,7 @@ import logging import os import tomllib +from collections.abc import Mapping from dataclasses import dataclass, field from pathlib import Path from typing import Any @@ -73,6 +74,17 @@ DEFAULT_AGENT_MAP = "agents.toml" +def group_file_path(env: Mapping[str, str] | Any, root: Path) -> Path: + """Where the group file is looked for, whether or not it exists; shared with ``asbs validate`` (N19). + + ``BLUEPRINT_GROUP_CONFIG`` when it is set, else ``./deployment-groups.yaml``; a relative path is + relative to ``root``, the image root. + """ + configured = str(env.get(GROUP_CONFIG_ENV, "") or "").strip() + path = Path(configured) if configured else root / DEFAULT_GROUP_CONFIG + return path if path.is_absolute() else root / path + + class GroupConfigError(Exception): """A group could not be resolved, and the process must not start. @@ -250,10 +262,8 @@ def resolve_at(cls, root: Path, *, environ: dict[str, str] | None = None) -> "Gr @staticmethod def _group_file_path(env: dict[str, str] | Any, root: Path) -> Path: - """Return where the group file is looked for, whether or not it exists.""" - configured = str(env.get(GROUP_CONFIG_ENV, "") or "").strip() - path = Path(configured) if configured else root / DEFAULT_GROUP_CONFIG - return path if path.is_absolute() else root / path + """Return where the group file is looked for, whether or not it exists; see :func:`group_file_path`.""" + return group_file_path(env, root) @classmethod def _read_group_file(cls, env: dict[str, str] | Any, root: Path) -> dict[str, Any]: diff --git a/src/blueprint/agents/handler/handler_chain.py b/src/blueprint/agents/handler/handler_chain.py index 96d1c013..8f66a4bb 100644 --- a/src/blueprint/agents/handler/handler_chain.py +++ b/src/blueprint/agents/handler/handler_chain.py @@ -5,6 +5,7 @@ import re import time from dataclasses import dataclass +from collections.abc import Callable from typing import Any from opentelemetry import trace @@ -185,6 +186,87 @@ class IdempotencyPolicy: ttl: int +def resolve_idempotency_policy(get: Callable[[str, Any], Any], *, has_cache: bool) -> IdempotencyPolicy: + """Read and validate the dedup settings (spec sec. 7.4); shared with ``asbs validate`` (N19). + + ``idempotency_ttl`` has no default on purpose. The window has to outlast the redelivery + window it is there to cover -- under JetStream that is ``nats_ack_wait * nats_max_deliver``, + under Dapr it is whatever the component's retry policy says -- and neither number is one this + layer can read. Choosing a value here would mean shipping a dedup window that silently expires + before the last redelivery arrives, which looks exactly like dedup not working. Enabling dedup + is therefore two keys, and the second one is the decision spec sec. 7.4 requires the author to + make. + + Args: + get: How to read a key, ``(key, default) -> value``. + has_cache: Whether the agent has a cache to keep the markers in. + + Raises: + ValueError: if ``idempotency_enabled`` is not a boolean, if it is on without a positive + ``idempotency_ttl``, or if it is on with no cache -- there would be nowhere to keep the + markers, and dedup would be silently off. + """ + if not parse_bool(get("idempotency_enabled", False), "idempotency_enabled"): + return IdempotencyPolicy(enabled=False, ttl=0) + + raw_ttl = get("idempotency_ttl", None) + if raw_ttl is None: + raise ValueError( + "'idempotency_enabled' is true but 'idempotency_ttl' is not set. It is the number of " + "seconds a processed event is remembered, and it must outlast the broker's redelivery " + "window ('nats_ack_wait' * 'nats_max_deliver' on JetStream), or a redelivery arrives " + "after the marker has expired and is processed again." + ) + try: + ttl = int(raw_ttl) + except (TypeError, ValueError) as exc: + raise ValueError(f"Config key 'idempotency_ttl' must be an integer number of seconds, got {raw_ttl!r}.") from exc + if ttl <= 0: + raise ValueError(f"'idempotency_ttl' must be greater than 0, got {ttl}. It is the dedup window, in seconds.") + + if not has_cache: + raise ValueError( + "'idempotency_enabled' is true but no cache is registered, so there is nowhere to record " + "the events already processed. Add '.with_cache()' to the AppBuilder chain." + ) + return IdempotencyPolicy(enabled=True, ttl=ttl) + + +def dedup_redelivery_warning(get: Callable[[str, Any], Any], agent: str) -> str | None: + """The warning for dedup where a run can outlast its delivery (S6, plan D4), or ``None``; shared (N19). + + A marker has no "in progress" state: a redelivery that arrives while the first run is still + going finds the marker, is skipped as a duplicate and acknowledged -- and if the first run then + fails, the event is lost. The NATS heartbeat (``in_progress``) is what stops the broker + redelivering a running delivery, so dedup without it is the one combination where that can + happen. Dapr has no heartbeat at all: the sidecar's app-call timeout decides when it gives up on + a delivery and sends it again. + + Args: + get: How to read a key, ``(key, default) -> value``, for an agent that deduplicates. + agent: The agent's name for the message; ```` for the root. + """ + bus = str(get("event_bus", "") or "").strip().lower() + try: + heartbeat = parse_bool(get("nats_heartbeat_enabled", True), "nats_heartbeat_enabled") + except ValueError: + # Not ours to refuse: the NATS client fails startup on the same value, naming it. + heartbeat = True + if bus == "nats" and not heartbeat: + return ( + f"Agent '{agent}' deduplicates events with 'nats_heartbeat_enabled = false': a run that outlasts ack_wait is " + "redelivered while it runs, the redelivery is skipped as a duplicate and acknowledged, and if the first run " + "then fails the event is lost. Keep the heartbeat on, or keep runs well under ack_wait." + ) + if bus == "dapr": + return ( + f"Agent '{agent}' deduplicates events under Dapr, which has no heartbeat: a run that outlasts the sidecar's " + "app-call timeout is delivered again while it runs, that delivery is skipped as a duplicate, and if the first " + "run then fails the event is lost. Keep runs well under that timeout." + ) + return None + + class HandlerChain(Component): """Executes registered event handlers in priority order. @@ -501,36 +583,10 @@ def _warn_ambiguous_runtime(self, handler: EventHandlerBase, names: list[str]) - # ------------------------------------------------------------------ def _warn_without_a_heartbeat(self) -> None: - """Warn when dedup runs where a run can outlast its delivery (S6, plan D4). - - A marker has no "in progress" state: a redelivery that arrives while the first run is - still going finds the marker, is skipped as a duplicate and acknowledged -- and if the - first run then fails, the event is lost. The NATS heartbeat (``in_progress``) is what - stops the broker redelivering a running delivery, so dedup without it is the one - combination where that can happen. Dapr has no heartbeat at all: the sidecar's app-call - timeout decides when it gives up on a delivery and sends it again. - """ - bus = str(self.config.get("event_bus", "") or "").strip().lower() - agent = self.namespace or ROOT_LABEL - try: - heartbeat = parse_bool(self.config.get("nats_heartbeat_enabled", True), "nats_heartbeat_enabled") - except ValueError: - # Not ours to refuse: the NATS client fails startup on the same value, naming it. - heartbeat = True - if bus == "nats" and not heartbeat: - logger.warning( - "Agent '%s' deduplicates events with 'nats_heartbeat_enabled = false': a run that outlasts ack_wait is " - "redelivered while it runs, the redelivery is skipped as a duplicate and acknowledged, and if the " - "first run then fails the event is lost. Keep the heartbeat on, or keep runs well under ack_wait.", - agent, - ) - elif bus == "dapr": - logger.warning( - "Agent '%s' deduplicates events under Dapr, which has no heartbeat: a run that outlasts the sidecar's " - "app-call timeout is delivered again while it runs, that delivery is skipped as a duplicate, and if " - "the first run then fails the event is lost. Keep runs well under that timeout.", - agent, - ) + """Warn when dedup runs where a run can outlast its delivery; see :func:`dedup_redelivery_warning`.""" + warning = dedup_redelivery_warning(self.config.get, self.namespace or ROOT_LABEL) + if warning: + logger.warning("%s", warning) async def _claim(self, event: CloudEvent[Any], policy: IdempotencyPolicy, context: dict[str, Any]) -> bool: """Record that this event is being processed, and report whether to dispatch it. @@ -628,49 +684,9 @@ def _idempotency_key(event: CloudEvent[Any], context: dict[str, Any]) -> dict[st return {"id": event_id, "source": source} def _resolve_idempotency_policy(self) -> IdempotencyPolicy: - """Read and validate the dedup settings (spec sec. 7.4). - - ``idempotency_ttl`` has no default on purpose. The window has to outlast the - redelivery window it is there to cover -- under JetStream that is - ``nats_ack_wait * nats_max_deliver``, under Dapr it is whatever the component's - retry policy says -- and neither number is one this layer can read. Choosing a - value here would mean shipping a dedup window that silently expires before the last - redelivery arrives, which looks exactly like dedup not working. Enabling dedup is - therefore two keys, and the second one is the decision spec sec. 7.4 requires the - author to make. + """Read and validate the dedup settings; see :func:`resolve_idempotency_policy`. Raises: - ValueError: if ``idempotency_enabled`` is not a boolean, if it is on without a - positive ``idempotency_ttl``, or if it is on with no cache registered -- - there would be nowhere to keep the markers, and dedup would be silently off. + ValueError: as :func:`resolve_idempotency_policy` does. """ - enabled = self._read_bool("idempotency_enabled", False) - if not enabled: - return IdempotencyPolicy(enabled=False, ttl=0) - - raw_ttl = self.config.get("idempotency_ttl", None) - if raw_ttl is None: - raise ValueError( - "'idempotency_enabled' is true but 'idempotency_ttl' is not set. It is the number of " - "seconds a processed event is remembered, and it must outlast the broker's redelivery " - "window ('nats_ack_wait' * 'nats_max_deliver' on JetStream), or a redelivery arrives " - "after the marker has expired and is processed again." - ) - try: - ttl = int(raw_ttl) - except (TypeError, ValueError) as exc: - raise ValueError(f"Config key 'idempotency_ttl' must be an integer number of seconds, got {raw_ttl!r}.") from exc - if ttl <= 0: - raise ValueError(f"'idempotency_ttl' must be greater than 0, got {ttl}. It is the dedup window, in seconds.") - - if not self.registry.has_cache(): - raise ValueError( - "'idempotency_enabled' is true but no cache is registered, so there is nowhere to record " - "the events already processed. Add '.with_cache()' to the AppBuilder chain." - ) - - return IdempotencyPolicy(enabled=True, ttl=ttl) - - def _read_bool(self, key: str, default: bool) -> bool: - """Read a boolean config key, accepting the strings an environment variable delivers.""" - return parse_bool(self.config.get(key, default), key) + return resolve_idempotency_policy(self.config.get, has_cache=self.registry.has_cache()) diff --git a/src/blueprint/agents/io/api/actuators/actuator_api.py b/src/blueprint/agents/io/api/actuators/actuator_api.py index 822d1331..987d3ba7 100644 --- a/src/blueprint/agents/io/api/actuators/actuator_api.py +++ b/src/blueprint/agents/io/api/actuators/actuator_api.py @@ -15,7 +15,7 @@ from opentelemetry import trace from ....component.component import Component, traced -from ....component.namespace import ROOT_NAMESPACE +from ....component.namespace import ROOT_LABEL, ROOT_NAMESPACE from ....component.registry import Registry from ....config import Config from ....config.config import DEFAULT_ENVVAR_PREFIX @@ -74,6 +74,33 @@ def __init__(self, namespaces: Sequence[str] = (ROOT_NAMESPACE,), critical_agent self._namespaces: tuple[str, ...] = tuple(namespaces) self._critical_agents: tuple[str, ...] = tuple(critical_agents) self._supervisor: NamespaceSupervisor | None = None + self._not_live: dict[str, str] = {} + self._orphaned: dict[str, str] = {} + + def mark_not_live(self, namespace: str, reason: str) -> None: + """Make the liveness probe answer DOWN for good, naming ``namespace`` and why (D23). + + For a fault no retry and no recovery can fix -- the broker's answer is final -- so the + orchestrator restarts the pod and the operator who looks finds the reason in the probe's + payload. Latched: nothing in the process can make the fault go away. + + Args: + namespace: The agent the fault belongs to; ``""`` for the root. + reason: What failed and what to change, as the fault's message says it. + """ + self._not_live.setdefault(namespace, reason) + + def mark_orphaned(self, namespace: str, reason: str) -> None: + """Make the liveness probe answer DOWN while ``namespace`` consumes nothing for a reason that does not pass by itself (N12). + + Not latched, unlike :meth:`mark_not_live`: the resume that keeps failing may still succeed, + and :meth:`clear_orphaned` takes it back then. + """ + self._orphaned[namespace] = reason + + def clear_orphaned(self, namespace: str) -> None: + """``namespace`` consumes again.""" + self._orphaned.pop(namespace, None) @property def health_entries(self) -> tuple[HealthCheckEntry, ...]: @@ -270,7 +297,15 @@ async def liveness_probe(self) -> LivenessResponse: Returns 200 OK even if configuration has validation errors, as restarting the pod won't fix configuration issues. Configuration errors should be caught by the readiness probe instead. + + Answers 503 once an agent hit a transport fault no retry can fix (:meth:`mark_not_live`, + D23), and while an agent is orphaned (:meth:`mark_orphaned`, N12), with each such agent and + its reason in the payload. """ + if self._not_live or self._orphaned: + failures = {namespace or ROOT_LABEL: reason for namespace, reason in {**self._orphaned, **self._not_live}.items()} + logger.warning("Liveness probe failed: %s", failures) + raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail={"status": "DOWN", "agents": failures}) if self.config and self.config.has_validation_errors(): logger.warning( "Liveness probe: configuration validation errors present: %s", diff --git a/src/blueprint/agents/io/api/actuators/health/health_cache.py b/src/blueprint/agents/io/api/actuators/health/health_cache.py index 5c10ccdf..fe77bfd1 100644 --- a/src/blueprint/agents/io/api/actuators/health/health_cache.py +++ b/src/blueprint/agents/io/api/actuators/health/health_cache.py @@ -184,7 +184,9 @@ async def _run_health_checks(self) -> None: components[entry.key] = result namespace_status, consumption_status, namespaces = self._aggregate_by_agent(components) - overall_status = "UP" if self._policy.is_ready(namespace_status, self._critical_namespaces()) else "DOWN" + orphaned = self._supervisor.forced_down if self._supervisor is not None else {} + ready = self._policy.is_ready(namespace_status, self._critical_namespaces(), orphaned) + overall_status = "UP" if ready else "DOWN" # Update cache self._cached_response = ReadinessResponse( diff --git a/src/blueprint/agents/io/api/actuators/health/readiness_policy.py b/src/blueprint/agents/io/api/actuators/health/readiness_policy.py index 5bc1ac24..a4d63c06 100644 --- a/src/blueprint/agents/io/api/actuators/health/readiness_policy.py +++ b/src/blueprint/agents/io/api/actuators/health/readiness_policy.py @@ -22,6 +22,10 @@ in a grouped process it holds the shared infrastructure every agent depends on. A root that is degraded is not a partial failure. +**An orphaned agent gates under every policy too** (N12): one latched down -- its startup failed +and recovery retries it, or its transport failed for good -- consumes nothing for a reason that is +not transient, and the policy exists to ignore agents that may recover, not ones that will not. + **The probe decides where traffic goes; it does not decide who is woken.** A degraded namespace is reported as ``blueprint.namespace.up = 0`` and an ERROR event whatever the policy (C3, C7), so choosing ``critical`` or ``any`` suppresses a *routing* consequence and never a signal. @@ -71,19 +75,27 @@ def parse(cls, value: object) -> "ReadinessPolicy": f"{', '.join(repr(policy.value) for policy in cls)}." ) from None - def is_ready(self, namespace_status: Mapping[str, bool], critical_namespaces: Collection[str]) -> bool: + def is_ready(self, namespace_status: Mapping[str, bool], critical_namespaces: Collection[str], orphaned: Collection[str] = ()) -> bool: """Return whether the pod is ready, given each namespace's health. + **An orphaned agent gates under every policy** (D23, N12): one latched down -- its startup + failed and recovery retries it, or its transport failed for good -- consumes nothing for a + reason that is not transient, so the pod is short a consumer whatever the deployment chose + to run without. The policy decides only for an agent whose checks fail and may recover. + Args: namespace_status: ``True`` where every one of that namespace's health checks passed. The root (``""``) is expected to be present; a namespace with no checks at all counts as up, because nothing about it can be failing. critical_namespaces: The agents the group flagged critical. Read only by :attr:`CRITICAL`. + orphaned: The agents latched down (the supervisor's ``forced_down``). Returns: Whether the readiness probe should answer ``UP``. """ + if orphaned: + return False if not namespace_status.get(ROOT_NAMESPACE, True): return False diff --git a/src/blueprint/agents/io/api/eventing/dapr.py b/src/blueprint/agents/io/api/eventing/dapr.py index 36d00fa0..845a733a 100644 --- a/src/blueprint/agents/io/api/eventing/dapr.py +++ b/src/blueprint/agents/io/api/eventing/dapr.py @@ -1,7 +1,7 @@ """Generic Dapr pub/sub endpoints for the agent service (framework-level).""" import logging -from collections.abc import Callable, Coroutine +from collections.abc import Callable, Coroutine, Iterable, Mapping from typing import Any from fastapi import Request, Response @@ -23,6 +23,45 @@ from ..rest_api_base import RestApiBase from .dapr_response import dapr_status from .event_handling_base import UNDECLARED_TOPIC_LABEL, EventHandlingBase +from ....utils import parse_bool + + +def shared_topic_warnings(topics_by_agent: Mapping[str, Iterable[str]], idempotency_enabled: Callable[[str], object]) -> list[str]: + """The warnings for a topic two agents declare while one of them does not deduplicate (S5); shared (N19). + + There is one Dapr delivery for every agent of a topic, and so one answer: a retry asked for by + one agent redelivers the event to all of them, and one that does not deduplicate runs it again. + + Args: + topics_by_agent: Each agent's declared topics; ``""`` is the root. + idempotency_enabled: An agent's ``idempotency_enabled``, as configured. Read as the handler + chain reads it, so ``"false"`` from an environment variable is off; a value that is not + a boolean at all counts as off here (the chain fails startup on it, naming it). + """ + + def deduplicates(namespace: str) -> bool: + try: + return parse_bool(idempotency_enabled(namespace), "idempotency_enabled") + except ValueError: + return False + + sharing: dict[str, list[str]] = {} + for namespace, topics in topics_by_agent.items(): + for topic in topics: + sharing.setdefault(topic, []).append(namespace) + warnings = [] + for topic, namespaces in sharing.items(): + if len(namespaces) < 2: + continue + repeating = [ns or ROOT_LABEL for ns in namespaces if not deduplicates(ns)] + if repeating: + warnings.append( + f"Topic '{topic}' is declared by agents {', '.join(ns or ROOT_LABEL for ns in namespaces)}, and Dapr delivers " + f"it once for all of them: a retry asked for by one redelivers it to every one, and {', '.join(repeating)} " + "run it again because 'idempotency_enabled' is off." + ) + return warnings + logger = logging.getLogger(__name__) @@ -174,22 +213,8 @@ def _warn_about_shared_topics(self, topics_by_agent: dict[str, list[str]]) -> No redelivers the event to every agent of the topic, and one that does not deduplicate runs it again. """ - sharing: dict[str, list[str]] = {} - for namespace, topics in topics_by_agent.items(): - for topic in topics: - sharing.setdefault(topic, []).append(namespace) - for topic, namespaces in sharing.items(): - if len(namespaces) < 2: - continue - repeating = [ns or ROOT_LABEL for ns in namespaces if not self.config.for_namespace(ns).get("idempotency_enabled", False)] - if repeating: - logger.warning( - "Topic '%s' is declared by agents %s, and Dapr delivers it once for all of them: a retry asked for " - "by one redelivers it to every one, and %s run it again because 'idempotency_enabled' is off.", - topic, - ", ".join(ns or ROOT_LABEL for ns in namespaces), - ", ".join(repeating), - ) + for warning in shared_topic_warnings(topics_by_agent, lambda ns: self.config.for_namespace(ns).get("idempotency_enabled", False)): + logger.warning("%s", warning) def _metric_topic(self, namespace: str, topic: str) -> str: """The topic for a declared one, :data:`UNDECLARED_TOPIC_LABEL` otherwise (S9, plan D6). diff --git a/src/blueprint/agents/io/api/scheduling/scheduler.py b/src/blueprint/agents/io/api/scheduling/scheduler.py index 6ff8384d..37818cf2 100644 --- a/src/blueprint/agents/io/api/scheduling/scheduler.py +++ b/src/blueprint/agents/io/api/scheduling/scheduler.py @@ -60,10 +60,37 @@ async def tick(self) -> None: from ....handler.event_handler_base import EventHandlerBase from ....models.events import GenericCloudEvent from ...telemetry.providers import agent_meter + from ..rest_api_base import RestApiBase logger = logging.getLogger(__name__) + +def resolve_scheduler_timezone(value: object, scheduler: str = "") -> ZoneInfo | None: + """``scheduler_timezone`` as a ``ZoneInfo``, or ``None`` for the host's local time (plan D15); shared (N19). + + Opt-in: unset keeps the host-local timezone every in-process scheduler has always used. Only the + in-process timer reads it; in event mode the external cron's own timezone decides. + + Args: + value: The configured ``scheduler_timezone``. + scheduler: The scheduler's name, for the message; empty when the check is not about one. + + Raises: + ValueError: if the value is not an IANA timezone name. + """ + raw = str(value or "").strip() + if not raw: + return None + try: + return ZoneInfo(raw) + except (ZoneInfoNotFoundError, ValueError): + of = f" of scheduler '{scheduler}'" if scheduler else "" + raise ValueError( + f"'scheduler_timezone'{of} is {raw!r}, which is not an IANA timezone name (such as 'Europe/Berlin' or 'UTC')." + ) from None + + SCHEDULER_MODE_EVENT = "event" """No in-process timer; the tick arrives as an ordinary namespaced event.""" @@ -480,16 +507,7 @@ def _resolve_timezone(self) -> Any: Raises: ValueError: if the value is not an IANA timezone name. """ - raw = str(self.config.get("scheduler_timezone", "") or "").strip() - if not raw: - return None - try: - return ZoneInfo(raw) - except (ZoneInfoNotFoundError, ValueError): - raise ValueError( - f"'scheduler_timezone' of scheduler '{self.base_name}' is {raw!r}, which is not an IANA timezone name " - "(such as 'Europe/Berlin' or 'UTC')." - ) from None + return resolve_scheduler_timezone(self.config.get("scheduler_timezone", ""), self.base_name) def _require_event_transport(self) -> None: """Fail unless a transport that can deliver a tick is configured. diff --git a/src/blueprint/agents/io/telemetry/telemetry.py b/src/blueprint/agents/io/telemetry/telemetry.py index 90e348df..85bac46f 100644 --- a/src/blueprint/agents/io/telemetry/telemetry.py +++ b/src/blueprint/agents/io/telemetry/telemetry.py @@ -160,6 +160,15 @@ def _framework_attributes(service_name: str, group: str, pod: str, own_service_n return {key: value for key, value in attributes.items() if key not in declared or (own_service_name and key == "service.name")} +class TelemetryConfigError(ValueError): + """The deployment's telemetry declaration cannot be honoured in this process; it fails the start (D17). + + Raised through :meth:`TelemetryManager.configure_tracing`, which otherwise only logs a failure: + telemetry that cannot be set up must not stop a service, but telemetry that would be wrong + about which agent did what must. + """ + + class TelemetryManager(IOBase): """Object-oriented manager for logging and tracing setup.""" @@ -174,6 +183,10 @@ def configure_tracing(self, namespaces: Sequence[str] = ()) -> None: namespaces: The agents this process hosts. The root is configured whether or not it appears here, because it is where a single-agent application's components live and where the framework's own root components go. + + Raises: + TelemetryConfigError: in a group, ``service.name`` is declared only through + ``OTEL_RESOURCE_ATTRIBUTES`` (D17). Every other failure is logged, not raised. """ if self.config is None: @@ -199,6 +212,16 @@ def configure_tracing(self, namespaces: Sequence[str] = ()) -> None: # every agent would make their telemetry impossible to tell apart. grouped = any(namespace != ROOT_NAMESPACE for namespace in namespaces) declared_service_name = os.environ.get("OTEL_SERVICE_NAME", "").strip() + if grouped and not declared_service_name and "service.name" in OTELResourceDetector().detect().attributes: + # Declared there, it would be every agent's service.name: the deployment's word is + # used as declared, and here it would make the agents' telemetry indistinguishable. + raise TelemetryConfigError( + f"OTEL_RESOURCE_ATTRIBUTES declares service.name, and this process hosts a group " + f"({', '.join(namespace for namespace in namespaces if namespace)}). Taken as declared it would name " + "every agent alike, so their telemetry could not be told apart. Remove service.name from " + "OTEL_RESOURCE_ATTRIBUTES -- each agent then reports its own name -- or set OTEL_SERVICE_NAME, which " + "names the root only." + ) if grouped and declared_service_name: logger.warning( "OTEL_SERVICE_NAME is set to '%s', which names the root's telemetry only: in a group every agent " @@ -212,7 +235,7 @@ def configure_tracing(self, namespaces: Sequence[str] = ()) -> None: continue own_service_name = bool(declared_service_name) and namespace != ROOT_NAMESPACE self._configure_namespace( - namespace, observability.otel_service_name, group, pod, span_processors, metric_exporters, own_service_name + namespace, self._service_name(namespace, observability), group, pod, span_processors, metric_exporters, own_service_name ) _register_exit_hook() @@ -226,13 +249,26 @@ def configure_tracing(self, namespaces: Sequence[str] = ()) -> None: self._setup_instrumentation() + except TelemetryConfigError: + raise except Exception as exc: # pragma: no cover - defensive logging logger.error("Failed to configure telemetry", exc_info=exc) + def _service_name(self, namespace: str, observability: Any) -> str: + """The ``service.name`` of ``namespace``: the root's ``otel_service_name``, else the agent's view's (N16). + + An agent's view resolves its own name -- ``.otel_service_name`` when the agent set one, + else the agent's name, never the root's value (C2). Reading it there, rather than taking the + namespace, is what lets an agent's own setting reach its resource. + """ + if namespace == ROOT_NAMESPACE: + return str(observability.otel_service_name) + return str(self.config.for_namespace(namespace).get_observability_config().otel_service_name) # type: ignore[union-attr] + @staticmethod def _configure_namespace( namespace: str, - root_service_name: str, + service_name: str, group: str, pod: str, span_processors: Sequence[_SharedSpanProcessor], @@ -248,7 +284,8 @@ def _configure_namespace( Args: namespace: The agent to configure; ``""`` for the root. - root_service_name: ``otel_service_name``, used only for the root. + service_name: The name to report: ``otel_service_name`` for the root, the agent's own + (its name, or ``.otel_service_name``) for an agent. group: The deployment group, for ``deployment.group``. pod: The replica, for ``service.instance.id``. span_processors: The process's span processors, shared by every provider. @@ -257,7 +294,6 @@ def _configure_namespace( own_service_name: Keep ``service.name`` although ``OTEL_SERVICE_NAME`` declares one -- an agent of a group (D17). """ - service_name = root_service_name if namespace == ROOT_NAMESPACE else namespace resource = Resource.create(_framework_attributes(service_name, group, pod, own_service_name)) # No atexit hook per provider: shutdown_providers() closes them in order, the root last. diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 2a3b1861..f3df85ab 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -33,6 +33,7 @@ from contextlib import asynccontextmanager from pathlib import Path from typing import Any +from unittest.mock import patch import nats import pytest @@ -68,6 +69,21 @@ def pytest_collection_modifyitems(items: list[pytest.Item]) -> None: item.add_marker(pytest.mark.integration) +@pytest.fixture(autouse=True) +def _the_process_is_not_ended() -> Iterator[None]: + """Fail a test whose application ends the process, instead of letting it end pytest. + + A fault no retry can fix in a critical agent makes the framework send SIGTERM to its own + process (D23) -- here that is pytest, which then stops without a report. A test that expects + it patches ``signal.raise_signal`` itself, and that inner patch wins over this one. + """ + with patch("blueprint.agents.app_builder.signal.raise_signal") as raise_signal: + yield + assert not raise_signal.called, ( + "the application ended the process (SIGTERM): an agent hit a fault no retry can fix -- see the CRITICAL log" + ) + + # --------------------------------------------------------------------------- # The broker # --------------------------------------------------------------------------- diff --git a/tests/integration/connection_source.py b/tests/integration/connection_source.py index 7ad0fd9f..4dc44f82 100644 --- a/tests/integration/connection_source.py +++ b/tests/integration/connection_source.py @@ -4,9 +4,11 @@ (nats-accounts.conf). Everything per test comes from the process config the factory is called with, because that is all the framework hands it: ``test_source_url``, ``test_source_prefix`` (keeps streams and subjects apart between tests), ``test_source_tenants``, ``test_source_unclaimed``, -``test_source_wrong_password`` (tenants whose connection logs in with a password the broker refuses) -and ``test_source_foreign_deliver`` (tenants whose binding names another tenant's deliver subject, -which their agent user may not subscribe to). +``test_source_wrong_password`` (tenants whose connection logs in with a password the broker refuses), +``test_source_foreign_deliver`` (tenants whose binding names another tenant's deliver subject, +which their agent user may not subscribe to) and ``test_source_unreachable`` (tenants whose +connection points at a port nothing listens on -- a fault that may heal, unlike the two before it, +which are tenancy faults the framework does not retry, D23). """ import dataclasses @@ -25,6 +27,9 @@ SOURCES: list["TenantSource"] = [] """Every source built in this process, so a test can change its connections at runtime.""" +UNREACHABLE_URL = "nats://127.0.0.1:1" +"""A port nothing listens on: the connection is refused, which is transient -- the broker may come up.""" + PASSWORDS = { "agent-a": "agent-a-test-only", "agent-a2": "agent-a2-test-only", @@ -65,6 +70,7 @@ def __init__(self, config: Any) -> None: self.unclaimed = tuple(config.get("test_source_unclaimed") or ()) self.wrong_password = set(config.get("test_source_wrong_password") or ()) self.foreign_deliver = set(config.get("test_source_foreign_deliver") or ()) + self.unreachable = set(config.get("test_source_unreachable") or ()) self.notifiers: list[Callable[[], None]] = [] SOURCES.append(self) @@ -74,18 +80,23 @@ def claims(self, agent: str, subjects: tuple[str, ...]) -> tuple[str, ...]: def watch(self, notify: Callable[[], None]) -> None: self.notifiers.append(notify) - def set_users(self, users: dict[str, str], *, wrong_password: set[str] | None = None) -> None: - """Replace the tenants and their users (and which of them log in wrongly), and tell every client.""" + def set_users(self, users: dict[str, str], *, wrong_password: set[str] | None = None, unreachable: set[str] | None = None) -> None: + """Replace the tenants and their users (and which of them log in wrongly or reach nothing), and tell every client.""" self.users = dict(users) if wrong_password is not None: self.wrong_password = set(wrong_password) + if unreachable is not None: + self.unreachable = set(unreachable) for notify in self.notifiers: notify() def connections(self) -> dict[str, ConnectionSpec]: return { tenant: ConnectionSpec( - name=tenant, url=self.url, user=user, password="wrong-test-only" if tenant in self.wrong_password else PASSWORDS[user] + name=tenant, + url=UNREACHABLE_URL if tenant in self.unreachable else self.url, + user=user, + password="wrong-test-only" if tenant in self.wrong_password else PASSWORDS[user], ) for tenant, user in self.users.items() } diff --git a/tests/integration/test_final_faults.py b/tests/integration/test_final_faults.py new file mode 100644 index 00000000..8ff3d69a --- /dev/null +++ b/tests/integration/test_final_faults.py @@ -0,0 +1,170 @@ +"""Faults no retry can fix, against a real broker (D23). + +The broker answered, and its answer is final: a durable that filters another subject, a stream the +server refuses to create, a grant the account lacks. Each test lets the fault happen and observes +what an operator would -- the CRITICAL line, ``/health/live`` answering 503 with the agent and the +reason -- and that the client does not try again. The tenancy faults of a named connection are in +``test_named_connections.py``. + +The agents are critical, as an unflagged agent is, so the framework also ends the process: it sends +SIGTERM to itself, and here the process is pytest, so that call is patched and asserted on. +""" + +import asyncio +import logging +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Any +from unittest.mock import patch + +import httpx +import pytest +from nats.aio.client import Client as NatsClient +from nats.js import api as js_api +from nats.js.client import JetStreamContext + +from blueprint.agents.agent_group import AgentGroup +from blueprint.agents.app_builder import AppBuilder +from blueprint.agents.clients.io.nats_client import JetStreamPermissionError, NATSClient +from blueprint.agents.component.component import Component +from blueprint.agents.config import Config +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.events import GenericCloudEvent + +from .conftest import base_settings +from .helpers import wait_until + + +def subscribing(topics: list[str]) -> type: + """A handler that declares ``topics`` and runs nothing; the faults happen before any delivery.""" + + class Subscribing(EventHandlerBase): + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + def get_subscribed_topics(self) -> list[str]: + return topics + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return True + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> None: + return None + + return Subscribing + + +@asynccontextmanager +async def started(tmp_path: Path, settings: str, agents: dict[str, list[str]]) -> AsyncIterator[tuple[Any, dict[str, NATSClient]]]: + """A running group of ``agents`` (name -> topics), without waiting for subscriptions: they never come.""" + (tmp_path / "settings.toml").write_text(settings, encoding="utf-8") + config = Config(settings_files=["settings.toml"], root_path=str(tmp_path)) + group = AgentGroup("integration", {name: AppBuilder().with_handler(subscribing(topics)) for name, topics in agents.items()}) + try: + app = group.assemble(config) + async with app.router.lifespan_context(app): + registry = Component.shared_registry + assert registry is not None + yield app, {name: registry.get_component(NATSClient, namespace=name) for name in agents} + finally: + Component.reset_shared_state() + + +async def liveness(app: Any) -> httpx.Response: + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://it") as http: + return await http.get("/health/live") + + +def critical(caplog: pytest.LogCaptureFixture) -> list[str]: + return [record.getMessage() for record in caplog.records if record.levelno == logging.CRITICAL] + + +class TestADurableOfAnotherSubscription: + """C1, S1 -- the durable the agent derives exists and filters another subject.""" + + async def test_it_is_refused_once_and_takes_liveness_down( + self, + tmp_path: Path, + nats_url: str, + nats_connection: NatsClient, + jetstream: JetStreamContext, + jetstream_stream: str, + subject_prefix: str, + caplog: pytest.LogCaptureFixture, + ) -> None: + agent = f"orders_{subject_prefix}" + topic = f"{subject_prefix}.orders.created" + durable = f"{agent}-{topic.replace('.', '_')}-durable" + await jetstream.add_consumer( + jetstream_stream, + config=js_api.ConsumerConfig( + durable_name=durable, filter_subject=f"{subject_prefix}.other", ack_policy=js_api.AckPolicy.EXPLICIT + ), + ) + + with patch("blueprint.agents.app_builder.signal.raise_signal") as raise_signal: + async with started(tmp_path, base_settings(nats_url, jetstream_stream), {agent: [topic]}) as (app, _): + await wait_until(lambda: raise_signal.called, timeout=15, description="the fatal handler to act") + live = await liveness(app) + refusals = sum("belongs to another subscription" in r.getMessage() for r in caplog.records) + await asyncio.sleep(2.0) # four retry delays (0.5 s): a retry would have shown by now + assert sum("belongs to another subscription" in r.getMessage() for r in caplog.records) == refusals + + assert live.status_code == 503 + assert durable in live.json()["detail"]["agents"][agent] + assert any(durable in message and "Not retried" in message for message in critical(caplog)) + info = await jetstream.consumer_info(jetstream_stream, durable) + assert info.config.filter_subject == f"{subject_prefix}.other", "the other subscription's consumer is left as it was" + + +class TestAStreamTheServerRefuses: + """The agent's stream would capture subjects another stream already captures.""" + + async def test_it_is_refused_once_and_takes_liveness_down( + self, + tmp_path: Path, + nats_url: str, + jetstream: JetStreamContext, + jetstream_stream: str, + subject_prefix: str, + caplog: pytest.LogCaptureFixture, + ) -> None: + agent = f"orders_{subject_prefix}" + own_stream = f"{jetstream_stream}_OWN" + settings = base_settings(nats_url, own_stream) + with patch("blueprint.agents.app_builder.signal.raise_signal") as raise_signal: + async with started(tmp_path, settings, {agent: [f"{subject_prefix}.orders.created"]}) as (app, _): + await wait_until(lambda: raise_signal.called, timeout=15, description="the fatal handler to act") + live = await liveness(app) + + assert live.status_code == 503 + reason = live.json()["detail"]["agents"][agent] + assert own_stream in reason and "refused" in reason + assert any("StreamConflictError" in message or f"stream '{own_stream}'" in message for message in critical(caplog)) + + +class TestAGrantTheAccountLacks: + """The agent's own connection may not make the JetStream requests consuming needs. + + Found by the health poll that connects every client before startup: the JetStream probe times + out while the broker reports the refused grant. It used to read as a slow broker, the agent was + paused as degraded and stayed so -- consuming nothing, retrying nothing, saying nothing. + """ + + async def test_it_fails_the_start( + self, tmp_path: Path, accounts_url: str, subject_prefix: str, caplog: pytest.LogCaptureFixture + ) -> None: + agent = f"orders_{subject_prefix}" + # 'proc' may publish and subscribe nothing (nats-accounts.conf). + settings = base_settings(accounts_url, f"IT_{subject_prefix.upper()}", 'nats_user = "proc"\nnats_password = "proc-test-only"\n') + with pytest.raises(JetStreamPermissionError, match="refused this agent's connection a permission") as refused: + async with started(tmp_path, settings, {agent: [f"{subject_prefix}.orders.created"]}): + pass + + assert "$js.api" in str(refused.value).lower() + assert "proc-test-only" not in str(refused.value) + assert any("whatever 'critical_agents' says" in message for message in critical(caplog)) diff --git a/tests/integration/test_named_connections.py b/tests/integration/test_named_connections.py index f9631b35..4f4c87b0 100644 --- a/tests/integration/test_named_connections.py +++ b/tests/integration/test_named_connections.py @@ -8,8 +8,11 @@ - a delivery the source rejects never runs and is termed; - a subject the source does not claim fails startup unless the hybrid mode is asked for; - connections added, changed and removed at runtime lose and duplicate nothing; -- a tenant connection that cannot log in moves readiness as ``nats_connections_readiness`` says, - and never pauses the agent: its other connection keeps delivering. +- a tenant connection that cannot reach its broker moves readiness as ``nats_connections_readiness`` + says, and never pauses the agent: its other connection keeps delivering; +- a tenancy fault -- a refused login, a refused deliver subject -- is not retried: the connection + reads ``failed``, the fault is logged CRITICAL, liveness answers 503, and a critical agent ends the + process (D23). """ import asyncio @@ -18,6 +21,7 @@ import uuid from collections.abc import AsyncIterator, Awaitable, Callable from typing import Any +from unittest.mock import patch import httpx import nats @@ -359,11 +363,11 @@ async def test_a_second_change_retires_the_link_that_was_still_delivering( client, source = clients[agent], SOURCES[-1] first = client._named[0].link.nats_client - source.set_users({"A": "agent-a2"}, wrong_password={"A"}) # changed, and it cannot log in + source.set_users({"A": "agent-a2"}, unreachable={"A"}) # changed, and it cannot connect (yet) await wait_until(lambda: len(client._named) == 2, timeout=10, description="the changed binding to be added") assert not first.is_closed, "the old link serves while the new one cannot bind" - source.set_users({"A": "agent-a2"}, wrong_password=set()) # changed again, now it can + source.set_users({"A": "agent-a2"}, unreachable=set()) # changed again, now it can await wait_until(lambda: first.is_closed, timeout=15, description="the first link to be retired") await wait_until( lambda: len(client._named) == 1 and client._named[0].subscriptions_ready, timeout=10, description="one bound binding" @@ -383,7 +387,7 @@ async def test_removing_it_retires_the_link_that_was_still_delivering( ) as clients: client, source = clients[agent], SOURCES[-1] first = client._named[0].link.nats_client - source.set_users({"A": "agent-a2"}, wrong_password={"A"}) + source.set_users({"A": "agent-a2"}, unreachable={"A"}) await wait_until(lambda: len(client._named) == 2, timeout=10, description="the changed binding to be added") source.set_users({}) @@ -392,25 +396,65 @@ async def test_removing_it_retires_the_link_that_was_still_delivering( class TestARefusedSubscriptionIsNotBound: - """M4 -- the broker refuses a subscription through error_cb only; subscribe() returned and it read as bound.""" + """M4 -- the broker refuses a subscription through error_cb only; subscribe() returned and it read as bound. - async def test_it_reads_retrying_with_a_permission_violation( - self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str + D23 -- and the refusal is a tenancy fault: final, not retried. + """ + + async def test_it_reads_failed_with_a_permission_violation( + self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str, caplog: pytest.LogCaptureFixture ) -> None: agent = f"risk_{subject_prefix}" await operator(["A"], {agent: ["risk.>"]}) extra = 'test_source_foreign_deliver = ["A"]\n' - async with settings_group( - settings(accounts_url, subject_prefix, ["A"], extra), {agent: recording_handler(["risk.>"], [])}, named=0 - ) as clients: - client = clients[agent] - await wait_until(lambda: client._named[0].last_error != "", timeout=10, description="the bind attempt to fail") - # error_cb reports the refusal while the bind still waits on its round trip: read the state - # once that bind has finished, or a binding that goes on to read as bound passes too. - await asyncio.sleep(1.0) - state = client._state_of(client._named[0]) - assert (state.state, state.permission_denied) == ("retrying", True) - assert client._named[0].subscriptions_ready is False + with patch("blueprint.agents.app_builder.signal.raise_signal") as raise_signal: + async with settings_group( + settings(accounts_url, subject_prefix, ["A"], extra), {agent: recording_handler(["risk.>"], [])}, named=0 + ) as clients: + client = clients[agent] + await wait_until(lambda: client._named[0].failed, timeout=10, description="the binding to fail") + state = client._state_of(client._named[0]) + assert (state.state, state.permission_denied) == ("failed", True) + assert client._named[0].subscriptions_ready is False + attempts = sum("refused the subscription to deliver subject" in r.getMessage() for r in caplog.records) + await asyncio.sleep(2.0) # longer than event_client_retry_delay: a retry would have shown by now + assert sum("refused the subscription to deliver subject" in r.getMessage() for r in caplog.records) == attempts + assert raise_signal.called, "a critical agent ends the process" + assert any(r.levelno == logging.CRITICAL and "deliver subject" in r.getMessage() for r in caplog.records) + + +class TestARefusedLoginIsATenancyFault: + """D23 -- the credentials the source hands over are wrong for the tenant's broker: CRITICAL, liveness DOWN.""" + + async def test_it_reads_failed_and_liveness_answers_503( + self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str, caplog: pytest.LogCaptureFixture + ) -> None: + agent = f"risk_{subject_prefix}" + await operator(["A", "B"], {agent: ["risk.>"]}) + runs: list[dict[str, Any]] = [] + apps: list[Any] = [] + extra = 'test_source_wrong_password = ["B"]\n' + with patch("blueprint.agents.app_builder.signal.raise_signal") as raise_signal: + async with settings_group( + settings(accounts_url, subject_prefix, ["A", "B"], extra), {agent: recording_handler(["risk.>"], runs)}, named=1, apps=apps + ) as clients: + client = clients[agent] + await wait_until( + lambda: {s.name: s.state for s in client.named_connection_states()} == {"A": "bound", "B": "failed"}, + timeout=15, + description="A bound, B failed", + ) + (b,) = [s for s in client.named_connection_states() if s.name == "B"] + assert "refused the login" in b.last_error and "wrong-test-only" not in b.describe() + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=apps[0]), base_url="http://it") as http: + live = await http.get("/health/live") + assert live.status_code == 503 + assert "refused the login" in live.json()["detail"]["agents"][agent] + assert "wrong-test-only" not in live.text + assert raise_signal.called, "a critical agent ends the process" + critical = [r.getMessage() for r in caplog.records if r.levelno == logging.CRITICAL] + assert any("named connection 'B'" in message and "refused the login" in message for message in critical) + assert all("wrong-test-only" not in message for message in critical) class TestStatusMessagesOfAnOperatorsConsumer: @@ -446,7 +490,10 @@ async def settled() -> bool: class TestADeadConnectionCountsForReadinessOnly: - """Step 5 / D5: a tenant whose connection cannot log in never pauses the agent on its other tenants.""" + """Step 5 / D5: a tenant whose connection cannot reach its broker never pauses the agent on its other tenants. + + A fault that may heal; a refused login is a tenancy fault and is not retried (D23, above). + """ @pytest.mark.parametrize("mode, ready", [("never", True), ("any", True), ("all", False)]) async def test_readiness_follows_the_mode_and_nothing_is_paused( @@ -455,7 +502,7 @@ async def test_readiness_follows_the_mode_and_nothing_is_paused( agent = f"risk_{subject_prefix}" await operator(["A", "B"], {agent: ["risk.>"]}) runs: list[dict[str, Any]] = [] - extra = f'test_source_wrong_password = ["B"]\nnats_connections_readiness = "{mode}"\nhealth_check_interval_seconds = 1\n' + extra = f'test_source_unreachable = ["B"]\nnats_connections_readiness = "{mode}"\nhealth_check_interval_seconds = 1\n' apps: list[Any] = [] async with settings_group( settings(accounts_url, subject_prefix, ["A", "B"], extra), {agent: recording_handler(["risk.>"], runs)}, named=1, apps=apps diff --git a/tests/unit/agent_generator/cli/commands/test_validate_runtime_parity.py b/tests/unit/agent_generator/cli/commands/test_validate_runtime_parity.py index 8609280e..538f77a2 100644 --- a/tests/unit/agent_generator/cli/commands/test_validate_runtime_parity.py +++ b/tests/unit/agent_generator/cli/commands/test_validate_runtime_parity.py @@ -315,3 +315,40 @@ def test_an_invalid_loop_debug_value_is_an_issue(self, tmp_path: Path) -> None: issues, _, _ = _findings(project) assert any("event_loop_debug" in issue for issue in issues) + + +class TestTheValidatorAppliesTheRuntimesOwnRules: + """N19 -- a rule restated in the validator drifts from the runtime's; it calls the runtime's function instead.""" + + @pytest.mark.parametrize( + ("module", "name"), + [ + ("blueprint.agents.clients.io.nats_client", "resolve_nats_url"), + ("blueprint.agents.clients.io.nats_client", "resolve_heartbeat_enabled"), + ("blueprint.agents.clients.io.nats_client", "resolve_root_queue_group"), + ("blueprint.agents.clients.io.nats_client", "validate_durable_name"), + ("blueprint.agents.handler.handler_chain", "resolve_idempotency_policy"), + ("blueprint.agents.handler.handler_chain", "dedup_redelivery_warning"), + ("blueprint.agents.io.api.scheduling.scheduler", "resolve_scheduler_timezone"), + ], + ) + def test_the_single_command_uses_the_runtimes_function(self, module: str, name: str) -> None: + import importlib + + from blueprint.agent_generator.cli.commands import validate + + assert getattr(validate, name) is getattr(importlib.import_module(module), name) + + @pytest.mark.parametrize( + ("module", "name"), + [ + ("blueprint.agents.io.api.eventing.dapr", "shared_topic_warnings"), + ("blueprint.agents.group_config", "group_file_path"), + ], + ) + def test_the_group_command_uses_the_runtimes_function(self, module: str, name: str) -> None: + import importlib + + from blueprint.agent_generator.cli.commands import validate_group + + assert getattr(validate_group, name) is getattr(importlib.import_module(module), name) diff --git a/tests/unit/agents/app_builder/test_startup_failure_policy.py b/tests/unit/agents/app_builder/test_startup_failure_policy.py index efa38c4f..ac021a7f 100644 --- a/tests/unit/agents/app_builder/test_startup_failure_policy.py +++ b/tests/unit/agents/app_builder/test_startup_failure_policy.py @@ -14,12 +14,13 @@ from collections.abc import Iterator from pathlib import Path from typing import Any -from unittest.mock import AsyncMock, patch +from unittest.mock import AsyncMock, MagicMock, patch import pytest from fastapi import FastAPI from blueprint.agents.app_builder import AppBuilder +from blueprint.agents.clients.io.nats_client import DurableConflictError from blueprint.agents.component.namespace import namespace_scope from blueprint.agents.config import Config from blueprint.agents.io.telemetry.providers import reset_providers @@ -327,3 +328,82 @@ async def test_a_non_critical_agent_is_marked_down(self, config: Config) -> None await builder._on_transport_fatal("billing", RuntimeError("no JetStream")) raise_signal.assert_not_called() builder._mark_agent_down.assert_awaited_once_with("billing", "no JetStream") + + +class ClashingService(ServiceBase): + """A service whose ``on_startup`` meets a fault no retry can fix (D23).""" + + async def on_startup(self) -> None: + raise DurableConflictError("consumer 'billing_created-durable' filters 'orders.created'") + + async def on_shutdown(self) -> None: + pass + + +class TestAFaultNoRetryFixes: + """D23 -- fatal in every agent, whatever critical_agents says; liveness DOWN after startup.""" + + async def test_it_fails_the_start_of_a_non_critical_agent(self, config: Config, caplog: pytest.LogCaptureFixture) -> None: + app, _ = build_with(config, ClashingService) + with caplog.at_level("CRITICAL"), pytest.raises(DurableConflictError, match="filters 'orders.created'"): + async with app.router.lifespan_context(app): + pass + assert "whatever 'critical_agents' says" in caplog.text + + async def test_after_startup_it_takes_liveness_down_in_a_non_critical_agent( + self, config: Config, caplog: pytest.LogCaptureFixture + ) -> None: + builder = TestAFatalTransportErrorAfterStartup._builder(config) + builder._mark_agent_down = AsyncMock() # type: ignore[method-assign] + builder._actuator_api = MagicMock() + clash = DurableConflictError("clash") + with patch("blueprint.agents.app_builder.signal.raise_signal") as raise_signal, caplog.at_level("CRITICAL"): + await builder._on_transport_fatal("billing", clash) + raise_signal.assert_not_called() + builder._actuator_api.mark_not_live.assert_called_once_with("billing", "clash") + builder._mark_agent_down.assert_awaited_once_with("billing", "clash") + assert "liveness is DOWN although the agent is not critical" in caplog.text + + @pytest.mark.parametrize("namespace", ["", "orders"], ids=["root", "critical"]) + async def test_the_root_or_a_critical_agent_also_ends_the_process(self, config: Config, namespace: str) -> None: + builder = TestAFatalTransportErrorAfterStartup._builder(config) + builder._actuator_api = MagicMock() + with patch("blueprint.agents.app_builder.signal.raise_signal") as raise_signal: + await builder._on_transport_fatal(namespace, DurableConflictError("clash")) + raise_signal.assert_called_once_with(signal.SIGTERM) + builder._actuator_api.mark_not_live.assert_called_once_with(namespace, "clash") + + async def test_another_fatal_error_leaves_liveness_alone(self, config: Config) -> None: + builder = TestAFatalTransportErrorAfterStartup._builder(config) + builder._mark_agent_down = AsyncMock() # type: ignore[method-assign] + builder._actuator_api = MagicMock() + await builder._on_transport_fatal("billing", RuntimeError("something else")) + builder._actuator_api.mark_not_live.assert_not_called() + + +class TestAnOrphanedAgent: + """N12 -- its resume keeps failing or its connection loop gave up: liveness DOWN, whatever its flag; back when it consumes.""" + + async def test_it_takes_liveness_down_and_back(self, config: Config, caplog: pytest.LogCaptureFixture) -> None: + builder = TestAFatalTransportErrorAfterStartup._builder(config) + builder._actuator_api = MagicMock() + with caplog.at_level("WARNING"): + builder._on_orphaned("billing", "its resume failed (attempt 1) and is retried: stream gone") + builder._on_orphaned("billing", None) + builder._actuator_api.mark_orphaned.assert_called_once_with("billing", "its resume failed (attempt 1) and is retried: stream gone") + builder._actuator_api.clear_orphaned.assert_called_once_with("billing") + assert any(r.levelname == "CRITICAL" and "liveness is DOWN" in r.getMessage() for r in caplog.records) + assert any("consumes again" in r.getMessage() for r in caplog.records) + + async def test_a_latched_non_critical_agent_takes_readiness_down_under_the_critical_policy(self, tmp_path: Path) -> None: + """A non-critical agent whose startup failed is retried and still gates readiness; liveness stays UP.""" + settings = tmp_path / "settings.toml" + settings.write_text( + '[development]\napp_name = "group"\napp_port = 8000\napp_environment = "development"\nreadiness_policy = "critical"\n' + ) + app, builder = build(Config(settings_files=[str(settings)], root_path=str(tmp_path)), critical=False) + async with app.router.lifespan_context(app): + status = await readiness(builder) + live = await builder._actuator_api.liveness_probe() # type: ignore[union-attr] + assert status.status == "DOWN" + assert live.status == "UP" diff --git a/tests/unit/agents/clients/io/test_nats_binding_mode.py b/tests/unit/agents/clients/io/test_nats_binding_mode.py index 6deecbb5..d127dfcd 100644 --- a/tests/unit/agents/clients/io/test_nats_binding_mode.py +++ b/tests/unit/agents/clients/io/test_nats_binding_mode.py @@ -8,7 +8,7 @@ from nats.js import api as js_api from nats.js.errors import APIError, NotFoundError -from blueprint.agents.clients.io.nats_client import JetStreamBindingError, NATSClient, _Binding +from blueprint.agents.clients.io.nats_client import JetStreamBindingError, NATSClient, TenancyError, _Binding from blueprint.agents.clients.io.nats_connections import JetStreamBinding from blueprint.agents.models.errors import RetryableHandlerError from blueprint.agents.models.events import CloudEvent @@ -224,7 +224,7 @@ async def refuse() -> None: mock_nats_core.jsm = MagicMock(return_value=jsm) nats_client._link.nats_client = mock_nats_core - with pytest.raises(PermissionError, match="acme.agent.A.risk"): + with pytest.raises(TenancyError, match="acme.agent.A.risk"): await nats_client._subscribe_all(binding) mock_nats_core.subscribe.return_value.unsubscribe.assert_awaited_once() diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index b01a1da1..c66d01bd 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -16,8 +16,11 @@ from blueprint.agents.clients.io.nats_client import ( DEVELOPMENT_NATS_URL, ConsumerTuning, + DurableConflictError, + JetStreamPermissionError, JetStreamUnavailableError, NATSClient, + StreamConflictError, _Binding, _Link, redact_url, @@ -2094,6 +2097,51 @@ async def subscribe_all() -> None: assert subscribed._subscriptions == [] assert "attempt 1" in caplog.text and "attempt 2" in caplog.text + async def test_a_failed_resume_reports_the_agent_orphaned_once_and_success_takes_it_back( + self, subscribed: NATSClient, mock_config: MagicMock + ) -> None: + """N12 -- paused, healthy by design, consuming nothing: liveness must hear of it, and of the end of it.""" + self._fast_retries(mock_config) + handler = MagicMock() + subscribed.set_orphan_handler(handler) + await subscribed.pause_consumption() + outcomes = [RuntimeError("stream gone"), RuntimeError("stream gone"), None] + + async def subscribe_all() -> None: + outcome = outcomes.pop(0) + if outcome is not None: + raise outcome + + with patch.object(subscribed, "_subscribe_all", new=subscribe_all): + await subscribed.resume_consumption() + await asyncio.wait_for(subscribed._resume_retry, timeout=5) # type: ignore[arg-type] + + assert [c.args[1] is None for c in handler.call_args_list] == [False, True], "orphaned once, then back" + assert "attempt 1" in handler.call_args_list[0].args[1] and "stream gone" in handler.call_args_list[0].args[1] + + async def test_a_resume_that_meets_a_fault_no_retry_fixes_reports_it_fatal(self, subscribed: NATSClient) -> None: + """D23 -- a clash that appeared while the agent was paused is as final as one at the first connect.""" + fatal = AsyncMock() + subscribed._started = True + subscribed.set_fatal_handler(fatal) + await subscribed.pause_consumption() + clash = DurableConflictError("clash found on resume") + with patch.object(subscribed, "_subscribe_all", new=AsyncMock(side_effect=clash)): + await subscribed.resume_consumption() + await asyncio.sleep(0) + fatal.assert_awaited_once_with(subscribed.namespace, clash) + await subscribed.close() + + async def test_a_connection_loop_that_gave_up_reports_the_agent_orphaned(self, nats_client: NATSClient) -> None: + handler = MagicMock() + nats_client.set_orphan_handler(handler) + task = MagicMock() + task.cancelled.return_value = False + task.exception.return_value = OSError("final failure") + nats_client._on_retry_done(task) + handler.assert_called_once() + assert "gave up" in handler.call_args.args[1] and "final failure" in handler.call_args.args[1] + async def test_a_pause_stops_the_retry(self, subscribed: NATSClient, mock_config: MagicMock) -> None: await subscribed.pause_consumption() with patch.object(subscribed, "_subscribe_all", new=AsyncMock(side_effect=RuntimeError("no"))): @@ -2343,6 +2391,27 @@ async def test_a_timeout_is_not_an_answer(self, nats_client: NATSClient, mock_co await self._connect(nats_client, self._server(AsyncMock(side_effect=NatsTimeoutError()))) assert nats_client._jetstream_mismatch is None + async def test_a_timeout_after_a_refused_grant_is_final(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """D23 -- a denied request just times out; the grant is the cause. Found before startup, it fails startup.""" + self._configure(mock_config, jetstream=True) + + async def refused() -> None: + await nats_client._on_error(Exception('nats: permissions violation for publish to "$js.api.info"')) + raise NatsTimeoutError() + + with pytest.raises(JetStreamPermissionError, match=r"\$js\.api\.info"): + await self._connect(nats_client, self._server(AsyncMock(side_effect=refused))) + assert isinstance(nats_client._jetstream_mismatch, JetStreamPermissionError) + health = await nats_client.health_check() + assert health.status == "unhealthy" and "refused this agent's connection a permission" in (health.message or "") + + async def test_a_grant_refused_on_an_earlier_connect_does_not_count(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + self._configure(mock_config, jetstream=True) + nats_client._link.permission_errors.append("nats: permissions violation for publish to x") + with pytest.raises(NatsTimeoutError): + await self._connect(nats_client, self._server(AsyncMock(side_effect=NatsTimeoutError()))) + assert nats_client._jetstream_mismatch is None + async def test_a_server_with_jetstream_connects(self, nats_client: NATSClient, mock_config: MagicMock) -> None: self._configure(mock_config, jetstream=True) await self._connect(nats_client, self._server(AsyncMock())) @@ -2771,13 +2840,13 @@ class TestADurableOfAnotherTopicIsNotBound: async def test_a_consumer_filtering_another_subject_is_refused( self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple ) -> None: - from blueprint.agents.clients.io.nats_client import JetStreamBindingError + from blueprint.agents.clients.io.nats_client import DurableConflictError mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders-created"]) theirs = js_api.ConsumerConfig(durable_name="orders-created-durable", filter_subject="created", deliver_group="orders") mock_js.consumer_info = AsyncMock(return_value=MagicMock(config=theirs)) - with pytest.raises(JetStreamBindingError) as refused: + with pytest.raises(DurableConflictError) as refused: await nats_client._subscribe_one("orders-created", AsyncMock()) mock_js.subscribe_bind.assert_not_awaited() @@ -2835,3 +2904,137 @@ async def test_a_configured_ack_wait_is_shown_in_seconds( with caplog.at_level("INFO", logger="blueprint.agents.clients.io.nats_client"): await nats_client._subscribe_one("orders.created", AsyncMock()) assert any("ack_wait 45.0s" in message for message in caplog.messages) + + +class TestAFaultNoRetryFixes: + """D23 -- the broker answered and the answer is final: not retried, handed to the fatal handler.""" + + @staticmethod + def _managed(nats_client: NATSClient, mock_config: MagicMock) -> AsyncMock: + mock_config.get.side_effect = lambda k, d=None: {"event_client_max_retries": -1, "event_client_retry_delay": 0.0}.get(k, d) + nats_client._subscriptions_managed = True + nats_client._started = True + handler = AsyncMock() + nats_client.set_fatal_handler(handler) + return handler + + async def test_a_durable_clash_stops_the_loop_and_reaches_the_handler(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + handler = self._managed(nats_client, mock_config) + clash = DurableConflictError("consumer 'orders-created-durable' filters 'created'") + attempt = AsyncMock(side_effect=clash) + with patch.object(nats_client, "_connect_and_subscribe", attempt), pytest.raises(DurableConflictError): + await nats_client._start_with_retry() + await asyncio.sleep(0) + assert attempt.await_count == 1 + handler.assert_awaited_once_with(nats_client.namespace, clash) + assert nats_client.subscriptions_ready is False + + async def test_a_refused_grant_is_a_permission_fault_not_a_timeout(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """The broker reports the grant through error_cb and lets the request time out; the grant is the cause.""" + handler = self._managed(nats_client, mock_config) + + async def refused() -> None: + await nats_client._on_error(Exception('nats: permissions violation for publish to "$js.api.consumer.create.events"')) + raise NatsTimeoutError() + + attempt = AsyncMock(side_effect=refused) + with patch.object(nats_client, "_connect_and_subscribe", attempt), pytest.raises(JetStreamPermissionError, match="consumer.create"): + await nats_client._start_with_retry() + await asyncio.sleep(0) + assert attempt.await_count == 1 + handler.assert_awaited_once() + assert isinstance(handler.await_args.args[1], JetStreamPermissionError) + + async def test_a_transient_fault_is_still_retried(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + handler = self._managed(nats_client, mock_config) + attempt = AsyncMock(side_effect=[OSError("connection refused"), None]) + with patch.object(nats_client, "_connect_and_subscribe", attempt): + await nats_client._start_with_retry() + assert attempt.await_count == 2 + handler.assert_not_awaited() + + async def test_a_permission_error_of_an_earlier_attempt_does_not_linger(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + """Recorded at runtime (a refused publish), it must not make the next connect failure read as final.""" + handler = self._managed(nats_client, mock_config) + nats_client._link.permission_errors.append("nats: permissions violation for publish to x") + attempt = AsyncMock(side_effect=[OSError("connection refused"), None]) + with patch.object(nats_client, "_connect_and_subscribe", attempt): + await nats_client._start_with_retry() + handler.assert_not_awaited() + + async def test_the_done_callback_does_not_call_a_final_fault_exhausted_retries(self, nats_client: NATSClient) -> None: + task = MagicMock() + task.cancelled.return_value = False + task.exception.return_value = DurableConflictError("clash") + with patch.object(logging.getLogger("blueprint.agents.clients.io.nats_client"), "error") as mock_log: + nats_client._on_retry_done(task) + mock_log.assert_not_called() + + async def test_a_stream_the_server_refuses_to_create_is_final( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + mock_js.add_stream = AsyncMock( + side_effect=APIError(code=400, err_code=10065, description="subjects overlap with an existing stream") + ) + with pytest.raises(StreamConflictError, match="overlap") as refused: + await nats_client._provision_stream() + assert "'EVENTS'" in str(refused.value) + assert "orders.created" in str(refused.value) + + async def test_a_stream_created_meanwhile_is_widened_not_refused( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + """Found live: two agents of one process sharing a stream both create it; the second loses the race.""" + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + from nats.js.errors import NotFoundError + + existing = MagicMock(config=js_api.StreamConfig(name="EVENTS", subjects=["other.subject"])) + mock_js.stream_info = AsyncMock(side_effect=[NotFoundError(), existing]) + mock_js.add_stream = AsyncMock( + side_effect=APIError(code=400, err_code=10058, description="stream name already in use with a different configuration") + ) + await nats_client._provision_stream() + updated = mock_js.update_stream.await_args.args[0].subjects + assert {"other.subject", "orders.created"} <= set(updated) + + async def test_a_stream_the_server_refuses_to_widen_is_final( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple + ) -> None: + mock_js = await _prepare_js_client(nats_client, mock_config, mock_nats_jetstream, ["orders.created"]) + mock_js.stream_info = AsyncMock(return_value=MagicMock(config=js_api.StreamConfig(name="EVENTS", subjects=["legacy.subject"]))) + mock_js.update_stream = AsyncMock( + side_effect=APIError(code=400, err_code=10065, description="subjects overlap with an existing stream") + ) + with pytest.raises(StreamConflictError, match="add subject"): + await nats_client._provision_stream() + + async def test_a_reconnect_that_finds_a_clash_reports_it(self, nats_client: NATSClient, mock_config: MagicMock) -> None: + handler = self._managed(nats_client, mock_config) + nats_client._use_jetstream = True + nats_client._topic_callbacks = {"orders-created": AsyncMock()} + clash = DurableConflictError("clash after the broker came back") + with patch.object(nats_client, "_ensure_broker_state", AsyncMock(side_effect=clash)): + await nats_client._on_reconnected() + await asyncio.sleep(0) + handler.assert_awaited_once_with(nats_client.namespace, clash) + assert nats_client.subscriptions_ready is False + + async def test_the_handler_hears_the_first_fault_and_every_later_one_is_logged_critical( + self, nats_client: NATSClient, mock_config: MagicMock, caplog: pytest.LogCaptureFixture + ) -> None: + handler = self._managed(nats_client, mock_config) + first, second = DurableConflictError("first"), StreamConflictError("second") + with caplog.at_level(logging.CRITICAL): + nats_client._report_fatal(first) + nats_client._report_fatal(first) + nats_client._report_fatal(second) + nats_client._report_fatal(second) + await asyncio.sleep(0) + handler.assert_awaited_once_with(nats_client.namespace, first) + assert [r.getMessage().endswith("second") for r in caplog.records if r.levelno == logging.CRITICAL] == [True] + + async def test_the_error_callback_records_a_refused_grant(self, nats_client: NATSClient) -> None: + await nats_client._on_error(Exception("nats: permissions violation for subscription to _DELIVER.x")) + await nats_client._on_error(Exception("nats: unexpected EOF")) + assert nats_client._link.permission_errors == ["nats: permissions violation for subscription to _DELIVER.x"] diff --git a/tests/unit/agents/clients/io/test_nats_connection_readiness.py b/tests/unit/agents/clients/io/test_nats_connection_readiness.py index c53bbdba..815b39fe 100644 --- a/tests/unit/agents/clients/io/test_nats_connection_readiness.py +++ b/tests/unit/agents/clients/io/test_nats_connection_readiness.py @@ -131,13 +131,17 @@ async def test_a_failing_connection_reads_retrying_with_its_error_redacted(self, assert states["B"].last_error.startswith("ConnectionError: nats://***@h:4222 refused") assert PASSWORD not in states["B"].describe() - async def test_a_refused_permission_is_reported(self, nats_client: NATSClient, broker: Broker) -> None: + async def test_a_refused_permission_fails_the_connection(self, nats_client: NATSClient, broker: Broker) -> None: + """D23: a grant the account lacks is a tenancy fault -- the connection reads failed, and is not retried.""" broker.failing["B"] = TimeoutError("no response") broker.denied.add("B") - with patch.object(nats_client_module, "PERMISSION_RETRY_SECONDS", 0.01): - await _started(nats_client, "B") - assert _states(nats_client)["B"].permission_denied - assert "permission violation" in _states(nats_client)["B"].describe() + await _started(nats_client, "B") + state = _states(nats_client)["B"] + assert state.state == "failed" + assert state.permission_denied + assert "permission violation" in state.describe() + assert "TenancyError" in state.last_error + assert nats_client._named_tasks[nats_client._named[0]].done() async def test_the_error_is_cleared_once_it_binds(self, nats_client: NATSClient, broker: Broker) -> None: broker.failing["B"] = ConnectionError("down") @@ -147,8 +151,8 @@ async def test_the_error_is_cleared_once_it_binds(self, nats_client: NATSClient, await asyncio.sleep(0.01) assert _states(nats_client)["B"] == NamedConnectionState("B", "bound") - async def test_a_refused_login_reads_retrying_although_connect_never_returns(self, nats_client: NATSClient) -> None: - """With max_reconnect_attempts=-1 nats.connect() retries a refused login itself; only error_cb hears of it.""" + async def test_a_refused_login_fails_the_connection_although_connect_never_returns(self, nats_client: NATSClient) -> None: + """With max_reconnect_attempts=-1 nats.connect() retries a refused login itself; only error_cb hears of it (D23).""" await _started(nats_client, "B") binding = nats_client._named[0] binding.subscriptions_ready = False @@ -162,7 +166,9 @@ async def test_a_refused_login_reads_retrying_although_connect_never_returns(sel await nats_client._open_named_link(link) await connect.call_args.kwargs["error_cb"](Exception("nats: 'Authorization Violation'")) - assert _states(nats_client)["B"] == NamedConnectionState("B", "retrying", "Exception: nats: 'Authorization Violation'") + state = _states(nats_client)["B"] + assert state.state == "failed" + assert state.last_error.startswith("TenancyError: Agent '': named connection 'B' -- the broker refused the login") async def test_a_lost_broker_reads_reconnecting(self, nats_client: NATSClient, broker: Broker) -> None: await _started(nats_client, "A") diff --git a/tests/unit/agents/clients/io/test_nats_runtime_changes.py b/tests/unit/agents/clients/io/test_nats_runtime_changes.py index 1c93b7e1..bd66eb6e 100644 --- a/tests/unit/agents/clients/io/test_nats_runtime_changes.py +++ b/tests/unit/agents/clients/io/test_nats_runtime_changes.py @@ -423,9 +423,10 @@ async def test_close_during_a_change_cancels_it_and_cleans_up(self, nats_client: class TestPermissionViolations: - async def test_a_refused_permission_backs_off_and_says_so( + async def test_a_refused_permission_fails_the_connection_and_says_so( self, nats_client: NATSClient, broker: Broker, caplog: pytest.LogCaptureFixture ) -> None: + """D23: a missing grant is final -- not retried, reported CRITICAL naming the connection and the subject.""" source = WatchedSource(A=_binding("A")) calls = 0 @@ -439,12 +440,14 @@ async def denied(link: Any) -> None: with ( patch.object(nats_client, "_open_named_link", side_effect=denied), - patch.object(nats_client_module, "PERMISSION_RETRY_SECONDS", 0.01), caplog.at_level(logging.ERROR), ): + nats_client._started = True await _started(nats_client, source, broker) - assert any("refused a permission" in message and "deliver.A" in message for message in caplog.messages) - assert calls == 2 + critical = [r.getMessage() for r in caplog.records if r.levelno == logging.CRITICAL] + assert any("named connection 'A'" in message and "deliver.A" in message for message in critical) + assert calls == 1 + assert nats_client.named_connection_states()[0].state == "failed" async def test_the_error_callback_records_permission_violations(self, nats_client: NATSClient) -> None: from blueprint.agents.clients.io.nats_client import _Link diff --git a/tests/unit/agents/config/test_config_init.py b/tests/unit/agents/config/test_config_init.py index 4727efc1..3f9dbd8e 100644 --- a/tests/unit/agents/config/test_config_init.py +++ b/tests/unit/agents/config/test_config_init.py @@ -261,3 +261,36 @@ def test_a_sectioned_declaration_is_not_seen_by_the_first_pass(self, tmp_path: P config = Config(settings_files=[str(path)], root_path=str(tmp_path)) assert config.get("app_name") == "from-default" + + def test_a_sectioned_declaration_reads_as_the_environment_that_loaded_and_is_warned( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture + ) -> None: + """N15 -- it read 'production' while [development] was loaded, so production checks ran in development.""" + monkeypatch.delenv("DYNACONF_APP_ENVIRONMENT", raising=False) + monkeypatch.delenv("ENV_FOR_DYNACONF", raising=False) + path = self._written( + tmp_path, + """ +[default] +app_environment = "production" +app_name = "from-default" +app_port = 8000 +""", + ) + with caplog.at_level("WARNING"): + config = Config(settings_files=[str(path)], root_path=str(tmp_path)) + + assert config.get("app_environment") == "development" + assert config.for_namespace("orders").get("app_environment") == "development" + assert "app_environment = 'production', but the 'development' environment was loaded" in caplog.text + + def test_a_selected_environment_reads_as_itself_without_a_warning( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture + ) -> None: + monkeypatch.setenv("DYNACONF_APP_ENVIRONMENT", "production") + path = self._written(tmp_path, '[default]\napp_name = "a"\napp_port = 8000\n\n[production]\napp_name = "b"\n') + with caplog.at_level("WARNING"): + config = Config(settings_files=[str(path)], root_path=str(tmp_path)) + + assert config.get("app_environment") == "production" + assert "does not select the environment" not in caplog.text diff --git a/tests/unit/agents/io/api/actuators/health/test_health_cache.py b/tests/unit/agents/io/api/actuators/health/test_health_cache.py index 6e8fd9fd..7994c48d 100644 --- a/tests/unit/agents/io/api/actuators/health/test_health_cache.py +++ b/tests/unit/agents/io/api/actuators/health/test_health_cache.py @@ -304,10 +304,11 @@ async def test_passing_checks_do_not_make_it_up(self) -> None: assert response.namespaces["billing"].failing == [] supervisor.observe.assert_awaited_once_with({"": True, "orders": True, "billing": False}) - async def test_critical_policy_keeps_the_pod_in_but_says_why(self) -> None: + async def test_critical_policy_takes_the_pod_out_for_it_and_says_why(self) -> None: + """N12, D23: a latched agent is orphaned -- it gates under every policy, flagged critical or not.""" cache, _ = await self._run(ReadinessPolicy.CRITICAL, {"orders"}, [_entry("db", "healthy", namespace="billing")]) response = await cache.get_health_status() - assert response.status == "UP" + assert response.status == "DOWN" assert response.namespaces["billing"].reason == self.REASON async def test_it_is_reported_with_no_checks_registered_at_all(self) -> None: diff --git a/tests/unit/agents/io/api/actuators/health/test_readiness_policy.py b/tests/unit/agents/io/api/actuators/health/test_readiness_policy.py index 81cf2847..dc95c8d0 100644 --- a/tests/unit/agents/io/api/actuators/health/test_readiness_policy.py +++ b/tests/unit/agents/io/api/actuators/health/test_readiness_policy.py @@ -63,3 +63,16 @@ def test_any_is_ready_while_one_agent_is_up(self) -> None: def test_any_refuses_readiness_when_every_agent_is_down(self) -> None: assert ReadinessPolicy.ANY.is_ready({"": True, "orders": False, "billing": False}, set()) is False + + +class TestAnOrphanedAgent: + """N12, D23 -- a latched agent consumes nothing for a reason that is not transient: it gates under every policy.""" + + @pytest.mark.parametrize("policy", list(ReadinessPolicy)) + def test_it_takes_the_pod_out_whatever_the_policy(self, policy: ReadinessPolicy) -> None: + status = {"": True, "orders": True, "billing": False} + assert policy.is_ready(status, {"orders"}, orphaned={"billing"}) is False + + def test_without_it_the_policy_still_decides(self) -> None: + status = {"": True, "orders": True, "billing": False} + assert ReadinessPolicy.CRITICAL.is_ready(status, {"orders"}, orphaned=()) is True diff --git a/tests/unit/agents/io/api/actuators/test_actuator_api.py b/tests/unit/agents/io/api/actuators/test_actuator_api.py index ca50590c..435ec43b 100644 --- a/tests/unit/agents/io/api/actuators/test_actuator_api.py +++ b/tests/unit/agents/io/api/actuators/test_actuator_api.py @@ -172,6 +172,31 @@ async def test_returns_up_even_when_config_has_validation_errors(self, actuator_ result = await actuator_api.liveness_probe() assert result.status == "UP" + async def test_an_orphaned_agent_answers_503_until_it_consumes_again(self, actuator_api: ActuatorApi, mock_config: MagicMock) -> None: + """N12 -- unlike a fault no retry fixes, an orphan may clear: its resume can still succeed.""" + from fastapi import HTTPException + + mock_config.has_validation_errors.return_value = False + actuator_api.mark_orphaned("orders", "its resume failed (attempt 1) and is retried: stream gone") + with pytest.raises(HTTPException) as down: + await actuator_api.liveness_probe() + assert down.value.detail == {"status": "DOWN", "agents": {"orders": "its resume failed (attempt 1) and is retried: stream gone"}} + actuator_api.clear_orphaned("orders") + assert (await actuator_api.liveness_probe()).status == "UP" + + async def test_a_fault_no_retry_fixes_answers_503_naming_each_agent(self, actuator_api: ActuatorApi, mock_config: MagicMock) -> None: + """D23 -- the orchestrator restarts the pod, and the operator who looks finds why.""" + from fastapi import HTTPException + + mock_config.has_validation_errors.return_value = False + actuator_api.mark_not_live("billing", "consumer clash") + actuator_api.mark_not_live("", "stream refused") + actuator_api.mark_not_live("billing", "a later fault") + with pytest.raises(HTTPException) as down: + await actuator_api.liveness_probe() + assert down.value.status_code == 503 + assert down.value.detail == {"status": "DOWN", "agents": {"billing": "consumer clash", "": "stream refused"}} + # --------------------------------------------------------------------------- # on_startup / on_shutdown diff --git a/tests/unit/agents/io/api/eventing/test_dapr.py b/tests/unit/agents/io/api/eventing/test_dapr.py index 2ed0b928..90fc162c 100644 --- a/tests/unit/agents/io/api/eventing/test_dapr.py +++ b/tests/unit/agents/io/api/eventing/test_dapr.py @@ -459,3 +459,24 @@ async def test_on_startup_returns_without_raising(self, dapr_eventing: DaprEvent mock_registry.get_event_handler.return_value = [handler] await dapr_eventing.on_startup() # must not raise or hang + + +class TestSharedTopicWarnings: + """S5, N19 -- the rule DaprEventing and asbs validate --group share.""" + + def test_a_topic_two_agents_declare_warns_for_the_one_that_does_not_deduplicate(self) -> None: + from blueprint.agents.io.api.eventing.dapr import shared_topic_warnings + + warnings = shared_topic_warnings( + {"orders": ["t"], "billing": ["t"], "solo": ["u"]}, {"orders": True, "billing": False, "solo": False}.get + ) + assert len(warnings) == 1 + assert "'t'" in warnings[0] and "billing run it again" in warnings[0] + + def test_false_from_an_environment_variable_is_off(self) -> None: + """It read the raw value, and the string 'false' is truthy: no warning for an agent that does not deduplicate.""" + from blueprint.agents.io.api.eventing.dapr import shared_topic_warnings + + warnings = shared_topic_warnings({"orders": ["t"], "billing": ["t"]}, {"orders": "true", "billing": "false"}.get) + assert len(warnings) == 1 + assert "billing run it again" in warnings[0] diff --git a/tests/unit/agents/io/telemetry/test_telemetry.py b/tests/unit/agents/io/telemetry/test_telemetry.py index 04706478..9a65400a 100644 --- a/tests/unit/agents/io/telemetry/test_telemetry.py +++ b/tests/unit/agents/io/telemetry/test_telemetry.py @@ -6,7 +6,7 @@ import pytest from blueprint.agents.io.telemetry.providers import agent_meter, agent_tracer, configured_namespaces, reset_providers, tracer_provider -from blueprint.agents.io.telemetry.telemetry import TelemetryManager, TracingContext +from blueprint.agents.io.telemetry.telemetry import TelemetryConfigError, TelemetryManager, TracingContext from blueprint.agents.models.config import ObservabilityConfig @@ -24,6 +24,14 @@ def _forget_providers() -> Iterator[None]: reset_providers() +@pytest.fixture(autouse=True) +def _agent_views(mock_config: MagicMock) -> None: + """An agent's view reports the agent's name, as ``Config`` does for an agent that sets none (C2).""" + mock_config.for_namespace.side_effect = lambda namespace: MagicMock( + get_observability_config=MagicMock(return_value=ObservabilityConfig(otel_service_name=namespace)) + ) + + @pytest.fixture def telemetry_manager(mock_config: MagicMock, mock_registry: MagicMock) -> TelemetryManager: """Return a TelemetryManager with mocked config.""" @@ -489,3 +497,36 @@ def test_standalone_is_unchanged(self, configure, monkeypatch: pytest.MonkeyPatc configure() assert self._name("") == "platform-wide" assert [r for r in caplog.records if r.levelname == "WARNING" and r.name.startswith("blueprint")] == [] + + def test_a_service_name_only_in_resource_attributes_fails_a_group(self, configure, monkeypatch: pytest.MonkeyPatch) -> None: + """D17 (D23 c) -- taken as declared it would name every agent alike.""" + monkeypatch.delenv("OTEL_SERVICE_NAME", raising=False) + monkeypatch.setenv("OTEL_RESOURCE_ATTRIBUTES", "service.name=platform-wide,deployment.environment=prod") + with pytest.raises(TelemetryConfigError, match="orders, billing"): + configure("orders", "billing") + + def test_with_otel_service_name_too_it_does_not(self, configure, monkeypatch: pytest.MonkeyPatch) -> None: + """OTEL_SERVICE_NAME names the root only, and the agents keep their names, as before.""" + monkeypatch.setenv("OTEL_SERVICE_NAME", "platform-wide") + monkeypatch.setenv("OTEL_RESOURCE_ATTRIBUTES", "service.name=platform-wide") + configure("orders") + assert [self._name(ns) for ns in ("", "orders")] == ["platform-wide", "orders"] + + def test_standalone_it_is_used_as_declared(self, configure, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("OTEL_SERVICE_NAME", raising=False) + monkeypatch.setenv("OTEL_RESOURCE_ATTRIBUTES", "service.name=platform-wide") + configure() + assert self._name("") == "platform-wide" + + def test_an_agents_own_otel_service_name_reaches_its_resource( + self, configure, mock_config: MagicMock, monkeypatch: pytest.MonkeyPatch + ) -> None: + """N16 -- ``.otel_service_name`` was resolved by the view and never used.""" + monkeypatch.delenv("OTEL_SERVICE_NAME", raising=False) + monkeypatch.delenv("OTEL_RESOURCE_ATTRIBUTES", raising=False) + names = {"orders": "orders", "billing": "billing-override"} + mock_config.for_namespace.side_effect = lambda namespace: MagicMock( + get_observability_config=MagicMock(return_value=ObservabilityConfig(otel_service_name=names[namespace])) + ) + configure("orders", "billing") + assert [self._name(ns) for ns in ("", "orders", "billing")] == ["test-service", "orders", "billing-override"] From 17f4033ce4115ac6d54e6c5831ba5a6f662196d9 Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Tue, 20 Oct 2026 16:18:47 +0200 Subject: [PATCH 130/133] fix: findings of the first consumer's test report on 0.9.0a16 (B1-B4) A colleague ran all 19 agents of the first consumer on 0.9.0a16 against a local backend. B1 (owner decision): the NATS publish route, which has no authentication, refuses a subject one of the agent's tenants owns -- claimed by the connection source, or filtered or delivered to by a tenant binding -- with 403: an anonymous POST put an event into a tenant's stream, to run under the tenant's identity. operator_routes_enabled = false (process scope) leaves the publish and the cache routes out; Dapr's delivery route stays. B2 (regression of 1d877f2): an unset nats_url outside development is a validator notice, not an issue -- an image that validates while it is built has none yet, and every build failed. B3: the periodic health job runs late instead of being dropped (misfire_grace_time=None, coalesce); dropped runs kept the first startup verdict for 96-217 s. A refresh at the end of startup was tried and withdrawn: it paused agents whose subscriptions were still being made. B4 (owner decision: a fixed default): nats_nak_delay, default 1/5/15/30/60 s per redelivery, 0 for the old behaviour; all attempts used to be spent within 0.3 s. A degraded agent's hand-back stays immediate. This also fixes the pre-existing test_the_broker_counts_it_as_a_redelivery. Live in WSL, against 33fb329 as control: first redelivery after 0.00 s before, 1 s and 5 s now; publish to a tenant subject 200 before, 403 now; asbs validate exit 1 before, 0 with a notice now. Integration 73 of 73. Plan: docs/plans/2026-10-16-pr96-review-fixes.md, step 23. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 24 +++- docs/plans/2026-10-16-pr96-review-fixes.md | 14 +++ .../agent_generator/cli/commands/validate.py | 15 ++- .../docs/concepts/event-processing.md | 4 +- .../docs/guides/cli/validate.md | 8 +- .../agent_generator/docs/guides/deployment.md | 12 +- .../docs/reference/configuration-keys.md | 4 +- src/blueprint/agents/app_builder.py | 24 +++- .../agents/clients/io/nats_client.py | 118 ++++++++++++++++- src/blueprint/agents/config/config.py | 1 + .../io/api/actuators/health/health_cache.py | 8 +- src/blueprint/agents/io/api/eventing/nats.py | 22 ++++ .../test_acknowledgement_lifecycle.py | 24 +++- tests/integration/test_named_connections.py | 26 ++++ .../commands/test_validate_group_runtime.py | 10 +- .../commands/test_validate_runtime_parity.py | 9 +- .../app_builder/test_route_namespacing.py | 25 ++++ .../agents/clients/io/test_nats_client.py | 119 ++++++++++++++++++ .../api/actuators/health/test_health_cache.py | 13 ++ tests/unit/agents/io/api/eventing/conftest.py | 1 + .../unit/agents/io/api/eventing/test_nats.py | 14 +++ 21 files changed, 466 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 93a29bdc..095831ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -188,6 +188,17 @@ Full migration path, including the one decision to get right before the first de `JetStreamBindingError` for the clash), `StreamConflictError`, `JetStreamPermissionError`, `TenancyError`; `JetStreamUnavailableError` is one too. A missing binding-mode stream is still retried (Known issues). +20. **A failed JetStream delivery comes back after a delay.** A `RetryableHandlerError`, any + unexpected exception and `nats_handler_timeout` used to nak for immediate redelivery, so every + attempt was used up within a few hundred milliseconds -- measured: 5 attempts in 0.3 s -- and a + backend restart or a 5xx outlasted them all. The new `nats_nak_delay` (agent scope) defaults to + 1 s, 5 s, 15 s, 30 s, then 60 s per redelivery; `0` restores the old behaviour. A degraded + agent still hands its buffered deliveries back at once. +21. **The NATS publish route refuses a tenant's subject.** With a connection source, + `POST .../events/{topic}` answers 403 for a subject the source claims for the agent or a tenant + binding filters or delivers to: the route has no authentication, and an event put into a + tenant's stream ran under that tenant's identity. `operator_routes_enabled = false` (process + scope) leaves the publish route and the cache routes out altogether. 19. **An orphaned agent takes the pod out, whatever `readiness_policy` says.** An agent latched down -- its startup failed and recovery retries it, or its transport failed for good -- now gates readiness under `"critical"` and `"any"` too: it consumes nothing for a reason that is not @@ -240,7 +251,7 @@ Full migration path, including the one decision to get right before the first de messages; keep `nats_max_ack_pending` near replicas x this value. - **`nats_heartbeat_enabled`** (bool, default `true`): switches the delivery heartbeat off for an agent. - **`nats_handler_timeout`** (seconds, unset by default): the longest one run may take. At the limit the - run is cancelled and nak'd for immediate redelivery; a `TimeoutError` of the handler's own is an + run is cancelled and nak'd for redelivery after `nats_nak_delay`; a `TimeoutError` of the handler's own is an ordinary failure. Unset, a run is never cut. - **`RestApiBase.path_prefix`**, an optional class attribute putting every route of an API under one segment -- `/api/reports/...` standalone, `/api//reports/...` in a group. Default `""`, @@ -390,6 +401,17 @@ Full migration path, including the one decision to get right before the first de ### Fixed +- **`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 + process still refuses to start without one. + +- **Readiness follows a healthy start within seconds.** The periodic health check is an + APScheduler job, and APScheduler dropped a run that started more than 1 s late; every dropped run + kept the verdict of the first startup moment -- AI clients "not initialized", agents paused -- + for another interval: measured 96 to 217 s after a start. A late run now runs, and runs missed + meanwhile are folded into one. + - **Under Dapr, a shared topic is warned about when `idempotency_enabled` is `"false"`.** The startup check for a topic two agents declare read the raw value, and the string `"false"` an environment variable can deliver counts as true, so an agent that does not deduplicate went diff --git a/docs/plans/2026-10-16-pr96-review-fixes.md b/docs/plans/2026-10-16-pr96-review-fixes.md index 802124ae..e5694cfd 100644 --- a/docs/plans/2026-10-16-pr96-review-fixes.md +++ b/docs/plans/2026-10-16-pr96-review-fixes.md @@ -317,6 +317,20 @@ Must-fix and blockers first (steps 1-14), then hardening (15-20), then documenta - **22d N15** checked and decided; **22e N19** -- the runtime rules the validator restates become public and the validator calls them. +23. **Findings of the first consumer's test report** (2026-10-20, 19 agents on 0.9.0a16 against a + local backend). B2 (regression of 22e/`ab6bd74`): an unset `nats_url` outside development is a + validator notice, not an issue -- an image that validates while it is built has none yet. B3: + the health job runs late instead of being dropped (`misfire_grace_time=None`, `coalesce`). A + refresh at the end of startup, the report's other suggestion, was tried and withdrawn: it caught + the subscriptions still being made, the supervisor read that as a transition and paused the agent + mid-subscribe (integration tests timed out). Why each run started ~2.7 s late in their setup is + not explained. B4 also fixed the pre-existing `test_the_broker_counts_it_as_a_redelivery`. B4 (owner, 2026-10-20: a fixed default, not opt-in): `nats_nak_delay`, + default 1/5/15/30/60 s; a degraded agent's hand-back stays immediate. B1 (owner, 2026-10-20): + the publish route refuses a subject the agent's tenants own (403) and `operator_routes_enabled` + switches the publish and cache routes off; authentication stays the deployment's. Checked for + this agent's own tenants only -- another agent's tenant subjects are the process account's + permissions to deny. + --- ## 3. Decisions diff --git a/src/blueprint/agent_generator/cli/commands/validate.py b/src/blueprint/agent_generator/cli/commands/validate.py index bea3c1e2..e232dd5e 100644 --- a/src/blueprint/agent_generator/cli/commands/validate.py +++ b/src/blueprint/agent_generator/cli/commands/validate.py @@ -22,6 +22,7 @@ from blueprint.agents.clients.io.nats_client import ( CONNECTIONS_READINESS_MODES, resolve_heartbeat_enabled, + resolve_nak_delays, resolve_nats_url, resolve_root_queue_group, validate_durable_name, @@ -795,6 +796,7 @@ def transport_findings(agent_dir: Path, *, view: SettingsView, settings: Process return [], warnings, [] issues: list[str] = [] + notices: list[str] = [] try: resolve_nats_url( view.get("nats_url", ""), @@ -802,13 +804,16 @@ def transport_findings(agent_dir: Path, *, view: SettingsView, settings: Process override_variable=f"{settings.override_variable_prefix}NATS_URL", ) except ValueError as exc: - issues.append(f"{named}{exc}") + # A notice, not an issue, as for 'event_bus': nats_url is container topology the deployment + # injects when the container starts, so a check that runs while the image is built cannot + # see it -- and failed every image build that validates there (B2). Startup still refuses. + notices.append(f"{named}{exc} Startup fails unless the deployment sets it.") try: resolve_heartbeat_enabled(view.get("nats_heartbeat_enabled", True)) except ValueError as exc: issues.append(f"{named}{exc}") if not consumes: - return issues, warnings, [] + return issues, warnings, notices if not agent: # A namespaced client's queue group is its namespace; only the root reads these keys. @@ -828,7 +833,7 @@ def transport_findings(agent_dir: Path, *, view: SettingsView, settings: Process validate_durable_name(durable, count) except ValueError as exc: issues.append(f"{named}{exc}") - return issues, warnings, [] + return issues, warnings, notices def process_findings(settings: ProcessSettings) -> Findings: @@ -858,6 +863,10 @@ def nats_value_findings(project_dir: Path, view: SettingsView) -> list[str]: if timeout is not None and timeout != "": if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or timeout <= 0: issues.append(f"'nats_handler_timeout' must be a number of seconds above 0, got {timeout!r}. Unset it for no limit.") + try: + resolve_nak_delays(view.get("nats_nak_delay")) + except ValueError as exc: + issues.append(str(exc)) readiness = view.get("nats_connections_readiness") if readiness is not None and str(readiness).strip().lower() not in CONNECTIONS_READINESS_MODES: issues.append(f"'nats_connections_readiness' must be one of {', '.join(CONNECTIONS_READINESS_MODES)}, got {readiness!r}.") diff --git a/src/blueprint/agent_generator/docs/concepts/event-processing.md b/src/blueprint/agent_generator/docs/concepts/event-processing.md index 102dcab3..b9f0eca4 100644 --- a/src/blueprint/agent_generator/docs/concepts/event-processing.md +++ b/src/blueprint/agent_generator/docs/concepts/event-processing.md @@ -297,7 +297,7 @@ lost -- nothing redelivers it and nothing records it. |---------|-------------| | The handler chain returned and every result was published, including "no handler matched" | `ack` | | A result could not be published | `nak` -- the handler runs again on redelivery; with deduplication on, its marker is released first | -| `RetryableHandlerError`, or any unexpected exception | `nak` -- redelivered at once, not after `nats_ack_wait` | +| `RetryableHandlerError`, or any unexpected exception | `nak` with `nats_nak_delay` -- by default redelivered after 1 s, then 5, 15, 30 and 60 s, not after `nats_ack_wait` | | `InvalidEventError` or `CriticalHandlerError` | dead-lettered, then `term` | | The payload is not a parseable CloudEvent | dead-lettered, then `term` | | The last delivery `nats_max_deliver` allows failed again (only when `nats_max_deliver` is set) | dead-lettered, then `term` | @@ -334,7 +334,7 @@ heartbeat. `nats_heartbeat_enabled = false` switches the heartbeat off for an ag **A run can be bounded.** The heartbeat proves the process is alive, not that the run makes progress: a hung model request would hold its slot -- and, with one run per subscription, every later event of that subscription -- forever. `nats_handler_timeout` cancels a run at the limit and naks its delivery -for immediate redelivery, up to `nats_max_deliver` attempts. Whether the limit was hit is read from +for redelivery after `nats_nak_delay`, up to `nats_max_deliver` attempts. Whether the limit was hit is read from the run's own timer: a `TimeoutError` raised by the handler is an ordinary failure. An existing consumer is never rewritten. Its filter subject and deliver group are broker-side diff --git a/src/blueprint/agent_generator/docs/guides/cli/validate.md b/src/blueprint/agent_generator/docs/guides/cli/validate.md index 9bbf9b00..207738e6 100644 --- a/src/blueprint/agent_generator/docs/guides/cli/validate.md +++ b/src/blueprint/agent_generator/docs/guides/cli/validate.md @@ -100,9 +100,11 @@ NATS (per agent with `--group`): `nats_unclaimed_subjects`, and `nats_connection_source` (form, and its module found). Checked whatever `event_bus` the files say, because the deployment can set it; a value from the image is reported once, an agent's own value under the agent's name -- With `event_bus = "nats"`, for an agent that consumes or publishes: `nats_url` is set outside - `development` (a `DYNACONF_NATS_URL` in the environment counts), `nats_heartbeat_enabled` is a - boolean, and one `nats_durable_name` does not serve several topics under JetStream +- With `event_bus = "nats"`, for an agent that consumes or publishes: `nats_heartbeat_enabled` is a + boolean, and one `nats_durable_name` does not serve several topics under JetStream. An unset + `nats_url` outside `development` is a **notice**, not an issue: the deployment usually injects it + when the container starts (`DYNACONF_NATS_URL`), so a validation that runs while the image is + built cannot see it -- and the process still refuses to start without one - Standalone, the queue group (`nats_queue_group`, else `app_name`) can appear in a subject: no whitespace, `*` or `>`. A grouped agent's queue group is its name, which is checked as a namespace diff --git a/src/blueprint/agent_generator/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md index 342494af..976a3749 100644 --- a/src/blueprint/agent_generator/docs/guides/deployment.md +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -352,8 +352,8 @@ scaling out and regrouping are independent of each other. | Outcome | Disposition | |---|---| | Handled, skipped (`HandlerResult.skipped`), or no handler matched it | **ack** -- none of them is a failure | -| A retryable failure | **nak**, redelivered at once (no delay is set) | -| A run that exceeded `nats_handler_timeout` | cancelled and **nak**'d for immediate redelivery | +| A retryable failure | **nak**, redelivered after `nats_nak_delay` (by default 1 s, then 5, 15, 30, 60 s) | +| A run that exceeded `nats_handler_timeout` | cancelled and **nak**'d, redelivered after `nats_nak_delay` | | A poison payload, or a `CriticalHandlerError` | **term**, and dead-lettered | | `nats_max_deliver` attempts exhausted | dead-lettered | @@ -560,6 +560,14 @@ with any section under it, a URL's userinfo, secret query parameters (`token=`, `Name=value` segments of connection strings (`AccountKey=`); a URL whose userinfo cannot be told from the rest is masked whole. Treat it as an operator endpoint all the same. +**Routes without authentication.** The framework authenticates no route. Two of them act on the +broker or a cache: NATS's `POST /events/{topic}` (`/api//nats/events/{topic}` in a group) +publishes whatever it is given, and `/cache/*` reads and evicts cache entries. Keep the port off the +public network, or set `operator_routes_enabled = false` to leave both out. With a connection +source, the publish route refuses a subject one of the agent's tenants owns (403): an event put into +a tenant's stream there would run under that tenant's identity. Grant the process's own NATS +account no publish rights on tenant subjects either. + ### `readiness_policy` A process-scope key -- one pod has one readiness probe: diff --git a/src/blueprint/agent_generator/docs/reference/configuration-keys.md b/src/blueprint/agent_generator/docs/reference/configuration-keys.md index 842b9aef..74b83ea7 100644 --- a/src/blueprint/agent_generator/docs/reference/configuration-keys.md +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -49,7 +49,8 @@ Settings for the event bus transport layer. | `nats_max_concurrent_runs` | `int` or `"N%"` | unset -- one run at a time per subscription, as before the key existed | How many deliveries one (agent, connection) pair runs at once, per process. The pair's **first** run is always allowed and counts against no limit; every further run also needs a free slot of `nats_extra_runs_per_process`. A percentage is taken of the (agent, connection) pairs the process consumes on, at least 1. An agent that waits on a model or an API gains the most from raising it; every run shares the process's one event loop, so CPU-heavy handlers gain little. | | `nats_extra_runs_per_process` | `int` or `"N%"` | unset -- unlimited | **Process scope.** The pool of runs beyond each pair's guaranteed one, shared by every agent and connection of the process; a percentage is taken of the current number of pairs. It is what keeps a burst on many pairs from overloading the event loop while an idle pair still never waits. `0` allows no runs beyond the guaranteed ones. | | `nats_connection_source` | `str` | unset -- the agent consumes on its one connection, as before | **Process scope.** `"package.module:attribute"` naming a factory that is called with the process `Config` and returns a `ConnectionSource` (`blueprint.agents.clients.io.nats_connections`). The source lists named connections -- each with its own URL and account -- and, per agent and connection, a `JetStreamBinding`: which declared subjects the connection serves, the subject prefix, and the deployment's durable consumer with its wire values verbatim. Those subjects leave the agent's default connection. Each delivery from a named connection is checked by the source's `validate` before anything runs (a reason terminates it), runs in an empty context inside the source's `run_scope`, and is settled on the connection it arrived on; the handler sees the subject without the prefix and the connection's name under the context key `nats_connection`. JetStream only. An agent with named connections may not map handler results to topics. A source that also defines `watch(notify)` is followed at runtime: connections added, changed or removed are applied while the agent runs (`subscription_change_grace`); a changed connection keeps delivering on its old link until the new one is bound, however often it changes in between, and a change of its `tls` context alone is not applied. A subscription the broker refuses (a deliver subject the account may not subscribe to) reads as `retrying` with a permission violation and is retried, never as bound. A wrong path fails startup. | -| `nats_handler_timeout` | `float` | unset -- no limit | Seconds one run may take, on every connection of the agent. At the limit the run is cancelled and its delivery nak'd for immediate redelivery, so a hung model request no longer holds its slot forever; after `nats_max_deliver` attempts the delivery is given up as usual. A `TimeoutError` the handler raises itself is an ordinary failure. A handler that catches the cancellation and carries on keeps its slot until it returns, which is logged, and its delivery is nak'd all the same. Set it above the longest legitimate run. | +| `nats_nak_delay` | `float` or list of `float` | `[1, 5, 15, 30, 60]` | Seconds before a failed JetStream delivery is redelivered: one number for every redelivery, or one per redelivery with the last repeating. `0` redelivers at once, as before the key existed. Without a delay a backend restart, a 5xx or a short network fault used up every attempt within a few hundred milliseconds. A degraded agent still hands its buffered deliveries back at once. Agent scope. | +| `nats_handler_timeout` | `float` | unset -- no limit | Seconds one run may take, on every connection of the agent. At the limit the run is cancelled and its delivery nak'd for redelivery after `nats_nak_delay`, so a hung model request no longer holds its slot forever; after `nats_max_deliver` attempts the delivery is given up as usual. A `TimeoutError` the handler raises itself is an ordinary failure. A handler that catches the cancellation and carries on keeps its slot until it returns, which is logged, and its delivery is nak'd all the same. Set it above the longest legitimate run. | | `subscription_change_grace` | `float` | `event_client_drain_timeout` | Seconds the runs of a named connection that is removed or replaced at runtime get to finish. A run still going after that is revoked: it is never acked or nak'd -- the delivery stays with the broker and returns after `ack_wait` -- its heartbeat stops, and a `publish` from it raises `DeliveryRevokedError`; it is not cancelled. | | `nats_connections_readiness` | `str` | `"never"` | Only with a `nats_connection_source`; agent scope. Whether the agent's named connections count for its readiness: `"never"` -- they never make it not ready; `"any"` -- ready while at least one named connection is bound (none at all counts as not ready); `"all"` -- ready only while every named connection is bound. Any other value fails startup, naming the key. **Readiness only, in every mode:** a named connection that is down never pauses the agent, so its other connections keep delivering. Each connection's state (`bound`, `connecting`, `reconnecting`, `retrying` with the last error, `paused`, and a permission violation if one was seen) is listed in the readiness entry `.nats_client:connections` in every mode, and the gauge `blueprint.nats.connection.bound` reports it. The agent's default connection keeps its behaviour. | | `nats_unclaimed_subjects` | `str` | `"fail"` | Only with a `nats_connection_source`. What happens to a declared subject the source does not `claims()` for the agent: `"fail"` -- the agent's startup fails, naming the subjects; `"default_connection"` -- consumed on the agent's own connection (the explicit hybrid mode; the process account must then be allowed to subscribe them). A claimed subject never goes to the default connection, even while no named connection serves it yet. | @@ -254,6 +255,7 @@ Additional logging behavior settings. | Key | Type | Default | Description | |-----|------|---------|-------------| +| `operator_routes_enabled` | `bool` | `true` | Whether the routes that act without authentication are served: NATS's `POST .../events/{topic}` and `.../cache/*`. `false` leaves them out of the application; Dapr's `/events/{topic}` stays, it is how the sidecar delivers. Process scope. | | `readiness_policy` | `str` | `"all"` | Which agents gate `/health/ready`: `"all"`, `"critical"` (only the agents the group flagged critical) or `"any"` (ready while one is up). The root gates readiness under every policy, and so does an agent latched down (its startup failed, or its transport failed for good). Any other value fails startup. Process scope. | | `health_check_interval_seconds` | `int` | `30` | Seconds between health polls; readiness and an agent's pause or resume follow the latest poll. Process scope. | | `event_loop_debug` | `bool` | `false` | asyncio debug mode, which names a blocking callback and its source. Off unless set, in every environment; with it on, the watchdog does not run. Read as a boolean (`"false"` from the environment means false); any other value fails startup. | diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index d088bedf..f06126b7 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -60,6 +60,12 @@ from .io.telemetry.telemetry import TelemetryConfigError from .utils import parse_bool +OPERATOR_ROUTES_KEY = "operator_routes_enabled" +"""Process scope, default true: whether the NATS publish route and the cache routes are served (B1). + +They act on the broker and on a cache without authentication, which a deployment whose port is +reachable from outside may not want at all. ``false`` leaves them out of the application.""" + _UNCONSTRUCTED_KINDS = frozenset({"cache", "health_checker"}) """Declaration kinds the replay pass does not construct. @@ -1193,8 +1199,17 @@ def _publishing_requested(self, namespace: str = ROOT_NAMESPACE) -> bool: return parse_bool(raw, "event_publishing_enabled") def _build_rest_endpoints(self, app: FastAPI, registry: Registry) -> None: - """Include all routers into the FastAPI app.""" + """Include all routers into the FastAPI app. + + ``operator_routes_enabled = false`` leaves out the routes that act on the broker or a cache + without authentication -- NATS's ``POST .../events/{topic}`` and ``.../cache/*`` (B1). Dapr's + ``/events/{topic}`` stays: it is how the sidecar delivers. + """ app.include_router(RootApi(app=app).router, tags=["root"]) + raw = self._require_config().get(OPERATOR_ROUTES_KEY, None) + operator_routes = True if raw is None or (isinstance(raw, str) and not raw.strip()) else parse_bool(raw, OPERATOR_ROUTES_KEY) + if not operator_routes: + logger.info("'%s' is false: the NATS publish and the cache routes are not served", OPERATOR_ROUTES_KEY) for rest_api in registry.get_rest_apis(): # No blanket `tags=["rest"]`: it stamps every operation with a redundant "rest" tag on @@ -1206,9 +1221,11 @@ def _build_rest_endpoints(self, app: FastAPI, registry: Registry) -> None: self._mount(app, rest_api, root_prefix="/api") for eventing_component in self._eventing_components: + if not operator_routes and isinstance(eventing_component, NatsEventing): + eventing_component.drop_publish_route() self._mount(app, eventing_component, root_prefix="") - for namespace in self._cache_owners(registry): + for namespace in self._cache_owners(registry) if operator_routes else []: # One router per agent that has a cache, mounted under that agent's prefix, so # ``/api/orders/cache/stats`` reports the orders agent's cache and nothing else. # A process-wide endpoint would report one agent's keys to another, which is the @@ -1697,6 +1714,9 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]: await self._start_component("Lifecycle component", lifecycle_component, type(lifecycle_component).__name__) self._start_startup_recovery(startup_retry_interval) + # No health refresh here (B3, tried and measured): the subscriptions are still being made, + # so the client reads "not yet established", the supervisor sees a transition and pauses + # the agent mid-subscribe. The periodic job, which no longer drops a late run, follows. logger.info("Application startup completed") yield diff --git a/src/blueprint/agents/clients/io/nats_client.py b/src/blueprint/agents/clients/io/nats_client.py index a910b934..2a97919a 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -122,6 +122,15 @@ class TenancyError(DeterministicTransportError): CONTROL_MESSAGE_STATUS = "100" """The status a JetStream idle heartbeat and flow control request carry (``nats.js.api.StatusCode.CONTROL_MESSAGE``).""" +NAK_DELAY_KEY = "nats_nak_delay" +"""Seconds before a failed JetStream delivery comes back: one number, or one per redelivery (B4).""" + +DEFAULT_NAK_DELAYS: tuple[float, ...] = (1.0, 5.0, 15.0, 30.0, 60.0) +"""The redelivery delays when ``nats_nak_delay`` is unset: the first redelivery after 1 s, the second +after 5 s, then 15 s, 30 s, and 60 s for every one after that. With ``max_deliver = 5`` a failing +event is retried over about 51 s rather than within a few hundred milliseconds: a backend restart, a +5xx or a short network fault used to use up every attempt before it had passed.""" + RESUME_RETRY_MAX_DELAY = 60.0 """The longest wait between two attempts of a resume that keeps failing (M2): the delay doubles from ``event_client_retry_delay`` up to this.""" @@ -234,6 +243,38 @@ def validate_durable_name(configured: str, topic_count: int) -> None: ) +def resolve_nak_delays(raw: object) -> tuple[float, ...]: + """``nats_nak_delay`` as one delay per redelivery, the last one repeating (B4); shared with ``asbs validate``. + + Unset is :data:`DEFAULT_NAK_DELAYS`. A number applies to every redelivery; ``0`` redelivers at + once, as before this key existed. A list gives the delay before the first, second, ... + redelivery. + + Raises: + ValueError: anything but a number of seconds, or a non-empty list of them, none negative. + A boolean is refused rather than read as 1. + """ + if raw is None or raw == "": + return DEFAULT_NAK_DELAYS + values = list(raw) if isinstance(raw, (list, tuple)) else [raw] + delays: list[float] = [] + for value in values: + if isinstance(value, bool) or not isinstance(value, (int, float, str)): + delays = [] + break + try: + delays.append(float(value)) + except ValueError: + delays = [] + break + if not delays or any(delay < 0 for delay in delays): + raise ValueError( + f"'{NAK_DELAY_KEY}' must be a number of seconds or a non-empty list of them, none negative, got {raw!r}. " + "0 redelivers a failed event at once." + ) + return tuple(delays) + + DEAD_LETTERED_COUNTER = "blueprint.events.dead_lettered" """Events the framework gave up on, whether or not their payload was kept. @@ -474,8 +515,10 @@ class NATSClient(IOClientBase): ``nats_heartbeat_enabled`` (bool, default true): whether running JetStream deliveries report ``in_progress``; off, a run longer than the consumer's ``ack_wait`` is redelivered while it runs. ``nats_handler_timeout`` (float seconds, unset by default): the longest one run may take, on - every connection. At the limit the run is cancelled and nak'd for immediate redelivery; unset, - a run is never cut. + every connection. At the limit the run is cancelled and nak'd for redelivery after + ``nats_nak_delay``; unset, a run is never cut. + ``nats_nak_delay`` (seconds, or a list per redelivery; default 1, 5, 15, 30, 60): how long a + failed delivery waits before it is redelivered; ``0`` redelivers at once. Concurrent runs ~~~~~~~~~~~~~~~ @@ -525,6 +568,7 @@ def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: self._pairs_registered = 0 self._heartbeat_enabled: bool = True self._handler_timeout: float | None = None + self._nak_delays: tuple[float, ...] = DEFAULT_NAK_DELAYS self._source: ConnectionSource | None = None self._named: list[_Binding] = [] self._named_tasks: dict[_Binding, asyncio.Task[None]] = {} @@ -698,6 +742,37 @@ def connections_readiness(self) -> str: self._connections_readiness = self._resolve_connections_readiness() return self._connections_readiness + def tenant_subject(self, topic: str) -> str | None: + """Why ``topic`` belongs to one of this agent's tenants, or ``None`` (B1). + + A subject the connection source claims for this agent, or one a tenant binding filters on + or delivers to -- the bindings in place and the ones the source would hand over now. A + publish there on the agent's default connection lands in the tenant's stream and runs under + the tenant's identity, which is what plan D4 already refuses for handler results. A source + that cannot be asked counts as owning the subject: refusing is the safe answer. + + Args: + topic: A subject to publish to. + """ + if self._source is None: + return None + owners: dict[str, str] = dict.fromkeys(self._claimed, "the connection source claims it") + bindings = [binding.jetstream for binding in self._named if binding.jetstream is not None] + try: + for spec in self._source.connections().values(): + jetstream = self._source.binding(self._queue_group, tuple(self._declared), spec) + if jetstream is not None: + bindings.append(jetstream) + except Exception as exc: + return f"the connection source could not be asked which subjects its tenants own ({type(exc).__name__})" + for jetstream in bindings: + for subject in (*jetstream.filter_subjects, jetstream.deliver_subject): + owners.setdefault(subject, f"a tenant binding on stream '{jetstream.stream}' carries it") + for pattern, why in owners.items(): + if topic == pattern or subject_is_covered_by(topic, pattern): + return f"'{topic}' is a tenant subject: {why} ('{pattern}')" + return None + def named_connection_states(self) -> tuple[NamedConnectionState, ...]: """How each current named connection stands, in the source's order; one being replaced is left out.""" return tuple(self._state_of(binding) for binding in self._named if not binding.superseded) @@ -838,6 +913,7 @@ async def subscribe(self, topic_callbacks: dict[str, DeliveryCallback]) -> None: self._binding.limit = self._max_concurrent_runs self._heartbeat_enabled = self._resolve_heartbeat_enabled() self._handler_timeout = self._resolve_handler_timeout() + self._nak_delays = self._resolve_nak_delays() self._change_grace = self._resolve_change_grace() self._connections_readiness = self._resolve_connections_readiness() self._declared = dict(topic_callbacks) @@ -1654,6 +1730,22 @@ def _resolve_heartbeat_enabled(self) -> bool: """ return resolve_heartbeat_enabled(self.config.get("nats_heartbeat_enabled", True)) + def _resolve_nak_delays(self) -> tuple[float, ...]: + """Return ``nats_nak_delay`` for this agent; see :func:`resolve_nak_delays`. + + Raises: + ValueError: as :func:`resolve_nak_delays` does, naming the agent. + """ + try: + return resolve_nak_delays(self.config.get(NAK_DELAY_KEY, None)) + except ValueError as exc: + raise ValueError(f"{exc} (agent '{self.namespace or ROOT_LABEL}')") from None + + def _nak_delay(self, msg: Any) -> float: + """The delay before this failed delivery comes back: by its delivery count, the last delay repeating.""" + delivered = self._delivery_count(msg) or 1 + return self._nak_delays[min(delivered, len(self._nak_delays)) - 1] + def _resolve_handler_timeout(self) -> float | None: """Return ``nats_handler_timeout``: seconds one run may take, or ``None`` for no limit (plan D9). @@ -2836,7 +2928,7 @@ async def message_handler(msg: Any) -> None: # the buffer while the pause waits for a connection change to finish, before it # can drain -- is nak'd at once, so it redelivers to a healthy replica (N4). Core # NATS cannot nak; its buffered messages run, as the drain lets them. - await self._settle(msg, DeliveryDisposition.NAK, msg.subject, self._peek_event_id(msg), binding) + await self._settle(msg, DeliveryDisposition.NAK, msg.subject, self._peek_event_id(msg), binding, delayed=False) return resolved = topic if topic is not None else self._bound_topic(binding, msg) if resolved is None: @@ -2941,7 +3033,7 @@ async def _run_delivery(self, msg: Any, topic: str, callback: DeliveryCallback, Everything is settled against ``binding``, the one the message arrived on. With ``nats_handler_timeout`` set, a run that reaches the limit is cancelled and nak'd for - immediate redelivery (plan D9). Whether the limit was hit is read from the run's own timer, + redelivery after ``nats_nak_delay`` (plan D9, B4). Whether the limit was hit is read from the run's own timer, not from the exception: a ``TimeoutError`` the handler raises itself is an ordinary failure. A handler that swallows the cancellation runs on and holds its slot until it returns; that is logged, and its delivery is nak'd all the same. @@ -3142,7 +3234,14 @@ async def _keep_alive(msg: Any, interval: float) -> None: # ------------------------------------------------------------------ async def _settle( - self, msg: Any, disposition: DeliveryDisposition, topic: str, event_id: str | None, binding: _Binding | None = None + self, + msg: Any, + disposition: DeliveryDisposition, + topic: str, + event_id: str | None, + binding: _Binding | None = None, + *, + delayed: bool = True, ) -> None: """Tell the broker what became of a delivery (spec sec. 7.2). @@ -3163,6 +3262,12 @@ async def _settle( redelivers and the message leaves the consumer with no trace of why. Terming it here keeps the payload, on the dead-letter subject, and releases the consumer's pending slot immediately instead of one more ``ack_wait`` later. + + A nak waits ``nats_nak_delay`` before the broker redelivers (B4): a failed run usually failed + on something that needs a moment -- a restarting backend, a 5xx, a dropped connection -- and + an immediate redelivery used up every attempt within a few hundred milliseconds. ``delayed`` + is ``False`` only where the delivery should go elsewhere at once: a degraded agent hands its + buffered deliveries back to a healthy replica (N4). """ binding = binding or self._binding if not self._settles(binding): @@ -3172,7 +3277,8 @@ async def _settle( if disposition is DeliveryDisposition.ACK: await msg.ack() elif disposition is DeliveryDisposition.NAK and not self._deliveries_exhausted(msg, binding): - await msg.nak() + delay = self._nak_delay(msg) if delayed else 0.0 + await (msg.nak(delay=delay) if delay > 0 else msg.nak()) else: await self._dead_letter(msg, disposition, topic, event_id, binding) await msg.term() diff --git a/src/blueprint/agents/config/config.py b/src/blueprint/agents/config/config.py index b05177a7..54da72d1 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -79,6 +79,7 @@ class ConfigError(Exception): "health_check_interval_seconds", "startup_retry_interval_seconds", "readiness_policy", + "operator_routes_enabled", "dot_placeholder", "nats_stream_name", "nats_connection_source", diff --git a/src/blueprint/agents/io/api/actuators/health/health_cache.py b/src/blueprint/agents/io/api/actuators/health/health_cache.py index fe77bfd1..b0a37d3c 100644 --- a/src/blueprint/agents/io/api/actuators/health/health_cache.py +++ b/src/blueprint/agents/io/api/actuators/health/health_cache.py @@ -104,13 +104,19 @@ async def start(self) -> None: # Run initial check immediately await self._run_health_checks() - # Schedule periodic checks + # Schedule periodic checks. A late run is run, not dropped (B3): APScheduler skips a run that + # starts more than misfire_grace_time (default 1 s) late, and every skipped run kept the + # verdict of the first startup moment -- agents paused, readiness DOWN -- for another + # interval; measured 96 to 217 s after a start. coalesce folds runs missed meanwhile into one. self._scheduler.add_job( self._run_health_checks, trigger=IntervalTrigger(seconds=self.check_interval_seconds), id="health_check_job", name="Periodic health check", replace_existing=True, + misfire_grace_time=None, + coalesce=True, + max_instances=1, ) self._scheduler.start() diff --git a/src/blueprint/agents/io/api/eventing/nats.py b/src/blueprint/agents/io/api/eventing/nats.py index e6e3b246..c2b46c86 100644 --- a/src/blueprint/agents/io/api/eventing/nats.py +++ b/src/blueprint/agents/io/api/eventing/nats.py @@ -3,6 +3,9 @@ import logging from typing import Any +from fastapi import HTTPException, status +from fastapi.routing import APIRoute + from ....clients.client_base import DeliveryCallback from ....clients.io.nats_client import NATSClient from ....clients.io.nats_connections import NATS_CONNECTION_CONTEXT_KEY, current_connection, current_delivery @@ -156,19 +159,38 @@ async def _process_event(event: CloudEvent[Any], subject: str) -> None: return _process_event + def drop_publish_route(self) -> None: + """Remove ``POST /events/{topic}`` before mounting, for ``operator_routes_enabled = false`` (B1).""" + self.router.routes[:] = [route for route in self.router.routes if not (isinstance(route, APIRoute) and route.name == "publish")] + @RestApiBase.post("/events/{topic}", tags=["nats"]) async def publish(self, topic: str, event: CloudEvent[Any]) -> dict[str, Any]: """Publish a CloudEvent to a NATS topic. + **A tenant's subject is refused** (B1): the route has no authentication of its own, and a + subject a tenant connection owns would put the event into that tenant's stream, to run under + the tenant's identity -- the reason plan D4 refuses handler results on such an agent. Turn + the route off altogether with ``operator_routes_enabled = false``. + Args: topic: The topic to publish to. event: The CloudEvent to publish. Returns: Success message. + + Raises: + HTTPException: 403 for a subject one of this agent's tenants owns. """ if not self._client: raise RuntimeError("NATS client not initialized") + owned = self._client.tenant_subject(topic) + if owned is not None: + logger.warning("Refused to publish event %s through the HTTP route: %s", event.id, owned) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=f"{owned}. An event published here would run under that tenant's identity; it is refused.", + ) await self._client.publish(topic, event) return {"message": f"Published event {event.id} to topic {topic}"} diff --git a/tests/integration/test_acknowledgement_lifecycle.py b/tests/integration/test_acknowledgement_lifecycle.py index bc94dff1..87dda550 100644 --- a/tests/integration/test_acknowledgement_lifecycle.py +++ b/tests/integration/test_acknowledgement_lifecycle.py @@ -8,7 +8,7 @@ | what the handler does | disposition | what the broker does | |----------------------------------|-------------|---------------------------------| | returns normally | ack | nothing more | -| raises `RetryableHandlerError` | nak | redelivers after `nats_ack_wait`| +| raises `RetryableHandlerError` | nak | redelivers after `nats_nak_delay`| | raises `CriticalHandlerError` | term | never redelivers | | raises `InvalidEventError` | term | never redelivers | | no handler matches | **ack** | nothing more | @@ -47,6 +47,8 @@ class Attempts: handler: type[EventHandlerBase] topic: str seen: list[str] = field(default_factory=list) + times: list[float] = field(default_factory=list) + """The event loop's clock at each call, for the delay between deliveries.""" @pytest.fixture @@ -60,6 +62,7 @@ def failing(subject_prefix: str) -> Any: def make(error: BaseException | None, *, matches: bool = True) -> Attempts: topic = f"{subject_prefix}.orders.created" seen: list[str] = [] + times: list[float] = [] class FailingHandler(EventHandlerBase): async def on_startup(self) -> None: @@ -76,11 +79,12 @@ async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, An async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> None: seen.append(event.id) + times.append(asyncio.get_running_loop().time()) if error is not None: raise error return None - return Attempts(handler=FailingHandler, topic=topic, seen=seen) + return Attempts(handler=FailingHandler, topic=topic, seen=seen, times=times) return make @@ -280,3 +284,19 @@ async def collect(msg: Any) -> None: assert dead.headers["Blueprint-Dead-Letter-Reason"] == "deliveries-exhausted" assert dead.headers["Blueprint-Delivery-Count"] == "3" + + +class TestARetryComesBackAfterADelay: + """B4 -- every attempt used to be spent within 0.3 s, so a backend restart outlasted them all.""" + + async def test_the_default_waits_1_then_5_seconds(self, nats_app: Any, failing: Any, jetstream: JetStreamContext) -> None: + """``nats_max_deliver = 3`` here, so three deliveries: the first, after 1 s, after 5 more.""" + attempts = failing(RetryableHandlerError(status="failed", reason="backend restarting")) + + async with nats_app(attempts.handler): + await jetstream.publish(attempts.topic, an_order().model_dump_json().encode()) + await wait_until(lambda: len(attempts.times) >= 3, timeout=20, description="three deliveries") + + first, second = attempts.times[1] - attempts.times[0], attempts.times[2] - attempts.times[1] + assert 0.9 <= first < 3.0, f"first redelivery after {first:.2f}s" + assert 4.5 <= second < 8.0, f"second redelivery after {second:.2f}s" diff --git a/tests/integration/test_named_connections.py b/tests/integration/test_named_connections.py index 4f4c87b0..7fe346ef 100644 --- a/tests/integration/test_named_connections.py +++ b/tests/integration/test_named_connections.py @@ -532,3 +532,29 @@ async def probe_settled() -> bool: assert not client.consumption_paused, "a dead named connection never pauses the agent" sent = await publish(accounts_url, subject_prefix, "A", "risk.created") await wait_until(lambda: sent in [run["id"] for run in runs], timeout=10, description="A to keep delivering") + + +class TestThePublishRouteRefusesATenantSubject: + """B1 -- an anonymous POST put an event into a tenant's stream, to run under the tenant's identity.""" + + async def test_403_for_a_tenant_subject_and_nothing_runs( + self, settings_group: Any, operator: Operator, accounts_url: str, subject_prefix: str + ) -> None: + agent = f"risk_{subject_prefix}" + await operator(["A"], {agent: ["risk.>"]}) + runs: list[dict[str, Any]] = [] + apps: list[Any] = [] + tenant_subject = f"{subject_prefix_for(subject_prefix, 'A')}risk.created" + event = {"specversion": "1.0", "id": str(uuid.uuid4()), "source": "/x", "type": "risk.created", "data": {}} + async with settings_group( + settings(accounts_url, subject_prefix, ["A"]), {agent: recording_handler(["risk.>"], runs)}, named=1, apps=apps + ): + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=apps[0]), base_url="http://it") as http: + refused = await http.post(f"/api/{agent}/nats/events/{tenant_subject}", json=event) + other = await http.post(f"/api/{agent}/nats/events/{subject_prefix}.elsewhere", json=event) + await asyncio.sleep(1.0) + + assert refused.status_code == 403, refused.text + assert "tenant subject" in refused.json()["detail"] + assert other.status_code == 200, other.text + assert runs == [], "nothing reached the tenant's stream" diff --git a/tests/unit/agent_generator/cli/commands/test_validate_group_runtime.py b/tests/unit/agent_generator/cli/commands/test_validate_group_runtime.py index 4382d3a9..e1b7b65a 100644 --- a/tests/unit/agent_generator/cli/commands/test_validate_group_runtime.py +++ b/tests/unit/agent_generator/cli/commands/test_validate_group_runtime.py @@ -244,14 +244,18 @@ def test_dedup_without_a_ttl_in_an_agent_is_an_issue(self, tmp_path: Path) -> No assert any("Agent 'orders'" in issue and "'idempotency_ttl' is not set" in issue for issue in issues) - def test_nats_without_a_url_is_an_issue_per_consuming_agent(self, tmp_path: Path) -> None: + def test_nats_without_a_url_is_a_notice_per_consuming_agent(self, tmp_path: Path) -> None: + """B2 -- the deployment injects nats_url when the container starts; a build-time check cannot see it.""" image = _image(tmp_path, "orders", image_settings='[default]\napp_name = "group"\nevent_bus = "nats"\n') (image / "agents" / "orders" / "src" / "handlers").mkdir() (image / "agents" / "orders" / "src" / "handlers" / "order_handler.py").write_text("# h\n", encoding="utf-8") - issues, _, _ = _findings(image) + issues, _, notices = _findings(image) - assert any("Agent 'orders'" in issue and "'nats_url' is not set" in issue for issue in issues) + assert not any("'nats_url' is not set" in issue for issue in issues) + assert any( + "Agent 'orders'" in notice and "'nats_url' is not set" in notice and "unless the deployment" in notice for notice in notices + ) def test_a_shared_dapr_topic_without_dedup_is_warned(self, tmp_path: Path) -> None: """Audit 6: the runtime warns at startup that one retry redelivers to every agent.""" diff --git a/tests/unit/agent_generator/cli/commands/test_validate_runtime_parity.py b/tests/unit/agent_generator/cli/commands/test_validate_runtime_parity.py index 538f77a2..c46deb25 100644 --- a/tests/unit/agent_generator/cli/commands/test_validate_runtime_parity.py +++ b/tests/unit/agent_generator/cli/commands/test_validate_runtime_parity.py @@ -257,12 +257,14 @@ def test_handlers_without_an_event_bus_are_warned(self, tmp_path: Path) -> None: assert any("no valid event_bus" in warning for warning in warnings) - def test_nats_without_a_url_in_production_is_an_issue(self, tmp_path: Path) -> None: + def test_nats_without_a_url_in_production_is_a_notice(self, tmp_path: Path) -> None: + """B2 -- an issue failed every image build that validates; the deployment sets it at container start.""" project = _project(tmp_path, '[default]\napp_name = "demo"\nevent_bus = "nats"\n', handler=True) - issues, _, _ = _findings(project) + issues, _, notices = _findings(project) - assert any("'nats_url' is not set" in issue for issue in issues) + assert not any("'nats_url' is not set" in issue for issue in issues) + assert any("'nats_url' is not set" in notice for notice in notices) def test_nats_without_a_url_in_development_falls_back(self, tmp_path: Path) -> None: project = _project(tmp_path, '[default]\napp_name = "demo"\nevent_bus = "nats"\n', handler=True) @@ -327,6 +329,7 @@ class TestTheValidatorAppliesTheRuntimesOwnRules: ("blueprint.agents.clients.io.nats_client", "resolve_heartbeat_enabled"), ("blueprint.agents.clients.io.nats_client", "resolve_root_queue_group"), ("blueprint.agents.clients.io.nats_client", "validate_durable_name"), + ("blueprint.agents.clients.io.nats_client", "resolve_nak_delays"), ("blueprint.agents.handler.handler_chain", "resolve_idempotency_policy"), ("blueprint.agents.handler.handler_chain", "dedup_redelivery_warning"), ("blueprint.agents.io.api.scheduling.scheduler", "resolve_scheduler_timezone"), diff --git a/tests/unit/agents/app_builder/test_route_namespacing.py b/tests/unit/agents/app_builder/test_route_namespacing.py index 38cf8dd8..a7406e5b 100644 --- a/tests/unit/agents/app_builder/test_route_namespacing.py +++ b/tests/unit/agents/app_builder/test_route_namespacing.py @@ -451,3 +451,28 @@ def test_no_endpoint_at_all_without_a_cache(self, cache_config: Config) -> None: app = AppBuilder(cache_config).build() assert not [path for path in paths(app) if "/cache/" in path] + + +class TestOperatorRoutesCanBeSwitchedOff: + """B1 -- the NATS publish route and the cache routes act without authentication.""" + + @staticmethod + def _off(tmp_path: Path) -> Config: + """The fixture's settings file again, with the switch off.""" + settings = tmp_path / "settings.toml" + text = settings.read_text().replace("app_port = 8000\n", "app_port = 8000\noperator_routes_enabled = false\n", 1) + settings.write_text(text) + return Config(settings_files=[str(settings)], root_path=str(tmp_path)) + + def test_they_are_served_by_default(self, nats_config: Config) -> None: + app = AgentGroup("g", {"orders": AppBuilder().with_handler(OrderHandler).with_cache()}).assemble(nats_config) + assert {"/api/orders/nats/events/{topic}", "/api/orders/cache/stats"} <= set(paths(app)) + + def test_false_leaves_them_out(self, nats_config: Config, tmp_path: Path) -> None: + app = AgentGroup("g", {"orders": AppBuilder().with_handler(OrderHandler).with_cache()}).assemble(self._off(tmp_path)) + assert not [path for path in paths(app) if "/nats/events/" in path or "/cache/" in path] + + def test_the_dapr_delivery_route_stays(self, dapr_config: Config, tmp_path: Path) -> None: + """It is how the sidecar delivers, not an operator route.""" + app = AppBuilder(self._off(tmp_path)).with_handler(OrderHandler).build() + assert "/events/{topic}" in paths(app) diff --git a/tests/unit/agents/clients/io/test_nats_client.py b/tests/unit/agents/clients/io/test_nats_client.py index c66d01bd..53837b50 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -3038,3 +3038,122 @@ async def test_the_error_callback_records_a_refused_grant(self, nats_client: NAT await nats_client._on_error(Exception("nats: permissions violation for subscription to _DELIVER.x")) await nats_client._on_error(Exception("nats: unexpected EOF")) assert nats_client._link.permission_errors == ["nats: permissions violation for subscription to _DELIVER.x"] + + +class TestAFailedRunComesBackAfterADelay: + """B4 -- all five attempts were used up within 0.3 s; a nak now waits nats_nak_delay before the redelivery.""" + + @staticmethod + async def _failing(nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, **overrides: object): + async def _callback(event: CloudEvent, subject: str) -> None: + raise RetryableHandlerError(status="error", reason="backend restarting") + + return await TestNATSClientDeadLettering._handler( + nats_client, mock_config, mock_nats_jetstream, _callback, nats_max_deliver=10, **overrides + ) + + @pytest.mark.parametrize(("delivered", "delay"), [(1, 1.0), (2, 5.0), (3, 15.0), (4, 30.0), (5, 60.0), (9, 60.0)]) + async def test_the_default_backs_off_by_delivery_count( + self, + nats_client: NATSClient, + mock_config: MagicMock, + mock_nats_jetstream: tuple, + cloud_event: CloudEvent, + delivered: int, + delay: float, + ) -> None: + handler = await self._failing(nats_client, mock_config, mock_nats_jetstream) + msg = TestNATSClientDeadLettering._msg(json.dumps(dict(cloud_event)).encode(), num_delivered=delivered) + await handler(msg) + msg.nak.assert_awaited_once_with(delay=delay) + + async def test_one_number_applies_to_every_redelivery( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + handler = await self._failing(nats_client, mock_config, mock_nats_jetstream, nats_nak_delay=2) + msg = TestNATSClientDeadLettering._msg(json.dumps(dict(cloud_event)).encode(), num_delivered=4) + await handler(msg) + msg.nak.assert_awaited_once_with(delay=2.0) + + async def test_zero_redelivers_at_once_as_before( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + handler = await self._failing(nats_client, mock_config, mock_nats_jetstream, nats_nak_delay=0) + msg = TestNATSClientDeadLettering._msg(json.dumps(dict(cloud_event)).encode()) + await handler(msg) + msg.nak.assert_awaited_once_with() + + async def test_a_paused_agent_hands_a_buffered_delivery_back_at_once( + self, nats_client: NATSClient, mock_config: MagicMock, mock_nats_jetstream: tuple, cloud_event: CloudEvent + ) -> None: + """N4 -- it should reach a healthy replica now, not after a backoff.""" + handler = await self._failing(nats_client, mock_config, mock_nats_jetstream) + nats_client._consumption_paused = True + msg = TestNATSClientDeadLettering._msg(json.dumps(dict(cloud_event)).encode()) + msg.subject = "orders.created" + await handler(msg) + msg.nak.assert_awaited_once_with() + + @pytest.mark.parametrize("value", [-1, True, "soon", [], [1, -2], {"a": 1}]) + def test_a_value_that_is_not_a_delay_is_refused(self, value: object) -> None: + from blueprint.agents.clients.io.nats_client import resolve_nak_delays + + with pytest.raises(ValueError, match="nats_nak_delay"): + resolve_nak_delays(value) + + def test_unset_is_the_default_backoff(self) -> None: + from blueprint.agents.clients.io.nats_client import DEFAULT_NAK_DELAYS, resolve_nak_delays + + assert resolve_nak_delays(None) == DEFAULT_NAK_DELAYS == (1.0, 5.0, 15.0, 30.0, 60.0) + + +class TestWhichSubjectsATenantOwns: + """B1 -- the publish route asks this before it publishes on the agent's default connection.""" + + @staticmethod + def _sourced(nats_client: NATSClient, *, raises: bool = False) -> NATSClient: + from blueprint.agents.clients.io.nats_connections import JetStreamBinding + + bound = JetStreamBinding( + subjects=("risk.>",), + stream="RISK_A", + durable="d", + deliver_subject="deliver.a.risk", + deliver_group="risk", + ack_wait=30.0, + subject_prefix="t.a.", + ) + offered = JetStreamBinding( + subjects=("risk.>",), + stream="RISK_B", + durable="d", + deliver_subject="deliver.b.risk", + deliver_group="risk", + ack_wait=30.0, + subject_prefix="t.b.", + ) + source = MagicMock() + source.connections.side_effect = RuntimeError("down") if raises else None + source.connections.return_value = {"B": MagicMock()} + source.binding.return_value = offered + nats_client._source = source + nats_client._claimed = frozenset({"risk.>"}) + nats_client._named = [_Binding(link=_Link(name="A"), jetstream=bound)] + return nats_client + + @pytest.mark.parametrize( + "topic", + ["t.a.risk.created", "deliver.a.risk", "t.b.risk.created", "risk.created"], + ids=["bound-filter", "bound-deliver", "offered-not-yet-bound", "claimed"], + ) + def test_a_tenant_subject_is_named(self, nats_client: NATSClient, topic: str) -> None: + assert self._sourced(nats_client).tenant_subject(topic) is not None + + def test_another_subject_is_not(self, nats_client: NATSClient) -> None: + assert self._sourced(nats_client).tenant_subject("orders.created") is None + + def test_without_a_source_nothing_is(self, nats_client: NATSClient) -> None: + assert nats_client.tenant_subject("t.a.risk.created") is None + + def test_a_source_that_cannot_be_asked_owns_everything(self, nats_client: NATSClient) -> None: + assert "could not be asked" in (self._sourced(nats_client, raises=True).tenant_subject("orders.created") or "") diff --git a/tests/unit/agents/io/api/actuators/health/test_health_cache.py b/tests/unit/agents/io/api/actuators/health/test_health_cache.py index 7994c48d..39a3cdf7 100644 --- a/tests/unit/agents/io/api/actuators/health/test_health_cache.py +++ b/tests/unit/agents/io/api/actuators/health/test_health_cache.py @@ -409,3 +409,16 @@ async def test_a_failing_check(self, caplog: pytest.LogCaptureFixture) -> None: with caplog.at_level("WARNING", logger="blueprint.agents.io.api.actuators.health.health_cache"): await cache._run_health_checks() assert caplog.messages == ["Health check failed for db: boom"] + + +class TestALateRunIsRunNotDropped: + """B3 -- APScheduler dropped a run starting over 1 s late, and the first startup verdict stood for minutes.""" + + async def test_the_job_has_no_misfire_limit_and_coalesces(self) -> None: + cache = HealthCheckCache(check_interval_seconds=30) + await cache.start() + try: + job = cache._scheduler.get_job("health_check_job") # type: ignore[union-attr] + assert (job.misfire_grace_time, job.coalesce, job.max_instances) == (None, True, 1) + finally: + await cache.stop() diff --git a/tests/unit/agents/io/api/eventing/conftest.py b/tests/unit/agents/io/api/eventing/conftest.py index 295ec8bb..534a19b8 100644 --- a/tests/unit/agents/io/api/eventing/conftest.py +++ b/tests/unit/agents/io/api/eventing/conftest.py @@ -56,5 +56,6 @@ def connected_nats_eventing(nats_eventing: NatsEventing) -> NatsEventing: mock_client = MagicMock() mock_client.subscribe = AsyncMock() mock_client.publish = AsyncMock() + mock_client.tenant_subject = MagicMock(return_value=None) # no tenants: every subject may be published nats_eventing._client = mock_client return nats_eventing diff --git a/tests/unit/agents/io/api/eventing/test_nats.py b/tests/unit/agents/io/api/eventing/test_nats.py index b4bc7b5b..40f4e905 100644 --- a/tests/unit/agents/io/api/eventing/test_nats.py +++ b/tests/unit/agents/io/api/eventing/test_nats.py @@ -271,3 +271,17 @@ async def test_no_topics( with caplog.at_level("INFO", logger="blueprint.agents.io.api.eventing.nats"): await nats_eventing.on_startup() assert caplog.messages == ["NatsEventing: no auto-subscriptions configured"] + + +class TestATenantSubjectIsRefused: + """B1 -- the route has no authentication; a tenant's subject would run under that tenant's identity.""" + + async def test_it_answers_403_and_publishes_nothing(self, connected_nats_eventing: NatsEventing, cloud_event: CloudEvent) -> None: + from fastapi import HTTPException + + connected_nats_eventing._client.tenant_subject.return_value = "'t.acme.risk.created' is a tenant subject" # type: ignore[union-attr] + with pytest.raises(HTTPException) as refused: + await connected_nats_eventing.publish("t.acme.risk.created", cloud_event) + assert refused.value.status_code == 403 + assert "tenant" in refused.value.detail + connected_nats_eventing._client.publish.assert_not_awaited() # type: ignore[union-attr] From c902df16d7cc9dbefb6333917d8c8b23b65878ed Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Wed, 21 Oct 2026 14:28:19 +0200 Subject: [PATCH 131/133] docs(plans): name the rewritten commits; D1 revised to a history rewrite Internal project names were removed from the history of main, develop and this branch: file contents and eight commit messages from 2026-08-24 on, so each of those commits has a new SHA and the release tags moved with them. Author, dates and the files each commit touches are unchanged. This commit points the plans' 18 references to rewritten commits at the new SHAs, records the revised decision D1 and adds the step to the feature changelog. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../2026-08-28-multi-agent-grouping-changelog.md | 8 ++++++++ docs/plans/2026-10-14-named-connections.md | 12 ++++++------ .../2026-10-15-named-connections-step6-inventory.md | 10 +++++----- docs/plans/2026-10-16-pr96-review-fixes.md | 13 +++++++------ 4 files changed, 26 insertions(+), 17 deletions(-) diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index c98c9ca0..57e3a10a 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -284,6 +284,14 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a replaced by generic ones (`acme.agent..`, "the first consumer") in the named-connections plan, the accounts broker config, its connection source and three unit tests. Tree only; the published history keeps them (D1). The named-connection broker tests pass with the new subjects. +- Step 3, history (D1 revised 2026-10-21): the names are gone from the history as well -- the first + consumer's names on this branch, and two other projects' names that came in from `main` (the + job-scoped session-key spec and the release changelog). `git filter-repo` replaced them in file + contents and eight commit messages of `main`, `develop` and this branch from 2026-08-24 on, so each + of those commits has a new SHA and the release tags `v0.7.0` to `v0.9.0a17` moved with them. Author, + dates and the files each commit touches are unchanged. The plans' references to rewritten commits + name the new SHAs; older versions of those files keep the old ones. A review for project names before + every commit (a `CLAUDE.md` rule and a Claude Code hook) goes to `develop` in a pull request of its own. **Measured against a real broker** (`tests/integration`, NATS 2.10 with JetStream, plus an accounts broker): acknowledgement exactly once, redelivery after `ack_wait`, concurrent runs, diff --git a/docs/plans/2026-10-14-named-connections.md b/docs/plans/2026-10-14-named-connections.md index aeac2495..f2fb4d1d 100644 --- a/docs/plans/2026-10-14-named-connections.md +++ b/docs/plans/2026-10-14-named-connections.md @@ -30,7 +30,7 @@ yet, so nothing has to be migrated. framework has (dispositions, dead letter, drain budget, telemetry) and had to re-implement the rest (settlement, heartbeat, run limit, degraded pause). - **Concurrency.** Measured 2026-10-14: runs were strictly one at a time per subscription and - process in both implementations. `19c4c48` fixed the framework's path + process in both implementations. `a20a2b7` fixed the framework's path (`nats_max_concurrent_runs`, heartbeat); this plan carries it over to every connection. --- @@ -195,7 +195,7 @@ All taken on 2026-10-14; each entry starts with the decision, followed by the an pairs in the process (`"33%"`), recomputed when connections are added or removed. The owner's sizing: K up to about a third of the pairs. - Defaults keep today's behaviour: K unset = one run at a time *per subscription* (what every - agent did before; corrected in step 1 -- `19c4c48` had made it one per agent), pool unset + agent did before; corrected in step 1 -- `a20a2b7` had made it one per agent), pool unset (unlimited). With K set, the subscriptions of a pair share its K runs. - Order of acquisition is fixed (the pair's slot, then the pool), so there is no deadlock; waiters are served first come, first served, so no pair starves. @@ -204,7 +204,7 @@ All taken on 2026-10-14; each entry starts with the decision, followed by the an - Per-connection K from the binding (a large tenant gets more) is not built; it can be added later without reshaping anything. The analysis that led here: `nats_max_concurrent_runs` becomes per (agent, connection) -- it was per agent - in `19c4c48`, which is unpushed and unused -- plus a new process-scope cap + in `a20a2b7`, which is unpushed and unused -- plus a new process-scope cap `nats_max_concurrent_runs_per_process` across every agent and connection. Defaults: 1 and unset (no cap) to keep N6; the deployment sets both. - **D8 -- Core NATS on named connections. Decided 2026-10-14: (a), JetStream only.** A binding @@ -220,7 +220,7 @@ All taken on 2026-10-14; each entry starts with the decision, followed by the an itself is an ordinary failure (the run's own timer is checked, not the exception type). The run's slot is freed only when its task has actually ended -- a handler that swallows the cancellation keeps holding its slot, logged, instead of running unseen beside its redelivery. The heartbeat - (`19c4c48`) already exists and stops before the nak. The analysis that led here: + (`a20a2b7`) already exists and stops before the nak. The analysis that led here: Part A's hard limit (`nats_handler_timeout`, cancel + nak) is in the first consumer today and in the handler-time-bounds draft spec. Include it in this plan **(recommended)** -- "everything works as it does now" requires it. @@ -258,7 +258,7 @@ One step, one reviewable commit. Each step names its acceptance. JetStream context, subscriptions, slots, in-flight, ack-wait map) moves into a `_Connection` object; the client holds a default one. No behaviour change, with one addition decided 2026-10-14: `nats_heartbeat_enabled` (bool, agent-scoped, default `true`) switches the heartbeat - of `19c4c48` off per agent, as in handler-time-bounds sec. 4.1. + of `a20a2b7` off per agent, as in handler-time-bounds sec. 4.1. *Acceptance:* unit and integration suites unchanged; the 2026-10-14 probe (B1-B5, K1-K3) gives the same results. 2. **Binding mode.** A `_Connection` can bind with a `JetStreamBinding`: no stream provisioning, @@ -270,7 +270,7 @@ One step, one reviewable commit. Each step names its acceptance. validation hook (N2), empty Context per run, `nats_connection` context key, run scope hook (D3), per-connection slots and per-process cap (D7), handler timeout (D9). *Acceptance:* isolation test below; mismatch -> term; limits respected (measured overlap). -4. **Connection source, dynamic. Done 2026-10-15 (4a `3c16c10`, 4b).** Add, change, remove at runtime; drain on remove; never delete a +4. **Connection source, dynamic. Done 2026-10-15 (4a `c8ec35a`, 4b).** Add, change, remove at runtime; drain on remove; never delete a foreign consumer. Built on the rules of `docs/specs/2026-09-23-dynamic-subscriptions.md`, for whole connections only (no selectors, no REST API), with building blocks that spec can reuse later: - a change and a reconnect never interleave (one lock per agent, spec 7.2); diff --git a/docs/plans/2026-10-15-named-connections-step6-inventory.md b/docs/plans/2026-10-15-named-connections-step6-inventory.md index 502d5526..26085424 100644 --- a/docs/plans/2026-10-15-named-connections-step6-inventory.md +++ b/docs/plans/2026-10-15-named-connections-step6-inventory.md @@ -29,7 +29,7 @@ changed or why nothing was, and what is still open. Checked against the code on ## Checked, unchanged -- **W5**: already fixed by `519566f` (the second `CLAUDE.md` was removed). +- **W5**: already fixed by `9b4560c` (the second `CLAUDE.md` was removed). - `AGENTS.md`, `CLAUDE.md` (repository): no statement about delivery, handlers or `main.py` that disagrees with the code. - `docs/guides/multi-agent-setup.md`, `multi-agent-migration.md`: already show the declaration; @@ -57,11 +57,11 @@ changed or why nothing was, and what is still open. Checked against the code on ## Done after the first pass (2026-10-15) - `webhook_relay` and `order_event_pipeline`: one handler per event type, one service call - (`46d5db4`, `d698836`); `document_summarizer` without `assert` (`df8c3f3`). -- The named-connection example `examples/site_readings` (`639f2fa`), run live against a broker with + (`f72c84a`, `1d40fdc`); `document_summarizer` without `assert` (`4cbc3c2`). +- The named-connection example `examples/site_readings` (`30f14e7`), run live against a broker with accounts. -- Spec sec. 7.2 now matches the WARNING for an event no handler takes (`b81d5b9`, own commit). -- `nats_delivery_attempt` / `nats_max_deliver` in the handler context (`7e90ab4`). +- Spec sec. 7.2 now matches the WARNING for an event no handler takes (`ad771f0`, own commit). +- `nats_delivery_attempt` / `nats_max_deliver` in the handler context (`b7586e3`). ## Open diff --git a/docs/plans/2026-10-16-pr96-review-fixes.md b/docs/plans/2026-10-16-pr96-review-fixes.md index e5694cfd..bb77fd6a 100644 --- a/docs/plans/2026-10-16-pr96-review-fixes.md +++ b/docs/plans/2026-10-16-pr96-review-fixes.md @@ -4,7 +4,8 @@ what ran live; final run with containers recorded in the feature changelog. Step 22 done 2026-10-20. Open: the way forward on D22 (N13), N18, and D23 (b) (a missing binding-mode stream or consumer); everything else in "Decisions" is settled. -**Base:** `81f6bf2` (head of `feature/multi-agent-namespaces`, unchanged since the reviews). +**Base:** `be15878` (head of `feature/multi-agent-namespaces`, unchanged since the reviews; `81f6bf2` +before the history rewrite of 2026-10-21, see D1). **Sources:** pajoma's review (2026-10-15, CHANGES_REQUESTED, 3 blockers), Develebook's review (2026-10-16, 12 must-fix / 27 should-fix / 9 nits, inline), solicho's leftovers (2026-09-14/16). Earlier comments (version bump, retarget to `develop`, #97) are resolved. @@ -18,7 +19,7 @@ Dockerfile steps get a live run in WSL before they are reported as done. ## 1. Verification result -Every finding was re-checked against `81f6bf2`: by reading the code, and for most by a throwaway +Every finding was re-checked against `be15878`: by reading the code, and for most by a throwaway reproduction (fakes, fakeredis, InMemoryMetricReader, APScheduler/croniter, Docker in WSL). Verdicts: **C** confirmed, **P** partly, **R** refuted. "SA" = also affects standalone agents. @@ -301,7 +302,7 @@ Must-fix and blockers first (steps 1-14), then hardening (15-20), then documenta missing consumer, D23 (b)). Spec C1, C3 and 9.1 amended. 22c: the start fails on a `service.name` only in `OTEL_RESOURCE_ATTRIBUTES` in a group; N16 by reading the agent's view. 22d: N15 fixed. 22e: N19 fixed. Live in WSL (NATS, NATS accounts, Redis), each against the code before step 22 - (`fd1e3f5`) as control: durable clash -- before 8 attempts in 4 s, liveness 200, nothing CRITICAL; + (`4c10274`) as control: durable clash -- before 8 attempts in 4 s, liveness 200, nothing CRITICAL; now one, CRITICAL, liveness 503, SIGTERM for a critical agent; JetStream grant refused to the agent's own connection -- before the agent started and stayed paused for good, liveness 200, nothing logged (an orphaned agent, 22b); now the start fails with `JetStreamPermissionError`. @@ -318,7 +319,7 @@ Must-fix and blockers first (steps 1-14), then hardening (15-20), then documenta become public and the validator calls them. 23. **Findings of the first consumer's test report** (2026-10-20, 19 agents on 0.9.0a16 against a - local backend). B2 (regression of 22e/`ab6bd74`): an unset `nats_url` outside development is a + local backend). B2 (regression of 22e/`1d877f2`): an unset `nats_url` outside development is a validator notice, not an issue -- an image that validates while it is built has none yet. B3: the health job runs late instead of being dropped (`misfire_grace_time=None`, `coalesce`). A refresh at the end of startup, the report's other suggestion, was tried and withdrawn: it caught @@ -350,7 +351,7 @@ Must-fix and blockers first (steps 1-14), then hardening (15-20), then documenta | ID | Question | Blocks step | |---|---|---| -| D1 | B3: replace the names in the tree only, or also rewrite the published branch history? **Decided 2026-10-16: tree only, no history rewrite.** | 3 | +| D1 | B3: replace the names in the tree only, or also rewrite the published branch history? **Decided 2026-10-16: tree only, no history rewrite.** **Revised 2026-10-21: the history too** -- after further review feedback, internal project names were removed from the history of `main`, `develop` and this branch (every commit since 2026-08-24 has a new SHA), and the release tags moved with it. | 3 | | D2 | M2: after a failed resume, retry in a backoff task, or report unhealthy so the supervisor cycles? **Decided 2026-10-16: backoff task in the client (cancelled by pause/close), readiness unchanged, WARNING per failed attempt.** | 5 | | D4 | S6: in-progress TTL: opt-in key, derived from handler timeout / `ack_wait`, or document only? **Decided 2026-10-16: no in-progress state. The loss needs a redelivery while the first run is still going, which the heartbeat prevents. Document it, and log a startup WARNING when dedup runs without a heartbeat: NATS with `idempotency_enabled` and `nats_heartbeat_enabled = false`; Dapr with `idempotency_enabled` (Dapr has no heartbeat; the WARNING names the app-call timeout).** | 15 | | D6 | S9: undeclared topics as ``, a capped set, or drop the `topic` label? **Decided 2026-10-19: `` for every topic the agent did not declare; declared topics keep their name. With `dapr_declarative_subscriptions = true` everything counts as ``, the real name stays in the log line.** | 16 | @@ -363,7 +364,7 @@ Must-fix and blockers first (steps 1-14), then hardening (15-20), then documenta | D16 | S23: raise the pin to `diskcache-rs>=0.4.10`, or document disk as per-process only? **Decided 2026-10-19: raise the pin to `diskcache-rs>=0.4.10`. Live in WSL: two processes claim the same key, exactly one wins; "atomic across processes" stays in the docs only if that holds. Drop "a disk cache on a shared volume" for several replicas (`configuration-keys.md:144`, `deployment.md:386`): cross-pod dedup needs Redis, disk covers processes on one host. General rule (user, 2026-10-19): where a dependency's behaviour changed in a way that affects us, adapt to it and raise the minimum version -- S7 is re-checked under this rule in step 15 (which redis-py version brought the default socket timeouts).** | 20 | | D17 | W1: in a group, ignore `OTEL_SERVICE_NAME` for agents with a WARNING, refuse to start, or document? **Decided 2026-10-19: in a group every agent provider keeps `service.name` = agent name even when `OTEL_SERVICE_NAME` is set, so telemetry stays filterable per agent; the root provider still takes `OTEL_SERVICE_NAME`. One startup WARNING names the value and why it does not apply to the agents. `OTEL_RESOURCE_ATTRIBUTES` stays untouched. Docs: the exception to "declared keys are never replaced". Standalone unchanged.** | 17 | | D19 | W8: fold `[0.9.0]` into `[Unreleased]` and restore the `develop` version string, or keep as is? **Decided 2026-10-19: this PR follows its own `AGENTS.md` rule -- `[0.9.0] - 2026-09-14` (never released, only `v0.9.0a1..a15`) is folded into `[Unreleased]`, `pyproject.toml` goes back to develop's `0.8.2`; `publish.yml` sets the version from the tag anyway (L43/L66). Reply to SawwR's bump comment with the rule. Follow-up issue, not in this PR: derive the version from git tags with `setuptools-scm` so source installs report it too (drops the `sed` step); the stale `__version__ = "0.3.0"` fallback in `src/blueprint/__init__.py:8` goes with it.** | 21 | -| D20 | Is the MIT licence choice approved by the responsible owner (pajoma F)? Not a code decision. **Decided 2026-10-19: no approval exists. The licence is deferred: this PR goes back to develop's licence state (`LICENSE` from `a9a8f3b` removed, `license`, `license-files` and the MIT classifier out of `pyproject.toml`). Open point for the `develop` -> `main` merge: licence approval by the responsible owner, then add it there. The PR description says so. Already published alphas (`v0.9.0a1..a15`) carry MIT and cannot be changed.** | 21 | +| D20 | Is the MIT licence choice approved by the responsible owner (pajoma F)? Not a code decision. **Decided 2026-10-19: no approval exists. The licence is deferred: this PR goes back to develop's licence state (`LICENSE` from `424d9dc` removed, `license`, `license-files` and the MIT classifier out of `pyproject.toml`). Open point for the `develop` -> `main` merge: licence approval by the responsible owner, then add it there. The PR description says so. Already published alphas (`v0.9.0a1..a15`) carry MIT and cannot be changed.** | 21 | | D21 | N12: a paused client whose own resume keeps failing reports healthy, so readiness is UP while the agent consumes nothing. Options: (a) while paused, report unhealthy once a resume attempt has failed, and let `_retry_resume` keep running through a re-pause (today a pause cancels it, which would then deadlock); (b) leave readiness as it is and add a `blueprint.nats.resume_failures` counter plus the failure in the readiness payload; (c) accept and document. **Decided 2026-10-20 with D23 -- see 22b.** Measured (step 18, root topic `orders-created` against a consumer filtering `created`, health interval 2 s): 200 at 0-2 s, 503 at 2.1 s (degraded, paused), 200 from 4.1 s on while paused, resume attempts failing at 5 s and 10 s backoff. | -- | | D22 | N13: make `DiskCacheService.claim` atomic across processes on one host -- an OS file lock (`fcntl.flock` / `msvcrt.locking`, or the `filelock` package) around the `add` -- or keep the disk cache per-process for claims and warn at startup when dedup or the in-process tick claim runs on a disk cache with `app_workers > 1`? **Decided 2026-10-19: document only, for now** -- the docs say per-process (claim docstring, deployment guide, configuration keys, CHANGELOG Known issues); how to proceed beyond that is to be clarified. | -- | | D23 | Startup and tenancy faults (owner, 2026-10-19). **Principle: a critical problem or collision found at startup fails the start; a fault caused by a wrong or problematic tenancy is logged CRITICAL and the process exits -- at startup and at runtime, when a `ConnectionSource` change hands it over -- because an operator must notice it.** Critical means deterministic (a retry cannot fix it): durable clash (S1), stream not creatable/updatable (subject overlap), missing JetStream permissions, tenant login refused, tenant deliver subject refused, binding-mode consumer missing or filtering another subject. Transient faults (broker unreachable, connection lost, timeouts) keep retrying; D5 stays for those. Open before implementing: (a) do an agent's own faults respect `critical_agents` (spec sec. 9.1) or always exit; (b) is a missing binding-mode stream fatal or still transient (provisioning); (c) D17 -- refuse `service.name` in `OTEL_RESOURCE_ATTRIBUTES` in a group, and what happens to `OTEL_SERVICE_NAME`. Partly supersedes D21 (N12). **Added (owner, 2026-10-19): a constellation that leaves orphaned agents -- agents that should exist but consume nothing for a non-transient reason (startup latch, final subscription fault, a resume that keeps failing) -- makes the service at least unhealthy, possibly exits.** So D21 is decided in principle: a paused client whose resume keeps failing reports unhealthy. Open: whether "unhealthy" is readiness DOWN or liveness DOWN, and whether it overrides `readiness_policy = "critical"` for a non-critical agent. **Settled (owner, 2026-10-19):** (1) such critical faults set **liveness** DOWN, and each is logged well enough for an operator to act on (what failed, which agent/connection, why it is not transient, what to change); (2) a transient fault stays under `readiness_policy`, an orphaned agent counts regardless of the policy; (3) D17: in a group, a `service.name` declared only through `OTEL_RESOURCE_ATTRIBUTES` (no `OTEL_SERVICE_NAME`), which would name every agent alike, **fails the start**; `OTEL_SERVICE_NAME` alone or together with it stays as implemented (agents keep their names, WARNING). Still open: (a) an agent's own faults vs `critical_agents`, (b) a missing binding-mode stream. **Clarified (owner, 2026-10-19): M agents x N tenants; N = 0 (the source hands over no tenant) is a valid state -- nothing to bind, nothing fails (as implemented: "consumes on 0 named connection(s)").** (b) concerns N >= 1: a tenant handed over whose binding names a stream (or, with `manage_consumer = false`, a consumer) that does not exist. **(b) deferred (owner, 2026-10-19):** whether a missing binding-mode stream -- or, with `manage_consumer = false`, a missing consumer -- is fatal at once or after a grace period depends on whether the tenancy source hands over a tenant only once its stream is provisioned; to be clarified with the tenancy owner. Until then it stays as implemented: retried, visible in readiness only (`.nats_client:connections` reads `retrying`); with `manage_consumer = false` a missing consumer is not detected at all (the client sends no JetStream request). **(a) settled (owner, 2026-10-19): fail early.** A deterministic fault (durable clash, stream not creatable/updatable, missing JetStream permissions) is fatal in every agent, whatever `critical_agents` says: logged CRITICAL, startup fails or liveness goes DOWN. `critical_agents` and `readiness_policy` keep deciding only for faults that may be transient (startup recovery, health). | 22 | From 53211925cba64201129138b66683aade088f3dfe Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 22 Oct 2026 13:03:33 +0200 Subject: [PATCH 132/133] fix(claude): the push guard reads quoted and multi-line repository paths The guard let an old-history branch through whenever the command named the repository in double quotes (cd "C:/..." && git push, git -C "..." push) or as cd followed by a line break: the extracted path kept the JSON-escaped quote or the \n, did not resolve, and an unresolved path is let through. A quoted -C path with a space was not recognised as a push at all. A quoted path is now taken whole and then unquoted, and a line break ends a bare one. Regression tests in tests/unit/hooks run a copy of the hook against a throwaway repository with a replaced root of its own. Of 18 ways to name the repository, the old hook refused 5, the fixed one 18. Co-Authored-By: Claude Opus 5.5 (1M context) --- .claude/hooks/replaced-history-guard.sh | 17 +- ...26-08-28-multi-agent-grouping-changelog.md | 10 + tests/unit/hooks/__init__.py | 0 .../unit/hooks/test_replaced_history_guard.py | 185 ++++++++++++++++++ 4 files changed, 206 insertions(+), 6 deletions(-) create mode 100644 tests/unit/hooks/__init__.py create mode 100644 tests/unit/hooks/test_replaced_history_guard.py diff --git a/.claude/hooks/replaced-history-guard.sh b/.claude/hooks/replaced-history-guard.sh index a0e15dbf..4546dc56 100755 --- a/.claude/hooks/replaced-history-guard.sh +++ b/.claude/hooks/replaced-history-guard.sh @@ -21,18 +21,23 @@ REPLACED_ROOT=1c2098c131ea654c850dccd2c7c627dab2e26f4a input=$(cat) +# One shell word in the JSON input: bare, in single quotes, or in double quotes (JSON-escaped: +# \"...\"). Quoted, it may contain spaces, and it is taken whole. +word='(\\"[^"]*\\"|'\''[^'\'']*'\''|[^[:space:];&|"'\''\\][^[:space:];&|"'\'']*)' + # `git push`, also after global options (`git -C dir push`, `git -c k=v push`). printf '%s' "$input" | - grep -Eq 'git(([[:space:]]+-[Cc][[:space:]]+[^[:space:]]+)|([[:space:]]+--?[A-Za-z][-A-Za-z]*(=[^[:space:]]+)?))*[[:space:]]+push([[:space:]]|$|["'\'';&|)])' || + grep -Eq 'git(([[:space:]]+-[Cc][[:space:]]+('"$word"'|[^[:space:]]+))|([[:space:]]+--?[A-Za-z][-A-Za-z]*(=[^[:space:]]+)?))*[[:space:]]+push([[:space:]]|$|["'\'';&|)])' || exit 0 root=$(cd "${CLAUDE_PROJECT_DIR:-.}" 2>/dev/null && pwd -P) || exit 0 -# The repository: `git -C `, else a leading `cd `, else the project. JSON-escaped -# backslashes (Windows paths) become slashes; paths with spaces are not recognised (-> the project). -dir=$(printf '%s' "$input" | grep -Eo 'git[[:space:]]+-C[[:space:]]+[^[:space:];&|]+' | head -n 1 | sed -E 's/^git[[:space:]]+-C[[:space:]]+//') -[ -n "$dir" ] || dir=$(printf '%s' "$input" | grep -Eo '"command":[[:space:]]*"cd[[:space:]]+[^[:space:];&|]+' | head -n 1 | sed -E 's/^"command":[[:space:]]*"cd[[:space:]]+//') -dir=$(printf '%s' "$dir" | sed 's#\\\\#/#g' | tr -d '"'\') +# The repository: `git -C `, else a leading `cd `, else the project. A path that does not +# resolve is let through below, so a quoted one must be taken whole, quotes and all, then unquoted. +# JSON-escaped backslashes (Windows paths) become slashes; a line break ends a bare path. +dir=$(printf '%s' "$input" | grep -Eo "git[[:space:]]+-C[[:space:]]+$word" | head -n 1 | sed -E 's/^git[[:space:]]+-C[[:space:]]+//') +[ -n "$dir" ] || dir=$(printf '%s' "$input" | grep -Eo "\"command\":[[:space:]]*\"cd[[:space:]]+$word" | head -n 1 | sed -E 's/^"command":[[:space:]]*"cd[[:space:]]+//') +dir=$(printf '%s' "$dir" | sed -e 's/^\\"\(.*\)\\"$/\1/' -e "s/^'\(.*\)'\$/\1/" -e 's#\\\\#/#g' -e 's/\\n.*//') if [ -n "$dir" ]; then dir=$(cd "$dir" 2>/dev/null && pwd -P) || exit 0 case "$dir/" in diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 57e3a10a..66e899d3 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -292,6 +292,16 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a dates and the files each commit touches are unchanged. The plans' references to rewritten commits name the new SHAs; older versions of those files keep the old ones. A review for project names before every commit (a `CLAUDE.md` rule and a Claude Code hook) goes to `develop` in a pull request of its own. +- Guards from `develop` (#108, merged into this branch): the commit review hook, the push guard against + the replaced history and the CI job "No replaced history". Tried live here, the push guard let an + old-history branch through whenever the command named the repository in double quotes + (`cd "C:/..." && git push`, `git -C "..." push`) or as `cd ` followed by a line break: the + extracted path kept the JSON-escaped quote or the `\n`, did not resolve, and an unresolved path is + let through. A quoted `-C` path with a space was not even recognised as a push. Fixed in + `.claude/hooks/replaced-history-guard.sh` (a quoted path is taken whole, then unquoted; a line break + ends a bare one), with regression tests in `tests/unit/hooks/` that now run in CI. Control, 18 ways to + name the repository: the old hook refused 5, the fixed one 18; live with `--dry-run`, the three shapes + that got through are refused and a clean branch still goes through. **Measured against a real broker** (`tests/integration`, NATS 2.10 with JetStream, plus an accounts broker): acknowledgement exactly once, redelivery after `ack_wait`, concurrent runs, diff --git a/tests/unit/hooks/__init__.py b/tests/unit/hooks/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/unit/hooks/test_replaced_history_guard.py b/tests/unit/hooks/test_replaced_history_guard.py new file mode 100644 index 00000000..9d3d7d00 --- /dev/null +++ b/tests/unit/hooks/test_replaced_history_guard.py @@ -0,0 +1,185 @@ +"""Regression tests for the Claude Code push guard `.claude/hooks/replaced-history-guard.sh`. + +The hook reads the proposed Bash call as JSON and refuses (exit 2) a `git push` of a branch that +descends from the replaced root commit. Each test builds a throwaway repository with a root of its +own and runs a copy of the hook whose REPLACED_ROOT names that commit; nothing is pushed anywhere. +""" + +import json +import os +import shutil +import stat +import subprocess +import tempfile +import uuid +from collections.abc import Callable, Iterator +from pathlib import Path + +import pytest + +HOOK = Path(__file__).resolve().parents[3] / ".claude" / "hooks" / "replaced-history-guard.sh" +SH = shutil.which("sh") or "sh" + +pytestmark = pytest.mark.skipif(shutil.which("sh") is None or shutil.which("git") is None, reason="needs sh and git on PATH") + +REFUSED = 2 +LET_THROUGH = 0 + +# No environment is passed explicitly: a failing call's arguments end up in the traceback. +GIT = ["git", "-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "commit.gpgsign=false"] + + +def _git(repo: Path, *args: str) -> str: + """Run git in ``repo`` and return its stdout.""" + return subprocess.run([*GIT, "-C", str(repo), *args], check=True, capture_output=True, text=True).stdout.strip() + + +class Project: + """A repository whose `main` is clean and whose `old` descends from the replaced root.""" + + def __init__(self, path: Path, hook: Path) -> None: + self.path = path + self.hook = hook + + def run(self, command: str, spaced: bool = False) -> subprocess.CompletedProcess[str]: + """Feed the hook the PreToolUse input for a Bash call of ``command``.""" + payload = { + "session_id": "test", + "cwd": str(self.path), + "hook_event_name": "PreToolUse", + "tool_name": "Bash", + "tool_input": {"command": command, "description": "test"}, + } + text = json.dumps(payload) if spaced else json.dumps(payload, separators=(",", ":")) + return subprocess.run([SH, self.hook.as_posix()], input=text, capture_output=True, text=True, cwd=self.path) + + +@pytest.fixture +def scratch(monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]: + """A directory with default permissions, which git (and the hook's git) accepts as safe. + + pytest's ``tmp_path`` is owner-only (mode 0o700), and Git for Windows cannot enter such a + directory ("cannot change to ...: Permission denied"). Where the temporary directory belongs to + another owner than the user (e.g. the Administrators group), git refuses it as of dubious + ownership; ``safe.directory`` is only read from command-line scope or above, hence the variables. + """ + monkeypatch.setenv("GIT_CONFIG_COUNT", "1") + monkeypatch.setenv("GIT_CONFIG_KEY_0", "safe.directory") + monkeypatch.setenv("GIT_CONFIG_VALUE_0", "*") + path = Path(tempfile.gettempdir()) / f"guard-test-{uuid.uuid4().hex}" + path.mkdir() + yield path + + def make_writable_and_retry(function: Callable[[str], object], name: str, _: BaseException) -> None: + os.chmod(name, stat.S_IWRITE) # git's object files are read-only + function(name) + + shutil.rmtree(path, onexc=make_writable_and_retry) + + +@pytest.fixture +def make_project(scratch: Path, monkeypatch: pytest.MonkeyPatch) -> Callable[[str], Project]: + def make(name: str) -> Project: + path = scratch / name + path.mkdir() + _git(path, "init", "-q", "-b", "main") + _git(path, "commit", "-q", "--allow-empty", "-m", "clean") + _git(path, "checkout", "-q", "-b", "old") + _git(path, "commit", "-q", "--allow-empty", "-m", "replaced root") + root = _git(path, "rev-parse", "HEAD") + _git(path, "commit", "-q", "--allow-empty", "-m", "replaced child") + _git(path, "checkout", "-q", "main") + + hook = scratch / "guard.sh" + script = HOOK.read_text(encoding="utf-8") + original = next(line for line in script.splitlines() if line.startswith("REPLACED_ROOT=")) + hook.write_text(script.replace(original, f"REPLACED_ROOT={root}"), encoding="utf-8", newline="\n") + monkeypatch.setenv("CLAUDE_PROJECT_DIR", str(path)) + return Project(path, hook) + + return make + + +@pytest.fixture +def project(make_project: Callable[[str], Project]) -> Project: + return make_project("project") + + +def _path_forms(path: Path, bare: bool = True) -> list[str]: + """The ways a command can name ``path``: bare, single- and double-quoted, native separators.""" + forms = [f'"{path.as_posix()}"', f"'{path.as_posix()}'", f'"{path}"'] + if bare: + forms.insert(0, path.as_posix()) + return list(dict.fromkeys(forms)) + + +REFUSED_COMMANDS = [ + "git push origin old", + "git push --dry-run origin old", + "git push origin +old:other", + "git push origin main old", + "git push --all origin", + "git push --mirror origin", + "git -c push.default=current push origin old", + "git status && git push origin old", + "git status; git push origin old", +] + +LET_THROUGH_COMMANDS = [ + "git push origin main", + "git push origin", + "git push origin --delete old", + "git push --tags origin", + "git log --oneline -1", + "git push origin main && git log old", +] + + +@pytest.mark.parametrize("spaced", [False, True], ids=["compact", "spaced"]) +@pytest.mark.parametrize("command", REFUSED_COMMANDS) +def test_a_push_of_the_replaced_history_is_refused(project: Project, command: str, spaced: bool) -> None: + result = project.run(command, spaced) + assert result.returncode == REFUSED, result.stderr + assert "old" in result.stderr + + +@pytest.mark.parametrize("spaced", [False, True], ids=["compact", "spaced"]) +@pytest.mark.parametrize("command", LET_THROUGH_COMMANDS) +def test_other_commands_are_let_through(project: Project, command: str, spaced: bool) -> None: + assert project.run(command, spaced).returncode == LET_THROUGH + + +def test_a_push_of_the_current_branch_is_refused_when_it_carries_the_replaced_history(project: Project) -> None: + _git(project.path, "checkout", "-q", "old") + assert project.run("git push origin").returncode == REFUSED + assert project.run("git push").returncode == REFUSED + + +@pytest.mark.parametrize("spaced", [False, True], ids=["compact", "spaced"]) +def test_the_repository_is_found_however_the_command_names_it(project: Project, spaced: bool) -> None: + for form in _path_forms(project.path): + for command in ( + f"cd {form} && git push origin old", + f"git -C {form} push origin old", + f"cd {form}\ngit push origin old", + ): + assert project.run(command, spaced).returncode == REFUSED, command + for command in (f"cd {form} && git push origin main", f"git -C {form} push origin --delete old"): + assert project.run(command, spaced).returncode == LET_THROUGH, command + + +def test_a_quoted_path_may_contain_spaces(make_project: Callable[[str], Project]) -> None: + project = make_project("my project") + for form in _path_forms(project.path, bare=False): + assert project.run(f"cd {form} && git push origin old").returncode == REFUSED, form + assert project.run(f"git -C {form} push origin old").returncode == REFUSED, form + + +def test_a_repository_outside_the_project_is_not_inspected(project: Project, scratch: Path) -> None: + # The hook runs before the user approves the command, so it never runs git where the command + # merely points; CI ("No replaced history") refuses such a branch instead. + outside = scratch / "outside" + _git(scratch, "clone", "-q", str(project.path), str(outside)) + _git(outside, "branch", "old", "origin/old") + for form in _path_forms(outside): + assert project.run(f"git -C {form} push origin old").returncode == LET_THROUGH, form From 1de7dcd66147b33766911a06f5e950577b049ccc Mon Sep 17 00:00:00 2001 From: "Bechtle\\jan.weber" Date: Thu, 22 Oct 2026 13:13:32 +0200 Subject: [PATCH 133/133] docs(changelog): Breaking 18-21 in order; the upgrade notes name nats_nak_delay Two points of the 2026-10-21 re-review of #96: item 19 had landed after 21, and the standalone upgrade notes did not say that nats_nak_delay changes redelivery timing for a standalone agent too (with nats_max_deliver = 5, about 50 s to the dead letter instead of a fraction of a second). Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 16 ++++++++++------ .../2026-08-28-multi-agent-grouping-changelog.md | 3 +++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 095831ef..3fbe268e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -188,6 +188,12 @@ Full migration path, including the one decision to get right before the first de `JetStreamBindingError` for the clash), `StreamConflictError`, `JetStreamPermissionError`, `TenancyError`; `JetStreamUnavailableError` is one too. A missing binding-mode stream is still retried (Known issues). +19. **An orphaned agent takes the pod out, whatever `readiness_policy` says.** An agent latched down + -- its startup failed and recovery retries it, or its transport failed for good -- now gates + readiness under `"critical"` and `"any"` too: it consumes nothing for a reason that is not + transient. And an agent whose resume after a degradation keeps failing, or whose connection loop + gave up (`event_client_max_retries`), fails liveness until it consumes again, logged CRITICAL: it + reported healthy while paused, so readiness read UP while nothing was consumed. 20. **A failed JetStream delivery comes back after a delay.** A `RetryableHandlerError`, any unexpected exception and `nats_handler_timeout` used to nak for immediate redelivery, so every attempt was used up within a few hundred milliseconds -- measured: 5 attempts in 0.3 s -- and a @@ -199,12 +205,6 @@ Full migration path, including the one decision to get right before the first de binding filters or delivers to: the route has no authentication, and an event put into a tenant's stream ran under that tenant's identity. `operator_routes_enabled = false` (process scope) leaves the publish route and the cache routes out altogether. -19. **An orphaned agent takes the pod out, whatever `readiness_policy` says.** An agent latched down - -- its startup failed and recovery retries it, or its transport failed for good -- now gates - readiness under `"critical"` and `"any"` too: it consumes nothing for a reason that is not - transient. And an agent whose resume after a degradation keeps failing, or whose connection loop - gave up (`event_client_max_retries`), fails liveness until it consumes again, logged CRITICAL: it - reported healthy while paused, so readiness read UP while nothing was consumed. ### Added @@ -976,6 +976,10 @@ What the broker sees change when an agent that ran on 0.8 starts on this version through JetStream, the publish subjects. - **Core NATS subscriptions join a queue group** (`nats_queue_group`, else `app_name`), so each message reaches one replica instead of every one. +- **A failed JetStream delivery is redelivered after a delay**, not at once: `nats_nak_delay` + defaults to 1 s, 5 s, 15 s, 30 s, then 60 s per redelivery, so with `nats_max_deliver = 5` a + failing message is dead-lettered after about 50 s instead of a fraction of a second. + `nats_nak_delay = 0` restores 0.8's immediate redelivery (Breaking 20). What the code sees change: diff --git a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md index 66e899d3..20f142b1 100644 --- a/docs/plans/2026-08-28-multi-agent-grouping-changelog.md +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -302,6 +302,9 @@ framework endpoints (`nats`, `cache`, `scheduler`), one Swagger tag per agent, a ends a bare one), with regression tests in `tests/unit/hooks/` that now run in CI. Control, 18 ways to name the repository: the old hook refused 5, the fixed one 18; live with `--dry-run`, the three shapes that got through are refused and a clean branch still goes through. +- Re-review of 2026-10-21, before the merge into `develop`: `CHANGELOG.md`'s Breaking items run 18-21 + in order again (19 had landed after 21), and the standalone upgrade notes name `nats_nak_delay`, + which changes redelivery timing for a standalone agent too. **Measured against a real broker** (`tests/integration`, NATS 2.10 with JetStream, plus an accounts broker): acknowledgement exactly once, redelivery after `ack_wait`, concurrent runs,