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/.gitignore b/.gitignore index a4c6f414..5638753e 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 @@ -160,3 +164,6 @@ uv.lock ARCHITECTURE_DECISIONS.md + +# Private, machine-local Claude Code instructions +CLAUDE.local.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..c7668808 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,276 @@ +# 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 `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. + +--- + +## 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.** 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 + +**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. + +**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 +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, 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/`, + `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 + 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 96ef88c2..3fbe268e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,1013 @@ # Changelog +## [Unreleased] + +**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`. + +### 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 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 + 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 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`): + 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 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 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 + 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`. + +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"` 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 + 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 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. +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 -- 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. +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. +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. +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. + +### 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), `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 + 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 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 `""`, + 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`** 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 + 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. + +- **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 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 + 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 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 **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. + +### 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. + +### 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 + 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 + 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. 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: + - 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. 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 + 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. + +- **`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 + `/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 + `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 + 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 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 + 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 + 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 + 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 + 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 + 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 + 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; + 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 + 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 + 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 + 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. +- **`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. + 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 + 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`, + `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` + 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 + `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). +- **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. +- **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 + 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 + 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 `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 + 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 + `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 + 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`. +- **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. + +- **`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. + +- **⚠️ 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 + 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 (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 + 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. + +### 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 + 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. +- **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 + +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. +- **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: + +- **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()`. 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 + +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 @@ -225,7 +1234,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 f554efbf..5f42b50b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,7 +2,13 @@ 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. + +## 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 @@ -10,17 +16,25 @@ See `AGENTS.md` for architecture, component patterns, and testing conventions sh # 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/ @@ -63,6 +77,77 @@ cp dist/* ~/local-pypi/ 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-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 +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) +``` + ## Project names This repository is public and used by many projects. The names of projects, products, customers, diff --git a/CONTRIBUTE.md b/CONTRIBUTE.md index d69db65a..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 ... ``` @@ -206,16 +209,34 @@ mypy src/ black src/ tests/ && ruff check src/ tests/ && mypy src/ ``` -## Pre-commit & Pre-push Hooks +## Commit Messages + +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 -Set up both commit and 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 @@ -270,7 +291,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/README.md b/README.md index fb85d48d..61d90d2d 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.** @@ -14,9 +14,10 @@ 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 - **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 @@ -28,16 +29,24 @@ 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`. +Your service is now running at `http://localhost:8000` with interactive API docs at `/docs`, +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 -- 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). --- @@ -57,27 +66,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 @@ -93,30 +118,37 @@ 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 src.handlers.order_handler import OrderHandler -from src.services.order_service import OrderService -from src.api.routes import OrderApi +from blueprint.agents import AppBuilder -config = Config(settings_files=["settings.toml", "secrets.toml"]) +from .handlers.order_handler import OrderHandler +from .services.order_service import OrderService +from .api.routes import OrderApi -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. 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 | 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 | @@ -134,17 +166,85 @@ 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, 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] +root = "agents/orders" +module = "agents.orders.src.main:agent" + +[agents.billing] +root = "agents/billing" +module = "agents.billing.src.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](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 | --- @@ -172,7 +272,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] @@ -218,7 +318,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. --- @@ -227,17 +327,20 @@ See the [Configuration Reference](docs/concepts/configuration.md) for all availa 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](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). --- @@ -249,39 +352,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 +- [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) -- Persistent disk cache with TTL and namespaces -- [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) --- @@ -297,7 +414,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 @@ -307,4 +424,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/components/event-handlers.md b/docs/components/event-handlers.md deleted file mode 100644 index 49e1d512..00000000 --- a/docs/components/event-handlers.md +++ /dev/null @@ -1,315 +0,0 @@ -# Event Handlers - -Event handlers process incoming CloudEvents using a chain-of-responsibility pattern. Each handler declares which events it can process, and the framework routes events through all registered handlers in priority order. - -## Import - -```python -from blueprint.agents.handler.event_handler_base import EventHandlerBase -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. - -## Base Class - -```python -from typing import Any -from blueprint.agents.handler.event_handler_base import EventHandlerBase -from blueprint.agents.models.events import GenericCloudEvent, HandlerResult - - -class MyHandler(EventHandlerBase): - - def __init__(self) -> None: - super().__init__(priority=100) # Lower priority runs first - - async def on_startup(self) -> None: - self._service = self.registry.get_service(MyService) - - async def on_shutdown(self) -> None: - pass - - async def can_handle_event( - self, event: GenericCloudEvent, context: dict[str, Any] - ) -> bool: - ... - - async def handle_event( - self, event: GenericCloudEvent, context: dict[str, Any] - ) -> Any | HandlerResult | list[HandlerResult] | None: - ... -``` - -## 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. - -```python -super().__init__(priority=10) # Runs early -super().__init__(priority=100) # Default -super().__init__(priority=500) # Runs late -``` - -## Abstract Methods - -### 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. - -```python -async def can_handle_event( - self, event: GenericCloudEvent, context: dict[str, Any] -) -> bool: - return event.type == "order.created" -``` - -### handle_event - -Performs the actual processing. Called only when `can_handle_event` returned `True`. - -```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") -``` - -## 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. | - -Note: The handler chain always continues through all handlers that return `True` from `can_handle_event`. Returning a `HandlerResult` does not stop subsequent handlers. - -## Sharing Data Between Handlers via context - -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 -# Handler at priority 5 -- runs first -class NormalizerHandler(EventHandlerBase): - def __init__(self) -> None: - super().__init__(priority=5) - - 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]) -> None: - # Parse once and store for downstream handlers - normalized = self._service.normalize(event.data) - context["normalized"] = normalized - context["source"] = normalized.source - return None # Pass to next handler - - -# Handler at priority 20 -- runs after NormalizerHandler but double checked with filled context -class EnricherHandler(EventHandlerBase): - def __init__(self) -> None: - super().__init__(priority=20) - - async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: - return context.get("normalized") and event.type == "webhook.received" - - async def handle_event( - self, event: GenericCloudEvent, context: dict[str, Any] - ) -> HandlerResult | None: - # Read data written by the earlier handler - normalized = context.get("normalized") - - enriched = self._service.enrich(normalized) - return HandlerResult(event_type="webhook.processed", data=enriched) -``` - -## Published Event Types - -Optionally declare the event types this handler can produce. Used for documentation and subscription introspection. - -```python -def get_published_event_types(self) -> tuple[str, str] | None: - return ("order.processed", "order.error") -``` - -The tuple is `(success_type, error_type)`. Return `None` if the handler does not publish events. - -## Accessing Services - -Resolve service dependencies in `on_startup()`. Never in `__init__()`. - -```python -from blueprint.agents.services.service_base import ServiceBase - - -class OrderService(ServiceBase): - async def process(self, order: dict) -> dict: - ... - - -class OrderHandler(EventHandlerBase): - - def __init__(self) -> None: - super().__init__(priority=100) - self._order_service: OrderService | None = None - - async def on_startup(self) -> None: - self._order_service = self.registry.get_service(OrderService) - - 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: - if self._order_service is None: - return None - result = await self._order_service.process(event.data) - return HandlerResult(data=result, event_type="order.processed") -``` - -## Registration - -Register handlers with `AppBuilder` by passing the **class** or an instance of the class: - -```python -from blueprint.agents import AppBuilder, Config - -config = Config(settings_files=["settings.toml", "secrets.toml"]) -app = ( - AppBuilder(config) - .with_service(OrderService) - .with_handler(OrderHandler) - .build() -) -``` - -Services must be registered before the handlers that depend on them. - -## Full Example - -```python -from typing import Any -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 InvoiceService(ServiceBase): - """Domain service for invoice processing.""" - - async def on_startup(self) -> None: - pass - - async def on_shutdown(self) -> None: - pass - - async def generate_invoice(self, order_id: str, items: list[dict]) -> dict: - return {"invoice_id": "INV-001", "order_id": order_id, "total": 99.99} - - -class InvoiceHandler(EventHandlerBase): - """Generates invoices when an order is confirmed.""" - - def __init__(self) -> None: - super().__init__(priority=50) - self._invoice_service: InvoiceService | None = None - - async def on_startup(self) -> None: - self._invoice_service = self.registry.get_service(InvoiceService) - - async def on_shutdown(self) -> None: - pass - - def get_published_event_types(self) -> tuple[str, str] | None: - return ("invoice.created", "invoice.error") - - async def can_handle_event( - self, event: GenericCloudEvent, context: dict[str, Any] - ) -> bool: - return event.type == "order.confirmed" - - 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", - ) -``` - -## Testing - -Use a mock registry to unit test handlers in isolation. - -```python -import pytest -from unittest.mock import AsyncMock, MagicMock -from blueprint.agents.models.events import GenericCloudEvent - - -@pytest.fixture -def mock_registry(): - registry = MagicMock() - invoice_service = AsyncMock() - invoice_service.generate_invoice.return_value = { - "invoice_id": "INV-TEST", - "order_id": "ORD-1", - "total": 50.00, - } - registry.get_service.return_value = invoice_service - return registry - - -@pytest.fixture -async def handler(mock_registry): - h = InvoiceHandler() - h._registry = mock_registry - await h.on_startup() - return h - - -async def test_can_handle_matching_event(handler): - event = GenericCloudEvent(id="1", type="order.confirmed", data={}) - assert await handler.can_handle_event(event, {}) is True - - -async def test_ignores_unrelated_event(handler): - event = GenericCloudEvent(id="2", type="user.created", data={}) - assert await handler.can_handle_event(event, {}) is False - - -async def test_handle_event_returns_result(handler): - event = GenericCloudEvent( - id="3", - type="order.confirmed", - data={"order_id": "ORD-1", "items": [{"sku": "A", "qty": 2}]}, - ) - result = await handler.handle_event(event, {}) - assert result is not None - assert result.event_type == "invoice.created" - assert result.data["invoice_id"] == "INV-TEST" -``` 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 deleted file mode 100644 index 55af35f6..00000000 --- a/docs/concepts/caching.md +++ /dev/null @@ -1,347 +0,0 @@ -# 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. - -## Enabling the Cache - -Enable caching by calling `.with_cache()` on the `AppBuilder`: - -```python -from blueprint.agents import AppBuilder, Config - -config = Config(settings_files=["settings.toml", "secrets.toml"]) - -app = ( - AppBuilder(config) - .with_service(MyService) - .with_handler(MyHandler) - .with_cache() - .build() -) -``` - -Once enabled, the cache service is registered in the component registry and a management REST API is automatically mounted. - -## Accessing the Cache - -The cache is available through the component registry from `on_startup()` onward: - -```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, - ) -``` - -## Cache Operations - -### get(key, namespace) - -Retrieve a value by key within a namespace. Returns `None` if the key does not exist or has expired. - -```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) - -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. - -```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") -``` - -### delete(key, namespace) - -Remove a specific key from a namespace. - -```python -await self.cache.delete("user:12345", namespace="profiles") -``` - -### clear(namespace) - -Remove all entries in a namespace. Useful for bulk invalidation. - -```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. - -```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 no TTL is provided, the `default_ttl` value from `[default.cache]` in `settings.toml` is applied. - -## Namespace Isolation - -Namespaces partition the cache into logical segments. Different components can use separate namespaces without risk of key collisions. - -```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 -``` - -Namespaces also allow targeted invalidation. Clearing one namespace does not affect others. - -## Key Hashing for Complex Keys - -The cache supports complex keys such as lists, dictionaries, and tuples. These are automatically hashed to produce a stable string key. - -```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) - -# List key -- also automatically hashed -chunk_ids = ["chunk-a", "chunk-b", "chunk-c"] -await self.cache.set(chunk_ids, merged_result, namespace="merged_chunks") -``` - -## Cache Management REST API - -When the cache is enabled, the framework automatically registers a REST API for cache inspection and management at `/api/cache`. - -### Endpoints - -| Method | Path | Description | -|---|---|---| -| `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 - -```bash -# Retrieve a cached value -curl http://localhost:8000/api/cache/profiles/user:12345 - -# 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}' - -# Delete a specific key -curl -X DELETE http://localhost:8000/api/cache/profiles/user:12345 - -# 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: - -```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) -``` - -### Configuration Fields - -| 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 | - -## Redis Backend - -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. - -### Installation - -The Redis client is an optional extra. Install it explicitly: - -```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: - -```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 -``` - -### Field Reference - -| 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. | - -### Multi-Service Shared Redis - -When several microservices share one Redis cluster, set a unique `key_prefix` per service: - -```toml -# Service A -[default.cache] -backend = "redis" -key_prefix = "inventory-api" -redis_url = "redis://shared-redis:6379/0" - -# 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. - -### Graceful Degradation - -In development or non-critical environments, set `fallback_to_local = true` to keep the service running when Redis is unavailable: - -```toml -[default.cache] -backend = "redis" -redis_url = "redis://localhost:6379/0" -fallback_to_local = true -``` - -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. - -## File-Based Locking - -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. - -```toml -[default.cache] -# Shared cache directory across replicas -cache_dir = "/mnt/shared/blueprint-cache" -``` - -## Complete Example - -```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 - - -class EmbeddingService(ServiceBase): - async def on_startup(self) -> None: - self.cache = self.registry.cache_service - self.agent = self.registry.get_agent("embedder") - - 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 - - # Compute and cache - embedding = await self.agent.run(text) - await self.cache.set(text, embedding, namespace="embeddings", ttl=86400) - return embedding - - -class DocumentHandler(EventHandlerBase): - priority = 10 - - async def on_startup(self) -> None: - self.embedding_svc = self.registry.get_service(EmbeddingService) - - 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}, - ) - - def get_published_event_types(self) -> list[str]: - return ["document.embedded"] - - -config = Config(settings_files=["settings.toml"]) - -app = ( - AppBuilder(config) - .with_service(EmbeddingService) - .with_handler(DocumentHandler) - .with_agent("embedder", EmbedderAgent) - .with_cache() - .build() -) -``` diff --git a/docs/concepts/configuration.md b/docs/concepts/configuration.md deleted file mode 100644 index 326c849a..00000000 --- a/docs/concepts/configuration.md +++ /dev/null @@ -1,235 +0,0 @@ -# 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. - -## Config Class - -The `Config` class is the entry point for all configuration. It accepts a list of settings files and merges them in order, with later files overriding earlier ones. - -```python -from blueprint.agents import Config - -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`. - -## File Structure - -### settings.toml - -The primary configuration file. All settings live under a `[default]` section (the Dynaconf default environment). - -```toml -[default] -app_name = "document-processor" -log_level = "INFO" -event_bus = "dapr" -``` - -### 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. - -```toml -[default] -openai_api_key = "sk-..." -database_connection_string = "postgresql://user:pass@host/db" -``` - -## Environment Variable Interpolation - -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. - -```toml -[default] -openai_api_key = "${OPENAI_API_KEY}" -nats_url = "${NATS_URL}" -database_url = "${DATABASE_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, ...)`. - -```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_max_tokens = 2048 -model_temperature = 0.0 -``` - -### Cache Configuration - -Settings for the built-in disk cache service, under `[default.cache]`. - -```toml -[default.cache] -cache_dir = "/tmp/blueprint-cache" -size_limit = 1073741824 # 1 GB in bytes -eviction_policy = "least-recently-used" -default_ttl = 3600 # seconds -``` - -See the [Caching](caching.md) concept document for full details. - -### Event Publishing Configuration - -Controls how events are published, including the default pub/sub component and topic-to-event-type mappings. - -```toml -[default.event_publishing] -default_pubsub_name = "pubsub" - -[default.event_publishing.topic_mapping] -"document.received" = "documents-inbound" -"document.summarized" = "documents-processed" -"document.error" = "documents-errors" -``` - -See the [Event Processing](event-processing.md) concept document for full details. - -### Observability Configuration - -Settings for OpenTelemetry tracing and structured logging. - -```toml -[default] -otel_enabled = true -otel_endpoint = "http://localhost:4317" -otel_service_name = "document-processor" -log_level = "INFO" -``` - -See the [Observability](observability.md) concept document for full details. - -## Accessing Configuration at Runtime - -All components inherit access to configuration through `self.config`, which is available from `on_startup()` onward. - -### General Access - -```python -from blueprint.agents.services.service_base import ServiceBase - - -class StorageService(ServiceBase): - async def on_startup(self) -> None: - # Read a single value - db_url = self.config.get("database_url") - - # Read a value with a default - timeout = self.config.get("request_timeout", 30) -``` - -### 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. - -```python -from blueprint.agents.services.service_base import ServiceBase - - -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 -``` - -### Cache Configuration - -Use `get_cache_config()` to retrieve cache-related settings as a structured object. - -```python -cache_config = self.config.get_cache_config() -print(cache_config.cache_dir) # "/tmp/blueprint-cache" -print(cache_config.size_limit) # 1073741824 -print(cache_config.eviction_policy) # "least-recently-used" -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. - -```python -from blueprint.agents import AppBuilder, Config - -config = Config(settings_files=["settings.toml"]) - -try: - app = AppBuilder(config).with_agent("summarizer", SummarizerAgent).build() -except ConfigError as e: - # e.g., "Missing required config: default.runtimes.summarizer.model_provider" - 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 - -## Full Example settings.toml - -```toml -[default] -app_name = "document-processor" -log_level = "INFO" -event_bus = "dapr" - -# Observability -otel_enabled = true -otel_endpoint = "http://localhost:4317" -otel_service_name = "document-processor" - -# Event publishing -[default.event_publishing] -default_pubsub_name = "pubsub" - -[default.event_publishing.topic_mapping] -"document.received" = "documents-inbound" -"document.summarized" = "documents-processed" -"document.error" = "documents-errors" - -# AI runtimes -[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_max_tokens = 2048 -model_temperature = 0.0 - -# Cache -[default.cache] -cache_dir = "/tmp/blueprint-cache" -size_limit = 1073741824 -eviction_policy = "least-recently-used" -default_ttl = 3600 -``` diff --git a/docs/concepts/event-processing.md b/docs/concepts/event-processing.md deleted file mode 100644 index 06a0e531..00000000 --- a/docs/concepts/event-processing.md +++ /dev/null @@ -1,319 +0,0 @@ -# Event Processing - -Blueprint Agents uses the CloudEvents v1.0 specification as its universal message format. Events flow through a handler chain where each handler can inspect, process, transform, or forward events to downstream consumers. - -## CloudEvent Model - -The framework provides a generic `CloudEvent[T]` model that wraps the standard CloudEvents attributes with a typed data payload. - -```python -from blueprint.agents.models.events import CloudEvent, GenericCloudEvent -``` - -### Core Fields - -| Field | Type | Description | -|---|---|---| -| `id` | `str` | Unique event identifier (UUID by default) | -| `type` | `str` | Event type identifier, e.g. `"document.received"` | -| `source` | `str` | URI identifying the event producer | -| `subject` | `str` | Subject of the event in context of the source | -| `time` | `datetime` | Timestamp when the event was created | -| `data` | `T` | The event payload, typed by the generic parameter | - -### GenericCloudEvent - -For cases where the data payload does not require a specific schema, use the pre-defined alias: - -```python -# GenericCloudEvent is equivalent to CloudEvent[dict[str, Any]] -event = GenericCloudEvent( - type="document.received", - source="/ingest/api", - subject="doc-12345", - data={"content": "The full document text...", "format": "plaintext"}, -) -``` - -### Typed Events - -For structured payloads, parameterize `CloudEvent` with a Pydantic model or dataclass: - -```python -from pydantic import BaseModel -from blueprint.agents.models.events import CloudEvent - - -class DocumentPayload(BaseModel): - content: str - format: str - word_count: int - - -event: CloudEvent[DocumentPayload] = CloudEvent( - type="document.received", - source="/ingest/api", - subject="doc-12345", - data=DocumentPayload(content="...", format="plaintext", word_count=1500), -) -``` - -## 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. - -### 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. - -```python -from blueprint.agents.handler.event_handler_base import EventHandlerBase -from blueprint.agents.models.events import CloudEvent - - -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 EnrichmentHandler(EventHandlerBase): - priority = 10 # Runs after validation - - def can_handle_event(self, event: CloudEvent) -> 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) -``` - -### Handler Methods - -Every handler must implement two methods: - -- **`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. - -## Return Values from handle_event - -The return value of `handle_event()` determines what happens after processing: - -### Return None -- Pass to Next Handler - -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. - -```python -async def handle_event(self, event: CloudEvent) -> None: - await self.log_event(event) - return None # Continue chain -``` - -### 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 a List of HandlerResult -- Publish Multiple Events - -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 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. - -```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()} -``` - -## Declaring Published Event Types - -Each handler should declare the event types it may produce. The framework uses this metadata for validation and documentation. - -```python -class DocumentHandler(EventHandlerBase): - def get_published_event_types(self) -> list[str]: - return ["document.summarized", "document.error"] -``` - -## Event Bus Configuration - -Blueprint Agents supports two event bus backends: Dapr and NATS. The choice is made in `settings.toml`. - -### Selecting the Event Bus - -```toml -[default] -event_bus = "dapr" # "dapr", "nats", or "sessions" -``` - -### Topic Mapping - -Map event types to topics so the framework knows where to publish each event: - -```toml -[default.event_publishing] -default_pubsub_name = "pubsub" - -[default.event_publishing.topic_mapping] -"document.received" = "documents-inbound" -"document.summarized" = "documents-processed" -"document.error" = "documents-errors" -``` - -## Dapr Event Bus - -When `event_bus = "dapr"`, the framework integrates with the Dapr sidecar for pub/sub messaging. - -- **Receiving events**: The application exposes an HTTP endpoint at `/events/{topic}`. The Dapr sidecar delivers messages by calling this endpoint. -- **Publishing events**: The framework publishes events through the Dapr sidecar HTTP API (`/v1.0/publish/{pubsub}/{topic}`). - -Dapr handles message delivery guarantees, retries, and dead-letter queues through its component configuration. - -```toml -[default] -event_bus = "dapr" - -[default.event_publishing] -default_pubsub_name = "pubsub" - -[default.event_publishing.topic_mapping] -"document.received" = "documents" -``` - -## NATS Event Bus - -When `event_bus = "nats"`, the framework connects directly to a NATS server. - -- **Receiving events**: The framework subscribes to NATS subjects mapped from topic names. -- **Publishing events**: Messages are published directly to NATS subjects. -- **JetStream**: Optional JetStream support provides persistence, replay, and at-least-once delivery guarantees. - -```toml -[default] -event_bus = "nats" -nats_url = "nats://localhost:4222" - -[default.event_publishing] -default_pubsub_name = "default" - -[default.event_publishing.topic_mapping] -"document.received" = "documents.inbound" -"document.summarized" = "documents.processed" -``` - -## Sessions Transport - -When `event_bus = "sessions"`, `AppBuilder.build()` wires three components automatically: - -1. `SessionsApiClient` — REST client for the sessions service -2. `SessionKeyProvider` — session-key resolution with TTL cache -3. `SessionsBus` — outbound SSE consumer that converts job notifications into CloudEvents and dispatches them through the handler chain - -`SessionsBus` has no inbound HTTP surface — there is no router to mount. Connection to the sessions service is established asynchronously after startup; the framework tolerates a sessions service that is unreachable at boot and retries in the background. - -> **Agent registration (sessions v0.4.0+):** Before opening the SSE job stream, `SessionsBus` calls -> `POST /agents/register` to declare its `agent_id`, `agent_type`, and `capabilities` — the dispatch -> source of truth. It re-registers before every reconnect attempt (idempotent), and on graceful -> shutdown it drains in-flight jobs and unregisters (`DELETE /agents/{agent_id}`). Against a pre-v0.4.0 -> server the register call returns 404 and is skipped ("legacy, proceed without registration"). - -> **Reconnect catch-up:** SSE only pushes jobs created *while connected*, so jobs created during a -> restart, redeploy, or stream gap would otherwise be missed. On every (re)connect `SessionsBus` -> reconciles in two ways: it resumes the stream with `Last-Event-ID` (the server replays missed -> frames from its ring buffer on a same-process reconnect), and it runs a REST **catch-up** — -> `GET /jobs?status=pending` for its capabilities — dispatching any pending jobs through the normal -> handler path. Both feed the same idempotent handler, so a job that arrives via more than one route -> is processed once. Catch-up is best-effort: a listing failure is logged and never disturbs the live -> stream. A job stranded in `running` because its previous owner crashed is recovered server-side -> (the sessions reaper re-pends it) and then redelivered by this catch-up. - -```toml -[default] -event_bus = "sessions" - -[default.sessions_service] -base_url = "http://sessions:8000" -agent_id = "my-agent" -agent_type = "analyser" -capabilities = ["analyse_documents"] -api_key = "@format {env[SESSIONS_API_KEY]}" -# Optional per-agent HS256 bearer. Sent as `Authorization: Bearer ` alongside -# `X-Api-Key` on the gated routes only when set. See service-sessions#198/#326. Inject via -# SESSIONS_AGENT_TOKEN, never commit it. To opt out, OMIT this line (or export an empty -# SESSIONS_AGENT_TOKEN=) — keeping it with the env var undefined fails Dynaconf config load. -agent_token = "@format {env[SESSIONS_AGENT_TOKEN]}" -max_concurrent_jobs = 5 -job_timeout_seconds = 300 -``` - -## Complete Handler Example - -```python -from blueprint.agents.handler.event_handler_base import EventHandlerBase -from blueprint.agents.models.events import CloudEvent, HandlerResult - - -class IngestionHandler(EventHandlerBase): - priority = 5 - - async def on_startup(self) -> None: - self.storage = self.registry.get_service(StorageService) - self.cache = self.registry.cache_service - - 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 - - # 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 - - # Store the document - await self.storage.save(doc_id, event.data) - await self.cache.set(doc_id, True, namespace="ingested", ttl=3600) - - # Publish downstream - return HandlerResult( - event_type="document.stored", - data={"doc_id": doc_id, "source": event.source}, - ) - - def get_published_event_types(self) -> list[str]: - return ["document.stored", "document.ingestion_error"] -``` diff --git a/docs/concepts/observability.md b/docs/concepts/observability.md deleted file mode 100644 index ac97ea16..00000000 --- a/docs/concepts/observability.md +++ /dev/null @@ -1,298 +0,0 @@ -# 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. - -## OpenTelemetry Tracing - -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. - -### Configuration - -Enable tracing in `settings.toml`: - -```toml -[default] -otel_enabled = true -otel_endpoint = "http://localhost:4317" -otel_service_name = "document-processor" -``` - -| Field | Type | Description | -|---|---|---| -| `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 | - -### Automatic FastAPI Instrumentation - -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. - -### Automatic CloudEvent Attribute Extraction - -When an event handler processes a CloudEvent, the framework automatically extracts event metadata and attaches it to the active span: - -- `cloudevent.id` -- The unique event identifier -- `cloudevent.type` -- The event type string -- `cloudevent.source` -- The event source URI -- `cloudevent.subject` -- The event subject - -This makes it straightforward to correlate traces with specific events in your observability backend. - -## The @traced() Decorator - -For custom spans on application-specific logic, use the `@traced()` decorator on any async method: - -```python -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") - - @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) - - @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 decorator creates a span named `{ClassName}.{method_name}` by default. Nested `@traced()` calls produce parent-child span relationships, giving full visibility into call hierarchies. - -### Custom Span Names - -Pass a name argument to override the default span name: - -```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. - -### Token Usage Metrics - -For every AI agent invocation, the following metrics are recorded: - -| 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 - -| Metric | Description | -|---|---| -| `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. - -## Structured Logging - -Blueprint Agents uses structured logging with correlation context. Log messages are formatted with key-value pairs that are queryable in log aggregation systems. - -### 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). - -```python -import logging - -logger = logging.getLogger(__name__) - - -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) - - # Incorrect: f-string formatting (defeats structured logging) - # logger.info(f"Processing document {event.subject} from source {event.source}") - - result = await self.process(event) - logger.debug("Processing complete for %s, result size: %d", event.subject, len(result)) - - return HandlerResult(event_type="document.processed", data=result) -``` - -### Log Level Configuration - -Set the log level in `settings.toml`: - -```toml -[default] -log_level = "INFO" # DEBUG, INFO, WARNING, ERROR, CRITICAL -``` - -### Correlation Context - -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. - -## Health Checks - -The framework automatically registers health check endpoints on the FastAPI application. These endpoints follow standard conventions for container orchestration platforms such as Kubernetes. - -### 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. | - -### Response Format - -The `/health/detailed` endpoint returns structured information about each component: - -```json -{ - "status": "healthy", - "components": { - "EmbeddingService": {"status": "healthy"}, - "DocumentHandler": {"status": "healthy"}, - "summarizer": {"status": "healthy", "type": "agent"}, - "cache": {"status": "healthy", "entries": 1523} - }, - "uptime_seconds": 3847 -} -``` - -### Custom Health Checkers - -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() -) -``` - -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. - -## Complete Configuration Example - -```toml -[default] -app_name = "document-processor" -log_level = "INFO" - -# OpenTelemetry -otel_enabled = true -otel_endpoint = "http://otel-collector:4317" -otel_service_name = "document-processor" -``` - -## Complete Code Example - -```python -import logging - -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__) - - -class AnalyticsService(ServiceBase): - async def on_startup(self) -> None: - self.agent = self.registry.get_agent("analyzer") - - @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 - - -class AnalyticsHandler(EventHandlerBase): - priority = 10 - - async def on_startup(self) -> None: - self.analytics = self.registry.get_service(AnalyticsService) - - def can_handle_event(self, event: CloudEvent) -> bool: - return event.type == "document.received" - - @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() -) -``` 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/guides/cli-reference.md b/docs/guides/cli-reference.md deleted file mode 100644 index e54b5eaf..00000000 --- a/docs/guides/cli-reference.md +++ /dev/null @@ -1,925 +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` | `DocumentAnalyzer` | `document_analyzer_agent.py` | No "Agent" suffix in class name | -| **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: product_catalog_models.py (without the "_api" suffix) -``` - -#### Agent Examples -```bash -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() -``` - -### 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 -``` - -### Arguments - -| Argument | Description | Required | -|----------------|------------------------------------|----------| -| `project-name` | Name of the project to create | Yes | - -### Generated Project Structure - -``` -/ - src/ - main.py - handlers/ - services/ - api/ - models/ - prompts/ - tests/ - unit/ - integration/ - settings.toml - secrets.toml - pyproject.toml - Dockerfile -``` - -### Example - -```bash -asbs setup my-ai-service -``` - -The generated `main.py` contains the minimal application bootstrap: - -```python -from blueprint.agents import AppBuilder, Config - -app = AppBuilder(Config()).build() -``` - ---- - -## asbs create handler - -Generate a new event handler component by creating a subclass of `EventHandlerBase`. - -```bash -asbs create handler [--event-type ] [--priority ] -``` - -### 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) | `0` | - -### 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=0) - - 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 -``` - -### Arguments - -| Argument | Description | Required | -|----------|---------------------------------|----------| -| `name` | Name of the service to create | Yes | - -### 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 -``` - -### Arguments - -| Argument | Description | Required | -|----------|------------------------------|----------| -| `name` | Name of the API to create | Yes | - -### Naming - -API names are converted to `Api` format with an accompanying models file: - -- Input: `order_management` - - Class: `OrderManagementApi` - - API File: `order_management_api.py` - - Models File: `order_management_models.py` - -### 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(...)` - -2. **Models File** (`src/models/_models.py`) - - Request and Response Pydantic models - - Example: `OrderManagementRequest` and `OrderManagementResponse` - -### 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 `OrderManagementApi` class -- `src/models/order_management_models.py` with `OrderManagementRequest` and `OrderManagementResponse` classes - -#### 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_models 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 - -Generate an AI agent component with `AgentRuntime`, `AgentBuilder` boilerplate, system prompt, instruction prompt, and settings configuration. - -```bash -asbs create agent -``` - -### Arguments - -| Argument | Description | Required | -|----------|--------------------------------|----------| -| `name` | Name of the agent to create | Yes | - -### 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` - -### Files Generated - -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 - -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 - -4. **Settings Configuration** (`settings.toml`) - - `[default.runtimes.]` section with model configuration - - Model provider, name, temperature, and token limits - -### Auto-Registration - -The created agent is automatically: -- Imported in `src/main.py` -- Agent instance created before `app =` -- Registered with `.with_agent(_agent)` -- Configuration added to `settings.toml` - -### Examples - -#### Basic Agent - -```bash -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` - -#### Agent Generated Code - -The generated agent builder includes: - -```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") - ) - - return agent -``` - -#### Settings Configuration - -Auto-generated in `settings.toml`: - -```toml -[default.runtimes.document_analyzer] -model_provider = "openai" -model_name = "gpt-4o-mini" -model_temperature = 0.7 -model_max_tokens = 2000 -``` - -Override any defaults in your `settings.toml` after creation. - ---- - -## asbs create scheduler - -Generate a scheduled task component by creating a subclass of `SchedulerBase`. - -```bash -asbs create scheduler [--cron ] -``` - -### Arguments - -| Argument | Description | Required | -|----------|------------------------------------|----------| -| `name` | Name of the scheduler to create | Yes | - -### Options - -| Flag | Description | Default | -|------------------|--------------------------------------|---------------| -| `--cron ` | Cron expression for the schedule | `0 * * * *` | - -### 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 files. Checks for required directories, valid `settings.toml` entries, correct component registrations, and import consistency. - -```bash -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 - -### Example - -```bash -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 -``` - ---- - -## asbs dev - -Run the application in development mode with hot reload enabled. Uses `uvicorn` under the hood. - -```bash -asbs dev [--port ] -``` - -### Options - -| Flag | Description | Default | -|------------------|----------------------------------|---------| -| `--port ` | Port to bind the server to | `8000` | - -### 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 -- `AppBuilder(config)` instantiation -- `.build()` call - -Example valid structure: -```python -from blueprint.agents import AppBuilder, Config - -config = Config(...) - -app = ( - AppBuilder(config) - # Components added here - .build() -) -``` - -### Manual Registration - -If auto-registration fails, the CLI displays instructions. Follow this pattern for each component type: - -#### Handler -```python -# In src/main.py - -from src.handlers.order_placed_handler import OrderPlacedHandler - -app = ( - AppBuilder(config) - .with_handler(OrderPlacedHandler()) - .build() -) -``` - -#### Service -```python -# In src/main.py - -from src.services.invoice_processor_service import InvoiceProcessorService - -app = ( - AppBuilder(config) - .with_service(InvoiceProcessorService()) - .build() -) -``` - -#### API -```python -# In src/main.py - -from src.models.order_management_models import OrderManagementRequest, OrderManagementResponse -from src.api.order_management_api import OrderManagementApi - -app = ( - AppBuilder(config) - .with_rest_api(OrderManagementApi()) - .build() -) -``` - -#### Agent -```python -# In src/main.py - -from src.agents.document_analyzer_agent import build_document_analyzer_agent - -document_analyzer_agent: AgentRuntime = build_document_analyzer_agent(config) - -app = ( - AppBuilder(config) - .with_agent(document_analyzer_agent) - .build() -) -``` - -#### Scheduler -```python -# In src/main.py - -from src.schedulers.cleanup_scheduler import CleanupScheduler - -app = ( - AppBuilder(config) - .with_scheduler(CleanupScheduler()) - .build() -) -``` - -### 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 -app = ( - AppBuilder(config) - # 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) - # 4. Schedulers - .with_scheduler(CleanupScheduler()) - .build() -) -``` - ---- - -## asbs claude - -Generate or update Claude Code context files for AI integration. The CLI creates framework and project-specific CLAUDE.md files automatically. - -```bash -asbs claude [create|update] -``` - -### Subcommands - -| Subcommand | Description | -|------------|----------------------------------------------------------| -| `create` | Generate new Claude Code context files | -| `update` | Update existing Claude Code context files | - -### CLAUDE.md Placement - -The CLI creates and manages files in a consistent structure: - -| 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) | - -### Framework CLAUDE.md - -Running `asbs claude create` generates: - -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 - -2. **`.claude/` directory** - Generated context for Claude Code: - - Agent documentation in `.claude/agents/` - - Skill definitions in `.claude/skills/` - - Automatically updated when components are created - -### Example - -```bash -# Generate initial Claude Code context files -asbs claude create - -# Update after adding new components -asbs claude update -``` - -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: - -```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/docs/guides/deployment.md b/docs/guides/deployment.md deleted file mode 100644 index 622d3851..00000000 --- a/docs/guides/deployment.md +++ /dev/null @@ -1,429 +0,0 @@ -# Deployment Guide - -This guide covers packaging, deploying, and operating Blueprint Agents applications in production environments using Docker, Kubernetes, and Helm. - ---- - -## Docker - -### Dockerfile - -Blueprint Agents projects ship with a multi-stage Dockerfile. The following template provides a production-ready build: - -```dockerfile -# Stage 1: Base image -FROM python:3.13-slim AS base - -ENV PYTHONDONTWRITEBYTECODE=1 -ENV PYTHONUNBUFFERED=1 - -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 settings.toml ./ -COPY prompts/ ./prompts/ - -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 -``` - -### Environment Variable Overrides - -Blueprint Agents uses Dynaconf for configuration. Any setting in `settings.toml` can be overridden at runtime using environment variables prefixed with `DYNACONF_`: - -```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: - -```toml -[llm] -api_key = "sk-..." -``` - ---- - -## Kubernetes with Helm - -### Helm Chart Structure - -``` -helm/ - Chart.yaml - values.yaml - templates/ - deployment.yaml - service.yaml - configmap.yaml - hpa.yaml -``` - -### values.yaml - -```yaml -replicaCount: 2 - -image: - repository: myregistry.azurecr.io/my-ai-service - tag: "latest" - pullPolicy: IfNotPresent - -service: - type: ClusterIP - port: 80 - targetPort: 8000 - -dapr: - enabled: true - appId: "my-ai-service" - appPort: 8000 - logLevel: "info" - -app: - port: 8000 - logLevel: "info" - -resources: - requests: - cpu: 250m - memory: 512Mi - limits: - cpu: "1" - memory: 1Gi - -probes: - liveness: - path: /health/live - initialDelaySeconds: 15 - periodSeconds: 20 - timeoutSeconds: 5 - failureThreshold: 3 - readiness: - path: /health/ready - initialDelaySeconds: 10 - periodSeconds: 10 - timeoutSeconds: 5 - failureThreshold: 3 - -autoscaling: - enabled: false - minReplicas: 2 - maxReplicas: 10 - targetCPUUtilizationPercentage: 70 -``` - -### Deployment Template - -```yaml -# templates/deployment.yaml -apiVersion: apps/v1 -kind: Deployment -metadata: - name: {{ .Release.Name }} - labels: - app: {{ .Release.Name }} -spec: - replicas: {{ .Values.replicaCount }} - selector: - matchLabels: - app: {{ .Release.Name }} - template: - metadata: - labels: - app: {{ .Release.Name }} - annotations: - {{- if .Values.dapr.enabled }} - dapr.io/enabled: "true" - dapr.io/app-id: {{ .Values.dapr.appId | quote }} - dapr.io/app-port: {{ .Values.dapr.appPort | quote }} - dapr.io/log-level: {{ .Values.dapr.logLevel | quote }} - {{- end }} - spec: - containers: - - name: {{ .Release.Name }} - image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" - imagePullPolicy: {{ .Values.image.pullPolicy }} - ports: - - containerPort: {{ .Values.app.port }} - envFrom: - - configMapRef: - name: {{ .Release.Name }}-config - - secretRef: - name: {{ .Release.Name }}-secrets - optional: 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: - path: {{ .Values.probes.readiness.path }} - 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 }} -``` - -### Service Template - -```yaml -# templates/service.yaml -apiVersion: v1 -kind: Service -metadata: - name: {{ .Release.Name }} -spec: - type: {{ .Values.service.type }} - ports: - - port: {{ .Values.service.port }} - targetPort: {{ .Values.service.targetPort }} - protocol: TCP - selector: - app: {{ .Release.Name }} -``` - -### ConfigMap Template - -```yaml -# templates/configmap.yaml -apiVersion: v1 -kind: ConfigMap -metadata: - name: {{ .Release.Name }}-config -data: - DYNACONF_APP__PORT: {{ .Values.app.port | quote }} - DYNACONF_APP__LOG_LEVEL: {{ .Values.app.logLevel | quote }} -``` - -### Deploying with Helm - -```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=3 - -# 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 -``` - ---- - -## Health Probes - -Blueprint Agents provides three built-in health endpoints: - -### /health/live - -Returns a simple liveness check indicating the application process is running. - -```json -{ - "status": "alive" -} -``` - -Use this for the Kubernetes liveness probe. If this endpoint fails, the container should be restarted. - -### /health/ready - -Returns a readiness check indicating the application and its dependencies are ready to serve traffic. - -```json -{ - "status": "ready" -} -``` - -Use this for the Kubernetes readiness probe. If this endpoint fails, the pod is removed from the service load balancer until it recovers. - -### /health/detailed - -Returns component-level health status for debugging and monitoring. - -```json -{ - "status": "healthy", - "components": { - "cache": {"status": "healthy", "latency_ms": 2}, - "llm_provider": {"status": "healthy", "latency_ms": 150}, - "event_bus": {"status": "healthy", "latency_ms": 5} - } -} -``` - -### Kubernetes Probe Configuration - -```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 -``` - ---- - -## Environment Configuration - -### Settings via ConfigMap - -Non-sensitive configuration values belong in a Kubernetes ConfigMap: - -```yaml -apiVersion: v1 -kind: ConfigMap -metadata: - name: my-ai-service-config -data: - DYNACONF_APP__PORT: "8000" - DYNACONF_APP__LOG_LEVEL: "info" - DYNACONF_CACHE__TTL: "3600" - DYNACONF_LLM__PROVIDER: "openai" - DYNACONF_LLM__MODEL: "gpt-4" -``` - -### 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 -type: Opaque -stringData: - DYNACONF_LLM__API_KEY: "sk-..." - DYNACONF_DATABASE__PASSWORD: "secret-password" -``` - -### Dynaconf Override Hierarchy - -Dynaconf resolves configuration in the following order (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. - ---- - -## Scaling Considerations - -### Horizontal Pod Autoscaling - -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 - -When running multiple replicas, be aware of cache behavior: - -- **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. - -### Stateless Design - -Handlers and services should be designed as stateless components: - -- 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. diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md deleted file mode 100644 index 71e8f13e..00000000 --- a/docs/guides/troubleshooting.md +++ /dev/null @@ -1,568 +0,0 @@ -# Troubleshooting Guide - -This guide covers common issues encountered when developing and deploying Blueprint Agents applications, along with their causes and solutions. - ---- - -## Installation Issues - -### Wrong Python Version - -**Symptom:** Installation fails with an error referencing unsupported syntax or incompatible package versions. - -``` -ERROR: Package 'avs-blueprint-agents' requires a different Python: 3.10.x not in '>=3.13' -``` - -**Cause:** Blueprint Agents requires Python 3.13 or later. - -**Solution:** Install the correct Python version and verify it is active: - -```bash -python --version -# Must be 3.13 or later - -# If using pyenv -pyenv install 3.13.0 -pyenv local 3.13.0 -``` - -### pip vs uv Installation - -**Symptom:** Dependencies fail to resolve or installation is unexpectedly slow. - -**Cause:** The standard `pip` resolver may struggle with complex dependency trees. - -**Solution:** Use `uv` for faster and more reliable installs: - -```bash -pip install uv -uv pip install avs-blueprint-agents -``` - -### TestPyPI Configuration - -**Symptom:** Package not found when installing a pre-release version. - -``` -ERROR: Could not find a version that satisfies the requirement avs-blueprint-agents==0.6.0a3 -``` - -**Cause:** Pre-release versions may be hosted on TestPyPI rather than the main PyPI index. - -**Solution:** Configure pip to check TestPyPI as an additional index: - -```bash -pip install avs-blueprint-agents==0.6.0a3 \ - --index-url https://test.pypi.org/simple/ \ - --extra-index-url https://pypi.org/simple/ -``` - ---- - -## Configuration Errors - -### ConfigError on Startup - -**Symptom:** Application crashes immediately with a `ConfigError` or `ValidationError`. - -``` -blueprint.agents.exceptions.ConfigError: Missing required configuration: 'app.name' -``` - -**Cause:** Required settings are missing from `settings.toml` or have not been provided via environment variables. - -**Solution:** Verify that `settings.toml` contains all required keys: - -```toml -[app] -name = "my-ai-service" -port = 8000 - -[llm] -provider = "openai" -model = "gpt-4" -``` - -Check which settings are required by running validation: - -```bash -asbs validate -``` - -### Missing Required Settings - -**Symptom:** A specific component fails to initialize because a setting it depends on is absent. - -**Cause:** The component expects a configuration key that was not provided. - -**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" -``` - -### Invalid Port Configuration - -**Symptom:** Server fails to bind on startup. - -``` -[ERROR] Could not bind to port 80: Permission denied -``` - -**Cause:** The configured port is privileged (below 1024) or already in use. - -**Solution:** Use a non-privileged port in `settings.toml`: - -```toml -[app] -port = 8000 -``` - -Or check for port conflicts: - -```bash -lsof -i :8000 -``` - ---- - -## Event Bus Connectivity - -### Dapr Sidecar Not Running - -**Symptom:** Application logs show errors when attempting to publish or subscribe to events. - -``` -ConnectionRefusedError: Cannot connect to Dapr sidecar at localhost:3500 -``` - -**Cause:** The Dapr sidecar process is not running alongside the application. - -**Solution:** - -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 -``` - -In Kubernetes, verify the Dapr annotations are present on the pod: - -```yaml -annotations: - dapr.io/enabled: "true" - dapr.io/app-id: "my-ai-service" - dapr.io/app-port: "8000" -``` - -### NATS Connection Refused - -**Symptom:** Event bus fails to connect to the NATS server. - -``` -nats.errors.ConnectionClosedError: connection refused -``` - -**Cause:** The NATS server is not reachable at the configured address. - -**Solution:** Verify the NATS server is running and accessible: - -```bash -# Check if NATS is running locally -nats-server --addr 0.0.0.0 --port 4222 - -# Test connectivity -nats sub test.subject -``` - -In Kubernetes, verify the NATS service is deployed and the Dapr component configuration points to the correct address. - -### 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. - -**Solution:** Verify that the event types match exactly between publisher and subscriber: - -```python -# Publisher -await event_bus.publish(topic="order.created", data=order_data) - -# Handler -- event_type must match exactly -class OrderHandler(EventHandlerBase): - event_type = "order.created" # Must match the publish topic -``` - -Check the Dapr subscription configuration to ensure topic mappings are correct. - ---- - -## LLM Provider Issues - -### Missing API Key - -**Symptom:** Agent calls fail with an authentication error. - -``` -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): - -```toml -# secrets.toml (local only -- do not commit) -[llm] -api_key = "sk-..." -``` - -```bash -# Environment variable -export DYNACONF_LLM__API_KEY="sk-..." -``` - -### Invalid Model Name - -**Symptom:** Agent initialization fails with a model-not-found error. - -``` -InvalidRequestError: The model 'gpt-5-turbo' does not exist -``` - -**Cause:** The configured model name is not recognized by the LLM provider. - -**Solution:** Verify the model name against the provider's documentation: - -```toml -[llm] -provider = "openai" -model = "gpt-4" # Use a valid model identifier -``` - -### Timeout Errors - -**Symptom:** LLM calls fail intermittently with timeout errors. - -``` -TimeoutError: Request timed out after 30.0 seconds -``` - -**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: - -```toml -[llm] -timeout = 60 # seconds -``` - -Alternatively, consider breaking complex prompts into smaller steps or implementing retry logic in your service. - -### Provider Not Supported - -**Symptom:** Application raises an error about an unsupported LLM provider. - -``` -ValueError: LLM provider 'anthropic_legacy' is not supported -``` - -**Cause:** The provider name in configuration does not match any registered provider. - -**Solution:** Use a supported provider name: - -```toml -[llm] -provider = "openai" # OpenAI API -# provider = "azure" # Azure OpenAI -# provider = "anthropic" # Anthropic Claude -``` - ---- - -## Component Registration Errors - -### Duplicate Component Names - -**Symptom:** Application fails to start with a duplicate registration error. - -``` -RegistrationError: Component 'order_handler' is already registered -``` - -**Cause:** Two components share the same `name` attribute. - -**Solution:** Ensure every component has a unique `name`: - -```python -class OrderCreatedHandler(EventHandlerBase): - name = "order_created_handler" # Must be unique - -class OrderUpdatedHandler(EventHandlerBase): - name = "order_updated_handler" # Must be unique -``` - -Run validation to detect duplicates: - -```bash -asbs validate -``` - -### Missing Dependencies in on_startup - -**Symptom:** A service raises a `KeyError` or `None` reference when trying to access another service during startup. - -``` -KeyError: 'pricing_engine' -``` - -**Cause:** The service is trying to access a dependency from the registry before that dependency has been registered and started. - -**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" - - 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__ - -**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() -``` - ---- - -## Health Check Failures - -### Client Health Checker Failing - -**Symptom:** The `/health/ready` endpoint returns unhealthy status for a specific client or external dependency. - -```json -{ - "status": "unhealthy", - "components": { - "llm_provider": {"status": "unhealthy", "error": "Connection refused"} - } -} -``` - -**Cause:** The external service that the health checker is testing is unreachable. - -**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: - -```python -# Verify the health check endpoint is correct -health_checker = ClientHealthChecker( - name="llm_provider", - url="https://api.openai.com/v1/models", - timeout=5 -) -``` - -### Custom Health Checkers - -**Symptom:** You need to add a health check for a custom dependency. - -**Solution:** Implement a custom health checker and register it with the application: - -```python -from blueprint.agents.health import HealthCheckerBase - - -class DatabaseHealthChecker(HealthCheckerBase): - name = "database" - - async def check(self) -> dict: - try: - await self.db.ping() - return {"status": "healthy"} - except Exception as e: - return {"status": "unhealthy", "error": str(e)} -``` - ---- - -## Cache Issues - -### Permission Errors on Cache Directory - -**Symptom:** Cache operations fail with permission errors. - -``` -PermissionError: [Errno 13] Permission denied: '/app/.cache/data.db' -``` - -**Cause:** The application process does not have write permissions to the cache directory. - -**Solution:** In Docker, ensure the cache directory is writable: - -```dockerfile -RUN mkdir -p /app/.cache && chmod 777 /app/.cache -``` - -In Kubernetes, use an `emptyDir` volume: - -```yaml -volumes: - - name: cache-volume - emptyDir: {} -volumeMounts: - - name: cache-volume - mountPath: /app/.cache -``` - -### Disk Full - -**Symptom:** Cache writes fail with a disk space error. - -``` -OSError: [Errno 28] No space left on device -``` - -**Cause:** The cache has grown beyond the available disk space. - -**Solution:** Configure a cache size limit in `settings.toml`: - -```toml -[cache] -max_size_mb = 500 -ttl = 3600 # Entries expire after 1 hour -``` - -In Kubernetes, set a size limit on the `emptyDir` volume: - -```yaml -volumes: - - name: cache-volume - emptyDir: - sizeLimit: 1Gi -``` - -### Stale Cache - -**Symptom:** The application returns outdated data despite changes in the source. - -**Cause:** Cached entries have not expired and are being served instead of fresh data. - -**Solution:** Reduce the TTL or clear the cache manually: - -```toml -[cache] -ttl = 300 # 5 minutes -``` - -To clear the cache programmatically: - -```python -cache = self.registry.get_service("cache") -await cache.clear() -``` - ---- - -## Testing Issues - -### Async Test Setup - -**Symptom:** Async tests fail with `RuntimeWarning: coroutine was never awaited` or `PytestUnraisableExceptionWarning`. - -**Cause:** pytest is not configured to handle async test functions. - -**Solution:** Install `pytest-asyncio` and set the mode to `auto` in `pyproject.toml`: - -```bash -pip install pytest-asyncio -``` - -```toml -[tool.pytest.ini_options] -asyncio_mode = "auto" -``` - -With `asyncio_mode = "auto"`, all async test functions are detected automatically. You do not need the `@pytest.mark.asyncio` decorator. - -### Mock Registry Patterns - -**Symptom:** Tests fail because the component cannot access services from the registry. - -**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: - -```python -import pytest -from unittest.mock import MagicMock, AsyncMock - - -@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 - - -@pytest.fixture -def my_service(mock_registry): - from src.services.my_service import MyService - svc = MyService() - svc.registry = mock_registry - return svc -``` - -### Missing pytest-asyncio - -**Symptom:** Tests are collected but skipped or produce warnings about missing async support. - -``` -PytestUnhandledCoroutineWarning: async def functions are not natively supported -``` - -**Cause:** The `pytest-asyncio` package is not installed. - -**Solution:** - -```bash -pip install pytest-asyncio -``` - -Verify it is listed in your test dependencies in `pyproject.toml`: - -```toml -[project.optional-dependencies] -test = [ - "pytest>=7.0", - "pytest-asyncio>=0.21", - "pytest-mock>=3.10", - "httpx>=0.24", -] -``` 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 99% rename from docs/superpowers/plans/2026-04-01-component-naming-refactor.md rename to docs/plans/2026-04-01-component-naming-refactor.md index 97c425dd..dadd4c3f 100644 --- a/docs/superpowers/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. 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 new file mode 100644 index 00000000..20f142b1 --- /dev/null +++ b/docs/plans/2026-08-28-multi-agent-grouping-changelog.md @@ -0,0 +1,361 @@ +# 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` | +| **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` | + +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 + +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. + +**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. +- 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. +- 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 + 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 + 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 + 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 + 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 + 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 + 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 + 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, + `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 + 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`, + `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`; + `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 + 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` + 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`, + `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 + 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 + 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, + 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 + 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 + 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. +- 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. +- 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, +heartbeat, run timeout, reconnect with resubscription, named connections without permission +violations, skipped results, delivery attempts. + +--- + +## Compatibility + +Every breaking change, with its migration, is listed in `CHANGELOG.md` under +`[Unreleased]` -> *Breaking*. The two that most often bite: + +- **`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. + +`tests/unit/agents/test_frozen_compatibility.py` holds what existing projects do; it is never edited +to accommodate an API change. + +--- + +## Open points + +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. +- **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`. 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..c90415f2 --- /dev/null +++ b/docs/plans/2026-08-28-multi-agent-grouping.md @@ -0,0 +1,1413 @@ +# Plan -- Multi-Agent Grouping + +| | | +|---|---| +| **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` | +| **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 +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.**~~ **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 +(`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.**~~ **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 +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. 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 +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:** 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 +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 — **the same builder**, minus its `config` argument and minus the `.build()`: +```python +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. `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 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. + +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 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 = ( + 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). + +--- + +## 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` | **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 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}/` | +| `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) + +> **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`: +- 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 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. + +--- + +## 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 + +> **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): + - 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: 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. + +`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.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 + `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 = AgentGroup(config).with_group(group).build() + run_app(app, config) +``` + +`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 + 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` 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 +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 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`, +`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. +- `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 +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) | + +--- + +## 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 -- 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. + +**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 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) -- **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 `-`. +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. + +**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, 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. **Landed.** + +--- + +## File change summary + +| File | Phase | +|---|---| +| `utils/utils.py` | 0 | +| `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) | +| `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, 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 | +| `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), 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 +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 | +|---|---| +| `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)** — 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 + +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` / `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 + 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. + +**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 + 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/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/plans/2026-09-11-broker-integration-tests.md b/docs/plans/2026-09-11-broker-integration-tests.md new file mode 100644 index 00000000..a7b72e38 --- /dev/null +++ b/docs/plans/2026-09-11-broker-integration-tests.md @@ -0,0 +1,441 @@ +# Broker integration tests + +| | | +|---|---| +| **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. | + +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 + +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. 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.** 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 + +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.**~~ **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.**~~ **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 + 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.**~~ **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 + 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 + +### 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** +(`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/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/plans/2026-10-14-named-connections.md b/docs/plans/2026-10-14-named-connections.md new file mode 100644 index 00000000..f2fb4d1d --- /dev/null +++ b/docs/plans/2026-10-14-named-connections.md @@ -0,0 +1,367 @@ +# 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. `a20a2b7` 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 unset = one run at a time *per subscription* (what every + 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. + - 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 `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 + 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 + (`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. + +- **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). +- **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. + +--- + +## 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 `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, + 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. 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); + - 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. Take review finding #6 (the readiness probe waits on a + 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 + 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. 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..26085424 --- /dev/null +++ b/docs/plans/2026-10-15-named-connections-step6-inventory.md @@ -0,0 +1,77 @@ +# 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 `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; + 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. + +## Done after the first pass (2026-10-15) + +- `webhook_relay` and `order_event_pipeline`: one handler per event type, one service call + (`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 (`ad771f0`, own commit). +- `nats_delivery_attempt` / `nats_max_deliver` in the handler context (`b7586e3`). + +## Open + +- **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 brokers in WSL Docker, not inside WSL. 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..bb77fd6a --- /dev/null +++ b/docs/plans/2026-10-16-pr96-review-fixes.md @@ -0,0 +1,370 @@ +# PR #96 review fixes -- verification and plan + +**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:** `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. + +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 `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. + +### 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) | **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`) | 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) | **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 + +| # | 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. +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 + (`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`. + 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. + +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/`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 + 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 + +### 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.** **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 | +| 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 `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 | diff --git a/docs/reference/configuration-keys.md b/docs/reference/configuration-keys.md deleted file mode 100644 index 42737664..00000000 --- a/docs/reference/configuration-keys.md +++ /dev/null @@ -1,173 +0,0 @@ -# Configuration Keys Reference - -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`). - ---- - -## Application - -Top-level application settings. - -| Key | Type | Default | Description | -|-----|------|---------|-------------| -| `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"`). | -| `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. | - ---- - -## Event Bus - -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"`. | - ---- - -## Event Publishing - -Section: `[default.event_publishing]` - -Controls how outbound events are published to topics. - -| Key | Type | Default | Description | -|-----|------|---------|-------------| -| `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. | - ---- - -## AI / Model Runtime - -Section: `[default.runtimes.]` - -Each named runtime defines model provider settings. The `default` runtime is used when no name is specified. - -| Key | Type | Default | Description | -|-----|------|---------|-------------| -| `model_provider` | `str` | -- | Model provider. `"openai"` for OpenAI-compatible APIs, `"vllm"` for vLLM endpoints. | -| `model_name` | `str` | -- | Model identifier (e.g., `"gpt-4o"`, `"meta-llama/Llama-3-70b"`). | -| `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_temperature` | `float` | -- | Sampling temperature. Lower values produce more deterministic output. | -| `concurrent_requests` | `int` | -- | Maximum number of concurrent requests to the model provider. | - ---- - -## Prompts - -Top-level settings for prompt file resolution. - -| Key | Type | Default | Description | -|-----|------|---------|-------------| -| `prompt_directory` | `str` | -- | Primary directory containing prompt template files. | -| `prompt_search_paths` | `list[str]` | `[]` | Additional directories to search for prompt files, in order. | -| `system_prompt_name` | `str` | `"system"` | Filename (without extension) of the system prompt template. | -| `instruction_prompt_name` | `str` | `"instruction"` | Filename (without extension) of the instruction prompt template. | - ---- - -## Cache - -Section: `[default.cache]` - -Disk cache settings used when `with_cache()` is enabled on the `AppBuilder`. - -| 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. | - ---- - -## Observability - -OpenTelemetry and tracing settings. - -| Key | Type | Default | Description | -|-----|------|---------|-------------| -| `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. | -| `token_metrics_enabled` | `bool` | `true` | Record LLM token usage and response latency to OpenTelemetry. Only takes effect when `otel_enabled` is also `true`. | - ---- - -## Logging - -Additional logging behavior settings. - -| Key | Type | Default | Description | -|-----|------|---------|-------------| -| `suppress_noisy_loggers` | `bool` | `true` | Suppress verbose log output from third-party libraries (e.g., `httpx`, `httpcore`). | - ---- - -## Example settings.toml - -```toml -# Application -app_name = "my_agent_service" -app_port = 8000 -app_environment = "development" -log_level = "INFO" -log_format = "text" - -# Event Bus -event_bus = "nats" -nats_url = "nats://localhost:4222" - -# Prompts -prompt_directory = "prompts" -prompt_search_paths = ["shared/prompts"] -system_prompt_name = "system" -instruction_prompt_name = "instruction" - -# Logging -suppress_noisy_loggers = true - -# Observability -otel_enabled = false -otel_endpoint = "http://localhost:4317" -otel_service_name = "my_agent_service" -token_metrics_enabled = true - -[default.event_publishing] -default_pubsub_name = "pubsub" - -[default.event_publishing.topic_mapping] -"order.created.v1" = "orders" -"order.completed.v1" = "orders" - -[default.runtimes.default] -model_provider = "openai" -model_name = "gpt-4o" -model_api_key = "@format {this.OPENAI_API_KEY}" -model_max_tokens = 4096 -model_temperature = 0.7 -concurrent_requests = 5 - -[default.runtimes.fast] -model_provider = "openai" -model_name = "gpt-4o-mini" -model_api_key = "@format {this.OPENAI_API_KEY}" -model_max_tokens = 2048 -model_temperature = 0.3 -concurrent_requests = 10 - -[default.cache] -cache_dir = ".cache/blueprint" -size_limit = 1000000000 -eviction_policy = "least-recently-used" -default_ttl = 3600 -``` 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/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..fe6e57a9 --- /dev/null +++ b/docs/specs/2026-08-28-multi-agent-grouping.md @@ -0,0 +1,1310 @@ +# 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) | +| **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. + +--- + +## 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: 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. | + +--- + +## 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"`; 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 + 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. + 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 (`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.)* 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. + +**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. 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. + +**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. + +### 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": })`, +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; 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. + +**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`: + +| 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. | + +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. + +### 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 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 + +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. *(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. + +--- + +## 4. Public API + +### 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: + """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_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, module path, root, critical flag + image_root: Path + # No cache list: an agent may use only the caches it declared itself (sec. 8). + + @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 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` -- except the instance refusal, which +`AppBuilder.build(config)` applies too (sec. 10). *(Amended 2026-10-19, PR #96 review.)* + +### 4.2 Changed + +```python +class AppBuilder: + """One declaration surface. Records what it is told; wires nothing until build().""" + def __init__(self, config: Config | None = None) -> None: ... + + # 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:** `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). + +**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** +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)` +(`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 `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 +**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. + +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. + +### 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` | 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. | +| `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 + +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. 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 +two cannot fail together. + +--- + +## 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.** 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 +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. 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 +(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. +**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 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, `` 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. + +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. + +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.)* + +--- + +## 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. + +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 + +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`, `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. + +| 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. 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 +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 +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 +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`. 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 +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 +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 -- 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`). + +**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 +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 `(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. + +### 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"` | 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 +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 +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. + +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 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 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. + +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. + +`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. +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** +warn that ticks are uncoordinated, naming both remedies. + +Neither mode is exactly-once: `CronJob` is at-least-once (controller restart, missed +`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. 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 +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 + +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 +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. + +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. 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 +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. + +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. + +--- + +## 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 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. + +### 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; 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. + +**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, 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 +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. + +### 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. `AppBuilder(config)...build()` behaves as today, and no `namespace` parameter is added to anything. | +| 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). | +| `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 +agent = ( + AppBuilder() + .with_service(OrderService) + .with_handler(OrderValidationHandler) + .with_rest_api(OrderApi) +) +``` + +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(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` 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. + +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 + +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 | `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) | + +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 + +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). +- [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: 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`. +- [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) -- 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 + +- [ ] 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). + 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). `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. 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). + `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 + 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. + + +--- + +## 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. +- 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 + 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? +- **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. + `..` 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. 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/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/document_summarizer/src/api/routes.py b/examples/document_summarizer/src/api/routes.py index 40e3f781..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__) @@ -15,13 +16,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,8 +36,8 @@ 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) + 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}", @@ -50,8 +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.""" - assert self._service is not None, "Service not initialised" - 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 b42c4dad..de7c89e8 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 src.models.schemas import DocumentSummary -from src.services.summarizer_service import SummarizerService +from blueprint.agents import AgentBuilder, AppBuilder, Config 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.models.domain_models import DocumentSummary +from src.services.summarizer_service import SummarizerService +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/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 f3ae459b..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,34 +37,35 @@ 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 - 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] @@ -77,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 @@ -95,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/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/settings.toml b/examples/health_monitor/settings.toml index 00036931..5de9cf5f 100644 --- a/examples/health_monitor/settings.toml +++ b/examples/health_monitor/settings.toml @@ -1,8 +1,11 @@ [default] -app_name = "Health Monitor" +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/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/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/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/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/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/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/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/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/README.md b/examples/order_event_pipeline/README.md index 0cde1d59..eda4106e 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 + dto.py # DTO: OrderPayload (event data) + domain_models.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/ @@ -52,7 +48,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,10 +56,10 @@ 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 +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/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/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..aa2abf0a --- /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_models import Order +from ..models.dto 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 c392f2fc..bcf76ab4 100644 --- a/examples/order_event_pipeline/src/main.py +++ b/examples/order_event_pipeline/src/main.py @@ -1,20 +1,22 @@ -"""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 .handlers.order_enrichment_handler import OrderEnrichmentHandler -from .services.order_service import OrderService from .api.routes import OrderApi +from .handlers.order_handler import OrderHandler +from .services.order_service import OrderService + +agent = AppBuilder().with_service(OrderService).with_handler(OrderHandler).with_rest_api(OrderApi).with_cache() + -config = Config(settings_files=["settings.toml"]) - -app = ( - AppBuilder(config) - .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/order_event_pipeline/src/models/domain_models.py b/examples/order_event_pipeline/src/models/domain_models.py new file mode 100644 index 00000000..67a763eb --- /dev/null +++ b/examples/order_event_pipeline/src/models/domain_models.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/dto.py similarity index 50% rename from examples/order_event_pipeline/src/models/schemas.py rename to examples/order_event_pipeline/src/models/dto.py index 48e8bb84..b3f0ae72 100644 --- a/examples/order_event_pipeline/src/models/schemas.py +++ b/examples/order_event_pipeline/src/models/dto.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..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.schemas import OrderPayload, ValidationError +from ..models.domain_models 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..3f013e4a 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_models 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..1381ee06 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_models 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" diff --git a/examples/site_readings/README.md b/examples/site_readings/README.md new file mode 100644 index 00000000..f7d1e2d9 --- /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/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 + 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/src/blueprint/agents/models/event_routing.py b/examples/site_readings/src/__init__.py similarity index 100% rename from src/blueprint/agents/models/event_routing.py rename to examples/site_readings/src/__init__.py 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..e892cb60 --- /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_models import Reading +from ..models.dto 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_models.py b/examples/site_readings/src/models/domain_models.py new file mode 100644 index 00000000..08e74f80 --- /dev/null +++ b/examples/site_readings/src/models/domain_models.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/dto.py b/examples/site_readings/src/models/dto.py new file mode 100644 index 00000000..b60069c6 --- /dev/null +++ b/examples/site_readings/src/models/dto.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..3432fae4 --- /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_models 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..5af1591d --- /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_models 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" diff --git a/examples/webhook_relay/README.md b/examples/webhook_relay/README.md index 6d0f44e2..a6684abb 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 @@ -69,17 +63,17 @@ 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 +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 + dto.py # DTO: WebhookPayload (REST body and event data) + domain_models.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/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/examples/webhook_relay/src/api/routes.py b/examples/webhook_relay/src/api/routes.py index d0b9514d..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__) @@ -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..ef664b01 --- /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_models import IncomingWebhook +from ..models.dto 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 74981b54..a87958ba 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 @@ -7,31 +13,22 @@ 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 -# 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) - # 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 +agent = ( + AppBuilder() + # Business service: deduplication, normalisation, filtering, enrichment .with_service(WebhookService) + # 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 .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))) diff --git a/examples/webhook_relay/src/models/domain_models.py b/examples/webhook_relay/src/models/domain_models.py new file mode 100644 index 00000000..683a792f --- /dev/null +++ b/examples/webhook_relay/src/models/domain_models.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/dto.py b/examples/webhook_relay/src/models/dto.py new file mode 100644 index 00000000..3a4e97a2 --- /dev/null +++ b/examples/webhook_relay/src/models/dto.py @@ -0,0 +1,17 @@ +"""DTOs: what arrives over HTTP and in the ``webhook.received`` event.""" + +from __future__ import annotations + +from typing import Any, Literal + +from pydantic import BaseModel + + +class WebhookPayload(BaseModel): + """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 diff --git a/examples/webhook_relay/src/models/schemas.py b/examples/webhook_relay/src/models/schemas.py deleted file mode 100644 index b48f9163..00000000 --- a/examples/webhook_relay/src/models/schemas.py +++ /dev/null @@ -1,40 +0,0 @@ -"""Pydantic models for the webhook relay pipeline.""" - -from __future__ import annotations - -from datetime import UTC, datetime -from typing import Any, Literal - -from pydantic import BaseModel, Field - - -class WebhookPayload(BaseModel): - """Incoming webhook payload from an external source.""" - - 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..96fc7354 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_models 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..12e77ea0 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_models 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..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.schemas import NormalizedEvent, WebhookPayload +from src.models.domain_models 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") diff --git a/pyproject.toml b/pyproject.toml index b8a92b38..31c22207 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,7 +17,6 @@ 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", @@ -34,15 +33,15 @@ 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", "apscheduler>=3.11.2", - "diskcache-rs>=0.4.4", - "nats-py>=2.13.1", + "diskcache-rs>=0.4.10", + "nats-py[nkeys]>=2.13.1", "croniter>=6.0.0", - "pytest", - "pytest-asyncio" + "pyyaml>=6.0" ] [project.optional-dependencies] @@ -55,10 +54,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", @@ -108,7 +107,7 @@ packages = [ [tool.setuptools.package-data] "blueprint.agents" = ["py.typed"] -"blueprint.agent_generator" = ["base_files/**/*", "assistant_integrations/**/*", "claude_docs/**/*"] +"blueprint.agent_generator" = ["base_files/**/*", "claude_docs/**/*", "docs/**/*"] [tool.black] line-length = 140 @@ -131,6 +130,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 @@ -171,6 +179,7 @@ module = [ "croniter", "dapr.*", "nats.*", + "yaml", ] ignore_missing_imports = true 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 deleted file mode 100644 index 1da40eb3..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 df5fe8c1..a09c3979 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 && \ @@ -29,9 +31,18 @@ FROM builder AS dev 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"] +# 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 +# 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 @@ -60,25 +71,52 @@ COPY --from=builder /usr/local/bin /usr/local/bin COPY --chown=appuser:appuser src ./src COPY --chown=appuser:appuser settings.toml ./ -# 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 - +# 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 same directory is hosted by a group image without changing a line: that image's +# agents.toml names this module and builds the same declaration under the agent's namespace, +# which is where the routes gain their /api/ 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, +# 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, 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=... + +# 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 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 -ENTRYPOINT ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"] +# 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 -p 8000:8000 +# +# 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/group_Dockerfile b/src/blueprint/agent_generator/base_files/group_Dockerfile new file mode 100644 index 00000000..02062942 --- /dev/null +++ b/src/blueprint/agent_generator/base_files/group_Dockerfile @@ -0,0 +1,84 @@ +# syntax=docker/dockerfile:1.7 + +# ============================================================================ +# Group image - hosts several agents in one process +# ============================================================================ +# +# 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 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 + +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 + +# 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 ["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: +# +# 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..5af8a82a --- /dev/null +++ b/src/blueprint/agent_generator/base_files/group_agents_toml.txt @@ -0,0 +1,43 @@ +# 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 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. +# 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 b2c1b3ee..8cd76a5a 100644 --- a/src/blueprint/agent_generator/base_files/settings.txt +++ b/src/blueprint/agent_generator/base_files/settings.txt @@ -2,16 +2,57 @@ app_name 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" -[default.logging] -level = "DEBUG" -format = "json" +# 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); +# 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 -[default.observability] +# 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. +# (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 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" + +# 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 + +# 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*, 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 +# 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/src/handlers/handler.txt b/src/blueprint/agent_generator/base_files/src/handlers/handler.txt index ae1095c6..75fb1570 100644 --- a/src/blueprint/agent_generator/base_files/src/handlers/handler.txt +++ b/src/blueprint/agent_generator/base_files/src/handlers/handler.txt @@ -19,34 +19,67 @@ 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 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-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. + # + # 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 + # 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. logger.info("MyHandler processing event '%s'", event.type) raise NotImplementedError() diff --git a/src/blueprint/agent_generator/base_files/src/main.txt b/src/blueprint/agent_generator/base_files/src/main.txt index a3b2bed8..50d5d316 100644 --- a/src/blueprint/agent_generator/base_files/src/main.txt +++ b/src/blueprint/agent_generator/base_files/src/main.txt @@ -1,19 +1,41 @@ """ 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. + +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 -# Initialize config -config = Config( - settings_files=[ - "settings.toml", - "secrets.toml", - ], - root_path=Path(__file__).parent.parent -) +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. -agents_and_app_initialization + 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/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/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..d38691b9 --- /dev/null +++ b/src/blueprint/agent_generator/base_files/template_for_docker_ignore.txt @@ -0,0 +1,62 @@ +# 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 + +# 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/ +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/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 b7f30aef..57039147 100644 --- a/src/blueprint/agent_generator/claude_docs/CLAUDE.md +++ b/src/blueprint/agent_generator/claude_docs/CLAUDE.md @@ -31,39 +31,60 @@ 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 + 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. + ## Component Patterns ### EventHandler @@ -80,20 +101,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. +- 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 (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 + 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): @@ -103,6 +136,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.""" ... @@ -155,27 +200,45 @@ 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()`.** `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 + 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 + 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) ```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/`: @@ -213,12 +276,36 @@ 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 + +# 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 ``` -**secrets.toml** (never commit): `model_api_key = "sk-..."` +**.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-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. ## CLI (`asbs`) @@ -229,8 +316,9 @@ 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 ``` **IMPORTANT:** Always use `asbs create` when adding components for consistent naming and imports. @@ -241,7 +329,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 @@ -261,6 +349,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 3acbfd53..045d3f18 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 -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** +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 +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/add-component/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/add-component/SKILL.md index e37a5590..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 @@ -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: @@ -47,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 @@ -61,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 @@ -81,7 +87,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 @@ -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..e229abc4 --- /dev/null +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-cli/SKILL.md @@ -0,0 +1,56 @@ +--- +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 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 [--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 +``` + +## 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. 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 new file mode 100644 index 00000000..2f68652e --- /dev/null +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-config/SKILL.md @@ -0,0 +1,78 @@ +--- +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 -- 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. 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. + +## 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. + +**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 + +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..96f6bc1a --- /dev/null +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-deployment/SKILL.md @@ -0,0 +1,86 @@ +--- +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 | 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 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 + 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. +- **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..e49a3540 --- /dev/null +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-events/SKILL.md @@ -0,0 +1,97 @@ +--- +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 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 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 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. + +**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 +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 +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" # 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, 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`. +- **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 + +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-migration/SKILL.md b/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md new file mode 100644 index 00000000..e63b7ccd --- /dev/null +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-migration/SKILL.md @@ -0,0 +1,100 @@ +--- +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** - 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 + +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, 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 + `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. + +## 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`. +- **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 + +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 new file mode 100644 index 00000000..6ce3ac9e --- /dev/null +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-multi-agent/SKILL.md @@ -0,0 +1,188 @@ +--- +name: blueprint-multi-agent +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 +--- + +# 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 | 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 + +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, 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: + +``` +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 **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. + +**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. + +## 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**, 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. + +## Three ways to run one declaration + +| 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. + +## 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, 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 + +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 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 new file mode 100644 index 00000000..1f1a6002 --- /dev/null +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-testing/SKILL.md @@ -0,0 +1,50 @@ +--- +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`; it +starts the in-process timer and the tick-age gauge (`build()` registers the trigger route and the +tick handler). + +## 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..0562630d --- /dev/null +++ b/src/blueprint/agent_generator/claude_docs/skills/blueprint-troubleshooting/SKILL.md @@ -0,0 +1,46 @@ +--- +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 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. + +## 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()`, 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 | + +## 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 9ec98a79..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. @@ -32,7 +35,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,9 +55,24 @@ 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 +## 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/create.py b/src/blueprint/agent_generator/cli/commands/create.py index c90fbd99..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,14 +8,18 @@ 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, add_component_registration_to_main, + insert_before_declaration, read_main_py, write_main_py, ) @@ -98,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: { @@ -132,13 +137,17 @@ 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: 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 @@ -149,8 +158,8 @@ 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 import: from .handlers.{module_name} import {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 +176,28 @@ 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 _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: @@ -186,17 +216,21 @@ 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", "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", }, } }, @@ -231,7 +265,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 @@ -242,8 +276,8 @@ 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 import: from .services.{module_name} import {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 +294,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: @@ -388,7 +422,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__) @@ -470,11 +504,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 @@ -485,9 +519,9 @@ 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 registration: .with_rest_api({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: logger.debug("Could not auto-register API: %s", e) @@ -507,9 +541,9 @@ 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" .with_rest_api({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") @@ -526,9 +560,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() @@ -589,10 +624,16 @@ 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" - settings_content += 'openai_reasoning_effort = "gpt-5-mini"\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' settings_content += 'openai_reasoning_summary = "detailed"\n' settings_file.write_text(settings_content, encoding="utf-8") @@ -604,35 +645,39 @@ 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" - - # 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 +685,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 +700,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: @@ -670,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) @@ -699,34 +755,47 @@ 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 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 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}") 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) @@ -740,7 +809,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 @@ -751,8 +820,8 @@ 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 import: from .schedulers.{module_name} import {class_name}") + print(f" - Added registration: .with_scheduler({class_name})") except (FileNotFoundError, ValueError) as e: logger.debug("Could not auto-register scheduler: %s", e) @@ -769,5 +838,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..618beb76 100644 --- a/src/blueprint/agent_generator/cli/commands/dev.py +++ b/src/blueprint/agent_generator/cli/commands/dev.py @@ -1,24 +1,72 @@ """Dev command - start development server.""" +import ast +import atexit import logging -import sys +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" +STANDALONE_FACTORY = "src.main:create_app" + +AGENTS_ENV = "BLUEPRINT_AGENTS" +GROUP_ENV = "BLUEPRINT_GROUP" + def run(args: Namespace) -> None: """Execute the dev command. + 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 """ - # 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) - print("Make sure you're in a Blueprint Agents project directory", file=sys.stderr) + agent_map = Path(AGENT_MAP_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 _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: 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}") @@ -26,24 +74,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 +85,136 @@ 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] + + +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 + question about its shape. + """ + try: + module = ast.parse(entry_point.read_text(encoding="utf-8")) + except (OSError, SyntaxError): + return False + 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(requested: str) -> str: + """Return the name this agent runs under while developing: ``--name``, as a namespace. + + 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 the name is not a legal namespace once dashes and spaces become + underscores, because a further-repaired name would be a different agent. + """ + candidate = re.sub(r"[-\s]+", "_", requested.strip()).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(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') + 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).") + print(f"Its routes are under /api/{name}.") + return path 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/commands/group_setup.py b/src/blueprint/agent_generator/cli/commands/group_setup.py new file mode 100644 index 00000000..34c45c75 --- /dev/null +++ b/src/blueprint/agent_generator/cli/commands/group_setup.py @@ -0,0 +1,162 @@ +"""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. 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 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] +app_environment = "development" +log_level = "DEBUG" +""" + + +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``. + + 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", + # 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] = [] + 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) + + 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") + 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 -- it reports the") + print("empty map as an issue until the first agent is added.") + + +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 06ec7fc9..cc49cefa 100644 --- a/src/blueprint/agent_generator/cli/commands/setup.py +++ b/src/blueprint/agent_generator/cli/commands/setup.py @@ -10,6 +10,7 @@ from ...generator.generator import AgentGenerator from ...generator.part_generators.part_generator_base import PartGeneratorBase +from . import group_setup logger = logging.getLogger(__name__) @@ -113,32 +114,57 @@ 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.") - # 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. + 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() - 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 / "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}") - + # 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: - # Create basic configuration - config = create_basic_config(project_name) + 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 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) @@ -152,7 +178,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/") @@ -160,19 +186,40 @@ def run(args: Namespace) -> None: print(" │ ├── api/") 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:") - 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(" 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 (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") + 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(" - 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 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.") + 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 46f57f7f..e232dd5e 100644 --- a/src/blueprint/agent_generator/cli/commands/validate.py +++ b/src/blueprint/agent_generator/cli/commands/validate.py @@ -1,12 +1,291 @@ -"""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 sys +import tomllib from argparse import Namespace +from dataclasses import dataclass from pathlib import Path +from typing import Any + +from dynaconf import Dynaconf + +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_nak_delays, + 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, + DEFAULT_ENVVAR_PREFIX, + DEFAULT_SETTINGS_FILES, + Config, + ConfigError, + 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 + +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( + [ + "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, 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. @@ -14,109 +293,621 @@ 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): + validate_group.run(args) + return + project_dir = Path(args.project_dir).resolve() if not project_dir.is_dir(): 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 = [] + 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}") + print(f"[ok] Found {file_name}") - # Check for secrets template - secrets_example = project_dir / "secrets.toml.example" - secrets_file = project_dir / "secrets.toml" - if not secrets_example.is_file(): - warnings.append("Missing secrets.toml.example 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. + 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(): - warnings.append("Missing secrets.toml (copy from secrets.toml.example)") + 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." + ) + 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 - 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") - 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"] 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 (project_dir / "docker-compose.yml").is_file(): + print("[ok] Found docker-compose.yml") - if docker_compose.is_file(): - print("✓ 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(): + swallowed = swallowed_cancellations(src_dir) + if swallowed: + warnings.append(swallowed_cancellation_warning(project_dir.name, swallowed)) + + issues.extend(settings.problems) + warnings.extend(settings.unread_key_warnings()) + + # 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) + 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.") + 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 root_findings(project_dir: Path, settings: ProcessSettings) -> Findings: + """Everything the process checks at startup for a standalone agent, which runs at the root namespace. + + Args: + project_dir: The project root, which is also the process's directory. + settings: The project's settings, loaded for the target environment. + """ + if not settings.readable: + return [], [], [] + view = settings.root_view() + issues: list[str] = [] + warnings: list[str] = [] + notices: list[str] = [] + + # 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 + + +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 if settings.root_view().get("idempotency_enabled") is None else None + + +# ---------------------------------------------------------------------------------------------- +# Group readiness +# +# 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( + [ + "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.", + ] +) + + +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) + + +def _group_findings(project_dir: Path, environment: str | None = None) -> Findings: + """Report what the project's agent map says, if it has one. + + 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. + + 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: + 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}"], [], [] + 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) + + +# ---------------------------------------------------------------------------------------------- +# The runtime's startup checks, for one namespace +# ---------------------------------------------------------------------------------------------- + + +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 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"] + + +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 declared_crontabs(path: Path) -> list[str]: + """The literal crontabs a scheduler module hands ``SchedulerBase.__init__``. + + 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. + """ + try: + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + except (OSError, SyntaxError, UnicodeDecodeError): + return [] + 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) + + +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() + + +def _mode(view: SettingsView) -> str: + return normalise_scheduler_mode(view.get("scheduler_mode")) + + +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, *, 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`` 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. + 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 the messages. + """ + schedulers = scheduler_modules(agent_dir) + if not schedulers: + return [], [], [] + named = f"Agent '{agent}': " if agent else "" + + 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 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)}"], [], [] + + 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. + notices.append( + "\n".join( + [ + 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", + " schedule the scheduler declares, for every scheduler under src/schedulers/.", + ] + ) + ) + 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 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): + 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" + ) + return issues, [], notices + + # 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( + [ + 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.", + ] + ) + ) + else: + notice = _disk_claim_notice(view, named, "each in-process scheduler tick") + if notice: + notices.append(notice) + return issues, [], notices + + +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 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 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: + policy = resolve_idempotency_policy(view.get, has_cache=main_declares_a_cache(agent_dir)) + except ValueError as exc: + return [f"{named}{exc} Startup fails"], [], [] + if not policy.enabled: + return [], [], [] + + issues: list[str] = [] + warning = dedup_redelivery_warning(view.get, agent or "") + warnings = [warning] if warning else [] + + 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 transport_findings(agent_dir: Path, *, view: SettingsView, settings: ProcessSettings, agent: str = "") -> Findings: + """What wiring this agent's transport refuses or warns about at startup. + + 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] = [] + notices: list[str] = [] + try: + resolve_nats_url( + view.get("nats_url", ""), + view.get("app_environment", "development"), + override_variable=f"{settings.override_variable_prefix}NATS_URL", + ) + except ValueError as 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, notices + + if not agent: + # A namespaced client's queue group is its namespace; only the root reads these keys. + 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"): + 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) + try: + validate_durable_name(durable, count) + except ValueError as exc: + issues.append(f"{named}{exc}") + return issues, warnings, notices + + +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 depends on the + deployment's own data and is only known at startup. + """ + issues: list[str] = [] + for key, minimum in (("nats_max_concurrent_runs", 1), ("nats_extra_runs_per_process", 0)): + try: + RunLimit.parse(key, view.get(key), minimum=minimum) + except ValueError as exc: + issues.append(str(exc)) + 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.") + 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}.") + 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 = view.get("nats_connection_source") + if source: + issue = _connection_source_issue(project_dir, str(source)) + if issue: + issues.append(issue) + 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``. + + 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 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..8db12502 --- /dev/null +++ b/src/blueprint/agent_generator/cli/commands/validate_group.py @@ -0,0 +1,606 @@ +"""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 +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. + +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.config import AGENT_REFUSED_KEYS +from blueprint.agents.group_config import ( + AGENTS_ENV, + CRITICAL_AGENTS_ENV, + 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 +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" + +# How many absolute `src` imports one warning lists before it summarises the rest. +_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``. + + 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) + + 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}") + environment = getattr(args, "environment", None) + print(f"Environment: {ProcessSettings.load(image_root, environment).environment} (choose another with --environment)") + print() + + 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) + + +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 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. + 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 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 " + 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 + + 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: + 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 = _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], 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] = [] + + 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, 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, None + + module = entry.get("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") + 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", relative to the image root.' + ) + 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, 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, 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, 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)) + + 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)) + if (root / "src").is_dir(): + swallowed = swallowed_cancellations(root / "src") + if swallowed: + warnings.append(swallowed_cancellation_warning(name, swallowed)) + + # 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( + 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, _CheckedAgent(name, root, view) + + +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: + 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, 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 for the + environment in force; this reports it in any section, because a section that is inactive here + is active in another deployment. + """ + 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)))}) 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, 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. + + 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. + """ + 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 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 {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 [] + 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): + """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 = 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): + 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``. + + 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. Parsed rather than grepped or imported. + """ + 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)): + 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 f129261b..203d9aa6 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 +from .commands import claude, create, dev, docs, 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,20 @@ def main() -> None: ) setup_parser.add_argument( "project_name", - help="Name of the project to create (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", 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", @@ -103,28 +145,26 @@ 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", + # 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", ) - windsurf_parser.add_argument( - "output_dir", + docs_parser.add_argument( + "topic", nargs="?", - default=".", - help="Project root directory (default: current directory)", + help="Page to locate, e.g. 'guides/multi-agent-setup' or 'caching' (default: list all)", ) - windsurf_parser.add_argument( - "--overwrite", + docs_parser.add_argument( + "--cat", action="store_true", - help="Overwrite existing files", + help="Print the page contents instead of its path", ) - windsurf_parser.add_argument( - "--verbose", - "-v", + docs_parser.add_argument( + "--root", action="store_true", - help="Enable verbose logging", + help="Print the documentation root directory and exit", ) # Validate command @@ -137,14 +177,58 @@ 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, the group file (when there is one), and " + "every agent the map 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.", + ) + 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 the application with hot reload", + 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", + 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", + help="Comma-separated agents to host (default: every agent in agents.toml)", ) dev_parser.add_argument( "--port", @@ -173,6 +257,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/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/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/docs/README.md b/src/blueprint/agent_generator/docs/README.md similarity index 67% rename from docs/README.md rename to src/blueprint/agent_generator/docs/README.md index 893ec163..93091e51 100644 --- a/docs/README.md +++ b/src/blueprint/agent_generator/docs/README.md @@ -18,8 +18,8 @@ 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 | +| [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 | --- @@ -40,7 +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 | +| [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 | @@ -52,5 +54,20 @@ 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 | + +--- + +## 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 78% rename from docs/components/agents.md rename to src/blueprint/agent_generator/docs/components/agents.md index ed7a5454..9f1f1b77 100644 --- a/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 ``` @@ -250,9 +252,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] @@ -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() ) ``` @@ -362,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: @@ -379,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, } ``` @@ -389,19 +388,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 +419,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 - -config = Config() +from blueprint.agents import AppBuilder -app = ( - AppBuilder(config) - .with_agent(classifier_agent) +agent = ( + AppBuilder() .with_service(TicketService) + .with_agent(classifier_agent, name="ticket_classifier") .with_handler(TicketClassificationHandler) - .build() ) ``` @@ -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 new file mode 100644 index 00000000..769a6eb2 --- /dev/null +++ b/src/blueprint/agent_generator/docs/components/event-handlers.md @@ -0,0 +1,379 @@ +# Event Handlers + +Event handlers process incoming CloudEvents using a chain-of-responsibility pattern. Each handler declares which events it can process, and the framework routes events through all registered handlers in priority order. + +## Import + +```python +from blueprint.agents.handler.event_handler_base import EventHandlerBase +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 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 + +```python +from typing import Any +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.events import GenericCloudEvent, HandlerResult + + +class MyHandler(EventHandlerBase): + + def __init__(self) -> None: + super().__init__(priority=100) # Lower priority runs first + + async def on_startup(self) -> None: + self._service = self.registry.get_service(MyService) + + async def on_shutdown(self) -> None: + pass + + async def can_handle_event( + self, event: GenericCloudEvent, context: dict[str, Any] + ) -> bool: + ... + + async def handle_event( + self, event: GenericCloudEvent, context: dict[str, Any] + ) -> Any | HandlerResult | list[HandlerResult] | None: + ... +``` + +## Priority + +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 +super().__init__(priority=100) # Default +super().__init__(priority=500) # Runs late +``` + +## Abstract Methods + +### can_handle_event + +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( + self, event: GenericCloudEvent, context: dict[str, Any] +) -> bool: + return event.type == "order.created" +``` + +### handle_event + +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] +) -> 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. 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**. | + +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 +# Handler at priority 5 -- runs first +class NormalizerHandler(EventHandlerBase): + def __init__(self) -> None: + super().__init__(priority=5) + + 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]) -> None: + # Parse once and store for downstream handlers + normalized = self._service.normalize(event.data) + context["normalized"] = normalized + context["source"] = normalized.source + return None # Pass to next handler + + +# Handler at priority 20 -- runs after NormalizerHandler but double checked with filled context +class EnricherHandler(EventHandlerBase): + def __init__(self) -> None: + super().__init__(priority=20) + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return context.get("normalized") and event.type == "webhook.received" + + async def handle_event( + self, event: GenericCloudEvent, context: dict[str, Any] + ) -> HandlerResult | None: + # Read data written by the earlier handler + normalized = context.get("normalized") + + enriched = self._service.enrich(normalized) + 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 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 +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. + +**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. +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. + +## Published Event Types + +Optionally declare the event types this handler can produce. Used for documentation and subscription introspection. + +```python +def get_published_event_types(self) -> tuple[str, str] | None: + return ("order.processed", "order.error") +``` + +The tuple is `(success_type, error_type)`. Return `None` if the handler does not publish events. + +## Accessing Services + +Resolve service dependencies in `on_startup()`. Never in `__init__()`. + +```python +from blueprint.agents.services.service_base import ServiceBase + + +class OrderService(ServiceBase): + async def process(self, order: dict) -> dict: + ... + + +class OrderHandler(EventHandlerBase): + + def __init__(self) -> None: + super().__init__(priority=100) + self._order_service: OrderService | None = None + + async def on_startup(self) -> None: + self._order_service = self.registry.get_service(OrderService) + + 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: + if self._order_service is None: + return None + result = await self._order_service.process(event.data) + return HandlerResult(data=result, event_type="order.processed") +``` + +## Registration + +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 +from blueprint.agents import AppBuilder + +agent = ( + AppBuilder() + .with_service(OrderService) + .with_handler(OrderHandler) +) +``` + +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 + +```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.""" + + async def on_startup(self) -> None: + pass + + async def on_shutdown(self) -> None: + pass + + 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} + + +class InvoiceHandler(EventHandlerBase): + """Generates invoices when an order is confirmed.""" + + def __init__(self) -> None: + super().__init__(priority=50) + self._invoice_service: InvoiceService | None = None + + async def on_startup(self) -> None: + self._invoice_service = self.registry.get_service(InvoiceService) + + async def on_shutdown(self) -> None: + pass + + def get_published_event_types(self) -> tuple[str, str] | None: + return ("invoice.created", "invoice.error") + + async def can_handle_event( + self, event: GenericCloudEvent, context: dict[str, Any] + ) -> bool: + return event.type == "order.confirmed" + + async def handle_event( + self, event: GenericCloudEvent, context: dict[str, Any] + ) -> HandlerResult | None: + 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. 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(): + """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", + "order_id": "ORD-1", + "total": 50.00, + } + registry.get_service.return_value = invoice_service + Component.shared_registry = registry + yield registry + Component.reset_shared_state() + + +@pytest.fixture +async def handler(mock_registry): + h = InvoiceHandler() + await h.on_startup() + return h + + +async def test_can_handle_matching_event(handler): + event = GenericCloudEvent(id="1", type="order.confirmed", data={}) + assert await handler.can_handle_event(event, {}) is True + + +async def test_ignores_unrelated_event(handler): + event = GenericCloudEvent(id="2", type="user.created", data={}) + assert await handler.can_handle_event(event, {}) is False + + +async def test_handle_event_returns_result(handler): + event = GenericCloudEvent( + id="3", + type="order.confirmed", + data={"order_id": "ORD-1", "items": [{"sku": "A", "qty": 2}]}, + ) + result = await handler.handle_event(event, {}) + assert result is not None + assert result.event_type == "invoice.created" + assert result.data["invoice_id"] == "INV-TEST" +``` diff --git a/docs/components/rest-apis.md b/src/blueprint/agent_generator/docs/components/rest-apis.md similarity index 80% rename from docs/components/rest-apis.md rename to src/blueprint/agent_generator/docs/components/rest-apis.md index 85af6655..9f9296af 100644 --- a/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. @@ -141,17 +166,15 @@ 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, 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) ) ``` @@ -202,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 --- @@ -215,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, @@ -276,14 +308,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) ) ``` @@ -301,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 = { @@ -325,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}], @@ -343,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/docs/components/schedulers.md b/src/blueprint/agent_generator/docs/components/schedulers.md similarity index 50% rename from docs/components/schedulers.md rename to src/blueprint/agent_generator/docs/components/schedulers.md index 8392232b..0cebf40b 100644 --- a/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: @@ -52,7 +55,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 +67,63 @@ 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"`); 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 @@ -83,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 @@ -111,7 +167,12 @@ The `scheduler_name` is derived from the class name. For a class named `DataSync POST /api/data_sync_scheduler/trigger ``` -This is useful for testing, debugging, and on-demand execution without waiting for the next cron interval. +In a group, the trigger moves under the agent's reserved `scheduler` segment: +`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. 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 @@ -119,23 +180,21 @@ 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, Config +from blueprint.agents import AppBuilder -config = Config() -app = ( - AppBuilder(config) - .with_scheduler(DataSyncScheduler()) - .build() +agent = ( + AppBuilder() + .with_scheduler(DataSyncScheduler) ) ``` @@ -163,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 @@ -184,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. @@ -195,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 @@ -207,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 --- @@ -237,33 +302,42 @@ class CatalogSyncScheduler(SchedulerBase): ### Application Assembly ```python -from blueprint.agents import AppBuilder, Config - -config = Config() +from blueprint.agents import AppBuilder -app = ( - AppBuilder(config) +agent = ( + AppBuilder() .with_service(ExternalApiClient) .with_service(CatalogService) - .with_scheduler(CatalogSyncScheduler()) - .build() + .with_scheduler(CatalogSyncScheduler) ) ``` 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(): @@ -273,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 @@ -295,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/docs/components/services.md b/src/blueprint/agent_generator/docs/components/services.md similarity index 78% rename from docs/components/services.md rename to src/blueprint/agent_generator/docs/components/services.md index 2afdf172..67791000 100644 --- a/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 @@ -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 @@ -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 and `create_app()` refuse an instance, because it would be constructed before any namespace exists. ## Best Practices @@ -158,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: @@ -177,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.""" @@ -195,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 @@ -213,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 @@ -222,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/docs/concepts/architecture.md b/src/blueprint/agent_generator/docs/concepts/architecture.md similarity index 54% rename from docs/concepts/architecture.md rename to src/blueprint/agent_generator/docs/concepts/architecture.md index c8b35462..31016c13 100644 --- a/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 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; 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 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 @@ -84,7 +98,7 @@ class IngestHandler(EventHandlerBase): |---|---| | `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 @@ -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 new file mode 100644 index 00000000..54352f10 --- /dev/null +++ b/src/blueprint/agent_generator/docs/concepts/caching.md @@ -0,0 +1,401 @@ +# Caching + +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). + +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. + +--- + +## Declaring a cache + +`with_cache()` on the builder: + +```python +from blueprint.agents import AppBuilder + +agent = ( + AppBuilder() + .with_service(MyService) + .with_handler(MyHandler) + .with_cache() +) +``` + +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. + +### Several caches + +Call it again with a name: + +```python +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 +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. + +| 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 | + +`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*. + +--- + +## Using a cache + +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 +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) +``` + +**The cache interface is synchronous.** `get`, `set` and the rest are ordinary methods; they are +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. + +### Operations + +| 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 | + +### `claim`: deciding which process does the work + +`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. + +**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 caller got there first +``` + +### Keys and namespaces + +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 +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) +``` + +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`. + +### TTL + +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. + +--- + +## A cache belongs to the agent that declared it + +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. + +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. + +Where the data goes: + +| | Disk backend | Redis backend | +|---|---|---| +| 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` | + +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 +[deployment.md](../guides/deployment.md). + +A single-agent application is unaffected in every respect: same directory, same Redis keyspace, +same registry names it always had. + +> **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. + +--- + +## Configuration + +Under `[default.cache]` in `settings.toml`: + +```toml +[default.cache] +cache_dir = ".cache/blueprint" +size_limit = 1000000000 # bytes +eviction_policy = "least-recently-used" +default_ttl = 3600 # seconds +``` + +| 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` | 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 | +| `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 +Redis beside a neighbour on disk: + +```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 + +### Disk (default) + +Backed by `diskcache-rs`, a Rust implementation of the diskcache format. Persists to +`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 + +For state shared across replicas -- horizontal scaling, blue/green, several pods behind one +service. Install the extra: + +```bash +pip install 'avs-blueprint-agents[redis]' +``` + +and switch backends in the settings file: + +```toml +[default.cache] +backend = "redis" +redis_url = "redis://localhost:6379/0" +key_prefix = "inventory-api" +``` + +No code changes: `with_cache()` picks up the backend from configuration. + +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. + +**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: + +- 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. + +The same applies when the `redis` extra is not installed at all. + +--- + +## Readiness + +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. + +| 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` | + +`/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. + +--- + +## The management API + +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. + +| 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 | + +`?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"}' +``` + +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. + +**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, ...} +``` + +> `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 + +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. + +``` + 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: + +- **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. + +A new backend means implementing `CacheService` and extending the factory. Nothing that uses a +cache has to change. + +--- + +## Where things live + +| 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` | + +--- + +## Troubleshooting + +| 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/src/blueprint/agent_generator/docs/concepts/configuration.md b/src/blueprint/agent_generator/docs/concepts/configuration.md new file mode 100644 index 00000000..10ccd953 --- /dev/null +++ b/src/blueprint/agent_generator/docs/concepts/configuration.md @@ -0,0 +1,318 @@ +# Configuration + +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 + +The `Config` class is the entry point for all configuration. It accepts a list of settings files and merges them in order, with later files overriding earlier ones. + +```python +from blueprint.agents import Config + +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`. + +## File Structure + +### settings.toml + +The primary configuration file. All settings live under a `[default]` section (the Dynaconf default environment). + +```toml +[default] +app_name = "document-processor" +log_level = "INFO" +event_bus = "dapr" +``` + +### .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. + +```toml +[default] +model_api_key = "YOUR_API_KEY_HERE" +database_connection_string = "postgresql://USER:PASSWORD@HOST/DB" +``` + +## Values from the Environment + +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] +nats_url = "@format {env[NATS_URL]}" +``` + +## Configuration Sections + +### AI Runtime Configuration + +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_max_tokens = 4096 +model_temperature = 0.3 +model_base_url = "https://api.openai.com/v1" + +[default.runtimes.classifier] +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]`. + +```toml +[default.cache] +cache_dir = "/tmp/blueprint-cache" +size_limit = 1073741824 # 1 GB in bytes +eviction_policy = "least-recently-used" +default_ttl = 3600 # seconds +``` + +See the [Caching](caching.md) concept document for full details. + +### Event Publishing Configuration + +Controls how events are published, including the default pub/sub component and topic-to-event-type mappings. + +```toml +[default.event_publishing] +default_pubsub_name = "pubsub" + +[default.event_publishing.topic_mapping] +"document.received" = "documents-inbound" +"document.summarized" = "documents-processed" +"document.error" = "documents-errors" +``` + +See the [Event Processing](event-processing.md) concept document for full details. + +### Observability Configuration + +Settings for OpenTelemetry tracing and structured logging. + +```toml +[default] +otel_enabled = true +otel_endpoint = "http://localhost:4317" +otel_service_name = "document-processor" +log_level = "INFO" +``` + +See the [Observability](observability.md) concept document for full details. + +## Accessing Configuration at Runtime + +All components inherit access to configuration through `self.config`, which is available from `on_startup()` onward. + +### General Access + +```python +from blueprint.agents.services.service_base import ServiceBase + + +class StorageService(ServiceBase): + async def on_startup(self) -> None: + # Read a single value + db_url = self.config.get("database_url") + + # Read a value with a default + timeout = self.config.get("request_timeout", 30) +``` + +### AI Runtime Configuration + +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 + + +class ModelService(ServiceBase): + async def on_startup(self) -> None: + ai_config = self.config.get_ai_config("summarizer") + + 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 + +Use `get_cache_config()` to retrieve cache-related settings as a structured object. + +```python +cache_config = self.config.get_cache_config() +print(cache_config.cache_dir) # "/tmp/blueprint-cache" +print(cache_config.size_limit) # 1073741824 +print(cache_config.eviction_policy) # "least-recently-used" +print(cache_config.default_ttl) # 3600 +``` + +## Validation + +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, ValueError) as e: + # e.g., "No model name for runtime agent 'summarizer' configured" + print(f"Configuration error: {e}") +``` + +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 + +```toml +[default] +app_name = "document-processor" +log_level = "INFO" +event_bus = "dapr" + +# Observability +otel_enabled = true +otel_endpoint = "http://localhost:4317" +otel_service_name = "document-processor" + +# Event publishing +[default.event_publishing] +default_pubsub_name = "pubsub" + +[default.event_publishing.topic_mapping] +"document.received" = "documents-inbound" +"document.summarized" = "documents-processed" +"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_max_tokens = 4096 +model_temperature = 0.3 + +[default.runtimes.classifier] +model_provider = "openai" +model_name = "gpt-4o-mini" +model_max_tokens = 2048 +model_temperature = 0.0 + +# Cache +[default.cache] +cache_dir = "/tmp/blueprint-cache" +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. 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: + +```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. + +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`, `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 -- +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/concepts/event-processing.md b/src/blueprint/agent_generator/docs/concepts/event-processing.md new file mode 100644 index 00000000..b9f0eca4 --- /dev/null +++ b/src/blueprint/agent_generator/docs/concepts/event-processing.md @@ -0,0 +1,508 @@ +# Event Processing + +Blueprint Agents uses the CloudEvents v1.0 specification as its universal message format. Events flow through a handler chain where each handler can inspect, process, transform, or forward events to downstream consumers. + +## CloudEvent Model + +The framework provides a generic `CloudEvent[T]` model that wraps the standard CloudEvents attributes with a typed data payload. + +```python +from blueprint.agents.models.events import CloudEvent, GenericCloudEvent +``` + +### Core Fields + +| Field | Type | Description | +|---|---|---| +| `id` | `str` | Unique event identifier (UUID by default) | +| `type` | `str` | Event type identifier, e.g. `"document.received"` | +| `source` | `str` | URI identifying the event producer | +| `subject` | `str` | Subject of the event in context of the source | +| `time` | `datetime` | Timestamp when the event was created | +| `data` | `T` | The event payload, typed by the generic parameter | + +### GenericCloudEvent + +For cases where the data payload does not require a specific schema, use the pre-defined alias: + +```python +# GenericCloudEvent is equivalent to CloudEvent[dict[str, Any]] +event = GenericCloudEvent( + type="document.received", + source="/ingest/api", + subject="doc-12345", + data={"content": "The full document text...", "format": "plaintext"}, +) +``` + +### Typed Events + +For structured payloads, parameterize `CloudEvent` with a Pydantic model or dataclass: + +```python +from pydantic import BaseModel +from blueprint.agents.models.events import CloudEvent + + +class DocumentPayload(BaseModel): + content: str + format: str + word_count: int + + +event: CloudEvent[DocumentPayload] = CloudEvent( + type="document.received", + source="/ingest/api", + subject="doc-12345", + data=DocumentPayload(content="...", format="plaintext", word_count=1500), +) +``` + +## Handler Chain-of-Responsibility + +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` (lower values are asked earlier), set through the base +class constructor: + +```python +from typing import Any + +from blueprint.agents.handler.event_handler_base import EventHandlerBase +from blueprint.agents.models.events import GenericCloudEvent, HandlerResult + + +class DocumentHandler(EventHandlerBase): + def __init__(self) -> None: + super().__init__(priority=10) + + async def on_startup(self) -> None: + self._service = self.registry.get_service(DocumentService) + + async def on_shutdown(self) -> None: + pass + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return event.type == "document.received" + + 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 implements two methods, both `async` and both given the event and the processing +`context`: + +- **`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 next: + +| 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) | + +### Return None -- Offer the Event to the Next Handler + +`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 +return HandlerResult(event_type="document.summarized", data={"summary": summary, "original_id": event.id}) +``` + +### Return a List of HandlerResult -- Publish Multiple Events + +Returning a list publishes multiple downstream events, useful for fan-out patterns. + +```python +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 + +**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. + +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. 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. + +**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 +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 a dict + +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 + +Each handler should declare the event types it may produce. The framework uses this metadata for validation and documentation. + +```python +class DocumentHandler(EventHandlerBase): + def get_published_event_types(self) -> list[str]: + return ["document.summarized", "document.error"] +``` + +## Event Bus Configuration + +Blueprint Agents supports two event bus backends: Dapr and NATS. The choice is made in `settings.toml`. + +### Selecting the Event Bus + +```toml +[default] +event_bus = "dapr" # "dapr", "nats", or "sessions" +``` + +### Topic Mapping + +Map event types to topics so the framework knows where to publish each event: + +```toml +[default.event_publishing] +default_pubsub_name = "pubsub" + +[default.event_publishing.topic_mapping] +"document.received" = "documents-inbound" +"document.summarized" = "documents-processed" +"document.error" = "documents-errors" +``` + +## Dapr Event Bus + +When `event_bus = "dapr"`, the framework integrates with the Dapr sidecar for pub/sub messaging. + +- **Receiving events**: The application exposes an HTTP endpoint at `/events/{topic}`. The Dapr sidecar delivers messages by calling this endpoint. +- **Publishing events**: The framework publishes events through the Dapr sidecar HTTP API (`/v1.0/publish/{pubsub}/{topic}`). + +Dapr handles message delivery guarantees, retries, and dead-letter queues through its component configuration. + +```toml +[default] +event_bus = "dapr" + +[default.event_publishing] +default_pubsub_name = "pubsub" + +[default.event_publishing.topic_mapping] +"document.received" = "documents" +``` + +## NATS Event Bus + +When `event_bus = "nats"`, the framework connects directly to a NATS server. + +- **Receiving events**: The framework subscribes to NATS subjects mapped from topic names. +- **Publishing events**: Messages are published directly to NATS subjects. +- **JetStream**: Optional JetStream support provides persistence, replay, and at-least-once delivery guarantees. + +```toml +[default] +event_bus = "nats" +nats_url = "nats://localhost:4222" + +[default.event_publishing] +default_pubsub_name = "default" + +[default.event_publishing.topic_mapping] +"document.received" = "documents.inbound" +"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: + +**`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. + +**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 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` 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` | + +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. 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 + 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 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, 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. + +**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. `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 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 +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 `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 + +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. | + +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 + +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: + +1. `SessionsApiClient` — REST client for the sessions service +2. `SessionKeyProvider` — session-key resolution with TTL cache +3. `SessionsBus` — outbound SSE consumer that converts job notifications into CloudEvents and dispatches them through the handler chain + +`SessionsBus` has no inbound HTTP surface — there is no router to mount. Connection to the sessions service is established asynchronously after startup; the framework tolerates a sessions service that is unreachable at boot and retries in the background. + +> **Agent registration (sessions v0.4.0+):** Before opening the SSE job stream, `SessionsBus` calls +> `POST /agents/register` to declare its `agent_id`, `agent_type`, and `capabilities` — the dispatch +> source of truth. It re-registers before every reconnect attempt (idempotent), and on graceful +> shutdown it drains in-flight jobs and unregisters (`DELETE /agents/{agent_id}`). Against a pre-v0.4.0 +> server the register call returns 404 and is skipped ("legacy, proceed without registration"). + +> **Reconnect catch-up:** SSE only pushes jobs created *while connected*, so jobs created during a +> restart, redeploy, or stream gap would otherwise be missed. On every (re)connect `SessionsBus` +> reconciles in two ways: it resumes the stream with `Last-Event-ID` (the server replays missed +> frames from its ring buffer on a same-process reconnect), and it runs a REST **catch-up** — +> `GET /jobs?status=pending` for its capabilities — dispatching any pending jobs through the normal +> handler path. Both feed the same idempotent handler, so a job that arrives via more than one route +> is processed once. Catch-up is best-effort: a listing failure is logged and never disturbs the live +> stream. A job stranded in `running` because its previous owner crashed is recovered server-side +> (the sessions reaper re-pends it) and then redelivered by this catch-up. + +```toml +[default] +event_bus = "sessions" + +[default.sessions_service] +base_url = "http://sessions:8000" +agent_id = "my-agent" +agent_type = "analyser" +capabilities = ["analyse_documents"] +api_key = "@format {env[SESSIONS_API_KEY]}" +# Optional per-agent HS256 bearer. Sent as `Authorization: Bearer ` alongside +# `X-Api-Key` on the gated routes only when set. See service-sessions#198/#326. Inject via +# SESSIONS_AGENT_TOKEN, never commit it. To opt out, OMIT this line (or export an empty +# SESSIONS_AGENT_TOKEN=) — keeping it with the env var undefined fails Dynaconf config load. +agent_token = "@format {env[SESSIONS_AGENT_TOKEN]}" +max_concurrent_jobs = 5 +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 GenericCloudEvent, HandlerResult + + +class DocumentChanged(BaseModel): + """DTO: the payload of document.received / document.updated.""" + + document_id: str + + +class IngestionHandler(EventHandlerBase): + def __init__(self) -> None: + super().__init__(priority=5) + + async def on_startup(self) -> None: + self._ingestion = self.registry.get_service(IngestionService) + + async def on_shutdown(self) -> None: + pass + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + return event.type in ("document.received", "document.updated") + + 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 new file mode 100644 index 00000000..68729dcf --- /dev/null +++ b/src/blueprint/agent_generator/docs/concepts/observability.md @@ -0,0 +1,429 @@ +# Observability + +Traces, metrics, logs and probes, and -- the part that only matters once several agents share a +process -- **which agent each of them belongs to**. + +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. + +Two rules run through all of it: + +- **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). + +--- + +## Tracing + +### Configuration + +```toml +[default] +otel_enabled = true +otel_endpoint = "localhost:4317" # OTLP over gRPC; host:port, no path +otel_service_name = "document-processor" +``` + +| Key | Type | Meaning | +|---|---|---| +| `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. | + +### One identity per agent + +The framework does not configure *a* tracer provider; it configures one per namespace, each with +its own resource: + +| Attribute | Value | +|---|---| +| `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. | + +**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. **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` 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 +reporting `otel_service_name`, unchanged, because its components live in the root namespace. + +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. + +**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. + +### `@traced()` + +`@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 + + +class EmbeddingService(ServiceBase): + async def on_startup(self) -> None: + self._model = self.registry.get_agent("embedder") + + @traced() + async def compute(self, text: str) -> list[float]: + return await self._model.run(text) +``` + +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: ... +``` + +- 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. + +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. + +An exception propagating out of the method sets the span status to `ERROR` before it is re-raised. + +--- + +## Metrics + +| 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. 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`. | +| `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. | + +**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. + +`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. + +`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. + +--- + +## Probes + +| Endpoint | Answers | +|---|---| +| `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. | + +**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. + +**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 + +```toml +[default] +readiness_policy = "critical" # "all" (default) | "critical" | "any" +``` + +| 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. 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. + +`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] +``` + +### 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"]} + } +} +``` + +`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. + +**`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: + +```python +from blueprint.agents.io.api.actuators.health import HealthCheckerBase +from blueprint.agents.models.api import ComponentHealth + + +class DatabaseHealth(HealthCheckerBase): + def __init__(self, database: DatabaseService) -> None: + self._database = database + + 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") +``` + +Register it on the builder, where the agent it belongs to is whichever one is in force: + +```python +builder.with_health_checker("database", DatabaseHealth(database)) +``` + +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, 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 + +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), +`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 (OSError: connection refused)" +} +``` + +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 + +One state -- is this agent serving -- with three consequences, and they are deliberately not three +mechanisms. + +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: 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 + 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`. 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 +health check while the agent is unusable, so an observed-health signal would put it straight back +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. + +--- + +## Detecting a blocked event loop + +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. + +| Setting | Mechanism | +|---|---| +| 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 # 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 +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` 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 +in. That is still the difference between "the pod was slow" and "one of these two agents blocked +the loop for four seconds". + +--- + +## 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. + +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. + +--- + +## Logging + +Use `%`-style lazy formatting, not f-strings, and get a module-level logger: + +```python +from logging import getLogger + +_log = getLogger(__name__) + +_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/getting-started.md b/src/blueprint/agent_generator/docs/getting-started.md similarity index 70% rename from docs/getting-started.md rename to src/blueprint/agent_generator/docs/getting-started.md index e932fd26..0d53e2e6 100644 --- a/docs/getting-started.md +++ b/src/blueprint/agent_generator/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 @@ -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. -- **`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. +- **`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) 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. --- @@ -202,7 +209,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/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..53c4318d --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/cli-reference.md @@ -0,0 +1,63 @@ +# 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 | +| `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 +``` + +--- + +## 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 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 [--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/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..f8fa0d8f --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/cli/create.md @@ -0,0 +1,532 @@ +# 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, 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` | + +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 (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: + # 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 handler resources on shutdown.""" + + async def can_handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> bool: + # Example: + # return event.type == "order.placed" + raise NotImplementedError() + + async def handle_event(self, event: GenericCloudEvent, context: dict[str, Any]) -> HandlerResult | 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 + +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 + +from pydantic import BaseModel + + +class InvoiceProcessorService(ServiceBase): + def __init__(self) -> None: + super().__init__() + + async def on_startup(self) -> None: + """Initialize the service by getting dependencies from the registry.""" + + async def on_shutdown(self) -> None: + """Clean up service resources on shutdown.""" + + async def process(self, base_model: BaseModel) -> BaseModel: + """This method contains business logic of this microservice. + + Args: + base_model (BaseModel): The incoming data, parsed into the domain input model. + + Returns: + BaseModel: The processed data parsed into the domain output model. + """ + + raise NotImplementedError() +``` + +--- + +## 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 (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 ..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: + # TODO: Get services from registry + # Example: self._service = self.registry.get_service("some_service") + 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..model_settings]` 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.model_settings] +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()` -- 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. + +### 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 (mon-sun; 0-6 = Monday-Sunday) +│ │ │ │ │ +│ │ │ │ │ +* * * * * +``` + +Common patterns: +- `*/5 * * * *` - Every 5 minutes +- `0 * * * *` - Every hour at minute 0 +- `0 2 * * *` - Daily at 2: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 + +```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 (docstrings shortened): + +```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: + """Declare the schedule; 'scheduler_mode' in settings.toml decides what calls tick().""" + super().__init__(crontab="0 2 * * *") + + async def on_startup(self) -> None: + """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.""" + + await super().on_shutdown() + + async def tick(self) -> None: + """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 new file mode 100644 index 00000000..7720102c --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/cli/dev.md @@ -0,0 +1,76 @@ +# asbs dev + +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 [--name ] [--agents ] [--host ] [--port ] +``` + +## Options + +| Flag | Description | Default | +|--------------------|-------------------------------------------------------------|------------------| +| `--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 over the map +and `--agents`: a developer reproducing a particular deployment is not overridden by a default +read out of the agent map. + +## Example + +```bash +asbs dev --port 9000 +``` + +In an agent directory: + +``` +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 [...] +``` + +uvicorn's reloader watches the directory `asbs dev` was started in and restarts the server when a +file changes. + +--- + +## Running a single agent + +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 # served on its own: routes under /api/... +asbs dev --name orders # served as "orders": routes under /api/orders/... +``` + +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 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/naming.md b/src/blueprint/agent_generator/docs/guides/cli/naming.md new file mode 100644 index 00000000..cc9a272d --- /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 .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..815f3234 --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/cli/setup.md @@ -0,0 +1,155 @@ +# asbs setup + +Scaffold a complete Blueprint Agents project with all required directories and configuration files. + +```bash +asbs setup [--output-dir ] [--overwrite] [--verbose] +asbs setup --group [--output-dir ] [--overwrite] +``` + +## Arguments + +| Argument | Description | Required | +|----------------|------------------------------------|----------| +| `project-name` | The agent's name | Yes, unless `--group` | + +## Options + +| Flag | Description | Default | +|-----------------------|--------------------------------------------------------|---------| +| `--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 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/ + handlers/ + 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` 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. + +## Example + +```bash +mkdir my-ai-service && cd my-ai-service +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, 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 --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** +map, which lives in the repository that builds the image: + +```toml +[agents.my_ai_service] +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. + +--- + +## 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 +.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 +`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 new file mode 100644 index 00000000..207738e6 --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/cli/validate.md @@ -0,0 +1,218 @@ +# asbs validate + +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 [] [--environment NAME] +asbs validate --group [] [--agent-map PATH] [--group-config PATH] [--group-name NAME] [--environment NAME] +``` + +## Which settings are checked + +Settings are read the way the process reads them, for **one environment**: + +- 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. + +No value from a `.secrets.toml` is ever printed; only key names are. + +## Checks performed + +Project shape (`asbs validate` only): + +- 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 + +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 +- 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_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 + +Process keys: + +- `event_loop_debug` is a boolean (read with the runtime's `parse_bool`); anything else fails + startup + +## Example + +```bash +asbs validate +``` + +``` +Validating Blueprint Agents project: /work/orders +Environment: production (choose another with --environment) + +[ok] Found src/ +[ok] Found tests/ +[ok] Found settings.toml +... + +============================================================ + +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, 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 --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 +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: + +- 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 +- 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 +- 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 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/docs/guides/deployment.md b/src/blueprint/agent_generator/docs/guides/deployment.md new file mode 100644 index 00000000..976a3749 --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/deployment.md @@ -0,0 +1,880 @@ +# Deployment Guide + +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 (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 +> `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. + +--- + +## The image + +**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 runtime stage, as `asbs setup --group` writes it (comments shortened): + +```dockerfile +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 --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 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)"] + +ENTRYPOINT ["python", "-m", "blueprint.agents.entrypoint"] +``` + +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 + *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`**, 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. + 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 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. + +### Building and running + +```bash +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 +``` + +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. + +--- + +## Choosing what a process runs + +| 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 | + +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. + +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. + +**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 + +### Chart structure + +``` +helm/ + Chart.yaml + values.yaml + templates/ + 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 +group: checkout # which group this Deployment runs +replicaCount: 2 # safe; see "Running more than one replica" + +image: + repository: myregistry.azurecr.io/my-agents + tag: "1.2.3" + pullPolicy: IfNotPresent + +service: + type: ClusterIP + port: 80 + targetPort: 8000 + +dapr: + enabled: false # a group has one Dapr endpoint; see the note under scaling + appId: "checkout" + appPort: 8000 + logLevel: "info" + +app: + port: 8000 + logLevel: "info" + +resources: + requests: + cpu: 250m + memory: 512Mi + limits: + cpu: "1" + memory: 1Gi # a group's memory is the sum of its agents; see "Sizing a group" + +probes: + liveness: + path: /health/live + initialDelaySeconds: 15 + periodSeconds: 20 + timeoutSeconds: 5 + failureThreshold: 3 + readiness: + path: /health/ready + initialDelaySeconds: 10 + periodSeconds: 10 + timeoutSeconds: 5 + failureThreshold: 12 # the broker's own startup; see "Health probes" + +autoscaling: + enabled: false + minReplicas: 2 + maxReplicas: 10 + targetCPUUtilizationPercentage: 70 +``` + +### Deployment template + +```yaml +# templates/deployment.yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + 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" + dapr.io/app-id: {{ .Values.dapr.appId | quote }} + dapr.io/app-port: {{ .Values.dapr.appPort | quote }} + dapr.io/log-level: {{ .Values.dapr.logLevel | quote }} + {{- end }} + spec: + containers: + - 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 }} + failureThreshold: {{ .Values.probes.liveness.failureThreshold }} + readinessProbe: + httpGet: + path: {{ .Values.probes.readiness.path }} + port: {{ .Values.app.port }} + initialDelaySeconds: {{ .Values.probes.readiness.initialDelaySeconds }} + periodSeconds: {{ .Values.probes.readiness.periodSeconds }} + failureThreshold: {{ .Values.probes.readiness.failureThreshold }} + resources: + {{- toYaml .Values.resources | nindent 12 }} + volumes: + - name: groups + configMap: + name: {{ .Release.Name }}-groups +``` + +`POD_NAME` is worth injecting: the framework reads it for the telemetry `service.instance.id` and +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 + +```yaml +# templates/groups-configmap.yaml +apiVersion: v1 +kind: ConfigMap +metadata: + 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. 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 + +```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, skipped (`HandlerResult.skipped`), or no handler matched it | **ack** -- none of them is a failure | +| 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 | + +Keys to set deliberately. 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). 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 (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 + 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`** (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. + +### 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 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`. + +**The TTL must outlast the broker's redelivery window**, which is +`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 # nats_ack_wait = 300, nats_max_deliver = 5 +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 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 +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: + 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 }} +``` + +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` 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. + +--- + +## 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 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, 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"` + +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, 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, +the `CronJob` must publish on the schedule that code declares, and keeping them in step is currently +manual: + +```yaml +apiVersion: batch/v1 +kind: CronJob +metadata: + 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 +``` + +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`. + +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, and can every agent still consume? | a degraded agent | +| `GET /health/ready` | Should this pod receive traffic? | -- | + +**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 +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. + +**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: + +| 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. Both +`policy` and `namespaces` appear only when the process hosts a group; a standalone agent's payload +is `status` and `components`. + +### 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 + +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: agents + 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 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. + +**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. + +> **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. + +--- + +## Configuration + +### Environment variable overrides + +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: + +```toml +[default] +app_port = 8000 +log_level = "INFO" +model_provider = "openai" + +[default.cache] +backend = "redis" + +[default.runtimes.order_agent] +model_name = "gpt-4.1-nano" +``` + +```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 +``` + +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.*`, `event_publishing.*` and +`runtimes..*` (with its legacy singular `runtime..*`). + +#### 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-agents: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-agents: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. + +`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. + +#### 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-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: checkout-config +data: + 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" +``` + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: checkout-secrets +type: Opaque +stringData: + DYNACONF_MODEL_API_KEY: "sk-..." + DYNACONF_CACHE__REDIS_PASSWORD: "..." +``` + +### Resolution order + +Later sources override earlier ones: + +1. `settings.toml` -- base configuration, baked into the image +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. + +--- + +## 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.** 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. `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. + +--- + +## Stateless design + +Handlers and services should be designed as stateless components: + +- 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. + +--- + +## See also + +- [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/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..dc8297c3 --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-migration.md @@ -0,0 +1,338 @@ +# 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 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. + +## 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, and so does `create_app()`. + +## 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 ./ +``` + +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 +`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, 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: + +```bash +asbs setup --group +``` + +Then add this agent: + +```toml +[agents.order] +root = "agents/order" +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. + +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 +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. +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 # inside the agent's directory: the agent itself +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 +file sitting where the framework will not look for it, and names process-wide keys left in an +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 + +| 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. + +--- + +## 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/ +``` + +### 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: +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 + +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). + +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 + +- [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/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md new file mode 100644 index 00000000..a07053ee --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/multi-agent-setup.md @@ -0,0 +1,503 @@ +# 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. 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 +deployed on its own keeps working, unchanged, indefinitely. There is no deprecation here. + +--- + +## A. A new project + +```bash +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: + +**`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, and so does +`create_app()`. + +**The agent carries no `agents.toml`, and that is the point.** + +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: + +| Host | Where the name comes from | +|---|---| +| 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 | + +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 + +```bash +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 +``` + +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 -p 8000:8000 order-processor +``` + +### Adding a second agent to the same image + +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, 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: + +```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] +root = "agents/some_topic/order_processor" +module = "agents.some_topic.order_processor.src.main:agent" + +[agents.billing] +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 **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. + +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/ + ... +``` + +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. + +**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 +``` + +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. + +--- + +## 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. 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. + +--- + +## 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}` | +| 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` | + +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}` | +| 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` | + +**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. + +### 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 +**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] +root = "agents/order" +module = "agents.order.src.main:agent" + +[agents.billing] +root = "agents/billing" +module = "agents.billing.src.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. +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 + +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. + +### 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, 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 + +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. 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 + +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 pathlib import Path + +from blueprint.agents import AgentGroup, Config + +from agents.order.src.main import agent as order +from agents.billing.src.main import agent as billing + +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. + +--- + +## 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). 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 +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** -- 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. +So a retry asked for by one agent redelivers to every agent in the group, and grouped Dapr therefore +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. + +--- + +## 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 +- [Observability](../concepts/observability.md) -- what each agent reports, and under which identity diff --git a/docs/guides/testing.md b/src/blueprint/agent_generator/docs/guides/testing.md similarity index 62% rename from docs/guides/testing.md rename to src/blueprint/agent_generator/docs/guides/testing.md index 28f84c4b..588f9913 100644 --- a/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 @@ -196,9 +192,8 @@ class TestProductCatalogApi: def app(self, mock_registry): """Create a FastAPI app with the API routes registered.""" app = FastAPI() - api = ProductCatalogApi() - api.registry = mock_registry - api.register_routes(app.router) + api = ProductCatalogApi() # wires its decorated routes on construction + app.include_router(api.router) # mounted bare: the application would add /api return app @pytest.fixture @@ -275,68 +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"] == "alive" +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): - 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 "components" in data +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 ``` --- @@ -346,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 new file mode 100644 index 00000000..c7f8e865 --- /dev/null +++ b/src/blueprint/agent_generator/docs/guides/troubleshooting.md @@ -0,0 +1,643 @@ +# Troubleshooting Guide + +This guide covers common issues encountered when developing and deploying Blueprint Agents applications, along with their causes and solutions. + +--- + +## Installation Issues + +### Wrong Python Version + +**Symptom:** Installation fails with an error referencing unsupported syntax or incompatible package versions. + +``` +ERROR: Package 'avs-blueprint-agents' requires a different Python: 3.10.x not in '>=3.13' +``` + +**Cause:** Blueprint Agents requires Python 3.13 or later. + +**Solution:** Install the correct Python version and verify it is active: + +```bash +python --version +# Must be 3.13 or later + +# If using pyenv +pyenv install 3.13.0 +pyenv local 3.13.0 +``` + +### pip vs uv Installation + +**Symptom:** Dependencies fail to resolve or installation is unexpectedly slow. + +**Cause:** The standard `pip` resolver may struggle with complex dependency trees. + +**Solution:** Use `uv` for faster and more reliable installs: + +```bash +pip install uv +uv pip install avs-blueprint-agents +``` + +### TestPyPI Configuration + +**Symptom:** Package not found when installing a pre-release version. + +``` +ERROR: Could not find a version that satisfies the requirement avs-blueprint-agents==0.6.0a3 +``` + +**Cause:** Pre-release versions may be hosted on TestPyPI rather than the main PyPI index. + +**Solution:** Configure pip to check TestPyPI as an additional index: + +```bash +pip install avs-blueprint-agents==0.6.0a3 \ + --index-url https://test.pypi.org/simple/ \ + --extra-index-url https://pypi.org/simple/ +``` + +--- + +## Configuration Errors + +### ConfigError on Startup + +**Symptom:** Application crashes immediately with a `ConfigError`. + +``` +blueprint.agents.config.config.ConfigError: Invalid app port: 70000 +``` + +**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:** Correct the setting the message names. The framework's keys are **flat** keys under +`[default]`, not tables of their own: + +```toml +[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: + +```bash +asbs validate +``` + +### Missing Required Settings + +**Symptom:** A specific component fails to initialize because a setting it depends on is absent. + +**Cause:** The component expects a configuration key that was not provided. + +**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_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. + +``` +[ERROR] Could not bind to port 80: Permission denied +``` + +**Cause:** The configured port is privileged (below 1024) or already in use. + +**Solution:** Use a non-privileged port in `settings.toml`: + +```toml +[default] +app_port = 8000 +``` + +Or check for port conflicts: + +```bash +lsof -i :8000 +``` + +--- + +## Event Bus Connectivity + +### Dapr Sidecar Not Running + +**Symptom:** Application logs show errors when attempting to publish or subscribe to events. + +``` +ConnectionRefusedError: Cannot connect to Dapr sidecar at localhost:3500 +``` + +**Cause:** The Dapr sidecar process is not running alongside the application. + +**Solution:** + +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:create_app --factory +``` + +In Kubernetes, verify the Dapr annotations are present on the pod: + +```yaml +annotations: + dapr.io/enabled: "true" + dapr.io/app-id: "my-ai-service" + dapr.io/app-port: "8000" +``` + +### NATS Connection Refused + +**Symptom:** Event bus fails to connect to the NATS server. + +``` +nats.errors.ConnectionClosedError: connection refused +``` + +**Cause:** The NATS server is not reachable at the configured address. + +**Solution:** Verify the NATS server is running and accessible: + +```bash +# Check if NATS is running locally +nats-server --addr 0.0.0.0 --port 4222 + +# Test connectivity +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. 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 + +**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). + +### `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. + +### `DurableConflictError`: a consumer that `belongs to another subscription` + +**Symptom:** One agent never starts, or `/health/live` answers `503` naming it, and the log has a +CRITICAL line: + +``` +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 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. + +**Cause:** The topic the handler subscribes to, or the event type it accepts, does not match what the +publisher sends. + +**Solution:** Verify that topic and event type match exactly between publisher and subscriber: + +```python +# Publisher (EventPublishingService) +await publisher.publish_event(event, topic="order.created") + +# Handler -- the subscribed topic and the accepted type must match exactly +class OrderHandler(EventHandlerBase): + 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. + +--- + +## LLM Provider Issues + +### Missing API Key + +**Symptom:** Startup or the first agent call fails with an authentication error from the provider's +client, for the `openai` provider: + +``` +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:** `model_api_key` is not configured. + +**Solution:** Set it in `.secrets.toml` (for local development) or via an environment variable (for production): + +```toml +# .secrets.toml (local only -- do not commit) +[default] +model_api_key = "YOUR_API_KEY_HERE" +``` + +```bash +# Environment variable +export DYNACONF_MODEL_API_KEY="YOUR_API_KEY_HERE" +``` + +### Invalid Model Name + +**Symptom:** Agent initialization fails with a model-not-found error. + +``` +InvalidRequestError: The model 'gpt-5-turbo' does not exist +``` + +**Cause:** The configured model name is not recognized by the LLM provider. + +**Solution:** Verify the model name against the provider's documentation: + +```toml +[default] +model_provider = "openai" +model_name = "gpt-4.1-mini" # Use a valid model identifier +``` + +### Timeout Errors + +**Symptom:** LLM calls fail intermittently with timeout errors. + +``` +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 (unset, the provider SDK's own default applies): + +```toml +[default] +model_timeout = 60 # seconds, per model request +``` + +Alternatively, consider breaking complex prompts into smaller steps or implementing retry logic in your service. + +### Provider Not Supported + +**Symptom:** Application raises an error about an unsupported LLM provider. + +``` +ValueError: Unsupported provider: 'anthropic'. Supported: ['vllm', 'openai'] +``` + +**Cause:** `model_provider` names a provider the framework has no client for. + +**Solution:** Use a supported provider name: + +```toml +[default] +model_provider = "openai" # OpenAI API +# model_provider = "vllm" # a vLLM server at model_base_url; model_api_key is required +``` + +--- + +## Component Registration Errors + +### Duplicate Component Names + +**Symptom:** Application fails to start with a duplicate registration error. + +``` +ValueError: Component with name order_handler already exists +``` + +**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:** Give the second registration a name of its own: + +```python +agent = ( + AppBuilder() + .with_service(PricingService) + .with_service(PricingService, name="eu_pricing_service") # a second instance, its own name +) +``` + +Run validation to detect duplicates: + +```bash +asbs validate +``` + +### Looking Up Components in __init__ + +**Symptom:** A service fails when trying to access another service during construction. + +``` +ValueError: Component with name pricing_engine does not exist +``` + +**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: + +```python +class OrderService(ServiceBase): + 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") + self.cache = self.registry.get_cache() # only if the agent declares .with_cache() + + async def on_shutdown(self) -> None: + pass +``` + +--- + +## Health Check Failures + +### Client Health Checker Failing + +**Symptom:** The `/health/ready` endpoint returns unhealthy status for a specific client or external dependency. + +```json +{ + "detail": { + "status": "DOWN", + "components": { + "nats_client": {"status": "unhealthy", "message": "Unhealthy: ..."} + } + } +} +``` + +The probe answers `503`, and the payload is wrapped in `detail`. + +**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`). + +**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 + +**Symptom:** You need to add a health check for a custom dependency. + +**Solution:** Implement a custom health checker and register it with the application: + +```python +from blueprint.agents import AppBuilder +from blueprint.agents.io.api.actuators.health import HealthCheckerBase +from blueprint.agents.models.api import ComponentHealth + + +class DatabaseHealthChecker(HealthCheckerBase): + def __init__(self, db): + self._db = db + + async def health_check(self) -> ComponentHealth: + try: + await self._db.ping() + return ComponentHealth(status="healthy", message="database reachable") + except Exception as 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:** Startup fails because the cache directory cannot be created. + +``` +RuntimeError: Cache directory '.cache/blueprint' could not be created (Permission denied). ... +``` + +**Cause:** The application process does not have write permissions where the cache directory +(`cache.cache_dir`) is. + +**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 && chown -R appuser:appuser /app/.cache +``` + +With a read-only root filesystem, mount an `emptyDir` volume there: + +```yaml +volumes: + - name: cache-volume + emptyDir: {} +volumeMounts: + - name: cache-volume + mountPath: /app/.cache +``` + +### Disk Full + +**Symptom:** Cache writes fail with a disk space error. + +``` +OSError: [Errno 28] No space left on device +``` + +**Cause:** The cache has grown beyond the available disk space. + +**Solution:** Configure a cache size limit in `settings.toml`: + +```toml +[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: + +```yaml +volumes: + - name: cache-volume + emptyDir: + sizeLimit: 1Gi +``` + +### Stale Cache + +**Symptom:** The application returns outdated data despite changes in the source. + +**Cause:** Cached entries have not expired and are being served instead of fresh data. + +**Solution:** Reduce the TTL or clear the cache manually: + +```toml +[default.cache] +default_ttl = 300 # 5 minutes +``` + +To clear the cache programmatically (the cache API is synchronous): + +```python +cache = self.registry.get_cache() +cache.clear() +``` + +--- + +## Testing Issues + +### Async Test Setup + +**Symptom:** Async tests fail with `RuntimeWarning: coroutine was never awaited` or `PytestUnraisableExceptionWarning`. + +**Cause:** pytest is not configured to handle async test functions. + +**Solution:** Install `pytest-asyncio` and set the mode to `auto` in `pyproject.toml`: + +```bash +pip install pytest-asyncio +``` + +```toml +[tool.pytest.ini_options] +asyncio_mode = "auto" +``` + +With `asyncio_mode = "auto"`, all async test functions are detected automatically. You do not need the `@pytest.mark.asyncio` decorator. + +### Mock Registry Patterns + +**Symptom:** Tests fail because the component cannot access services from the registry. + +**Cause:** The registry was not mocked or injected into the component under test. + +**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 + +from blueprint.agents.component.component import Component +from blueprint.agents.component.registry import Registry + + +@pytest.fixture +def mock_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 + return MyService() +``` + +### Missing pytest-asyncio + +**Symptom:** Tests are collected but skipped or produce warnings about missing async support. + +``` +PytestUnhandledCoroutineWarning: async def functions are not natively supported +``` + +**Cause:** The `pytest-asyncio` package is not installed. + +**Solution:** + +```bash +pip install pytest-asyncio +``` + +Verify it is listed in your test dependencies in `pyproject.toml`: + +```toml +[project.optional-dependencies] +test = [ + "pytest>=7.0", + "pytest-asyncio>=0.21", + "pytest-mock>=3.10", + "httpx>=0.24", +] +``` diff --git a/docs/reference/api.md b/src/blueprint/agent_generator/docs/reference/api.md similarity index 68% rename from docs/reference/api.md rename to src/blueprint/agent_generator/docs/reference/api.md index 1fd5e1d5..8d446624 100644 --- a/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,35 @@ 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_health_checker(name, checker)` | `AppBuilder` | Add a named health-check probe. | -| `build()` | `FastAPI` | Finalize and return the configured FastAPI application. | +| `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. 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 ```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** (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. + --- ## Config @@ -98,12 +105,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. | @@ -119,7 +126,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 @@ -131,14 +138,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 ``` --- @@ -197,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}) ``` @@ -223,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. | @@ -262,6 +271,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 | @@ -293,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 @@ -314,7 +334,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. --- @@ -324,17 +345,23 @@ This endpoint allows manual invocation of the `tick()` method outside the cron s 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 new file mode 100644 index 00000000..74b83ea7 --- /dev/null +++ b/src/blueprint/agent_generator/docs/reference/configuration-keys.md @@ -0,0 +1,350 @@ +# Configuration Keys Reference + +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 `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. + +--- + +## Application + +Top-level application settings. + +| Key | Type | Default | Description | +|-----|------|---------|-------------| +| `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, 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. | + +--- + +## Event Bus + +Settings for the event bus transport layer. + +| Key | Type | Default | Description | +|-----|------|---------|-------------| +| `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. | +| `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"`. | +| `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). 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. | +| `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` 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_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. | +| `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`. + +--- + +## 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 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 | 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. 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 +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 +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 `_`. 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. | +| 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 +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 +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 -- 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. | + +--- + +## Scheduling + +| 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 -- 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. | + +--- + +## Event Publishing + +Section: `[default.event_publishing]` + +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. | + +--- + +## AI / Model Runtime + +Section: `[default.runtimes.]` + +Each named runtime defines model provider settings. The `default` runtime is used when no name is specified. + +| Key | Type | Default | Description | +|-----|------|---------|-------------| +| `model_provider` | `str` | -- | Model provider. `"openai"` for OpenAI-compatible APIs, `"vllm"` for vLLM endpoints. | +| `model_name` | `str` | -- | Model identifier (e.g., `"gpt-4o"`, `"meta-llama/Llama-3-70b"`). | +| `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. | + +--- + +## Prompts + +Top-level settings for prompt file resolution. + +| Key | Type | Default | Description | +|-----|------|---------|-------------| +| `prompt_directory` | `str` | -- | Primary directory containing prompt template files. | +| `prompt_search_paths` | `list[str]` | `[]` | Additional directories to search for prompt files, in order. | +| `system_prompt_name` | `str` | `"system"` | Filename (without extension) of the system prompt template. | +| `instruction_prompt_name` | `str` | `"instruction"` | Filename (without extension) of the instruction prompt template. | + +--- + +## Cache + +Section: `[default.cache]` + +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 | +|-----|------|---------|-------------| +| `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. | + +--- + +## Observability + +OpenTelemetry and tracing settings. + +| Key | Type | Default | Description | +|-----|------|---------|-------------| +| `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, 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`. | + +--- + +## Logging + +Additional logging behavior settings. + +| Key | Type | Default | Description | +|-----|------|---------|-------------| +| `suppress_noisy_loggers` | `bool` | `true` | Suppress verbose log output from third-party libraries (e.g., `httpx`, `httpcore`). | + +--- + +## Health and Diagnostics + +| 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. | +| `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 +# Application +app_name = "my_agent_service" +app_port = 8000 +app_environment = "development" +log_level = "INFO" +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" +# 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 +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) +# 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"] +system_prompt_name = "system" +instruction_prompt_name = "instruction" + +# Logging +suppress_noisy_loggers = true + +# Observability +otel_enabled = false +otel_endpoint = "http://localhost:4317" +otel_service_name = "my_agent_service" +token_metrics_enabled = true + +[default.event_publishing] +default_pubsub_name = "pubsub" + +[default.event_publishing.topic_mapping] +"order.created.v1" = "orders" +"order.completed.v1" = "orders" + +[default.runtimes.default] +model_provider = "openai" +model_name = "gpt-4o" +model_api_key = "@format {this.OPENAI_API_KEY}" +model_max_tokens = 4096 +model_temperature = 0.7 +concurrent_requests = 5 + +[default.runtimes.fast] +model_provider = "openai" +model_name = "gpt-4o-mini" +model_api_key = "@format {this.OPENAI_API_KEY}" +model_max_tokens = 2048 +model_temperature = 0.3 +concurrent_requests = 10 + +[default.cache] +cache_dir = ".cache/blueprint" +size_limit = 1000000000 +eviction_policy = "least-recently-used" +default_ttl = 3600 +``` diff --git a/docs/reference/models.md b/src/blueprint/agent_generator/docs/reference/models.md similarity index 74% rename from docs/reference/models.md rename to src/blueprint/agent_generator/docs/reference/models.md index 96c9fb42..5b550a93 100644 --- a/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. --- @@ -75,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). | --- @@ -109,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. | --- diff --git a/src/blueprint/agent_generator/generator/claude_generator.py b/src/blueprint/agent_generator/generator/claude_generator.py index b1339ed1..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,9 +111,25 @@ 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") + 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/src/blueprint/agent_generator/generator/generator.py b/src/blueprint/agent_generator/generator/generator.py index dac234f0..56cb748f 100644 --- a/src/blueprint/agent_generator/generator/generator.py +++ b/src/blueprint/agent_generator/generator/generator.py @@ -16,15 +16,13 @@ InitPartGenerator, MainPartGenerator, MapperPartGenerator, + PyprojectPartGenerator, + SecretsPartGenerator, ServicePartGenerator, SettingsPartGenerator, - SecretsPartGenerator, + TestsPartGenerator, ) -# 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__) @@ -79,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) @@ -92,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. @@ -339,17 +341,54 @@ def _create_files_from_templates(self) -> None: f"{self.config['agent_layer'][agent_name]['runtime_name']}_instruction.prompt", ).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(self.config, self.template_dir, "", "Dockerfile", "Dockerfile").create_file(out) + CopyPartGenerator( + self.config, + self.template_dir, + "", + "Dockerfile", + "Dockerfile", + ).create_file(out) # 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) - # 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) + + # 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) @@ -383,9 +422,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/agent_generator/generator/part_generators/__init__.py b/src/blueprint/agent_generator/generator/part_generators/__init__.py index efd07e35..b6c96144 100644 --- a/src/blueprint/agent_generator/generator/part_generators/__init__.py +++ b/src/blueprint/agent_generator/generator/part_generators/__init__.py @@ -6,7 +6,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", @@ -19,5 +21,7 @@ "HandlerPartGenerator", "CopyPartGenerator", "SettingsPartGenerator", + "PyprojectPartGenerator", "SecretsPartGenerator", + "TestsPartGenerator", ] 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..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 @@ -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,19 +32,20 @@ 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.""" - 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") - if self.config["agent_layer"]: - lines.append("from blueprint.agents.agent import AgentRuntime") + lines.append("from blueprint.agents.config import Config") - 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 +64,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/agent_generator/generator/part_generators/part_generator_base.py b/src/blueprint/agent_generator/generator/part_generators/part_generator_base.py index ed446d52..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 @@ -41,6 +41,35 @@ 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, 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 + 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/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..a26c7c32 --- /dev/null +++ b/src/blueprint/agent_generator/generator/part_generators/pyproject_part_generator.py @@ -0,0 +1,62 @@ +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`, 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/secrets_part_generator.py b/src/blueprint/agent_generator/generator/part_generators/secrets_part_generator.py index be0bd473..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,13 +6,29 @@ 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. + + **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: 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/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/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..df01d87d --- /dev/null +++ b/src/blueprint/agent_generator/generator/part_generators/tests_part_generator.py @@ -0,0 +1,178 @@ +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 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 + 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 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 +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. +""" + +import importlib +import sys + +import pytest + +from blueprint.agents.app_builder import AppBuilder + + +@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(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(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(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] + + assert "service" in kinds + assert "handler" in kinds + + +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 + 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/__init__.py b/src/blueprint/agents/__init__.py index 3d5407a9..03da4ae5 100644 --- a/src/blueprint/agents/__init__.py +++ b/src/blueprint/agents/__init__.py @@ -1,12 +1,16 @@ """Base framework components for the agent blueprint.""" from .agent import AgentBuilder, AgentRuntime +from .agent_group import AgentGroup from .app_builder import AppBuilder from .config import Config +from .utils import run_app __all__ = [ "AgentBuilder", + "AgentGroup", "AgentRuntime", "AppBuilder", "Config", + "run_app", ] diff --git a/src/blueprint/agents/agent/agent_builder.py b/src/blueprint/agents/agent/agent_builder.py index 3c5f09f1..7ebd4fe3 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,28 +68,94 @@ 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 - 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 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 +167,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 +192,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 +283,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 +302,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 +320,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 +339,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 +356,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] ) @@ -283,16 +376,41 @@ def build(self, **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 + # 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 [], + # 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 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] @@ -302,7 +420,7 @@ def build(self, **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/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 new file mode 100644 index 00000000..194c7ed7 --- /dev/null +++ b/src/blueprint/agents/agent_group.py @@ -0,0 +1,553 @@ +"""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 +from collections.abc import Collection, Mapping +from enum import Enum +from pathlib import Path +from types import BuiltinFunctionType, FunctionType, MethodType, ModuleType +from typing import Any + +from fastapi import FastAPI + +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 DEFAULT_GROUP_NAME, AgentSpec, GroupConfig, GroupConfigError +from .layout import check_agent_layout + +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, _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, 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. + + 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, + secrets: Mapping[str, Path] | None = None, + roots: Mapping[str, Path] | None = None, + critical: Collection[str] | 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` 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 -- + 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. + """ + 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()} + 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) + + @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) + + @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.""" + return dict(self._roots) + + @property + def critical_agents(self) -> frozenset[str]: + """The agents this deployment cannot run without.""" + return self._critical + + # ------------------------------------------------------------------ + # 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. + """ + 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). 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 + def from_config(cls, group: GroupConfig) -> "AgentGroup": + """Import each agent named by ``group``, and return the group they form. + + **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. + + 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] = {} + secrets: 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) + 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 + # 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) + roots[spec.name] = spec.root + # Only for an agent that loaded: a skipped non-critical agent has no scope to merge + # anything into. + 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) + # 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 + # 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, secrets=secrets, roots=roots, critical=critical) + + @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 _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) + 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 + # 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) + + 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, critical=namespace in self._critical) + with namespace_scope(namespace): + for declaration in builder.declarations: + declaration.replay(root) + + 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. + + **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. + """ + 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: + 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 + 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. + + 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." + ) + + refuse_constructed_components(builder, namespace) diff --git a/src/blueprint/agents/app_builder.py b/src/blueprint/agents/app_builder.py index 73bc9e91..f06126b7 100644 --- a/src/blueprint/agents/app_builder.py +++ b/src/blueprint/agents/app_builder.py @@ -1,36 +1,90 @@ """Generic FastAPI application setup and configuration.""" +import asyncio +import copy import logging -from collections.abc import AsyncIterator +import signal +from collections.abc import AsyncIterator, Callable, Mapping from contextlib import asynccontextmanager +from dataclasses import dataclass from typing import TYPE_CHECKING, Any, TypeVar from fastapi import FastAPI +from fastapi.routing import APIRoute if TYPE_CHECKING: 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, + construction_scope, + current_namespace, + namespace_of, + 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, NamedConnectionsHealthChecker from .io.api.eventing.dapr import DaprEventing from .io.api.eventing.nats import NatsEventing from .io.api.eventing.sessions_bus import SessionsBus from .io.api.utilities.root import RootApi from .io.api.utilities.cache import CacheManagementApi from .clients.io.dapr_client import DaprClient -from .clients.io.nats_client import NATSClient +from .clients.io.io_client_base import TOPIC_TRANSPORTS +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 from .services.eventing.event_processing_service import EventProcessingService 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 .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 .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. + +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. +""" + +_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) @@ -40,6 +94,125 @@ 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: + """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_*`` 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] + + @property + def is_built(self) -> bool: + """Whether ``target`` is a component that already exists. + + 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._restore_declaration_order`` evens out, and + what a group refuses outright. + """ + return isinstance(self.target, Component) + + def replay(self, builder: "AppBuilder") -> None: + """Re-issue this call on ``builder``, which records it again. + + 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 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 record this call on. + """ + 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) + + +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. @@ -54,169 +227,826 @@ 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 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 + and what keeps its ``with_*`` logging formatted as it always was. """ - def __init__(self, config: Config) -> None: - 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() - self._eventing_component: DaprEventing | NatsEventing | None = None + # 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. + 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 # 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. + 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] = [] + # 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 + # ------------------------------------------------------------------ + + def _use_config(self, config: Config) -> Config: + """Adopt ``config`` as this application's configuration and configure logging from it. + + 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: + config: The configuration to adopt. + + Returns: + The same configuration, so callers can chain. + """ + config.configure_logging() + self._config = config + return config + + def _resolve_config(self, config: Config | None) -> Config: + """Settle which configuration ``build()`` uses, and adopt it if it is new. + + Args: + config: What was passed to ``build()``, or ``None``. + + Returns: + 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 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. + """ + if config is not None and self._config is not None: + raise ValueError( + "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 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 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 self._config is not None + + @property + def is_built(self) -> bool: + """Whether ``build()`` has already run. + + 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 + + def _require_config(self) -> Config: + """Return the configuration, which exists only from ``build()`` onwards. + + Raises: + RuntimeError: if called before ``build()`` has settled which configuration to use. + Internal: every caller runs during or after the wiring pass. + """ + if self._config is None: + raise RuntimeError("The application's configuration is not settled until build() runs.") + return self._config # ------------------------------------------------------------------ # 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 - return self + def host_agent(self, namespace: str, *, critical: bool = True) -> "AppBuilder": + """Record that this process serves ``namespace``, whether or not it declares anything. - 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 - return self + 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. - 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 + 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: + 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. + + Raises: + ValueError: if ``namespace`` is not a legal namespace, is the root, or is already + hosted by this process. + """ + 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) + if critical: + self._critical_namespaces.append(agent) + logger.info("Hosting agent namespace '%s'%s", agent, "" if critical else " (not critical)") 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 + @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. + + 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. + + 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) + + @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 :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 | Callable[[], HandlerT], *, name: str | None = None, **kwargs: Any + ) -> "AppBuilder": + """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, 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__}") + return self._record("handler", handler, kwargs, name=name, method="with_handler") + + def with_service( + self, service: type[ServiceT] | ServiceT | Callable[[], ServiceT], *, name: str | None = None, **kwargs: Any + ) -> "AppBuilder": + """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 | AgentBuilder | Callable[[], AgentT], *, name: str | None = None, **kwargs: Any + ) -> "AppBuilder": + """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 | Callable[[], SchedulerT], *, name: str | None = None, **kwargs: Any + ) -> "AppBuilder": + """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//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") + + def with_rest_api( + self, api: type[RestApiT] | RestApiT | Callable[[], RestApiT], *, name: str | None = None, **kwargs: Any + ) -> "AppBuilder": + """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 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. + """ + 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 - 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 _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 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. + + 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. + + **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. + + Returns: + The component instance, already in the registry. + """ + if declaration.is_built: + instance = declaration.target + elif isinstance(declaration.target, AgentBuilder): + with construction_scope(declaration.namespace): + 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) + + 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 = declaration.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). + + **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. + 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: + 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 + # 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 with_cache(self, enabled: bool = True, enable_locking: bool = True) -> "AppBuilder": - """Enable persistent caching using DiskCache. + 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: - enabled: Whether to enable caching (default: True) - enable_locking: Enable file-based locking for multi-deployment safety (default: True). + declaration: A ``kind="cache"`` declaration; its ``name`` is the cache's name. + config: The application's configuration, scoped to the declaring agent here. """ - 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] + 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) + if name == DEFAULT_CACHE_NAME and not namespace: logger.info( "Registered %s with cache_dir=%s (locking=%s)", type(cache_service).__name__, - cache_config.cache_dir, + config.get_cache_config().cache_dir, enable_locking, ) else: - logger.info("Caching disabled") - return self + 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. - Must be called after build() has created the ActuatorApi, or the checker - will be added during build() automatically. Prefer calling before build(). + 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. + + 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. 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 + 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. + """ + built: list[tuple[Declaration, Any]] = [] + for entry in self._declarations: + if entry.kind not in _UNCONSTRUCTED_KINDS: + built.append((entry, self._construct(entry, config))) + + self._restore_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 _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 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. Before 0.9 every + ``with_handler`` call registered at once, so the order was the call order. + + 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. + """ + 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. This method: + 0. Settles the configuration and constructs every recorded declaration 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 + + 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. + 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." + ) + # 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) + + # 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] - # 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() - if event_bus_type == "dapr": - DaprClient() # auto-registers - self._eventing_component = DaprEventing() - elif event_bus_type == "nats": - NATSClient() # auto-registers - 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." + # 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 internal services (auto-register) + # 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(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 + ) + # 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) + + # 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 - # API calling RestApiBase._process_resource() directly. + # requests to -- whether via an eventing endpoint (see step 3) or a REST + # 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() - if registry.get_io_clients(): - EventPublishingService() - - # 4. 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) - if hasattr(self, "_custom_health_checkers"): - health_providers.update(self._custom_health_checkers) + # 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. 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 + # 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]), builtin=True) + 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 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), 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( + HealthCheckEntry( + name=f"{client.base_name}:connections", + namespace=client.namespace, + checker=NamedConnectionsHealthChecker(client), + affects_consumption=False, + builtin=True, + ) + for client in self._sourced_nats_clients + ) + health_providers.extend(self._health_checkers) 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", ""), - 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(), # Configurable so a consumer can disable a route (docs_url = "@none" in # settings.toml) before FastAPI.__init__ ever registers it (#191) rather @@ -226,134 +1056,667 @@ def build(self) -> FastAPI: # to the root value, so a scoped override here would be silently ignored. # Note FastAPI itself only registers docs_url/redoc_url when openapi_url # is also set — disabling openapi_url disables all three. - docs_url=self._config.get("docs_url", "/docs"), - redoc_url=self._config.get("redoc_url", "/redoc"), - openapi_url=self._config.get("openapi_url", "/openapi.json"), + docs_url=resolved_config.get("docs_url", "/docs"), + redoc_url=resolved_config.get("redoc_url", "/redoc"), + openapi_url=resolved_config.get("openapi_url", "/openapi.json"), ) self._build_rest_endpoints(app, registry) return app + def _wire_transport( + 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. + + 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. + 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 + 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": + 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: + self._sourced_nats_clients.append(client) + 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": + 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)) + 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 " + "('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. + + 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, 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 + 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. + + 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._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") + 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 # 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. - app.include_router(rest_api.router, prefix="/api") + # 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") - if self._eventing_component is not None: - app.include_router(self._eventing_component.router) + 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="") - if registry.has_cache(): - app.include_router(CacheManagementApi().router, prefix="/api", tags=["cache"]) + 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 + # 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"]) + 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 _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. + + ``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. + + 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. + 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: + 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): + 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 # ------------------------------------------------------------------ + 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. + + **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. + 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, 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 + 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, + ) + 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 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. + + 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. + + **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", + namespace or ROOT_LABEL, + "the root" if not namespace else "critical", + error, + ) + 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. + + 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() + # 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: + """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. + + ``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. + + 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. + """ + 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") + 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 _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. + + 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) + # 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 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") + self._warn_if_development(resolved_config) + startup_retry_interval = self._startup_retry_interval(resolved_config) - # 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 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) + # 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 - for rest_api in registry.get_rest_apis(): - 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 + # 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): + 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 component (Dapr / NATS endpoint) - if self._eventing_component is not None: - try: - await self._eventing_component.on_startup() - logger.info("Eventing component startup completed") - except Exception as e: - logger.error("Eventing component startup failed: %s", e, exc_info=True) - raise + # Eventing components (one Dapr / NATS endpoint per agent that consumes) + for eventing_component in self._eventing_components: + # 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: - 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__) + 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 @@ -361,6 +1724,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: @@ -373,11 +1737,19 @@ 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) + 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: @@ -385,7 +1757,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: @@ -417,7 +1789,25 @@ 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() + + # 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() + + # 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/clients/ai/openai_client.py b/src/blueprint/agents/clients/ai/openai_client.py index ce124c3d..6d3f339e 100644 --- a/src/blueprint/agents/clients/ai/openai_client.py +++ b/src/blueprint/agents/clients/ai/openai_client.py @@ -1,14 +1,14 @@ """OpenAI client implementation.""" import logging -from collections.abc import Awaitable, Callable 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 +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: str, callback: 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: @@ -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 5048648e..ec461106 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 @@ -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).""" @@ -38,7 +42,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, 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: @@ -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/client_base.py b/src/blueprint/agents/clients/client_base.py index c6507dda..78d1fd2d 100644 --- a/src/blueprint/agents/clients/client_base.py +++ b/src/blueprint/agents/clients/client_base.py @@ -5,12 +5,25 @@ 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: 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). @@ -26,9 +39,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: @@ -68,8 +88,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, 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 + 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..5797d374 100644 --- a/src/blueprint/agents/clients/io/dapr_client.py +++ b/src/blueprint/agents/clients/io/dapr_client.py @@ -1,25 +1,91 @@ """Dapr client implementation for eventing.""" +import asyncio +import contextlib import json import logging -from collections.abc import Awaitable, Callable from typing import Any import httpx +from ...component.namespace import ROOT_LABEL, ROOT_NAMESPACE 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__) -# 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.""" + """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. + + 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 + failure; ``-1`` = indefinite, ``0`` = single attempt. + ``event_client_retry_delay`` (float, default 5.0): seconds between retries. + """ + + def __init__(self, namespace: str = ROOT_NAMESPACE) -> None: + super().__init__(namespace=namespace) + self._topic_callbacks: dict[str, DeliveryCallback] = {} + 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, DeliveryCallback]) -> 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 +94,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, @@ -60,24 +126,29 @@ 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.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 + # ------------------------------------------------------------------ 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 +164,47 @@ 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: + """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( + "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.""" + 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/io_client_base.py b/src/blueprint/agents/clients/io/io_client_base.py index 484c0323..9f08586a 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,4 +13,191 @@ 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) + 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") +"""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. +""" + + +_SUBJECT_UNUSABLE = re.compile(r"[*>\s]") +"""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. + + 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 0c15680c..2a97919a 100644 --- a/src/blueprint/agents/clients/io/nats_client.py +++ b/src/blueprint/agents/clients/io/nats_client.py @@ -1,114 +1,2400 @@ """NATS client implementation for eventing.""" +import asyncio +import contextlib +import contextvars +import functools +import importlib.util import json import logging +import re +from collections.abc import AsyncIterator, Awaitable, Callable, Iterable +from dataclasses import dataclass, field +from functools import cached_property +from pathlib import Path from typing import Any -from collections.abc import Awaitable, Callable +from urllib.parse import urlsplit, urlunsplit 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.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 +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, describe_validation_errors, disposition_for from ...models.events import CloudEvent -from .io_client_base import IOClientBase +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, DeliveryAttempt, JetStreamBinding, mark_connection, mark_delivery +from .nats_run_pool import PairRuns, Release, RunLimit, RunPool 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. +""" + + +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 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 + 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. + """ + + +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. + +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). +""" + + +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``.""" + +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``).""" + +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.""" + +_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.""" + +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. + + 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}")) + + +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." + ) + + +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. + +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. +""" + + +@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. + """ + + # 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 + + +@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), ``"failed"`` (a tenancy fault no retry fixes; + ``last_error`` says which, D23) 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. + + 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.""" + # 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 + 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 + """We are closing this link ourselves: its disconnect is not a lost broker.""" + + +@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 + 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 + subscriptions: list[Any] = field(default_factory=list) + subscriptions_ready: bool = False + 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) + 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) + 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 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 + """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.""" + 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() + + def slots_for(self, topic: str) -> asyncio.Semaphore: + """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: + """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.""" + """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 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 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + 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 + 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, unset = server default): seconds the broker waits for an + acknowledgement before redelivering. Must exceed p99 handler duration. + ``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. + ``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. + ``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 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 + ~~~~~~~~~~~~~~~ + 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. 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. + + 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. ``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._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._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() + 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 + 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]] = {} + self._declared: dict[str, DeliveryCallback] = {} + self._claimed: frozenset[str] = frozenset() + self._default_pairs = 0 + 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() + + # ------------------------------------------------------------------ + # 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) -> DeterministicTransportError | None: + return self._link.jetstream_mismatch + + @_jetstream_mismatch.setter + def _jetstream_mismatch(self, value: DeterministicTransportError | 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 + # ------------------------------------------------------------------ + + @property + 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()``.""" + return self._queue_group + + @property + def inflight_handlers(self) -> int: + """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 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 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) + + 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 binding.failed: + state = "failed" + 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 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)) + 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.""" + 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 + # ------------------------------------------------------------------ + + 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._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 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() + 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) + # 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(default_topics)) + self._tuning = self._resolve_consumer_tuning(list(default_topics)) + self._subscriptions_managed = True + 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( + "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() + 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 + + 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) + 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 self._claimed] + if unknown: + raise ValueError( + 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) + served.update(jetstream.subjects) + if self._named: + self._refuse_result_publishing() + logger.info( + "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(self._claimed - served), + len(unclaimed), + ) + # 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). + + 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: + 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 -- 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 + 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 + 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. + 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) + binding.last_error = self._describe_error(binding.link, exc) + binding.permission_denied = bool(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). + 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." + ) + 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, + binding.link.name, + attempt, + delay, + binding.last_error, + ) + 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: + 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: + if link.closing or self._closing: + return + 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: + # 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. 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 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) + + 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" -- + # 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 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( + 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) + + # ------------------------------------------------------------------ + # 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._claimed] + if unknown: + logger.error( + "Agent '%s': connection '%s' skipped -- its binding serves %s, which the source does not claim", + 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 + 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") + 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: + # 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).""" + + 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 + binding.bound = 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(): + return + 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). + + 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 + 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 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 + return resolve_root_queue_group(self.config.get) + + # ------------------------------------------------------------------ + # 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) + # ------------------------------------------------------------------ + + 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. + + **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 configured value is not a number, is zero, or is a negative value + other than ``-1``. + """ + 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_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_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( + "'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() + 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 " + "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: + 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 + + 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. 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 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. + """ + 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: + """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_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 _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``. + + 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. + """ + 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). + + 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: + return None + return self._read_int(key, 0) + + 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 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". + + **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. + """ + 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 + # ------------------------------------------------------------------ + + async def on_startup(self) -> None: + """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 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) + 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_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. + + 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. + + 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. + """ + 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 url + + 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 + + async def connect(self) -> None: + """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() + 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) + try: + self._nats_client = await nats.connect( + self._nats_url, + name=self._connection_name or None, + 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, + 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. + 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() + self._publish_subjects = self._resolve_publish_subjects() + if self._use_jetstream: + self._js = self._nats_client.jetstream() + await self._require_jetstream(nats_url) + self._log_connected("with JetStream", nats_url) + else: + self._log_connected("(Core NATS)", nats_url) + except DeterministicTransportError: + raise + except Exception as 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 + + @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: + 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. + + ``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 -- 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 " + "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." + ) + 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; 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)) + task.add_done_callback(self._on_fatal_handler_done) - def __init__(self) -> None: - super().__init__() - self._nats_client: NatsClient | None = None - self._js: JetStreamContext | None = None - self._use_jetstream: bool = False - self._subscriptions: list[Any] = [] + 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(), + ) - 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 pause_consumption(self) -> None: + """Drain this agent's subscriptions so its events redeliver elsewhere (C4). - async def connect(self) -> None: - """Connect to NATS server.""" - if self._nats_client is not None and not self._nats_client.is_closed: + Drained rather than unsubscribed, for the same reason shutdown drains: a drain stops + 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. + """ + # 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 + self._subscriptions_ready = False + 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", + self.namespace or ROOT_LABEL, + ) - nats_url = self.config.get("nats_url", "nats://localhost:4222") + async def resume_consumption(self) -> None: + """Re-subscribe this agent's topics after its health checks pass again. + + **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 + self._consumption_paused = False + if not self._subscriptions_managed: + return + # Each named connection re-binds in its own loop, over its still-open link. + 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 + # 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: - self._nats_client = await nats.connect( - nats_url, - 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, + await self._subscribe_all() + except Exception as exc: + await self._drop_subscriptions() + self._consumption_paused = True + 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), ) - self._client = self._nats_client - self._use_jetstream = self.config.get("nats_use_jetstream", False) - if self._use_jetstream: - try: - self._js = self._nats_client.jetstream() - logger.info("Connected to NATS server with JetStream at %s", nats_url) - 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) - except Exception as e: - logger.error("Failed to connect to NATS: %s", str(e)) - raise + 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 + + 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: - """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 + 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): + await self._retry_task + await self._cancel_resume_retry() + 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() + + 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 + 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: - for sub in self._subscriptions: - await sub.unsubscribe() - self._subscriptions.clear() + 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 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, 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. + """ + binding = binding or self._binding + for sub in binding.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) + binding.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 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: + # 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 - 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, binding: _Binding | None = None) -> None: + """Give handlers that are still running a bounded chance to finish.""" + 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, binding.inflight) + try: + 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", + binding.inflight, + ) - self._subscriptions.append(sub) + def _enter_handler(self) -> None: + self._binding.enter_run() - except Exception as e: - logger.error("Failed to subscribe to topic '%s': %s", topic, str(e)) - raise + def _exit_handler(self) -> None: + self._binding.exit_run() + + # ------------------------------------------------------------------ + # Publish + # ------------------------------------------------------------------ async def publish(self, topic: str, event: CloudEvent[Any], routing_key: str | None = None) -> None: """Publish a CloudEvent to a topic. @@ -116,14 +2402,20 @@ 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. + + 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: 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: @@ -134,10 +2426,1061 @@ 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. + + **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 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: + 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") + 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}") + + # ------------------------------------------------------------------ + # 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: + self._link.permission_errors.clear() + try: + await self._connect_and_subscribe() + if self._consumption_paused: + return + self._subscriptions_ready = True + logger.info("NATSClient connected and subscribed successfully") + return + 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)) + 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 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( + "Agent '%s' permanently failed to connect to NATS after exhausting retries: %s", + 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() + # Clean up any partial subscriptions from a previous failed attempt + 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. + 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() + + 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. 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 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 + # ------------------------------------------------------------------ + + 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) + # 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: + """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 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") + wanted = self._stream_subjects() + + try: + info = await js.stream_info(stream) + except NotFoundError: + 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 -- + # which used to be reported as "consumers will fail to bind" when they bind fine. + existing = set(info.config.subjects or []) + missing = {subject for subject in wanted if not any(subject_is_covered_by(subject, pattern) for pattern in 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 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); " + "consumers filtering those subjects will fail to bind", + stream, + sorted(missing), + 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. + + ``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 %s, max_ack_pending %s, max_deliver %s", + durable, + stream, + topic, + desired.deliver_group, + # 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. 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 + 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). " + "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, + "; ".join(drift), + ) + return info.config + + @staticmethod + 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}" + # 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) + ] + + # ------------------------------------------------------------------ + # Internal — per-topic subscription + # ------------------------------------------------------------------ + + async def _subscribe_one(self, topic: str, callback: DeliveryCallback, binding: _Binding | None = None) -> None: + binding = binding or self._binding + client = await self.client + message_handler = self._message_handler(binding, topic, topic, callback) + + 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) + # The broker's value, not nats_ack_wait: an existing consumer keeps its own. + 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, + consumer=durable_name, + cb=message_handler, + manual_ack=True, + ) + 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) + 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) + + binding.subscriptions.append(sub) + + except Exception as e: + 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. + TenancyError: the broker refused the subscription to the deliver subject (D23). + """ + 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) + # 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 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 + # 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()] + if refused: + with contextlib.suppress(Exception): + await sub.unsubscribe() + 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)", + 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: + 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 + # 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, delayed=False) + 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) + return + release = await self._acquire_run(binding, slot_key) + binding.enter_run() + 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 + + @staticmethod + 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 + 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. + + 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: + return False + 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 + 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. + + 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 + 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 + # ------------------------------------------------------------------ + + 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. + + With ``nats_handler_timeout`` set, a run that reaches the limit is cancelled and nak'd for + 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. + """ + 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, 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) + _CURRENT_BINDING.set(binding) + if not await self._accepted(msg, topic, cloud_event, binding): + return + + 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 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 + 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() + # 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: + """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, 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) + 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( + "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, 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._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) + binding.heartbeats.add(heartbeat) + heartbeat.add_done_callback(binding.heartbeats.discard) + 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 + # ------------------------------------------------------------------ + + async def _settle( + 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). + + 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. + + 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): + return + + try: + if disposition is DeliveryDisposition.ACK: + await msg.ack() + elif disposition is DeliveryDisposition.NAK and not self._deliveries_exhausted(msg, binding): + 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() + 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, 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 + ``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._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 None + return 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, 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 + 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. + """ + binding = binding or self._binding + 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" + + 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.", + 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: + # 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( + "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 + + 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 "", + topic, + subject, + delivered if delivered is not None else "an unknown number of", + 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 + # ------------------------------------------------------------------ + + 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_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: + 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) + # 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: + # 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._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", + 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/src/blueprint/agents/clients/io/nats_connections.py b/src/blueprint/agents/clients/io/nats_connections.py new file mode 100644 index 00000000..98acc0fb --- /dev/null +++ b/src/blueprint/agents/clients/io/nats_connections.py @@ -0,0 +1,287 @@ +"""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. 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 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.""" + + 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, 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): + 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. + + **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 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()``.""" + ... + + 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: + """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) + + +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/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/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/component.py b/src/blueprint/agents/component/component.py index 89c6cc0e..ecac3ba2 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 @@ -19,34 +20,60 @@ 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_LABEL, ROOT_NAMESPACE, current_namespace, qualified_component_name, validate_namespace if TYPE_CHECKING: from .registry import Registry 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__(). @@ -76,8 +103,34 @@ 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. 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 + 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 +138,20 @@ def __init__(self, should_register: bool = True) -> None: Component.init_registry(Registry(Component)) - self._name = camel_to_snake(self.__class__.__name__) + # 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()) + # 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._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) @@ -96,26 +162,129 @@ 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. 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 + 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 + 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: + """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.""" - 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. + + **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: + return registry + return registry.for_namespace(self._namespace) @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 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.""" - 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: @@ -164,6 +333,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``, @@ -216,6 +391,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) @@ -231,6 +407,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/component/namespace.py b/src/blueprint/agents/component/namespace.py new file mode 100644 index 00000000..2b213222 --- /dev/null +++ b/src/blueprint/agents/component/namespace.py @@ -0,0 +1,325 @@ +"""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 collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar +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`.""" + +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`.""" + + +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." + ) + + 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 + + +_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) + + +@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. + + 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. + + 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}" + + +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, 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 + 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. + + 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) + + +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/component/registry.py b/src/blueprint/agents/component/registry.py index 206376e0..3bc34f6b 100644 --- a/src/blueprint/agents/component/registry.py +++ b/src/blueprint/agents/component/registry.py @@ -3,9 +3,32 @@ 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 collections.abc import Sequence +from concurrent.futures import ThreadPoolExecutor +from copy import copy from typing import Any, TypeVar from ..agent.agent_runtime import AgentRuntime @@ -19,6 +42,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 +51,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 +83,15 @@ 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[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] = {} - logger.info("ComponentRegistry initialized") + logger.info("Registry 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,391 @@ 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 = {} + 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.""" + 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, 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. + + **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``. + + 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. + + **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) + 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): + return None + return found + @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. + """ + + # 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( + 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. + """ + + 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) + self._executors.clear() + + 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. + + **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 + + 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 + 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. + namespace: The agent it belongs to. Omitted means this object's agent. + """ + + agent = self._cache_owner(namespace) + key = (agent, name) + if key in self._caches: + logger.warning( + "Cache '%s' of agent '%s' is already registered as %s and is being replaced by %s", + name, + agent or ROOT_LABEL, + 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 + + def get_cache(self, name: str = DEFAULT_CACHE_NAME, *, namespace: str | None = None) -> CacheService: + """Get the cache one agent registered under ``name``. + + 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 that agent registered under that name. + + Raises: + ValueError: If that agent registered no cache under ``name``. + """ + + agent = self._cache_owner(namespace) + cache = self._caches.get((agent, name)) + if cache is None: + 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 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. + + 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. + """ + + agent = self._cache_owner(namespace) + return {name: cache for (owner, name), cache in self._caches.items() if owner == agent} + + def cache_entries(self) -> list[tuple[str, str, CacheService]]: + """Return every cache in the process as ``(namespace, name, cache)``, in registration order. + + 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. + """ + + 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: - """Get the registered cache service. + """This agent's 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` for this object's agent Raises: - ValueError: If no cache service is registered + ValueError: If no cache service is registered for it """ - if self._cache_service is None: - raise ValueError("No cache service registered") - return self._cache_service + if not self.get_all_caches(): + 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 def cache_service(self, cache_service: CacheService) -> None: - """Register a cache service. + """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 """ - 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. @@ -122,114 +495,216 @@ 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: - raise ValueError(f"Component with name {name} already exists") + existing = type(self._components[name]).__name__ + 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 " + "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 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 + + 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) - 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 = 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 - 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 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).""" + self._refuse_on_a_view("clear the components") logger.info("Clearing all registered components") self._components.clear() @@ -240,22 +715,32 @@ 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() - if self._cache_service is not None: - self._cache_service.clear() - self._cache_service = None + self.shutdown_executors() + 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) -> bool: - """Check if a cache service is registered. + 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 cache service is registered, False otherwise + True if that agent has a cache under that name, False otherwise """ - return self._cache_service is not None + return (self._cache_owner(namespace), 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 +750,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, namespace: str | None = None) -> list[EventHandlerBase]: + """Get all registered handlers. - def get_event_handler(self) -> 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 +771,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 +787,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. + + Args: + namespace: Restrict to this agent; ``None`` (the default) is every namespace. + """ - return self.get_component_names_by_type(AgentRuntime) + 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 +811,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. - return self.get_component_names_by_type(RestApiBase) + Args: + namespace: Restrict to this agent; ``None`` (the default) is every namespace. + """ - def get_rest_api(self, name_or_class: str | type[RestApiBase]) -> RestApiBase: + return self.get_component_names_by_type(RestApiBase, namespace) + + 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 +836,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 +857,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 +873,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, namespace: str | None = None) -> list[ServiceBase]: + """Get all registered business services. - def get_services(self) -> 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 +894,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 +910,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. + """ - def get_client(self, name_or_class: str | type[ClientBase]) -> ClientBase: + return self.get_components_by_type(SchedulerBase, namespace) + + 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 +935,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 +951,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 +967,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/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 04da0a05..54da72d1 100644 --- a/src/blueprint/agents/config/config.py +++ b/src/blueprint/agents/config/config.py @@ -2,6 +2,10 @@ import json import logging +import os +import re +import tomllib +from copy import copy from pathlib import Path from typing import Any @@ -28,6 +32,201 @@ 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. +""" + + +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. + +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", + "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", + "operator_routes_enabled", + "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. + +One process binds one port, loads one environment section, reads its environment through one +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. + +``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. +""" + + +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. + +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. + +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. +""" + + +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.""" @@ -46,24 +245,85 @@ 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_roots: dict[str, Path] = {} self._agent_scope = agent_scope - - # First pass: load config to get app_environment + 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). + 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. + 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. + # + # 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) + # 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) + 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", + ) - # Validators differ when scoped: app_name/app_port must live under the scope. + # 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 + # 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: @@ -73,49 +333,647 @@ def __init__( Validator("app_environment", must_exist=True, default="development"), ] - # Second pass: load with the correct environment - self.settings = Dynaconf( + # 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, + 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() + # 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() + 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", "") + 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. + """ + + 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 + + self._agent_namespaces.add(namespace.lower()) + view = copy(self) + view._agent_scope = namespace + 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 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. + + 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_namespaces.add(namespace.lower()) + 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.""" + 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 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`` -- + ``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. + 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 + 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." + ) + + self._agent_namespaces.add(namespace.lower()) + 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 () - # Initialize logging after config is fully loaded - self._initialize_logging() + 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) + self._refuse_self_scoped_fragment(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 + 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. + """ + 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; 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: + documents.append(tomllib.loads(path.read_text(encoding="utf-8"))) + except (OSError, tomllib.TOMLDecodeError): + continue + return environment_section_names(documents) + + @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], *, 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 -- except for a secrets file, whose values are + never logged, and the process's then neither. + """ + refused = AGENT_REFUSED_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)) + 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 (%s) is ignored and %s. Remove it from the agent's settings file, or set it in the group's.", + namespace, + key, + path, + "" if secret else repr(value), + used, + ) + 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`. + + **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}" + existing = spelled.get(str(key).lower()) + if existing is None: + target[key] = value + spelled[str(key).lower()] = key + added.append(path) + continue + 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[existing] = 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. + + 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". + + 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 a view is asked for a namespace other than its own. + """ + if self._is_view: + 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) + # 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(): + 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) @@ -201,20 +1059,89 @@ 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. + + **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}") + scoped = self._settings.get(f"{self._agent_scope}.{key}") if scoped is not None: return scoped - return self.settings.get(key, default) + 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. + + 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, or if it is bare and names an agent. + """ + head = key.split(".", 1)[0] + 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 " + 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.""" + """Get a configuration value, scope-aware when ``agent_scope`` is set. + + Raises: + 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 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 " + "moving the agent to another group then breaks it. Framework code reads these from the " + "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 @@ -344,6 +1271,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( @@ -376,14 +1304,42 @@ 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.get("otel_service_name", self.get("app_name", "agent-service")), + otel_service_name=self._resolve_service_name(), + token_metrics_enabled=self.get("token_metrics_enabled", True), 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. @@ -433,6 +1389,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: @@ -477,7 +1434,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')}") @@ -489,17 +1446,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/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/src/blueprint/agents/deployment.py b/src/blueprint/agents/deployment.py new file mode 100644 index 00000000..fe7f45c2 --- /dev/null +++ b/src/blueprint/agents/deployment.py @@ -0,0 +1,85 @@ +"""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.""" + + +_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 runs as, or :data:`UNGROUPED_LABEL`. + + 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). + """ + 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: + """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/entrypoint.py b/src/blueprint/agents/entrypoint.py new file mode 100644 index 00000000..009a3ecc --- /dev/null +++ b/src/blueprint/agents/entrypoint.py @@ -0,0 +1,120 @@ +"""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 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 +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 .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__) + + +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) + app = AgentGroup.resolve(config, environ=environ).assemble(config) + 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. + + 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..52a9d5f6 --- /dev/null +++ b/src/blueprint/agents/group_config.py @@ -0,0 +1,542 @@ +"""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 collections.abc import Mapping +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" + +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" +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. + + 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 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. + + 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 ``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, + 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 + 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 + its probes while a queue silently backed up. ``False`` is the deliberate choice to + run the rest without it. + """ + + name: str + module: str + root: Path + 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. + 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 + ``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, ...] + image_root: Path = field(default_factory=Path.cwd) + + @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. + """ + 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 + + declared = cls._read_group_file(env, root) + name, agent_names, critical_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), image_root=root.resolve()) + logger.info( + "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), + ) + 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; 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]: + """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.") + + 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 + + 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, 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 + 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, 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): + raise GroupConfigError( + f"Agent '{agent_name}' in {path} has no 'module', so its declaration cannot be found. Write it as " + 'module = "pkg.mod:registration".' + ) + 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 " + 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." + ) + 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 + + # ------------------------------------------------------------------ + # Overriding and validating + # ------------------------------------------------------------------ + + @staticmethod + 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 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()] + + 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 = _names("agents") + critical = set(_names("critical_agents")) + sources = {"name": "file", "agents": "file", "critical_agents": "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"] = DEFAULT_GROUP_NAME, "default" + + 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 + 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 + 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 + 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: " + 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=entry.module, root=entry.root, critical=critical)) + return specs diff --git a/src/blueprint/agents/handler/event_handler_base.py b/src/blueprint/agents/handler/event_handler_base.py index 26b0cc2d..a02f69fe 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. """ @@ -43,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 @@ -69,6 +71,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. @@ -161,6 +174,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 e0fdfdba..8f66a4bb 100644 --- a/src/blueprint/agents/handler/handler_chain.py +++ b/src/blueprint/agents/handler/handler_chain.py @@ -1,15 +1,271 @@ """Handler chain for executing event handlers in priority order.""" +import asyncio import logging +import re +import time +from dataclasses import dataclass +from collections.abc import Callable from typing import Any 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 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. +""" + +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.""" + +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. + +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: + """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 + + +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. @@ -18,14 +274,92 @@ 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. 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 + (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. + + 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``. + + 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: - """No startup actions required.""" + """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 for namespace '%s' with a %d second window", + self.namespace or ROOT_LABEL, + self._policy.ttl, + ) + self._warn_without_a_heartbeat() + + 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.""" @@ -39,31 +373,320 @@ 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 """ - handlers = sorted(self.registry.get_event_handler()) + # 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 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) + return None + + try: + return await self._dispatch(event, context) + 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. + await self.release(event, context) + raise + + # ------------------------------------------------------------------ + # 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: + """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)) + span.set_attribute("agent", self.namespace or ROOT_LABEL) - logger.debug("Processing event through %d handlers", len(handlers)) + 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) + 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) 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 - logger.warning("No handler processed event '%s'", 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 + + # ------------------------------------------------------------------ + # 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) + # ------------------------------------------------------------------ + + def _warn_without_a_heartbeat(self) -> None: + """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. + + 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 + is already in the cache, meaning some earlier delivery already ran the chain. + """ + if not policy.enabled: + return True + + key = self._idempotency_key(event, context) + if key is None: + 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. 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, + ttl=policy.ttl, + ) + if claimed: + context[CLAIMED_CONTEXT_KEY] = True + return claimed + + 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 + 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. + + 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. + + 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 context.pop(CLAIMED_CONTEXT_KEY, False): + return + + key = self._idempotency_key(event, context) + if key is None: + return + + # 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 + 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 + ``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. + + 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() + 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 + 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: + """Read and validate the dedup settings; see :func:`resolve_idempotency_policy`. + + Raises: + ValueError: as :func:`resolve_idempotency_policy` does. + """ + return resolve_idempotency_policy(self.config.get, has_cache=self.registry.has_cache()) diff --git a/src/blueprint/agents/handler/sessions_job_handler.py b/src/blueprint/agents/handler/sessions_job_handler.py index 5a109175..90258676 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).""" @@ -141,9 +189,36 @@ 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 -- 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: """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/actuators/actuator_api.py b/src/blueprint/agents/io/api/actuators/actuator_api.py index 520b5934..987d3ba7 100644 --- a/src/blueprint/agents/io/api/actuators/actuator_api.py +++ b/src/blueprint/agents/io/api/actuators/actuator_api.py @@ -3,51 +3,206 @@ 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 parse_qsl, urlencode, urlsplit, urlunsplit import httpx 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_LABEL, 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 from ..rest_api_base import RestApiBase -from .health.health_base import HealthCheckerBase +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__) +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. +""" + +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.""" + 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._pending_providers: dict[str, HealthCheckerBase] = {} + self._health_entries: list[HealthCheckEntry] = [] + 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 add_health_providers(self, providers: dict[str, HealthCheckerBase]) -> None: - """Register health check providers. + 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: - providers: Mapping of component name to HealthCheckerBase instance + 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, ...]: + """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. + + **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. **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, 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 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 " + 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) + """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() + 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: @@ -102,7 +257,20 @@ 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'. + 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(), @@ -129,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", @@ -146,19 +322,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") + + # 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. + # 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} + + 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=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, ) @RestApiBase.get("/status/llm", response_model=LLMStatus, tags=["Status"], summary="Returns AI provider configuration and diagnostics.") @@ -226,30 +442,142 @@ 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"), ) 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. + + 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. + + 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, bool): + return value + if isinstance(value, dict): + 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 self._is_secret_key(key): + return CONFIG_MASK + if isinstance(value, str): + 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() + 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: + """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. + """ + 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: + # 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}:{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/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/__init__.py b/src/blueprint/agents/io/api/actuators/health/__init__.py index f4563bb5..0ad3c31b 100644 --- a/src/blueprint/agents/io/api/actuators/health/__init__.py +++ b/src/blueprint/agents/io/api/actuators/health/__init__.py @@ -1,13 +1,16 @@ """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 .named_connections_health import NamedConnectionsHealthChecker from .sessions_health import SessionsServiceHealthChecker __all__ = [ + "HealthCheckEntry", "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 38e54f19..09b37a21 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 @@ -16,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") ``` """ @@ -25,9 +27,56 @@ 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. """ 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. + 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: + """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..b0a37d3c 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,15 @@ 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 .....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 @@ -37,30 +42,56 @@ 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 + # 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 if self._grouped else None, + 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._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.""" @@ -73,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() @@ -98,51 +135,71 @@ 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. + + 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.""" - if not self._health_check_provider: - logger.debug("No health check providers configured") - return + """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; aggregating supervisor state only") try: async with self._lock: 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): - logger.warning( - "Health check failed for %s: %s", - name, - result, - ) - components[name] = ComponentHealth( + # 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. + 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}", ) else: - components[name] = result + 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, consumption_status, namespaces = self._aggregate_by_agent(components) + 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( status=overall_status, components=components, + policy=self._policy.value if self._grouped else None, + namespaces=namespaces if self._grouped else None, ) self._last_update = datetime.now() @@ -152,9 +209,79 @@ 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: + # 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) + 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, 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 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", + # 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() + } + 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/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..02b1a4f0 --- /dev/null +++ b/src/blueprint/agents/io/api/actuators/health/namespace_supervisor.py @@ -0,0 +1,245 @@ +"""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 typing import Protocol + +from opentelemetry.metrics import CallbackOptions, Observation + +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. + +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) + + @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" + + 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._consumers(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._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 _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. + """ + 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/actuators/health/readiness_policy.py b/src/blueprint/agents/io/api/actuators/health/readiness_policy.py new file mode 100644 index 00000000..a4d63c06 --- /dev/null +++ b/src/blueprint/agents/io/api/actuators/health/readiness_policy.py @@ -0,0 +1,113 @@ +"""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. + +**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. +""" + +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], 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 + + 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/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/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 d7511b98..845a733a 100644 --- a/src/blueprint/agents/io/api/eventing/dapr.py +++ b/src/blueprint/agents/io/api/eventing/dapr.py @@ -1,114 +1,430 @@ """Generic Dapr pub/sub endpoints for the agent service (framework-level).""" import logging +from collections.abc import Callable, Coroutine, Iterable, Mapping 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.client_base import DeliveryCallback from ....clients.io.dapr_client import DaprClient -from ....models import ProcessingStatus +from ....component.namespace import ROOT_LABEL, ROOT_NAMESPACE, namespace_of +from ....models.errors import ( + DeliveryDisposition, + HandlerError, + combined_disposition, + describe_validation_errors, + 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 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__) +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() + # 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: + return await handle(request) + except RequestValidationError as 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 + + 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. + + 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. 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] = {} + # 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: - """Fetch the registered DaprClient from the registry.""" - self._client = self.registry.get_component(DaprClient) + """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() + 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) + self._clients[namespace] = client + 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, + len(topic_callbacks), + ", ".join(topic_callbacks), + ) + await client.subscribe(topic_callbacks) async def on_shutdown(self) -> None: - """No shutdown actions required — DaprClient lifecycle is managed separately.""" + 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. + """ + 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). + + 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. + + 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) + 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]: + async def subscribe(self) -> list[dict[str, Any]]: + """Return the subscription document the Dapr sidecar fetches at startup. + + 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. + + 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. """ - Dapr subscription discovery endpoint. + if self.config.get("dapr_declarative_subscriptions", False): + logger.debug("DaprEventing: subscriptions are declared externally, returning an empty document") + return [] - Implementations can override this by adding their own router with the same - path to provide real topics and routes. + pubsub_name = self.config.get("dapr_pubsub_name", "pubsub") + # 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() + ] - Note: this complements subscription resources defined in kubernetes - (you can choose your approach) + 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: + by_agent.setdefault(namespace_of(handler), {})[topic] = None + return {namespace: list(topics) for namespace, topics in by_agent.items()} - # Framework default: no subscriptions declared. - # Example structure: - # return [ - # {"pubsubname": "pubsub", "topic": "events.topic1", "route": "/events/topic1"} - # ] - return {} + def _declared_topics(self) -> list[str]: + """Return every topic any agent in this process declares, deduplicated. - @RestApiBase.post("/events/{topic}", tags=["dapr"]) - async def publish(self, topic: str, cloud_event: CloudEvent[Any]) -> dict[str, Any]: + 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. """ - Generic Dapr event handler that processes events through the unified service. + 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,) - try: - context = { - "dapr_topic": topic, - } + def _is_paused(self, namespace: str) -> bool: + """Whether ``namespace`` has been taken off its topics because it is degraded (C4). - processing_result = await self._process_cloud_event(cloud_event, context) + 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)) - # Return Dapr-compatible response based on result status - if processing_result.status == ProcessingStatus.PROCESSED: - return {"status": "SUCCESS"} + @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. - 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} + 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 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. - except RetryableHandlerError as exc: - logger.error( - "Retrying message for topic %s: %s", - topic, - str(exc), - exc_info=True, - ) - return {"status": "RETRY", "reason": exc.reason} + **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. - except InvalidEventError as exc: - logger.error( - "Dropping message for topic %s: %s", - topic, - str(exc), - exc_info=True, - ) - return {"status": "DROP", "reason": exc.reason} + 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. It is a + ``HandlerError``'s ``reason``, or for any other exception only its type name. + """ + agents = self._agents_for(topic) + dispositions: list[DeliveryDisposition] = [] + reason: str | None = None - except CriticalHandlerError as exc: - logger.error( - "Critical error for topic %s: %s", - topic, - str(exc), - exc_info=True, - ) - return {"status": "RETRY", "reason": exc.reason} + 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 + # 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(delivered, {"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: + # 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, + cloud_event.id, + topic, + dapr_status(disposition), + exc, + exc_info=True, + ) - except Exception as exc: # pragma: no cover - integration behaviour - logger.error( - "Processing service failed for Dapr topic %s: %s", + 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, - str(exc), - exc_info=True, + len(agents), + ", ".join(namespace or ROOT_LABEL for namespace in agents), + dapr_status(combined), ) - 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. 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/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..f04a9242 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,38 @@ from abc import ABC, abstractmethod from typing import Any +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 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_COUNTER = "blueprint.events.unhandled" +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", + SKIPPED_EVENTS_COUNTER: "Events whose selected handler was responsible but found nothing to do (HandlerResult.skipped)", +} + class EventHandlingBase(RestApiBase, CloudEventProcessorMixin, ABC): """Base class for event-driven REST API components. @@ -22,60 +45,112 @@ 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. """ @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, + namespace: str | None = None, ) -> ProcessingResult: - """Process a CloudEvent with error handling and logging. + """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 + 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. + + 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. + + 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. - Wraps ``_dispatch_cloud_event`` with structured logging and exception - handling for the four known error types. All exceptions are re-raised - after logging. + 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. - Args: - cloud_event: The CloudEvent to process - context: Additional context for processing + ``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. + """ + 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: a group would otherwise report one + # agent's broad subscription as everybody's. + if context.get(DUPLICATE_CONTEXT_KEY): + 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: + 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: + """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": self._metric_topic(namespace, topic)}) - Returns: - The processing result + def _metric_topic(self, namespace: str, topic: str) -> str: + """The ``topic`` label for a delivery: the topic itself, which a transport may narrow (S9). - Raises: - Exception: Re-raises all exceptions after logging + NATS delivers only on subscriptions its agents declared, so every value is bounded. Dapr + overrides this, because its topic comes from the request path. """ - 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 + return topic diff --git a/src/blueprint/agents/io/api/eventing/nats.py b/src/blueprint/agents/io/api/eventing/nats.py index 319f0700..c2b46c86 100644 --- a/src/blueprint/agents/io/api/eventing/nats.py +++ b/src/blueprint/agents/io/api/eventing/nats.py @@ -3,120 +3,194 @@ 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 ....models.errors import CriticalHandlerError, InvalidEventError, RetryableHandlerError +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 from .event_handling_base import EventHandlingBase logger = logging.getLogger(__name__) +NATS_SUBJECT_CONTEXT_KEY = "nats_subject" +"""Handler context key holding the subject a NATS message was delivered on. -class NatsEventing(EventHandlingBase): - """Implements event handling using NATS via NATSClient.""" +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. +""" - 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. +NATS_DELIVERY_ATTEMPT_CONTEXT_KEY = "nats_delivery_attempt" +"""Handler context key: which attempt this JetStream delivery is, 1-based (the broker's ``num_delivered``). - 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) +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. +""" - seen: dict[str, 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 - for topic in self.config.get_nats_subscription_config(): - if topic and topic not in seen: - seen[topic] = None +NATS_MAX_DELIVER_CONTEXT_KEY = "nats_max_deliver" +"""Handler context key: the attempts the delivering consumer allows; ``None`` when unlimited or unknown. - if not seen: - logger.info("NatsEventing: no auto-subscriptions configured") - return +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``. +""" - 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. +class NatsEventing(EventHandlingBase): + """Implements event handling using NATS via NATSClient. - 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") + ``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. - 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) + 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. - await self._client.subscribe(topic, _process_event) - logger.info("NatsEventing: auto-subscribed to topic '%s'", topic) + 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. - async def on_shutdown(self) -> None: - """No shutdown actions required — NATSClient lifecycle is managed separately.""" + **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. - @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. + In a group its publish endpoint is ``/api//nats/events/{topic}``; standalone it + stays ``/events/{topic}`` (spec sec. 11.2). + """ - Args: - topic: The topic to subscribe to - queue_group: Optional queue group + group_segment = "nats" - Returns: - Success message + 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. """ - if not self._client: - raise RuntimeError("NATS client not initialized") + super().__init__(should_register=False, namespace=namespace) + self._client: NATSClient | None = None - # 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, + 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, DeliveryCallback] = {topic: self._make_event_callback(topic) for topic in self._declared_topics()} + + if topic_callbacks: + if self.namespace: + logger.info( + "Namespace '%s' subscribes to %d topic(s): %s", + self.namespace, + len(topic_callbacks), + ", ".join(topic_callbacks), ) - except (RetryableHandlerError, InvalidEventError, CriticalHandlerError) as exc: - logger.error("Event processing failed: %s", str(exc), exc_info=True) - # NATS handles retries/acks via client + 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") + + def _declared_topics(self) -> list[str]: + """Return the topics this agent subscribes to, in declaration order. - await self._client.subscribe(topic, _process_event) - return {"message": f"Subscribed to topic {topic}"} + 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 + + 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: 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", + event.id, + topic, + processing_result.status.value, + ) + + 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 + topic: The topic to publish to. + event: The CloudEvent to publish. Returns: - Success message + 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/src/blueprint/agents/io/api/eventing/sessions_bus.py b/src/blueprint/agents/io/api/eventing/sessions_bus.py index 603855d2..9b8975c9 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_LABEL, ROOT_NAMESPACE from ....models.errors import InvalidEventError, RetryableHandlerError from ....models.events import GenericCloudEvent from ....models.sessions import JobNotification @@ -52,9 +53,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 @@ -87,6 +95,58 @@ def __init__(self) -> 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(): @@ -123,7 +183,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()) + 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", @@ -144,12 +208,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() @@ -279,6 +338,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).""" @@ -368,6 +453,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/src/blueprint/agents/io/api/rest_api_base.py b/src/blueprint/agents/io/api/rest_api_base.py index 6c2f8b49..08595bc8 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 @@ -30,16 +32,28 @@ 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 from ...component.component import traced +from ...component.namespace import ROOT_NAMESPACE from ...models import ProcessResourceResponse, ProcessingStatus from ..io_base import IOBase 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. @@ -50,11 +64,75 @@ class RestApiBase(IOBase, ABC): never need to call ``_wire_routes()`` or touch the router directly. """ - def __init__(self, should_register: bool = True) -> None: - super().__init__(should_register) - self._router = APIRouter() + 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. + """ + + 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. + + 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(prefix=_normalise_path_prefix(type(self).path_prefix), 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 -- ``/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. + + 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. + """ + 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: """Access the instance router. This property is read-only.""" @@ -144,7 +222,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__, }, ) @@ -158,9 +238,12 @@ 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 + # 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/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..37818cf2 100644 --- a/src/blueprint/agents/io/api/scheduling/scheduler.py +++ b/src/blueprint/agents/io/api/scheduling/scheduler.py @@ -1,10 +1,31 @@ """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 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 +than on the code -- see :meth:`SchedulerBase._resolve_mode`. + +A REST endpoint for manual triggering is registered under ``/{name}/trigger`` in +both modes: ``/api/{name}/trigger`` standalone, ``/api//scheduler/{name}/trigger`` +in a group (spec sec. 11.2). Example:: @@ -18,37 +39,328 @@ async def tick(self) -> None: from __future__ import annotations +import asyncio +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 +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, namespace_scope +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.""" + +SCHEDULER_MODE_IN_PROCESS = "in_process" +"""An APScheduler timer inside every replica of the process.""" + +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.""" + +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. +""" + +_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 _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 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, 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: + 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." + ) + 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. + +``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. + # 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 + + @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.run_tick() + return {"status": "ticked", "scheduler": self._scheduler.name} + + class SchedulerBase(RestApiBase): """Abstract base class for cron-based background schedulers. 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 (on Redis; a disk + cache claims within one process). 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: + group_segment = "scheduler" + + 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 + # 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 + # 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: @@ -60,31 +372,426 @@ 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 + + @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: - self._scheduler = AsyncIOScheduler() - self._scheduler.add_job(self.tick, trigger, name=self.name) - self._scheduler.start() + - ``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() + # 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() + 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 + # 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: + """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 + # 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 - logger.info("Scheduler '%s' started with crontab '%s'", self.name, self._crontab) + def _resolve_mode(self) -> str: + """Read and validate ``scheduler_mode``, which has no default (spec sec. 7.5). + + 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 = 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. " + 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 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}.") + 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. + """ + 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. + + 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 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 " + 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}"`` 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 + 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 + 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, 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 + validate_subject_segment(topic, source=f"The tick topic given to scheduler '{self.name}'", subject=topic) + return topic + + # 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: " + "set 'app_name', or pass topic=... to SchedulerBase.__init__." + ) + + 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.base_name, source=f"The name of scheduler '{self.base_name}'", subject=topic) + 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 + # 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 + # without the builder still gets its handler and its route. + 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'.", + self.name, + self.tick_topic, + self._crontab, + ) + return + + 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) + scheduler.start() + self._scheduler = scheduler + self._started = True + + if self.registry.has_cache(): + logger.info( + "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, + ) + 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, + ) + + 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. + """ + 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 + + 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. + + 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: 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 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() + + 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 + 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 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 + + 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, + {"scheduler": self.name, "slot": slot}, + {"claimed_at": time.time()}, + namespace=TICK_CACHE_NAMESPACE, + 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 # ------------------------------------------------------------------ @@ -97,5 +804,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/api/utilities/cache.py b/src/blueprint/agents/io/api/utilities/cache.py index b6befac7..73606def 100644 --- a/src/blueprint/agents/io/api/utilities/cache.py +++ b/src/blueprint/agents/io/api/utilities/cache.py @@ -4,14 +4,33 @@ 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 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: super().__init__(should_register=False) @@ -22,35 +41,67 @@ 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. + + "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. + + 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, + 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, 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) @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/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..1f772761 --- /dev/null +++ b/src/blueprint/agents/io/telemetry/loop_watchdog.py @@ -0,0 +1,164 @@ +"""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, 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". The exact answer is a deliberate choice: set ``event_loop_debug`` and accept the cost. +""" + +import asyncio +import logging +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__) + +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 with debug mode on, where the exact callback is worth the overhead.""" + + +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``. + + 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 = parse_bool(getter(DEBUG_KEY, False), DEBUG_KEY) if callable(getter) else False + 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..b69188af --- /dev/null +++ b/src/blueprint/agents/io/telemetry/providers.py @@ -0,0 +1,125 @@ +"""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. +""" + +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.""" + +_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 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. + + 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..85bac46f 100644 --- a/src/blueprint/agents/io/telemetry/telemetry.py +++ b/src/blueprint/agents/io/telemetry/telemetry.py @@ -1,19 +1,173 @@ -"""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: 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. +======================== ====================================================================== + +A key the deployment declares in ``OTEL_RESOURCE_ATTRIBUTES`` or ``OTEL_SERVICE_NAME`` is never +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 +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. 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 -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.resources import Resource -from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import MetricExporter, MetricExportResult, MetricsData, PeriodicExportingMetricReader +from opentelemetry.sdk.resources import OTELResourceDetector, Resource +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, shutdown_providers, tracer_provider logger = logging.getLogger(__name__) +_exit_hook_registered = False +"""Whether :func:`shutdown_providers` is registered with ``atexit`` -- once per process.""" + + +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 + ``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. + + **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: + 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 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.""" @@ -22,8 +176,18 @@ 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. + + 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: raise ValueError("TelemetryManager.configure_tracing requires a Config instance") @@ -36,26 +200,120 @@ 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 = [_SharedSpanProcessor(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 = [_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 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 " + "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 + own_service_name = bool(declared_service_name) and namespace != ROOT_NAMESPACE + self._configure_namespace( + namespace, self._service_name(namespace, observability), 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 + # 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 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, + service_name: str, + group: str, + pod: str, + span_processors: Sequence[_SharedSpanProcessor], + metric_exporters: Sequence[_SharedMetricExporter], + own_service_name: bool = False, + ) -> 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. + 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. + 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). + """ + 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. + 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.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.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) + 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.""" @@ -86,6 +344,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.""" @@ -93,10 +369,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/src/blueprint/agents/layout.py b/src/blueprint/agents/layout.py new file mode 100644 index 00000000..5b1184c6 --- /dev/null +++ b/src/blueprint/agents/layout.py @@ -0,0 +1,113 @@ +"""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. " + "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." + ), + ), +) +"""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) -> 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. + + 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] = [] + for artifact in MISPLACED: + for wrong in artifact.wrong: + 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/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/api.py b/src/blueprint/agents/models/api.py index 93605c34..f6f45903 100644 --- a/src/blueprint/agents/models/api.py +++ b/src/blueprint/agents/models/api.py @@ -181,6 +181,36 @@ 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.", + ) + 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): """Response for the readiness probe, including downstream components.""" @@ -193,6 +223,21 @@ class ReadinessResponse(BaseModel): ..., description="Health status of individual components.", ) + # 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] | 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( json_schema_extra={ @@ -208,6 +253,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"]}, + }, } } ) @@ -244,13 +294,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 +331,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/src/blueprint/agents/models/config.py b/src/blueprint/agents/models/config.py index 084955e2..1571e0ba 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") @@ -167,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/models/errors.py b/src/blueprint/agents/models/errors.py index 718f3b8e..d63e1415 100644 --- a/src/blueprint/agents/models/errors.py +++ b/src/blueprint/agents/models/errors.py @@ -1,3 +1,31 @@ +"""Handler exceptions, and the delivery disposition each one implies.""" + +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): """Domain-specific exception raised by handlers.""" @@ -27,3 +55,94 @@ class InvalidEventError(HandlerError): 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. + + 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 + + +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/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 c4c9d70d..43bd566d 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,48 +67,20 @@ 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.""" 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/models/status.py b/src/blueprint/agents/models/status.py index c18035f1..d53302e3 100644 --- a/src/blueprint/agents/models/status.py +++ b/src/blueprint/agents/models/status.py @@ -34,19 +34,44 @@ 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]] | 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. Present only when the process hosts a group " + "of agents." + ), ) 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/services/eventing/event_processing_service.py b/src/blueprint/agents/services/eventing/event_processing_service.py index 6ab16e4d..0f2a8561 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 @@ -7,8 +8,11 @@ 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 ...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 @@ -16,24 +20,91 @@ 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. 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: - """No startup actions required.""" + """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. + """ + 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: - """No shutdown actions required.""" + """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( @@ -42,14 +113,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 @@ -57,9 +133,26 @@ 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 - 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 + # 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) @@ -72,39 +165,62 @@ 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) + 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: - handler_result: Any | HandlerResult | list[HandlerResult] | None = await self._handler_chain.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 chain.process(event, context) 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: - 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 {}, source_event=event, new_subject=result.subject or new_subject, + index=index, ) - 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 + 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 + 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: + await chain.release(event, context) self._correlation_context.reset(correlation_token) async def process_rest_request( @@ -112,6 +228,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. @@ -119,6 +237,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 @@ -134,7 +254,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 @@ -173,7 +293,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, @@ -183,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 @@ -198,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/src/blueprint/agents/services/eventing/event_publishing_service.py b/src/blueprint/agents/services/eventing/event_publishing_service.py index e56ac043..083ae888 100644 --- a/src/blueprint/agents/services/eventing/event_publishing_service.py +++ b/src/blueprint/agents/services/eventing/event_publishing_service.py @@ -2,11 +2,12 @@ import logging from typing import Any -from uuid import uuid4 +from uuid import NAMESPACE_URL, uuid4, uuid5 from opentelemetry import trace from ...component.component import traced +from ...component.namespace import ROOT_NAMESPACE from ..service_base import ServiceBase from ...clients.io.io_client_base import IOClientBase from ...models import GenericCloudEvent @@ -16,22 +17,52 @@ 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. 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. + + 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: @@ -103,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/src/blueprint/agents/services/infrastructure/cache_backend_factory.py b/src/blueprint/agents/services/infrastructure/cache_backend_factory.py index c68defff..9bfe327d 100644 --- a/src/blueprint/agents/services/infrastructure/cache_backend_factory.py +++ b/src/blueprint/agents/services/infrastructure/cache_backend_factory.py @@ -1,31 +1,171 @@ """Factory for selecting the appropriate cache backend from configuration.""" import logging +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 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, 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 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 + :meth:`_component_name` derives. + + Raises: + ValueError: if ``name`` cannot serve as a cache 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 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 create(config: CacheConfig, enable_locking: bool = True) -> CacheService: - if config.backend == "redis": - return CacheBackendFactory._create_redis(config, enable_locking) - return CacheBackendFactory._create_disk(config, enable_locking) + 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, 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 + 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 storage == DEFAULT_CACHE_NAME: + return config.cache_dir + return str(PurePosixPath(config.cache_dir.replace("\\", "/")) / storage) + + @staticmethod + 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`` + 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 storage == DEFAULT_CACHE_NAME: + return config.key_prefix + return f"{config.key_prefix}:{storage}" if config.key_prefix else storage @staticmethod - def _create_redis(config: CacheConfig, enable_locking: bool) -> 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) + return CacheBackendFactory._create_disk(config, enable_locking, name, storage) raise resolved_url = config.redis_url or "redis://localhost:6379/0" @@ -35,9 +175,11 @@ 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, storage), 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 @@ -55,19 +197,24 @@ 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 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) -> 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=config.cache_dir, + 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, 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 37621718..29b89b60 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. @@ -163,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. @@ -175,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 @@ -186,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( @@ -313,6 +350,64 @@ 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, and report whether we stored it. + + ``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. + + 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..16130e9a 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. @@ -36,8 +40,13 @@ def __init__( key_prefix: str = "", default_ttl: int | None = None, fallback_to_local: bool = False, + component_name: str | None = None, + socket_timeout: float | 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) @@ -54,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: @@ -102,15 +117,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: @@ -147,6 +177,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) @@ -168,14 +218,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: @@ -232,6 +291,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/src/blueprint/agents/services/service_base.py b/src/blueprint/agents/services/service_base.py index c5f33ae3..411c8093 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,17 @@ 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, *, should_register: bool = True) -> 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. + 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. + ``RestApiBase`` has taken the same parameter since before namespaces. + """ + super().__init__(should_register=should_register, name=name, namespace=namespace) diff --git a/src/blueprint/agents/services/sessions/api_client.py b/src/blueprint/agents/services/sessions/api_client.py index 51863397..90298885 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 ...models.sessions import JobError from ..service_base import ServiceBase @@ -34,8 +35,15 @@ class SessionsApiClient(ServiceBase): agent_token = "@format {env[SESSIONS_AGENT_TOKEN]}" """ - 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._agent_token: str | None = None diff --git a/src/blueprint/agents/services/sessions/key_provider.py b/src/blueprint/agents/services/sessions/key_provider.py index c7e9fdd7..f43ca357 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/src/blueprint/agents/utils/__init__.py b/src/blueprint/agents/utils/__init__.py index a0cd0b5c..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 +from .utils import camel_to_snake, parse_bool, run_app, uvicorn_log_level -__all__ = ["camel_to_snake"] +__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 1be0400a..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: @@ -14,3 +38,124 @@ 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}.") + + +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/__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 new file mode 100644 index 00000000..f3df85ab --- /dev/null +++ b/tests/integration/conftest.py @@ -0,0 +1,474 @@ +"""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. + +**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 + +``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 +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 +from unittest.mock import patch + +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) + + +@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 +# --------------------------------------------------------------------------- + + +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. 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 + # 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 + + +# --------------------------------------------------------------------------- +# 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: + ... + + ``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. + """ + + @asynccontextmanager + async def factory( + 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)) + # 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: + 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 + 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..4dc44f82 --- /dev/null +++ b/tests/integration/connection_source.py @@ -0,0 +1,134 @@ +"""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``, ``test_source_unclaimed``, +``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 +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.""" + +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", + "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.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) + + 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], *, 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=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() + } + + def binding(self, agent: str, subjects: tuple[str, ...], connection: ConnectionSpec) -> JetStreamBinding: + 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.""" + 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/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/integration/docker-compose.yml b/tests/integration/docker-compose.yml new file mode 100644 index 00000000..0fc6a3ad --- /dev/null +++ b/tests/integration/docker-compose.yml @@ -0,0 +1,63 @@ +# 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 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: + - "4222:4222" + - "8222:8222" + healthcheck: + test: ["CMD", "wget", "--spider", "-q", "http://localhost:8222/healthz"] + interval: 5s + timeout: 3s + 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 + ports: + - "6379:6379" + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 5 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/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/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_acknowledgement_lifecycle.py b/tests/integration/test_acknowledgement_lifecycle.py new file mode 100644 index 00000000..87dda550 --- /dev/null +++ b/tests/integration/test_acknowledgement_lifecycle.py @@ -0,0 +1,302 @@ +"""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_nak_delay`| +| 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) + times: list[float] = field(default_factory=list) + """The event loop's clock at each call, for the delay between deliveries.""" + + +@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] = [] + times: list[float] = [] + + 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) + times.append(asyncio.get_running_loop().time()) + if error is not None: + raise error + return None + + return Attempts(handler=FailingHandler, topic=topic, seen=seen, times=times) + + 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" + + +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_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/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_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_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_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_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..0ff32723 --- /dev/null +++ b/tests/integration/test_harness.py @@ -0,0 +1,215 @@ +"""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", + ) + # 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] diff --git a/tests/integration/test_named_connections.py b/tests/integration/test_named_connections.py new file mode 100644 index 00000000..7fe346ef --- /dev/null +++ b/tests/integration/test_named_connections.py @@ -0,0 +1,560 @@ +"""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; +- 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 +import json +import logging +import uuid +from collections.abc import AsyncIterator, Awaitable, Callable +from typing import Any +from unittest.mock import patch + +import httpx +import nats +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 +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, event_id: str | None = None +) -> str: + user, password = ADMINS[tenant] + admin = await nats.connect(accounts_url, user=user, password=password) + 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() + 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") + + 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( + 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 + ) -> 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) == [] + + +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"}, 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"}, 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" + ) + 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"}, unreachable={"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. + + 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' + 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: + """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 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( + 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_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 + ) 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") + + +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/integration/test_shared_redis_cache.py b/tests/integration/test_shared_redis_cache.py index 6be95e2c..523ad041 100644 --- a/tests/integration/test_shared_redis_cache.py +++ b/tests/integration/test_shared_redis_cache.py @@ -4,11 +4,13 @@ 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 os import subprocess import sys import textwrap @@ -16,9 +18,15 @@ import pytest import redis -REDIS_URL = "redis://localhost:6379/0" +from .conftest import COMPOSE_HINT + +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 +"""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 +40,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(f"Redis is not available at {REDIS_URL}. Start it with: " + COMPOSE_HINT) return REDIS_URL @@ -65,6 +73,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 +91,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/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/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/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..db0304fe --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_create_agent.py @@ -0,0 +1,98 @@ +"""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 + + +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/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 new file mode 100644 index 00000000..f3f5ec0c --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_create_scheduler.py @@ -0,0 +1,76 @@ +"""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 + + 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 157b913e..7fa350db 100644 --- a/tests/unit/agent_generator/cli/commands/test_dev.py +++ b/tests/unit/agent_generator/cli/commands/test_dev.py @@ -1,27 +1,129 @@ -"""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 + + +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_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/agent_generator/cli/commands/test_validate.py b/tests/unit/agent_generator/cli/commands/test_validate.py new file mode 100644 index 00000000..fd535e00 --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_validate.py @@ -0,0 +1,54 @@ +"""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_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) == 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) + 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/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 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..32c52abd --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_validate_group.py @@ -0,0 +1,199 @@ +"""`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, image_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, _, _ = image_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, _, _ = 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, _, _ = 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." + 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, _, _ = image_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" + + +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, _ = 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] + 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, _ = 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, _ = 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, _ = 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_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, _ = 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, _ = 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] + + +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, _, _ = image_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 = 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 new file mode 100644 index 00000000..977ec43a --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_validate_group_gates.py @@ -0,0 +1,271 @@ +"""`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. + +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 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: + (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_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: + """The map is how a name reaches code; the gate is everything that stops it.""" + + 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 warnings == [] + 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: + project = _project(tmp_path, agent_map=_agent()) + _agent_dir(project, "orders") + + issues, warnings, _ = _group_findings(project) + + 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_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: + 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 usable 'module'" in issues[0] + + def test_a_module_that_names_no_attribute_is_reported(self, tmp_path: Path) -> None: + project = _project(tmp_path, agent_map=_agent(module="agents.orders.src.main")) + _agent_dir(project, "orders") + + issues, _, _ = _group_findings(project) + + 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='[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_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") + + 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.""" + 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: + 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) + + assert issues == [] + + +class TestSettingsThatWillNotSurviveGrouping: + """An agent's settings are read from beside its root's src, and scoped to it.""" + + 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") + + issues, _, _ = _group_findings(project) + + 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_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("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) + + 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 + + @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 = 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, settings='[default]\napp_name = "demo"\n')) + + 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, settings='[default]\nscheduler_mode = "cron"\n')) + + 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"\nnats_url = "nats://b:4222"\napp_name = "demo"\n' + project = self._with_scheduler(_project(tmp_path, settings=settings)) + + issues, _, notices = self._findings(project) + + assert issues == [] + 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, settings='[default]\nscheduler_mode = "event"\n')) + + issues, _, notices = self._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, settings=settings)) + + 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"\nnats_url = "nats://b:4222"\napp_name = "demo"\n' + project = self._with_scheduler(_project(tmp_path, settings=settings)) + + issues, _, _ = self._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") + monkeypatch.setenv("DYNACONF_NATS_URL", "nats://b:4222") + project = self._with_scheduler(_project(tmp_path, settings='[default]\napp_name = "demo"\n')) + + 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, settings=settings)) + + _, _, notices = self._findings(project) + + assert len(notices) == 1 + assert "every replica runs every tick" in notices[0] + + 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, settings=settings, main=main)) + + _, _, 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..e1b7b65a --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_validate_group_runtime.py @@ -0,0 +1,283 @@ +"""`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_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, _, notices = _findings(image) + + 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.""" + 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 new file mode 100644 index 00000000..d41cb73c --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_validate_nats.py @@ -0,0 +1,81 @@ +"""``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_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: + 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 == [] 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..c46deb25 --- /dev/null +++ b/tests/unit/agent_generator/cli/commands/test_validate_runtime_parity.py @@ -0,0 +1,357 @@ +"""`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_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, _, notices = _findings(project) + + 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) + + 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) + + +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.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"), + ], + ) + 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/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_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 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/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_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") 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..8b0a79b7 --- /dev/null +++ b/tests/unit/agent_generator/generator/test_generated_project.py @@ -0,0 +1,585 @@ +"""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 re +import shutil +import sys +import tomllib +from collections.abc import Iterator +from contextlib import contextmanager +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" + + +@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_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 "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: + """A scaffolded agent has no agent map, and its own image does not write one either. + + 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_its_own_image_does_not_write_one(self, project: Path) -> None: + dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") + + assert "agents.toml" not in dockerfile.replace("# agents.toml names this module", "") + assert "BLUEPRINT_AGENTS" not in dockerfile.replace("BLUEPRINT_* variable", "") + + def test_it_is_served_through_its_own_factory(self, project: Path) -> None: + dockerfile = (project / "Dockerfile").read_text(encoding="utf-8") + + assert "src.main:create_app" in dockerfile + assert "blueprint.agents.entrypoint" not in dockerfile + + def test_the_agent_name_is_a_legal_namespace(self, project: Path) -> None: + """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 + + 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.""" + 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.")} + 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 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_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: + """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 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_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 "# 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 + 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 in ("src", "agents") or name.startswith(("src.", "agents.")) + } + for name in saved_modules: + del sys.modules[name] + + # 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() + 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 + + 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: + """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") + + 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_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 "/app/agents.toml" not in dockerfile + assert "COPY --chown=appuser:appuser agents.toml" not 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_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") + + 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 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.""" + + def test_a_leading_digit_is_refused_with_the_reason(self) -> None: + from blueprint.agent_generator.generator.part_generators.part_generator_base import PartGeneratorBase + + 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.""" + + 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() diff --git a/tests/unit/agents/TESTS.md b/tests/unit/agents/TESTS.md new file mode 100644 index 00000000..82e76b70 --- /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); 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 | + +--- + +## 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/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/agent/test_agent_builder.py b/tests/unit/agents/agent/test_agent_builder.py index 558b0d1a..35a54a6c 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,140 @@ 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: + """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 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: + 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" # --------------------------------------------------------------------------- @@ -154,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( @@ -171,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 diff --git a/tests/unit/agents/app_builder/TESTS.md b/tests/unit/agents/app_builder/TESTS.md index 860a0670..9d2b9aab 100644 --- a/tests/unit/agents/app_builder/TESTS.md +++ b/tests/unit/agents/app_builder/TESTS.md @@ -8,7 +8,9 @@ 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_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) | --- @@ -18,7 +20,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 | @@ -30,6 +32,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 b01f2a3f..40829936 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,25 +59,28 @@ 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'. """ 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 @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) @@ -120,10 +125,24 @@ 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 = [] 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 9eb35381..c4378e3e 100644 --- a/tests/unit/agents/app_builder/test_app_builder.py +++ b/tests/unit/agents/app_builder/test_app_builder.py @@ -6,8 +6,39 @@ 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 +# --------------------------------------------------------------------------- + + +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 @@ -23,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() @@ -33,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: @@ -103,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() @@ -121,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 @@ -280,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] # ---------------------------------------------------------------------- @@ -315,9 +370,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() @@ -335,7 +390,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( @@ -386,7 +441,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() @@ -417,8 +472,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() @@ -532,3 +587,273 @@ def test_each_url_can_be_individually_disabled( assert kwargs["docs_url"] is None assert kwargs["redoc_url"] is None assert kwargs["openapi_url"] is None + + +# --------------------------------------------------------------------------- +# 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. + # 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() + + 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_components == [] + + 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() + + +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() + + 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/app_builder/test_build_namespaces.py b/tests/unit/agents/app_builder/test_build_namespaces.py new file mode 100644 index 00000000..35ef68eb --- /dev/null +++ b/tests/unit/agents/app_builder/test_build_namespaces.py @@ -0,0 +1,300 @@ +"""``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 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, 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 +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() + + +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 = hosting(nats_config, orders=AppBuilder().with_handler(OrderHandler), billing=AppBuilder().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 = hosting(nats_config, orders=AppBuilder().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 = 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 = hosting(nats_config, reporting=AppBuilder().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 = hosting(nats_config, orders=AppBuilder().with_handler(OrderHandler), billing=AppBuilder().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 = 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: + 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 = hosting(nats_config, orders=AppBuilder().with_handler(OrderHandler), billing=AppBuilder().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 = hosting(nats_config, orders=AppBuilder().with_handler(OrderHandler), billing=AppBuilder().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 = hosting(nats_config, orders=AppBuilder(), billing=AppBuilder()) + + 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 = 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_deferred_wiring.py b/tests/unit/agents/app_builder/test_deferred_wiring.py new file mode 100644 index 00000000..5f44d0bc --- /dev/null +++ b/tests/unit/agents/app_builder/test_deferred_wiring.py @@ -0,0 +1,350 @@ +"""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] + + +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_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() + + assert _handler_order() == ["FirstHandler", "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() + + 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.""" + 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_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/app_builder/test_named_caches.py b/tests/unit/agents/app_builder/test_named_caches.py new file mode 100644 index 00000000..e71042e3 --- /dev/null +++ b/tests/unit/agents/app_builder/test_named_caches.py @@ -0,0 +1,280 @@ +"""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 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: + 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") + 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) + + +def registry() -> Registry: + assert Component.shared_registry is not None + 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: + 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: + 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.""" + 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: + 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 + realize(builder.with_cache()) + assert registry().has_cache() + + +class TestPositionalCompatibility: + def test_disabled_registers_nothing(self, builder: AppBuilder) -> None: + 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: + 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: + realize(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: + 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: + 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.""" + 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: + 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.""" + 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: + 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: + 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().""" + realize(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() + + +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 entry_keys(builder) + + 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() + + 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.""" + builder.with_cache(name="sessions") + + with patch("blueprint.agents.app_builder.FastAPI"): + builder.build() + + 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") + + with patch("blueprint.agents.app_builder.FastAPI"): + builder.build() + + 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_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 new file mode 100644 index 00000000..a7406e5b --- /dev/null +++ b/tests/unit/agents/app_builder/test_route_namespacing.py @@ -0,0 +1,478 @@ +"""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.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.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 + + +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 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 + + 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)) + + +@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"]) + + +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_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) + 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: + 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.""" + declaration = AppBuilder().with_rest_api(OrderApi) + + app = AgentGroup("g", {"orders": declaration, "billing": declaration}).assemble(dapr_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: + """In a group an agent's operations form exactly one Swagger group, named after the agent (spec sec. 11.2).""" + + 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) + + 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) + + 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(ItemApi) + + app = AgentGroup("g", {"orders": declaration, "billing": declaration}).assemble(dapr_config) + + 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: + """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 + + @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: + 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.""" + 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) + 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.""" + declaration = AppBuilder().with_handler(OrderHandler) + + app = AgentGroup("g", {"orders": declaration, "billing": declaration}).assemble(nats_config) + + 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) + OrderHandler() + + document = await DaprEventing().subscribe() + + 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. + + 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] + + +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/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/app_builder/test_standalone_readiness.py b/tests/unit/agents/app_builder/test_standalone_readiness.py new file mode 100644 index 00000000..cb2fd4a0 --- /dev/null +++ b/tests/unit/agents/app_builder/test_standalone_readiness.py @@ -0,0 +1,180 @@ +"""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.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 +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() + + +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"] + + +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/app_builder/test_startup_failure_policy.py b/tests/unit/agents/app_builder/test_startup_failure_policy.py new file mode 100644 index 00000000..ac021a7f --- /dev/null +++ b/tests/unit/agents/app_builder/test_startup_failure_policy.py @@ -0,0 +1,409 @@ +"""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. +""" + +import asyncio +import signal +from collections.abc import Iterator +from pathlib import Path +from typing import Any +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 +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 == () + + +# --------------------------------------------------------------------------- +# 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 + + +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") + + +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/TESTS.md b/tests/unit/agents/clients/TESTS.md index 0f6b6bdd..a49b2010 100644 --- a/tests/unit/agents/clients/TESTS.md +++ b/tests/unit/agents/clients/TESTS.md @@ -13,7 +13,8 @@ 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; 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/ai/test_openai_client.py b/tests/unit/agents/clients/ai/test_openai_client.py index bb961076..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 @@ -36,7 +37,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 @@ -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 25c73575..829b6c84 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()) @@ -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/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/clients/io/conftest.py b/tests/unit/agents/clients/io/conftest.py index c89dd3e9..c9d89c01 100644 --- a/tests/unit/agents/clients/io/conftest.py +++ b/tests/unit/agents/clients/io/conftest.py @@ -1,8 +1,10 @@ """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 from blueprint.agents.clients.io.dapr_client import DaprClient from blueprint.agents.clients.io.nats_client import NATSClient @@ -15,12 +17,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, } @@ -77,26 +81,37 @@ 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() + mock.flush = AsyncMock() mock.jetstream = MagicMock(return_value=None) return mock @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 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_dapr_client.py b/tests/unit/agents/clients/io/test_dapr_client.py index bf8f95e1..a7f7a2b0 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: @@ -77,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, @@ -140,3 +167,126 @@ 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 + + +# --------------------------------------------------------------------------- +# 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_binding_mode.py b/tests/unit/agents/clients/io/test_nats_binding_mode.py new file mode 100644 index 00000000..d127dfcd --- /dev/null +++ b/tests/unit/agents/clients/io/test_nats_binding_mode.py @@ -0,0 +1,288 @@ +"""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, 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 + +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() + + +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(TenancyError, 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_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) + 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_client.py b/tests/unit/agents/clients/io/test_nats_client.py index cffb2037..53837b50 100644 --- a/tests/unit/agents/clients/io/test_nats_client.py +++ b/tests/unit/agents/clients/io/test_nats_client.py @@ -1,14 +1,48 @@ """Unit tests for NATSClient.""" +import asyncio import json +import logging from unittest.mock import AsyncMock, MagicMock, patch +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.nats_client import NATSClient +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, + DurableConflictError, + JetStreamPermissionError, + JetStreamUnavailableError, + NATSClient, + StreamConflictError, + _Binding, + _Link, + redact_url, +) +from blueprint.agents.models.errors import CriticalHandlerError, InvalidEventError, RetryableHandlerError 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 @@ -22,6 +56,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 +99,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) @@ -82,6 +134,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: @@ -100,18 +153,194 @@ 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 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_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 +354,322 @@ 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 _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 + ) -> None: + dispatched = [] + + async def _callback(event: CloudEvent, subject: str) -> 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_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 = _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"] + + 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, subject: str) -> 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, subject: str) -> 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, subject: str) -> 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, subject: str) -> 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 _until_settled(nats_client, 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, subject: str) -> 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, subject: str) -> 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, subject: str) -> 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, subject: str) -> 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 = _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() + 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, subject: str) -> 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, subject: str) -> 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 = _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) + + 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, subject: str) -> 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 = _until_settled(nats_client, 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( @@ -150,7 +695,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) @@ -158,6 +705,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, @@ -170,7 +737,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 +754,2406 @@ 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="'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: + 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_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=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, + 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"], nats_ack_wait=300.0) + existing = js_api.ConsumerConfig( + 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"): + 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 + 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 + ) -> 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 _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 + ) -> None: + async def _callback(event: CloudEvent, subject: str) -> 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, subject: str) -> 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, subject: str) -> 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, subject: str) -> 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, 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) + 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, 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) + 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 + + @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 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() + + 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 +# --------------------------------------------------------------------------- + + +# --------------------------------------------------------------------------- +# 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 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.""" + + 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_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" + + 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() == "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() == "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() == "laptop" + + 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) + + def _raise() -> str: + raise OSError("no host name") + + monkeypatch.setattr("blueprint.agents.deployment.socket.gethostname", _raise) + 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.""" + 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, mock_config: MagicMock, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("POD_NAME", raising=False) + monkeypatch.setenv("HOSTNAME", "web-7.eu.internal") + name = _namespaced_client(mock_config, "orders")._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") + + +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.""" + + @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_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_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"))): + 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.""" + 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 + + +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) + + +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_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())) + 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() + + +# --------------------------------------------------------------------------- +# 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'"] + + +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 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.""" + + @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") + + +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) + 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 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 + 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() + + +_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 + + +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 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(DurableConflictError) 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) + + +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"] + + +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/clients/io/test_nats_connection_readiness.py b/tests/unit/agents/clients/io/test_nats_connection_readiness.py new file mode 100644 index 00000000..815b39fe --- /dev/null +++ b/tests/unit/agents/clients/io/test_nats_connection_readiness.py @@ -0,0 +1,312 @@ +"""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() + core.flush = 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_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") + 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") + 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_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 + 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'")) + + 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") + 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/clients/io/test_nats_connection_source.py b/tests/unit/agents/clients/io/test_nats_connection_source.py new file mode 100644 index 00000000..1b1abf8b --- /dev/null +++ b/tests/unit/agents/clients/io/test_nats_connection_source.py @@ -0,0 +1,432 @@ +"""Named connections from a connection source (named-connections plan, step 3a).""" + +import asyncio +import contextvars +import json +import ssl +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, + 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 + +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, 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} + + 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(), + flush=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}) + + 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: + source = FakeSource({"A": _binding("A", "risk.>", "issue.>"), "B": _binding("B", "risk.>"), "C": None}) + 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"] + + 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"): + 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 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.>",)) + 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 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) 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 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..bd66eb6e --- /dev/null +++ b/tests/unit/agents/clients/io/test_nats_runtime_changes.py @@ -0,0 +1,460 @@ +"""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 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 { + 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, flush=AsyncMock()) + 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 claims(self, agent: str, subjects: tuple) -> tuple: + return subjects + + 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_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) + 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_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 + + 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), + caplog.at_level(logging.ERROR), + ): + nats_client._started = True + await _started(nats_client, source, broker) + 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 + + 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"] diff --git a/tests/unit/agents/component/TESTS.md b/tests/unit/agents/component/TESTS.md index 527cb01a..d6b754bf 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); 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); 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/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..a89b0dc6 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 @@ -114,7 +117,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)) @@ -293,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 @@ -341,3 +361,193 @@ 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 + + +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_name_uniqueness.py b/tests/unit/agents/component/test_name_uniqueness.py new file mode 100644 index 00000000..c55ce3d2 --- /dev/null +++ b/tests/unit/agents/component/test_name_uniqueness.py @@ -0,0 +1,271 @@ +"""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.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.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 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. + + ``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" + + +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_namespace.py b/tests/unit/agents/component/test_namespace.py new file mode 100644 index 00000000..c896d802 --- /dev/null +++ b/tests/unit/agents/component/test_namespace.py @@ -0,0 +1,187 @@ +"""Unit tests for the namespace naming, validation and resolution helpers (P6).""" + +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, + display_segment, + namespace_of, + namespace_scope, + 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(" ") + + @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") + + +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(" ", "") == "" + + +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..b0b5917c 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,428 @@ 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 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.""" + + 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_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" + + 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_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", "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.""" + 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/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_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 f3971b54..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,37 +106,61 @@ 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", - ) - - def test_missing_scoped_app_port_raises(self, write_settings: WriteSettings) -> None: + + 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.""" + settings_file = write_settings(""" + [development] + app_environment = "development" + app_port = 8080 + + [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_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" - # 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_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_agent_settings_fragments.py b/tests/unit/agents/config/test_agent_settings_fragments.py new file mode 100644 index 00000000..1fb5dc06 --- /dev/null +++ b/tests/unit/agents/config/test_agent_settings_fragments.py @@ -0,0 +1,366 @@ +"""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 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.""" + 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")) + + +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/config/test_config_init.py b/tests/unit/agents/config/test_config_init.py index d9ed9533..3f9dbd8e 100644 --- a/tests/unit/agents/config/test_config_init.py +++ b/tests/unit/agents/config/test_config_init.py @@ -2,6 +2,9 @@ from pathlib import Path +import pytest +from unittest.mock import MagicMock + from blueprint.agents.config import Config @@ -57,6 +60,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).""" @@ -112,3 +137,160 @@ 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" + + 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/config/test_config_specialized_configs.py b/tests/unit/agents/config/test_config_specialized_configs.py index 7bb3cf58..4657cb5d 100644 --- a/tests/unit/agents/config/test_config_specialized_configs.py +++ b/tests/unit/agents/config/test_config_specialized_configs.py @@ -49,6 +49,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_envvar_prefix.py b/tests/unit/agents/config/test_envvar_prefix.py new file mode 100644 index 00000000..2413b2a3 --- /dev/null +++ b/tests/unit/agents/config/test_envvar_prefix.py @@ -0,0 +1,215 @@ +"""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_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.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: + 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_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 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..c87604d0 --- /dev/null +++ b/tests/unit/agents/config/test_namespace_views.py @@ -0,0 +1,243 @@ +"""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_to_an_agent(self, two_agent_config: Config, key: str) -> None: + with pytest.raises(ValueError, match="deployment identity"): + 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.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.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" + + +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") + + +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/conftest.py b/tests/unit/agents/conftest.py index 4d0388f4..91feb79c 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", @@ -22,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/handler/TESTS.md b/tests/unit/agents/handler/TESTS.md index 1522a2b4..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; 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; 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/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/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_handler_chain.py b/tests/unit/agents/handler/test_handler_chain.py index d33d4296..7b0e12e9 100644 --- a/tests/unit/agents/handler/test_handler_chain.py +++ b/tests/unit/agents/handler/test_handler_chain.py @@ -1,17 +1,32 @@ """Unit tests for HandlerChain.""" +import asyncio +from typing import Any from unittest.mock import MagicMock import pytest -from blueprint.agents.handler.handler_chain import HandlerChain +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, + 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 +41,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() @@ -86,6 +102,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: @@ -117,3 +169,471 @@ async def handle_event(self, event, context): _wire_handlers(mock_registry, [BrokenHandler()]) 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) +# --------------------------------------------------------------------------- + + +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 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.""" + 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_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: + """#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()]) + + context: dict[str, Any] = {} + await chain.process(cloud_event, context) + await chain.release(cloud_event, context) + await chain.process(cloud_event, {}) + + assert seen == ["evt-001", "evt-001"] + + 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) + + await 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) + + await 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) + await chain.release(cloud_event, context) + await chain.process(cloud_event, {}) # the redelivery claims again + + await 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: + _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_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"}) + + await 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: + """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_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: + 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) + + +# --------------------------------------------------------------------------- +# 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}'"] + + +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_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: + 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/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/handler/test_sessions_job_handler.py b/tests/unit/agents/handler/test_sessions_job_handler.py index 8ff1a026..62f25513 100644 --- a/tests/unit/agents/handler/test_sessions_job_handler.py +++ b/tests/unit/agents/handler/test_sessions_job_handler.py @@ -819,3 +819,58 @@ 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 + + +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/TESTS.md b/tests/unit/agents/io/TESTS.md index 7824d054..5f079ef6 100644 --- a/tests/unit/agents/io/TESTS.md +++ b/tests/unit/agents/io/TESTS.md @@ -8,19 +8,22 @@ 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/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; 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` | -| `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_dapr.py` | `DaprEventing` | `publish` PROCESSED→SUCCESS, no-handler→RETRY, `RetryableHandlerError`→RETRY, `InvalidEventError`→DROP, `CriticalHandlerError`→RETRY; `subscribe` returns empty dict | +| `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) | -| `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/utilities/test_cache.py` | `CacheManagementApi` | 503 when no cache, `get_cache_stats`/`list_cache_namespaces`/`evict_cache_entry` delegate to registry cache service | +| `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`; 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 | -| `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/api/actuators/health/test_health_cache.py b/tests/unit/agents/io/api/actuators/health/test_health_cache.py index b94c0dc4..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 @@ -1,9 +1,14 @@ """Unit tests for HealthCheckCache.""" +import asyncio 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.io.api.actuators.health.readiness_policy import ReadinessPolicy from blueprint.agents.models.api import ComponentHealth @@ -14,6 +19,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 +35,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 +43,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 +91,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 +100,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 +132,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 +153,272 @@ 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") + + +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], 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 + + @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" + + +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_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 == "DOWN" + 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() + + +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 +# --------------------------------------------------------------------------- + + +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"] + + +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/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..dc95c8d0 --- /dev/null +++ b/tests/unit/agents/io/api/actuators/health/test_readiness_policy.py @@ -0,0 +1,78 @@ +"""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 + + +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/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" 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..435ec43b 100644 --- a/tests/unit/agents/io/api/actuators/test_actuator_api.py +++ b/tests/unit/agents/io/api/actuators/test_actuator_api.py @@ -1,10 +1,17 @@ """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.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 @@ -55,6 +62,98 @@ 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" + + @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 @@ -73,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 @@ -92,16 +216,16 @@ 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: - 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() @@ -173,3 +297,230 @@ 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 -- no "namespaces" key.""" + result = await ActuatorApi().env_status() + 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: + 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 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" + assert result.settings["MODEL_NAME"] == "orders-model" + assert "billing" not in {str(key).lower() for key in result.settings} + + +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]) + + +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 + + +# --------------------------------------------------------------------------- +# 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/conftest.py b/tests/unit/agents/io/api/eventing/conftest.py index 19cbca73..534a19b8 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() @@ -50,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_dapr.py b/tests/unit/agents/io/api/eventing/test_dapr.py index 15d3d9ca..90fc162c 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,391 @@ 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"] == "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"), + [ + (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"] + handler.namespace = "" + 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"] + 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 + + 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"] + 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 + + 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"] + handler.namespace = "" + 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_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: + _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._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)) + + 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 + + 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: + """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._clients == {} + + 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"] + 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() + + 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"] + 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() # 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/api/eventing/test_dapr_fanout.py b/tests/unit/agents/io/api/eventing/test_dapr_fanout.py new file mode 100644 index 00000000..225fd867 --- /dev/null +++ b/tests/unit/agents/io/api/eventing/test_dapr_fanout.py @@ -0,0 +1,384 @@ +"""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, MagicMock + +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] + + +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"] + + +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 1529cdf8..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 @@ -1,12 +1,35 @@ """Unit tests for EventHandlingBase._unwrap_nested_cloud_event and handle_event.""" import json -from unittest.mock import AsyncMock, MagicMock +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, 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 +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 + + +@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 @@ -104,28 +127,258 @@ 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 _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": "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 _counters() as counters: + await dapr_eventing._process_cloud_event(cloud_event, {}, "orders.created") + + 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 + ) -> None: + """The count is read as a ratio against received volume, so it must not be deduplicated.""" + self._returning(dapr_eventing, unhandled_result) + + with _counters() as counters: + for _ in range(5): + await dapr_eventing._process_cloud_event(cloud_event, {}, "orders.created") + + assert counters[UNHANDLED_EVENTS_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_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 + + +# --------------------------------------------------------------------------- +# 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 _counters() as counters: + await dapr_eventing.handle_event("orders", cloud_event) + + 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, + 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 _counters() as counters: + await dapr_eventing.handle_event("orders", cloud_event) + + 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"}] == [] + + +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_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/eventing/test_nats.py b/tests/unit/agents/io/api/eventing/test_nats.py index b3a37195..40f4e905 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.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 -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,199 @@ 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"] + + 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 # --------------------------------------------------------------------------- -# _subscribe_to_topic — client guard and delegation +# the callback must let failures reach the transport (spec sec. 7.2) # --------------------------------------------------------------------------- -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") +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, "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, "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" + + +# --------------------------------------------------------------------------- +# 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"] + + +class TestATenantSubjectIsRefused: + """B1 -- the route has no authentication; a tenant's subject would run under that tenant's identity.""" - 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") + 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.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]) + 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] 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() diff --git a/tests/integration/test_sessions_startup_resilience.py b/tests/unit/agents/io/api/eventing/test_sessions_startup_resilience.py similarity index 89% rename from tests/integration/test_sessions_startup_resilience.py rename to tests/unit/agents/io/api/eventing/test_sessions_startup_resilience.py index 121eb540..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 @@ -54,15 +57,11 @@ 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 -# 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/unit/agents/io/api/scheduling/test_scheduler.py b/tests/unit/agents/io/api/scheduling/test_scheduler.py index a197f82d..d8a3a140 100644 --- a/tests/unit/agents/io/api/scheduling/test_scheduler.py +++ b/tests/unit/agents/io/api/scheduling/test_scheduler.py @@ -1,10 +1,29 @@ -"""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.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" class _TestScheduler(SchedulerBase): @@ -12,8 +31,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 +45,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 scheduler(mock_config: MagicMock, mock_registry: MagicMock) -> _TestScheduler: - """Return a concrete SchedulerBase instance.""" +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 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 +100,334 @@ 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_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): + def __init__(self) -> None: + super().__init__(crontab="0 3 * *") + + async def tick(self) -> None: + """Never called.""" + + 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: + 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.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.""" + 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" + 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="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="cannot appear in a NATS subject"): + _ = unusable.tick_topic + + 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() + 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: + 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 +447,367 @@ 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() + 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() + 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() + + +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 + + +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() + + +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/io/api/scheduling/test_scheduler_event_mode.py b/tests/unit/agents/io/api/scheduling/test_scheduler_event_mode.py new file mode 100644 index 00000000..7c49b52f --- /dev/null +++ b/tests/unit/agents/io/api/scheduling/test_scheduler_event_mode.py @@ -0,0 +1,209 @@ +"""An event-mode scheduler is ticked through the ordinary event path. + +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: + +- ``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.reset_shared_state() + yield + Component.reset_shared_state() + + +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}"', + # 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)]) + + +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/agents/io/api/test_rest_api_base.py b/tests/unit/agents/io/api/test_rest_api_base.py index 6ff56843..9d1f60f8 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,61 @@ 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 + + +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/io/api/utilities/test_cache.py b/tests/unit/agents/io/api/utilities/test_cache.py index 61a564fb..3a2f2b43 100644 --- a/tests/unit/agents/io/api/utilities/test_cache.py +++ b/tests/unit/agents/io/api/utilities/test_cache.py @@ -1,39 +1,77 @@ -"""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 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", + "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 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 +83,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 +99,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 +123,146 @@ 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 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() + 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/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_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..1dd5c44d --- /dev/null +++ b/tests/unit/agents/io/telemetry/test_loop_watchdog.py @@ -0,0 +1,106 @@ +"""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_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(**{DEBUG_KEY: True})) is True + assert loop.get_debug() is True + finally: + loop.set_debug(False) + + 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"})) 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(**{DEBUG_KEY: True}, event_loop_slow_callback_seconds=0.5)) + 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 0e4b318b..9a65400a 100644 --- a/tests/unit/agents/io/telemetry/test_telemetry.py +++ b/tests/unit/agents/io/telemetry/test_telemetry.py @@ -1,13 +1,37 @@ """Unit tests for TelemetryManager and TracingContext.""" +from collections.abc import Iterator from unittest.mock import MagicMock, patch import pytest -from blueprint.agents.io.telemetry.telemetry import TelemetryManager, TracingContext +from blueprint.agents.io.telemetry.providers import agent_meter, agent_tracer, configured_namespaces, reset_providers, tracer_provider +from blueprint.agents.io.telemetry.telemetry import TelemetryConfigError, 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(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.""" @@ -41,7 +65,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() @@ -68,6 +92,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 +101,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, @@ -144,3 +242,291 @@ 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") != "" + + +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")] == [] + + 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"] diff --git a/tests/unit/agents/models/TESTS.md b/tests/unit/agents/models/TESTS.md index 879e4ba3..c3b2dd8a 100644 --- a/tests/unit/agents/models/TESTS.md +++ b/tests/unit/agents/models/TESTS.md @@ -9,8 +9,9 @@ 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_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_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`, `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, 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 new file mode 100644 index 00000000..07e8cfe6 --- /dev/null +++ b/tests/unit/agents/models/test_errors.py @@ -0,0 +1,76 @@ +"""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: + 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) 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/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"}) diff --git a/tests/unit/agents/services/TESTS.md b/tests/unit/agents/services/TESTS.md index 4f9f6260..a2dbd437 100644 --- a/tests/unit/agents/services/TESTS.md +++ b/tests/unit/agents/services/TESTS.md @@ -8,9 +8,11 @@ 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; 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 | +| `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). `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/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/eventing/conftest.py b/tests/unit/agents/services/eventing/conftest.py index cf8a2e17..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 @@ -54,5 +55,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_namespaces.py b/tests/unit/agents/services/eventing/test_event_processing_namespaces.py new file mode 100644 index 00000000..01c83bef --- /dev/null +++ b/tests/unit/agents/services/eventing/test_event_processing_namespaces.py @@ -0,0 +1,263 @@ +"""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, 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 = """ + [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")), namespace="orders") + registry = Component.shared_registry + assert registry is not None + registry.add_cache(DEFAULT_CACHE_NAME, cache, namespace="orders") + 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 df3bf721..32d2bed2 100644 --- a/tests/unit/agents/services/eventing/test_event_processing_service.py +++ b/tests/unit/agents/services/eventing/test_event_processing_service.py @@ -1,12 +1,22 @@ """Unit tests for EventProcessingService.""" -from unittest.mock import AsyncMock +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) @@ -63,6 +73,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" @@ -113,19 +127,82 @@ 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 # --------------------------------------------------------------------------- +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_is_noop(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_chains = {ROOT_NAMESPACE: chain} + + await event_processing_service.on_startup() + + chain.on_startup.assert_awaited_once() + + 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() - async def test_on_shutdown_is_noop(self, event_processing_service: EventProcessingService) -> None: + 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() + root.on_shutdown.assert_awaited_once() + orders.on_shutdown.assert_awaited_once() + # --------------------------------------------------------------------------- # process_rest_request @@ -157,3 +234,204 @@ 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) + chain.release = AsyncMock() + 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_awaited_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_awaited() + + 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] + + +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) + chain.release = AsyncMock() + 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.""" + + 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"} + + 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) + chain.release = AsyncMock() + 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"] + + +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 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..7042f876 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 unittest.mock import MagicMock +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 @@ -14,16 +18,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, real_registry: Registry, mock_config: MagicMock, register_client: Callable[[str], MagicMock] + ) -> None: mock_config.get_event_publishing_config.return_value = EventPublishingConfig() + client = register_client("") svc = EventPublishingService() await svc.on_startup() - mock_registry.get_component.assert_called() - assert svc._client is not None + assert svc._client is 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 +218,160 @@ 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) +# --------------------------------------------------------------------------- + + +@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: + 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, real_registry: Registry, mock_config: MagicMock, register_client: Callable[..., MagicMock] + ) -> None: + """Outbound traffic on another namespace's connection would be unattributable.""" + 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, real_registry: Registry, mock_config: MagicMock, register_client: Callable[..., MagicMock] + ) -> None: + """A namespaced agent in a process with one shared transport keeps working.""" + 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, 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 IOClientBase is registered"): + await svc.on_startup() + + 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, real_registry: Registry, mock_config: MagicMock) -> None: + mock_config.get_event_publishing_config.return_value = EventPublishingConfig() + 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) 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..63c57430 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,178 @@ 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() + + +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/services/infrastructure/test_cache_sharing_via_registry.py b/tests/unit/agents/services/infrastructure/test_cache_sharing_via_registry.py index 238a4792..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 @@ -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 @@ -150,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 d986dca8..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 @@ -244,3 +245,94 @@ 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 + + +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) 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..5a8819a3 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,127 @@ 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 + + +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() + + +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 diff --git a/tests/unit/agents/test_agent_files.py b/tests/unit/agents/test_agent_files.py new file mode 100644 index 00000000..434ac0cd --- /dev/null +++ b/tests/unit/agents/test_agent_files.py @@ -0,0 +1,313 @@ +"""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, ConfigError +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_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) + + 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 TestAStandaloneAgentIsNotAGroupOfOne: + """An agent served on its own has no map, so nothing can sit at its root claiming otherwise. + + 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") + write_map( + image, + """ + [agents.solo] + root = "." + module = "src.main:agent" + """, + ) + + with pytest.raises(GroupConfigError, match="belongs to the image"): + resolve(image, "solo") + + +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") + + +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" diff --git a/tests/unit/agents/test_agent_group.py b/tests/unit/agents/test_agent_group.py new file mode 100644 index 00000000..9f15ee68 --- /dev/null +++ b/tests/unit/agents/test_agent_group.py @@ -0,0 +1,652 @@ +"""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.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 +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, 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]: + 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", 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", root=Path("agents") / "order"),) + ) + + 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, root=Path("agents") / "order"),)) + + 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", root=Path("agents") / "order", 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_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", + agents=( + AgentSpec(name="order", module="no.such.module:declaration", root=Path("agents") / "order", 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", root=Path("agents") / "order"), + 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 / "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)) + + 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 / "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)) + + group: Any = AgentGroup.resolve(config, environ={"BLUEPRINT_AGENTS": "order"}) + + 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.""" + 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_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"] == 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: + """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) + + 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 == {} + + +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"] + + +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_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 + + monkeypatch.setenv("BLUEPRINT_GROUP", "from-env") + assert deployment_group() == "from-env" + monkeypatch.delenv("BLUEPRINT_GROUP") + assert deployment_group() == UNGROUPED_LABEL diff --git a/tests/unit/agents/test_agent_isolation.py b/tests/unit/agents/test_agent_isolation.py new file mode 100644 index 00000000..4732e49f --- /dev/null +++ b/tests/unit/agents/test_agent_isolation.py @@ -0,0 +1,438 @@ +"""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 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 reached a *neighbour's* key, not + only the root's; +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()`` 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 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 +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_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.""" + 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 == [] + + 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.""" + + 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/agents/test_design_rules.py b/tests/unit/agents/test_design_rules.py new file mode 100644 index 00000000..eb3cd11f --- /dev/null +++ b/tests/unit/agents/test_design_rules.py @@ -0,0 +1,1071 @@ +"""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 os +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 / "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}) + + 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." + ) + + +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. + + *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] = {} +"""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. + + 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]: + """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 diff --git a/tests/unit/agents/test_entrypoint.py b/tests/unit/agents/test_entrypoint.py new file mode 100644 index 00000000..9efb154c --- /dev/null +++ b/tests/unit/agents/test_entrypoint.py @@ -0,0 +1,214 @@ +"""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 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 + + +# What a project's main.py contains: an AppBuilder that has never been built. +order_declaration = AppBuilder().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 / "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 + + +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]\nroot = "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_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 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().with_service(OrderService).build(config) + + 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]\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"}) + + 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_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 new file mode 100644 index 00000000..15ada02c --- /dev/null +++ b/tests/unit/agents/test_group_config.py @@ -0,0 +1,347 @@ +"""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] +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 + 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) + 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') + 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, 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", + 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. + + 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.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"}) + + 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) + 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') + 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) + 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)) + + 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) + 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)) + + 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.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.""" + 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 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.""" + 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)}) + + 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: + """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", root=Path("agents/invoice")),)) + + assert (group.name, group.agent_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] diff --git a/tests/unit/agents/utils/TESTS.md b/tests/unit/agents/utils/TESTS.md index c117d8ec..229f5365 100644 --- a/tests/unit/agents/utils/TESTS.md +++ b/tests/unit/agents/utils/TESTS.md @@ -9,11 +9,20 @@ 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 | --- ## 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. + +### `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_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") 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 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..c716a75d --- /dev/null +++ b/tests/unit/examples/test_example_structure.py @@ -0,0 +1,131 @@ +"""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 + +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] = { + "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." + ), +} +"""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 _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/`` 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]: + """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_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" 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