From dd735d0630aa0cf32820f6c14a30ec31776aff27 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Mon, 26 Oct 2026 17:20:08 -0300
Subject: [PATCH 01/71] carry the deploy templates into blueprint/ on the
generator context, with their tests
---
.github/workflows/linting.yml | 4 +-
.github/workflows/tests.yml | 3 +
.../deploy/local/docker-compose.yml.j2 | 108 ++++++++++
.../templates/deploy/nginx/default.conf.j2 | 33 +++
.../deploy/nginx/docker-compose.yml.j2 | 148 +++++++++++++
.../deploy/prod/docker-compose.yml.j2 | 127 +++++++++++
blueprint/tests/test_deploy_templates.py | 197 ++++++++++++++++++
7 files changed, 618 insertions(+), 2 deletions(-)
create mode 100644 blueprint/templates/deploy/local/docker-compose.yml.j2
create mode 100644 blueprint/templates/deploy/nginx/default.conf.j2
create mode 100644 blueprint/templates/deploy/nginx/docker-compose.yml.j2
create mode 100644 blueprint/templates/deploy/prod/docker-compose.yml.j2
create mode 100644 blueprint/tests/test_deploy_templates.py
diff --git a/.github/workflows/linting.yml b/.github/workflows/linting.yml
index e12a747a..1291d93a 100644
--- a/.github/workflows/linting.yml
+++ b/.github/workflows/linting.yml
@@ -28,7 +28,7 @@ jobs:
- name: Ruff check
# --no-sync skips uv run's implicit sync: the step above already installed
# every member and extra, and skipping it keeps each step from re-resolving.
- run: uv run --no-sync ruff check backend/src backend/tests backend/scripts backend/migrations cli/src cli/tests tools
+ run: uv run --no-sync ruff check backend/src backend/tests backend/scripts backend/migrations cli/src cli/tests tools blueprint/tests
- name: Ruff format
- run: uv run --no-sync ruff format --check backend/src backend/tests backend/scripts backend/migrations cli/src cli/tests tools
+ run: uv run --no-sync ruff format --check backend/src backend/tests backend/scripts backend/migrations cli/src cli/tests tools blueprint/tests
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 1c94f005..746fd114 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -34,6 +34,9 @@ jobs:
- name: Pytest (cli)
run: cd cli && uv run --no-sync pytest
+ - name: Pytest (blueprint)
+ run: uv run --no-sync pytest blueprint/tests
+
removal-drills:
runs-on: ubuntu-latest
strategy:
diff --git a/blueprint/templates/deploy/local/docker-compose.yml.j2 b/blueprint/templates/deploy/local/docker-compose.yml.j2
new file mode 100644
index 00000000..c2e4e5b1
--- /dev/null
+++ b/blueprint/templates/deploy/local/docker-compose.yml.j2
@@ -0,0 +1,108 @@
+# Generated by `fastro make deploy local`.
+# Hot-reload dev stack: API + Taskiq worker + Postgres + Redis.
+# Source is mounted into the container so file changes trigger a reload.
+
+name: {{ project.slug }}
+
+services:
+ api:
+ build:
+ context: .
+ dockerfile: backend/Dockerfile
+ target: dev
+ env_file:
+ - ./backend/.env
+ environment:
+ POSTGRES_SERVER: postgres
+ CACHE_REDIS_HOST: redis
+ RATE_LIMITER_REDIS_HOST: redis
+ TASKIQ_REDIS_HOST: redis
+ volumes:
+ - ./backend/src:/app/src
+ - ./backend/tests:/app/tests
+ ports:
+ - "{{ params.api_port }}:8000"
+ depends_on:
+ postgres:
+ condition: service_healthy
+ redis:
+ condition: service_healthy
+{% if "worker" in services %}
+ worker:
+ build:
+ context: .
+ dockerfile: backend/Dockerfile
+ target: dev
+ env_file:
+ - ./backend/.env
+ environment:
+ POSTGRES_SERVER: postgres
+ CACHE_REDIS_HOST: redis
+ RATE_LIMITER_REDIS_HOST: redis
+ TASKIQ_REDIS_HOST: redis
+ working_dir: /app/src
+ command: >
+ taskiq worker src.infrastructure.taskiq.worker:default_broker
+ --reload
+ volumes:
+ - ./backend/src:/app/src
+ depends_on:
+ postgres:
+ condition: service_healthy
+ redis:
+ condition: service_healthy
+{% endif %}
+{%- if "scheduler" in services %}
+ # Run exactly one of these: each scheduler fires every schedule it finds.
+ scheduler:
+ build:
+ context: .
+ dockerfile: backend/Dockerfile
+ target: dev
+ env_file:
+ - ./backend/.env
+ environment:
+ POSTGRES_SERVER: postgres
+ CACHE_REDIS_HOST: redis
+ RATE_LIMITER_REDIS_HOST: redis
+ TASKIQ_REDIS_HOST: redis
+ working_dir: /app/src
+ command: >
+ taskiq scheduler src.infrastructure.taskiq.scheduler:scheduler
+ volumes:
+ - ./backend/src:/app/src
+ depends_on:
+ postgres:
+ condition: service_healthy
+ redis:
+ condition: service_healthy
+{% endif %}
+ postgres:
+ image: postgres:16-alpine
+ env_file:
+ - ./backend/.env
+ volumes:
+ - postgres-data:/var/lib/postgresql/data
+ ports:
+ - "127.0.0.1:5432:5432"
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER:-postgres}\""]
+ interval: 5s
+ timeout: 3s
+ retries: 10
+
+ redis:
+ image: redis:7-alpine
+ volumes:
+ - redis-data:/data
+ ports:
+ - "127.0.0.1:6379:6379"
+ healthcheck:
+ test: ["CMD", "redis-cli", "ping"]
+ interval: 5s
+ timeout: 3s
+ retries: 10
+
+volumes:
+ postgres-data:
+ redis-data:
diff --git a/blueprint/templates/deploy/nginx/default.conf.j2 b/blueprint/templates/deploy/nginx/default.conf.j2
new file mode 100644
index 00000000..8873337b
--- /dev/null
+++ b/blueprint/templates/deploy/nginx/default.conf.j2
@@ -0,0 +1,33 @@
+# Generated by `fastro make deploy nginx`.
+# Drop-in nginx vhost in front of the FastAPI app container.
+
+upstream {{ project.slug }}_api {
+ server api:8000;
+}
+
+server {
+ listen 80;
+ server_name _;
+
+ client_max_body_size 25M;
+ server_tokens off;
+
+ # Forwarded headers. X-Forwarded-For and X-Forwarded-Proto are replaced with what
+ # nginx saw, dropping whatever the client sent. uvicorn trusts the headers only from
+ # the compose network (FORWARDED_ALLOW_IPS); crudauth counts hops from the right
+ # through TRUSTED_PROXY_HOPS.
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $remote_addr;
+ proxy_set_header X-Forwarded-Proto $scheme;
+
+ # Long-running endpoints (exports, AI, etc.) want generous timeouts.
+ proxy_connect_timeout 60s;
+ proxy_send_timeout 300s;
+ proxy_read_timeout 300s;
+
+ location / {
+ proxy_pass http://{{ project.slug }}_api;
+ proxy_redirect off;
+ }
+}
diff --git a/blueprint/templates/deploy/nginx/docker-compose.yml.j2 b/blueprint/templates/deploy/nginx/docker-compose.yml.j2
new file mode 100644
index 00000000..b8873080
--- /dev/null
+++ b/blueprint/templates/deploy/nginx/docker-compose.yml.j2
@@ -0,0 +1,148 @@
+# Generated by `fastro make deploy nginx`.
+# Production stack with an nginx reverse proxy in front of the API.
+# Public traffic enters on port 80 (and 443 once you wire TLS); the
+# API container only exposes itself on the internal compose network.
+
+name: {{ project.slug }}
+
+services:
+ # One-shot, and nothing waits on it: run it and only then restart the rest, so a
+ # migration that fails leaves the old code serving on the old schema.
+ # docker compose --profile migrate run --rm migrate
+ migrate:
+ build:
+ context: .
+ dockerfile: backend/Dockerfile
+ target: migrate
+ env_file:
+ - ./backend/.env
+ environment:
+ POSTGRES_SERVER: postgres
+ CONFIRM_PRODUCTION_MIGRATION: "yes"
+ profiles: ["migrate"]
+ depends_on:
+ postgres:
+ condition: service_healthy
+ restart: "no"
+
+ api:
+ build:
+ context: .
+ dockerfile: backend/Dockerfile
+ target: prod
+ env_file:
+ - ./backend/.env
+ environment:
+ POSTGRES_SERVER: postgres
+ CACHE_REDIS_HOST: redis
+ RATE_LIMITER_REDIS_HOST: redis
+ TASKIQ_REDIS_HOST: redis
+ TRUSTED_PROXY_HOPS: "1"
+ FORWARDED_ALLOW_IPS: "{{ params.internal_subnet }}"
+ WORKERS: "{{ params.workers }}"
+ expose:
+ - "8000"
+ depends_on:
+ postgres:
+ condition: service_healthy
+ redis:
+ condition: service_healthy
+ healthcheck:
+ test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health/ready').read()"]
+ interval: 15s
+ timeout: 5s
+ retries: 5
+ start_period: 20s
+ restart: unless-stopped
+{% if "worker" in services %}
+ worker:
+ build:
+ context: .
+ dockerfile: backend/Dockerfile
+ target: prod
+ env_file:
+ - ./backend/.env
+ environment:
+ POSTGRES_SERVER: postgres
+ CACHE_REDIS_HOST: redis
+ RATE_LIMITER_REDIS_HOST: redis
+ TASKIQ_REDIS_HOST: redis
+ working_dir: /app/src
+ command: taskiq worker src.infrastructure.taskiq.worker:default_broker --workers 2
+ depends_on:
+ postgres:
+ condition: service_healthy
+ redis:
+ condition: service_healthy
+ restart: unless-stopped
+{% endif %}
+{%- if "scheduler" in services %}
+ # Run exactly one of these: each scheduler fires every schedule it finds.
+ scheduler:
+ build:
+ context: .
+ dockerfile: backend/Dockerfile
+ target: prod
+ env_file:
+ - ./backend/.env
+ environment:
+ POSTGRES_SERVER: postgres
+ CACHE_REDIS_HOST: redis
+ RATE_LIMITER_REDIS_HOST: redis
+ TASKIQ_REDIS_HOST: redis
+ working_dir: /app/src
+ command: taskiq scheduler src.infrastructure.taskiq.scheduler:scheduler
+ depends_on:
+ postgres:
+ condition: service_healthy
+ redis:
+ condition: service_healthy
+ restart: unless-stopped
+{% endif %}
+ nginx:
+ image: nginx:1.27-alpine
+ ports:
+ - "80:80"
+ volumes:
+ - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
+ depends_on:
+ - api
+ restart: unless-stopped
+
+ postgres:
+ image: postgres:16-alpine
+ env_file:
+ - ./backend/.env
+ volumes:
+ - postgres-data:/var/lib/postgresql/data
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER:-postgres}\""]
+ interval: 10s
+ timeout: 5s
+ retries: 10
+ restart: unless-stopped
+
+ redis:
+ image: redis:7-alpine
+ command: ["redis-server", "--appendonly", "yes"]
+ volumes:
+ - redis-data:/data
+ healthcheck:
+ test: ["CMD", "redis-cli", "ping"]
+ interval: 10s
+ timeout: 5s
+ retries: 10
+ restart: unless-stopped
+
+volumes:
+ postgres-data:
+ redis-data:
+
+# The API trusts forwarded headers only from this range, so a client can neither
+# claim another address nor say the request arrived over HTTPS. Change both this
+# subnet and FORWARDED_ALLOW_IPS together if it clashes with a network you use.
+networks:
+ default:
+ ipam:
+ config:
+ - subnet: "{{ params.internal_subnet }}"
diff --git a/blueprint/templates/deploy/prod/docker-compose.yml.j2 b/blueprint/templates/deploy/prod/docker-compose.yml.j2
new file mode 100644
index 00000000..d792a5a8
--- /dev/null
+++ b/blueprint/templates/deploy/prod/docker-compose.yml.j2
@@ -0,0 +1,127 @@
+# Generated by `fastro make deploy prod`.
+# Production-ish single-host stack: multi-worker API + Taskiq worker
+# + Postgres + Redis. The API is exposed directly on the host port —
+# add a reverse proxy (or use the `nginx` mode) before public traffic.
+
+name: {{ project.slug }}
+
+services:
+ # One-shot, and nothing waits on it: run it and only then restart the rest, so a
+ # migration that fails leaves the old code serving on the old schema.
+ # docker compose --profile migrate run --rm migrate
+ migrate:
+ build:
+ context: .
+ dockerfile: backend/Dockerfile
+ target: migrate
+ env_file:
+ - ./backend/.env
+ environment:
+ POSTGRES_SERVER: postgres
+ CONFIRM_PRODUCTION_MIGRATION: "yes"
+ profiles: ["migrate"]
+ depends_on:
+ postgres:
+ condition: service_healthy
+ restart: "no"
+
+ api:
+ build:
+ context: .
+ dockerfile: backend/Dockerfile
+ target: prod
+ env_file:
+ - ./backend/.env
+ environment:
+ POSTGRES_SERVER: postgres
+ CACHE_REDIS_HOST: redis
+ RATE_LIMITER_REDIS_HOST: redis
+ TASKIQ_REDIS_HOST: redis
+ WORKERS: "{{ params.workers }}"
+ ports:
+ - "{{ params.api_port }}:8000"
+ depends_on:
+ postgres:
+ condition: service_healthy
+ redis:
+ condition: service_healthy
+ healthcheck:
+ test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health/ready').read()"]
+ interval: 15s
+ timeout: 5s
+ retries: 5
+ start_period: 20s
+ restart: unless-stopped
+{% if "worker" in services %}
+ worker:
+ build:
+ context: .
+ dockerfile: backend/Dockerfile
+ target: prod
+ env_file:
+ - ./backend/.env
+ environment:
+ POSTGRES_SERVER: postgres
+ CACHE_REDIS_HOST: redis
+ RATE_LIMITER_REDIS_HOST: redis
+ TASKIQ_REDIS_HOST: redis
+ working_dir: /app/src
+ command: taskiq worker src.infrastructure.taskiq.worker:default_broker --workers 2
+ depends_on:
+ postgres:
+ condition: service_healthy
+ redis:
+ condition: service_healthy
+ restart: unless-stopped
+{% endif %}
+{%- if "scheduler" in services %}
+ # Run exactly one of these: each scheduler fires every schedule it finds.
+ scheduler:
+ build:
+ context: .
+ dockerfile: backend/Dockerfile
+ target: prod
+ env_file:
+ - ./backend/.env
+ environment:
+ POSTGRES_SERVER: postgres
+ CACHE_REDIS_HOST: redis
+ RATE_LIMITER_REDIS_HOST: redis
+ TASKIQ_REDIS_HOST: redis
+ working_dir: /app/src
+ command: taskiq scheduler src.infrastructure.taskiq.scheduler:scheduler
+ depends_on:
+ postgres:
+ condition: service_healthy
+ redis:
+ condition: service_healthy
+ restart: unless-stopped
+{% endif %}
+ postgres:
+ image: postgres:16-alpine
+ env_file:
+ - ./backend/.env
+ volumes:
+ - postgres-data:/var/lib/postgresql/data
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER:-postgres}\""]
+ interval: 10s
+ timeout: 5s
+ retries: 10
+ restart: unless-stopped
+
+ redis:
+ image: redis:7-alpine
+ command: ["redis-server", "--appendonly", "yes"]
+ volumes:
+ - redis-data:/data
+ healthcheck:
+ test: ["CMD", "redis-cli", "ping"]
+ interval: 10s
+ timeout: 5s
+ retries: 10
+ restart: unless-stopped
+
+volumes:
+ postgres-data:
+ redis-data:
diff --git a/blueprint/tests/test_deploy_templates.py b/blueprint/tests/test_deploy_templates.py
new file mode 100644
index 00000000..6c3ea73c
--- /dev/null
+++ b/blueprint/tests/test_deploy_templates.py
@@ -0,0 +1,197 @@
+"""What the generated compose files say about running this app behind a proxy.
+
+The templates are rendered with the generator context of catalog spec 6.2, under
+``StrictUndefined``: a template that reaches for anything the tool doesn't pass fails here.
+"""
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+import yaml
+from jinja2 import Environment, FileSystemLoader, StrictUndefined
+
+TEMPLATES = Path(__file__).resolve().parents[1] / "templates" / "deploy"
+
+INTERNAL_SUBNET = "172.31.240.0/24"
+"""The default of the ``internal_subnet`` param."""
+
+TASKIQ_SERVICES = ("scheduler", "worker")
+"""What the taskiq feature puts in ``services``."""
+
+
+def _context(
+ features: tuple[str, ...] = ("accounts", "taskiq"),
+ services: tuple[str, ...] = TASKIQ_SERVICES,
+ **params: Any,
+) -> dict[str, Any]:
+ """The spec 6.2 context, as the tool builds it for a generator."""
+ return {
+ "project": {"name": "example", "slug": "example"},
+ "blueprint": {"name": "fastro", "version": "0.20.0"},
+ "fastro": {"version": "0.1.0"},
+ "features": list(features),
+ "options": {},
+ "services": sorted(services),
+ "params": {"api_port": 8000, "workers": 4, "internal_subnet": INTERNAL_SUBNET, **params},
+ "has": lambda name: name in features,
+ }
+
+
+def _render(template: str, **overrides: Any) -> str:
+ environment = Environment(
+ loader=FileSystemLoader(TEMPLATES),
+ keep_trailing_newline=True,
+ undefined=StrictUndefined,
+ )
+
+ return environment.get_template(template).render(_context(**overrides))
+
+
+def _compose(mode: str, **overrides: Any) -> dict:
+ return yaml.safe_load(_render(f"{mode}/docker-compose.yml.j2", **overrides))
+
+
+@pytest.mark.parametrize("mode", ["prod", "nginx"])
+def test_the_api_reports_whether_it_is_ready(mode: str):
+ """Compose has no way to hold traffic back without one."""
+ healthcheck = _compose(mode)["services"]["api"]["healthcheck"]
+
+ assert "/health/ready" in " ".join(healthcheck["test"])
+
+
+@pytest.mark.parametrize("mode", ["prod", "nginx"])
+def test_the_worker_does_not_run_as_root(mode: str):
+ """The base stage has no USER, so building the worker from it would run it as root."""
+ assert _compose(mode)["services"]["worker"]["build"]["target"] == "prod"
+
+
+def test_behind_nginx_the_app_is_told_how_many_proxies_it_sits_behind():
+ """Without this every client looks like the nginx container, and one attacker locks everyone out."""
+ api = _compose("nginx")["services"]["api"]["environment"]
+
+ assert api["TRUSTED_PROXY_HOPS"] == "1"
+
+
+def test_forwarded_headers_are_trusted_only_from_the_compose_network():
+ """With a wildcard, uvicorn reads the leftmost X-Forwarded-For entry, which the client sets."""
+ compose = _compose("nginx")
+
+ assert compose["services"]["api"]["environment"]["FORWARDED_ALLOW_IPS"] == INTERNAL_SUBNET
+ assert compose["networks"]["default"]["ipam"]["config"] == [{"subnet": INTERNAL_SUBNET}]
+
+
+def test_nginx_hides_its_version():
+ assert "server_tokens off;" in _render("nginx/default.conf.j2")
+
+
+def test_the_local_compose_does_not_claim_a_proxy():
+ """Nothing sits in front of it, so trusting forwarded headers would let a client forge its IP."""
+ api = _compose("local")["services"]["api"]
+
+ assert "TRUSTED_PROXY_HOPS" not in api.get("environment", {})
+
+
+def test_the_local_compose_publishes_its_databases_to_the_host_only():
+ """Both database ports are bound to the loopback address."""
+ services = _compose("local")["services"]
+
+ assert services["postgres"]["ports"] == ["127.0.0.1:5432:5432"]
+ assert services["redis"]["ports"] == ["127.0.0.1:6379:6379"]
+
+
+def test_nginx_sends_only_the_address_it_saw():
+ """A client's own X-Forwarded-For must not reach the app as its address."""
+ conf = _render("nginx/default.conf.j2")
+
+ assert "proxy_set_header X-Forwarded-For $remote_addr;" in conf
+ assert "$proxy_add_x_forwarded_for" not in conf
+
+
+def test_the_compose_network_quotes_the_subnet():
+ rendered = _render("nginx/docker-compose.yml.j2")
+
+ assert f'- subnet: "{INTERNAL_SUBNET}"' in rendered
+
+
+SCHEDULER_COMMAND = "taskiq scheduler src.infrastructure.taskiq.scheduler:scheduler"
+
+
+@pytest.mark.parametrize("mode", ["local", "prod", "nginx"])
+def test_a_project_with_taskiq_gets_one_scheduler(mode: str):
+ """Every schedule fires once per scheduler, so the stack runs a single one."""
+ scheduler = _compose(mode)["services"]["scheduler"]
+
+ assert SCHEDULER_COMMAND in " ".join(scheduler["command"].split())
+ assert "deploy" not in scheduler
+
+
+@pytest.mark.parametrize("mode", ["local", "prod", "nginx"])
+def test_a_project_without_taskiq_gets_neither_worker_nor_scheduler(mode: str):
+ services = _compose(mode, features=("accounts",), services=())["services"]
+
+ assert "worker" not in services
+ assert "scheduler" not in services
+ assert "api" in services
+
+
+@pytest.mark.parametrize("mode", ["prod", "nginx"])
+def test_the_migration_runner_waits_to_be_asked(mode: str):
+ """A deploy runs it and only then restarts, so a failed migration leaves the old code serving."""
+ migrate = _compose(mode)["services"]["migrate"]
+
+ assert migrate["profiles"] == ["migrate"]
+ assert migrate["build"]["target"] == "migrate"
+
+
+@pytest.mark.parametrize("mode", ["local", "prod", "nginx"])
+def test_nothing_depends_on_a_service_behind_a_profile(mode: str):
+ """Compose refuses the whole project when a service it starts depends on a profiled one."""
+ services = _compose(mode)["services"]
+ behind_a_profile = {name for name, service in services.items() if service.get("profiles")}
+
+ for name, service in services.items():
+ assert behind_a_profile.isdisjoint(service.get("depends_on", {})), name
+
+
+@pytest.mark.parametrize("mode", ["local", "prod", "nginx"])
+def test_the_database_takes_its_credentials_from_the_environment_file(mode: str):
+ """Compose interpolates ``${VAR}`` from the shell, never from ``env_file``, and
+ ``environment`` wins over it: a password set in ``backend/.env``, which is where every page
+ says to set it, was replaced in the container by the literal fallback.
+ """
+ postgres = _compose(mode)["services"]["postgres"]
+
+ assert postgres["env_file"] == ["./backend/.env"]
+ assert "${" not in yaml.safe_dump(postgres.get("environment", {}))
+
+
+@pytest.mark.parametrize("mode", ["local", "prod", "nginx"])
+def test_the_database_probe_reads_the_user_inside_the_container(mode: str):
+ """A probe interpolated by compose asks for ``postgres`` whatever ``POSTGRES_USER`` says."""
+ probe = " ".join(_compose(mode)["services"]["postgres"]["healthcheck"]["test"])
+
+ assert "$${POSTGRES_USER" in probe
+
+
+@pytest.mark.parametrize("mode", ["local", "prod", "nginx"])
+def test_the_compose_project_is_named_after_the_project(mode: str):
+ """The slug is what compose accepts as a project name, and what the nginx upstream is keyed on."""
+ assert _compose(mode)["name"] == "example"
+
+
+def test_the_api_runs_the_workers_the_params_asked_for():
+ """``workers`` and ``api_port`` are generator params, so a flag has to reach the template."""
+ compose = _compose("prod", workers=7, api_port=9001)
+
+ assert compose["services"]["api"]["environment"]["WORKERS"] == "7"
+ assert compose["services"]["api"]["ports"] == ["9001:8000"]
+
+
+@pytest.mark.parametrize("mode", ["local", "prod", "nginx"])
+def test_each_background_service_follows_its_own_entry(mode: str):
+ """The blocks are keyed on ``services``, not on the feature, so one without the other works."""
+ services = _compose(mode, services=("worker",))["services"]
+
+ assert "worker" in services
+ assert "scheduler" not in services
From eb24ef2258f80ca9c2c362e45db250347f1deb43 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Mon, 26 Oct 2026 23:49:30 -0300
Subject: [PATCH 02/71] draw a secret key the project's own rules accept from a
backend script
---
backend/scripts/gen_secret.py | 93 ++++++++++++++++
backend/tests/unit/scripts/test_gen_secret.py | 101 ++++++++++++++++++
docs/user-guide/project-structure.md | 2 +
3 files changed, 196 insertions(+)
create mode 100644 backend/scripts/gen_secret.py
create mode 100644 backend/tests/unit/scripts/test_gen_secret.py
diff --git a/backend/scripts/gen_secret.py b/backend/scripts/gen_secret.py
new file mode 100644
index 00000000..4a67b78a
--- /dev/null
+++ b/backend/scripts/gen_secret.py
@@ -0,0 +1,93 @@
+"""Print a secret key the project's own rules accept.
+
+Run it from ``backend/``:
+
+ python -m scripts.gen_secret [--bytes 32]
+
+``SECRET_KEY`` signs the session cookies, the CSRF tokens and the admin panel's session,
+and production refuses a key its rules read as something a person typed. A draw of random
+bytes can land on such a key: about one hex key in twelve million runs through eight
+consecutive digits. So this draws again while the rules refuse what it drew, and prints the
+last draw either way, which keeps it from drawing for ever.
+
+It reads no configuration and touches no database, so it works before there is a ``.env``
+to put the key in. The rules are loaded from their own file rather than through
+``src.infrastructure.security``, whose import configures logging and writes a line to
+stdout: the key is meant to be piped, and a log line would be piped with it.
+"""
+
+import argparse
+import importlib.util
+import secrets
+from pathlib import Path
+from types import ModuleType
+
+RULES_PATH = Path(__file__).parent.parent / "src" / "infrastructure" / "security" / "secret_key.py"
+"""The project's own secret-key rules, the ones production refuses a key by."""
+
+
+def _rules() -> ModuleType:
+ """The rules module, loaded from its file so nothing around it is imported."""
+ spec = importlib.util.spec_from_file_location("secret_key_rules", RULES_PATH)
+ if spec is None or spec.loader is None:
+ raise ImportError(f"No secret-key rules at {RULES_PATH}.")
+
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+
+ return module
+
+
+is_weak_secret_key = _rules().is_weak_secret_key
+
+DRAWS = 8
+"""How many keys are drawn at most; the last one is printed whatever the rules say."""
+
+DEFAULT_BYTES = 32
+SMALLEST_BYTES = 16
+LARGEST_BYTES = 128
+
+
+def generate(byte_count: int = DEFAULT_BYTES) -> str:
+ """A hex key of ``byte_count`` random bytes, redrawn while the rules refuse it."""
+ candidate = secrets.token_hex(byte_count)
+ for _ in range(DRAWS - 1):
+ if not is_weak_secret_key(candidate):
+ break
+ candidate = secrets.token_hex(byte_count)
+
+ return candidate
+
+
+def parse_byte_count(value: str) -> int:
+ """``value`` as a byte count the key may be drawn from.
+
+ Raises:
+ argparse.ArgumentTypeError: it isn't a number, or sits outside the range.
+ """
+ try:
+ count = int(value)
+ except ValueError as error:
+ raise argparse.ArgumentTypeError(f"{value!r} is not a number of bytes.") from error
+
+ if not SMALLEST_BYTES <= count <= LARGEST_BYTES:
+ raise argparse.ArgumentTypeError(f"{count} is outside {SMALLEST_BYTES} to {LARGEST_BYTES}.")
+
+ return count
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description="Print a secret key suitable for SECRET_KEY.")
+ parser.add_argument(
+ "--bytes",
+ dest="byte_count",
+ type=parse_byte_count,
+ default=DEFAULT_BYTES,
+ help=f"Random bytes to draw, {SMALLEST_BYTES} to {LARGEST_BYTES}; the hex output is twice as long.",
+ )
+
+ print(generate(parser.parse_args().byte_count))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/backend/tests/unit/scripts/test_gen_secret.py b/backend/tests/unit/scripts/test_gen_secret.py
new file mode 100644
index 00000000..baa4dd44
--- /dev/null
+++ b/backend/tests/unit/scripts/test_gen_secret.py
@@ -0,0 +1,101 @@
+"""The key the script prints, and why it sometimes draws more than once.
+
+``SECRET_KEY`` is refused at startup in production when the project's own rules read it as
+something a person typed. A generator that printed such a key would send you into that
+refusal, so it draws again while the rules refuse what it drew.
+"""
+
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from scripts.gen_secret import generate
+from src.infrastructure.config.settings import EnvironmentOption, Settings
+from src.infrastructure.security.production_validator import ProductionSecurityValidator
+from src.infrastructure.security.secret_key import is_weak_secret_key
+
+BACKEND = Path(__file__).resolve().parents[3]
+
+REFUSED = "e48102bfe6ac2eac3aa8623456789a6030e4fa7dee3cd173bfb7941f2f819678"
+"""A hex key the rules refuse: it runs through eight consecutive digits."""
+
+
+def _run(*arguments: str) -> subprocess.CompletedProcess[str]:
+ """Run the script from ``backend/``, with nothing configured but the interpreter."""
+ environment = {
+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),
+ "HOME": os.environ.get("HOME", "/tmp"),
+ "PYTHONPATH": str(BACKEND),
+ }
+
+ return subprocess.run(
+ [sys.executable, *arguments],
+ cwd=BACKEND,
+ env=environment,
+ capture_output=True,
+ text=True,
+ timeout=60,
+ )
+
+
+def test_the_key_it_prints_is_one_the_validator_accepts():
+ """The script is what an operator runs to satisfy the validator, so ask the validator."""
+ key = generate()
+
+ validator = ProductionSecurityValidator(Settings(SECRET_KEY=key, ENVIRONMENT=EnvironmentOption.PRODUCTION))
+
+ assert len(key) == 64
+ assert not validator._is_insecure_secret_key()
+
+
+def test_a_key_the_rules_refuse_is_drawn_again(monkeypatch):
+ """One hex key in twelve million runs through eight digits, which production refuses."""
+ accepted = "7b1c9d4e2a6f8305b4c7e1d9f2a6b8c30d5e7f91a2b3c4d5e6f708192a3b4c5d"
+ draws = iter([REFUSED, accepted])
+ monkeypatch.setattr("scripts.gen_secret.secrets.token_hex", lambda size: next(draws))
+
+ assert is_weak_secret_key(REFUSED)
+ assert generate() == accepted
+
+
+def test_it_gives_up_after_the_draws_it_allows(monkeypatch):
+ """Drawing for ever would hang; the last draw is printed whatever the rules say."""
+ monkeypatch.setattr("scripts.gen_secret.secrets.token_hex", lambda size: REFUSED)
+
+ assert generate() == REFUSED
+
+
+def test_the_byte_count_decides_the_length():
+ assert len(generate(16)) == 32
+
+
+@pytest.mark.parametrize("invocation", [("scripts/gen_secret.py",), ("-m", "scripts.gen_secret")])
+def test_it_runs_the_way_the_documentation_runs_it(invocation: tuple[str, ...]):
+ """As a file from ``backend/``, and as a module, which is what the blueprint declares."""
+ result = _run(*invocation)
+
+ assert result.returncode == 0, result.stderr
+ assert len(result.stdout.strip()) == 64
+
+
+@pytest.mark.parametrize("count", ["8", "256", "many"])
+def test_a_byte_count_the_script_will_not_take_is_refused(count: str):
+ """A short key is one the rules would refuse anyway, and a usage error exits 2."""
+ result = _run("scripts/gen_secret.py", "--bytes", count)
+
+ assert result.returncode == 2
+ assert result.stdout.strip() == ""
+
+
+def test_it_prints_the_key_and_nothing_else():
+ """The documented use pipes it (``| gh secret set SECRET_KEY``), so a log line would go too.
+
+ Importing ``src.infrastructure.security`` configures logging, which writes to stdout.
+ """
+ result = _run("-m", "scripts.gen_secret")
+
+ assert result.stdout.count("\n") == 1
+ assert len(result.stdout.strip()) == 64
diff --git a/docs/user-guide/project-structure.md b/docs/user-guide/project-structure.md
index cd6fcd2a..cf31af4b 100644
--- a/docs/user-guide/project-structure.md
+++ b/docs/user-guide/project-structure.md
@@ -34,6 +34,7 @@ backend/
│ ├── create_first_superuser.py
│ ├── create_first_tier.py
│ ├── create_tables.py
+│ ├── gen_secret.py # Prints a SECRET_KEY the project's own rules accept
│ ├── prune_key_usage.py # The usage prune, for a project with no worker to schedule it
│ ├── revoke_scrypt_api_keys.py
│ ├── seeders.py # The seeders the selected features contribute
@@ -208,6 +209,7 @@ scripts/
├── cleanup_api_key_json.py # One-off repair for legacy API key rows
├── canonicalize_emails.py # One-off repair for addresses stored with case or spaces
├── unlock_account.py # Clears the login lockout one account is held in
+├── gen_secret.py # Prints a SECRET_KEY the project's own rules accept
├── revoke_scrypt_api_keys.py # Names the API keys still stored as scrypt, revokes them on request
└── prune_key_usage.py # Deletes the API-key usage rows past KEY_USAGE_RETENTION_DAYS
```
From 77ce33ed1249291487dc7a47f6b0391c77ab239c Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 27 Oct 2026 13:24:13 -0300
Subject: [PATCH 03/71] audit the environment the way production would from a
backend script
---
backend/scripts/validate_env.py | 61 ++++++
.../tests/unit/scripts/test_validate_env.py | 176 ++++++++++++++++++
docs/user-guide/project-structure.md | 4 +-
3 files changed, 240 insertions(+), 1 deletion(-)
create mode 100644 backend/scripts/validate_env.py
create mode 100644 backend/tests/unit/scripts/test_validate_env.py
diff --git a/backend/scripts/validate_env.py b/backend/scripts/validate_env.py
new file mode 100644
index 00000000..b1a1bccf
--- /dev/null
+++ b/backend/scripts/validate_env.py
@@ -0,0 +1,61 @@
+"""Audit this environment the way production would.
+
+Run it from ``backend/``:
+
+ python -m scripts.validate_env
+
+The settings are audited as a copy whose ``ENVIRONMENT`` reads ``production``, whatever the
+configured one says, so a development or staging configuration is held to the gate that
+stops a production boot, and a finding that names an environment names the one it was
+checked for.
+
+It exits 1 when anything critical is found, and 0 otherwise. Warnings are printed and
+exit 0: they are worth reading, not worth refusing a boot over.
+"""
+
+import sys
+from pathlib import Path
+
+backend_dir = Path(__file__).parent.parent
+sys.path.append(str(backend_dir))
+
+from src.infrastructure.config.settings import EnvironmentOption, get_settings # noqa: E402
+from src.infrastructure.security.production_validator import ProductionSecurityValidator # noqa: E402
+
+
+def audit() -> tuple[list[str], list[str]]:
+ """The critical findings and the warnings, for these settings read as production."""
+ as_production = get_settings().model_copy(update={"ENVIRONMENT": EnvironmentOption.PRODUCTION})
+
+ return ProductionSecurityValidator(as_production).audit()
+
+
+def report(critical: list[str], warnings: list[str]) -> None:
+ """Print what the audit found, grouped, or say that it found nothing."""
+ if not critical and not warnings:
+ print("No issues found. Configuration would pass production validation.")
+
+ return
+
+ if critical:
+ print(f"Critical ({len(critical)}):")
+ for finding in critical:
+ print(f" • {finding}")
+
+ if warnings:
+ if critical:
+ print()
+ print(f"Warnings ({len(warnings)}):")
+ for finding in warnings:
+ print(f" • {finding}")
+
+
+def main() -> int:
+ critical, warnings = audit()
+ report(critical, warnings)
+
+ return 1 if critical else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/backend/tests/unit/scripts/test_validate_env.py b/backend/tests/unit/scripts/test_validate_env.py
new file mode 100644
index 00000000..13bf5638
--- /dev/null
+++ b/backend/tests/unit/scripts/test_validate_env.py
@@ -0,0 +1,176 @@
+"""What the environment audit reports, and what it exits with.
+
+The audit answers one question: what would production refuse about this configuration?
+It therefore reads the settings as production whatever ``ENVIRONMENT`` says, so that a
+development or staging configuration is held to the same gate, and so that a finding that
+names an environment names the one it was checked for.
+"""
+
+import os
+import secrets
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from scripts.validate_env import audit, main
+from src.infrastructure.config.settings import EnvironmentOption, Settings
+
+BACKEND = Path(__file__).resolve().parents[3]
+
+PRODUCTION_SHAPED: dict[str, Any] = {
+ "ENVIRONMENT": EnvironmentOption.PRODUCTION,
+ "CREATE_TABLES_ON_STARTUP": False,
+ "EMAIL_BACKEND": "smtp",
+ "EMAIL_SMTP_HOST": "smtp.example.com",
+ "FRONTEND_URL": "https://app.example.com",
+}
+"""The settings whose defaults describe development rather than the production these stand for."""
+
+
+def _settings(**overrides: Any) -> Settings:
+ return Settings(**(PRODUCTION_SHAPED | overrides))
+
+
+def _audited(monkeypatch, settings: Settings) -> None:
+ """Answer the script with these settings instead of the ones the environment holds."""
+ monkeypatch.setattr("scripts.validate_env.get_settings", lambda: settings)
+
+
+def _strong() -> dict[str, Any]:
+ return {
+ "SECRET_KEY": secrets.token_hex(32),
+ "POSTGRES_PASSWORD": "a-strong-database-password",
+ "CORS_ORIGINS": "https://app.example.com",
+ "ADMIN_ENABLED": False,
+ "DEBUG": False,
+ "OPENAPI_URL": "",
+ "CACHE_REDIS_PASSWORD": "redis-password",
+ "RATE_LIMITER_REDIS_PASSWORD": "redis-password",
+ "SESSION_SECURE_COOKIES": True,
+ "SESSION_BACKEND": "redis",
+ "RATE_LIMITER_BACKEND": "redis",
+ }
+
+
+def test_a_clean_configuration_says_so(monkeypatch, capsys):
+ _audited(monkeypatch, _settings(**_strong()))
+
+ code = main()
+
+ assert code == 0
+ assert "No issues found" in capsys.readouterr().out
+
+
+def test_a_weak_configuration_is_refused_and_named(monkeypatch, capsys):
+ """Settings the validator really refuses come out as critical findings that name them."""
+ _audited(monkeypatch, _settings(SECRET_KEY="insecure-secret-key-change-this", POSTGRES_PASSWORD="postgres"))
+
+ code = main()
+
+ printed = capsys.readouterr().out
+ assert code == 1
+ assert "SECRET_KEY" in printed
+ assert "Database is using default credentials" in printed
+
+
+def test_warnings_are_reported_even_when_something_is_critical(monkeypatch, capsys):
+ """The warnings used to be computed only when nothing critical was found."""
+ _audited(monkeypatch, _settings(SECRET_KEY="insecure-secret-key-change-this"))
+
+ code = main()
+
+ printed = capsys.readouterr().out
+ assert code == 1
+ assert "Critical (" in printed
+ assert "Warnings (" in printed
+
+
+def test_warnings_alone_do_not_fail_the_audit(monkeypatch, capsys):
+ """A warning is something to look at, not something that would stop a boot."""
+ _audited(monkeypatch, _settings(**(_strong() | {"CACHE_REDIS_PASSWORD": ""})))
+
+ code = main()
+
+ printed = capsys.readouterr().out
+ assert code == 0
+ assert "Warnings (" in printed
+ assert "Critical (" not in printed
+
+
+def test_every_finding_names_the_environment_it_is_checked_for(monkeypatch, capsys):
+ """Audited as production, a finding that names a development environment is a lie."""
+ _audited(monkeypatch, _settings(ENVIRONMENT=EnvironmentOption.DEVELOPMENT, EMAIL_BACKEND="console"))
+
+ main()
+
+ printed = capsys.readouterr().out
+ assert "in production" in printed
+ assert "in development" not in printed
+
+
+def test_the_audited_settings_carry_the_environment_as_the_app_reads_it(monkeypatch):
+ """The app factory and the logger read ``ENVIRONMENT.value``, which a plain string has not."""
+ handed: list[Settings] = []
+ _audited(monkeypatch, _settings(ENVIRONMENT=EnvironmentOption.DEVELOPMENT))
+
+ class _Validator:
+ def __init__(self, settings: Settings):
+ handed.append(settings)
+
+ def audit(self) -> tuple[list[str], list[str]]:
+ return [], []
+
+ monkeypatch.setattr("scripts.validate_env.ProductionSecurityValidator", _Validator)
+ audit()
+
+ assert handed[0].ENVIRONMENT.value == "production"
+
+
+def _run(environment: dict[str, str]) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ [sys.executable, "-m", "scripts.validate_env"],
+ cwd=BACKEND,
+ env={
+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),
+ "HOME": os.environ.get("HOME", "/tmp"),
+ "PYTEST_VERSION": os.environ.get("PYTEST_VERSION", "1"),
+ **environment,
+ },
+ capture_output=True,
+ text=True,
+ timeout=120,
+ )
+
+
+@pytest.mark.parametrize(
+ ("secret", "code"),
+ [("insecure-secret-key-change-this", 1), (secrets.token_hex(32), 0)],
+)
+def test_it_runs_as_a_module_and_exits_on_what_it_found(secret: str, code: int):
+ """``python -m scripts.validate_env`` is what the blueprint declares as a command."""
+ environment = {
+ "PYTHONPATH": str(BACKEND),
+ "ENVIRONMENT": "development",
+ "SECRET_KEY": secret,
+ "POSTGRES_PASSWORD": "a-strong-database-password",
+ "CORS_ORIGINS": "https://app.example.com",
+ "ADMIN_ENABLED": "false",
+ "DEBUG": "false",
+ "OPENAPI_URL": "",
+ "CACHE_REDIS_PASSWORD": "redis-password",
+ "RATE_LIMITER_REDIS_PASSWORD": "redis-password",
+ "SESSION_SECURE_COOKIES": "true",
+ "CREATE_TABLES_ON_STARTUP": "false",
+ "EMAIL_BACKEND": "smtp",
+ "EMAIL_SMTP_HOST": "smtp.example.com",
+ "FRONTEND_URL": "https://app.example.com",
+ "SESSION_BACKEND": "redis",
+ "RATE_LIMITER_BACKEND": "redis",
+ }
+
+ result = _run(environment)
+
+ assert result.returncode == code, result.stdout + result.stderr
diff --git a/docs/user-guide/project-structure.md b/docs/user-guide/project-structure.md
index cf31af4b..c0417621 100644
--- a/docs/user-guide/project-structure.md
+++ b/docs/user-guide/project-structure.md
@@ -39,7 +39,8 @@ backend/
│ ├── revoke_scrypt_api_keys.py
│ ├── seeders.py # The seeders the selected features contribute
│ ├── setup_initial_data.py
-│ └── unlock_account.py
+│ ├── unlock_account.py
+│ └── validate_env.py # Audits the environment the way production would
├── src/ # Application source (the three layers below)
└── tests/ # Test suite (unit + integration)
```
@@ -210,6 +211,7 @@ scripts/
├── canonicalize_emails.py # One-off repair for addresses stored with case or spaces
├── unlock_account.py # Clears the login lockout one account is held in
├── gen_secret.py # Prints a SECRET_KEY the project's own rules accept
+├── validate_env.py # Audits the environment the way production would
├── revoke_scrypt_api_keys.py # Names the API keys still stored as scrypt, revokes them on request
└── prune_key_usage.py # Deletes the API-key usage rows past KEY_USAGE_RETENTION_DAYS
```
From 4778e01966423057ec0a10f7565103940774d254 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 27 Oct 2026 15:36:20 -0300
Subject: [PATCH 04/71] describe the blueprint, its dependencies, its presets
and its verify sets
---
backend/tests/unit/test_blueprint_catalog.py | 146 +++++++++++++++++++
blueprint.toml | 80 ++++++++++
2 files changed, 226 insertions(+)
create mode 100644 backend/tests/unit/test_blueprint_catalog.py
create mode 100644 blueprint.toml
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
new file mode 100644
index 00000000..f2811f12
--- /dev/null
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -0,0 +1,146 @@
+"""The catalog describes this repository, and `tools/removal_drill.py` is what it describes.
+
+`blueprint.toml` is read by fastro, which isn't a dependency here yet, so nothing in this
+file imports it: the rules it checks are transcribed from the catalog spec, and the facts it
+checks against come from the drill, which is the repository's own account of its features.
+
+This file goes when `fastro blueprint lint` and `fastro blueprint verify` replace the drill.
+"""
+
+import importlib.util
+import re
+import sys
+import tomllib
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+
+CATALOG = REPO_ROOT / "blueprint.toml"
+BACKEND_PYPROJECT = REPO_ROOT / "backend" / "pyproject.toml"
+
+FEATURE_NAME = re.compile(r"^[a-z][a-z0-9_]*$")
+"""Spec 1.2. Written out rather than imported, because fastro is not a dependency yet."""
+
+BLUEPRINT_NAME = re.compile(r"^[a-z][a-z0-9-]*$")
+
+NOT_YET_WRITTEN = {"fastro.toml"}
+"""`fastro.toml` is declared in the catalog before it exists."""
+
+
+def _catalog() -> dict[str, Any]:
+ with CATALOG.open("rb") as handle:
+ return tomllib.load(handle)
+
+
+def _drill():
+ """The drill's manifest, loaded as a module: its dataclasses need it in ``sys.modules``."""
+ spec = importlib.util.spec_from_file_location("removal_drill_manifest", REPO_ROOT / "tools" / "removal_drill.py")
+ assert spec is not None and spec.loader is not None
+ manifest = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = manifest
+ spec.loader.exec_module(manifest)
+
+ return manifest
+
+
+def test_the_catalog_parses():
+ assert _catalog()["blueprint"]["name"] == "fastro"
+
+
+def test_it_names_itself_the_way_the_spec_allows():
+ blueprint = _catalog()["blueprint"]
+
+ assert BLUEPRINT_NAME.match(blueprint["name"])
+ assert blueprint["schema"] == 1
+ assert blueprint["python_root"] == "backend"
+ assert blueprint["import_root"] == "src"
+
+
+def test_the_version_is_the_one_the_backend_ships():
+ """FR002: a release tag is a blueprint release, so the two versions move together."""
+ with BACKEND_PYPROJECT.open("rb") as handle:
+ backend = tomllib.load(handle)
+
+ assert _catalog()["blueprint"]["version"] == backend["project"]["version"]
+
+
+def test_development_builds_of_the_tool_can_read_it():
+ """Spec 1.6: `0.1.0.dev0` sorts below `0.1`, so the lower bound has to name it."""
+ assert _catalog()["blueprint"]["requires_fastro"] == ">=0.1.0.dev0,<0.2"
+
+
+def test_the_core_dependencies_are_the_ones_the_backend_declares():
+ """The catalog carries the backend's lists until they are split per feature."""
+ with BACKEND_PYPROJECT.open("rb") as handle:
+ backend = tomllib.load(handle)
+
+ dependencies = _catalog()["blueprint"]["dependencies"]
+
+ assert dependencies["runtime"] == backend["project"]["dependencies"]
+ assert dependencies["dev"] == backend["project"]["optional-dependencies"]["dev"]
+
+
+@pytest.mark.parametrize("entry", sorted(_catalog()["blueprint"]["blueprint_only"]))
+def test_every_blueprint_only_path_is_written_the_way_the_spec_reads_them(entry: str):
+ """Spec 1.1: a trailing slash means the subtree, and without one it is a single file.
+
+ `docs` rather than `docs/` would name one file nobody has, and the whole tree would
+ reach projects.
+ """
+ assert not entry.startswith("/")
+ assert ".." not in Path(entry).parts
+ assert entry.endswith("/") == (REPO_ROOT / entry).is_dir()
+
+
+@pytest.mark.parametrize("entry", sorted(set(_catalog()["blueprint"]["blueprint_only"]) - NOT_YET_WRITTEN))
+def test_every_blueprint_only_path_is_one_this_repo_has(entry: str):
+ """A path that no longer exists keeps a file out of projects that nobody meant to keep out."""
+ assert (REPO_ROOT / entry).exists()
+
+
+def test_the_things_projects_must_not_receive_are_listed():
+ """The catalog, the drill, the docs and the tool's own tree belong to the blueprint only."""
+ listed = set(_catalog()["blueprint"]["blueprint_only"])
+
+ assert {"blueprint/", "blueprint.toml", "fastro.toml", "docs/", "tools/", "cli/"} <= listed
+ assert "backend/tests/unit/test_blueprint_catalog.py" in listed
+
+
+def test_the_docs_reading_tests_stay_in_the_blueprint():
+ """They read `docs/`, which projects don't get, so they would fail in one."""
+ listed = set(_catalog()["blueprint"]["blueprint_only"])
+
+ for name in ("test_docs_imports", "test_docs_recipes", "test_docs_scripts", "test_docs_wiring", "test_image_contents"):
+ assert f"backend/tests/unit/{name}.py" in listed
+
+
+def test_the_verify_sets_are_the_drills_presets():
+ """`everything` is implied by the spec, so the named sets are the other eight."""
+ expected = {name: list(features) for name, features in _drill().PRESETS.items() if name != "everything"}
+
+ assert _catalog()["verify"]["sets"] == expected
+
+
+def test_every_preset_is_closed_under_what_its_features_require():
+ """A preset that names tier_limits without tiers would generate a project that can't import."""
+ requires = _drill().REQUIRES
+
+ for name, features in _catalog()["presets"].items():
+ for feature in features:
+ assert set(requires.get(feature, ())) <= set(features), f"{name} is missing what {feature} requires"
+
+
+def test_the_presets_name_features_this_repository_has():
+ known = set(_drill().FEATURES)
+
+ for name, features in _catalog()["presets"].items():
+ assert set(features) <= known, name
+ for feature in features:
+ assert FEATURE_NAME.match(feature)
+
+
+def test_full_is_every_feature():
+ assert sorted(_catalog()["presets"]["full"]) == sorted(_drill().FEATURES)
diff --git a/blueprint.toml b/blueprint.toml
new file mode 100644
index 00000000..670519e4
--- /dev/null
+++ b/blueprint.toml
@@ -0,0 +1,80 @@
+[blueprint]
+name = "fastro"
+version = "0.20.0"
+schema = 1
+requires_fastro = ">=0.1.0.dev0,<0.2"
+python_root = "backend"
+import_root = "src"
+blueprint_only = [
+ ".github/",
+ "CODE_OF_CONDUCT.md",
+ "CONTRIBUTING.md",
+ "backend/tests/unit/test_blueprint_catalog.py",
+ "backend/tests/unit/test_docs_imports.py",
+ "backend/tests/unit/test_docs_recipes.py",
+ "backend/tests/unit/test_docs_scripts.py",
+ "backend/tests/unit/test_docs_wiring.py",
+ "backend/tests/unit/test_image_contents.py",
+ "blueprint/",
+ "blueprint.toml",
+ "cli/",
+ "docs/",
+ "fastro.toml",
+ "tools/",
+ "uv.lock",
+ "zensical.toml",
+]
+
+[blueprint.dependencies]
+runtime = [
+ "aiomcache>=0.8.2",
+ "aiosqlite>=0.21.0",
+ "alembic>=1.16.4",
+ "anyio>=4.15.1",
+ "asyncpg>=0.30.0",
+ "crudauth[all]>=0.8.2,<0.9.0",
+ "cryptography>=42.0.0",
+ "faker>=37.1.0",
+ "fastapi[standard]>=0.115.8",
+ "fastcrud>=0.21.0",
+ "greenlet>=3.1.1",
+ "httpx>=0.28.1",
+ "itsdangerous>=2.2.0",
+ "jinja2>=3.1.6",
+ "pydantic>=2.10.6",
+ "pydantic-settings>=2.14.2",
+ "redis>=6.1.0",
+ "sqladmin>=0.28.0",
+ "sqlalchemy>=2.0.37",
+ "starlette>=1.3.1",
+ "taskiq>=0.11.20",
+ "taskiq-redis>=1.1.2",
+ "taskiq-aio-pika>=0.4.3",
+ "user-agents>=2.2.0",
+]
+dev = [
+ "mypy>=1.14.1",
+ "ruff>=0.9.4",
+ "pytest>=8.3.5",
+ "pytest-asyncio>=0.25.3",
+ "pytest-mock>=3.14.0",
+ "testcontainers[postgres]>=4.10.0",
+ "pytest-xdist[psutil]>=3.8.0",
+ "taskiq[reload]>=0.11.20",
+ "pre-commit>=4.0.0",
+]
+
+[presets]
+minimal = ["accounts"]
+standard = ["accounts", "rbac", "ratelimit", "tiers", "tier_limits", "admin", "cache"]
+full = ["accounts", "rbac", "ratelimit", "tiers", "tier_limits", "api_keys", "admin", "cache", "taskiq"]
+
+[verify.sets]
+core-only = []
+core-taskiq = ["taskiq"]
+accounts-only = ["accounts"]
+accounts-rbac = ["accounts", "rbac"]
+accounts-admin = ["accounts", "admin"]
+accounts-api-keys = ["accounts", "api_keys"]
+accounts-rbac-tiers = ["accounts", "rbac", "tiers", "ratelimit"]
+accounts-cache-taskiq = ["accounts", "cache", "taskiq"]
From 0fdec4ebb369ba62a87a78f2f5d3b6948b06fd81 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 27 Oct 2026 22:34:54 -0300
Subject: [PATCH 05/71] declare the points features contribute to, and what
core contributes
---
backend/tests/unit/test_blueprint_catalog.py | 91 ++++++++++++++++++
blueprint.toml | 98 ++++++++++++++++++++
2 files changed, 189 insertions(+)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index f2811f12..5ec84c4c 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -7,6 +7,7 @@
This file goes when `fastro blueprint lint` and `fastro blueprint verify` replace the drill.
"""
+import ast
import importlib.util
import re
import sys
@@ -144,3 +145,93 @@ def test_the_presets_name_features_this_repository_has():
def test_full_is_every_feature():
assert sorted(_catalog()["presets"]["full"]) == sorted(_drill().FEATURES)
+
+
+ONE_OF_EACH = {"root_routers", "docs_guard", "email_sender", "cache_decorator"}
+"""The points a project may fill once: each renders as a single value with a fallback."""
+
+
+def _ref(text: str) -> tuple[str, str, str]:
+ """A spec 1.4 ref, as (module, attribute, local name)."""
+ body, _, alias = text.partition(" as ")
+ module, _, attribute = body.partition(":")
+
+ return module, attribute, alias or attribute
+
+
+def _import_line(entry: str) -> str:
+ """The import a wiring file under ``src/wiring/`` gets for this ref.
+
+ Spec 2.8: a file under the import root imports relatively, so ``src.a.b:name`` is
+ written ``from ..a.b import name``, and an alias keeps its own statement.
+ """
+ module, attribute, alias = _ref(entry)
+ imported = attribute if alias == attribute else f"{attribute} as {alias}"
+
+ return f"from ..{module.removeprefix('src.')} import {imported}"
+
+
+def _defines(module: str, attribute: str) -> bool:
+ """Whether ``module`` defines ``attribute`` at its top level, read without importing."""
+ path = REPO_ROOT / "backend" / Path(*module.split(".")).with_suffix(".py")
+ if not path.exists():
+ return False
+
+ tree = ast.parse(path.read_text())
+ for node in tree.body:
+ if isinstance(node, ast.Assign) and any(
+ isinstance(target, ast.Name) and target.id == attribute for target in node.targets
+ ):
+ return True
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == attribute:
+ return True
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef) and node.name == attribute:
+ return True
+ if isinstance(node, ast.ImportFrom | ast.Import) and any(
+ (alias.asname or alias.name) == attribute for alias in node.names
+ ):
+ return True
+
+ return False
+
+
+@pytest.mark.parametrize("name", sorted(_catalog()["points"]))
+def test_every_point_is_declared_the_way_the_spec_asks(name: str):
+ """Spec 2.3: a cardinality, and one line saying what the point collects."""
+ point = _catalog()["points"][name]
+
+ assert FEATURE_NAME.match(name)
+ assert point["cardinality"] in {"many", "one"}
+ assert point["doc"].strip() == point["doc"]
+ assert "\n" not in point["doc"]
+
+
+def test_the_points_a_project_may_fill_once_are_the_ones_rendered_as_a_value():
+ """A second contribution to one of these is an error, so the set has to be exact."""
+ points = _catalog()["points"]
+ single = {name for name, point in points.items() if point["cardinality"] == "one"}
+
+ assert single == ONE_OF_EACH
+
+
+def test_the_database_checks_belong_to_no_feature():
+ """The drill wires them whatever is selected, so the catalog gives them to core."""
+ core = _catalog()["core"]["contributes"]["critical_readiness"]
+ with_nothing_selected = _drill()._wiring_hooks(set())
+ rendered = with_nothing_selected.split("CRITICAL_READINESS_CHECKS: tuple[ReadinessCheck, ...] = (")[1]
+
+ assert [_ref(entry)[2] for entry in core] == [name.strip() for name in rendered.split(")")[0].split(",") if name.strip()]
+
+
+@pytest.mark.parametrize("entry", _catalog()["core"]["contributes"]["critical_readiness"])
+def test_every_core_contribution_is_imported_the_way_the_drill_imports_it(entry: str):
+ """The names alone would accept a ref that kept the alias and changed the module."""
+ assert _import_line(entry) in _drill()._wiring_hooks(set())
+
+
+@pytest.mark.parametrize("entry", _catalog()["core"]["contributes"]["critical_readiness"])
+def test_every_core_contribution_names_something_that_exists(entry: str):
+ """Spec 1.4: the attribute has to be defined at the module's top level."""
+ module, attribute, _ = _ref(entry)
+
+ assert _defines(module, attribute), entry
diff --git a/blueprint.toml b/blueprint.toml
index 670519e4..1d2a4cdd 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -78,3 +78,101 @@ accounts-admin = ["accounts", "admin"]
accounts-api-keys = ["accounts", "api_keys"]
accounts-rbac-tiers = ["accounts", "rbac", "tiers", "ratelimit"]
accounts-cache-taskiq = ["accounts", "cache", "taskiq"]
+
+[core.contributes]
+critical_readiness = [
+ "src.infrastructure.database.health:readiness as database_readiness",
+ "src.infrastructure.database.health:schema_readiness",
+]
+
+[points.routers]
+cardinality = "many"
+doc = "A router the API mounts under its version prefix."
+
+[points.root_routers]
+cardinality = "one"
+doc = "The routers mounted beside the API rather than under its prefix."
+
+[points.api_throttle]
+cardinality = "many"
+doc = "A dependency every throttled route runs before answering."
+
+[points.lifecycles]
+cardinality = "many"
+doc = "Startup and shutdown work, started in order and torn down in reverse."
+
+[points.installers]
+cardinality = "many"
+doc = "Something that installs itself on the app as the app is built."
+
+[points.docs_guard]
+cardinality = "one"
+doc = "The dependency that guards the documentation routes where they are served."
+
+[points.settings]
+cardinality = "many"
+doc = "A settings mixin the project's Settings inherits, with the core one last."
+
+[points.permission_sources]
+cardinality = "many"
+doc = "Answers which permissions an account holds."
+
+[points.rate_limit_resolvers]
+cardinality = "many"
+doc = "Answers the limit for a request, or declines to."
+
+[points.tier_delete_guards]
+cardinality = "many"
+doc = "Answers why a tier cannot be deleted yet."
+
+[points.tier_delete_releases]
+cardinality = "many"
+doc = "Releases the rows a feature keeps for a tier that is being deleted."
+
+[points.critical_readiness]
+cardinality = "many"
+doc = "A dependency a request needs, so readiness answers 503 while it is unreachable."
+
+[points.informational_readiness]
+cardinality = "many"
+doc = "A dependency readiness reports on without refusing traffic over it."
+
+[points.user_model]
+cardinality = "many"
+doc = "Columns a feature adds to the user model."
+
+[points.user_schema]
+cardinality = "many"
+doc = "Fields a feature adds to the user schemas."
+
+[points.admin_views]
+cardinality = "many"
+doc = "A model view the admin panel registers."
+
+[points.email_sender]
+cardinality = "one"
+doc = "The sender the account emails go out through."
+
+[points.cache_decorator]
+cardinality = "one"
+doc = "The decorator a route caches its response with."
+
+[points.task_modules]
+cardinality = "many"
+doc = "A module whose background tasks the worker registers."
+
+[points.table_modules]
+cardinality = "many"
+doc = "A module outside src/modules that declares tables on the metadata."
+
+[points.extra_transports]
+cardinality = "many"
+doc = "An authentication transport registered beside the session one."
+
+[points.seeders]
+cardinality = "many"
+doc = "A step the initial-data script runs, in order."
+
+[points.test_plugins]
+cardinality = "many"
+doc = "A fixture module pytest loads for the features the project carries."
From 339d7cc97e3cb59ab4882be93fd25af8451631c8 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 27 Oct 2026 22:40:35 -0300
Subject: [PATCH 06/71] declare the points features contribute to, and what
core contributes
---
backend/tests/unit/test_blueprint_catalog.py | 44 ++++++++++++++++----
1 file changed, 37 insertions(+), 7 deletions(-)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 5ec84c4c..6aa2a26e 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -159,16 +159,31 @@ def _ref(text: str) -> tuple[str, str, str]:
return module, attribute, alias or attribute
-def _import_line(entry: str) -> str:
- """The import a wiring file under ``src/wiring/`` gets for this ref.
+def _binding(entry: str) -> tuple[str, str, str]:
+ """What a wiring file under ``src/wiring/`` binds for this ref: (module, attribute, name).
- Spec 2.8: a file under the import root imports relatively, so ``src.a.b:name`` is
- written ``from ..a.b import name``, and an alias keeps its own statement.
+ Spec 2.8: a file under the import root imports relatively, so ``src.a.b:name`` is read
+ from ``..a.b``.
"""
module, attribute, alias = _ref(entry)
- imported = attribute if alias == attribute else f"{attribute} as {alias}"
- return f"from ..{module.removeprefix('src.')} import {imported}"
+ return ".." + module.removeprefix("src."), attribute, alias
+
+
+def _bindings(source: str) -> set[tuple[str, str, str]]:
+ """Every (module, attribute, local name) the imports in ``source`` bind.
+
+ Read with ``ast`` rather than by matching text: the drill merges names from one module
+ into a single statement and wraps long ones over several lines, and neither shape
+ contains the single-name line a substring check would look for.
+ """
+ bindings: set[tuple[str, str, str]] = set()
+ for node in ast.parse(source).body:
+ if isinstance(node, ast.ImportFrom):
+ module = "." * node.level + (node.module or "")
+ bindings.update((module, alias.name, alias.asname or alias.name) for alias in node.names)
+
+ return bindings
def _defines(module: str, attribute: str) -> bool:
@@ -226,7 +241,7 @@ def test_the_database_checks_belong_to_no_feature():
@pytest.mark.parametrize("entry", _catalog()["core"]["contributes"]["critical_readiness"])
def test_every_core_contribution_is_imported_the_way_the_drill_imports_it(entry: str):
"""The names alone would accept a ref that kept the alias and changed the module."""
- assert _import_line(entry) in _drill()._wiring_hooks(set())
+ assert _binding(entry) in _bindings(_drill()._wiring_hooks(set()))
@pytest.mark.parametrize("entry", _catalog()["core"]["contributes"]["critical_readiness"])
@@ -235,3 +250,18 @@ def test_every_core_contribution_names_something_that_exists(entry: str):
module, attribute, _ = _ref(entry)
assert _defines(module, attribute), entry
+
+
+def test_the_import_reader_sees_a_name_the_drill_merges():
+ """Two names from one module become one statement, whose second name no line contains."""
+ bindings = _bindings(_drill()._wiring_hooks({"accounts"}))
+
+ assert ("..infrastructure.auth.health", "limiter_readiness", "limiter_readiness") in bindings
+ assert ("..infrastructure.auth.health", "sessions_readiness", "sessions_readiness") in bindings
+
+
+def test_the_import_reader_sees_a_name_the_drill_wraps():
+ """The composition import is written over several lines, so no single line holds it."""
+ bindings = _bindings(_drill()._wiring_hooks(set()))
+
+ assert ("..infrastructure.composition", "ReadinessCheck", "ReadinessCheck") in bindings
From 90355bee0b8d307bc408d644651781c8143f7cee Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 27 Oct 2026 23:26:31 -0300
Subject: [PATCH 07/71] check the catalog against the rules spec rev 1.7
tightens
---
backend/tests/unit/test_blueprint_catalog.py | 15 +++++++++++++--
1 file changed, 13 insertions(+), 2 deletions(-)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 6aa2a26e..e4182bc9 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -27,6 +27,9 @@
BLUEPRINT_NAME = re.compile(r"^[a-z][a-z0-9-]*$")
+SET_NAME = re.compile(r"^[a-z][a-z0-9_-]*$")
+"""Spec 1.2. A preset or a verify set may carry a hyphen, which a feature name may not."""
+
NOT_YET_WRITTEN = {"fastro.toml"}
"""`fastro.toml` is declared in the catalog before it exists."""
@@ -119,10 +122,18 @@ def test_the_docs_reading_tests_stay_in_the_blueprint():
def test_the_verify_sets_are_the_drills_presets():
- """`everything` is implied by the spec, so the named sets are the other eight."""
+ """`everything` is implied by the spec, and declaring it is an error, so the sets are the other eight."""
expected = {name: list(features) for name, features in _drill().PRESETS.items() if name != "everything"}
+ sets = _catalog()["verify"]["sets"]
+
+ assert "everything" not in sets
+ assert sets == expected
+
- assert _catalog()["verify"]["sets"] == expected
+@pytest.mark.parametrize("name", sorted(_catalog()["presets"]) + sorted(_catalog()["verify"]["sets"]))
+def test_every_preset_and_verify_set_is_named_the_way_the_spec_allows(name: str):
+ """Spec 1.2: a name here is lower case and may carry a hyphen, so `accounts-only` reads as one."""
+ assert SET_NAME.match(name)
def test_every_preset_is_closed_under_what_its_features_require():
From 80839e9da6ce41767b4cd191292f12ce8dce94b7 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 27 Oct 2026 23:26:37 -0300
Subject: [PATCH 08/71] draw the test's key inside the test, not into its id
---
backend/tests/unit/scripts/test_validate_env.py | 14 ++++++++------
1 file changed, 8 insertions(+), 6 deletions(-)
diff --git a/backend/tests/unit/scripts/test_validate_env.py b/backend/tests/unit/scripts/test_validate_env.py
index 13bf5638..821803a5 100644
--- a/backend/tests/unit/scripts/test_validate_env.py
+++ b/backend/tests/unit/scripts/test_validate_env.py
@@ -145,12 +145,14 @@ def _run(environment: dict[str, str]) -> subprocess.CompletedProcess[str]:
)
-@pytest.mark.parametrize(
- ("secret", "code"),
- [("insecure-secret-key-change-this", 1), (secrets.token_hex(32), 0)],
-)
-def test_it_runs_as_a_module_and_exits_on_what_it_found(secret: str, code: int):
- """``python -m scripts.validate_env`` is what the blueprint declares as a command."""
+@pytest.mark.parametrize(("key", "code"), [("placeholder", 1), ("drawn", 0)])
+def test_it_runs_as_a_module_and_exits_on_what_it_found(key: str, code: int):
+ """``python -m scripts.validate_env`` is what the blueprint declares as a command.
+
+ The key is drawn here rather than in the parameter list, where it would land in the
+ test's id: ``pytest -n auto`` refuses a run whose workers collected different ids.
+ """
+ secret = secrets.token_hex(32) if key == "drawn" else "insecure-secret-key-change-this"
environment = {
"PYTHONPATH": str(BACKEND),
"ENVIRONMENT": "development",
From 4a062654f7bb151a34f53e4456b91df92c898154 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 27 Oct 2026 23:26:40 -0300
Subject: [PATCH 09/71] run the blueprint's tests when pytest runs from the
workspace root
---
pyproject.toml | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/pyproject.toml b/pyproject.toml
index 7aa03036..542c7d72 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,6 +10,11 @@
# uv sync --all-packages --all-extras # one venv shared by all members
# uv run bp ... # runs the CLI from cli/, from any cwd
# cd backend && uv run --no-sync pytest # runs the backend test suite
+# uv run --no-sync pytest # runs the blueprint's own tests
+#
+# Each package's tests run under their own root: `backend/tests/conftest.py` declares
+# `pytest_plugins`, which pytest only reads from the root's top-level conftest, and `cli`
+# has to be importable. So the root's testpaths name the blueprint's tests and nothing else.
#
# To install `bp` machine-wide so it works outside this repo:
#
@@ -24,6 +29,9 @@ requires-python = ">=3.11"
[tool.uv.workspace]
members = ["backend", "cli"]
+[tool.pytest.ini_options]
+testpaths = ["blueprint/tests"]
+
[tool.ruff]
line-length = 128
From 8bd2c1e9b4a5a9f13a37b2035728ee0568db878b Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Wed, 28 Oct 2026 12:43:27 -0300
Subject: [PATCH 10/71] declare the nine features, what they need and what they
own
---
backend/tests/unit/test_blueprint_catalog.py | 138 +++++++++++++++++
blueprint.toml | 155 +++++++++++++++++++
2 files changed, 293 insertions(+)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index e4182bc9..ea96f254 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -9,6 +9,7 @@
import ast
import importlib.util
+import itertools
import re
import sys
import tomllib
@@ -276,3 +277,140 @@ def test_the_import_reader_sees_a_name_the_drill_wraps():
bindings = _bindings(_drill()._wiring_hooks(set()))
assert ("..infrastructure.composition", "ReadinessCheck", "ReadinessCheck") in bindings
+
+
+GENERATED_BY_WIRING = "backend/src/wiring/admin.py"
+"""The drill deletes it with the admin feature; the catalog's `[[wiring]]` entry omits it instead."""
+
+
+def _declared(feature: dict[str, Any]) -> list[tuple[str, str | None]]:
+ """A feature's declared paths, each with the condition it is kept under, if any."""
+ paths: list[tuple[str, str | None]] = [(path.rstrip("/"), None) for path in feature.get("paths", ())]
+ for block in feature.get("when", ()):
+ paths.extend((path.rstrip("/"), block["if"]) for path in block.get("paths", ()))
+
+ return paths
+
+
+def _kept_by_the_catalog(features: dict[str, Any], chosen: set[str]) -> set[str]:
+ return {
+ path
+ for name, feature in features.items()
+ if name in chosen
+ for path, condition in _declared(feature)
+ if condition is None or condition in chosen
+ }
+
+
+def _kept_by_the_drill(manifest: Any, chosen: set[str]) -> set[str]:
+ """What `build` leaves on disk: a combination path needs both of its features."""
+ kept: set[str] = set()
+ for name, feature in manifest.FEATURES.items():
+ if name not in chosen:
+ continue
+
+ kept.update(path for path in feature.paths if path != GENERATED_BY_WIRING)
+ for partner, paths in feature.combination_paths.items():
+ if partner in chosen:
+ kept.update(paths)
+
+ return kept
+
+
+def _selections(manifest: Any) -> list[set[str]]:
+ """Every selection a project could carry: each subset of the features, closed under requires."""
+ closed = []
+ for size in range(len(manifest.FEATURES) + 1):
+ for combination in itertools.combinations(manifest.FEATURES, size):
+ selection = manifest._selected_from(combination)
+ if selection not in closed:
+ closed.append(selection)
+
+ return closed
+
+
+def test_the_features_are_the_ones_the_drill_knows():
+ """In the drill's order: spec 6.2 hands templates the selection in catalog order."""
+ assert list(_catalog()["features"]) == list(_drill().FEATURES)
+
+
+@pytest.mark.parametrize("name", sorted(_catalog()["features"]))
+def test_every_feature_is_declared_the_way_the_spec_asks(name: str):
+ """Spec 2.4: a one-line summary, and the heading the checklist groups it under."""
+ feature = _catalog()["features"][name]
+
+ assert FEATURE_NAME.match(name)
+ assert feature["summary"].strip() == feature["summary"]
+ assert "\n" not in feature["summary"]
+ assert feature["group"] in {"Accounts", "Operations"}
+
+
+def test_every_feature_requires_what_the_drill_says_it_requires():
+ """A requires that drifts would generate a project whose imports have nothing to bind."""
+ requires = _drill().REQUIRES
+
+ for name, feature in _catalog()["features"].items():
+ assert list(feature.get("requires", ())) == list(requires.get(name, ()))
+
+
+@pytest.mark.parametrize(
+ ("name", "condition"),
+ sorted((name, block["if"]) for name, feature in _catalog()["features"].items() for block in feature.get("when", ())),
+)
+def test_every_condition_names_a_feature_this_repository_has(name: str, condition: str):
+ """Spec 1.3: an unknown name is an error rather than something that reads as false."""
+ assert condition in _drill().FEATURES
+ assert condition != name
+
+
+@pytest.mark.parametrize(
+ "entry",
+ sorted(
+ {path for feature in _catalog()["features"].values() for path, _ in _declared(feature)},
+ ),
+)
+def test_every_feature_path_is_one_this_repo_has(entry: str):
+ """A path that no longer exists leaves a file in projects that nobody meant to keep."""
+ assert not entry.startswith("/")
+ assert ".." not in Path(entry).parts
+ assert (REPO_ROOT / entry).exists()
+
+
+@pytest.mark.parametrize("name", sorted(_catalog()["features"]))
+def test_a_directory_is_spelled_as_a_subtree_and_a_file_is_not(name: str):
+ """Spec 1.1: `src/modules/user` without the slash would name one file nobody has."""
+ for path in _catalog()["features"][name].get("paths", ()):
+ assert path.endswith("/") == (REPO_ROOT / path).is_dir(), path
+
+ for block in _catalog()["features"][name].get("when", ()):
+ for path in block.get("paths", ()):
+ assert path.endswith("/") == (REPO_ROOT / path).is_dir(), path
+
+
+def test_no_path_is_declared_twice():
+ """Spec 1.1: two declarations of the identical path are 'owned twice'."""
+ declared = [path for feature in _catalog()["features"].values() for path, _ in _declared(feature)]
+
+ assert sorted(declared) == sorted(set(declared))
+
+
+def test_the_generated_wiring_file_belongs_to_no_feature():
+ """It is written by `[[wiring]]`, which leaves it out of a project rather than deleting it."""
+ declared = {path for feature in _catalog()["features"].values() for path, _ in _declared(feature)}
+
+ assert GENERATED_BY_WIRING in _drill().FEATURES["admin"].paths
+ assert GENERATED_BY_WIRING not in declared
+
+
+def test_every_selection_keeps_the_files_the_drill_keeps():
+ """The catalog gives a shared file to the feature whose subtree holds it, and the drill to both.
+
+ `src/modules/user/admin.py` is admin's work inside accounts' package, and the drill lists it
+ under both. One declaration owns it here, so what's compared is the file surviving a
+ selection, not which feature spoke for it.
+ """
+ manifest = _drill()
+ features = _catalog()["features"]
+
+ for chosen in _selections(manifest):
+ assert _kept_by_the_catalog(features, chosen) == _kept_by_the_drill(manifest, chosen), sorted(chosen)
diff --git a/blueprint.toml b/blueprint.toml
index 1d2a4cdd..be8ff39b 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -176,3 +176,158 @@ doc = "A step the initial-data script runs, in order."
[points.test_plugins]
cardinality = "many"
doc = "A fixture module pytest loads for the features the project carries."
+
+[features.accounts]
+summary = "Users, sessions, CSRF, login lockout, OAuth"
+group = "Accounts"
+paths = [
+ "backend/scripts/canonicalize_emails.py",
+ "backend/scripts/create_first_superuser.py",
+ "backend/scripts/unlock_account.py",
+ "backend/src/infrastructure/auth/",
+ "backend/src/modules/user/",
+ "backend/tests/fixtures/accounts.py",
+ "backend/tests/integration/accounts/",
+ "backend/tests/integration/api/v1/users/",
+ "backend/tests/integration/auth/",
+ "backend/tests/unit/infrastructure/auth/",
+ "backend/tests/unit/modules/user/",
+ "backend/tests/unit/scripts/test_canonicalize_emails.py",
+ "backend/tests/unit/scripts/test_create_first_superuser.py",
+ "backend/tests/unit/scripts/test_setup_initial_data.py",
+ "backend/tests/unit/scripts/test_unlock_account.py",
+]
+
+[[features.accounts.when]]
+if = "admin"
+paths = [
+ "backend/src/modules/user/admin.py",
+ "backend/tests/unit/modules/user/test_admin.py",
+]
+
+[features.rbac]
+summary = "Roles and permissions"
+group = "Accounts"
+requires = ["accounts"]
+paths = [
+ "backend/src/modules/role/",
+ "backend/tests/integration/rbac/",
+ "backend/tests/unit/modules/role/",
+]
+
+[[features.rbac.when]]
+if = "admin"
+paths = [
+ "backend/src/modules/role/admin.py",
+ "backend/tests/unit/modules/role/test_admin.py",
+]
+
+[features.ratelimit]
+summary = "Per-caller API throttle"
+group = "Accounts"
+requires = ["accounts"]
+paths = [
+ "backend/src/infrastructure/ratelimit/",
+ "backend/tests/integration/ratelimit/",
+ "backend/tests/unit/infrastructure/ratelimit/",
+]
+
+[features.tiers]
+summary = "User tiers other features key off"
+group = "Accounts"
+requires = ["accounts"]
+paths = [
+ "backend/scripts/create_first_tier.py",
+ "backend/src/modules/tier/",
+ "backend/tests/fixtures/tiers.py",
+ "backend/tests/integration/tiers/",
+ "backend/tests/unit/modules/tier/",
+]
+
+[[features.tiers.when]]
+if = "admin"
+paths = [
+ "backend/src/modules/tier/admin.py",
+ "backend/tests/unit/modules/tier/test_admin.py",
+]
+
+[features.tier_limits]
+summary = "Per-tier rate limits"
+group = "Accounts"
+requires = ["tiers", "ratelimit"]
+paths = [
+ "backend/src/modules/rate_limit/",
+ "backend/tests/integration/tier_limits/",
+ "backend/tests/unit/modules/rate_limit/",
+]
+
+[features.api_keys]
+summary = "API keys: create, revoke, meter"
+group = "Accounts"
+requires = ["accounts"]
+paths = [
+ "backend/scripts/cleanup_api_key_json.py",
+ "backend/scripts/prune_key_usage.py",
+ "backend/scripts/revoke_scrypt_api_keys.py",
+ "backend/src/modules/api_keys/",
+ "backend/tests/integration/api/v1/api_keys/",
+ "backend/tests/unit/modules/api_keys/",
+]
+
+[[features.api_keys.when]]
+if = "ratelimit"
+paths = [
+ "backend/tests/integration/api_keys_ratelimit/",
+]
+
+[[features.api_keys.when]]
+if = "rbac"
+paths = [
+ "backend/tests/integration/api_keys_rbac/",
+]
+
+[[features.api_keys.when]]
+if = "taskiq"
+paths = [
+ "backend/src/modules/api_keys/tasks.py",
+ "backend/tests/unit/modules/api_keys/test_tasks.py",
+]
+
+[[features.api_keys.when]]
+if = "tier_limits"
+paths = [
+ "backend/tests/integration/api_keys_tiers/",
+]
+
+[features.admin]
+summary = "SQLAdmin panel at /admin"
+group = "Operations"
+requires = ["accounts"]
+paths = [
+ "backend/src/interfaces/admin/",
+ "backend/tests/unit/interfaces/admin/",
+]
+
+[features.cache]
+summary = "@cache over Redis or Memcached"
+group = "Operations"
+paths = [
+ "backend/src/infrastructure/cache/",
+ "backend/tests/unit/infrastructure/cache/",
+]
+
+[features.taskiq]
+summary = "Background tasks on Redis or RabbitMQ"
+group = "Operations"
+paths = [
+ "backend/src/infrastructure/taskiq/",
+ "backend/tests/unit/infrastructure/taskiq/",
+]
+
+[[features.taskiq.when]]
+if = "accounts"
+paths = [
+ "backend/src/infrastructure/taskiq/email.py",
+ "backend/tests/unit/infrastructure/taskiq/test_email.py",
+]
+
From 10327c39916a6d5b621f2055fbb7ce30e0c72e8d Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Wed, 28 Oct 2026 14:34:05 -0300
Subject: [PATCH 11/71] declare what each feature contributes, in what order,
and what it can be asked
---
backend/.env.example | 2 +
backend/tests/unit/test_blueprint_catalog.py | 401 +++++++++++++++++++
blueprint.toml | 100 +++++
3 files changed, 503 insertions(+)
diff --git a/backend/.env.example b/backend/.env.example
index 03b82981..791e7fe2 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -42,6 +42,7 @@ POSTGRES_POOL_RECYCLE=-1
# ===================================
CACHE_ENABLED=true
# Options: memcached, redis
+# @fastro option=cache.backend
CACHE_BACKEND=redis
# Client-side cache settings
@@ -132,6 +133,7 @@ KEY_USAGE_RETENTION_DAYS=90
# Taskiq Configuration
# ===================================
# Broker type: 'redis' or 'rabbitmq'
+# @fastro option=taskiq.broker
TASKIQ_BROKER_TYPE=redis
# How many times a task labelled retry_on_error=True runs in all, the first attempt
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index ea96f254..29c0cb28 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -414,3 +414,404 @@ def test_every_selection_keeps_the_files_the_drill_keeps():
for chosen in _selections(manifest):
assert _kept_by_the_catalog(features, chosen) == _kept_by_the_drill(manifest, chosen), sorted(chosen)
+
+
+POINTS: dict[str, tuple[str, str]] = {
+ "routers": ("_wiring_app", "ROUTER_MOUNTS"),
+ "root_routers": ("_wiring_app", "ROOT_ROUTERS"),
+ "api_throttle": ("_wiring_app", "API_THROTTLE"),
+ "lifecycles": ("_wiring_app", "LIFECYCLES"),
+ "installers": ("_wiring_app", "INSTALLERS"),
+ "docs_guard": ("_wiring_app", "DOCS_GUARD"),
+ "settings": ("_wiring_settings", "Settings"),
+ "permission_sources": ("_wiring_hooks", "PERMISSION_SOURCES"),
+ "rate_limit_resolvers": ("_wiring_hooks", "RATE_LIMIT_RESOLVERS"),
+ "tier_delete_guards": ("_wiring_hooks", "TIER_DELETE_GUARDS"),
+ "tier_delete_releases": ("_wiring_hooks", "TIER_DELETE_RELEASES"),
+ "critical_readiness": ("_wiring_hooks", "CRITICAL_READINESS_CHECKS"),
+ "informational_readiness": ("_wiring_hooks", "INFORMATIONAL_READINESS_CHECKS"),
+ "user_model": ("_wiring_models", "UserModelExtensions"),
+ "user_schema": ("_wiring_models", "UserSchemaExtensions"),
+ "admin_views": ("_wiring_admin", "ADMIN_VIEWS"),
+ "email_sender": ("_wiring_email", "EMAIL_SENDER"),
+ "cache_decorator": ("_wiring_cache", "cached"),
+ "task_modules": ("_wiring_tasks", "TASK_MODULES"),
+ "table_modules": ("_wiring_tables", "TABLE_MODULES"),
+ "extra_transports": ("_wiring_transports", "EXTRA_TRANSPORTS"),
+ "seeders": ("_seeders", "SEEDERS"),
+ "test_plugins": ("_tests_wiring", "PYTEST_PLUGINS"),
+}
+"""Where the drill writes each point: the generator, and the name it assigns or defines."""
+
+FALLBACKS = {
+ "root_routers": "()",
+ "docs_guard": "None",
+ "email_sender": "HandingOverSender(build_sender())",
+ "user_schema": "BaseModel",
+}
+"""What a point renders as when nothing contributes to it, which is no contribution at all."""
+
+APPENDED = {"settings": "CoreSettings"}
+"""A base the slot always adds last, after everything contributed."""
+
+
+def _true(condition: str, chosen: set[str]) -> bool:
+ """Whether a spec 1.3 condition holds for this selection."""
+ tokens = re.findall(r"\(|\)|[^\s()]+", condition)
+ position = 0
+
+ def expression() -> bool:
+ value = conjunction()
+ nonlocal position
+ while position < len(tokens) and tokens[position] == "or":
+ position += 1
+ value = conjunction() or value
+
+ return value
+
+ def conjunction() -> bool:
+ value = negation()
+ nonlocal position
+ while position < len(tokens) and tokens[position] == "and":
+ position += 1
+ value = negation() and value
+
+ return value
+
+ def negation() -> bool:
+ nonlocal position
+ if tokens[position] == "not":
+ position += 1
+
+ return not negation()
+
+ return atom()
+
+ def atom() -> bool:
+ nonlocal position
+ token = tokens[position]
+ position += 1
+ if token == "(":
+ value = expression()
+ assert tokens[position] == ")", condition
+ position += 1
+
+ return value
+
+ if "=" in token:
+ raise NotImplementedError(f"{token!r} names an option; this test only selects features.")
+
+ return token in chosen
+
+ held = expression()
+ assert position == len(tokens), condition
+
+ return held
+
+
+def _tables(entries: Any) -> list[dict[str, Any]]:
+ """Spec 1.5: a contribution is a bare ref or a table, and reads the same either way."""
+ return [{"ref": entry} if isinstance(entry, str) else dict(entry) for entry in entries]
+
+
+def _contributed(catalog: dict[str, Any], point: str, chosen: set[str]) -> list[dict[str, Any]]:
+ """What reaches a point for this selection, in the order spec 2.7 sorts it."""
+ collected = [(index, -1, 0, table) for index, table in enumerate(_tables(catalog["core"]["contributes"].get(point, ())))]
+
+ for index, (name, feature) in enumerate(catalog["features"].items()):
+ if name not in chosen:
+ continue
+
+ entries = list(feature.get("contributes", {}).get(point, ()))
+ for block in feature.get("when", ()):
+ if _true(block["if"], chosen):
+ entries.extend(block.get("contributes", {}).get(point, ()))
+
+ for position, table in enumerate(_tables(entries)):
+ if "if" in table and not _true(table["if"], chosen):
+ continue
+
+ collected.append((table.get("order", (index + 1) * 100 + position), index, position, table))
+
+ return [table for *_, table in sorted(collected, key=lambda entry: entry[:3])]
+
+
+def _named(entry: dict[str, Any]) -> Any:
+ """The local name a contribution binds, or the literal it contributes."""
+ if "value" in entry:
+ return entry["value"]
+
+ return _ref(entry["ref"])[2]
+
+
+def _defined(source: str, name: str) -> ast.AST | None:
+ """The value assigned to ``name``, or the class defined under it."""
+ for node in ast.parse(source).body:
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == name:
+ return node.value
+ if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == name for t in node.targets):
+ return node.value
+ if isinstance(node, ast.ClassDef) and node.name == name:
+ return node
+
+ return None
+
+
+def _leading_name(element: ast.AST) -> Any:
+ """What a rendered item is built around: ``RouterMount(users_router, …)`` is ``users_router``."""
+ if isinstance(element, ast.Constant):
+ return element.value
+ if isinstance(element, ast.Name):
+ return element.id
+ if isinstance(element, ast.Call):
+ return _leading_name(element.args[0]) if element.args else _leading_name(element.func)
+
+ raise AssertionError(ast.unparse(element))
+
+
+def _rendered(source: str, point: str, name: str) -> list[Any]:
+ """The names the drill rendered into this point, in the order it wrote them."""
+ if point == "cache_decorator":
+ bound = [module for module, _, alias in _bindings(source) if alias == name]
+
+ return [] if bound == ["..infrastructure.uncached"] else [name]
+
+ defined = _defined(source, name)
+ assert defined is not None, name
+
+ if isinstance(defined, ast.ClassDef):
+ bases = [base.id for base in defined.bases if isinstance(base, ast.Name)]
+ if point in APPENDED:
+ assert bases[-1] == APPENDED[point], bases
+ bases = bases[:-1]
+
+ return [] if bases == [FALLBACKS.get(point)] else bases
+
+ if isinstance(defined, ast.Tuple | ast.List):
+ return [_leading_name(element) for element in defined.elts]
+
+ return [] if ast.unparse(defined) == FALLBACKS[point] else [_leading_name(defined)]
+
+
+def _written_for(manifest: Any, generator: str, chosen: set[str]) -> str:
+ written: str = getattr(manifest, generator)(chosen)
+
+ return written
+
+
+def _constant(node: ast.expr) -> Any:
+ """The value of a rendered literal, such as a mount's prefix or its throttle flag."""
+ assert isinstance(node, ast.Constant), ast.unparse(node)
+
+ return node.value
+
+
+def test_every_declared_point_is_one_the_drill_writes_somewhere():
+ """A point missing from this table would skip the comparison below without saying so."""
+ assert set(POINTS) == set(_catalog()["points"])
+
+
+@pytest.mark.parametrize("point", sorted(POINTS))
+def test_every_point_is_written_by_a_generator_the_drill_has(point: str):
+ generator, _ = POINTS[point]
+
+ assert hasattr(_drill(), generator)
+
+
+def test_every_declared_point_is_contributed_to_or_filled_by_core():
+ """A point no feature and no core contribution reaches would render empty for every project."""
+ catalog = _catalog()
+ reached = set(catalog["core"]["contributes"])
+ for feature in catalog["features"].values():
+ reached.update(feature.get("contributes", {}))
+ for block in feature.get("when", ()):
+ reached.update(block.get("contributes", {}))
+
+ assert set(catalog["points"]) == reached
+
+
+def test_every_contribution_names_something_that_exists():
+ """Spec 1.4: a ref's attribute has to be defined at the top level of its module."""
+ catalog = _catalog()
+ everything = set(catalog["features"])
+
+ for point in catalog["points"]:
+ for entry in _contributed(catalog, point, everything):
+ if "value" in entry:
+ continue
+
+ module, attribute, _ = _ref(entry["ref"])
+ assert _defines(module, attribute), entry
+
+
+def test_a_point_a_project_fills_once_never_receives_two_contributions():
+ """Spec 2.6: a second contribution to a `value` slot is an error rather than a last-wins."""
+ catalog = _catalog()
+ single = {name for name, point in catalog["points"].items() if point["cardinality"] == "one"}
+
+ for chosen in _selections(_drill()):
+ for point in single:
+ assert len(_contributed(catalog, point, chosen)) <= 1, (point, sorted(chosen))
+
+
+@pytest.mark.parametrize("point", sorted(POINTS))
+def test_the_catalog_says_what_the_drill_renders(point: str):
+ """For every selection a project could carry, what reaches a point is what the drill wrote.
+
+ All 164 of them, not the verify sets: a set builds and tests a project, so the sets are
+ few, and a generator is a function of the selection alone, so it costs nothing to ask it
+ about combinations no set builds.
+ """
+ catalog = _catalog()
+ manifest = _drill()
+ generator, name = POINTS[point]
+
+ for chosen in _selections(manifest):
+ expected = [_named(entry) for entry in _contributed(catalog, point, chosen)]
+ if generator == "_wiring_admin" and "admin" not in chosen:
+ assert expected == [], sorted(chosen)
+ continue
+
+ assert _rendered(_written_for(manifest, generator, chosen), point, name) == expected, sorted(chosen)
+
+
+def test_every_mounted_router_is_mounted_where_the_drill_mounts_it():
+ """The prefix and the throttle are the catalog's to carry now, so they are compared too."""
+ catalog = _catalog()
+ manifest = _drill()
+
+ for chosen in _selections(manifest):
+ declared = [(_named(entry), entry["prefix"], entry["throttled"]) for entry in _contributed(catalog, "routers", chosen)]
+ mounts = _defined(_written_for(manifest, "_wiring_app", chosen), "ROUTER_MOUNTS")
+ assert isinstance(mounts, ast.Tuple)
+
+ rendered = [
+ (
+ _leading_name(element.args[0]),
+ _constant(element.args[1]),
+ next(_constant(word.value) for word in element.keywords if word.arg == "throttled"),
+ )
+ for element in mounts.elts
+ if isinstance(element, ast.Call)
+ ]
+
+ assert rendered == declared, sorted(chosen)
+
+
+def test_every_contribution_is_imported_the_way_the_drill_imports_it():
+ """A ref that kept the local name and changed the module would render the same line."""
+ catalog = _catalog()
+ manifest = _drill()
+ everything = set(manifest.FEATURES)
+
+ for point, (generator, _) in POINTS.items():
+ source = _written_for(manifest, generator, everything)
+ bound = _bindings(source)
+ for entry in _contributed(catalog, point, everything):
+ if "value" in entry:
+ continue
+
+ module, attribute, alias = _binding(entry["ref"])
+ assert (module.replace("..scripts.", "scripts."), attribute, alias) in bound, (point, entry)
+
+
+def test_a_transport_that_is_constructed_says_so():
+ """Spec 1.5: `call` is what renders `APIKeyTransport()` rather than the class itself."""
+ catalog = _catalog()
+ everything = set(catalog["features"])
+ entry = _contributed(catalog, "extra_transports", everything)[0]
+ rendered = _defined(_written_for(_drill(), "_wiring_transports", everything), "EXTRA_TRANSPORTS")
+
+ assert entry["call"] is True
+ assert isinstance(rendered, ast.Tuple) and isinstance(rendered.elts[0], ast.Call)
+
+
+@pytest.mark.parametrize(
+ "condition",
+ sorted(
+ {block["if"] for feature in _catalog()["features"].values() for block in feature.get("when", ())}
+ | {
+ entry["if"]
+ for feature in _catalog()["features"].values()
+ for entries in feature.get("contributes", {}).values()
+ for entry in _tables(entries)
+ if "if" in entry
+ }
+ ),
+)
+def test_every_condition_is_one_this_test_can_evaluate(condition: str):
+ """An option atom would need a selection to carry option values, which this test doesn't."""
+ assert _true(condition, set(_catalog()["features"])) in {True, False}
+
+
+@pytest.mark.parametrize(
+ ("feature", "option"),
+ sorted((name, option) for name, feature in _catalog()["features"].items() for option in feature.get("options", {})),
+)
+def test_every_option_is_declared_the_way_the_spec_asks(feature: str, option: str):
+ """Spec 2.5: named choices, listed once, with the default among them."""
+ declared = _catalog()["features"][feature]["options"][option]
+
+ assert FEATURE_NAME.match(option)
+ assert declared["choices"] == sorted(set(declared["choices"]), key=declared["choices"].index)
+ assert all(choice and not re.search(r"[\s()=]", choice) for choice in declared["choices"])
+ assert declared["default"] in declared["choices"]
+ assert all(re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", name) for name in declared.get("env", {}))
+
+
+EXTRA_SERVICES = {
+ ("cache", "backend"): {"memcached": ["memcached"]},
+ ("taskiq", "broker"): {"rabbitmq": ["rabbitmq"]},
+}
+"""The service each choice needs on top of what a project already runs, which is redis."""
+
+
+@pytest.mark.parametrize(("feature", "option"), sorted(EXTRA_SERVICES))
+def test_every_extra_service_an_option_asks_for_belongs_to_one_of_its_choices(feature: str, option: str):
+ """Spec 2.5: the key is the value that needs the service, so a typo would ask for nothing."""
+ declared = _catalog()["features"][feature]["options"][option]
+ services = declared.get("services", {})
+
+ assert set(services) <= set(declared["choices"])
+ assert services == EXTRA_SERVICES[(feature, option)]
+ assert declared["default"] not in services
+
+
+OPTION_SOURCES = {
+ ("cache", "backend"): ("src/infrastructure/cache/initialize.py", "CacheBackend"),
+ ("taskiq", "broker"): ("src/infrastructure/taskiq/settings.py", "TaskiqBrokerType"),
+}
+"""Where each option's choices are acted on, and the enum whose members name them."""
+
+
+@pytest.mark.parametrize(("feature", "option"), sorted(OPTION_SOURCES))
+def test_every_option_offers_the_values_its_feature_acts_on(feature: str, option: str):
+ """`CacheBackend` also names an in-memory backend that nothing starts, so it isn't offered."""
+ module, enum = OPTION_SOURCES[(feature, option)]
+ acted_on = re.findall(rf"{enum}\.([A-Z_]+)\.value", (REPO_ROOT / "backend" / module).read_text())
+
+ assert sorted(set(acted_on)) == sorted(
+ choice.upper() for choice in _catalog()["features"][feature]["options"][option]["choices"]
+ )
+
+
+@pytest.mark.parametrize(("feature", "option"), sorted(OPTION_SOURCES))
+def test_every_option_defaults_to_what_the_project_already_ships(feature: str, option: str):
+ """The question `fastro new` asks pre-picks the value a clone of this repo runs with."""
+ declared = _catalog()["features"][feature]["options"][option]
+ example = (REPO_ROOT / "backend" / ".env.example").read_text()
+
+ for variable in declared["env"]:
+ assert f"\n{variable}={declared['default']}\n" in example
+
+
+@pytest.mark.parametrize(("feature", "option"), sorted(OPTION_SOURCES))
+def test_every_option_marks_the_line_it_rewrites(feature: str, option: str):
+ """Spec 6.1: the marker sits on its own line directly above the VAR line it speaks for."""
+ declared = _catalog()["features"][feature]["options"][option]
+ lines = (REPO_ROOT / "backend" / ".env.example").read_text().splitlines()
+
+ for variable in declared["env"]:
+ marked = [index for index, line in enumerate(lines) if line == f"# @fastro option={feature}.{option}"]
+ assert len(marked) == 1
+ assert lines[marked[0] + 1].startswith(f"{variable}=")
diff --git a/blueprint.toml b/blueprint.toml
index be8ff39b..83920d42 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -198,12 +198,34 @@ paths = [
"backend/tests/unit/scripts/test_unlock_account.py",
]
+[features.accounts.contributes]
+routers = [
+ { ref = "src.modules.user.routes:router as users_router", prefix = "/users", throttled = true, order = 10 },
+ { ref = "src.infrastructure.auth.routes:router as auth_router", prefix = "/auth", throttled = false, order = 22 },
+]
+root_routers = ["src.infrastructure.auth.routes:root_routers as accounts_root_routers"]
+lifecycles = [
+ "src.infrastructure.auth.setup:lifecycle as accounts_lifecycle",
+ { ref = "src.infrastructure.handover:lifecycle as handover_lifecycle", if = "not taskiq", order = 950 },
+]
+installers = ["src.infrastructure.auth.install:install as accounts_install"]
+docs_guard = ["src.infrastructure.auth.dependencies:get_current_superuser"]
+settings = ["src.infrastructure.auth.settings:AccountsSettings"]
+critical_readiness = [
+ "src.infrastructure.auth.health:limiter_readiness",
+ "src.infrastructure.auth.health:sessions_readiness",
+]
+table_modules = [{ value = "src.infrastructure.auth.store" }]
+seeders = [{ ref = "scripts.create_first_superuser:create_first_superuser", order = 11 }]
+test_plugins = [{ value = "tests.fixtures.accounts" }]
+
[[features.accounts.when]]
if = "admin"
paths = [
"backend/src/modules/user/admin.py",
"backend/tests/unit/modules/user/test_admin.py",
]
+contributes.admin_views = [{ ref = "src.modules.user.admin:UserAdmin", order = 10 }]
[features.rbac]
summary = "Roles and permissions"
@@ -215,12 +237,26 @@ paths = [
"backend/tests/unit/modules/role/",
]
+[features.rbac.contributes]
+routers = [
+ { ref = "src.modules.role.routes:user_roles_router", prefix = "/users", throttled = true, order = 13 },
+ { ref = "src.modules.role.routes:permissions_router", prefix = "/permissions", throttled = true, order = 24 },
+ { ref = "src.modules.role.routes:router as roles_router", prefix = "/roles", throttled = true, order = 25 },
+]
+permission_sources = ["src.modules.role.sources:role_permissions"]
+user_model = ["src.modules.role.contrib:UserRoleColumns"]
+
[[features.rbac.when]]
if = "admin"
paths = [
"backend/src/modules/role/admin.py",
"backend/tests/unit/modules/role/test_admin.py",
]
+contributes.admin_views = [
+ { ref = "src.modules.role.admin:RoleAdmin", order = 12 },
+ { ref = "src.modules.role.admin:RolePermissionAdmin", order = 13 },
+ { ref = "src.modules.role.admin:UserRoleAdmin", order = 14 },
+]
[features.ratelimit]
summary = "Per-caller API throttle"
@@ -232,6 +268,10 @@ paths = [
"backend/tests/unit/infrastructure/ratelimit/",
]
+[features.ratelimit.contributes]
+api_throttle = ["src.infrastructure.ratelimit.dependency:api_rate_limit_dependency"]
+settings = ["src.infrastructure.ratelimit.settings:RateLimitSettings"]
+
[features.tiers]
summary = "User tiers other features key off"
group = "Accounts"
@@ -244,12 +284,24 @@ paths = [
"backend/tests/unit/modules/tier/",
]
+[features.tiers.contributes]
+routers = [
+ { ref = "src.modules.tier.routes:user_tier_router", prefix = "/users", throttled = true, order = 11 },
+ { ref = "src.modules.tier.routes:router as tiers_router", prefix = "/tiers", throttled = true, order = 20 },
+]
+settings = ["src.modules.tier.settings:TierSettings"]
+user_model = ["src.modules.tier.contrib:UserTierColumns"]
+user_schema = ["src.modules.tier.contrib:UserTierFields"]
+seeders = [{ ref = "scripts.create_first_tier:create_first_tier", order = 10 }]
+test_plugins = [{ value = "tests.fixtures.tiers" }]
+
[[features.tiers.when]]
if = "admin"
paths = [
"backend/src/modules/tier/admin.py",
"backend/tests/unit/modules/tier/test_admin.py",
]
+contributes.admin_views = [{ ref = "src.modules.tier.admin:TierAdmin", order = 11 }]
[features.tier_limits]
summary = "Per-tier rate limits"
@@ -261,6 +313,15 @@ paths = [
"backend/tests/unit/modules/rate_limit/",
]
+[features.tier_limits.contributes]
+routers = [
+ { ref = "src.modules.rate_limit.routes:user_rate_limits_router", prefix = "/users", throttled = true, order = 12 },
+ { ref = "src.modules.rate_limit.routes:router as rate_limits_router", prefix = "/rate-limits", throttled = true, order = 21 },
+]
+rate_limit_resolvers = ["src.modules.rate_limit.hooks:tier_rate_limit"]
+tier_delete_guards = ["src.modules.rate_limit.hooks:rate_limits_reference_tier"]
+tier_delete_releases = ["src.modules.rate_limit.hooks:release_deleted_rate_limits"]
+
[features.api_keys]
summary = "API keys: create, revoke, meter"
group = "Accounts"
@@ -274,6 +335,14 @@ paths = [
"backend/tests/unit/modules/api_keys/",
]
+[features.api_keys.contributes]
+routers = [
+ { ref = "src.modules.api_keys.routes:router as api_keys_router", prefix = "/api-keys", throttled = true, order = 23 },
+]
+installers = ["src.modules.api_keys.install:install as api_keys_install"]
+settings = ["src.modules.api_keys.settings:APIKeySettings"]
+extra_transports = [{ ref = "src.modules.api_keys.transport:APIKeyTransport", call = true }]
+
[[features.api_keys.when]]
if = "ratelimit"
paths = [
@@ -292,6 +361,7 @@ paths = [
"backend/src/modules/api_keys/tasks.py",
"backend/tests/unit/modules/api_keys/test_tasks.py",
]
+contributes.task_modules = [{ value = "src.modules.api_keys.tasks", order = 11 }]
[[features.api_keys.when]]
if = "tier_limits"
@@ -308,6 +378,10 @@ paths = [
"backend/tests/unit/interfaces/admin/",
]
+[features.admin.contributes]
+installers = ["src.interfaces.admin.initialize:install as admin_install"]
+settings = ["src.interfaces.admin.settings:SQLAdminSettings"]
+
[features.cache]
summary = "@cache over Redis or Memcached"
group = "Operations"
@@ -316,18 +390,44 @@ paths = [
"backend/tests/unit/infrastructure/cache/",
]
+[features.cache.contributes]
+lifecycles = ["src.infrastructure.cache.initialize:lifecycle as cache_lifecycle"]
+settings = ["src.infrastructure.cache.settings:CacheSettings"]
+informational_readiness = ["src.infrastructure.cache.health:readiness as cache_readiness"]
+cache_decorator = ["src.infrastructure.cache.decorator:cache as cached"]
+
+[features.cache.options.backend]
+choices = ["redis", "memcached"]
+default = "redis"
+env = { CACHE_BACKEND = "{value}" }
+services = { memcached = ["memcached"] }
+
[features.taskiq]
summary = "Background tasks on Redis or RabbitMQ"
group = "Operations"
+services = ["worker", "scheduler"]
paths = [
"backend/src/infrastructure/taskiq/",
"backend/tests/unit/infrastructure/taskiq/",
]
+[features.taskiq.contributes]
+lifecycles = ["src.infrastructure.taskiq.lifecycle:lifecycle as taskiq_lifecycle"]
+settings = ["src.infrastructure.taskiq.settings:TaskiqSettings"]
+informational_readiness = ["src.infrastructure.taskiq.health:readiness as broker_readiness"]
+
+[features.taskiq.options.broker]
+choices = ["redis", "rabbitmq"]
+default = "redis"
+env = { TASKIQ_BROKER_TYPE = "{value}" }
+services = { rabbitmq = ["rabbitmq"] }
+
[[features.taskiq.when]]
if = "accounts"
paths = [
"backend/src/infrastructure/taskiq/email.py",
"backend/tests/unit/infrastructure/taskiq/test_email.py",
]
+contributes.email_sender = ["src.infrastructure.taskiq.email:queued_sender"]
+contributes.task_modules = [{ value = "src.infrastructure.taskiq.email", order = 10 }]
From e1810766f7bcb29b7833c17a524054d0e4c4d595 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Wed, 28 Oct 2026 15:04:36 -0300
Subject: [PATCH 12/71] declare the twelve files the composition root is
generated into
---
backend/tests/unit/test_blueprint_catalog.py | 353 +++++++++++++++++--
blueprint.toml | 228 ++++++++++++
2 files changed, 561 insertions(+), 20 deletions(-)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 29c0cb28..1554e94e 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -8,7 +8,10 @@
"""
import ast
+import functools
+import importlib
import importlib.util
+import inspect
import itertools
import re
import sys
@@ -35,11 +38,13 @@
"""`fastro.toml` is declared in the catalog before it exists."""
+@functools.cache
def _catalog() -> dict[str, Any]:
with CATALOG.open("rb") as handle:
return tomllib.load(handle)
+@functools.cache
def _drill():
"""The drill's manifest, loaded as a module: its dataclasses need it in ``sys.modules``."""
spec = importlib.util.spec_from_file_location("removal_drill_manifest", REPO_ROOT / "tools" / "removal_drill.py")
@@ -175,11 +180,13 @@ def _binding(entry: str) -> tuple[str, str, str]:
"""What a wiring file under ``src/wiring/`` binds for this ref: (module, attribute, name).
Spec 2.8: a file under the import root imports relatively, so ``src.a.b:name`` is read
- from ``..a.b``.
+ from ``..a.b``. Anything outside it, such as ``scripts.seed``, is imported as written.
"""
module, attribute, alias = _ref(entry)
+ if module.startswith("src."):
+ module = ".." + module.removeprefix("src.")
- return ".." + module.removeprefix("src."), attribute, alias
+ return module, attribute, alias
def _bindings(source: str) -> set[tuple[str, str, str]]:
@@ -443,16 +450,30 @@ def test_every_selection_keeps_the_files_the_drill_keeps():
}
"""Where the drill writes each point: the generator, and the name it assigns or defines."""
-FALLBACKS = {
- "root_routers": "()",
- "docs_guard": "None",
- "email_sender": "HandingOverSender(build_sender())",
- "user_schema": "BaseModel",
-}
-"""What a point renders as when nothing contributes to it, which is no contribution at all."""
-APPENDED = {"settings": "CoreSettings"}
-"""A base the slot always adds last, after everything contributed."""
+def _slot_of(point: str) -> dict[str, Any]:
+ """The one slot that collects this point, which `[[wiring]]` declares exactly once."""
+ slots: list[dict[str, Any]] = [
+ slot for entry in _catalog()["wiring"] for slot in entry["slots"] if slot.get("point") == point
+ ]
+ assert len(slots) == 1, point
+
+ return slots[0]
+
+
+def _fallback_of(point: str) -> str | None:
+ """How a point renders with nothing contributed: an expression, or a ref's local name."""
+ slot = _slot_of(point)
+ fallback = slot.get("fallback")
+ if fallback is None:
+ return None
+
+ return _ref(fallback)[2] if slot["kind"] in {"class", "reexport"} else fallback
+
+
+def _appended_to(point: str) -> list[str]:
+ """The bases a `class` slot always adds last, by the name they are bound under."""
+ return [_ref(ref)[2] for ref in _slot_of(point).get("append", ())]
def _true(condition: str, chosen: set[str]) -> bool:
@@ -571,26 +592,28 @@ def _leading_name(element: ast.AST) -> Any:
def _rendered(source: str, point: str, name: str) -> list[Any]:
"""The names the drill rendered into this point, in the order it wrote them."""
- if point == "cache_decorator":
+ if _slot_of(point)["kind"] == "reexport":
+ fallback, _, _ = _binding(_slot_of(point)["fallback"])
bound = [module for module, _, alias in _bindings(source) if alias == name]
- return [] if bound == ["..infrastructure.uncached"] else [name]
+ return [] if bound == [fallback] else [name]
defined = _defined(source, name)
assert defined is not None, name
if isinstance(defined, ast.ClassDef):
bases = [base.id for base in defined.bases if isinstance(base, ast.Name)]
- if point in APPENDED:
- assert bases[-1] == APPENDED[point], bases
- bases = bases[:-1]
+ appended = _appended_to(point)
+ if appended:
+ assert bases[-len(appended) :] == appended, bases
+ bases = bases[: -len(appended)]
- return [] if bases == [FALLBACKS.get(point)] else bases
+ return [] if bases == [_fallback_of(point)] else bases
if isinstance(defined, ast.Tuple | ast.List):
return [_leading_name(element) for element in defined.elts]
- return [] if ast.unparse(defined) == FALLBACKS[point] else [_leading_name(defined)]
+ return [] if ast.unparse(defined) == _fallback_of(point) else [_leading_name(defined)]
def _written_for(manifest: Any, generator: str, chosen: set[str]) -> str:
@@ -711,8 +734,7 @@ def test_every_contribution_is_imported_the_way_the_drill_imports_it():
if "value" in entry:
continue
- module, attribute, alias = _binding(entry["ref"])
- assert (module.replace("..scripts.", "scripts."), attribute, alias) in bound, (point, entry)
+ assert _binding(entry["ref"]) in bound, (point, entry)
def test_a_transport_that_is_constructed_says_so():
@@ -815,3 +837,294 @@ def test_every_option_marks_the_line_it_rewrites(feature: str, option: str):
marked = [index for index, line in enumerate(lines) if line == f"# @fastro option={feature}.{option}"]
assert len(marked) == 1
assert lines[marked[0] + 1].startswith(f"{variable}=")
+
+
+SLOT_KINDS = {"tuple", "list", "class", "value", "reexport", "raw", "data"}
+"""Spec 2.6. A kind the engine doesn't know would be a slot nothing renders."""
+
+
+def _written_by_build(manifest: Any) -> list[str]:
+ """The files `build` writes, read out of its source rather than listed again here."""
+ source = inspect.getsource(manifest.build)
+
+ return re.findall(r'\(project / "([^"]+)"\)\.write_text', source)
+
+
+def _entries() -> list[dict[str, Any]]:
+ return list(_catalog()["wiring"])
+
+
+def _committed(path: str) -> str:
+ return (REPO_ROOT / path).read_text()
+
+
+def _annotated(source: str, name: str) -> str | None:
+ """How the committed file spells this name's annotation."""
+ for node in ast.parse(source).body:
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == name:
+ return ast.unparse(node.annotation)
+
+ return None
+
+
+def test_the_wiring_entries_are_the_files_the_drill_writes():
+ """One entry per generated file, both ways. The entries' order carries nothing, so it is free."""
+ written = _written_by_build(_drill())
+
+ assert sorted(entry["path"] for entry in _entries()) == sorted(written)
+ assert len(written) == 12
+
+
+@pytest.mark.parametrize("path", [entry["path"] for entry in _entries()])
+def test_every_wiring_file_is_under_the_python_root_and_is_a_file(path: str):
+ """Spec 2.6: a generated Python file lives under `python_root`, and names one file."""
+ blueprint = _catalog()["blueprint"]
+
+ assert path.startswith(blueprint["python_root"] + "/")
+ assert not path.endswith("/")
+ assert (REPO_ROOT / path).is_file()
+
+
+@pytest.mark.parametrize("path", [entry["path"] for entry in _entries()])
+def test_every_wiring_file_says_what_it_is_for(path: str):
+ """The entry's `doc` is the file's own docstring, minus the line naming what generated it."""
+ entry = next(entry for entry in _entries() if entry["path"] == path)
+ docstring = ast.get_docstring(ast.parse(_committed(path)))
+
+ assert docstring is not None
+ declared = entry["doc"].splitlines()
+ assert declared[0] == docstring.splitlines()[0]
+ assert " ".join(" ".join(declared[1:]).split()) in " ".join(docstring.split())
+
+
+@pytest.mark.parametrize(
+ ("path", "name"),
+ [(entry["path"], slot["name"]) for entry in _entries() for slot in entry["slots"] if "annotation" in slot],
+)
+def test_every_annotated_slot_is_annotated_the_way_the_file_annotates_it(path: str, name: str):
+ """`NAME: ANNOTATION` is what mypy and an IDE read, so the catalog has to spell it the same."""
+ slot = next(slot for slot in next(e for e in _entries() if e["path"] == path)["slots"] if slot.get("name") == name)
+
+ assert _annotated(_committed(path), name) == slot["annotation"]
+
+
+@pytest.mark.parametrize(
+ ("path", "name"),
+ [(entry["path"], slot["name"]) for entry in _entries() for slot in entry["slots"] if "name" in slot],
+)
+def test_every_slot_fills_a_name_the_file_defines(path: str, name: str):
+ assert _defined(_committed(path), name) is not None or name in {alias for _, _, alias in _bindings(_committed(path))}
+
+
+def test_every_declared_point_is_filled_by_exactly_one_slot():
+ """One direction: a point no slot collects is a point whose contributions reach nothing."""
+ filled = [slot["point"] for entry in _entries() for slot in entry["slots"] if "point" in slot]
+
+ assert sorted(filled) == sorted(_catalog()["points"])
+
+
+def test_every_slot_collects_a_point_the_catalog_declares():
+ """The other direction: a slot naming an undeclared point would collect nothing for ever."""
+ declared = set(_catalog()["points"])
+
+ for entry in _entries():
+ for slot in entry["slots"]:
+ if slot["kind"] == "raw":
+ assert "point" not in slot and "name" not in slot
+ continue
+
+ assert slot["point"] in declared, slot
+
+
+@pytest.mark.parametrize(
+ ("path", "kind"),
+ [(entry["path"], slot["kind"]) for entry in _entries() for slot in entry["slots"]],
+)
+def test_every_slot_is_a_kind_the_spec_has(path: str, kind: str):
+ assert kind in SLOT_KINDS
+
+
+def test_every_point_a_project_fills_once_is_rendered_as_one_value():
+ """Spec 2.6: `value`, `class` and `reexport` render one, and each needs its fallback."""
+ cardinality = {name: point["cardinality"] for name, point in _catalog()["points"].items()}
+
+ for entry in _entries():
+ for slot in entry["slots"]:
+ if slot["kind"] in {"value", "reexport"}:
+ assert cardinality[slot["point"]] == "one", slot
+ assert "fallback" in slot, slot
+ if slot["kind"] in {"tuple", "list"}:
+ assert cardinality[slot["point"]] == "many", slot
+
+
+def test_the_file_a_feature_brings_with_it_is_generated_only_for_that_feature():
+ """FR003: without admin the file is absent from the project, not emptied."""
+ admin = next(entry for entry in _entries() if entry["path"].endswith("wiring/admin.py"))
+ build = inspect.getsource(_drill().build)
+
+ assert admin["if"] == "admin"
+ assert 'if "admin" in chosen:' in build
+ assert [entry.get("if") for entry in _entries()].count(None) == 11
+
+
+def test_the_statement_a_raw_slot_carries_is_in_the_file():
+ """`settings = Settings()` is what the rest of the project imports, and no point fills it."""
+ raw = [slot for entry in _entries() for slot in entry["slots"] if slot["kind"] == "raw"]
+ committed = _committed("backend/src/wiring/settings.py")
+
+ assert [slot["code"] for slot in raw] == ["settings = Settings()"]
+ assert "settings = Settings()" in committed
+
+
+def _declared_bindings(catalog: dict[str, Any], entry: dict[str, Any], chosen: set[str]) -> set[tuple[str, str, str]]:
+ """Every name the catalog says this file binds: its own imports, and what reaches its slots."""
+ bindings: set[tuple[str, str, str]] = set()
+ for line in entry.get("imports", ()):
+ module, _, names = line.removeprefix("from ").partition(" import ")
+ bindings.update((module, name, name) for name in names.split(", "))
+
+ for slot in entry["slots"]:
+ if slot["kind"] == "raw":
+ continue
+
+ contributed = _contributed(catalog, slot["point"], chosen)
+ if contributed and not slot.get("literal"):
+ bindings.update(_binding(contribution["ref"]) for contribution in contributed if "ref" in contribution)
+ for line in slot.get("item_imports", ()):
+ module, _, names = line.removeprefix("from ").partition(" import ")
+ bindings.update((module, name, name) for name in names.split(", "))
+
+ if not contributed:
+ for line in slot.get("fallback_imports", ()):
+ module, _, names = line.removeprefix("from ").partition(" import ")
+ bindings.update((module, name, name) for name in names.split(", "))
+ if ":" in slot.get("fallback", ""):
+ bindings.add(_binding(slot["fallback"]))
+
+ bindings.update(_binding(ref) for ref in slot.get("append", ()))
+
+ return bindings
+
+
+@pytest.mark.parametrize("path", [entry["path"] for entry in _entries()])
+def test_the_catalog_accounts_for_every_name_the_file_imports(path: str):
+ """An import the entry forgets is a NameError in a project nobody has built yet.
+
+ The committed files carry every feature, so with everything selected the names the
+ catalog brings and the names the file binds are the same set, both ways.
+ """
+ catalog = _catalog()
+ entry = next(entry for entry in _entries() if entry["path"] == path)
+
+ assert _declared_bindings(catalog, entry, set(catalog["features"])) == _bindings(_committed(path))
+
+
+def _refs_of(slot: dict[str, Any]) -> list[str]:
+ """The refs a slot names itself: its fallback, and the bases it always appends."""
+ refs = list(slot.get("append", ()))
+ if ":" in slot.get("fallback", ""):
+ refs.append(slot["fallback"])
+
+ return refs
+
+
+def test_every_ref_a_slot_names_itself_exists():
+ """A fallback is what a project without the feature gets, so it has to be importable there."""
+ named = [(entry["path"], ref) for entry in _entries() for slot in entry["slots"] for ref in _refs_of(slot)]
+
+ assert sorted(ref for _, ref in named) == [
+ "pydantic:BaseModel",
+ "src.infrastructure.config.base:CoreSettings",
+ "src.infrastructure.uncached:cached",
+ ]
+
+ for path, ref in named:
+ module, attribute, _ = _ref(ref)
+ if module.startswith("src."):
+ assert _defines(module, attribute), (path, ref)
+ else:
+ assert hasattr(importlib.import_module(module), attribute), (path, ref)
+
+
+def test_every_import_a_fallback_needs_names_something_that_exists():
+ """Spec 2.6: these lines are emitted only when the fallback is used, so nothing else checks them."""
+ lines = [
+ (entry["path"], line) for entry in _entries() for slot in entry["slots"] for line in slot.get("fallback_imports", ())
+ ]
+
+ assert len(lines) == 2
+
+ for path, line in lines:
+ module, _, name = line.removeprefix("from ").partition(" import ")
+ assert path.startswith("backend/src/wiring/"), path
+ assert _defines("src." + module.lstrip("."), name), line
+
+
+def test_the_header_every_generated_file_carries_is_fastros_own():
+ """Spec 2.12, verbatim: a project's wiring says what wrote it and how to change it."""
+ assert _catalog()["wiring_defaults"]["header"] == (
+ "Generated by fastro from blueprint.toml and fastro.toml. Don't edit: change\n"
+ "fastro.toml (or [app] in it, for your own code) and run `fastro sync`."
+ )
+
+
+def test_the_header_fits_the_line_length_of_the_files_it_goes_into():
+ """Spec 2.8: each line is at most 100 characters, so a docstring passes E501 at 128."""
+ for line in _catalog()["wiring_defaults"]["header"].splitlines():
+ assert len(line) <= 100, line
+
+
+@pytest.mark.parametrize("path", [entry["path"] for entry in _entries()])
+def test_the_catalog_accounts_for_what_the_file_imports_for_every_selection(path: str):
+ """The fallbacks, where the committed files cannot reach: nothing falls back with all nine.
+
+ `fallback_imports`, the pydantic base and the uncached decorator are only written into a
+ project that left the feature out, so only a smaller selection compares them.
+ """
+ catalog = _catalog()
+ manifest = _drill()
+ entry = next(entry for entry in _entries() if entry["path"] == path)
+ generator = next(
+ drill_generator
+ for point, (drill_generator, _) in POINTS.items()
+ if any(slot.get("point") == point for slot in entry["slots"])
+ )
+
+ for chosen in _selections(manifest):
+ if generator == "_wiring_admin" and "admin" not in chosen:
+ continue
+
+ written = _bindings(_written_for(manifest, generator, chosen))
+ assert _declared_bindings(catalog, entry, chosen) == written, sorted(chosen)
+
+
+LINE_LENGTH = 128
+"""The project's ruff line length, which spec 2.8 wraps a generated import at."""
+
+
+@pytest.mark.parametrize("path", [entry["path"] for entry in _entries()])
+def test_no_import_in_a_generated_file_is_wrapped_before_it_has_to_be(path: str):
+ """Spec 2.8: a statement is wrapped only when one line of it would be too long."""
+ source = _committed(path)
+ for node in ast.parse(source).body:
+ if not isinstance(node, ast.Import | ast.ImportFrom):
+ continue
+
+ one_line = ast.unparse(node)
+ wrapped = (node.end_lineno or node.lineno) > node.lineno
+ assert wrapped == (len(one_line) > LINE_LENGTH), one_line
+
+
+@pytest.mark.parametrize(
+ ("path", "name"),
+ [(entry["path"], slot["name"]) for entry in _entries() for slot in entry["slots"] if slot["kind"] in {"tuple", "list"}],
+)
+def test_a_collection_of_more_than_one_is_written_one_entry_to_a_line(path: str, name: str):
+ """Spec 2.6: a tuple of two or more is always exploded, and a list always is."""
+ slot = next(slot for slot in next(e for e in _entries() if e["path"] == path)["slots"] if slot.get("name") == name)
+ defined = _defined(_committed(path), name)
+
+ assert isinstance(defined, ast.Tuple | ast.List)
+ exploded = (defined.end_lineno or defined.lineno) > defined.lineno
+
+ assert exploded == (len(defined.elts) >= (1 if slot["kind"] == "list" else 2))
diff --git a/blueprint.toml b/blueprint.toml
index 83920d42..97226792 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -431,3 +431,231 @@ paths = [
contributes.email_sender = ["src.infrastructure.taskiq.email:queued_sender"]
contributes.task_modules = [{ value = "src.infrastructure.taskiq.email", order = 10 }]
+
+[wiring_defaults]
+header = """Generated by fastro from blueprint.toml and fastro.toml. Don't edit: change
+fastro.toml (or [app] in it, for your own code) and run `fastro sync`."""
+
+[[wiring]]
+path = "backend/src/wiring/settings.py"
+doc = """The project's settings: each selected feature's mixin on top of the core.
+
+Core comes last, so a feature can override a core default rather than the other way round."""
+
+[[wiring.slots]]
+kind = "class"
+name = "Settings"
+point = "settings"
+append = ["src.infrastructure.config.base:CoreSettings"]
+doc = "The settings of every selected feature, on top of the core."
+
+[[wiring.slots]]
+kind = "raw"
+code = "settings = Settings()"
+
+[[wiring]]
+path = "backend/src/wiring/app.py"
+doc = "The composition root: what the app mounts, starts and installs."
+imports = [
+ "from collections.abc import Callable",
+ "from typing import Any",
+ "from fastapi import APIRouter, FastAPI",
+ "from ..infrastructure.composition import Lifecycle, RouterMount",
+]
+
+[[wiring.slots]]
+kind = "tuple"
+name = "ROUTER_MOUNTS"
+point = "routers"
+annotation = "tuple[RouterMount, ...]"
+item = 'RouterMount({name}, "{prefix}", throttled={throttled})'
+
+[[wiring.slots]]
+kind = "value"
+name = "ROOT_ROUTERS"
+point = "root_routers"
+annotation = "tuple[APIRouter, ...]"
+fallback = "()"
+
+[[wiring.slots]]
+kind = "tuple"
+name = "API_THROTTLE"
+point = "api_throttle"
+annotation = "tuple[Any, ...]"
+item = "Depends({name})"
+item_imports = ["from fastapi import Depends"]
+
+[[wiring.slots]]
+kind = "tuple"
+name = "LIFECYCLES"
+point = "lifecycles"
+annotation = "tuple[Lifecycle, ...]"
+
+[[wiring.slots]]
+kind = "tuple"
+name = "INSTALLERS"
+point = "installers"
+annotation = "tuple[Callable[[FastAPI], None], ...]"
+
+[[wiring.slots]]
+kind = "value"
+name = "DOCS_GUARD"
+point = "docs_guard"
+annotation = "Callable[..., Any] | None"
+fallback = "None"
+
+[[wiring]]
+path = "backend/src/wiring/hooks.py"
+doc = "The contributions features make to each other's extension points."
+imports = [
+ "from ..infrastructure.composition import PermissionSource, RateLimitResolver, ReadinessCheck, TierDeleteGuard, TierDeleteRelease",
+]
+
+[[wiring.slots]]
+kind = "tuple"
+name = "PERMISSION_SOURCES"
+point = "permission_sources"
+annotation = "tuple[PermissionSource, ...]"
+
+[[wiring.slots]]
+kind = "tuple"
+name = "RATE_LIMIT_RESOLVERS"
+point = "rate_limit_resolvers"
+annotation = "tuple[RateLimitResolver, ...]"
+
+[[wiring.slots]]
+kind = "tuple"
+name = "TIER_DELETE_GUARDS"
+point = "tier_delete_guards"
+annotation = "tuple[TierDeleteGuard, ...]"
+
+[[wiring.slots]]
+kind = "tuple"
+name = "TIER_DELETE_RELEASES"
+point = "tier_delete_releases"
+annotation = "tuple[TierDeleteRelease, ...]"
+
+[[wiring.slots]]
+kind = "tuple"
+name = "CRITICAL_READINESS_CHECKS"
+point = "critical_readiness"
+annotation = "tuple[ReadinessCheck, ...]"
+
+[[wiring.slots]]
+kind = "tuple"
+name = "INFORMATIONAL_READINESS_CHECKS"
+point = "informational_readiness"
+annotation = "tuple[ReadinessCheck, ...]"
+
+[[wiring]]
+path = "backend/src/wiring/models.py"
+doc = "Extension points of the user model: what other features add to ``User``."
+
+[[wiring.slots]]
+kind = "class"
+name = "UserModelExtensions"
+point = "user_model"
+doc = "Columns and relationships other features add to ``User``."
+
+[[wiring.slots]]
+kind = "class"
+name = "UserSchemaExtensions"
+point = "user_schema"
+fallback = "pydantic:BaseModel"
+doc = "Fields other features add to the user read schemas."
+
+[[wiring]]
+path = "backend/src/wiring/email.py"
+doc = """The sender the account emails go out through.
+
+It is its own module because ``hooks`` reaches features that import the accounts feature back."""
+imports = ["from crudauth import EmailSender"]
+
+[[wiring.slots]]
+kind = "value"
+name = "EMAIL_SENDER"
+point = "email_sender"
+annotation = "EmailSender"
+fallback = "HandingOverSender(build_sender())"
+fallback_imports = [
+ "from ..infrastructure.email.factory import build_sender",
+ "from ..infrastructure.email.senders import HandingOverSender",
+]
+
+[[wiring]]
+path = "backend/src/wiring/cache.py"
+doc = "The decorator a route caches its response with."
+
+[[wiring.slots]]
+kind = "reexport"
+name = "cached"
+point = "cache_decorator"
+fallback = "src.infrastructure.uncached:cached"
+
+[[wiring]]
+path = "backend/src/wiring/transports.py"
+doc = "The authentication transports this project registers beside the session one."
+imports = ["from crudauth import Transport"]
+
+[[wiring.slots]]
+kind = "tuple"
+name = "EXTRA_TRANSPORTS"
+point = "extra_transports"
+annotation = "tuple[Transport, ...]"
+
+[[wiring]]
+path = "backend/src/wiring/tasks.py"
+doc = """The modules whose background tasks the worker registers.
+
+A task the worker reports as unknown drops its message, so a module declaring one belongs in this list."""
+
+[[wiring.slots]]
+kind = "tuple"
+name = "TASK_MODULES"
+point = "task_modules"
+annotation = "tuple[str, ...]"
+literal = true
+
+[[wiring]]
+path = "backend/src/wiring/tables.py"
+doc = "Modules outside ``src/modules`` that declare tables on ``Base.metadata``."
+
+[[wiring.slots]]
+kind = "tuple"
+name = "TABLE_MODULES"
+point = "table_modules"
+annotation = "tuple[str, ...]"
+literal = true
+
+[[wiring]]
+path = "backend/src/wiring/admin.py"
+doc = "The model views the admin panel registers."
+if = "admin"
+
+[[wiring.slots]]
+kind = "tuple"
+name = "ADMIN_VIEWS"
+point = "admin_views"
+annotation = "tuple[type, ...]"
+
+[[wiring]]
+path = "backend/scripts/seeders.py"
+doc = "The initial-data steps ``scripts/setup_initial_data.py`` runs, in order."
+imports = ["from collections.abc import Awaitable, Callable"]
+
+[[wiring.slots]]
+kind = "tuple"
+name = "SEEDERS"
+point = "seeders"
+annotation = "tuple[Callable[[], Awaitable[None]], ...]"
+
+[[wiring]]
+path = "backend/tests/wiring.py"
+doc = "Fixture modules of the selected features, loaded by ``tests/conftest.py``."
+
+[[wiring.slots]]
+kind = "list"
+name = "PYTEST_PLUGINS"
+point = "test_plugins"
+annotation = "list[str]"
+literal = true
From c4dcb84df7a091fe9c6299f04709e97d0674c6b7 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Wed, 28 Oct 2026 15:04:40 -0300
Subject: [PATCH 13/71] lay the generated wiring out the way the spec renders
it
---
backend/src/wiring/hooks.py | 8 +-------
backend/src/wiring/tasks.py | 5 ++++-
2 files changed, 5 insertions(+), 8 deletions(-)
diff --git a/backend/src/wiring/hooks.py b/backend/src/wiring/hooks.py
index 6d542e41..b7b5f66f 100644
--- a/backend/src/wiring/hooks.py
+++ b/backend/src/wiring/hooks.py
@@ -6,13 +6,7 @@
from ..infrastructure.auth.health import limiter_readiness, sessions_readiness
from ..infrastructure.cache.health import readiness as cache_readiness
-from ..infrastructure.composition import (
- PermissionSource,
- RateLimitResolver,
- ReadinessCheck,
- TierDeleteGuard,
- TierDeleteRelease,
-)
+from ..infrastructure.composition import PermissionSource, RateLimitResolver, ReadinessCheck, TierDeleteGuard, TierDeleteRelease
from ..infrastructure.database.health import readiness as database_readiness
from ..infrastructure.database.health import schema_readiness
from ..infrastructure.taskiq.health import readiness as broker_readiness
diff --git a/backend/src/wiring/tasks.py b/backend/src/wiring/tasks.py
index 5e529acd..61bb4ba1 100644
--- a/backend/src/wiring/tasks.py
+++ b/backend/src/wiring/tasks.py
@@ -5,4 +5,7 @@
declaring one belongs in this list.
"""
-TASK_MODULES: tuple[str, ...] = ("src.infrastructure.taskiq.email", "src.modules.api_keys.tasks")
+TASK_MODULES: tuple[str, ...] = (
+ "src.infrastructure.taskiq.email",
+ "src.modules.api_keys.tasks",
+)
From b3a00dc764b938230c4a04af2220142f29a3f96e Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Wed, 28 Oct 2026 16:29:02 -0300
Subject: [PATCH 14/71] declare the deploy generator, the commands and the
blueprint's own project file
---
backend/tests/unit/test_blueprint_catalog.py | 166 ++++++++++++++++++-
blueprint.toml | 36 ++++
fastro.toml | 10 ++
3 files changed, 208 insertions(+), 4 deletions(-)
create mode 100644 fastro.toml
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 1554e94e..910e13e9 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -12,7 +12,9 @@
import importlib
import importlib.util
import inspect
+import ipaddress
import itertools
+import keyword
import re
import sys
import tomllib
@@ -34,9 +36,6 @@
SET_NAME = re.compile(r"^[a-z][a-z0-9_-]*$")
"""Spec 1.2. A preset or a verify set may carry a hyphen, which a feature name may not."""
-NOT_YET_WRITTEN = {"fastro.toml"}
-"""`fastro.toml` is declared in the catalog before it exists."""
-
@functools.cache
def _catalog() -> dict[str, Any]:
@@ -105,7 +104,7 @@ def test_every_blueprint_only_path_is_written_the_way_the_spec_reads_them(entry:
assert entry.endswith("/") == (REPO_ROOT / entry).is_dir()
-@pytest.mark.parametrize("entry", sorted(set(_catalog()["blueprint"]["blueprint_only"]) - NOT_YET_WRITTEN))
+@pytest.mark.parametrize("entry", sorted(_catalog()["blueprint"]["blueprint_only"]))
def test_every_blueprint_only_path_is_one_this_repo_has(entry: str):
"""A path that no longer exists keeps a file out of projects that nobody meant to keep out."""
assert (REPO_ROOT / entry).exists()
@@ -1128,3 +1127,162 @@ def test_a_collection_of_more_than_one_is_written_one_entry_to_a_line(path: str,
exploded = (defined.end_lineno or defined.lineno) > defined.lineno
assert exploded == (len(defined.elts) >= (1 if slot["kind"] == "list" else 2))
+
+
+PROJECT_FILE = REPO_ROOT / "fastro.toml"
+
+GENERATOR_NAME = re.compile(r"^[a-z][a-z0-9-]*$")
+"""Spec 2.9. It becomes the word after `fastro make`, and `fastro make` takes no underscore."""
+
+COMMAND_WORD = re.compile(r"^[a-z][a-z0-9-]*$")
+
+PARAM_TYPES = {"int", "str", "bool", "cidr", "choice"}
+
+PYTHON_TYPES: dict[str, type] = {"int": int, "str": str, "bool": bool, "cidr": str, "choice": str}
+
+
+@functools.cache
+def _project() -> dict[str, Any]:
+ with PROJECT_FILE.open("rb") as handle:
+ return tomllib.load(handle)
+
+
+def _owned_paths() -> set[str]:
+ return {path for feature in _catalog()["features"].values() for path, _ in _declared(feature)}
+
+
+@pytest.mark.parametrize("name", sorted(_catalog()["generators"]))
+def test_every_generator_is_named_the_way_fastro_make_reads_it(name: str):
+ assert GENERATOR_NAME.match(name)
+ assert "register" not in _catalog()["generators"][name] or name == "module"
+ assert "types" not in _catalog()["generators"][name] or name == "module"
+
+
+@pytest.mark.parametrize("name", sorted(_catalog()["generators"]))
+def test_every_generators_templates_are_a_directory_this_repo_has(name: str):
+ """Spec 2.9: subdirectories when the generator has modes, which is one tree per mode."""
+ generator = _catalog()["generators"][name]
+ templates = REPO_ROOT / generator["templates"]
+
+ assert templates.is_dir()
+ assert any(child.is_dir() for child in templates.iterdir())
+
+
+def test_the_deploy_modes_are_the_ones_this_repo_can_generate():
+ """A mode with no template tree would be offered and then fail; a tree with no mode is dead."""
+ templates = REPO_ROOT / _catalog()["generators"]["deploy"]["templates"]
+ offered = re.findall(r"^ (\w+) = \"\w+\"$", (REPO_ROOT / "cli/src/cli/commands/deploy.py").read_text(), re.M)
+
+ assert sorted(child.name for child in templates.iterdir() if child.is_dir()) == sorted(offered)
+
+
+@pytest.mark.parametrize(
+ ("generator", "param"),
+ sorted((name, param) for name, declared in _catalog()["generators"].items() for param in declared["params"]),
+)
+def test_every_param_is_declared_the_way_the_spec_asks(generator: str, param: str):
+ """Spec 2.9: a type and a default of that type, and the keys each type allows."""
+ declared = _catalog()["generators"][generator]["params"][param]
+
+ assert FEATURE_NAME.match(param)
+ assert declared["type"] in PARAM_TYPES
+ assert isinstance(declared["default"], PYTHON_TYPES[declared["type"]])
+ assert declared["type"] == "bool" or not isinstance(declared["default"], bool), "a bool is an int to isinstance"
+ assert declared["help"].strip() == declared["help"]
+ assert ("choices" in declared) == (declared["type"] == "choice")
+ for key in ("private_only", "max_prefix"):
+ assert key not in declared or declared["type"] == "cidr"
+
+
+def test_the_subnet_default_is_a_network_with_no_host_bits_set():
+ """Spec 2.9: `10.0.0.1/24` is not a network, and the tool would refuse the catalog for it."""
+ declared = _catalog()["generators"]["deploy"]["params"]["internal_subnet"]
+
+ assert str(ipaddress.ip_network(declared["default"], strict=True)) == declared["default"]
+ assert 0 <= declared["max_prefix"] <= 128
+
+
+def test_every_param_the_templates_read_is_a_param_the_catalog_declares():
+ """Both ways: an undeclared param is a StrictUndefined crash, a declared one nothing reads is dead."""
+ generator = _catalog()["generators"]["deploy"]
+ templates = REPO_ROOT / generator["templates"]
+ read = {name for template in templates.rglob("*.j2") for name in re.findall(r"params\.([a-z_]+)", template.read_text())}
+
+ assert read == set(generator["params"])
+
+
+def test_the_defaults_are_what_this_repos_own_generator_already_uses():
+ """`fastro make deploy` has to write what `bp deploy generate` writes, or the first run changes."""
+ params = _catalog()["generators"]["deploy"]["params"]
+ source = (REPO_ROOT / "cli/src/cli/commands/deploy.py").read_text()
+ subnet = (REPO_ROOT / "cli/src/cli/features/_builtins/deploy/feature.py").read_text()
+
+ assert f'typer.Option({params["api_port"]["default"]}, "--api-port"' in source
+ assert f'typer.Option({params["workers"]["default"]}, "--workers"' in source
+ assert f'DEFAULT_INTERNAL_SUBNET = "{params["internal_subnet"]["default"]}"' in subnet
+
+
+@pytest.mark.parametrize("words", sorted(_catalog()["commands"]))
+def test_every_command_is_spelled_the_way_the_spec_reads_it(words: str):
+ """Spec 2.9: the words become the command path, one space apart."""
+ command = _catalog()["commands"][words]
+
+ assert all(COMMAND_WORD.match(word) for word in words.split(" "))
+ assert " " not in words
+ assert all(part.isidentifier() and not keyword.iskeyword(part) for part in command["module"].split("."))
+ assert command["help"].strip() == command["help"]
+ assert "\n" not in command["help"]
+ assert command.get("outside_project", "error") in {"error", "token_hex"}
+
+
+@pytest.mark.parametrize("words", sorted(_catalog()["commands"]))
+def test_every_command_runs_a_module_this_repo_can_run(words: str):
+ """It is run as `python -m `, which needs the entry point that makes that work."""
+ module = _catalog()["commands"][words]["module"]
+ path = REPO_ROOT / _catalog()["blueprint"]["python_root"] / Path(*module.split(".")).with_suffix(".py")
+
+ assert path.is_file()
+ assert '__name__ == "__main__"' in path.read_text()
+
+
+@pytest.mark.parametrize("words", sorted(_catalog()["commands"]))
+def test_every_command_runs_a_script_no_feature_takes_away(words: str):
+ """A command carries no condition (spec 2.9), so one naming a feature's script would break.
+
+ `scripts/unlock_account.py` goes with accounts, and `fastro users unlock` in a project
+ without accounts would be a command pointing at a module that isn't there.
+ """
+ module = _catalog()["commands"][words]["module"]
+ script = f"{_catalog()['blueprint']['python_root']}/{Path(*module.split('.')).with_suffix('.py')}"
+
+ assert script not in _owned_paths(), script
+
+
+def test_the_blueprint_repo_says_it_is_the_blueprint():
+ """Spec 3: `source = true` only in a blueprint repo, where generated files are committed."""
+ assert _project()["source"] is True
+ assert _project()["blueprint"] == {"name": _catalog()["blueprint"]["name"], "version": _catalog()["blueprint"]["version"]}
+
+
+def test_the_blueprint_repo_carries_every_feature():
+ """It has to: the committed wiring is the `everything` selection, and the tests cover all nine."""
+ assert _project()["features"] == list(_catalog()["features"])
+
+
+def test_the_blueprint_repo_runs_every_option_at_its_default():
+ """Spec 6.1: the `.env.example` lines the options rewrite are the ones this repo ships."""
+ declared = {
+ f"{name}.{option}": option_table["default"]
+ for name, feature in _catalog()["features"].items()
+ for option, option_table in feature.get("options", {}).items()
+ }
+
+ assert _project()["options"] == declared
+
+
+def test_the_project_is_named_the_way_its_python_package_is():
+ """`project.name` is what the deploy templates name the compose project after (spec 6.2)."""
+ with BACKEND_PYPROJECT.open("rb") as handle:
+ backend = tomllib.load(handle)
+
+ assert _project()["project"]["name"] == backend["project"]["name"]
diff --git a/blueprint.toml b/blueprint.toml
index 97226792..38eb2cc5 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -659,3 +659,39 @@ name = "PYTEST_PLUGINS"
point = "test_plugins"
annotation = "list[str]"
literal = true
+
+[generators.deploy]
+templates = "blueprint/templates/deploy"
+
+[generators.deploy.params.api_port]
+type = "int"
+default = 8000
+help = "Host port to publish the API on."
+
+[generators.deploy.params.workers]
+type = "int"
+default = 4
+help = "Number of API workers, for the prod and nginx modes."
+
+[generators.deploy.params.internal_subnet]
+type = "cidr"
+default = "172.31.240.0/24"
+max_prefix = 8
+help = "The compose network, and the only peers uvicorn takes forwarded headers from, in nginx mode."
+
+[commands."env gen-secret"]
+module = "scripts.gen_secret"
+help = "Print a secret key the project's own rules accept."
+outside_project = "token_hex"
+
+[commands."env validate"]
+module = "scripts.validate_env"
+help = "Audit this environment the way production would."
+
+[commands."db tables"]
+module = "scripts.create_tables"
+help = "Create the tables the models declare, without alembic."
+
+[commands."db seed"]
+module = "scripts.setup_initial_data"
+help = "Run the initial-data steps of the selected features, in order."
diff --git a/fastro.toml b/fastro.toml
new file mode 100644
index 00000000..ee853cbe
--- /dev/null
+++ b/fastro.toml
@@ -0,0 +1,10 @@
+source = true
+features = ["accounts", "rbac", "ratelimit", "tiers", "tier_limits", "api_keys", "admin", "cache", "taskiq"]
+blueprint = { name = "fastro", version = "0.20.0" }
+
+[project]
+name = "fastapi-boilerplate"
+
+[options]
+"cache.backend" = "redis"
+"taskiq.broker" = "redis"
From 951950b99013800c0c5bbf1b939c2706d7cfee6d Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Wed, 28 Oct 2026 19:12:31 -0300
Subject: [PATCH 15/71] declare the commands each feature brings with it
---
backend/tests/unit/test_blueprint_catalog.py | 129 ++++++++++++++++---
blueprint.toml | 28 ++++
2 files changed, 140 insertions(+), 17 deletions(-)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 910e13e9..b41b9aad 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -18,6 +18,7 @@
import re
import sys
import tomllib
+from collections.abc import Iterable
from pathlib import Path
from typing import Any
@@ -1222,11 +1223,46 @@ def test_the_defaults_are_what_this_repos_own_generator_already_uses():
assert f'DEFAULT_INTERNAL_SUBNET = "{params["internal_subnet"]["default"]}"' in subnet
-@pytest.mark.parametrize("words", sorted(_catalog()["commands"]))
-def test_every_command_is_spelled_the_way_the_spec_reads_it(words: str):
- """Spec 2.9: the words become the command path, one space apart."""
- command = _catalog()["commands"][words]
+def _declared_commands() -> list[tuple[str | None, str, dict[str, Any]]]:
+ """Every declared command: the feature that owns it, or none, with its words and its table.
+
+ A list rather than a table keyed by the words, because two declarations of one command are
+ what spec 2.9 refuses, and a table would quietly keep the second.
+ """
+ declared: list[tuple[str | None, str, dict[str, Any]]] = [
+ (None, words, command) for words, command in _catalog()["commands"].items()
+ ]
+ for name, feature in _catalog()["features"].items():
+ declared.extend((name, words, command) for words, command in feature.get("commands", {}).items())
+
+ return declared
+
+
+def _script_of(command: dict[str, Any]) -> str:
+ return f"{_catalog()['blueprint']['python_root']}/{Path(*command['module'].split('.')).with_suffix('.py')}"
+
+
+def _under(script: str, paths: Iterable[str]) -> bool:
+ """Spec 1.1: a declaration names the file itself, or a subtree it sits in."""
+ return any(script == path or script.startswith(f"{path}/") for path in paths)
+
+def _sorted_commands() -> list[tuple[str | None, str, dict[str, Any]]]:
+ return sorted(_declared_commands(), key=lambda entry: entry[1])
+
+
+COMMANDS = [pytest.param(words, command, id=words) for _, words, command in _sorted_commands()]
+
+TOP_LEVEL_COMMANDS = [pytest.param(words, command, id=words) for owner, words, command in _sorted_commands() if owner is None]
+
+FEATURE_COMMANDS = [
+ pytest.param(owner, words, command, id=words) for owner, words, command in _sorted_commands() if owner is not None
+]
+
+
+@pytest.mark.parametrize(("words", "command"), COMMANDS)
+def test_every_command_is_spelled_the_way_the_spec_reads_it(words: str, command: dict[str, Any]):
+ """Spec 2.9: the words become the command path, one space apart."""
assert all(COMMAND_WORD.match(word) for word in words.split(" "))
assert " " not in words
assert all(part.isidentifier() and not keyword.iskeyword(part) for part in command["module"].split("."))
@@ -1235,27 +1271,86 @@ def test_every_command_is_spelled_the_way_the_spec_reads_it(words: str):
assert command.get("outside_project", "error") in {"error", "token_hex"}
-@pytest.mark.parametrize("words", sorted(_catalog()["commands"]))
-def test_every_command_runs_a_module_this_repo_can_run(words: str):
+@pytest.mark.parametrize(("words", "command"), COMMANDS)
+def test_every_command_runs_a_module_this_repo_can_run(words: str, command: dict[str, Any]):
"""It is run as `python -m `, which needs the entry point that makes that work."""
- module = _catalog()["commands"][words]["module"]
- path = REPO_ROOT / _catalog()["blueprint"]["python_root"] / Path(*module.split(".")).with_suffix(".py")
+ path = REPO_ROOT / _catalog()["blueprint"]["python_root"] / Path(*command["module"].split(".")).with_suffix(".py")
- assert path.is_file()
+ assert path.is_file(), words
assert '__name__ == "__main__"' in path.read_text()
-@pytest.mark.parametrize("words", sorted(_catalog()["commands"]))
-def test_every_command_runs_a_script_no_feature_takes_away(words: str):
- """A command carries no condition (spec 2.9), so one naming a feature's script would break.
+def test_no_two_commands_claim_the_same_words():
+ """Spec 2.9: the words are unique across `[commands]` and every feature's.
+
+ fastro refuses the catalog at the second declaration, so a repeat is a catalog no project
+ can be generated from at all.
+ """
+ claimed = [words for _, words, _ in _declared_commands()]
+
+ assert sorted(claimed) == sorted(set(claimed))
+
+
+@pytest.mark.parametrize(("words", "command"), TOP_LEVEL_COMMANDS)
+def test_every_command_runs_a_script_no_feature_takes_away(words: str, command: dict[str, Any]):
+ """`[commands]` are always present (spec 2.9), so one naming a feature's script would break.
+
+ `scripts/unlock_account.py` goes with accounts, so it is accounts that declares
+ `fastro users unlock`: top-level, the command would be there in a project without the
+ module it runs.
+ """
+ assert not _under(_script_of(command), _owned_paths()), words
+
+
+@pytest.mark.parametrize(("owner", "words", "command"), FEATURE_COMMANDS)
+def test_every_feature_command_sits_under_its_features_own_paths(owner: str, words: str, command: dict[str, Any]):
+ """Spec 2.9: under the feature's own `paths`, not a `when`'s, which a selection still drops."""
+ declared = _declared(_catalog()["features"][owner])
+ script = _script_of(command)
+
+ assert _under(script, [path for path, condition in declared if condition is None]), words
+ assert not _under(script, [path for path, condition in declared if condition is not None]), words
+
+
+def test_the_feature_commands_are_every_feature_owned_script_a_project_could_run():
+ """Both ways, and against the repository rather than against the catalog's own account.
- `scripts/unlock_account.py` goes with accounts, and `fastro users unlock` in a project
- without accounts would be a command pointing at a module that isn't there.
+ A runnable script of a feature's own that nothing declares is a command no project is
+ offered, and a command for a module its feature doesn't own is one some project is left
+ without.
"""
- module = _catalog()["commands"][words]["module"]
- script = f"{_catalog()['blueprint']['python_root']}/{Path(*module.split('.')).with_suffix('.py')}"
+ python_root = _catalog()["blueprint"]["python_root"]
+ directory = REPO_ROOT / python_root / "scripts"
+ runnable = {
+ f"{python_root}/scripts/{script.name}"
+ for script in sorted(directory.glob("*.py"))
+ if _under(f"{python_root}/scripts/{script.name}", _owned_paths()) and '__name__ == "__main__"' in script.read_text()
+ }
+
+ assert runnable, directory
+ assert {_script_of(command) for owner, _, command in _declared_commands() if owner is not None} == runnable
+
+
+def test_every_selection_carries_the_commands_whose_module_it_keeps():
+ """A feature's command is there only where the feature is (spec 2.4).
+
+ That has to be exactly where the module it runs is still on disk: a command offered by a
+ project that cannot run it is worse than no command, and one a project could run but is
+ never offered is work thrown away.
+ """
+ manifest = _drill()
+ owned = _owned_paths()
+
+ for chosen in _selections(manifest):
+ kept = _kept_by_the_drill(manifest, chosen)
+ offered = {words for owner, words, _ in _declared_commands() if owner is None or owner in chosen}
+ runnable = {
+ words
+ for _, words, command in _declared_commands()
+ if not _under(_script_of(command), owned) or _under(_script_of(command), kept)
+ }
- assert script not in _owned_paths(), script
+ assert offered == runnable, sorted(chosen)
def test_the_blueprint_repo_says_it_is_the_blueprint():
diff --git a/blueprint.toml b/blueprint.toml
index 38eb2cc5..0e92f2e0 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -219,6 +219,18 @@ table_modules = [{ value = "src.infrastructure.auth.store" }]
seeders = [{ ref = "scripts.create_first_superuser:create_first_superuser", order = 11 }]
test_plugins = [{ value = "tests.fixtures.accounts" }]
+[features.accounts.commands."users unlock"]
+module = "scripts.unlock_account"
+help = "Clear the login lockout an account is held in."
+
+[features.accounts.commands."users canonicalize-emails"]
+module = "scripts.canonicalize_emails"
+help = "Rewrite the user addresses stored with case or whitespace in them."
+
+[features.accounts.commands."users create-superuser"]
+module = "scripts.create_first_superuser"
+help = "Create the first superuser from the admin environment variables."
+
[[features.accounts.when]]
if = "admin"
paths = [
@@ -295,6 +307,10 @@ user_schema = ["src.modules.tier.contrib:UserTierFields"]
seeders = [{ ref = "scripts.create_first_tier:create_first_tier", order = 10 }]
test_plugins = [{ value = "tests.fixtures.tiers" }]
+[features.tiers.commands."tiers create-default"]
+module = "scripts.create_first_tier"
+help = "Create the default tier DEFAULT_TIER_NAME names, if it isn't there yet."
+
[[features.tiers.when]]
if = "admin"
paths = [
@@ -343,6 +359,18 @@ installers = ["src.modules.api_keys.install:install as api_keys_install"]
settings = ["src.modules.api_keys.settings:APIKeySettings"]
extra_transports = [{ ref = "src.modules.api_keys.transport:APIKeyTransport", call = true }]
+[features.api_keys.commands."keys cleanup-json"]
+module = "scripts.cleanup_api_key_json"
+help = "Repair the API key rows whose JSON columns hold something nothing can read."
+
+[features.api_keys.commands."keys prune-usage"]
+module = "scripts.prune_key_usage"
+help = "Delete the API key usage rows past the retention."
+
+[features.api_keys.commands."keys revoke-scrypt"]
+module = "scripts.revoke_scrypt_api_keys"
+help = "Name the API keys still stored under a scrypt hash, and revoke them when asked."
+
[[features.api_keys.when]]
if = "ratelimit"
paths = [
From 1ae7f452f3c47d0285b9f024fd5ef615713845cb Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Wed, 28 Oct 2026 23:53:37 -0300
Subject: [PATCH 16/71] write the baseline migration from a script, and declare
it as a command
---
backend/scripts/baseline.py | 182 +++++++++++++++
backend/tests/unit/scripts/test_baseline.py | 240 ++++++++++++++++++++
blueprint.toml | 4 +
docs/user-guide/database/migrations.md | 6 +
docs/user-guide/project-structure.md | 2 +
5 files changed, 434 insertions(+)
create mode 100644 backend/scripts/baseline.py
create mode 100644 backend/tests/unit/scripts/test_baseline.py
diff --git a/backend/scripts/baseline.py b/backend/scripts/baseline.py
new file mode 100644
index 00000000..cc5dbb91
--- /dev/null
+++ b/backend/scripts/baseline.py
@@ -0,0 +1,182 @@
+"""Write this project's baseline migration, and check that it recreates the models.
+
+Run it once, from ``backend/``:
+
+ python -m scripts.baseline
+ python -m scripts.baseline --check
+
+It starts a throwaway Postgres, autogenerates the revision against it, applies it to that
+empty database, and compares the tables and indexes it created with the ones the models
+declare. The revision is left in ``migrations/versions/`` to be committed. ``--check`` deletes
+it again, so a project can be checked without gaining a migration.
+
+A project that already has a revision is refused: a baseline is a project's first migration,
+and autogenerating one against an empty database beside a history writes a revision that
+recreates what the history already created.
+"""
+
+import argparse
+import asyncio
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+backend_dir = Path(__file__).parent.parent
+sys.path.append(str(backend_dir))
+
+from sqlalchemy import Connection, inspect # noqa: E402
+from testcontainers.postgres import PostgresContainer # noqa: E402
+
+from src.infrastructure.database.registry import import_models # noqa: E402
+from src.infrastructure.database.session import Base, build_engine # noqa: E402
+
+IMAGE = "postgres:16-alpine"
+
+MESSAGE = "baseline"
+"""What the revision is named after, which alembic turns into the slug its file is named with."""
+
+VERSIONS = Path("migrations/versions")
+
+EXPOSED_PORT = 5432
+
+
+class BaselineError(Exception):
+ """What went wrong, as the line the script exits with."""
+
+
+def alembic(*arguments: str) -> subprocess.CompletedProcess[str]:
+ return subprocess.run([sys.executable, "-m", "alembic", *arguments], capture_output=True, text=True)
+
+
+def connection_settings(postgres: PostgresContainer) -> dict[str, str]:
+ """The container, as the settings an alembic run reads the database from.
+
+ ``DATABASE_URL`` is blanked because it wins over these: a configured one would send the
+ autogenerate at the database the project really uses.
+ """
+ return {
+ "POSTGRES_SERVER": postgres.get_container_host_ip(),
+ "POSTGRES_PORT": str(postgres.get_exposed_port(EXPOSED_PORT)),
+ "POSTGRES_USER": postgres.username,
+ "POSTGRES_PASSWORD": postgres.password,
+ "POSTGRES_DB": postgres.dbname,
+ "DATABASE_URL": "",
+ }
+
+
+def database_url(postgres: PostgresContainer) -> str:
+ details = connection_settings(postgres)
+
+ return (
+ f"postgresql+asyncpg://{details['POSTGRES_USER']}:{details['POSTGRES_PASSWORD']}"
+ f"@{details['POSTGRES_SERVER']}:{details['POSTGRES_PORT']}/{details['POSTGRES_DB']}"
+ )
+
+
+def declared_schema() -> dict[str, list[str]]:
+ """The tables and named indexes the models declare, beside the one alembic keeps itself."""
+ import_models()
+ declared = {
+ name: sorted(str(index.name) for index in table.indexes if index.name is not None)
+ for name, table in Base.metadata.tables.items()
+ }
+ declared["alembic_version"] = []
+
+ return declared
+
+
+def _reflected(connection: Connection) -> dict[str, list[str]]:
+ """What is really there: an index a constraint brought with it is not counted twice."""
+ inspector = inspect(connection)
+
+ def indexes(table: str) -> list[str]:
+ found = inspector.get_indexes(table)
+ named = [index["name"] for index in found if not index.get("duplicates_constraint")]
+
+ return sorted(name for name in named if name is not None)
+
+ return {table: indexes(table) for table in sorted(inspector.get_table_names())}
+
+
+async def created_schema(url: str) -> dict[str, list[str]]:
+ """What applying the baseline left in the database."""
+ engine = build_engine(url)
+ try:
+ async with engine.connect() as connection:
+ return await connection.run_sync(_reflected)
+ finally:
+ await engine.dispose()
+
+
+def _revisions() -> list[Path]:
+ return sorted(VERSIONS.glob("*.py"))
+
+
+def write_revision() -> Path:
+ """Autogenerate the baseline, and return the one revision it wrote."""
+ before = set(_revisions())
+ autogenerated = alembic("revision", "--autogenerate", "-m", MESSAGE)
+ if autogenerated.returncode != 0:
+ raise BaselineError("autogenerate failed:\n" + autogenerated.stdout + autogenerated.stderr)
+
+ written = [path for path in _revisions() if path not in before]
+ if len(written) != 1:
+ raise BaselineError(f"autogenerate wrote {len(written)} revisions, and a baseline is one")
+
+ if not written[0].name.endswith(f"_{MESSAGE}.py"):
+ raise BaselineError(f"autogenerate wrote {written[0].name}, which is not the baseline")
+
+ return written[0]
+
+
+def write_baseline(url: str, *, keeping: bool) -> str:
+ """Write the baseline and apply it, and say what it recreated."""
+ declared = declared_schema()
+ revision = write_revision()
+ try:
+ applied = alembic("upgrade", "head")
+ if applied.returncode != 0:
+ raise BaselineError("upgrade failed:\n" + applied.stdout + applied.stderr)
+
+ created = asyncio.run(created_schema(url))
+ if created != declared:
+ raise BaselineError(f"the baseline left {created}, while the models declare {declared}")
+ finally:
+ if not keeping:
+ revision.unlink(missing_ok=True)
+
+ indexes = sum(len(names) for names in declared.values())
+
+ return f"a baseline of {len(declared) - 1} tables and {indexes} indexes applies to an empty database"
+
+
+def _refuse_a_history() -> None:
+ history = _revisions()
+ if history:
+ names = ", ".join(path.name for path in history)
+
+ raise BaselineError(f"this project already has {names}, and a baseline is a project's first revision")
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description="Write this project's baseline migration against a throwaway database.")
+ parser.add_argument("--check", action="store_true", help="delete the revision afterwards, leaving the tree as it was")
+ arguments = parser.parse_args(argv)
+
+ os.environ["TESTCONTAINERS_RYUK_DISABLED"] = "true"
+ try:
+ _refuse_a_history()
+ with PostgresContainer(IMAGE) as postgres:
+ os.environ.update(connection_settings(postgres))
+ print(write_baseline(database_url(postgres), keeping=not arguments.check))
+ except BaselineError as error:
+ print(error, file=sys.stderr)
+
+ return 1
+
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/backend/tests/unit/scripts/test_baseline.py b/backend/tests/unit/scripts/test_baseline.py
new file mode 100644
index 00000000..78da1496
--- /dev/null
+++ b/backend/tests/unit/scripts/test_baseline.py
@@ -0,0 +1,240 @@
+"""What the baseline writes, what it refuses, and what it leaves behind.
+
+The container and alembic are mocked, so the suite needs no Docker: what is checked here is
+the script's own reasoning. The revision it writes has to be the baseline rather than any
+revision, and ``--check`` has to leave ``migrations/versions/`` exactly as it found it, since
+that is the mode `fastro verify` runs in a project it has just generated.
+"""
+
+import os
+import subprocess
+import sys
+from collections.abc import Iterator
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from scripts import baseline
+
+HOST = "127.0.0.1"
+PORT = 54321
+
+
+class _Container:
+ """The pieces of a ``PostgresContainer`` the script reads."""
+
+ username = "baseline-user"
+ password = "baseline-password"
+ dbname = "baseline-db"
+
+ def __init__(self, image: str):
+ self.image = image
+
+ def __enter__(self) -> "_Container":
+ return self
+
+ def __exit__(self, *exception: Any) -> None:
+ return None
+
+ def get_container_host_ip(self) -> str:
+ return HOST
+
+ def get_exposed_port(self, port: int) -> int:
+ return PORT
+
+
+class _Alembic:
+ """Alembic as the script calls it: a recorder that writes the revision autogenerate would."""
+
+ def __init__(self, versions: Path, *, revision: str = "0a1b2c3d4e5f", slug: str | None = None, failing: str | None = None):
+ self.versions = versions
+ self.revision = revision
+ self.slug = slug
+ self.failing = failing
+ self.calls: list[tuple[str, ...]] = []
+ self.environments: list[dict[str, str]] = []
+
+ def __call__(self, *arguments: str) -> subprocess.CompletedProcess[str]:
+ self.calls.append(arguments)
+ self.environments.append(dict(os.environ))
+ if self.failing == arguments[0]:
+ return subprocess.CompletedProcess(list(arguments), 1, "", f"{arguments[0]} went wrong")
+
+ if arguments[0] == "revision":
+ slug = self.slug or arguments[arguments.index("-m") + 1]
+ (self.versions / f"{self.revision}_{slug}.py").write_text(f'revision = "{self.revision}"\n')
+
+ return subprocess.CompletedProcess(list(arguments), 0, "", "")
+
+
+@pytest.fixture
+def versions(tmp_path: Path, monkeypatch) -> Path:
+ directory = tmp_path / "versions"
+ directory.mkdir()
+ monkeypatch.setattr(baseline, "VERSIONS", directory)
+
+ return directory
+
+
+@pytest.fixture(autouse=True)
+def _restored_environment() -> Iterator[None]:
+ """The script writes the container's details into the environment, as alembic reads them."""
+ before = dict(os.environ)
+
+ yield
+
+ os.environ.clear()
+ os.environ.update(before)
+
+
+@pytest.fixture
+def container(monkeypatch) -> None:
+ monkeypatch.setattr(baseline, "PostgresContainer", _Container)
+
+
+@pytest.fixture
+def alembic(versions, monkeypatch) -> _Alembic:
+ """Alembic itself is never run: what it would do to the tree is what the script reasons about."""
+ recorder = _Alembic(versions)
+ monkeypatch.setattr(baseline, "alembic", recorder)
+
+ return recorder
+
+
+def _schema_of(declared: dict[str, list[str]]):
+ async def read(url: str) -> dict[str, list[str]]:
+ return declared
+
+ return read
+
+
+@pytest.fixture
+def matching(monkeypatch) -> None:
+ """A database the baseline left holding exactly what the models declare."""
+ monkeypatch.setattr(baseline, "created_schema", _schema_of(baseline.declared_schema()))
+
+
+def _written(versions: Path) -> dict[str, str]:
+ return {path.name: path.read_text() for path in versions.glob("*.py")}
+
+
+def test_it_writes_one_revision_named_after_the_baseline(versions, container, matching, alembic, capsys):
+ code = baseline.main([])
+
+ assert code == 0, capsys.readouterr()
+ assert list(_written(versions)) == ["0a1b2c3d4e5f_baseline.py"]
+ assert "tables" in capsys.readouterr().out
+
+
+def test_it_autogenerates_the_baseline_and_applies_it(versions, container, matching, alembic):
+ baseline.main([])
+
+ assert alembic.calls == [("revision", "--autogenerate", "-m", "baseline"), ("upgrade", "head")]
+
+
+def test_check_leaves_the_versions_directory_as_it_found_it(versions, container, matching, alembic):
+ before = _written(versions)
+
+ code = baseline.main(["--check"])
+
+ assert code == 0
+ assert _written(versions) == before
+ assert ("revision", "--autogenerate", "-m", "baseline") in alembic.calls
+
+
+def test_the_commands_run_against_the_container(versions, container, matching, alembic):
+ baseline.main([])
+
+ environment = alembic.environments[0]
+ assert environment["POSTGRES_SERVER"] == HOST
+ assert environment["POSTGRES_PORT"] == str(PORT)
+ assert environment["POSTGRES_USER"] == _Container.username
+ assert environment["POSTGRES_PASSWORD"] == _Container.password
+ assert environment["POSTGRES_DB"] == _Container.dbname
+ assert environment["DATABASE_URL"] == "", "a configured URL wins over these, and names the real database"
+
+
+def test_a_database_the_models_do_not_declare_is_refused(versions, container, alembic, monkeypatch, capsys):
+ monkeypatch.setattr(baseline, "created_schema", _schema_of({"alembic_version": []}))
+
+ code = baseline.main(["--check"])
+
+ printed = capsys.readouterr()
+ assert code == 1
+ assert "while the models declare" in printed.err
+ assert _written(versions) == {}
+
+
+def test_a_failed_autogenerate_is_reported_with_what_alembic_printed(versions, container, matching, monkeypatch, capsys):
+ monkeypatch.setattr(baseline, "alembic", _Alembic(versions, failing="revision"))
+
+ code = baseline.main([])
+
+ printed = capsys.readouterr()
+ assert code == 1
+ assert "revision went wrong" in printed.err
+ assert _written(versions) == {}
+
+
+def test_a_failed_upgrade_is_withdrawn_under_check(versions, container, matching, monkeypatch, capsys):
+ monkeypatch.setattr(baseline, "alembic", _Alembic(versions, failing="upgrade"))
+
+ code = baseline.main(["--check"])
+
+ printed = capsys.readouterr()
+ assert code == 1
+ assert "upgrade went wrong" in printed.err
+ assert _written(versions) == {}
+
+
+def test_a_revision_that_is_not_the_baseline_is_refused(versions, container, matching, monkeypatch, capsys):
+ """Alembic names the file after its own slug, and a project's first revision is the baseline."""
+ monkeypatch.setattr(baseline, "alembic", _Alembic(versions, slug="add_a_column"))
+
+ code = baseline.main(["--check"])
+
+ assert code == 1
+ assert "is not the baseline" in capsys.readouterr().err
+
+
+def test_a_project_that_already_has_a_history_is_refused(versions, container, matching, alembic, capsys):
+ (versions / "f5e4d3c2b1a0_add_a_column.py").write_text('revision = "f5e4d3c2b1a0"\n')
+ before = _written(versions)
+
+ code = baseline.main([])
+
+ printed = capsys.readouterr()
+ assert code == 1
+ assert "f5e4d3c2b1a0_add_a_column.py" in printed.err
+ assert _written(versions) == before
+
+
+def test_the_declared_schema_is_the_one_the_models_build(versions):
+ """It is read in this process, so a models import that stopped working would be silent."""
+ declared = baseline.declared_schema()
+
+ assert declared["alembic_version"] == []
+ assert "user" in declared
+
+
+def test_the_migrations_guide_names_the_script():
+ """The guide's manual recipe is this script by hand, which a reader has no way to know."""
+ guide = Path(baseline.__file__).resolve().parents[2] / "docs/user-guide/database/migrations.md"
+
+ assert "python -m scripts.baseline" in guide.read_text()
+
+
+def test_running_it_as_a_module_takes_the_check_flag():
+ """``--check`` is what verify runs, so an argument parser that refuses it is a broken verify."""
+ result = subprocess.run(
+ [sys.executable, "-m", "scripts.baseline", "--help"],
+ cwd=Path(baseline.__file__).resolve().parents[1],
+ capture_output=True,
+ text=True,
+ env={**os.environ, "PYTHONPATH": str(Path(baseline.__file__).resolve().parents[1])},
+ timeout=120,
+ )
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert "--check" in result.stdout
diff --git a/blueprint.toml b/blueprint.toml
index 0e92f2e0..66c2e4dc 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -716,6 +716,10 @@ outside_project = "token_hex"
module = "scripts.validate_env"
help = "Audit this environment the way production would."
+[commands."db baseline"]
+module = "scripts.baseline"
+help = "Write this project's baseline migration, checked against the models."
+
[commands."db tables"]
module = "scripts.create_tables"
help = "Create the tables the models declare, without alembic."
diff --git a/docs/user-guide/database/migrations.md b/docs/user-guide/database/migrations.md
index 8be1f0d6..f1fac7e1 100644
--- a/docs/user-guide/database/migrations.md
+++ b/docs/user-guide/database/migrations.md
@@ -31,6 +31,12 @@ Tracked, reviewable, reversible schema changes — what you want for anything be
want ([Composable Features](../composable-features.md)), then generate the baseline for what's
left.
+ **The script does all of this.** `uv run --no-sync python -m scripts.baseline` starts a
+ throwaway Postgres, autogenerates the revision against it, checks that applying it recreates
+ exactly what the models declare, and leaves it in `migrations/versions/` to commit; `--check`
+ deletes it again. The rest of this section is the same thing by hand, for when Docker isn't
+ there.
+
**Generate it against a database with nothing in it.** Autogenerate writes the difference
between the models and the database it connects to, so pointing it at a database that already
has the schema — a dev stack, which `CREATE_TABLES_ON_STARTUP` built with `create_all` — writes
diff --git a/docs/user-guide/project-structure.md b/docs/user-guide/project-structure.md
index c0417621..9694c951 100644
--- a/docs/user-guide/project-structure.md
+++ b/docs/user-guide/project-structure.md
@@ -29,6 +29,7 @@ backend/
│ ├── script.py.mako
│ └── versions/
├── scripts/ # Setup and maintenance scripts
+│ ├── baseline.py # Writes the project's first migration, checked against the models
│ ├── canonicalize_emails.py
│ ├── cleanup_api_key_json.py
│ ├── create_first_superuser.py
@@ -207,6 +208,7 @@ scripts/
├── create_first_superuser.py # Just the admin user
├── create_first_tier.py # Just the default tier
├── create_tables.py # Just the database tables
+├── baseline.py # Writes the project's first migration, checked against the models
├── cleanup_api_key_json.py # One-off repair for legacy API key rows
├── canonicalize_emails.py # One-off repair for addresses stored with case or spaces
├── unlock_account.py # Clears the login lockout one account is held in
From 7e49c355cfe6e8ddf4b093fb614e5b5b86db34f4 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Thu, 29 Oct 2026 00:09:27 -0300
Subject: [PATCH 17/71] say in every generated file that fastro generated it
---
backend/scripts/seeders.py | 3 +-
backend/src/wiring/__init__.py | 2 +-
backend/src/wiring/admin.py | 3 +-
backend/src/wiring/app.py | 4 +-
backend/src/wiring/cache.py | 4 +-
backend/src/wiring/email.py | 7 +--
backend/src/wiring/hooks.py | 4 +-
backend/src/wiring/models.py | 3 +-
backend/src/wiring/settings.py | 6 ++-
backend/src/wiring/tables.py | 4 +-
backend/src/wiring/tasks.py | 7 +--
backend/src/wiring/transports.py | 6 ++-
backend/tests/unit/test_blueprint_catalog.py | 56 +++++++++++++++-----
backend/tests/wiring.py | 3 +-
14 files changed, 78 insertions(+), 34 deletions(-)
diff --git a/backend/scripts/seeders.py b/backend/scripts/seeders.py
index 80df9ee7..e3beb0bd 100644
--- a/backend/scripts/seeders.py
+++ b/backend/scripts/seeders.py
@@ -1,6 +1,7 @@
"""The initial-data steps ``scripts/setup_initial_data.py`` runs, in order.
-Written by the generator in `tools/removal_drill.py`, which a test compares this file against.
+Generated by fastro from blueprint.toml and fastro.toml. Don't edit: change
+fastro.toml (or [app] in it, for your own code) and run `fastro sync`.
"""
from collections.abc import Awaitable, Callable
diff --git a/backend/src/wiring/__init__.py b/backend/src/wiring/__init__.py
index 80bd5182..4cc6f27b 100644
--- a/backend/src/wiring/__init__.py
+++ b/backend/src/wiring/__init__.py
@@ -1,5 +1,5 @@
"""The composition root: where the selected features meet.
-Every module here is hand-maintained until the generator exists, and holds only
+Every module beside this one is generated by fastro from ``blueprint.toml``, and holds only
imports and literals, so ruff, mypy and an IDE see exactly what is wired.
"""
diff --git a/backend/src/wiring/admin.py b/backend/src/wiring/admin.py
index 683ae994..263ad262 100644
--- a/backend/src/wiring/admin.py
+++ b/backend/src/wiring/admin.py
@@ -1,6 +1,7 @@
"""The model views the admin panel registers.
-Written by the generator in `tools/removal_drill.py`, which a test compares this file against.
+Generated by fastro from blueprint.toml and fastro.toml. Don't edit: change
+fastro.toml (or [app] in it, for your own code) and run `fastro sync`.
"""
from ..modules.role.admin import RoleAdmin, RolePermissionAdmin, UserRoleAdmin
diff --git a/backend/src/wiring/app.py b/backend/src/wiring/app.py
index bda0046e..02e62360 100644
--- a/backend/src/wiring/app.py
+++ b/backend/src/wiring/app.py
@@ -1,7 +1,7 @@
"""The composition root: what the app mounts, starts and installs.
-Written by the generator in `tools/removal_drill.py`, which a test compares this file against:
-imports and literals only, so ruff, mypy and an IDE see exactly what is wired.
+Generated by fastro from blueprint.toml and fastro.toml. Don't edit: change
+fastro.toml (or [app] in it, for your own code) and run `fastro sync`.
"""
from collections.abc import Callable
diff --git a/backend/src/wiring/cache.py b/backend/src/wiring/cache.py
index ab4b866e..d53bd5b5 100644
--- a/backend/src/wiring/cache.py
+++ b/backend/src/wiring/cache.py
@@ -1,7 +1,7 @@
"""The decorator a route caches its response with.
-Written by the generator in `tools/removal_drill.py`, which a test compares this file against:
-imports and literals only.
+Generated by fastro from blueprint.toml and fastro.toml. Don't edit: change
+fastro.toml (or [app] in it, for your own code) and run `fastro sync`.
"""
from ..infrastructure.cache.decorator import cache as cached
diff --git a/backend/src/wiring/email.py b/backend/src/wiring/email.py
index 723a1086..d472e5c2 100644
--- a/backend/src/wiring/email.py
+++ b/backend/src/wiring/email.py
@@ -1,8 +1,9 @@
"""The sender the account emails go out through.
-Written by the generator in `tools/removal_drill.py`, which a test compares this file against:
-imports and literals only. It is its own module because ``hooks`` reaches features that import the
-accounts feature back.
+It is its own module because ``hooks`` reaches features that import the accounts feature back.
+
+Generated by fastro from blueprint.toml and fastro.toml. Don't edit: change
+fastro.toml (or [app] in it, for your own code) and run `fastro sync`.
"""
from crudauth import EmailSender
diff --git a/backend/src/wiring/hooks.py b/backend/src/wiring/hooks.py
index b7b5f66f..434d9f32 100644
--- a/backend/src/wiring/hooks.py
+++ b/backend/src/wiring/hooks.py
@@ -1,7 +1,7 @@
"""The contributions features make to each other's extension points.
-Written by the generator in `tools/removal_drill.py`, which a test compares this file against:
-imports and literals only.
+Generated by fastro from blueprint.toml and fastro.toml. Don't edit: change
+fastro.toml (or [app] in it, for your own code) and run `fastro sync`.
"""
from ..infrastructure.auth.health import limiter_readiness, sessions_readiness
diff --git a/backend/src/wiring/models.py b/backend/src/wiring/models.py
index a32214fa..363c4324 100644
--- a/backend/src/wiring/models.py
+++ b/backend/src/wiring/models.py
@@ -1,6 +1,7 @@
"""Extension points of the user model: what other features add to ``User``.
-Written by the generator in `tools/removal_drill.py`, which a test compares this file against.
+Generated by fastro from blueprint.toml and fastro.toml. Don't edit: change
+fastro.toml (or [app] in it, for your own code) and run `fastro sync`.
"""
from ..modules.role.contrib import UserRoleColumns
diff --git a/backend/src/wiring/settings.py b/backend/src/wiring/settings.py
index 1d3d4b89..72a1c347 100644
--- a/backend/src/wiring/settings.py
+++ b/backend/src/wiring/settings.py
@@ -1,7 +1,9 @@
"""The project's settings: each selected feature's mixin on top of the core.
-Written by the generator in `tools/removal_drill.py`, which a test compares this file against. Core
-comes last, so a feature can override a core default rather than the other way round.
+Core comes last, so a feature can override a core default rather than the other way round.
+
+Generated by fastro from blueprint.toml and fastro.toml. Don't edit: change
+fastro.toml (or [app] in it, for your own code) and run `fastro sync`.
"""
from ..infrastructure.auth.settings import AccountsSettings
diff --git a/backend/src/wiring/tables.py b/backend/src/wiring/tables.py
index 3c9e797c..f18c7cf6 100644
--- a/backend/src/wiring/tables.py
+++ b/backend/src/wiring/tables.py
@@ -1,7 +1,7 @@
"""Modules outside ``src/modules`` that declare tables on ``Base.metadata``.
-Written by the generator in `tools/removal_drill.py`, which a test compares this file against:
-imports and literals only.
+Generated by fastro from blueprint.toml and fastro.toml. Don't edit: change
+fastro.toml (or [app] in it, for your own code) and run `fastro sync`.
"""
TABLE_MODULES: tuple[str, ...] = ("src.infrastructure.auth.store",)
diff --git a/backend/src/wiring/tasks.py b/backend/src/wiring/tasks.py
index 61bb4ba1..6fd060b2 100644
--- a/backend/src/wiring/tasks.py
+++ b/backend/src/wiring/tasks.py
@@ -1,8 +1,9 @@
"""The modules whose background tasks the worker registers.
-Written by the generator in `tools/removal_drill.py`, which a test compares this file against:
-imports and literals only. A task the worker reports as unknown drops its message, so a module
-declaring one belongs in this list.
+A task the worker reports as unknown drops its message, so a module declaring one belongs in this list.
+
+Generated by fastro from blueprint.toml and fastro.toml. Don't edit: change
+fastro.toml (or [app] in it, for your own code) and run `fastro sync`.
"""
TASK_MODULES: tuple[str, ...] = (
diff --git a/backend/src/wiring/transports.py b/backend/src/wiring/transports.py
index 8488ccd3..ffb4998b 100644
--- a/backend/src/wiring/transports.py
+++ b/backend/src/wiring/transports.py
@@ -1,4 +1,8 @@
-"""The authentication transports this project registers beside the session one."""
+"""The authentication transports this project registers beside the session one.
+
+Generated by fastro from blueprint.toml and fastro.toml. Don't edit: change
+fastro.toml (or [app] in it, for your own code) and run `fastro sync`.
+"""
from crudauth import Transport
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index b41b9aad..1c40d883 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -885,18 +885,6 @@ def test_every_wiring_file_is_under_the_python_root_and_is_a_file(path: str):
assert (REPO_ROOT / path).is_file()
-@pytest.mark.parametrize("path", [entry["path"] for entry in _entries()])
-def test_every_wiring_file_says_what_it_is_for(path: str):
- """The entry's `doc` is the file's own docstring, minus the line naming what generated it."""
- entry = next(entry for entry in _entries() if entry["path"] == path)
- docstring = ast.get_docstring(ast.parse(_committed(path)))
-
- assert docstring is not None
- declared = entry["doc"].splitlines()
- assert declared[0] == docstring.splitlines()[0]
- assert " ".join(" ".join(declared[1:]).split()) in " ".join(docstring.split())
-
-
@pytest.mark.parametrize(
("path", "name"),
[(entry["path"], slot["name"]) for entry in _entries() for slot in entry["slots"] if "annotation" in slot],
@@ -1074,6 +1062,50 @@ def test_the_header_fits_the_line_length_of_the_files_it_goes_into():
assert len(line) <= 100, line
+HAND_WRITTEN = "backend/src/wiring/__init__.py"
+"""The one module beside the generated ones that a person writes, and fastro never rewrites."""
+
+
+def _docstring(source: str) -> str | None:
+ """The module docstring as it is written, rather than as ``ast`` tidies it up."""
+ body = ast.parse(source).body
+ if body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant):
+ return str(body[0].value.value)
+
+ return None
+
+
+@pytest.mark.parametrize("path", [entry["path"] for entry in _entries()])
+def test_every_generated_file_carries_its_doc_and_then_the_header(path: str):
+ """Spec 2.8: the entry's `doc`, a blank line, then the header, each stripped before rendering.
+
+ This is the whole docstring, so a paragraph the file carries and the catalog doesn't is one
+ `fastro sync` would delete from a project without being asked.
+ """
+ entry = next(declared for declared in _entries() if declared["path"] == path)
+ header = _catalog()["wiring_defaults"]["header"]
+
+ assert _docstring(_committed(path)) == f"{entry['doc'].strip()}\n\n{header.strip()}\n"
+
+
+@pytest.mark.parametrize("path", [entry["path"] for entry in _entries()])
+def test_no_generated_file_names_the_drill(path: str):
+ """The header names fastro as the author, and the drill goes in B3: two authors is one too many."""
+ assert "removal_drill" not in _committed(path), path
+
+
+def test_the_hand_written_module_says_who_writes_the_ones_beside_it():
+ """It is not generated, so it is where the reason lives: once, in the file a person edits."""
+ docstring = _docstring(_committed(HAND_WRITTEN))
+
+ assert HAND_WRITTEN not in [entry["path"] for entry in _entries()]
+ assert docstring is not None
+ assert "fastro" in docstring
+ assert "blueprint.toml" in docstring
+ assert "imports and literals" in docstring
+ assert "removal_drill" not in docstring
+
+
@pytest.mark.parametrize("path", [entry["path"] for entry in _entries()])
def test_the_catalog_accounts_for_what_the_file_imports_for_every_selection(path: str):
"""The fallbacks, where the committed files cannot reach: nothing falls back with all nine.
diff --git a/backend/tests/wiring.py b/backend/tests/wiring.py
index 35b14696..c33cbdd0 100644
--- a/backend/tests/wiring.py
+++ b/backend/tests/wiring.py
@@ -1,6 +1,7 @@
"""Fixture modules of the selected features, loaded by ``tests/conftest.py``.
-Written by the generator in `tools/removal_drill.py`, which a test compares this file against.
+Generated by fastro from blueprint.toml and fastro.toml. Don't edit: change
+fastro.toml (or [app] in it, for your own code) and run `fastro sync`.
"""
PYTEST_PLUGINS: list[str] = [
From 48e8107f50e6aab241745d76f3f2c52217b755bc Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Fri, 30 Oct 2026 20:12:27 -0300
Subject: [PATCH 18/71] name the secret command what fastro names it, and keep
the blueprint's own root files out of projects
---
backend/tests/unit/test_blueprint_catalog.py | 66 ++++++++++++++++++++
blueprint.toml | 5 +-
2 files changed, 70 insertions(+), 1 deletion(-)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 1c40d883..85bc3b37 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -111,6 +111,72 @@ def test_every_blueprint_only_path_is_one_this_repo_has(entry: str):
assert (REPO_ROOT / entry).exists()
+def _withheld(path: str) -> bool:
+ """Whether `blueprint_only` keeps a project from receiving this path (spec 1.1 subtrees)."""
+ return any(path == entry.rstrip("/") or path.startswith(entry) for entry in _catalog()["blueprint"]["blueprint_only"])
+
+
+def _workspace_members() -> list[str]:
+ with (REPO_ROOT / "pyproject.toml").open("rb") as handle:
+ return list(tomllib.load(handle)["tool"]["uv"]["workspace"]["members"])
+
+
+def _hook_paths() -> list[str]:
+ """The literal head of each pre-commit `files:` pattern, which is a path in the repository."""
+ patterns = re.findall(r"^\s*files: (\S+)$", (REPO_ROOT / ".pre-commit-config.yaml").read_text(), re.M)
+
+ return [re.split(r"[(\[{|?*+.\\]", pattern.removeprefix("^"))[0].rstrip("/") for pattern in patterns]
+
+
+def _readme_references() -> list[str]:
+ """The files the README's own markup points at, leaving out what it fetches over the network."""
+ found = re.findall(r'src(?:set)?="([^"]+)"', (REPO_ROOT / "README.md").read_text())
+
+ return [reference for reference in found if not reference.startswith("http")]
+
+
+POINTS_AT = {
+ "pyproject.toml": _workspace_members,
+ ".pre-commit-config.yaml": _hook_paths,
+ "README.md": _readme_references,
+}
+"""Each root file that names paths, read the way that file spells them."""
+
+
+@pytest.mark.parametrize("path", sorted(POINTS_AT))
+def test_no_file_a_project_receives_points_at_one_it_does_not(path: str):
+ """Either the pointer goes or the file does.
+
+ A workspace member a project never receives is a project `uv sync` refuses; a lint pattern
+ is a hook over nothing; an image is a hole where the cover was. The three root files are
+ the blueprint's own, so they are the ones that go.
+ """
+ withheld = sorted(target for target in POINTS_AT[path]() if _withheld(target))
+
+ assert not withheld or _withheld(path), (path, withheld)
+
+
+WITHHELD_POINTERS = {
+ "pyproject.toml": "cli",
+ ".pre-commit-config.yaml": "cli/src",
+ "README.md": "docs/assets",
+}
+"""What keeps each of the three out of a project, pinned so a reader of it can't go quiet."""
+
+
+@pytest.mark.parametrize("path", sorted(POINTS_AT))
+def test_each_file_still_names_the_path_that_keeps_it_out(path: str):
+ """The reason each file is blueprint-only, rather than the fact of it.
+
+ A format that moved on -- a renamed pre-commit key, an image moved out of `docs/` -- would
+ leave the rule above with nothing to object to, and the file would ship. When `cli/` goes
+ in B3, this is where the question of shipping the workspace root comes back.
+ """
+ pointed = POINTS_AT[path]()
+
+ assert any(target.startswith(WITHHELD_POINTERS[path]) for target in pointed), pointed
+
+
def test_the_things_projects_must_not_receive_are_listed():
"""The catalog, the drill, the docs and the tool's own tree belong to the blueprint only."""
listed = set(_catalog()["blueprint"]["blueprint_only"])
diff --git a/blueprint.toml b/blueprint.toml
index 66c2e4dc..af2cf8c7 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -7,8 +7,10 @@ python_root = "backend"
import_root = "src"
blueprint_only = [
".github/",
+ ".pre-commit-config.yaml",
"CODE_OF_CONDUCT.md",
"CONTRIBUTING.md",
+ "README.md",
"backend/tests/unit/test_blueprint_catalog.py",
"backend/tests/unit/test_docs_imports.py",
"backend/tests/unit/test_docs_recipes.py",
@@ -20,6 +22,7 @@ blueprint_only = [
"cli/",
"docs/",
"fastro.toml",
+ "pyproject.toml",
"tools/",
"uv.lock",
"zensical.toml",
@@ -707,7 +710,7 @@ default = "172.31.240.0/24"
max_prefix = 8
help = "The compose network, and the only peers uvicorn takes forwarded headers from, in nginx mode."
-[commands."env gen-secret"]
+[commands."env secret"]
module = "scripts.gen_secret"
help = "Print a secret key the project's own rules accept."
outside_project = "token_hex"
From c7de105bdb0814c75ff18a03b06ba1c99a8e2bff Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Sat, 31 Oct 2026 00:00:54 -0300
Subject: [PATCH 19/71] keep the blueprint's own files out of the projects the
drill builds
---
backend/tests/unit/scripts/test_baseline.py | 51 ++++++++++++++----
.../tests/unit/scripts/test_validate_env.py | 52 ++++++++++++++++---
backend/tests/unit/test_blueprint_catalog.py | 50 +++++++++++++++++-
backend/tests/unit/test_docs_scripts.py | 9 ++++
backend/tests/unit/test_removal_drill.py | 19 +++++++
blueprint.toml | 1 +
tools/removal_drill.py | 15 ++++++
7 files changed, 180 insertions(+), 17 deletions(-)
diff --git a/backend/tests/unit/scripts/test_baseline.py b/backend/tests/unit/scripts/test_baseline.py
index 78da1496..0a5d362e 100644
--- a/backend/tests/unit/scripts/test_baseline.py
+++ b/backend/tests/unit/scripts/test_baseline.py
@@ -16,10 +16,13 @@
import pytest
from scripts import baseline
+from src.infrastructure.database.session import Base
HOST = "127.0.0.1"
PORT = 54321
+BACKEND = Path(baseline.__file__).resolve().parents[1]
+
class _Container:
"""The pieces of a ``PostgresContainer`` the script reads."""
@@ -156,7 +159,8 @@ def test_the_commands_run_against_the_container(versions, container, matching, a
def test_a_database_the_models_do_not_declare_is_refused(versions, container, alembic, monkeypatch, capsys):
- monkeypatch.setattr(baseline, "created_schema", _schema_of({"alembic_version": []}))
+ """The table named here is one no project declares, so it is a mismatch whatever is selected."""
+ monkeypatch.setattr(baseline, "created_schema", _schema_of({"alembic_version": [], "nothing_declares_this": []}))
code = baseline.main(["--check"])
@@ -211,28 +215,57 @@ def test_a_project_that_already_has_a_history_is_refused(versions, container, ma
def test_the_declared_schema_is_the_one_the_models_build(versions):
- """It is read in this process, so a models import that stopped working would be silent."""
+ """The tables are the ones this project's features declare, read rather than listed.
+
+ A project without accounts has no `user`, and one with no features has only alembic's own,
+ which the script adds because a baseline creates the table alembic records itself in.
+ """
declared = baseline.declared_schema()
assert declared["alembic_version"] == []
- assert "user" in declared
+ assert set(declared) == set(Base.metadata.tables) | {"alembic_version"}
+ assert all(indexes == sorted(indexes) for indexes in declared.values())
+
+
+_COLD_SCHEMA = """
+from scripts.baseline import declared_schema
+
+print(sorted(name for name in declared_schema() if name != "alembic_version"))
+"""
+
+def test_the_script_imports_the_models_itself():
+ """Only a cold interpreter can tell: in the suite, `tests/conftest.py` has imported the app,
+ which imports every model, so the metadata is already full whatever the script does.
-def test_the_migrations_guide_names_the_script():
- """The guide's manual recipe is this script by hand, which a reader has no way to know."""
- guide = Path(baseline.__file__).resolve().parents[2] / "docs/user-guide/database/migrations.md"
+ A project that declares no models of its own cannot tell an import that did nothing from one
+ that worked, so it skips rather than passing for the wrong reason.
+ """
+ declared = sorted(Base.metadata.tables)
+ if not declared:
+ pytest.skip("this project declares no models, so a missing import looks like a working one")
- assert "python -m scripts.baseline" in guide.read_text()
+ result = subprocess.run(
+ [sys.executable, "-c", _COLD_SCHEMA],
+ cwd=BACKEND,
+ env={**os.environ, "PYTHONPATH": str(BACKEND)},
+ capture_output=True,
+ text=True,
+ timeout=120,
+ )
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert result.stdout.strip().splitlines()[-1] == str(declared), "the settings log to stdout before it prints"
def test_running_it_as_a_module_takes_the_check_flag():
"""``--check`` is what verify runs, so an argument parser that refuses it is a broken verify."""
result = subprocess.run(
[sys.executable, "-m", "scripts.baseline", "--help"],
- cwd=Path(baseline.__file__).resolve().parents[1],
+ cwd=BACKEND,
capture_output=True,
text=True,
- env={**os.environ, "PYTHONPATH": str(Path(baseline.__file__).resolve().parents[1])},
+ env={**os.environ, "PYTHONPATH": str(BACKEND)},
timeout=120,
)
diff --git a/backend/tests/unit/scripts/test_validate_env.py b/backend/tests/unit/scripts/test_validate_env.py
index 821803a5..af6c8fae 100644
--- a/backend/tests/unit/scripts/test_validate_env.py
+++ b/backend/tests/unit/scripts/test_validate_env.py
@@ -14,6 +14,7 @@
from typing import Any
import pytest
+from pydantic import AliasChoices
from scripts.validate_env import audit, main
from src.infrastructure.config.settings import EnvironmentOption, Settings
@@ -39,8 +40,31 @@ def _audited(monkeypatch, settings: Settings) -> None:
monkeypatch.setattr("scripts.validate_env.get_settings", lambda: settings)
+def _accepted_names() -> set[str]:
+ """Every name this project's settings take, a field's alias choices included.
+
+ `SESSION_REDIS_PASSWORD` accepts `CACHE_REDIS_PASSWORD` as well, so a project with accounts
+ and no cache still takes that name and reads the session password from it.
+ """
+ accepted = set()
+ for name, field in Settings.model_fields.items():
+ accepted.add(name)
+ alias = field.validation_alias
+ if isinstance(alias, str):
+ accepted.add(alias)
+ elif isinstance(alias, AliasChoices):
+ accepted.update(choice for choice in alias.choices if isinstance(choice, str))
+
+ return accepted
+
+
def _strong() -> dict[str, Any]:
- return {
+ """A configuration production would accept, less whatever this project has no feature for.
+
+ `Settings` forbids an input no field of its own takes, so a project without the cache, the
+ limiter or the admin panel refuses their settings rather than ignoring them.
+ """
+ strong = {
"SECRET_KEY": secrets.token_hex(32),
"POSTGRES_PASSWORD": "a-strong-database-password",
"CORS_ORIGINS": "https://app.example.com",
@@ -54,6 +78,8 @@ def _strong() -> dict[str, Any]:
"RATE_LIMITER_BACKEND": "redis",
}
+ return {name: value for name, value in strong.items() if name in _accepted_names()}
+
def test_a_clean_configuration_says_so(monkeypatch, capsys):
_audited(monkeypatch, _settings(**_strong()))
@@ -77,8 +103,12 @@ def test_a_weak_configuration_is_refused_and_named(monkeypatch, capsys):
def test_warnings_are_reported_even_when_something_is_critical(monkeypatch, capsys):
- """The warnings used to be computed only when nothing critical was found."""
- _audited(monkeypatch, _settings(SECRET_KEY="insecure-secret-key-change-this"))
+ """The warnings used to be computed only when nothing critical was found.
+
+ Both findings are core: the placeholder key is critical and debug mode is a warning, so a
+ project with no features selected still produces one of each.
+ """
+ _audited(monkeypatch, _settings(SECRET_KEY="insecure-secret-key-change-this", DEBUG=True))
code = main()
@@ -89,8 +119,12 @@ def test_warnings_are_reported_even_when_something_is_critical(monkeypatch, caps
def test_warnings_alone_do_not_fail_the_audit(monkeypatch, capsys):
- """A warning is something to look at, not something that would stop a boot."""
- _audited(monkeypatch, _settings(**(_strong() | {"CACHE_REDIS_PASSWORD": ""})))
+ """A warning is something to look at, not something that would stop a boot.
+
+ Debug mode rather than an unprotected cache: the cache is a feature, and this test runs in
+ projects that didn't select it.
+ """
+ _audited(monkeypatch, _settings(**(_strong() | {"DEBUG": True})))
code = main()
@@ -101,8 +135,12 @@ def test_warnings_alone_do_not_fail_the_audit(monkeypatch, capsys):
def test_every_finding_names_the_environment_it_is_checked_for(monkeypatch, capsys):
- """Audited as production, a finding that names a development environment is a lie."""
- _audited(monkeypatch, _settings(ENVIRONMENT=EnvironmentOption.DEVELOPMENT, EMAIL_BACKEND="console"))
+ """Audited as production, a finding that names a development environment is a lie.
+
+ The table-creation finding is the one asked for, because it is core: the email backend names
+ the environment too, but only a project with accounts has anything to email.
+ """
+ _audited(monkeypatch, _settings(ENVIRONMENT=EnvironmentOption.DEVELOPMENT, CREATE_TABLES_ON_STARTUP=True))
main()
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 85bc3b37..14028346 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -113,7 +113,10 @@ def test_every_blueprint_only_path_is_one_this_repo_has(entry: str):
def _withheld(path: str) -> bool:
"""Whether `blueprint_only` keeps a project from receiving this path (spec 1.1 subtrees)."""
- return any(path == entry.rstrip("/") or path.startswith(entry) for entry in _catalog()["blueprint"]["blueprint_only"])
+ return any(
+ path == entry.rstrip("/") or (entry.endswith("/") and path.startswith(entry))
+ for entry in _catalog()["blueprint"]["blueprint_only"]
+ )
def _workspace_members() -> list[str]:
@@ -177,6 +180,51 @@ def test_each_file_still_names_the_path_that_keeps_it_out(path: str):
assert any(target.startswith(WITHHELD_POINTERS[path]) for target in pointed), pointed
+def _literals(module: Path) -> set[str]:
+ """Every string literal in a module, less the docstrings, which talk about files rather than
+ reach for them."""
+ tree = ast.parse(module.read_text())
+ docstrings = {
+ id(node.body[0].value)
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Module | ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef)
+ and node.body
+ and isinstance(node.body[0], ast.Expr)
+ and isinstance(node.body[0].value, ast.Constant)
+ }
+
+ return {
+ node.value
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Constant) and isinstance(node.value, str) and id(node) not in docstrings
+ }
+
+
+def test_no_test_a_project_receives_names_a_tree_it_does_not_get():
+ """A test that reaches for `docs/`, `tools/` or `cli/` is a test no project can run.
+
+ `test_removal_drill.py` loads `tools/removal_drill.py`, and `test_baseline.py` read the
+ migrations guide: both are files a project never receives, and the drill hid it by copying
+ the whole repository into every project it built. Only the subtree entries are compared,
+ because a root file's name is ambiguous: a shipped test naming `pyproject.toml` means
+ the one under `backend/`.
+ """
+ trees = [entry for entry in _catalog()["blueprint"]["blueprint_only"] if entry.endswith("/")]
+ reaching = {}
+ for module in sorted((REPO_ROOT / "backend" / "tests").rglob("*.py")):
+ relative = module.relative_to(REPO_ROOT).as_posix()
+ if _withheld(relative):
+ continue
+
+ named = sorted(
+ text for text in _literals(module) for tree in trees if text == tree.rstrip("/") or text.startswith(tree)
+ )
+ if named:
+ reaching[relative] = named
+
+ assert reaching == {}
+
+
def test_the_things_projects_must_not_receive_are_listed():
"""The catalog, the drill, the docs and the tool's own tree belong to the blueprint only."""
listed = set(_catalog()["blueprint"]["blueprint_only"])
diff --git a/backend/tests/unit/test_docs_scripts.py b/backend/tests/unit/test_docs_scripts.py
index 194b09e9..b1f16e3a 100644
--- a/backend/tests/unit/test_docs_scripts.py
+++ b/backend/tests/unit/test_docs_scripts.py
@@ -18,6 +18,15 @@
"""What a script a reader runs has, which the modules beside them do not."""
+MIGRATIONS = REPO_ROOT / "docs" / "user-guide" / "database" / "migrations.md"
+"""The one guide whose manual recipe is a script of its own done by hand."""
+
+
+def test_the_migrations_guide_names_the_script_that_writes_the_baseline():
+ """`scripts/baseline.py` does what that recipe does, and a reader has no way to know it."""
+ assert "python -m scripts.baseline" in MIGRATIONS.read_text()
+
+
def _runnable_scripts() -> list[str]:
return sorted(path.name for path in SCRIPTS.glob("*.py") if RUNNABLE in path.read_text())
diff --git a/backend/tests/unit/test_removal_drill.py b/backend/tests/unit/test_removal_drill.py
index 97ecc211..eb3bce9d 100644
--- a/backend/tests/unit/test_removal_drill.py
+++ b/backend/tests/unit/test_removal_drill.py
@@ -223,6 +223,25 @@ def _without_formatting(source: str) -> tuple[tuple[str, ...], tuple[str, ...]]:
return tuple(imports), tuple(statements)
+def test_a_project_is_kept_from_everything_the_catalog_reserves():
+ """A project that received the catalog, this drill or the docs would run the blueprint's own
+ tests against itself, and they describe a repository it is not. Spec 1.1: an entry with a
+ trailing slash reserves the whole subtree, not just the directory."""
+ reserved = drill.blueprint_only()
+
+ assert reserved, "the catalog reserves nothing, so this reads it wrongly"
+ for entry in reserved:
+ assert drill.withheld(entry.rstrip("/")), entry
+ if entry.endswith("/"):
+ assert drill.withheld(f"{entry}somewhere/deeper.py"), entry
+
+
+def test_nothing_a_drill_step_needs_is_kept_from_the_project():
+ """Every step runs from `backend/`, and reads its configuration and its tests from there."""
+ for needed in ("backend", "backend/pyproject.toml", "backend/tests/conftest.py", "backend/src/wiring/app.py"):
+ assert not drill.withheld(needed), needed
+
+
def test_the_generator_rebuilds_what_this_project_committed():
"""The drill proves a regenerated project reproduces this one, which needs them equal."""
present = _features_on_disk()
diff --git a/blueprint.toml b/blueprint.toml
index af2cf8c7..b644461a 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -17,6 +17,7 @@ blueprint_only = [
"backend/tests/unit/test_docs_scripts.py",
"backend/tests/unit/test_docs_wiring.py",
"backend/tests/unit/test_image_contents.py",
+ "backend/tests/unit/test_removal_drill.py",
"blueprint/",
"blueprint.toml",
"cli/",
diff --git a/tools/removal_drill.py b/tools/removal_drill.py
index 334d1a06..2d689f9d 100644
--- a/tools/removal_drill.py
+++ b/tools/removal_drill.py
@@ -20,6 +20,7 @@
import subprocess
import sys
import tempfile
+import tomllib
from dataclasses import dataclass, field
from pathlib import Path
@@ -541,6 +542,17 @@ def _tests_wiring(chosen: set[str]) -> str:
)
+def blueprint_only() -> tuple[str, ...]:
+ """The paths a project never receives, as `blueprint.toml` lists them."""
+ with (REPO / "blueprint.toml").open("rb") as handle:
+ return tuple(tomllib.load(handle)["blueprint"]["blueprint_only"])
+
+
+def withheld(path: str) -> bool:
+ """Whether a project is kept from receiving this path: a trailing slash means its subtree."""
+ return any(path == entry.rstrip("/") or (entry.endswith("/") and path.startswith(entry)) for entry in blueprint_only())
+
+
def copy_repository(source: Path, project: Path) -> None:
"""Copy ``source`` to ``project``, leaving out what a scratch build must not carry."""
shutil.copytree(
@@ -556,6 +568,9 @@ def build(preset: str, into: Path) -> Path:
project = into / preset
copy_repository(REPO, project)
+ for entry in blueprint_only():
+ _remove(project / entry.rstrip("/"))
+
for name, feature in FEATURES.items():
if name in chosen:
for partner, paths in feature.combination_paths.items():
From 2879f5a5b12dbb0b92c15115eafb603ffc610c2d Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Sat, 31 Oct 2026 00:14:17 -0300
Subject: [PATCH 20/71] declare faker and httpx for development, which is where
they are imported
---
backend/pyproject.toml | 4 +-
backend/tests/unit/test_blueprint_catalog.py | 90 ++++++++++++++++++++
blueprint.toml | 4 +-
docs/changelog.md | 4 +
uv.lock | 8 +-
5 files changed, 102 insertions(+), 8 deletions(-)
diff --git a/backend/pyproject.toml b/backend/pyproject.toml
index 2f016c69..efca55fe 100644
--- a/backend/pyproject.toml
+++ b/backend/pyproject.toml
@@ -18,11 +18,9 @@ dependencies = [
"asyncpg>=0.30.0",
"crudauth[all]>=0.8.2,<0.9.0",
"cryptography>=42.0.0",
- "faker>=37.1.0",
"fastapi[standard]>=0.115.8",
"fastcrud>=0.21.0",
"greenlet>=3.1.1",
- "httpx>=0.28.1",
"itsdangerous>=2.2.0",
"jinja2>=3.1.6",
"pydantic>=2.10.6",
@@ -48,6 +46,8 @@ dev = [
"pytest-xdist[psutil]>=3.8.0",
"taskiq[reload]>=0.11.20",
"pre-commit>=4.0.0",
+ "faker>=37.1.0",
+ "httpx>=0.28.1",
]
[tool.setuptools.packages.find]
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 14028346..b1b42c64 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -19,6 +19,7 @@
import sys
import tomllib
from collections.abc import Iterable
+from importlib.metadata import packages_distributions
from pathlib import Path
from typing import Any
@@ -93,6 +94,95 @@ def test_the_core_dependencies_are_the_ones_the_backend_declares():
assert dependencies["dev"] == backend["project"]["optional-dependencies"]["dev"]
+def _distribution(specifier: str) -> str:
+ """The distribution a PEP 508 specifier names, without its extras or its version."""
+ return re.split(r"[\[<>=!~;]", specifier)[0].strip().lower().replace("_", "-")
+
+
+@functools.cache
+def _provided() -> dict[str, frozenset[str]]:
+ """The modules each installed distribution provides, which is what an import names: `faker`
+ is imported as `faker`, and `user-agents` as `user_agents`."""
+ provided: dict[str, set[str]] = {}
+ for module, distributions in packages_distributions().items():
+ for distribution in distributions:
+ provided.setdefault(_distribution(distribution), set()).add(module)
+
+ return {name: frozenset(modules) for name, modules in provided.items()}
+
+
+@functools.cache
+def _imported(*directories: str, skipping: tuple[str, ...] = ()) -> frozenset[str]:
+ """Every top-level module imported under these directories of the python root, less the files
+ named in `skipping`, which are given relative to that root."""
+ root = REPO_ROOT / _catalog()["blueprint"]["python_root"]
+ skipped = {root / name for name in skipping}
+ found: set[str] = set()
+ for directory in directories:
+ for path in sorted((root / directory).rglob("*.py")):
+ if path in skipped:
+ continue
+
+ for node in ast.walk(ast.parse(path.read_text())):
+ if isinstance(node, ast.Import):
+ found.update(alias.name.split(".")[0] for alias in node.names)
+ elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
+ found.add(node.module.split(".")[0])
+
+ return frozenset(found)
+
+
+def _declared_distributions(listing: str) -> set[str]:
+ return {_distribution(specifier) for specifier in _catalog()["blueprint"]["dependencies"][listing]}
+
+
+def test_no_runtime_dependency_is_one_only_the_tests_import():
+ """A distribution only the tests import is installed in production for nothing.
+
+ `backend/Dockerfile` installs the runtime list with `--no-dev`, so that is the list that
+ decides the image. A distribution nothing imports at all is left alone here: several are
+ needed indirectly, through something that doesn't declare them.
+ """
+ runtime = _declared_distributions("runtime")
+ application = _imported("src", "scripts", "migrations")
+ tests = _imported("tests")
+
+ only_tested = {
+ name for name in runtime if _provided().get(name, frozenset()) & tests and not _provided()[name] & application
+ }
+
+ assert only_tested == set()
+
+
+DEVELOPMENT_SCRIPT = "scripts/baseline.py"
+"""The one script a project runs from its development environment rather than from the image."""
+
+
+def test_no_dependency_the_application_imports_is_declared_for_development_only():
+ """The other way round, where `uv export --no-dev` would leave an import with nothing behind it.
+
+ The scripts are read too, because an operator runs them in the image: the first-run guide
+ seeds a deployment with `docker compose exec api python -m scripts.setup_initial_data`, and
+ the repairs, the usage prune and the account unlock are all run the same way. `baseline.py`
+ is the exception, and the only one: it writes a project's first migration against a container
+ it starts itself, which is a thing to do once, from a checkout.
+ """
+ development = _declared_distributions("dev") - _declared_distributions("runtime")
+ application = _imported("src", "scripts", "migrations", skipping=(DEVELOPMENT_SCRIPT,))
+
+ assert {name for name in development if _provided().get(name, frozenset()) & application} == set()
+
+
+def test_the_dependency_readings_find_what_they_claim_to():
+ """Both rules report what they found, so a reading that stopped working would pass quietly."""
+ assert "fastapi" in _imported("src", "migrations")
+ assert "pytest" in _imported("tests")
+ assert _provided()["sqlalchemy"] == frozenset({"sqlalchemy"})
+ assert "testcontainers" in _imported("scripts")
+ assert "testcontainers" not in _imported("scripts", skipping=(DEVELOPMENT_SCRIPT,))
+ assert "asyncio" in _imported("scripts", skipping=(DEVELOPMENT_SCRIPT,)), "the other scripts are still read"
+
+
@pytest.mark.parametrize("entry", sorted(_catalog()["blueprint"]["blueprint_only"]))
def test_every_blueprint_only_path_is_written_the_way_the_spec_reads_them(entry: str):
"""Spec 1.1: a trailing slash means the subtree, and without one it is a single file.
diff --git a/blueprint.toml b/blueprint.toml
index b644461a..23e8a4c2 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -38,11 +38,9 @@ runtime = [
"asyncpg>=0.30.0",
"crudauth[all]>=0.8.2,<0.9.0",
"cryptography>=42.0.0",
- "faker>=37.1.0",
"fastapi[standard]>=0.115.8",
"fastcrud>=0.21.0",
"greenlet>=3.1.1",
- "httpx>=0.28.1",
"itsdangerous>=2.2.0",
"jinja2>=3.1.6",
"pydantic>=2.10.6",
@@ -66,6 +64,8 @@ dev = [
"pytest-xdist[psutil]>=3.8.0",
"taskiq[reload]>=0.11.20",
"pre-commit>=4.0.0",
+ "faker>=37.1.0",
+ "httpx>=0.28.1",
]
[presets]
diff --git a/docs/changelog.md b/docs/changelog.md
index 32ad0a17..37e52686 100644
--- a/docs/changelog.md
+++ b/docs/changelog.md
@@ -17,6 +17,10 @@ ___
image installs neither and a deployment is unaffected: the advisories are about the environments
a hook runs in and the lock files it takes, on the machines that run the hooks. `pre-commit run
--all-files` passes on the new versions.
+- **`faker` and `httpx` are development dependencies now**, because only the tests import them.
+ The image installs the runtime list with `--no-dev`, so `faker` is no longer in it: code of your
+ own that imported it there has to declare it. `httpx` still arrives in the image through
+ `fastapi[standard]`, which requires it, so only `faker` actually leaves.
___
diff --git a/uv.lock b/uv.lock
index 897ebc29..0811bdf3 100644
--- a/uv.lock
+++ b/uv.lock
@@ -890,11 +890,9 @@ dependencies = [
{ name = "asyncpg" },
{ name = "crudauth", extra = ["all"] },
{ name = "cryptography" },
- { name = "faker" },
{ name = "fastapi", extra = ["standard"] },
{ name = "fastcrud" },
{ name = "greenlet" },
- { name = "httpx" },
{ name = "itsdangerous" },
{ name = "jinja2" },
{ name = "pydantic" },
@@ -911,6 +909,8 @@ dependencies = [
[package.optional-dependencies]
dev = [
+ { name = "faker" },
+ { name = "httpx" },
{ name = "mypy" },
{ name = "pre-commit" },
{ name = "pytest" },
@@ -931,11 +931,11 @@ requires-dist = [
{ name = "asyncpg", specifier = ">=0.30.0" },
{ name = "crudauth", extras = ["all"], specifier = ">=0.8.2,<0.9.0" },
{ name = "cryptography", specifier = ">=42.0.0" },
- { name = "faker", specifier = ">=37.1.0" },
+ { name = "faker", marker = "extra == 'dev'", specifier = ">=37.1.0" },
{ name = "fastapi", extras = ["standard"], specifier = ">=0.115.8" },
{ name = "fastcrud", specifier = ">=0.21.0" },
{ name = "greenlet", specifier = ">=3.1.1" },
- { name = "httpx", specifier = ">=0.28.1" },
+ { name = "httpx", marker = "extra == 'dev'", specifier = ">=0.28.1" },
{ name = "itsdangerous", specifier = ">=2.2.0" },
{ name = "jinja2", specifier = ">=3.1.6" },
{ name = "mypy", marker = "extra == 'dev'", specifier = ">=1.14.1" },
From 52abbcf9b8c81fb44de5034cbf14d49cf5d3455f Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Sat, 31 Oct 2026 00:24:19 -0300
Subject: [PATCH 21/71] declare each feature's own dependencies, and the
memcached option's
---
.../cache/backends/test_memcached.py | 10 +-
backend/tests/unit/test_blueprint_catalog.py | 164 ++++++++++++++++--
blueprint.toml | 17 +-
3 files changed, 167 insertions(+), 24 deletions(-)
diff --git a/backend/tests/unit/infrastructure/cache/backends/test_memcached.py b/backend/tests/unit/infrastructure/cache/backends/test_memcached.py
index 232b1399..30a465ea 100644
--- a/backend/tests/unit/infrastructure/cache/backends/test_memcached.py
+++ b/backend/tests/unit/infrastructure/cache/backends/test_memcached.py
@@ -1,9 +1,17 @@
+"""The memcached backend, which a project only installs aiomcache for when it chooses it.
+
+The dependency belongs to the `cache.backend=memcached` option, and an option owns no paths, so
+a project on the default redis choice receives this file without the package it needs.
+"""
+
import json
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
-from src.infrastructure.cache.backends.memcached import (
+pytest.importorskip("aiomcache")
+
+from src.infrastructure.cache.backends.memcached import ( # noqa: E402
MemcachedBackend,
MemcachedSettings,
PatternMatchingNotSupportedError,
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index b1b42c64..3f51b19e 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -83,15 +83,31 @@ def test_development_builds_of_the_tool_can_read_it():
assert _catalog()["blueprint"]["requires_fastro"] == ">=0.1.0.dev0,<0.2"
-def test_the_core_dependencies_are_the_ones_the_backend_declares():
- """The catalog carries the backend's lists until they are split per feature."""
+def _declared_specifiers() -> set[str]:
+ """Every runtime specifier a project could install: the core's, each feature's, each option's."""
+ specifiers = set(_catalog()["blueprint"]["dependencies"]["runtime"])
+ for feature in _catalog()["features"].values():
+ specifiers.update(feature.get("dependencies", ()))
+ for block in feature.get("when", ()):
+ specifiers.update(block.get("dependencies", ()))
+ for option in feature.get("options", {}).values():
+ for chosen in option.get("dependencies", {}).values():
+ specifiers.update(chosen)
+
+ return specifiers
+
+
+def test_the_dependencies_a_project_could_install_are_the_ones_the_backend_declares():
+ """This repo selects every feature, so the union of the declarations is the backend's own list.
+
+ The specifiers are compared, not the distribution names, so a floor that moves in one file
+ and not the other is caught rather than averaged away.
+ """
with BACKEND_PYPROJECT.open("rb") as handle:
backend = tomllib.load(handle)
- dependencies = _catalog()["blueprint"]["dependencies"]
-
- assert dependencies["runtime"] == backend["project"]["dependencies"]
- assert dependencies["dev"] == backend["project"]["optional-dependencies"]["dev"]
+ assert _declared_specifiers() == set(backend["project"]["dependencies"])
+ assert _catalog()["blueprint"]["dependencies"]["dev"] == backend["project"]["optional-dependencies"]["dev"]
def _distribution(specifier: str) -> str:
@@ -111,31 +127,149 @@ def _provided() -> dict[str, frozenset[str]]:
return {name: frozenset(modules) for name, modules in provided.items()}
+@functools.cache
+def _module_imports(path: Path) -> frozenset[str]:
+ """Every module an absolute import in this file names, dotted as it is written."""
+ found: set[str] = set()
+ for node in ast.walk(ast.parse(path.read_text())):
+ if isinstance(node, ast.Import):
+ found.update(alias.name for alias in node.names)
+ elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
+ found.add(node.module)
+
+ return frozenset(found)
+
+
@functools.cache
def _imported(*directories: str, skipping: tuple[str, ...] = ()) -> frozenset[str]:
"""Every top-level module imported under these directories of the python root, less the files
named in `skipping`, which are given relative to that root."""
root = REPO_ROOT / _catalog()["blueprint"]["python_root"]
skipped = {root / name for name in skipping}
+
+ return frozenset(
+ module.split(".")[0]
+ for directory in directories
+ for path in sorted((root / directory).rglob("*.py"))
+ if path not in skipped
+ for module in _module_imports(path)
+ )
+
+
+@functools.cache
+def _imports_outright(path: Path) -> frozenset[str]:
+ """The top-level modules this file imports with no guard, counted statement by statement.
+
+ One import of a module inside a `try` doesn't excuse another outside it: the unguarded one is
+ what runs first and what fails, so a module imported both ways is imported outright.
+ """
+ tree = ast.parse(path.read_text())
+ guarded = {
+ id(inner)
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Try)
+ for inner in ast.walk(node)
+ if isinstance(inner, ast.Import | ast.ImportFrom)
+ }
+
found: set[str] = set()
- for directory in directories:
- for path in sorted((root / directory).rglob("*.py")):
- if path in skipped:
- continue
+ for node in ast.walk(tree):
+ if id(node) in guarded:
+ continue
- for node in ast.walk(ast.parse(path.read_text())):
- if isinstance(node, ast.Import):
- found.update(alias.name.split(".")[0] for alias in node.names)
- elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
- found.add(node.module.split(".")[0])
+ if isinstance(node, ast.Import):
+ found.update(alias.name.split(".")[0] for alias in node.names)
+ elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
+ found.add(node.module.split(".")[0])
return frozenset(found)
+@functools.cache
+def _importers() -> dict[str, frozenset[str]]:
+ """Which files under the python root import each top-level module, as repo-relative paths."""
+ root = REPO_ROOT / _catalog()["blueprint"]["python_root"]
+ found: dict[str, set[str]] = {}
+ for path in sorted(root.rglob("*.py")):
+ for module in _module_imports(path):
+ found.setdefault(module.split(".")[0], set()).add(path.relative_to(REPO_ROOT).as_posix())
+
+ return {module: frozenset(files) for module, files in found.items()}
+
+
def _declared_distributions(listing: str) -> set[str]:
+ """The distributions a listing names: `runtime` is every list a project could install from."""
+ if listing == "runtime":
+ return {_distribution(specifier) for specifier in _declared_specifiers()}
+
return {_distribution(specifier) for specifier in _catalog()["blueprint"]["dependencies"][listing]}
+INDIRECT_NEEDS = {
+ "itsdangerous": ("starlette.middleware.sessions", "backend/src/interfaces/admin/auth.py"),
+ "user-agents": ("crudauth.transports.session.transport", "backend/src/infrastructure/auth/evictions.py"),
+}
+"""Distributions nothing imports by name, each with the import that needs it and the file that
+makes that import. `starlette` doesn't declare `itsdangerous`, and
+`crudauth/transports/session/__init__.py` imports its `manager`, which imports `user_agents`
+inside a `try`. A project without either would refuse to start the admin panel, or record
+every session's device as unknown, with nothing naming what is missing."""
+
+
+@pytest.mark.parametrize(
+ ("feature", "specifier"),
+ sorted(
+ (name, specifier) for name, feature in _catalog()["features"].items() for specifier in feature.get("dependencies", ())
+ ),
+)
+def test_every_feature_dependency_is_one_that_feature_needs(feature: str, specifier: str):
+ """A dependency parked on the wrong feature is a project that installs it and never uses it,
+ or selects the feature and finds it missing."""
+ name = _distribution(specifier)
+ owned = [path for path, _ in _declared(_catalog()["features"][feature])]
+
+ if name in INDIRECT_NEEDS:
+ module, importer = INDIRECT_NEEDS[name]
+
+ assert _under(importer, owned), importer
+ assert module in _module_imports(REPO_ROOT / importer), module
+ assert not _provided()[name] & set(_importers()), f"{name} is imported by name now"
+
+ return
+
+ importers = {file for module in _provided()[name] for file in _importers().get(module, ())}
+ outright = {file for file in importers if _provided()[name] & _imports_outright(REPO_ROOT / file)}
+
+ assert importers, name
+ assert any(_under(file, owned) for file in outright), sorted(importers)
+
+
+@pytest.mark.parametrize(
+ ("feature", "option", "value", "specifier"),
+ sorted(
+ (name, option, value, specifier)
+ for name, feature in _catalog()["features"].items()
+ for option, declared in feature.get("options", {}).items()
+ for value, specifiers in declared.get("dependencies", {}).items()
+ for specifier in specifiers
+ ),
+)
+def test_every_option_dependency_is_one_its_value_needs(feature: str, option: str, value: str, specifier: str):
+ """Spec 2.5: the value has to be one of the option's choices, and the file that imports the
+ distribution has to belong to the feature that offers it."""
+ declared = _catalog()["features"][feature]["options"][option]
+ owned = [path for path, _ in _declared(_catalog()["features"][feature])]
+ importers = {file for module in _provided()[_distribution(specifier)] for file in _importers().get(module, ())}
+
+ assert value in declared["choices"]
+ assert importers, specifier
+ assert all(_under(file, owned) for file in importers), sorted(importers)
+ for file in importers:
+ assert not _provided()[_distribution(specifier)] & _imports_outright(REPO_ROOT / file), (
+ f"{file} imports {specifier} without a guard, and a project that chose another value has it absent"
+ )
+
+
def test_no_runtime_dependency_is_one_only_the_tests_import():
"""A distribution only the tests import is installed in production for nothing.
diff --git a/blueprint.toml b/blueprint.toml
index 23e8a4c2..6191c4e9 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -31,28 +31,20 @@ blueprint_only = [
[blueprint.dependencies]
runtime = [
- "aiomcache>=0.8.2",
"aiosqlite>=0.21.0",
"alembic>=1.16.4",
"anyio>=4.15.1",
"asyncpg>=0.30.0",
"crudauth[all]>=0.8.2,<0.9.0",
- "cryptography>=42.0.0",
"fastapi[standard]>=0.115.8",
"fastcrud>=0.21.0",
"greenlet>=3.1.1",
- "itsdangerous>=2.2.0",
"jinja2>=3.1.6",
"pydantic>=2.10.6",
"pydantic-settings>=2.14.2",
"redis>=6.1.0",
- "sqladmin>=0.28.0",
"sqlalchemy>=2.0.37",
"starlette>=1.3.1",
- "taskiq>=0.11.20",
- "taskiq-redis>=1.1.2",
- "taskiq-aio-pika>=0.4.3",
- "user-agents>=2.2.0",
]
dev = [
"mypy>=1.14.1",
@@ -184,6 +176,7 @@ doc = "A fixture module pytest loads for the features the project carries."
[features.accounts]
summary = "Users, sessions, CSRF, login lockout, OAuth"
group = "Accounts"
+dependencies = ["user-agents>=2.2.0"]
paths = [
"backend/scripts/canonicalize_emails.py",
"backend/scripts/create_first_superuser.py",
@@ -405,6 +398,7 @@ paths = [
summary = "SQLAdmin panel at /admin"
group = "Operations"
requires = ["accounts"]
+dependencies = ["sqladmin>=0.28.0", "itsdangerous>=2.2.0"]
paths = [
"backend/src/interfaces/admin/",
"backend/tests/unit/interfaces/admin/",
@@ -433,11 +427,18 @@ choices = ["redis", "memcached"]
default = "redis"
env = { CACHE_BACKEND = "{value}" }
services = { memcached = ["memcached"] }
+dependencies = { memcached = ["aiomcache>=0.8.2"] }
[features.taskiq]
summary = "Background tasks on Redis or RabbitMQ"
group = "Operations"
services = ["worker", "scheduler"]
+dependencies = [
+ "taskiq>=0.11.20",
+ "taskiq-redis>=1.1.2",
+ "taskiq-aio-pika>=0.4.3",
+ "cryptography>=42.0.0",
+]
paths = [
"backend/src/infrastructure/taskiq/",
"backend/tests/unit/infrastructure/taskiq/",
From e6aa1c28b2ea93645413623d5433bf4da6f921a4 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Sat, 31 Oct 2026 00:34:14 -0300
Subject: [PATCH 22/71] declare each feature's own dependencies, and the
memcached option's
---
backend/tests/unit/test_blueprint_catalog.py | 61 ++++++++++++++++++--
1 file changed, 57 insertions(+), 4 deletions(-)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 3f51b19e..757d5349 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -210,10 +210,11 @@ def _declared_distributions(listing: str) -> set[str]:
"user-agents": ("crudauth.transports.session.transport", "backend/src/infrastructure/auth/evictions.py"),
}
"""Distributions nothing imports by name, each with the import that needs it and the file that
-makes that import. `starlette` doesn't declare `itsdangerous`, and
-`crudauth/transports/session/__init__.py` imports its `manager`, which imports `user_agents`
-inside a `try`. A project without either would refuse to start the admin panel, or record
-every session's device as unknown, with nothing naming what is missing."""
+makes that import. `starlette` doesn't declare `itsdangerous`, and importing
+`crudauth.transports.session.transport` runs that package's `__init__`, which imports its
+`manager`, which imports `user_agents` inside a `try`. A project without either would refuse
+to start the admin panel, or record every session's device as unknown, with nothing naming
+what is missing."""
@pytest.mark.parametrize(
@@ -244,6 +245,58 @@ def test_every_feature_dependency_is_one_that_feature_needs(feature: str, specif
assert any(_under(file, owned) for file in outright), sorted(importers)
+def _needed_by(features: dict[str, Any]) -> dict[str, set[str]]:
+ """Each declared distribution, with the features that bring it. An option's brings an empty
+ set: a project selects the feature and still chooses another value, so nothing guarantees it."""
+ needed: dict[str, set[str]] = {}
+ for name, feature in features.items():
+ for specifier in feature.get("dependencies", ()):
+ needed.setdefault(_distribution(specifier), set()).add(name)
+ for option in feature.get("options", {}).values():
+ for specifiers in option.get("dependencies", {}).values():
+ for specifier in specifiers:
+ needed.setdefault(_distribution(specifier), set())
+
+ return needed
+
+
+def _removed_for(features: dict[str, Any], chosen: set[str]) -> list[str]:
+ """The owned paths this selection doesn't keep, which is what `_kept_by_the_catalog` leaves out."""
+ return [
+ path
+ for name, feature in features.items()
+ for path, condition in _declared(feature)
+ if name not in chosen or (condition is not None and not _true(condition, chosen))
+ ]
+
+
+def test_no_file_a_project_keeps_imports_a_dependency_it_did_not_select():
+ """The other half of moving a dependency off the core, over all 164 selections.
+
+ `fastro new` writes a project's `pyproject.toml` from the declarations (spec 6.3), so a file
+ kept without the feature that brings a distribution, importing it outright, is a project that
+ fails at import. Only the files that go with the feature may need it.
+ """
+ features = _catalog()["features"]
+ needed = _needed_by(features)
+
+ assert needed["sqladmin"] == {"admin"}
+ assert needed["aiomcache"] == set(), "an option's dependency is never guaranteed"
+
+ for chosen in _selections(_drill()):
+ removed = _removed_for(features, chosen)
+ for name, owners in needed.items():
+ if owners & chosen:
+ continue
+
+ for module in _provided()[name]:
+ for file in _importers().get(module, ()):
+ if not _provided()[name] & _imports_outright(REPO_ROOT / file):
+ continue
+
+ assert _under(file, removed) or _withheld(file), (sorted(chosen), name, file)
+
+
@pytest.mark.parametrize(
("feature", "option", "value", "specifier"),
sorted(
From b607680ec5d84dde7d17051c459cb001167bf851 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Sat, 31 Oct 2026 00:55:15 -0300
Subject: [PATCH 23/71] drop the dependency nothing used, and account for the
ones nothing imports
---
backend/pyproject.toml | 3 +-
backend/tests/conftest.py | 2 -
.../infrastructure/config/test_settings.py | 8 ----
backend/tests/unit/test_blueprint_catalog.py | 37 ++++++++++++++++++-
blueprint.toml | 3 +-
docs/changelog.md | 4 ++
uv.lock | 15 +-------
7 files changed, 44 insertions(+), 28 deletions(-)
diff --git a/backend/pyproject.toml b/backend/pyproject.toml
index efca55fe..f26c53ea 100644
--- a/backend/pyproject.toml
+++ b/backend/pyproject.toml
@@ -12,7 +12,6 @@ readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"aiomcache>=0.8.2",
- "aiosqlite>=0.21.0",
"alembic>=1.16.4",
"anyio>=4.15.1",
"asyncpg>=0.30.0",
@@ -22,7 +21,6 @@ dependencies = [
"fastcrud>=0.21.0",
"greenlet>=3.1.1",
"itsdangerous>=2.2.0",
- "jinja2>=3.1.6",
"pydantic>=2.10.6",
"pydantic-settings>=2.14.2",
"redis>=6.1.0",
@@ -48,6 +46,7 @@ dev = [
"pre-commit>=4.0.0",
"faker>=37.1.0",
"httpx>=0.28.1",
+ "jinja2>=3.1.6",
]
[tool.setuptools.packages.find]
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 665d169b..38f6ab6d 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -16,8 +16,6 @@
os.environ.setdefault("ADMIN_ENABLED", "true")
os.environ.setdefault("ADMIN_USERNAME", "admin")
os.environ.setdefault("ADMIN_PASSWORD", "s3cret")
-os.environ.setdefault("SQLITE_URI", ":memory:")
-os.environ.setdefault("SQLITE_ASYNC_PREFIX", "sqlite+aiosqlite:///")
# Disable the testcontainers Ryuk reaper. Under `pytest -n auto`, each xdist worker
# is a separate process that spins up its own Ryuk container, and Docker Desktop
diff --git a/backend/tests/unit/infrastructure/config/test_settings.py b/backend/tests/unit/infrastructure/config/test_settings.py
index d736458c..ad265146 100644
--- a/backend/tests/unit/infrastructure/config/test_settings.py
+++ b/backend/tests/unit/infrastructure/config/test_settings.py
@@ -127,14 +127,6 @@ def test_required_settings_exist(self):
assert hasattr(settings, attr), f"Missing required setting: {attr}"
assert getattr(settings, attr) is not None, f"Setting {attr} is None"
- @patch.dict(os.environ, {"SQLITE_URI": ":memory:"})
- def test_test_database_override(self):
- """Test that test database settings work."""
- settings = Settings()
- # In test mode, should use in-memory database
- if hasattr(settings, "SQLITE_URI"):
- assert ":memory:" in settings.SQLITE_URI
-
class TestCORSSettings:
"""Credentialed requests reject a wildcard origin, so the default must not be one."""
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 757d5349..88a13974 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -19,7 +19,7 @@
import sys
import tomllib
from collections.abc import Iterable
-from importlib.metadata import packages_distributions
+from importlib.metadata import packages_distributions, requires
from pathlib import Path
from typing import Any
@@ -217,6 +217,41 @@ def _declared_distributions(listing: str) -> set[str]:
what is missing."""
+NEEDED_WITHOUT_AN_IMPORT = {
+ "asyncpg": "the driver `POSTGRES_ASYNC_PREFIX` names, which sqlalchemy loads from the URL",
+ "greenlet": "what sqlalchemy runs a DBAPI call in, for its asyncio support",
+}
+"""Core distributions no file imports and no import pulls in: another distribution asks for them,
+or a setting names them as a driver. Written down so a project's image carries nothing nobody can
+account for."""
+
+
+def test_every_runtime_dependency_nothing_imports_is_accounted_for():
+ """Both ways: a distribution installed and never imported is either needed through something
+ else, which is worth writing down, or weight in every project's image for no reason."""
+ runtime = _declared_distributions("runtime")
+ imported = {name for name in runtime if _provided().get(name, frozenset()) & set(_importers())}
+
+ assert runtime - imported == set(INDIRECT_NEEDS) | set(NEEDED_WITHOUT_AN_IMPORT)
+
+
+def test_the_two_the_database_needs_are_the_blueprint_s_to_declare():
+ """Why neither can be left to sqlalchemy, read from the installed metadata and the settings.
+
+ `asyncpg` is the driver the URL names and sqlalchemy loads; `greenlet` is what sqlalchemy's
+ asyncio support runs a driver's calls in. Sqlalchemy asks for them only through extras the
+ backend doesn't declare, and the greenlet one outright on some platforms only, so a project
+ that installed plain `sqlalchemy` would have neither.
+ """
+ asked = requires("sqlalchemy") or ()
+ base = (REPO_ROOT / "backend/src/infrastructure/config/base.py").read_text()
+
+ assert 'POSTGRES_ASYNC_PREFIX", default="postgresql+asyncpg://"' in base
+ assert any(entry.startswith("asyncpg") and entry.endswith('extra == "postgresql-asyncpg"') for entry in asked)
+ assert any(entry.startswith("greenlet") and entry.endswith('extra == "asyncio"') for entry in asked)
+ assert "sqlalchemy>=2.0.37" in _catalog()["blueprint"]["dependencies"]["runtime"], "plain, with no extras"
+
+
@pytest.mark.parametrize(
("feature", "specifier"),
sorted(
diff --git a/blueprint.toml b/blueprint.toml
index 6191c4e9..6dd734c0 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -31,7 +31,6 @@ blueprint_only = [
[blueprint.dependencies]
runtime = [
- "aiosqlite>=0.21.0",
"alembic>=1.16.4",
"anyio>=4.15.1",
"asyncpg>=0.30.0",
@@ -39,7 +38,6 @@ runtime = [
"fastapi[standard]>=0.115.8",
"fastcrud>=0.21.0",
"greenlet>=3.1.1",
- "jinja2>=3.1.6",
"pydantic>=2.10.6",
"pydantic-settings>=2.14.2",
"redis>=6.1.0",
@@ -58,6 +56,7 @@ dev = [
"pre-commit>=4.0.0",
"faker>=37.1.0",
"httpx>=0.28.1",
+ "jinja2>=3.1.6",
]
[presets]
diff --git a/docs/changelog.md b/docs/changelog.md
index 37e52686..29d25861 100644
--- a/docs/changelog.md
+++ b/docs/changelog.md
@@ -21,6 +21,10 @@ ___
The image installs the runtime list with `--no-dev`, so `faker` is no longer in it: code of your
own that imported it there has to declare it. `httpx` still arrives in the image through
`fastapi[standard]`, which requires it, so only `faker` actually leaves.
+- **`aiosqlite` is gone and `jinja2` is a development dependency.** Nothing imported either:
+ `aiosqlite` answered `SQLITE_ASYNC_PREFIX`, which no module reads, and the admin panel gets
+ `jinja2` through `sqladmin`, which requires it. `jinja2` stays in the `dev` extra for the
+ template tests. A project of your own that imported either has to declare it.
___
diff --git a/uv.lock b/uv.lock
index 0811bdf3..ea8f91a4 100644
--- a/uv.lock
+++ b/uv.lock
@@ -232,15 +232,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" },
]
-[[package]]
-name = "aiosqlite"
-version = "0.22.1"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/4e/8a/64761f4005f17809769d23e518d915db74e6310474e733e3593cfc854ef1/aiosqlite-0.22.1.tar.gz", hash = "sha256:043e0bd78d32888c0a9ca90fc788b38796843360c855a7262a532813133a0650", size = 14821, upload-time = "2025-12-23T19:25:43.997Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/00/b7/e3bf5133d697a08128598c8d0abc5e16377b51465a33756de24fa7dee953/aiosqlite-0.22.1-py3-none-any.whl", hash = "sha256:21c002eb13823fad740196c5a2e9d8e62f6243bd9e7e4a1f87fb5e44ecb4fceb", size = 17405, upload-time = "2025-12-23T19:25:42.139Z" },
-]
-
[[package]]
name = "aiostream"
version = "0.7.1"
@@ -884,7 +875,6 @@ version = "0.20.0"
source = { editable = "backend" }
dependencies = [
{ name = "aiomcache" },
- { name = "aiosqlite" },
{ name = "alembic" },
{ name = "anyio" },
{ name = "asyncpg" },
@@ -894,7 +884,6 @@ dependencies = [
{ name = "fastcrud" },
{ name = "greenlet" },
{ name = "itsdangerous" },
- { name = "jinja2" },
{ name = "pydantic" },
{ name = "pydantic-settings" },
{ name = "redis" },
@@ -911,6 +900,7 @@ dependencies = [
dev = [
{ name = "faker" },
{ name = "httpx" },
+ { name = "jinja2" },
{ name = "mypy" },
{ name = "pre-commit" },
{ name = "pytest" },
@@ -925,7 +915,6 @@ dev = [
[package.metadata]
requires-dist = [
{ name = "aiomcache", specifier = ">=0.8.2" },
- { name = "aiosqlite", specifier = ">=0.21.0" },
{ name = "alembic", specifier = ">=1.16.4" },
{ name = "anyio", specifier = ">=4.15.1" },
{ name = "asyncpg", specifier = ">=0.30.0" },
@@ -937,7 +926,7 @@ requires-dist = [
{ name = "greenlet", specifier = ">=3.1.1" },
{ name = "httpx", marker = "extra == 'dev'", specifier = ">=0.28.1" },
{ name = "itsdangerous", specifier = ">=2.2.0" },
- { name = "jinja2", specifier = ">=3.1.6" },
+ { name = "jinja2", marker = "extra == 'dev'", specifier = ">=3.1.6" },
{ name = "mypy", marker = "extra == 'dev'", specifier = ">=1.14.1" },
{ name = "pre-commit", marker = "extra == 'dev'", specifier = ">=4.0.0" },
{ name = "pydantic", specifier = ">=2.10.6" },
From e838bf0107945121d32a275b7b233ef8b45e3cfd Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Sat, 31 Oct 2026 01:20:35 -0300
Subject: [PATCH 24/71] give every section of the environment example one owner
---
backend/.env.example | 38 ++++++---
backend/tests/unit/test_blueprint_catalog.py | 90 ++++++++++++++++++++
2 files changed, 114 insertions(+), 14 deletions(-)
diff --git a/backend/.env.example b/backend/.env.example
index 791e7fe2..6543bbaf 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -45,10 +45,6 @@ CACHE_ENABLED=true
# @fastro option=cache.backend
CACHE_BACKEND=redis
-# Client-side cache settings
-CLIENT_CACHE_ENABLED=true
-CLIENT_CACHE_MAX_AGE=60
-
# Cache Memcached settings (when using CACHE_BACKEND=memcached)
CACHE_MEMCACHED_HOST=localhost
CACHE_MEMCACHED_PORT=11211
@@ -68,15 +64,21 @@ CACHE_REDIS_POOL_SIZE=10
# ===================================
# Rate Limiting Configuration
# ===================================
-# Provided by crudauth (Redis-backed). Limits are resolved per request from the
+# The per-caller throttle on the API routes. Limits are resolved per request from the
# user's tier and path, falling back to the defaults below.
RATE_LIMITER_ENABLED=true
+DEFAULT_RATE_LIMIT_LIMIT=100
+DEFAULT_RATE_LIMIT_PERIOD=60
+
+# ===================================
+# Rate Limiter Store
+# ===================================
+# Where the counters live: the login lockout keeps its own here, and the API throttle,
+# where it is selected, shares them.
# redis (default), database or memory. Memory counters are per process, so each worker
# counts a login lockout on its own; database keeps them in two tables of this project's
# database, which every worker shares without a Redis.
RATE_LIMITER_BACKEND=redis
-DEFAULT_RATE_LIMIT_LIMIT=100
-DEFAULT_RATE_LIMIT_PERIOD=60
# Rate Limiter Redis settings
# Uses DB 1 by default to separate from cache (which uses DB 0)
@@ -179,12 +181,23 @@ CORS_ALLOW_HEADERS=*
GZIP_ENABLED=true
GZIP_MINIMUM_SIZE=1000
+# Client-side caching: the Cache-Control headers responses carry
+CLIENT_CACHE_ENABLED=true
+CLIENT_CACHE_MAX_AGE=60
+
+# Which peers uvicorn accepts X-Forwarded-For and X-Forwarded-Proto from. Read by
+# uvicorn, not by the app, and it decides what request.client and the access logs
+# say. Name your proxy's address or subnet; a wildcard lets any client claim any
+# address. Leave unset when nothing sits in front of the app. The login lockout, where
+# there is one, counts proxy hops with TRUSTED_PROXY_HOPS instead.
+# FORWARDED_ALLOW_IPS=172.31.240.0/24
+
# API documentation settings
ENABLE_DOCS_IN_PRODUCTION=false
OPENAPI_PREFIX=
# ===================================
-# Authentication & Security
+# Security
# ===================================
SECRET_KEY=insecure-secret-key-change-this-in-production
@@ -192,6 +205,9 @@ SECRET_KEY=insecure-secret-key-change-this-in-production
# Automatically validates security settings in production environments
PRODUCTION_SECURITY_VALIDATION_ENABLED=true
+# ===================================
+# Authentication & Security
+# ===================================
# Session Management
SESSION_TIMEOUT_MINUTES=30
SESSION_CLEANUP_INTERVAL_MINUTES=15
@@ -233,12 +249,6 @@ CSRF_ENABLED=true
# IP for login lockout. 0 = direct (socket peer); set 1 behind a single nginx/Caddy.
TRUSTED_PROXY_HOPS=0
-# Which peers uvicorn accepts X-Forwarded-For and X-Forwarded-Proto from. Read by
-# uvicorn, not by the app, and it decides what request.client and the access logs
-# say. Name your proxy's address or subnet; a wildcard lets any client claim any
-# address. Leave unset when nothing sits in front of the app.
-# FORWARDED_ALLOW_IPS=172.31.240.0/24
-
# Password policy (crudauth applies this to every password-writing path)
PASSWORD_MIN_LENGTH=8
PASSWORD_REQUIRE_UPPERCASE=true
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 88a13974..024da6af 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -1243,6 +1243,96 @@ def test_every_option_offers_the_values_its_feature_acts_on(feature: str, option
)
+ENV_EXAMPLE = REPO_ROOT / "backend" / ".env.example"
+
+NOT_A_SETTING = {
+ "DATABASE_URL": "core",
+ "FORWARDED_ALLOW_IPS": "core",
+ "SESSION_REDIS_URL": "accounts",
+}
+"""Variables the example sets that no settings field declares, and where each belongs:
+`DATABASE_URL` is the name `DATABASE_URL_OVERRIDE` is aliased to, `FORWARDED_ALLOW_IPS` is read
+by uvicorn and written by the deploy templates, and `SESSION_REDIS_URL` is built by the accounts
+settings rather than declared as a field."""
+
+
+@functools.cache
+def _settings_fields() -> dict[str, frozenset[str]]:
+ """Which part of the project declares each setting: `core`, or the features whose contributed
+ settings classes declare it."""
+ modules: dict[str, list[Path]] = {"core": [REPO_ROOT / "backend/src/infrastructure/config/base.py"]}
+ for name, feature in _catalog()["features"].items():
+ for entry in feature.get("contributes", {}).get("settings", ()):
+ module, _, _ = _ref(entry if isinstance(entry, str) else entry["ref"])
+ modules.setdefault(name, []).append(REPO_ROOT / "backend" / Path(*module.split(".")).with_suffix(".py"))
+
+ declared: dict[str, set[str]] = {}
+ for owner, paths in modules.items():
+ for path in paths:
+ for node in ast.walk(ast.parse(path.read_text())):
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id.isupper():
+ declared.setdefault(node.target.id, set()).add(owner)
+
+ return {name: frozenset(owners) for name, owners in declared.items()}
+
+
+@functools.cache
+def _env_sections() -> tuple[tuple[str, tuple[str, ...]], ...]:
+ """Each section of the example: its title, and the variables it sets, including the ones it
+ ships commented out, since a reader uncomments them where they sit."""
+ lines = ENV_EXAMPLE.read_text().splitlines()
+ rule = re.compile(r"^# ={10,}$")
+ headers = [
+ index
+ for index, line in enumerate(lines)
+ if rule.match(line) and index + 2 < len(lines) and rule.match(lines[index + 2])
+ ]
+
+ sections = []
+ for position, start in enumerate(headers):
+ end = headers[position + 1] if position + 1 < len(headers) else len(lines)
+ variables = tuple(
+ found.group(1) for line in lines[start + 3 : end] if (found := re.match(r"^#?\s*([A-Z][A-Z0-9_]*)=", line))
+ )
+ sections.append((lines[start + 1].lstrip("# ").strip(), variables))
+
+ return tuple(sections)
+
+
+def _owner_of(variable: str) -> frozenset[str]:
+ fields = _settings_fields()
+ if variable in fields:
+ return fields[variable]
+
+ assert variable in NOT_A_SETTING, f"{variable} is in the example and nothing declares it"
+
+ return frozenset({NOT_A_SETTING[variable]})
+
+
+@pytest.mark.parametrize("title", [title for title, _ in _env_sections()])
+def test_every_section_of_the_example_belongs_to_one_feature_or_to_the_core(title: str):
+ """Spec 6.1 keeps or drops a section whole, so a section can hold one feature's variables or
+ the core's, never both: dropping a mixed one would take `SECRET_KEY` from every project
+ without accounts.
+ """
+ variables = next(found for name, found in _env_sections() if name == title)
+ owners = {owner for variable in variables for owner in _owner_of(variable)}
+
+ assert len(owners) <= 1, sorted(owners)
+
+
+def test_the_example_is_read_the_way_it_is_written():
+ """The reading itself: a parse that found no sections, or missed the commented-out lines,
+ would leave the rule above with nothing to object to."""
+ sections = dict(_env_sections())
+
+ assert len(sections) >= 15
+ assert "CREATE_TABLES_ON_STARTUP" in sections["Database Configuration"], "a line shipped commented out"
+ assert _owner_of("SECRET_KEY") == frozenset({"core"})
+ assert _owner_of("CACHE_BACKEND") == frozenset({"cache"})
+ assert _owner_of("SESSION_REDIS_URL") == frozenset({"accounts"})
+
+
@pytest.mark.parametrize(("feature", "option"), sorted(OPTION_SOURCES))
def test_every_option_defaults_to_what_the_project_already_ships(feature: str, option: str):
"""The question `fastro new` asks pre-picks the value a clone of this repo runs with."""
From 2ffce919a232aa2696462e5fcb89f87dafc47f34 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Sat, 31 Oct 2026 01:38:45 -0300
Subject: [PATCH 25/71] say which feature keeps each section of the environment
example
---
backend/.env.example | 64 ++++--
backend/tests/unit/test_blueprint_catalog.py | 193 +++++++++++++++++--
2 files changed, 221 insertions(+), 36 deletions(-)
diff --git a/backend/.env.example b/backend/.env.example
index 6543bbaf..a7374a7c 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -40,6 +40,7 @@ POSTGRES_POOL_RECYCLE=-1
# ===================================
# Cache Configuration
# ===================================
+# @fastro if=cache
CACHE_ENABLED=true
# Options: memcached, redis
# @fastro option=cache.backend
@@ -61,9 +62,13 @@ CACHE_REDIS_PASSWORD=
CACHE_REDIS_CONNECT_TIMEOUT=5
CACHE_REDIS_POOL_SIZE=10
+# Before production: set CACHE_REDIS_PASSWORD, and keep CACHE_REDIS_DB to this service
+# alone, so a flush here leaves every other service's keys where they were.
+
# ===================================
# Rate Limiting Configuration
# ===================================
+# @fastro if=ratelimit
# The per-caller throttle on the API routes. Limits are resolved per request from the
# user's tier and path, falling back to the defaults below.
RATE_LIMITER_ENABLED=true
@@ -73,6 +78,7 @@ DEFAULT_RATE_LIMIT_PERIOD=60
# ===================================
# Rate Limiter Store
# ===================================
+# @fastro if=accounts
# Where the counters live: the login lockout keeps its own here, and the API throttle,
# where it is selected, shares them.
# redis (default), database or memory. Memory counters are per process, so each worker
@@ -91,6 +97,9 @@ RATE_LIMITER_REDIS_PASSWORD=
RATE_LIMITER_REDIS_CONNECT_TIMEOUT=5
RATE_LIMITER_REDIS_POOL_SIZE=10
+# Before production: set RATE_LIMITER_REDIS_PASSWORD, and keep RATE_LIMITER_REDIS_DB to
+# the counters alone.
+
# ===================================
# Email Configuration
# ===================================
@@ -120,6 +129,7 @@ EMAIL_SMTP_TIMEOUT_SECONDS=10
# ===================================
# API Keys
# ===================================
+# @fastro if=api_keys
# How many days of key usage rows to keep. Each row carries the caller's address and
# user agent, one row per request. 0 keeps every row and prunes nothing, and a value
# below 0 is refused at startup. The analytics
@@ -134,6 +144,7 @@ KEY_USAGE_RETENTION_DAYS=90
# ===================================
# Taskiq Configuration
# ===================================
+# @fastro if=taskiq
# Broker type: 'redis' or 'rabbitmq'
# @fastro option=taskiq.broker
TASKIQ_BROKER_TYPE=redis
@@ -162,6 +173,9 @@ TASKIQ_RABBITMQ_USER=guest
TASKIQ_RABBITMQ_PASSWORD=guest
TASKIQ_RABBITMQ_VHOST=/
+# Before production: give RabbitMQ credentials of the project's own rather than
+# guest/guest, and keep TASKIQ_REDIS_DB to the broker alone.
+
# ===================================
# Web Server Configuration
@@ -188,8 +202,7 @@ CLIENT_CACHE_MAX_AGE=60
# Which peers uvicorn accepts X-Forwarded-For and X-Forwarded-Proto from. Read by
# uvicorn, not by the app, and it decides what request.client and the access logs
# say. Name your proxy's address or subnet; a wildcard lets any client claim any
-# address. Leave unset when nothing sits in front of the app. The login lockout, where
-# there is one, counts proxy hops with TRUSTED_PROXY_HOPS instead.
+# address. Leave unset when nothing sits in front of the app.
# FORWARDED_ALLOW_IPS=172.31.240.0/24
# API documentation settings
@@ -208,6 +221,7 @@ PRODUCTION_SECURITY_VALIDATION_ENABLED=true
# ===================================
# Authentication & Security
# ===================================
+# @fastro if=accounts
# Session Management
SESSION_TIMEOUT_MINUTES=30
SESSION_CLEANUP_INTERVAL_MINUTES=15
@@ -235,10 +249,18 @@ SESSION_SECURE_COOKIES=true
# workers share them with no Redis; it adds the crudauth_store and crudauth_counters
# tables, which need one migration.
SESSION_BACKEND=redis
-# Sessions, CSRF tokens, OAuth state and login lockout counters use the cache Redis
-# connection (CACHE_REDIS_*) on their own DB, so a cache flush doesn't log everyone out.
+# Sessions, CSRF tokens, OAuth state and login lockout counters keep their own DB on the
+# session Redis connection, so a cache flush doesn't log everyone out.
SESSION_REDIS_DB=2
-# Optional full URL for a dedicated session Redis; overrides the cache connection and SESSION_REDIS_DB.
+# The connection itself. Left unset, each of these reads the cache's CACHE_REDIS_* where the
+# cache is selected, and localhost:6379 with no password otherwise, which is not the compose
+# stack's Redis. Set them when there is no cache, or to point sessions somewhere else. Setting
+# SESSION_REDIS_PASSWORD overrides the cache's password rather than adding to it.
+# SESSION_REDIS_HOST=redis
+# SESSION_REDIS_PORT=6379
+# SESSION_REDIS_PASSWORD=
+# Optional full URL for a dedicated session Redis; overrides the connection above and
+# SESSION_REDIS_DB.
# SESSION_REDIS_URL=rediss://user:password@sessions-redis.example.com:6380/0
# CSRF Protection
@@ -256,9 +278,14 @@ PASSWORD_REQUIRE_LOWERCASE=true
PASSWORD_REQUIRE_DIGIT=true
PASSWORD_REQUIRE_SPECIAL=true
+# Before production: read the session timeouts above against what you need, keep
+# SESSION_REDIS_DB to the session store alone, and make sure the session Redis has a
+# password, whether it comes from the cache's or from SESSION_REDIS_PASSWORD.
+
# ===================================
# Admin Interface (SQLAdmin)
# ===================================
+# @fastro if=admin
# Enable/disable the admin interface
ADMIN_ENABLED=true
# Where the panel is mounted; the admin session cookie is scoped to this path
@@ -267,6 +294,7 @@ ADMIN_BASE_URL=/admin
# ===================================
# OAuth Configuration
# ===================================
+# @fastro if=accounts
OAUTH_REDIRECT_BASE_URL=http://localhost:8000
# Google OAuth
@@ -321,15 +349,25 @@ API_TERMS_OF_SERVICE=
# DOCS_URL=/docs
# REDOC_URL=/redoc
+# ===================================
+# Tiers
+# ===================================
+# @fastro if=tiers
+# The tier the initial-data step creates, if it isn't there already.
+DEFAULT_TIER_NAME=free
+
# ===================================
# Initial Setup Configuration
# ===================================
+# @fastro if=accounts
# Admin user settings (for initial setup)
ADMIN_NAME=Admin User
ADMIN_EMAIL=admin@example.com
ADMIN_USERNAME=admin
ADMIN_PASSWORD=Change-Me-Now-1!
+# Before production: set ADMIN_USERNAME and ADMIN_PASSWORD to credentials of your own.
+
# ===================================
# Production Security Checklist
# ===================================
@@ -337,16 +375,6 @@ ADMIN_PASSWORD=Change-Me-Now-1!
# 1. Generate strong SECRET_KEY with high entropy
# Example: python -c "import secrets; print(secrets.token_urlsafe(64))"
# 2. Set unique database passwords (avoid defaults like 'postgres')
-# 3. Set Redis passwords for all instances:
-# - CACHE_REDIS_PASSWORD (for cache operations and sessions)
-# - RATE_LIMITER_REDIS_PASSWORD (for rate limiting)
-# 4. Use separate Redis instances/databases for different services:
-# - Cache: CACHE_REDIS_DB=0 (default)
-# - Rate Limiter: RATE_LIMITER_REDIS_DB=1 (default)
-# - Sessions: SESSION_REDIS_DB=2 (default)
-# - Taskiq: TASKIQ_REDIS_DB=3 (default)
-# 5. Restrict CORS_ORIGINS to specific domains (avoid *)
-# 6. Set strong admin credentials (ADMIN_USERNAME, ADMIN_PASSWORD)
-# 7. Review session timeout settings for your security requirements
-# 8. Set ENVIRONMENT=production to enable security validation
-# 9. Configure RabbitMQ with strong credentials (avoid guest/guest)
+# 3. Restrict CORS_ORIGINS to specific domains (avoid *)
+# 4. Set ENVIRONMENT=production to enable security validation
+# Each selected feature carries its own checks beside the settings they are about.
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 024da6af..107a1948 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -1246,20 +1246,36 @@ def test_every_option_offers_the_values_its_feature_acts_on(feature: str, option
ENV_EXAMPLE = REPO_ROOT / "backend" / ".env.example"
NOT_A_SETTING = {
- "DATABASE_URL": "core",
"FORWARDED_ALLOW_IPS": "core",
- "SESSION_REDIS_URL": "accounts",
}
-"""Variables the example sets that no settings field declares, and where each belongs:
-`DATABASE_URL` is the name `DATABASE_URL_OVERRIDE` is aliased to, `FORWARDED_ALLOW_IPS` is read
-by uvicorn and written by the deploy templates, and `SESSION_REDIS_URL` is built by the accounts
-settings rather than declared as a field."""
+"""Variables the example sets that no settings field takes: `FORWARDED_ALLOW_IPS` is read by
+uvicorn and written by the deploy templates, never by the app."""
+
+
+def _alias_names(node: ast.AnnAssign) -> set[str]:
+ """The names a field accepts besides its own, which is how one feature's setting reads
+ another's: `SESSION_REDIS_HOST` takes `CACHE_REDIS_HOST` when nothing sets it."""
+ names: set[str] = set()
+ for given in getattr(node.value, "keywords", ()):
+ if given.arg != "validation_alias":
+ continue
+
+ if isinstance(given.value, ast.Constant) and isinstance(given.value.value, str):
+ names.add(given.value.value)
+ else:
+ names.update(
+ argument.value
+ for argument in getattr(given.value, "args", ())
+ if isinstance(argument, ast.Constant) and isinstance(argument.value, str)
+ )
+
+ return names
@functools.cache
def _settings_fields() -> dict[str, frozenset[str]]:
- """Which part of the project declares each setting: `core`, or the features whose contributed
- settings classes declare it."""
+ """Which parts of the project take each setting: `core`, or the features whose contributed
+ settings classes declare it, counting the names a field accepts as aliases as well."""
modules: dict[str, list[Path]] = {"core": [REPO_ROOT / "backend/src/infrastructure/config/base.py"]}
for name, feature in _catalog()["features"].items():
for entry in feature.get("contributes", {}).get("settings", ()):
@@ -1271,15 +1287,38 @@ def _settings_fields() -> dict[str, frozenset[str]]:
for path in paths:
for node in ast.walk(ast.parse(path.read_text())):
if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id.isupper():
- declared.setdefault(node.target.id, set()).add(owner)
+ for name in {node.target.id} | _alias_names(node):
+ declared.setdefault(name, set()).add(owner)
return {name: frozenset(owners) for name, owners in declared.items()}
@functools.cache
-def _env_sections() -> tuple[tuple[str, tuple[str, ...]], ...]:
- """Each section of the example: its title, and the variables it sets, including the ones it
- ships commented out, since a reader uncomments them where they sit."""
+def _env_comments() -> dict[str, tuple[str, ...]]:
+ """Each section's comment lines, less its markers, which name variables as data."""
+ lines = ENV_EXAMPLE.read_text().splitlines()
+ rule = re.compile(r"^# ={10,}$")
+ headers = [
+ index
+ for index, line in enumerate(lines)
+ if rule.match(line) and index + 2 < len(lines) and rule.match(lines[index + 2])
+ ]
+
+ comments = {}
+ for position, start in enumerate(headers):
+ end = headers[position + 1] if position + 1 < len(headers) else len(lines)
+ comments[lines[start + 1].lstrip("# ").strip()] = tuple(
+ line for line in lines[start + 3 : end] if line.lstrip().startswith("#") and "@fastro" not in line
+ )
+
+ return comments
+
+
+@functools.cache
+def _env_sections() -> tuple[tuple[str, str | None, tuple[str, ...]], ...]:
+ """Each section of the example: its title, the marker directly below its header if it carries
+ one, and the variables it sets, including the ones it ships commented out, since a reader
+ uncomments them where they sit."""
lines = ENV_EXAMPLE.read_text().splitlines()
rule = re.compile(r"^# ={10,}$")
headers = [
@@ -1294,7 +1333,8 @@ def _env_sections() -> tuple[tuple[str, tuple[str, ...]], ...]:
variables = tuple(
found.group(1) for line in lines[start + 3 : end] if (found := re.match(r"^#?\s*([A-Z][A-Z0-9_]*)=", line))
)
- sections.append((lines[start + 1].lstrip("# ").strip(), variables))
+ marker = lines[start + 3] if start + 3 < end and lines[start + 3].startswith("# @fastro ") else None
+ sections.append((lines[start + 1].lstrip("# ").strip(), marker, variables))
return tuple(sections)
@@ -1309,28 +1349,145 @@ def _owner_of(variable: str) -> frozenset[str]:
return frozenset({NOT_A_SETTING[variable]})
-@pytest.mark.parametrize("title", [title for title, _ in _env_sections()])
+def _owners_of(title: str) -> set[str]:
+ """Every part of the project that takes any of this section's variables."""
+ variables = next(found for name, _, found in _env_sections() if name == title)
+
+ return {owner for variable in variables for owner in _owner_of(variable)}
+
+
+def _common_owners_of(title: str) -> set[str]:
+ """The parts that take *every* variable in the section, which is what a marker can name."""
+ variables = next(found for name, _, found in _env_sections() if name == title)
+
+ return set.intersection(*(set(_owner_of(variable)) for variable in variables)) if variables else {"core"}
+
+
+def _marked_feature(title: str) -> str:
+ marker = next(found for name, found, _ in _env_sections() if name == title)
+
+ return marker.removeprefix("# @fastro if=") if marker else "core"
+
+
+@pytest.mark.parametrize("title", [title for title, _, _ in _env_sections()])
def test_every_section_of_the_example_belongs_to_one_feature_or_to_the_core(title: str):
"""Spec 6.1 keeps or drops a section whole, so a section can hold one feature's variables or
the core's, never both: dropping a mixed one would take `SECRET_KEY` from every project
without accounts.
"""
- variables = next(found for name, found in _env_sections() if name == title)
- owners = {owner for variable in variables for owner in _owner_of(variable)}
+ assert _common_owners_of(title), sorted(_owners_of(title))
+
+
+@pytest.mark.parametrize("title", [title for title, _, _ in _env_sections()])
+def test_every_section_a_feature_owns_says_which_feature_keeps_it(title: str):
+ """Spec 6.1: the marker is a line of its own directly below the header's closing rule, and
+ the section goes when its condition is false. A core section carries none, because a project
+ keeps it whatever it selected.
+ """
+ common = _common_owners_of(title)
+ marker = next(found for name, found, _ in _env_sections() if name == title)
+
+ if common == {"core"}:
+ assert marker is None, title
+
+ return
+
+ assert marker is not None, sorted(common)
+ assert marker.removeprefix("# @fastro if=") in common - {"core"}
+
+
+@pytest.mark.parametrize("title", [title for title, _, _ in _env_sections()])
+def test_no_section_sends_a_reader_to_a_variable_another_feature_owns(title: str):
+ """A kept section has to read on its own: a project that selected one feature and not another
+ would otherwise be told to set something it hasn't got, with nowhere to set it.
+
+ Only variables this section's own feature declares, or the core's, may be named. The
+ production checklist is the reason this exists: it used to name eight of them.
+ """
+ mine = {_marked_feature(title)}
+ named = {
+ word
+ for line in _env_comments()[title]
+ for word in re.findall(r"\b[A-Z][A-Z0-9_]{2,}\b", line)
+ if word in _settings_fields() or word in NOT_A_SETTING
+ }
+
+ assert {word: sorted(_owner_of(word)) for word in named if not _owner_of(word) & (mine | {"core"})} == {}
+
+
+@functools.cache
+def _fields_falling_back_to_another_feature() -> dict[str, frozenset[str]]:
+ """Fields that read another feature's variable when nothing sets their own, with the features
+ whose names they borrow. `SESSION_REDIS_HOST` takes `CACHE_REDIS_HOST`, so a project with
+ accounts and no cache has nothing in its example pointing sessions at Redis."""
+ fields: dict[str, set[str]] = {}
+ for name, feature in _catalog()["features"].items():
+ for entry in feature.get("contributes", {}).get("settings", ()):
+ module, _, _ = _ref(entry if isinstance(entry, str) else entry["ref"])
+ path = REPO_ROOT / "backend" / Path(*module.split(".")).with_suffix(".py")
+ for node in ast.walk(ast.parse(path.read_text())):
+ if not isinstance(node, ast.AnnAssign) or not isinstance(node.target, ast.Name):
+ continue
+
+ borrowed = {
+ owner for alias in _alias_names(node) - {node.target.id} for owner in _owner_of(alias) if owner != name
+ }
+ if borrowed:
+ fields.setdefault(node.target.id, set()).update(borrowed)
+
+ return {name: frozenset(owners) for name, owners in fields.items()}
+
+
+@pytest.mark.parametrize("field", sorted(_fields_falling_back_to_another_feature()))
+def test_every_setting_that_borrows_another_features_variable_is_named_in_its_own_section(field: str):
+ """Otherwise the only line that sets it is the other feature's, and a project without that
+ feature is left with the default: for the session Redis, `localhost`, which is not the
+ service name the compose stack publishes.
+
+ The line may be commented out. It is there to be found and uncommented, and a live one would
+ beat the borrowed value rather than fall back to it.
+ """
+ owners = _owner_of(field) - _fields_falling_back_to_another_feature()[field]
+ sections = {title: variables for title, _, variables in _env_sections()}
+ theirs = [title for title in sections if _marked_feature(title) in owners]
+
+ assert theirs, sorted(owners)
+ assert any(field in sections[title] for title in theirs), (
+ f"{field} is set only by {sorted(_fields_falling_back_to_another_feature()[field])}"
+ )
+
+
+def test_the_comments_are_read_the_way_they_are_written():
+ """The reading above: comments that stopped being found would leave it nothing to object to."""
+ comments = _env_comments()
+
+ assert any("SECRET_KEY" in line for line in comments["Production Security Checklist"])
+ assert any("CACHE_REDIS_DB" in line for line in comments["Cache Configuration"])
+ assert not any("@fastro" in line for section in comments.values() for line in section)
+
+
+def test_no_marker_sits_anywhere_but_under_a_header():
+ """A marker further down would speak for the lines after it, which spec 6.1 doesn't read:
+ the section is what the condition keeps or drops."""
+ lines = ENV_EXAMPLE.read_text().splitlines()
+ marked = [line for line in lines if line.startswith("# @fastro if=")]
+ under_headers = [marker for _, marker, _ in _env_sections() if marker is not None]
- assert len(owners) <= 1, sorted(owners)
+ assert marked == under_headers
+ assert all(_true(marker.removeprefix("# @fastro if="), set(_catalog()["features"])) for marker in marked)
def test_the_example_is_read_the_way_it_is_written():
"""The reading itself: a parse that found no sections, or missed the commented-out lines,
would leave the rule above with nothing to object to."""
- sections = dict(_env_sections())
+ sections = {title: variables for title, _, variables in _env_sections()}
assert len(sections) >= 15
assert "CREATE_TABLES_ON_STARTUP" in sections["Database Configuration"], "a line shipped commented out"
assert _owner_of("SECRET_KEY") == frozenset({"core"})
assert _owner_of("CACHE_BACKEND") == frozenset({"cache"})
assert _owner_of("SESSION_REDIS_URL") == frozenset({"accounts"})
+ assert _owner_of("CACHE_REDIS_HOST") == frozenset({"accounts", "cache"}), "the session host takes it too"
@pytest.mark.parametrize(("feature", "option"), sorted(OPTION_SOURCES))
From 7dad5848dc409e206c35b98adb02ea3ff1dad5b6 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Sat, 31 Oct 2026 01:44:50 -0300
Subject: [PATCH 26/71] keep the blueprint's own files out of the source
tarball
---
.gitattributes | 4 ++
backend/tests/unit/test_tarball_contents.py | 59 +++++++++++++++++++++
blueprint.toml | 2 +
3 files changed, 65 insertions(+)
create mode 100644 .gitattributes
create mode 100644 backend/tests/unit/test_tarball_contents.py
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 00000000..c4926b32
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,4 @@
+docs/ export-ignore
+tools/ export-ignore
+zensical.toml export-ignore
+.github/ISSUE_TEMPLATE/ export-ignore
diff --git a/backend/tests/unit/test_tarball_contents.py b/backend/tests/unit/test_tarball_contents.py
new file mode 100644
index 00000000..84b82b84
--- /dev/null
+++ b/backend/tests/unit/test_tarball_contents.py
@@ -0,0 +1,59 @@
+"""What a source tarball carries, which is whatever `git archive` writes.
+
+GitHub builds a release's tarball the same way, so a path marked `export-ignore` is one a
+download doesn't have. What's left out is the blueprint's own: the documentation site, the
+removal drill and the issue templates are things to read or run in this repository, not things
+a reader builds the project from.
+"""
+
+import io
+import subprocess
+import tarfile
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+
+LEFT_OUT = (".github/ISSUE_TEMPLATE/", "docs/", "tools/", "zensical.toml")
+"""The paths `.gitattributes` keeps out of the tarball."""
+
+CARRIED = ("README.md", "backend/Dockerfile", "backend/pyproject.toml", "backend/src/interfaces/main.py")
+"""A few a reader could not build the project without, so the archive is read, not assumed.
+
+The compose file is not among them: `.gitignore` keeps it out, because the deploy generator
+writes it."""
+
+
+def _archived() -> set[str]:
+ """Every path `git archive` writes for the current commit.
+
+ The attributes are read from the working tree rather than from `HEAD`, so a `.gitattributes`
+ that isn't committed yet still counts and the answer doesn't wait for the commit.
+ """
+ written = subprocess.run(
+ ["git", "archive", "--worktree-attributes", "--format=tar", "HEAD"],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ check=True,
+ )
+ with tarfile.open(fileobj=io.BytesIO(written.stdout)) as archive:
+ return {member.name for member in archive.getmembers()}
+
+
+def test_the_tarball_leaves_out_what_only_this_repository_needs():
+ archived = _archived()
+
+ assert {name for name in archived for path in LEFT_OUT if name.startswith(path.rstrip("/"))} == set()
+
+
+def test_the_tarball_carries_what_the_project_is_built_from():
+ """The other direction, and the proof that the archive was read at all."""
+ archived = _archived()
+
+ assert archived
+ assert set(CARRIED) <= archived
+
+
+def test_every_path_kept_out_is_one_this_repository_has():
+ """A path that moved would be ignored silently, leaving the real one in the tarball."""
+ for path in LEFT_OUT:
+ assert (REPO_ROOT / path).exists(), path
diff --git a/blueprint.toml b/blueprint.toml
index 6dd734c0..55954b4d 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -6,6 +6,7 @@ requires_fastro = ">=0.1.0.dev0,<0.2"
python_root = "backend"
import_root = "src"
blueprint_only = [
+ ".gitattributes",
".github/",
".pre-commit-config.yaml",
"CODE_OF_CONDUCT.md",
@@ -18,6 +19,7 @@ blueprint_only = [
"backend/tests/unit/test_docs_wiring.py",
"backend/tests/unit/test_image_contents.py",
"backend/tests/unit/test_removal_drill.py",
+ "backend/tests/unit/test_tarball_contents.py",
"blueprint/",
"blueprint.toml",
"cli/",
From e46bf26cf8b2f2f2bb182e29b0b78b3b7ba34616 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Sat, 31 Oct 2026 01:54:36 -0300
Subject: [PATCH 27/71] give taskiq's reload extra to the taskiq feature, and
drop the example's em dash
---
backend/.env.example | 2 +-
backend/tests/unit/test_blueprint_catalog.py | 79 ++++++++++++++++----
blueprint.toml | 5 +-
3 files changed, 67 insertions(+), 19 deletions(-)
diff --git a/backend/.env.example b/backend/.env.example
index a7374a7c..9d28355d 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -23,7 +23,7 @@ POSTGRES_ASYNC_PREFIX=postgresql+asyncpg://
# CREATE_TABLES_ON_STARTUP=true
# Hosted / serverless Postgres (Neon, RDS, Cloud SQL, ...): DATABASE_URL overrides
-# every POSTGRES_* value above. Mind the asyncpg spelling — the driver prefix is
+# every POSTGRES_* value above. Mind the asyncpg spelling: the driver prefix is
# postgresql+asyncpg:// and TLS is ssl=require, NOT libpq's sslmode=require.
# Guide: https://benavlabs.github.io/FastAPI-boilerplate/user-guide/database/neon/
# DATABASE_URL=postgresql+asyncpg://user:password@host.example.com/dbname?ssl=require
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 107a1948..b2b19dad 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -83,14 +83,16 @@ def test_development_builds_of_the_tool_can_read_it():
assert _catalog()["blueprint"]["requires_fastro"] == ">=0.1.0.dev0,<0.2"
-def _declared_specifiers() -> set[str]:
- """Every runtime specifier a project could install: the core's, each feature's, each option's."""
- specifiers = set(_catalog()["blueprint"]["dependencies"]["runtime"])
+def _declared_specifiers(listing: str = "runtime") -> set[str]:
+ """Every specifier a project could install from this listing: the core's, each feature's, each
+ `when` block's, and, for the runtime one, each option's."""
+ key = "dependencies" if listing == "runtime" else "dev_dependencies"
+ specifiers = set(_catalog()["blueprint"]["dependencies"][listing])
for feature in _catalog()["features"].values():
- specifiers.update(feature.get("dependencies", ()))
+ specifiers.update(feature.get(key, ()))
for block in feature.get("when", ()):
- specifiers.update(block.get("dependencies", ()))
- for option in feature.get("options", {}).values():
+ specifiers.update(block.get(key, ()))
+ for option in feature.get("options", {}).values() if listing == "runtime" else ():
for chosen in option.get("dependencies", {}).values():
specifiers.update(chosen)
@@ -107,7 +109,7 @@ def test_the_dependencies_a_project_could_install_are_the_ones_the_backend_decla
backend = tomllib.load(handle)
assert _declared_specifiers() == set(backend["project"]["dependencies"])
- assert _catalog()["blueprint"]["dependencies"]["dev"] == backend["project"]["optional-dependencies"]["dev"]
+ assert _declared_specifiers("dev") == set(backend["project"]["optional-dependencies"]["dev"])
def _distribution(specifier: str) -> str:
@@ -198,11 +200,8 @@ def _importers() -> dict[str, frozenset[str]]:
def _declared_distributions(listing: str) -> set[str]:
- """The distributions a listing names: `runtime` is every list a project could install from."""
- if listing == "runtime":
- return {_distribution(specifier) for specifier in _declared_specifiers()}
-
- return {_distribution(specifier) for specifier in _catalog()["blueprint"]["dependencies"][listing]}
+ """The distributions a listing names, the core's and every feature's together."""
+ return {_distribution(specifier) for specifier in _declared_specifiers(listing)}
INDIRECT_NEEDS = {
@@ -332,6 +331,28 @@ def test_no_file_a_project_keeps_imports_a_dependency_it_did_not_select():
assert _under(file, removed) or _withheld(file), (sorted(chosen), name, file)
+@pytest.mark.parametrize(
+ ("feature", "specifier"),
+ sorted(
+ (name, specifier)
+ for name, feature in _catalog()["features"].items()
+ for specifier in feature.get("dev_dependencies", ())
+ ),
+)
+def test_every_feature_development_dependency_belongs_to_that_feature(feature: str, specifier: str):
+ """An extra is never imported by name, so what makes it the feature's is the distribution it
+ extends: `taskiq[reload]` is the taskiq worker's own `--reload`, and a project with no worker
+ has nothing to reload. A file of the feature's importing it counts too, for a test-only
+ dependency that is imported.
+ """
+ name = _distribution(specifier)
+ runtime = {_distribution(entry) for entry in _catalog()["features"][feature].get("dependencies", ())}
+ owned = [path for path, _ in _declared(_catalog()["features"][feature])]
+ importers = {file for module in _provided().get(name, ()) for file in _importers().get(module, ())}
+
+ assert name in runtime or any(_under(file, owned) for file in importers), name
+
+
@pytest.mark.parametrize(
("feature", "option", "value", "specifier"),
sorted(
@@ -1803,8 +1824,19 @@ def test_the_catalog_accounts_for_what_the_file_imports_for_every_selection(path
assert _declared_bindings(catalog, entry, chosen) == written, sorted(chosen)
-LINE_LENGTH = 128
-"""The project's ruff line length, which spec 2.8 wraps a generated import at."""
+LINE_LENGTH = _catalog()["wiring_defaults"]["line_length"]
+"""Spec 2.12: the length spec 2.8 wraps a generated import at, declared rather than assumed."""
+
+
+def test_the_generated_line_length_is_the_one_ruff_holds_the_project_to():
+ """Spec 2.12: an integer from 1 to 320. Declared shorter than ruff's, fastro would wrap an
+ import ruff is happy with; longer, and `ruff format --check` fails on a file nobody edited.
+ """
+ with BACKEND_PYPROJECT.open("rb") as handle:
+ backend = tomllib.load(handle)
+
+ assert 1 <= LINE_LENGTH <= 320
+ assert LINE_LENGTH == backend["tool"]["ruff"]["line-length"]
@pytest.mark.parametrize("path", [entry["path"] for entry in _entries()])
@@ -1903,9 +1935,21 @@ def test_every_param_is_declared_the_way_the_spec_asks(generator: str, param: st
def test_the_subnet_default_is_a_network_with_no_host_bits_set():
"""Spec 2.9: `10.0.0.1/24` is not a network, and the tool would refuse the catalog for it."""
declared = _catalog()["generators"]["deploy"]["params"]["internal_subnet"]
+ network = ipaddress.ip_network(declared["default"], strict=True)
+
+ assert str(network) == declared["default"]
+ assert network.prefixlen >= declared["max_prefix"][f"v{network.version}"], "the default meets its own limit"
+
- assert str(ipaddress.ip_network(declared["default"], strict=True)) == declared["default"]
- assert 0 <= declared["max_prefix"] <= 128
+def test_the_subnet_limit_is_set_for_both_families():
+ """Spec 2.9: a table with both `v4` (0 to 32) and `v6` (0 to 128), because one integer can't
+ carry the two. An IPv6 limit of 8 would accept a `/16`, which is half the address space.
+ """
+ limits = _catalog()["generators"]["deploy"]["params"]["internal_subnet"]["max_prefix"]
+
+ assert set(limits) == {"v4", "v6"}
+ assert 0 <= limits["v4"] <= 32
+ assert 0 <= limits["v6"] <= 128
def test_every_param_the_templates_read_is_a_param_the_catalog_declares():
@@ -1927,6 +1971,9 @@ def test_the_defaults_are_what_this_repos_own_generator_already_uses():
assert f'typer.Option({params["workers"]["default"]}, "--workers"' in source
assert f'DEFAULT_INTERNAL_SUBNET = "{params["internal_subnet"]["default"]}"' in subnet
+ limits = params["internal_subnet"]["max_prefix"]
+ assert f"SMALLEST_TRUSTED_PREFIX = {{4: {limits['v4']}, 6: {limits['v6']}}}" in subnet
+
def _declared_commands() -> list[tuple[str | None, str, dict[str, Any]]]:
"""Every declared command: the feature that owns it, or none, with its words and its table.
diff --git a/blueprint.toml b/blueprint.toml
index 55954b4d..84f2ffff 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -54,7 +54,6 @@ dev = [
"pytest-mock>=3.14.0",
"testcontainers[postgres]>=4.10.0",
"pytest-xdist[psutil]>=3.8.0",
- "taskiq[reload]>=0.11.20",
"pre-commit>=4.0.0",
"faker>=37.1.0",
"httpx>=0.28.1",
@@ -440,6 +439,7 @@ dependencies = [
"taskiq-aio-pika>=0.4.3",
"cryptography>=42.0.0",
]
+dev_dependencies = ["taskiq[reload]>=0.11.20"]
paths = [
"backend/src/infrastructure/taskiq/",
"backend/tests/unit/infrastructure/taskiq/",
@@ -467,6 +467,7 @@ contributes.task_modules = [{ value = "src.infrastructure.taskiq.email", order =
[wiring_defaults]
+line_length = 128
header = """Generated by fastro from blueprint.toml and fastro.toml. Don't edit: change
fastro.toml (or [app] in it, for your own code) and run `fastro sync`."""
@@ -710,7 +711,7 @@ help = "Number of API workers, for the prod and nginx modes."
[generators.deploy.params.internal_subnet]
type = "cidr"
default = "172.31.240.0/24"
-max_prefix = 8
+max_prefix = { v4 = 8, v6 = 48 }
help = "The compose network, and the only peers uvicorn takes forwarded headers from, in nginx mode."
[commands."env secret"]
From ccae106a37e7917c452499bffd52e744bf57349e Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Sat, 31 Oct 2026 02:07:55 -0300
Subject: [PATCH 28/71] give projects their own gitignore and agent
instructions
---
blueprint.toml | 2 +
blueprint/overlay/.gitignore | 22 ++++++
blueprint/overlay/AGENTS.md | 43 +++++++++++
blueprint/overlay/CLAUDE.md | 1 +
blueprint/tests/test_overlay.py | 133 ++++++++++++++++++++++++++++++++
5 files changed, 201 insertions(+)
create mode 100644 blueprint/overlay/.gitignore
create mode 100644 blueprint/overlay/AGENTS.md
create mode 100644 blueprint/overlay/CLAUDE.md
create mode 100644 blueprint/tests/test_overlay.py
diff --git a/blueprint.toml b/blueprint.toml
index 84f2ffff..8017ce00 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -4,9 +4,11 @@ version = "0.20.0"
schema = 1
requires_fastro = ">=0.1.0.dev0,<0.2"
python_root = "backend"
+overlay = "blueprint/overlay"
import_root = "src"
blueprint_only = [
".gitattributes",
+ ".gitignore",
".github/",
".pre-commit-config.yaml",
"CODE_OF_CONDUCT.md",
diff --git a/blueprint/overlay/.gitignore b/blueprint/overlay/.gitignore
new file mode 100644
index 00000000..81525504
--- /dev/null
+++ b/blueprint/overlay/.gitignore
@@ -0,0 +1,22 @@
+# Python
+__pycache__/
+*.py[cod]
+*.egg-info/
+.venv/
+
+# Tooling caches
+.mypy_cache/
+.pytest_cache/
+.ruff_cache/
+.coverage
+htmlcov/
+
+# Configuration: .env.example is the one that is committed
+.env
+.env.*
+!.env.example
+
+# Editors
+.idea/
+.vscode/
+.DS_Store
diff --git a/blueprint/overlay/AGENTS.md b/blueprint/overlay/AGENTS.md
new file mode 100644
index 00000000..72be0aa3
--- /dev/null
+++ b/blueprint/overlay/AGENTS.md
@@ -0,0 +1,43 @@
+# Working in this project
+
+A FastAPI backend generated by fastro. `backend/` holds everything that runs.
+
+## The layers
+
+- `src/interfaces/`: the app itself, the FastAPI factory and the routers it mounts.
+- `src/modules//`: one domain each, as `models.py`, `schemas.py`, `crud.py`, `service.py`
+ and `routes.py`. A module owns its tables and its rules, and reaches another module through
+ its service rather than its tables.
+- `src/infrastructure/`: what every module uses, such as the settings and the database, plus
+ whatever each selected feature brought with it.
+- `src/wiring/`: generated. It lists what this project selected, so the app imports one name per
+ extension point instead of asking what exists.
+
+## Adding code
+
+Add a domain as a module under `src/modules/`, following an existing one: the names and the file
+split are the pattern to copy. Register its router and anything else it contributes under
+`[app].contributes` in `fastro.toml`, then run `fastro sync`.
+
+**Never edit `src/wiring/`.** Those files are written from `blueprint.toml` and `fastro.toml`, and
+`fastro sync` overwrites them. To change what is wired, change `[app]` in `fastro.toml` and sync.
+
+A setting of your own goes on a settings class in the module that reads it, contributed under
+`[app].contributes.settings` in `fastro.toml` and picked up by `fastro sync`. Add its variable to
+`backend/.env.example` outside the marked sections, which belong to the features that own them.
+The files under `src/infrastructure/config/` are the blueprint's: a change there is one
+`fastro update` has to merge, so keep your own settings in your module.
+
+## Before finishing
+
+From `backend/`:
+
+```bash
+uv run --no-sync ruff check . && uv run --no-sync ruff format --check .
+uv run --no-sync mypy src scripts migrations tests
+uv run --no-sync pytest
+```
+
+Then `fastro check --json` from the project root, and read what it reports. A schema change needs a
+migration: `uv run --no-sync alembic revision --autogenerate -m "what changed"`, reviewed by hand
+before it is applied.
diff --git a/blueprint/overlay/CLAUDE.md b/blueprint/overlay/CLAUDE.md
new file mode 100644
index 00000000..43c994c2
--- /dev/null
+++ b/blueprint/overlay/CLAUDE.md
@@ -0,0 +1 @@
+@AGENTS.md
diff --git a/blueprint/tests/test_overlay.py b/blueprint/tests/test_overlay.py
new file mode 100644
index 00000000..d6acbd52
--- /dev/null
+++ b/blueprint/tests/test_overlay.py
@@ -0,0 +1,133 @@
+"""What the overlay puts in a project, and what it is allowed to say.
+
+Spec 2.1: the overlay's tree is copied into projects, and a `*.j2` file is rendered with the
+spec 6.2 context and loses the suffix. So every path here lands in a project beside the files
+core copies, and every name a template reads has to be one the tool passes.
+"""
+
+import re
+import tomllib
+from pathlib import Path
+from typing import Any
+
+import pytest
+from jinja2 import Environment, FileSystemLoader, StrictUndefined, meta
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+CATALOG = tomllib.loads((REPO_ROOT / "blueprint.toml").read_text())
+
+OVERLAY = REPO_ROOT / CATALOG["blueprint"]["overlay"]
+
+CONTEXT_NAMES = {"project", "blueprint", "fastro", "features", "options", "services", "params", "has"}
+"""Spec 6.2, in full. A template reaching for anything else fails under `StrictUndefined`."""
+
+BUILT_IN_COMMANDS = {"add", "check", "eject", "features", "init", "make", "new", "remove", "sync", "update"}
+"""Fastro's own verbs. Anything else after `fastro` has to be a command the catalog declares."""
+
+A_FASTRO_COMMAND = re.compile(r"\bfastro ((?:[a-z][a-z0-9-]*)(?: [a-z][a-z0-9-]*)?)")
+
+A_CODE_SPAN = re.compile(r"`([^`\n]+)`|```[a-z]*\n(.*?)```", re.DOTALL)
+"""Only what is written as code is read as a command: prose says "generated by fastro from
+blueprint.toml", and `fastro from` is not a command anybody runs. Each span is read on its own,
+or two of them in one sentence would read as one command."""
+
+
+def _context(features: tuple[str, ...] = (), **options: str) -> dict[str, Any]:
+ """The spec 6.2 context, as the tool builds it for the overlay: no generator params."""
+ return {
+ "project": {"name": "Example App", "slug": "example-app"},
+ "blueprint": {"name": CATALOG["blueprint"]["name"], "version": CATALOG["blueprint"]["version"]},
+ "fastro": {"version": "0.1.0"},
+ "features": list(features),
+ "options": dict(options),
+ "services": [],
+ "params": {},
+ "has": lambda name: name in features,
+ }
+
+
+def _files() -> list[Path]:
+ return sorted(path for path in OVERLAY.rglob("*") if path.is_file())
+
+
+def _declared_commands() -> set[str]:
+ """Every command the catalog declares, the features' own included."""
+ words = set(CATALOG.get("commands", {}))
+ for feature in CATALOG["features"].values():
+ words.update(feature.get("commands", {}))
+
+ return words
+
+
+def _withheld(path: str) -> bool:
+ return any(
+ path == entry.rstrip("/") or (entry.endswith("/") and path.startswith(entry))
+ for entry in CATALOG["blueprint"]["blueprint_only"]
+ )
+
+
+def test_the_overlay_is_where_the_catalog_says():
+ assert OVERLAY.is_dir()
+ assert _files(), OVERLAY
+
+
+@pytest.mark.parametrize("path", [str(path.relative_to(OVERLAY)) for path in _files()])
+def test_no_overlay_file_lands_on_a_file_a_project_already_receives(path: str):
+ """Two files at one path, and nothing says which wins: the overlay's `.gitignore` is the
+ project's, so this repository's own is `blueprint_only` and never copied."""
+ landing = Path(path)
+ written = landing.with_suffix("") if landing.suffix == ".j2" else landing
+
+ assert not (REPO_ROOT / written).exists() or _withheld(written.as_posix()), written.as_posix()
+
+
+@pytest.mark.parametrize("path", [str(path.relative_to(OVERLAY)) for path in _files() if path.suffix == ".j2"])
+def test_every_template_reads_only_what_the_tool_passes(path: str):
+ """Spec 6.2: the context is fixed, so a template that asks for anything else renders nothing."""
+ environment = Environment(loader=FileSystemLoader(OVERLAY), undefined=StrictUndefined, keep_trailing_newline=True)
+ source = environment.loader.get_source(environment, path)[0]
+
+ assert meta.find_undeclared_variables(environment.parse(source)) <= CONTEXT_NAMES
+
+
+@pytest.mark.parametrize("path", [str(path.relative_to(OVERLAY)) for path in _files() if path.suffix == ".j2"])
+def test_every_template_renders_for_a_project_with_no_features(path: str):
+ """Core only is the harshest selection: every feature's lines have to be behind a condition."""
+ environment = Environment(loader=FileSystemLoader(OVERLAY), undefined=StrictUndefined, keep_trailing_newline=True)
+
+ assert environment.get_template(path).render(_context()).strip()
+
+
+@pytest.mark.parametrize("path", [str(path.relative_to(OVERLAY)) for path in _files()])
+def test_every_fastro_command_the_overlay_names_is_one_a_project_has(path: str):
+ """A project told to run a command its blueprint doesn't declare is a project that can't.
+
+ `fastro make ` is checked against `[generators]` too, which is why this file says
+ nothing about `make module` yet: that generator arrives with the module scaffold.
+ """
+ spans = [span or fenced for span, fenced in A_CODE_SPAN.findall((OVERLAY / path).read_text())]
+ declared = _declared_commands()
+
+ for named in (found for span in spans for found in A_FASTRO_COMMAND.findall(span)):
+ verb, _, rest = named.partition(" ")
+ if verb == "make" and rest:
+ assert rest in CATALOG["generators"], named
+ elif rest:
+ assert named in declared, named
+ else:
+ assert verb in BUILT_IN_COMMANDS or verb in declared, named
+
+
+def test_the_claude_file_points_at_the_agents_file():
+ """One file for both, so instructions never drift: Claude Code reads `@AGENTS.md` as an import."""
+ assert (OVERLAY / "CLAUDE.md").read_text().strip() == "@AGENTS.md"
+
+
+def test_the_agents_file_tells_an_agent_what_it_must_not_edit():
+ """The wiring is generated, and an agent editing it loses its work on the next sync."""
+ text = (OVERLAY / "AGENTS.md").read_text()
+
+ assert "src/wiring/" in text
+ assert "fastro sync" in text
+ assert "make module" not in text, "that generator does not exist yet"
From 513647a9c6c526b4a69f2c6012804b02bfb3541d Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Sat, 31 Oct 2026 02:33:42 -0300
Subject: [PATCH 29/71] give projects a readme that matches what they carry
---
blueprint/overlay/README.md.j2 | 109 ++++++++++++++++++++++++++++
blueprint/tests/test_overlay.py | 121 +++++++++++++++++++++++++++++---
2 files changed, 220 insertions(+), 10 deletions(-)
create mode 100644 blueprint/overlay/README.md.j2
diff --git a/blueprint/overlay/README.md.j2 b/blueprint/overlay/README.md.j2
new file mode 100644
index 00000000..7126c09a
--- /dev/null
+++ b/blueprint/overlay/README.md.j2
@@ -0,0 +1,109 @@
+# {{ project.name }}
+
+A FastAPI backend, generated from the {{ blueprint.name }} blueprint ({{ blueprint.version }}) by
+fastro {{ fastro.version }}.
+{% if features %}
+Selected: {{ features | join(", ") }}.
+{%- else %}
+Nothing optional is selected: this is the core, and `uvx fastro@{{ fastro.version }} add` brings
+a feature in.
+{%- endif %}
+
+Every command below runs from this directory: the ones in a subshell step into `backend/` and come
+back. `uvx fastro@{{ fastro.version }}` fetches the tool that generated the project, so a checkout
+needs nothing installed first.
+
+## Get it running
+
+```bash
+uv sync --all-extras --project backend
+cp backend/.env.example backend/.env
+uvx fastro@{{ fastro.version }} env secret # put the key it prints in backend/.env
+uvx fastro@{{ fastro.version }} make deploy local # writes the compose files
+docker compose up -d
+```
+
+That stack runs the API{% if has("taskiq") %}, the worker and the scheduler{% endif %} and the data stores it needs, with `backend/src` mounted so a change reloads. Outside production the app builds the schema from the models as it boots, so there is nothing to migrate yet: the API is on , and its docs on `/docs`.
+{%- if has("accounts") %}
+Create the first superuser from the `ADMIN_*` variables in `backend/.env`:
+
+```bash
+docker compose exec api python -m scripts.setup_initial_data
+```
+{%- endif %}
+{%- if has("admin") %}
+
+## The admin panel
+
+`backend/.env.example` turns it on, so a copied example has it at `/admin`. Set
+`ADMIN_ENABLED=false` where you don't want it, and give `ADMIN_USERNAME` and `ADMIN_PASSWORD`
+values of your own before anything but your laptop can reach it.
+{%- endif %}
+
+## Migrations
+
+When alembic should own the schema instead of the boot-time `create_all`, write the first revision
+from the models and start the database empty, because the one that booted already holds the whole
+schema and an upgrade against it fails on tables that exist:
+
+```bash
+uvx fastro@{{ fastro.version }} db baseline
+docker compose down -v
+```
+
+Set `CREATE_TABLES_ON_STARTUP=false` in `backend/.env`, then bring the stack back: a container
+reads that file as it starts, so an edit needs `up -d` again.
+
+```bash
+docker compose up -d
+docker compose exec api alembic upgrade head
+```
+
+`db baseline` starts a throwaway Postgres of its own, so it runs here rather than in the container,
+and leaves the revision in `backend/migrations/versions/` to commit. To keep what is already in the
+development database instead of dropping it, run `docker compose exec api alembic stamp head`: the
+schema is there, and stamping records it as applied.
+
+## Running the app on your machine
+
+The stack publishes Postgres{% if has("accounts") or has("cache") or has("taskiq") %} and Redis{% endif %} on localhost, so the app can run outside it. Point `POSTGRES_SERVER` and every `*_HOST` in `backend/.env` at `localhost`, then:
+
+```bash
+docker compose stop api{% if has("taskiq") %} worker scheduler{% endif %}
+docker compose up -d postgres{% if has("accounts") or has("cache") or has("taskiq") %} redis{% endif %}
+(cd backend && uv run --no-sync uvicorn src.interfaces.main:app --reload)
+```
+
+The first line frees the port the stack publishes; without it nothing can bind it.
+{%- if has("taskiq") %}
+
+The worker and the scheduler run the same way, against the broker `TASKIQ_BROKER_TYPE` names:
+
+```bash
+(cd backend && uv run --no-sync taskiq worker src.infrastructure.taskiq.worker:default_broker)
+(cd backend && uv run --no-sync taskiq scheduler src.infrastructure.taskiq.scheduler:scheduler)
+```
+{%- endif %}
+
+## Work on it
+
+```bash
+(cd backend && uv run --no-sync ruff check . && uv run --no-sync ruff format --check .)
+(cd backend && uv run --no-sync mypy src scripts migrations tests)
+(cd backend && uv run --no-sync pytest)
+```
+
+`AGENTS.md` says where code goes and what not to edit. From this directory,
+`uvx fastro@{{ fastro.version }} check` reads the project the way CI does, and
+`uvx fastro@{{ fastro.version }} sync --check` tells you whether `src/wiring/` matches
+`fastro.toml`.
+
+## Change what it carries
+
+```bash
+uvx fastro@{{ fastro.version }} features # what is selected, and what else there is
+uvx fastro@{{ fastro.version }} add
+uvx fastro@{{ fastro.version }} remove
+```
+
+Either one rewrites `src/wiring/`, the dependencies and `.env.example`, and says what it changed.
diff --git a/blueprint/tests/test_overlay.py b/blueprint/tests/test_overlay.py
index d6acbd52..506e3ed7 100644
--- a/blueprint/tests/test_overlay.py
+++ b/blueprint/tests/test_overlay.py
@@ -23,9 +23,15 @@
"""Spec 6.2, in full. A template reaching for anything else fails under `StrictUndefined`."""
BUILT_IN_COMMANDS = {"add", "check", "eject", "features", "init", "make", "new", "remove", "sync", "update"}
-"""Fastro's own verbs. Anything else after `fastro` has to be a command the catalog declares."""
+"""Fastro's own verbs, which take arguments of their own: `fastro add admin` names a feature, not
+a command. Anything else after `fastro` has to be a command the catalog declares, and
+`make ` has to name one it has."""
-A_FASTRO_COMMAND = re.compile(r"\bfastro ((?:[a-z][a-z0-9-]*)(?: [a-z][a-z0-9-]*)?)")
+A_FASTRO_COMMAND = re.compile(r"\bfastro(?:@(?:\{\{[^}]*\}\}|[^\s{]+))? ((?:[a-z][a-z0-9-]*)(?: [a-z][a-z0-9-]*)?)")
+"""A command, however it is run: `fastro sync`, or `uvx fastro@{{ fastro.version }} sync`, or
+`uvx fastro@0.1.0 sync`. Without the pin in the pattern every pinned command goes unread, and
+with a pin of `\S+` the template's own `{{ fastro.version }}` reads as one, leaving `fastro` as
+the command."""
A_CODE_SPAN = re.compile(r"`([^`\n]+)`|```[a-z]*\n(.*?)```", re.DOTALL)
"""Only what is written as code is read as a command: prose says "generated by fastro from
@@ -60,6 +66,26 @@ def _declared_commands() -> set[str]:
return words
+def _landing(path: Path) -> Path:
+ """Where an overlay file lands in a project: a `*.j2` is rendered and loses the suffix."""
+ relative = path.relative_to(OVERLAY)
+
+ return relative.with_suffix("") if relative.suffix == ".j2" else relative
+
+
+def _received() -> set[str]:
+ """Paths a project receives besides the overlay's: the repository's own files that aren't
+ withheld, and every `[[wiring]]` path, which the tool writes whether or not this repository
+ has the file yet."""
+ written = {entry["path"] for entry in CATALOG["wiring"]}
+
+ return written | {
+ path.relative_to(REPO_ROOT).as_posix()
+ for path in REPO_ROOT.rglob("*")
+ if path.is_file() and not _withheld(path.relative_to(REPO_ROOT).as_posix())
+ }
+
+
def _withheld(path: str) -> bool:
return any(
path == entry.rstrip("/") or (entry.endswith("/") and path.startswith(entry))
@@ -74,12 +100,20 @@ def test_the_overlay_is_where_the_catalog_says():
@pytest.mark.parametrize("path", [str(path.relative_to(OVERLAY)) for path in _files()])
def test_no_overlay_file_lands_on_a_file_a_project_already_receives(path: str):
- """Two files at one path, and nothing says which wins: the overlay's `.gitignore` is the
- project's, so this repository's own is `blueprint_only` and never copied."""
- landing = Path(path)
- written = landing.with_suffix("") if landing.suffix == ".j2" else landing
+ """Spec 1.27: two files at one path is refused, and a `[[wiring]]` path counts as taken even
+ where this repository has no file yet. The overlay's `.gitignore` is the project's, which is
+ why this repository's own is `blueprint_only`."""
+ landing = _landing(OVERLAY / path).as_posix()
+
+ assert landing not in _received(), landing
- assert not (REPO_ROOT / written).exists() or _withheld(written.as_posix()), written.as_posix()
+
+def test_no_two_overlay_files_land_on_one_path():
+ """Spec 1.27: `x` and `x.j2` in the overlay would both land on `x`, and nothing says which
+ of the two a project gets."""
+ landings = [_landing(path).as_posix() for path in _files()]
+
+ assert sorted(landings) == sorted(set(landings))
@pytest.mark.parametrize("path", [str(path.relative_to(OVERLAY)) for path in _files() if path.suffix == ".j2"])
@@ -113,10 +147,77 @@ def test_every_fastro_command_the_overlay_names_is_one_a_project_has(path: str):
verb, _, rest = named.partition(" ")
if verb == "make" and rest:
assert rest in CATALOG["generators"], named
- elif rest:
- assert named in declared, named
+ elif verb in BUILT_IN_COMMANDS:
+ continue
else:
- assert verb in BUILT_IN_COMMANDS or verb in declared, named
+ assert named in declared if rest else verb in declared, named
+
+
+README = "README.md.j2"
+
+FEATURE_LINES = {
+ "accounts": "setup_initial_data",
+ "admin": "/admin",
+ "taskiq": "taskiq worker",
+}
+"""What the README writes for a feature, and nothing else writes: a project without the feature
+must be told none of it."""
+
+
+def _rendered(path: str, features: tuple[str, ...]) -> str:
+ environment = Environment(loader=FileSystemLoader(OVERLAY), undefined=StrictUndefined, keep_trailing_newline=True)
+
+ return environment.get_template(path).render(_context(features))
+
+
+@pytest.mark.parametrize("features", [(), ("accounts",), tuple(CATALOG["features"])], ids=["core", "accounts", "all"])
+def test_the_readme_tells_a_project_only_what_it_carries(features: tuple[str, ...]):
+ """Each feature's lines appear exactly where the feature does. A README is the first thing a
+ reader follows, and a step for something the project hasn't got is a step that fails."""
+ rendered = _rendered(README, features)
+
+ for feature, line in FEATURE_LINES.items():
+ assert (line in rendered) == (feature in features), feature
+
+ for name in CATALOG["features"]:
+ if name not in features:
+ assert not re.search(rf"\b{name}\b", rendered), name
+
+
+def test_the_readme_says_what_a_project_with_no_features_is():
+ """Core only is a real answer, so the file says so rather than leaving the line empty."""
+ rendered = _rendered(README, ())
+
+ assert "Nothing optional is selected" in rendered
+ assert "Selected:" not in rendered
+
+
+def test_the_readme_names_the_features_a_project_selected():
+ rendered = _rendered(README, ("accounts", "admin"))
+
+ assert "Selected: accounts, admin." in rendered
+
+
+def test_every_fastro_command_in_the_readme_runs_the_tool_that_generated_the_project():
+ """`uvx fastro@` needs nothing installed first and pins the project to the tool it
+ was generated with, so a reader never gets a newer tool's behaviour by accident.
+
+ Only what a reader runs is checked: `fastro.toml` is a file and `fastro.version` is a context
+ value, not something to run.
+ """
+ spans = [span or fenced for span, fenced in A_CODE_SPAN.findall((OVERLAY / README).read_text())]
+ unpinned = []
+ for span in spans:
+ for found in re.finditer(r"fastro", span):
+ before, after = span[: found.start()], span[found.end() :]
+ if after.startswith((".toml", ".version")):
+ continue
+
+ if not (before.endswith("uvx ") and after.startswith("@{{ fastro.version }}")):
+ unpinned.append(span.strip()[:60])
+
+ assert unpinned == []
+ assert "uvx fastro@{{ fastro.version }}" in (OVERLAY / README).read_text()
def test_the_claude_file_points_at_the_agents_file():
From 0b25ea0290c2807a1a3d9ac331ad17d1e2ae706b Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Sat, 31 Oct 2026 02:49:06 -0300
Subject: [PATCH 30/71] give projects a CI workflow and pre-commit hooks that
check what they carry
---
blueprint/overlay/.github/workflows/ci.yml.j2 | 46 ++++++++++++
blueprint/overlay/.pre-commit-config.yaml.j2 | 46 ++++++++++++
blueprint/tests/test_overlay.py | 71 +++++++++++++++++--
3 files changed, 156 insertions(+), 7 deletions(-)
create mode 100644 blueprint/overlay/.github/workflows/ci.yml.j2
create mode 100644 blueprint/overlay/.pre-commit-config.yaml.j2
diff --git a/blueprint/overlay/.github/workflows/ci.yml.j2 b/blueprint/overlay/.github/workflows/ci.yml.j2
new file mode 100644
index 00000000..f4818f01
--- /dev/null
+++ b/blueprint/overlay/.github/workflows/ci.yml.j2
@@ -0,0 +1,46 @@
+name: CI
+
+on: [push, pull_request]
+
+permissions:
+ contents: read
+
+jobs:
+ check:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Install uv
+ uses: astral-sh/setup-uv@v5
+ with:
+ enable-cache: true
+ cache-dependency-glob: backend/uv.lock
+
+ - name: Set up Python
+ run: uv python install 3.11
+
+ - name: Install
+ run: uv sync --all-extras --locked --project backend --python 3.11
+
+ - name: Lint
+ working-directory: backend
+ run: |
+ uv run --no-sync ruff check .
+ uv run --no-sync ruff format --check .
+
+ - name: Types
+ working-directory: backend
+ run: uv run --no-sync mypy src scripts migrations tests
+
+ - name: Tests
+ working-directory: backend
+ run: uv run --no-sync pytest
+ env:
+ ENVIRONMENT: local
+ SECRET_KEY: a-secret-key-this-run-only-with-32-bytes
+
+ - name: The project matches what it declares
+ run: |
+ uvx fastro@{{ fastro.version }} sync --check
+ uvx fastro@{{ fastro.version }} check
diff --git a/blueprint/overlay/.pre-commit-config.yaml.j2 b/blueprint/overlay/.pre-commit-config.yaml.j2
new file mode 100644
index 00000000..9cc54f0d
--- /dev/null
+++ b/blueprint/overlay/.pre-commit-config.yaml.j2
@@ -0,0 +1,46 @@
+default_language_version:
+ python: python3.11
+
+repos:
+ - repo: https://github.com/pre-commit/pre-commit-hooks
+ rev: v6.0.0
+ hooks:
+ - id: end-of-file-fixer
+ - id: trailing-whitespace
+ - id: check-yaml
+ - id: check-case-conflict
+ - id: check-merge-conflict
+ - id: check-added-large-files
+ args: ["--maxkb=750", "--enforce-all"]
+ - id: detect-private-key
+
+ - repo: https://github.com/asottile/pyupgrade
+ rev: v3.20.0
+ hooks:
+ - id: pyupgrade
+ args: [--py311-plus]
+ name: Upgrade code to Python 3.11+
+
+ - repo: https://github.com/astral-sh/ruff-pre-commit
+ rev: v0.15.12
+ hooks:
+ - id: ruff-check
+ args: [--fix]
+ - id: ruff-format
+
+ - repo: local
+ hooks:
+ - id: mypy
+ name: Mypy
+ language: system
+ entry: bash -c 'cd backend && uv run --no-sync mypy src scripts migrations tests --config-file pyproject.toml'
+ pass_filenames: false
+ files: ^backend/(src|scripts|migrations|tests)/
+ types: [python]
+
+ - id: wiring
+ name: The wiring matches fastro.toml
+ language: system
+ entry: uvx fastro@{{ fastro.version }} sync --check
+ pass_filenames: false
+ files: ^(fastro\.toml|backend/src/wiring/)
diff --git a/blueprint/tests/test_overlay.py b/blueprint/tests/test_overlay.py
index 506e3ed7..eca3656b 100644
--- a/blueprint/tests/test_overlay.py
+++ b/blueprint/tests/test_overlay.py
@@ -11,6 +11,7 @@
from typing import Any
import pytest
+import yaml
from jinja2 import Environment, FileSystemLoader, StrictUndefined, meta
REPO_ROOT = Path(__file__).resolve().parents[2]
@@ -30,7 +31,7 @@
A_FASTRO_COMMAND = re.compile(r"\bfastro(?:@(?:\{\{[^}]*\}\}|[^\s{]+))? ((?:[a-z][a-z0-9-]*)(?: [a-z][a-z0-9-]*)?)")
"""A command, however it is run: `fastro sync`, or `uvx fastro@{{ fastro.version }} sync`, or
`uvx fastro@0.1.0 sync`. Without the pin in the pattern every pinned command goes unread, and
-with a pin of `\S+` the template's own `{{ fastro.version }}` reads as one, leaving `fastro` as
+with a pin that takes any non-space text, the template's own `{{ fastro.version }}` reads as one, leaving `fastro` as
the command."""
A_CODE_SPAN = re.compile(r"`([^`\n]+)`|```[a-z]*\n(.*?)```", re.DOTALL)
@@ -198,26 +199,82 @@ def test_the_readme_names_the_features_a_project_selected():
assert "Selected: accounts, admin." in rendered
-def test_every_fastro_command_in_the_readme_runs_the_tool_that_generated_the_project():
+@pytest.mark.parametrize("path", [str(path.relative_to(OVERLAY)) for path in _files() if path.suffix == ".j2"])
+def test_every_fastro_command_a_template_writes_runs_the_tool_that_generated_the_project(path: str):
"""`uvx fastro@` needs nothing installed first and pins the project to the tool it
was generated with, so a reader never gets a newer tool's behaviour by accident.
- Only what a reader runs is checked: `fastro.toml` is a file and `fastro.version` is a context
- value, not something to run.
+ Templates only: `AGENTS.md` is written by hand and has no version to interpolate. In Markdown
+ the commands are what is written as code; anywhere else every line is run, so the whole file
+ counts. `fastro.toml` is a file and `fastro.version` a context value, so neither is read as a
+ command, however a pattern escapes the dot.
"""
- spans = [span or fenced for span, fenced in A_CODE_SPAN.findall((OVERLAY / README).read_text())]
+ text = (OVERLAY / path).read_text()
+ spans = (
+ [span or fenced for span, fenced in A_CODE_SPAN.findall(text)] if _landing(OVERLAY / path).suffix == ".md" else [text]
+ )
unpinned = []
for span in spans:
for found in re.finditer(r"fastro", span):
before, after = span[: found.start()], span[found.end() :]
- if after.startswith((".toml", ".version")):
+ if after.removeprefix("\\").startswith((".toml", ".version")):
continue
if not (before.endswith("uvx ") and after.startswith("@{{ fastro.version }}")):
unpinned.append(span.strip()[:60])
assert unpinned == []
- assert "uvx fastro@{{ fastro.version }}" in (OVERLAY / README).read_text()
+
+
+WORKFLOW = ".github/workflows/ci.yml.j2"
+
+PRE_COMMIT = ".pre-commit-config.yaml.j2"
+
+BEFORE_FINISHING = ("ruff check .", "ruff format --check .", "mypy src scripts migrations tests", "pytest")
+"""What an agent is told to run before finishing, which is what CI runs: one list, two files."""
+
+
+@pytest.mark.parametrize("path", [WORKFLOW, PRE_COMMIT])
+def test_the_yaml_a_project_receives_parses(path: str):
+ """Rendered for the harshest selection, since a conditional that empties a list or leaves a
+ dangling key is only visible once it is parsed."""
+ assert yaml.safe_load(_rendered(path, ()))
+
+
+def test_the_workflow_runs_what_the_agent_file_tells_an_agent_to_run():
+ """An agent whose checks are looser than CI's finishes work that CI then rejects."""
+ agents = (OVERLAY / "AGENTS.md").read_text()
+ workflow = _rendered(WORKFLOW, ())
+
+ for command in BEFORE_FINISHING:
+ assert command in agents, command
+ assert command in workflow, command
+
+
+def test_the_workflow_installs_the_project_rather_than_this_workspace():
+ """A project has one `pyproject.toml`, under the python root: `--all-packages` and a root
+ lock are this repository's own shape, and neither is there."""
+ workflow = yaml.safe_load(_rendered(WORKFLOW, ()))
+ steps = workflow["jobs"]["check"]["steps"]
+ installing = next(step for step in steps if step.get("name") == "Install")
+
+ assert "--project backend" in installing["run"]
+ assert "--all-packages" not in installing["run"]
+ assert (
+ "backend/uv.lock" in next(step for step in steps if step.get("name") == "Install uv")["with"]["cache-dependency-glob"]
+ )
+
+
+def test_every_pre_commit_hook_watches_paths_a_project_has():
+ """A `files:` pattern naming `cli/` or `tools/` is a hook over nothing: those are the
+ blueprint's own, and no project receives them."""
+ hooks = yaml.safe_load(_rendered(PRE_COMMIT, ()))
+ watched = [hook["files"] for repo in hooks["repos"] for hook in repo["hooks"] if "files" in hook]
+
+ assert watched
+ for pattern in watched:
+ head = re.split(r"[(\[{|?*+\\]", pattern.removeprefix("^"))[0].rstrip("/")
+ assert head in {"backend", "fastro.toml", "fastro\\.toml", ""} or not _withheld(head), pattern
def test_the_claude_file_points_at_the_agents_file():
From b6ab6f90f398f9e975da5c3f04633e703c131078 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Sat, 31 Oct 2026 03:02:05 -0300
Subject: [PATCH 31/71] ship the admin panel switched off in the environment
example
---
backend/.env.example | 5 ++-
backend/tests/unit/test_blueprint_catalog.py | 41 ++++++++++++++++++++
blueprint/overlay/README.md.j2 | 6 +--
blueprint/tests/test_overlay.py | 11 ++++++
docs/changelog.md | 4 ++
docs/getting-started/index.md | 2 +-
docs/getting-started/installation.md | 3 +-
docs/user-guide/admin-panel/configuration.md | 7 ++--
8 files changed, 69 insertions(+), 10 deletions(-)
diff --git a/backend/.env.example b/backend/.env.example
index 9d28355d..2263cf62 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -286,8 +286,9 @@ PASSWORD_REQUIRE_SPECIAL=true
# Admin Interface (SQLAdmin)
# ===================================
# @fastro if=admin
-# Enable/disable the admin interface
-ADMIN_ENABLED=true
+# The panel is off until a project asks for it. Set this to true, with credentials of your
+# own below, to serve it.
+ADMIN_ENABLED=false
# Where the panel is mounted; the admin session cookie is scoped to this path
ADMIN_BASE_URL=/admin
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index b2b19dad..5c1dbd9c 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -1498,6 +1498,47 @@ def test_no_marker_sits_anywhere_but_under_a_header():
assert all(_true(marker.removeprefix("# @fastro if="), set(_catalog()["features"])) for marker in marked)
+ADMIN_GUIDE = REPO_ROOT / "docs" / "user-guide" / "admin-panel" / "configuration.md"
+
+QUOTED_EXAMPLE = "The default `.env.example`"
+"""Where that guide quotes the example, which is the one place the docs reproduce its values."""
+
+
+def test_the_guide_quotes_the_example_as_it_ships():
+ """A quoted value that drifts from the file is a reader setting up a panel that stays dark, or
+ serving one they thought was off: the example keeps the admin panel off, as the setting's own
+ default has since 0.20.0."""
+ guide = ADMIN_GUIDE.read_text()
+ quoted = guide[guide.index(QUOTED_EXAMPLE) :].split("```")[1].removeprefix("env\n")
+ shipped = dict(line.split("=", 1) for line in ENV_EXAMPLE.read_text().splitlines() if re.match(r"^[A-Z][A-Z0-9_]*=", line))
+
+ assert "ADMIN_ENABLED=false" in quoted, "the example ships the panel off"
+ for line in quoted.splitlines():
+ name, _, value = line.partition("=")
+ assert shipped[name] == value, name
+
+
+FIRST_RUN = REPO_ROOT / "docs" / "getting-started"
+
+NEARBY_LINES = 2
+"""How far from a mention of the panel the flag may be and still be read as part of the same claim."""
+
+
+@pytest.mark.parametrize("page", sorted(path.name for path in FIRST_RUN.glob("*.md")))
+def test_no_first_run_page_offers_the_admin_panel_without_saying_what_turns_it_on(page: str):
+ """A new reader follows these pages in order, and `/admin` answers 404 until the flag is set
+ and both credentials are there. A page that lists it among the things that now work sends
+ that reader to look for a bug of their own."""
+ lines = (FIRST_RUN / page).read_text().splitlines()
+ unexplained = [
+ line
+ for index, line in enumerate(lines)
+ if "/admin" in line and "ADMIN_ENABLED" not in "\n".join(lines[max(0, index - NEARBY_LINES) : index + NEARBY_LINES + 1])
+ ]
+
+ assert unexplained == []
+
+
def test_the_example_is_read_the_way_it_is_written():
"""The reading itself: a parse that found no sections, or missed the commented-out lines,
would leave the rule above with nothing to object to."""
diff --git a/blueprint/overlay/README.md.j2 b/blueprint/overlay/README.md.j2
index 7126c09a..6660d50e 100644
--- a/blueprint/overlay/README.md.j2
+++ b/blueprint/overlay/README.md.j2
@@ -35,9 +35,9 @@ docker compose exec api python -m scripts.setup_initial_data
## The admin panel
-`backend/.env.example` turns it on, so a copied example has it at `/admin`. Set
-`ADMIN_ENABLED=false` where you don't want it, and give `ADMIN_USERNAME` and `ADMIN_PASSWORD`
-values of your own before anything but your laptop can reach it.
+It ships switched off. Set `ADMIN_ENABLED=true` in `backend/.env`, with `ADMIN_USERNAME` and
+`ADMIN_PASSWORD` values of your own, and it is served at `/admin`. Without both credentials it
+stays unmounted, whatever the flag says.
{%- endif %}
## Migrations
diff --git a/blueprint/tests/test_overlay.py b/blueprint/tests/test_overlay.py
index eca3656b..800d1fcd 100644
--- a/blueprint/tests/test_overlay.py
+++ b/blueprint/tests/test_overlay.py
@@ -185,6 +185,17 @@ def test_the_readme_tells_a_project_only_what_it_carries(features: tuple[str, ..
assert not re.search(rf"\b{name}\b", rendered), name
+def test_the_readme_describes_the_admin_panel_the_example_ships():
+ """The README and `.env.example` go to the same project, so one can't say the panel is off
+ while the other turns it on."""
+ example = (REPO_ROOT / CATALOG["blueprint"]["python_root"] / ".env.example").read_text()
+ rendered = _rendered(README, ("accounts", "admin"))
+ shipped_off = "\nADMIN_ENABLED=false\n" in example
+
+ assert ("ships switched off" in rendered) == shipped_off
+ assert ("Set `ADMIN_ENABLED=true`" in rendered) == shipped_off
+
+
def test_the_readme_says_what_a_project_with_no_features_is():
"""Core only is a real answer, so the file says so rather than leaving the line empty."""
rendered = _rendered(README, ())
diff --git a/docs/changelog.md b/docs/changelog.md
index 29d25861..8684fe1b 100644
--- a/docs/changelog.md
+++ b/docs/changelog.md
@@ -25,6 +25,10 @@ ___
`aiosqlite` answered `SQLITE_ASYNC_PREFIX`, which no module reads, and the admin panel gets
`jinja2` through `sqladmin`, which requires it. `jinja2` stays in the `dev` extra for the
template tests. A project of your own that imported either has to declare it.
+- **`.env.example` ships `ADMIN_ENABLED=false`.** The setting has defaulted to `false` since
+ 0.20.0, but the example still turned the panel on, so a copied example served `/admin` with the
+ example's own `admin` credentials. Set `ADMIN_ENABLED=true`, with credentials of your own, where
+ you want it.
___
diff --git a/docs/getting-started/index.md b/docs/getting-started/index.md
index 97d17c84..f0927758 100644
--- a/docs/getting-started/index.md
+++ b/docs/getting-started/index.md
@@ -113,7 +113,7 @@ You now have a working FastAPI app with:
- Redis-backed cache and rate limiting
- Session-based authentication with optional OAuth (Google, GitHub)
- API keys with per-key permissions
-- SQLAdmin admin interface at `/admin`
+- SQLAdmin admin interface at `/admin`, off until you set `ADMIN_ENABLED=true`
- Async background task support via Taskiq
## Test Your API
diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md
index ff632704..7c13a09b 100644
--- a/docs/getting-started/installation.md
+++ b/docs/getting-started/installation.md
@@ -276,7 +276,8 @@ After installing, verify everything works:
1. **API Docs**:
2. **Health Check**: `curl http://localhost:8000/health`
-3. **Admin Panel**:
+3. **Admin Panel**: , once `ADMIN_ENABLED=true` and both admin
+ credentials are set in `backend/.env`; it is off in the example, and unmounted until then
4. **Database**: check the app log for "Database connected" / no errors at startup
## Troubleshooting
diff --git a/docs/user-guide/admin-panel/configuration.md b/docs/user-guide/admin-panel/configuration.md
index d5d7466d..48e76706 100644
--- a/docs/user-guide/admin-panel/configuration.md
+++ b/docs/user-guide/admin-panel/configuration.md
@@ -222,17 +222,18 @@ For production behind HTTPS, you'll typically want to:
### Development
-The default `.env.example` is already development-ready:
+The default `.env.example` leaves the panel off:
```env
ENVIRONMENT=development
-ADMIN_ENABLED=true
+ADMIN_ENABLED=false
ADMIN_USERNAME=admin
ADMIN_PASSWORD=Change-Me-Now-1!
SECRET_KEY=insecure-secret-key-change-this-in-production
```
-Open , log in, and you have access to Users and Tiers.
+Set `ADMIN_ENABLED=true` in your `.env`, restart, then open , log in,
+and you have access to Users and Tiers.
### Production Hardening
From d7c218d188a2537f6884b6319bd2aa2c2b901441 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Wed, 4 Nov 2026 17:05:23 -0300
Subject: [PATCH 32/71] name the app blueprint verify imports, and the test
environment its checks run with, which holds no secrets
---
backend/tests/unit/test_blueprint_catalog.py | 39 ++++++++++++++++++++
blueprint.toml | 9 +++++
2 files changed, 48 insertions(+)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 5c1dbd9c..4d0872a3 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -870,6 +870,42 @@ def test_every_selection_keeps_the_files_the_drill_keeps():
assert _kept_by_the_catalog(features, chosen) == _kept_by_the_drill(manifest, chosen), sorted(chosen)
+TOOLCHAIN_ONLY = {"PATH", "PYTHONPATH", "HOME"}
+"""What the drill's environment holds beyond the settings: paths, not configuration."""
+
+
+def test_the_app_the_verification_imports_is_this_project_s_own():
+ """Spec 2.2: a dotted module whose first part is `import_root`, and whose file this repository
+ has. Without it `blueprint verify` skips the app-import check, which is the one that catches a
+ feature removal that left something importing what went."""
+ blueprint = _catalog()["blueprint"]
+ module = _catalog()["verify"]["app"]
+ path = REPO_ROOT / blueprint["python_root"] / Path(*module.split(".")).with_suffix(".py")
+
+ assert module.split(".")[0] == blueprint["import_root"]
+ assert path.is_file(), module
+ assert _defines(module, "app"), "the check imports the module for its app"
+
+
+def test_the_toolchain_environment_is_what_the_app_needs_to_import():
+ """Spec 2.12: names and string values only. These are the settings the drill sets itself
+ before it imports anything, and they are test values for checking a project rather than
+ secrets: a memory session store, a memory limiter, the local environment, and a key that
+ exists only so the settings validate.
+ """
+ declared = _catalog()["checks"]["toolchain"]["env"]
+ source = inspect.getsource(_drill().check)
+ set_by_the_drill = set(re.findall(r'^\s+"([A-Z][A-Z0-9_]*)":', source, re.M)) - TOOLCHAIN_ONLY
+
+ assert set(declared) == set_by_the_drill
+ for name, value in declared.items():
+ assert ENV_VAR.match(name), name
+ assert isinstance(value, str), name
+
+ assert len(declared["SECRET_KEY"]) >= 32, "the settings refuse a shorter one"
+ assert declared["SECRET_KEY"] not in ENV_EXAMPLE.read_text(), "not the example's placeholder"
+
+
POINTS: dict[str, tuple[str, str]] = {
"routers": ("_wiring_app", "ROUTER_MOUNTS"),
"root_routers": ("_wiring_app", "ROOT_ROUTERS"),
@@ -1915,6 +1951,9 @@ def test_a_collection_of_more_than_one_is_written_one_entry_to_a_line(path: str,
COMMAND_WORD = re.compile(r"^[a-z][a-z0-9-]*$")
+ENV_VAR = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+"""Spec 2.5 and 2.12: the name of an environment variable."""
+
PARAM_TYPES = {"int", "str", "bool", "cidr", "choice"}
PYTHON_TYPES: dict[str, type] = {"int": int, "str": str, "bool": bool, "cidr": str, "choice": str}
diff --git a/blueprint.toml b/blueprint.toml
index 8017ce00..e288ab91 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -67,6 +67,9 @@ minimal = ["accounts"]
standard = ["accounts", "rbac", "ratelimit", "tiers", "tier_limits", "admin", "cache"]
full = ["accounts", "rbac", "ratelimit", "tiers", "tier_limits", "api_keys", "admin", "cache", "taskiq"]
+[verify]
+app = "src.interfaces.main"
+
[verify.sets]
core-only = []
core-taskiq = ["taskiq"]
@@ -468,6 +471,12 @@ contributes.email_sender = ["src.infrastructure.taskiq.email:queued_sender"]
contributes.task_modules = [{ value = "src.infrastructure.taskiq.email", order = 10 }]
+[checks.toolchain.env]
+ENVIRONMENT = "local"
+SECRET_KEY = "a-key-only-the-toolchain-checks-run-with"
+SESSION_BACKEND = "memory"
+RATE_LIMITER_BACKEND = "memory"
+
[wiring_defaults]
line_length = 128
header = """Generated by fastro from blueprint.toml and fastro.toml. Don't edit: change
From 00661ee9dccfab19b775c0c9b26cf0ef894a030e Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Mon, 16 Nov 2026 18:20:16 -0300
Subject: [PATCH 33/71] pin fastro at the repository root, and run its sync
check in pre-commit and its sync check and blueprint lint in ci
---
.github/workflows/linting.yml | 6 +
.pre-commit-config.yaml | 7 +
backend/tests/unit/test_blueprint_catalog.py | 238 ++++++++++++++++++-
pyproject.toml | 6 +
uv.lock | 22 +-
5 files changed, 271 insertions(+), 8 deletions(-)
diff --git a/.github/workflows/linting.yml b/.github/workflows/linting.yml
index 1291d93a..e652ba18 100644
--- a/.github/workflows/linting.yml
+++ b/.github/workflows/linting.yml
@@ -32,3 +32,9 @@ jobs:
- name: Ruff format
run: uv run --no-sync ruff format --check backend/src backend/tests backend/scripts backend/migrations cli/src cli/tests tools blueprint/tests
+
+ - name: Wiring in sync
+ run: uv run --no-sync fastro sync --check
+
+ - name: Blueprint lint
+ run: uv run --no-sync fastro blueprint lint
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index e292631c..db8dee68 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -54,6 +54,13 @@ repos:
files: ^cli/src/
types: [python]
+ - id: fastro_sync_check
+ name: Wiring in sync (fastro)
+ language: system
+ entry: uv run --no-sync fastro sync --check
+ pass_filenames: false
+ files: ^(blueprint\.toml|fastro\.toml|backend/src/wiring/.*|backend/scripts/seeders\.py|backend/tests/wiring\.py)$
+
- id: unit_test
name: Unit test
language: system
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 4d0872a3..bf5d5947 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -1,8 +1,9 @@
"""The catalog describes this repository, and `tools/removal_drill.py` is what it describes.
-`blueprint.toml` is read by fastro, which isn't a dependency here yet, so nothing in this
-file imports it: the rules it checks are transcribed from the catalog spec, and the facts it
-checks against come from the drill, which is the repository's own account of its features.
+`blueprint.toml` is read by fastro, which the repository root installs and the backend doesn't,
+so nothing in this file imports it: the rules it checks are transcribed from the catalog spec,
+and the facts it checks against come from the drill, which is the repository's own account of
+its features.
This file goes when `fastro blueprint lint` and `fastro blueprint verify` replace the drill.
"""
@@ -31,7 +32,7 @@
BACKEND_PYPROJECT = REPO_ROOT / "backend" / "pyproject.toml"
FEATURE_NAME = re.compile(r"^[a-z][a-z0-9_]*$")
-"""Spec 1.2. Written out rather than imported, because fastro is not a dependency yet."""
+"""Spec 1.2. Written out rather than imported, because the backend's tests don't import fastro."""
BLUEPRINT_NAME = re.compile(r"^[a-z][a-z0-9-]*$")
@@ -457,11 +458,81 @@ def _workspace_members() -> list[str]:
return list(tomllib.load(handle)["tool"]["uv"]["workspace"]["members"])
+def _unwrapped(pattern: str) -> str:
+ """A pattern without the one group that wraps all of it, if there is one."""
+ depth = 0
+ for index, character in enumerate(pattern):
+ depth += {"(": 1, ")": -1}.get(character, 0)
+ if depth == 0:
+ return pattern[1:-1] if pattern.startswith("(") and index == len(pattern) - 1 else pattern
+
+ return pattern
+
+
+def _alternatives(pattern: str) -> list[str]:
+ """The top-level alternatives of an anchored pattern, outside a group that wraps it whole."""
+ body = _unwrapped(pattern.removeprefix("^").removesuffix("$"))
+
+ parts, depth, start = [], 0, 0
+ for index, character in enumerate(body):
+ depth += {"(": 1, "[": 1, ")": -1, "]": -1}.get(character, 0)
+ if character == "|" and depth == 0:
+ parts.append(body[start:index])
+ start = index + 1
+
+ return [*parts, body[start:]]
+
+
+def _literal_head(pattern: str) -> str:
+ """The characters a pattern matches literally before its first special one, unescaped."""
+ head = re.match(r"(?:[^\\()\[\]{}|?*+.^$]|\\[./-])*", pattern)
+ assert head is not None
+
+ return re.sub(r"\\(.)", r"\1", head.group())
+
+
+def _pattern_heads(pattern: str) -> list[str]:
+ """The path each alternative of a pre-commit `files:` pattern starts with, through nested ones."""
+ alternatives = _alternatives(pattern)
+ if len(alternatives) > 1:
+ return [head for alternative in alternatives for head in _pattern_heads(alternative)]
+
+ return [_literal_head(alternatives[0]).rstrip("/")]
+
+
+def _named_paths(patterns: list[str]) -> list[str]:
+ """The paths the patterns name, refusing one whose head is empty: it would name nothing to check."""
+ heads = [head for pattern in patterns for head in _pattern_heads(pattern)]
+ assert all(heads), patterns
+
+ return heads
+
+
def _hook_paths() -> list[str]:
- """The literal head of each pre-commit `files:` pattern, which is a path in the repository."""
- patterns = re.findall(r"^\s*files: (\S+)$", (REPO_ROOT / ".pre-commit-config.yaml").read_text(), re.M)
+ """The paths the pre-commit `files:` patterns name, one per alternative."""
+ return _named_paths(re.findall(r"^\s*files: (\S+)$", (REPO_ROOT / ".pre-commit-config.yaml").read_text(), re.M))
+
+
+@pytest.mark.parametrize(
+ ("pattern", "heads"),
+ [
+ ("^cli/src/", ["cli/src"]),
+ ("^backend/(src|scripts|migrations|tests)/", ["backend"]),
+ (r"^(blueprint\.toml|fastro\.toml|backend/src/wiring/)", ["blueprint.toml", "fastro.toml", "backend/src/wiring"]),
+ (r"^(a\.py)|(b/)$", ["a.py", "b"]),
+ (r"^(a|(b\.py|c/))$", ["a", "b.py", "c"]),
+ (r"^(a|b)/x", [""]),
+ ],
+)
+def test_the_hook_reader_sees_every_path_a_pattern_names(pattern: str, heads: list[str]):
+ """An alternation names one path per branch, and an escaped dot is part of the name."""
+ assert _pattern_heads(pattern) == heads
+
- return [re.split(r"[(\[{|?*+.\\]", pattern.removeprefix("^"))[0].rstrip("/") for pattern in patterns]
+def test_the_hook_reader_refuses_a_pattern_that_names_no_path():
+ """A head of `""` is never withheld, so the rules that read it would pass over nothing."""
+ with pytest.raises(AssertionError):
+ _named_paths([r"^(a|b)/x"])
def _readme_references() -> list[str]:
@@ -513,6 +584,159 @@ def test_each_file_still_names_the_path_that_keeps_it_out(path: str):
assert any(target.startswith(WITHHELD_POINTERS[path]) for target in pointed), pointed
+ROOT_PYPROJECT = REPO_ROOT / "pyproject.toml"
+FASTRO_REPOSITORY = "https://github.com/benavlabs/fastro"
+COMMIT = re.compile(r"^[0-9a-f]{40}$")
+
+
+def _root_project() -> dict[str, Any]:
+ with ROOT_PYPROJECT.open("rb") as handle:
+ return tomllib.load(handle)
+
+
+def test_the_repository_root_installs_fastro_for_its_own_checks():
+ """fastro checks the blueprint, so the root project, which no project receives, carries it."""
+ assert _withheld("pyproject.toml")
+ assert "fastro" in {_distribution(specifier) for specifier in _root_project()["dependency-groups"]["dev"]}
+
+
+def test_fastro_is_pinned_to_one_commit_of_its_repository():
+ """Unreleased, so a commit is the only version a lock can hold steady."""
+ source = _root_project()["tool"]["uv"]["sources"]["fastro"]
+
+ assert source.keys() == {"git", "rev"}
+ assert source["git"] == FASTRO_REPOSITORY
+ assert COMMIT.match(source["rev"]), source["rev"]
+
+
+def test_no_project_receives_the_fastro_pin():
+ """A project gets `backend/pyproject.toml`, and its own checks run fastro through `uvx`."""
+ with BACKEND_PYPROJECT.open("rb") as handle:
+ backend = tomllib.load(handle)
+
+ groups = [
+ backend["project"].get("dependencies", []),
+ *backend["project"].get("optional-dependencies", {}).values(),
+ *backend.get("dependency-groups", {}).values(),
+ ]
+
+ assert "fastro" not in {_distribution(specifier) for group in groups for specifier in group}
+ assert "fastro" not in backend.get("tool", {}).get("uv", {}).get("sources", {})
+
+
+def _pre_commit_hooks() -> list[dict[str, str]]:
+ """Each hook's keys, read from its `- id:` block, with the value written on the key's own line."""
+ blocks = re.findall(r"^( *)- id: (\S+)\n((?:\1 +[\w-]+:.*\n)*)", (REPO_ROOT / ".pre-commit-config.yaml").read_text(), re.M)
+
+ return [{"id": hook, **dict(re.findall(r"^ +([\w-]+):[ ]*(.*)$", keys, re.M))} for _, hook, keys in blocks]
+
+
+def _the_sync_check_hook() -> dict[str, str]:
+ hooks = [hook for hook in _pre_commit_hooks() if "fastro sync --check" in hook.get("entry", "")]
+ assert len(hooks) == 1, hooks
+
+ return hooks[0]
+
+
+def test_a_commit_runs_sync_check_on_the_whole_tree():
+ """`sync --check` compares every wiring file, so the hook hands it no file names."""
+ hook = _the_sync_check_hook()
+
+ assert hook["entry"] == "uv run --no-sync fastro sync --check"
+ assert hook["language"] == "system"
+ assert hook["pass_filenames"] == "false"
+
+
+def test_the_sync_check_hook_runs_at_every_commit():
+ """Any key beyond these narrows when it runs: a stage, an exclusion, a file type."""
+ assert _the_sync_check_hook().keys() == {"id", "name", "language", "entry", "pass_filenames", "files"}
+
+
+@pytest.mark.parametrize("path", ["blueprint.toml", "fastro.toml", *(entry["path"] for entry in _catalog()["wiring"])])
+def test_a_commit_that_touches_what_sync_compares_runs_sync_check(path: str):
+ """The catalog, the selection and every file it generates, so a new wiring file can't slip by."""
+ assert re.search(_the_sync_check_hook()["files"], path), path
+
+
+def test_a_commit_that_touches_nothing_sync_compares_skips_sync_check():
+ for path in (
+ "backend/src/modules/user/models.py",
+ "docs/backend/src/wiring/app.md",
+ "backend/fastro.toml",
+ "blueprint.toml.orig",
+ ):
+ assert not re.search(_the_sync_check_hook()["files"], path), path
+
+
+def _workflow_runs() -> list[str]:
+ """Every one-line `run:` in the repository's own CI."""
+ return [
+ run.strip()
+ for workflow in sorted((REPO_ROOT / ".github" / "workflows").glob("*.yml"))
+ for run in re.findall(r"^\s+run: (.+)$", workflow.read_text(), re.M)
+ ]
+
+
+def _defaults_blocks(workflow: str) -> list[str]:
+ """Each `defaults:` block of a workflow, at any level, with its value written on the same line or below it."""
+ lines = workflow.splitlines()
+ blocks = []
+ for index, line in enumerate(lines):
+ found = re.match(r"^( *)defaults:(.*)$", line)
+ if found is None:
+ continue
+
+ block = [found.group(2)]
+ for following in lines[index + 1 :]:
+ if following.strip() and len(following) - len(following.lstrip()) <= len(found.group(1)):
+ break
+ block.append(following)
+ blocks.append("\n".join(block))
+
+ return blocks
+
+
+@pytest.mark.parametrize(
+ "workflow",
+ [
+ "defaults:\n run:\n working-directory: backend\njobs:\n",
+ "jobs:\n lint:\n defaults:\n run:\n shell: bash\n working-directory: backend\n steps:\n",
+ "jobs:\n lint:\n defaults: {run: {working-directory: backend}}\n",
+ ],
+)
+def test_the_defaults_reader_sees_a_working_directory_however_it_is_written(workflow: str):
+ assert any("working-directory" in block for block in _defaults_blocks(workflow))
+
+
+def test_the_defaults_reader_stops_at_the_end_of_its_block():
+ workflow = "defaults:\n run:\n shell: bash\njobs:\n lint:\n steps:\n - working-directory: backend\n"
+
+ assert not any("working-directory" in block for block in _defaults_blocks(workflow))
+
+
+SYNC_THAT_KEEPS_THE_DEV_GROUP = {"uv", "sync", "--all-packages", "--all-extras", "--locked", "--python", "3.11"}
+"""The words a sync may use and still install the root dev group, where fastro is."""
+
+
+@pytest.mark.parametrize("command", ["fastro sync --check", "fastro blueprint lint"])
+def test_ci_runs_fastros_checks_where_fastro_is_installed(command: str):
+ """From the repository root, the project that declares fastro, never after a `cd`, and always gating the job."""
+ assert [run for run in _workflow_runs() if command in run] == [f"uv run --no-sync {command}"]
+
+ for workflow in sorted((REPO_ROOT / ".github" / "workflows").glob("*.yml")):
+ text = workflow.read_text()
+ steps = [step for step in re.split(r"\n(?= +- )", text) if command in step]
+ if steps:
+ assert not any("working-directory" in block for block in _defaults_blocks(text)), workflow.name
+ for step in steps:
+ assert set(re.findall(r"^\s*(?:- )?([\w-]+):", step, re.M)) == {"name", "run"}, step
+
+ syncs = re.findall(r"^\s+run: (uv sync\b.*)$", text, re.M)
+ assert syncs, workflow.name
+ for sync in syncs:
+ assert set(sync.split()) <= SYNC_THAT_KEEPS_THE_DEV_GROUP, sync
+
+
def _literals(module: Path) -> set[str]:
"""Every string literal in a module, less the docstrings, which talk about files rather than
reach for them."""
diff --git a/pyproject.toml b/pyproject.toml
index 542c7d72..88cfe6a8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -26,9 +26,15 @@ version = "0"
description = "Workspace root — see backend/ and cli/ for actual packages."
requires-python = ">=3.11"
+[dependency-groups]
+dev = ["fastro"]
+
[tool.uv.workspace]
members = ["backend", "cli"]
+[tool.uv.sources]
+fastro = { git = "https://github.com/benavlabs/fastro", rev = "ddda03f1151b3233e083dd2d4354649dc997e4ec" }
+
[tool.pytest.ini_options]
testpaths = ["blueprint/tests"]
diff --git a/uv.lock b/uv.lock
index ea8f91a4..f3cd0818 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1,5 +1,5 @@
version = 1
-revision = 3
+revision = 5
requires-python = ">=3.11"
resolution-markers = [
"python_full_version >= '3.15'",
@@ -980,6 +980,16 @@ name = "fastapi-boilerplate-workspace"
version = "0"
source = { virtual = "." }
+[package.dev-dependencies]
+dev = [
+ { name = "fastro" },
+]
+
+[package.metadata]
+
+[package.metadata.requires-dev]
+dev = [{ name = "fastro", git = "https://github.com/benavlabs/fastro?rev=ddda03f1151b3233e083dd2d4354649dc997e4ec" }]
+
[[package]]
name = "fastapi-cli"
version = "0.0.24"
@@ -1135,6 +1145,16 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/5f/1b/85fb4c1cb771845e5ede668ef28c090e021020d117e891fa1e599c9e32d1/fastcrud-0.21.0-py3-none-any.whl", hash = "sha256:94daa5ca7815a268b700ee31b36455a8248a1a0547f3fcef5969df0047aab338", size = 107150, upload-time = "2026-01-23T19:30:05.895Z" },
]
+[[package]]
+name = "fastro"
+version = "0.1.0.dev0"
+source = { git = "https://github.com/benavlabs/fastro?rev=ddda03f1151b3233e083dd2d4354649dc997e4ec#ddda03f1151b3233e083dd2d4354649dc997e4ec" }
+dependencies = [
+ { name = "jinja2" },
+ { name = "packaging" },
+ { name = "typer" },
+]
+
[[package]]
name = "filelock"
version = "4.2.4"
From 4bfe979b030e33318365df4174e526c13265b499 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Mon, 16 Nov 2026 19:35:58 -0300
Subject: [PATCH 34/71] run the sync check when a commit moves the fastro pin,
since another fastro can render the catalog differently
---
.pre-commit-config.yaml | 2 +-
backend/tests/unit/test_blueprint_catalog.py | 12 ++++++++++++
2 files changed, 13 insertions(+), 1 deletion(-)
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index db8dee68..fe2ac28a 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -59,7 +59,7 @@ repos:
language: system
entry: uv run --no-sync fastro sync --check
pass_filenames: false
- files: ^(blueprint\.toml|fastro\.toml|backend/src/wiring/.*|backend/scripts/seeders\.py|backend/tests/wiring\.py)$
+ files: ^(blueprint\.toml|fastro\.toml|pyproject\.toml|uv\.lock|backend/src/wiring/.*|backend/scripts/seeders\.py|backend/tests/wiring\.py)$
- id: unit_test
name: Unit test
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index bf5d5947..76fc073d 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -658,12 +658,24 @@ def test_a_commit_that_touches_what_sync_compares_runs_sync_check(path: str):
assert re.search(_the_sync_check_hook()["files"], path), path
+@pytest.mark.parametrize("path", ["pyproject.toml", "uv.lock"])
+def test_a_commit_that_moves_the_fastro_pin_runs_sync_check(path: str):
+ """Another fastro can render the same catalog differently, so the files that pin it count too."""
+ assert re.search(_the_sync_check_hook()["files"], path), path
+
+
def test_a_commit_that_touches_nothing_sync_compares_skips_sync_check():
for path in (
"backend/src/modules/user/models.py",
"docs/backend/src/wiring/app.md",
"backend/fastro.toml",
"blueprint.toml.orig",
+ "backend/pyproject.toml",
+ "backend/uv.lock",
+ "uv_lock",
+ "pyproject_toml",
+ "fastro_toml",
+ "blueprint_toml",
):
assert not re.search(_the_sync_check_hook()["files"], path), path
From d811716367c9f77d011b21e5a764c223abf1fab1 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Mon, 16 Nov 2026 20:23:57 -0300
Subject: [PATCH 35/71] say in the contributing guide that syncing installs
fastro, that a commit runs its sync check and how to fix it, and which uv
wrote the lock
---
CONTRIBUTING.md | 6 ++
backend/tests/unit/test_blueprint_catalog.py | 100 +++++++++++++++++++
blueprint/tests/test_fastro.py | 45 +++++++++
3 files changed, 151 insertions(+)
create mode 100644 blueprint/tests/test_fastro.py
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 03de15b1..d229a78d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -27,6 +27,11 @@ uv sync --all-packages --all-extras
`--all-packages` installs both workspace members, and `--all-extras` brings in the
dev tools: a plain `uv sync` leaves you without ruff, mypy or pytest.
+The sync also installs fastro, the CLI that generates projects from this blueprint
+and checks it. The root `pyproject.toml` pins fastro to one commit in its `dev`
+group. `uv.lock` is at lock revision 5, which uv 0.13.8 wrote, so use uv 0.13.8 or
+newer.
+
### Activating the Virtual Environment
uv creates a virtual environment for your project. Activate it using:
@@ -85,6 +90,7 @@ It helps in identifying simple issues before submission to code review. By runni
1. **Committing Your Changes**:
After making your changes, use `git commit -am 'Add some fooBar'` to commit them. Pre-commit will run automatically on your files when you commit, ensuring that they meet the required standards.
Note: If pre-commit identifies issues, it may block your commit. Fix these issues and commit again. This ensures that all contributions are of high quality.
+ A commit that touches `blueprint.toml`, `fastro.toml`, a wiring file fastro generates, the root `pyproject.toml`, or `uv.lock` also runs `uv run --no-sync fastro sync --check`, which fails when the wiring in the commit differs from what fastro generates. Run `uv run --no-sync fastro sync` to regenerate the wiring, then commit the result.
1. **Pushing Changes and Creating Pull Request**:
Push your changes to the branch using `git push origin feature/fooBar`.
Visit your fork on GitHub and create a new Pull Request to the main repository.
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 76fc073d..b8b2e9ea 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -749,6 +749,106 @@ def test_ci_runs_fastros_checks_where_fastro_is_installed(command: str):
assert set(sync.split()) <= SYNC_THAT_KEEPS_THE_DEV_GROUP, sync
+CONTRIBUTING = REPO_ROOT / "CONTRIBUTING.md"
+
+UV_THAT_WROTE_THE_LOCK = {5: "0.13.8"}
+"""The uv release this repository's lock was first written with at each revision, not the first release that writes it."""
+
+
+def _contributing_syncs() -> list[str]:
+ """Each sync the guide gives as a command on its own line, not a sync it names inline in prose."""
+ return re.findall(r"^\s*(?:\$\s+)?(uv sync\b.*)$", CONTRIBUTING.read_text(), re.M)
+
+
+def test_the_contributing_guide_is_the_blueprint_s_own():
+ assert _withheld("CONTRIBUTING.md")
+
+
+def test_the_sync_the_contributing_guide_gives_installs_fastro():
+ """The guide says the sync brings fastro in, so the sync it gives keeps the root dev group."""
+ assert _contributing_syncs()
+ for sync in _contributing_syncs():
+ assert set(sync.split()) <= SYNC_THAT_KEEPS_THE_DEV_GROUP, sync
+ assert re.search(r"The sync also installs fastro\b", CONTRIBUTING.read_text())
+
+
+def test_the_contributing_guide_names_the_group_that_pins_fastro():
+ groups = [
+ group
+ for group, specifiers in _root_project()["dependency-groups"].items()
+ if "fastro" in {_distribution(specifier) for specifier in specifiers}
+ ]
+
+ assert len(groups) == 1, groups
+ assert re.search(rf"pins fastro to one commit in its `{groups[0]}`\s+group\.", CONTRIBUTING.read_text())
+
+
+def test_the_contributing_guide_names_the_uv_that_wrote_the_lock():
+ """A uv older than the one that wrote the lock can write it back at an older revision, so the guide names that release."""
+ with (REPO_ROOT / "uv.lock").open("rb") as handle:
+ revision = tomllib.load(handle)["revision"]
+ assert revision in UV_THAT_WROTE_THE_LOCK, f"add the uv that wrote lock revision {revision}, and name it in CONTRIBUTING.md"
+
+ text = CONTRIBUTING.read_text()
+ assert re.search(rf"lock\s+revision\s+{revision}\b", text)
+ assert re.search(rf"uv\s+{re.escape(UV_THAT_WROTE_THE_LOCK[revision])}\s+or\s+newer\b", text)
+ assert set(re.findall(r"\buv\s+(\d+\.\d+\.\d+)", text)) == {UV_THAT_WROTE_THE_LOCK[revision]}
+
+
+def _the_guide_s_sentences() -> list[str]:
+ return re.split(r"(?<=\.)\s+", CONTRIBUTING.read_text())
+
+
+def _the_guide_s_sync_check_sentence() -> str:
+ hook = f"`{_the_sync_check_hook()['entry']}`"
+ sentences = [sentence for sentence in _the_guide_s_sentences() if hook in sentence]
+ assert len(sentences) == 1, sentences
+
+ return sentences[0]
+
+
+def test_the_contributing_guide_names_the_check_a_commit_runs():
+ """`blueprint/tests/` proves the check fails on wiring that differs from what fastro generates."""
+ hook = f"`{_the_sync_check_hook()['entry']}`"
+
+ assert re.search(
+ rf"{re.escape(hook)},\s+which\s+fails\s+when\s+the\s+wiring\s+in\s+the\s+commit\s+differs\b",
+ _the_guide_s_sync_check_sentence(),
+ )
+
+
+def test_the_contributing_guide_names_every_file_that_runs_the_check():
+ """The catalog, the selection and the pin by name, and the wiring by what it is, each one the hook runs on."""
+ sentence = _the_guide_s_sync_check_sentence()
+ named = set(re.findall(r"`([\w.]+\.(?:toml|lock))`", sentence))
+
+ assert named == {"blueprint.toml", "fastro.toml", "pyproject.toml", "uv.lock"}
+ for path in named:
+ assert re.search(_the_sync_check_hook()["files"], path), path
+ assert re.search(r"\ba wiring file fastro generates\b", sentence)
+
+
+def test_the_check_runs_on_no_file_the_contributing_guide_leaves_out():
+ """Each trigger is a file the guide names or a wiring file, so a new one fails until the guide names it."""
+ named = set(re.findall(r"`([\w.]+\.(?:toml|lock))`", _the_guide_s_sync_check_sentence()))
+ wiring = [entry["path"] for entry in _catalog()["wiring"]]
+
+ for alternative in _alternatives(_the_sync_check_hook()["files"]):
+ assert re.sub(r"\\(.)", r"\1", alternative) in named or any(re.fullmatch(alternative, path) for path in wiring), (
+ alternative
+ )
+
+
+def test_the_contributing_guide_names_the_command_that_fixes_a_failed_check():
+ """Right after the check, and `blueprint/tests/` proves the command regenerates what the check compares."""
+ sentences = _the_guide_s_sentences()
+ following = sentences[sentences.index(_the_guide_s_sync_check_sentence()) + 1]
+
+ assert following.rstrip() == "Run `uv run --no-sync fastro sync` to regenerate the wiring, then commit the result.", (
+ following
+ )
+
+
def _literals(module: Path) -> set[str]:
"""Every string literal in a module, less the docstrings, which talk about files rather than
reach for them."""
diff --git a/blueprint/tests/test_fastro.py b/blueprint/tests/test_fastro.py
new file mode 100644
index 00000000..37e2fa76
--- /dev/null
+++ b/blueprint/tests/test_fastro.py
@@ -0,0 +1,45 @@
+"""What the fastro the repository root installs gives the people who work on the blueprint."""
+
+import shutil
+import subprocess
+import sys
+import tomllib
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+
+def _fastro(*arguments: str, cwd: Path) -> subprocess.CompletedProcess[str]:
+ return subprocess.run([sys.executable, "-m", "fastro", *arguments], cwd=cwd, capture_output=True, text=True, check=False)
+
+
+def _tree(destination: Path) -> Path:
+ listed = subprocess.run(
+ ["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ check=True,
+ ).stdout
+ for name in filter(None, listed.split("\0")):
+ source = REPO_ROOT / name
+ if source.is_file():
+ (destination / name).parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(source, destination / name)
+
+ return destination
+
+
+def test_plain_sync_regenerates_what_the_check_compares(tmp_path: Path):
+ """CONTRIBUTING.md sends a failed `fastro sync --check` to `fastro sync`."""
+ tree = _tree(tmp_path / "blueprint")
+ wiring = tree / tomllib.loads((tree / "blueprint.toml").read_text())["wiring"][0]["path"]
+ generated = wiring.read_text()
+ wiring.write_text(generated + "\nedited = True\n")
+
+ assert _fastro("sync", "--check", cwd=tree).returncode == 1
+
+ synced = _fastro("sync", cwd=tree)
+
+ assert synced.returncode == 0, synced.stderr
+ assert _fastro("sync", "--check", cwd=tree).returncode == 0
From 93a3e164adf5469fa917263fd566ad6de9660a5a Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Mon, 16 Nov 2026 20:31:17 -0300
Subject: [PATCH 36/71] test the facts the contributing guide states about
fastro, not its wording
---
backend/tests/unit/test_blueprint_catalog.py | 37 ++++++--------------
1 file changed, 11 insertions(+), 26 deletions(-)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index b8b2e9ea..6cea6447 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -765,11 +765,10 @@ def test_the_contributing_guide_is_the_blueprint_s_own():
def test_the_sync_the_contributing_guide_gives_installs_fastro():
- """The guide says the sync brings fastro in, so the sync it gives keeps the root dev group."""
+ """Every sync it gives keeps the root dev group, where fastro is."""
assert _contributing_syncs()
for sync in _contributing_syncs():
assert set(sync.split()) <= SYNC_THAT_KEEPS_THE_DEV_GROUP, sync
- assert re.search(r"The sync also installs fastro\b", CONTRIBUTING.read_text())
def test_the_contributing_guide_names_the_group_that_pins_fastro():
@@ -780,7 +779,7 @@ def test_the_contributing_guide_names_the_group_that_pins_fastro():
]
assert len(groups) == 1, groups
- assert re.search(rf"pins fastro to one commit in its `{groups[0]}`\s+group\.", CONTRIBUTING.read_text())
+ assert f"`{groups[0]}`" in CONTRIBUTING.read_text()
def test_the_contributing_guide_names_the_uv_that_wrote_the_lock():
@@ -790,42 +789,33 @@ def test_the_contributing_guide_names_the_uv_that_wrote_the_lock():
assert revision in UV_THAT_WROTE_THE_LOCK, f"add the uv that wrote lock revision {revision}, and name it in CONTRIBUTING.md"
text = CONTRIBUTING.read_text()
- assert re.search(rf"lock\s+revision\s+{revision}\b", text)
- assert re.search(rf"uv\s+{re.escape(UV_THAT_WROTE_THE_LOCK[revision])}\s+or\s+newer\b", text)
+ assert re.search(rf"\brevision\s+{revision}\b", text)
assert set(re.findall(r"\buv\s+(\d+\.\d+\.\d+)", text)) == {UV_THAT_WROTE_THE_LOCK[revision]}
-
-
-def _the_guide_s_sentences() -> list[str]:
- return re.split(r"(?<=\.)\s+", CONTRIBUTING.read_text())
+ assert re.search(rf"uv\s+{re.escape(UV_THAT_WROTE_THE_LOCK[revision])}\s+or\s+(?:newer|later)\b", text)
def _the_guide_s_sync_check_sentence() -> str:
hook = f"`{_the_sync_check_hook()['entry']}`"
- sentences = [sentence for sentence in _the_guide_s_sentences() if hook in sentence]
+ sentences = [sentence for sentence in re.split(r"(?<=\.)\s+", CONTRIBUTING.read_text()) if hook in sentence]
assert len(sentences) == 1, sentences
return sentences[0]
def test_the_contributing_guide_names_the_check_a_commit_runs():
- """`blueprint/tests/` proves the check fails on wiring that differs from what fastro generates."""
- hook = f"`{_the_sync_check_hook()['entry']}`"
-
- assert re.search(
- rf"{re.escape(hook)},\s+which\s+fails\s+when\s+the\s+wiring\s+in\s+the\s+commit\s+differs\b",
- _the_guide_s_sync_check_sentence(),
- )
+ """`blueprint/tests/test_fastro.py::test_plain_sync_regenerates_what_the_check_compares` proves what it does."""
+ assert _the_guide_s_sync_check_sentence()
def test_the_contributing_guide_names_every_file_that_runs_the_check():
- """The catalog, the selection and the pin by name, and the wiring by what it is, each one the hook runs on."""
+ """The catalog, the selection and the pin by name, and the wiring, each one the hook runs on."""
sentence = _the_guide_s_sync_check_sentence()
named = set(re.findall(r"`([\w.]+\.(?:toml|lock))`", sentence))
assert named == {"blueprint.toml", "fastro.toml", "pyproject.toml", "uv.lock"}
for path in named:
assert re.search(_the_sync_check_hook()["files"], path), path
- assert re.search(r"\ba wiring file fastro generates\b", sentence)
+ assert "wiring" in sentence.split(f"`{_the_sync_check_hook()['entry']}`")[0]
def test_the_check_runs_on_no_file_the_contributing_guide_leaves_out():
@@ -840,13 +830,8 @@ def test_the_check_runs_on_no_file_the_contributing_guide_leaves_out():
def test_the_contributing_guide_names_the_command_that_fixes_a_failed_check():
- """Right after the check, and `blueprint/tests/` proves the command regenerates what the check compares."""
- sentences = _the_guide_s_sentences()
- following = sentences[sentences.index(_the_guide_s_sync_check_sentence()) + 1]
-
- assert following.rstrip() == "Run `uv run --no-sync fastro sync` to regenerate the wiring, then commit the result.", (
- following
- )
+ """`blueprint/tests/test_fastro.py::test_plain_sync_regenerates_what_the_check_compares` proves what it does."""
+ assert "`uv run --no-sync fastro sync`" in CONTRIBUTING.read_text()
def _literals(module: Path) -> set[str]:
From bfe285fba586f30889ea90b1484af899f40049b1 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Mon, 16 Nov 2026 20:58:09 -0300
Subject: [PATCH 37/71] name the sync check hook in the development guide's
hook table, and test the table against the config
---
backend/tests/unit/test_blueprint_catalog.py | 92 ++++++++++++++++++--
docs/user-guide/development.md | 1 +
2 files changed, 88 insertions(+), 5 deletions(-)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 6cea6447..8d78f0fc 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -638,6 +638,21 @@ def _the_sync_check_hook() -> dict[str, str]:
return hooks[0]
+SYNC_CHECK_TRIGGERS_BY_NAME = {"blueprint.toml", "fastro.toml", "pyproject.toml", "uv.lock"}
+"""The files the guides name as running the sync check; the wiring they name by what it is."""
+
+
+def _path_spans(text: str) -> set[str]:
+ """Each code span that reads as a path: no spaces, and a directory or an extension."""
+ return {span for span in re.findall(r"`([^`]+)`", text) if re.fullmatch(r"[\w./-]+", span) and re.search(r"[/.]", span)}
+
+
+def _assert_names_the_sync_check_triggers(text: str) -> None:
+ assert _path_spans(text) == SYNC_CHECK_TRIGGERS_BY_NAME, _path_spans(text)
+ for path in _path_spans(text):
+ assert re.search(_the_sync_check_hook()["files"], path), path
+
+
def test_a_commit_runs_sync_check_on_the_whole_tree():
"""`sync --check` compares every wiring file, so the hook hands it no file names."""
hook = _the_sync_check_hook()
@@ -680,6 +695,76 @@ def test_a_commit_that_touches_nothing_sync_compares_skips_sync_check():
assert not re.search(_the_sync_check_hook()["files"], path), path
+HYGIENE_HOOKS_REPOSITORY = "https://github.com/pre-commit/pre-commit-hooks"
+"""The repository whose hooks the development guide's table names together, as its hygiene hooks."""
+
+
+def _hook_repositories() -> dict[str, str]:
+ """Each hook id in `.pre-commit-config.yaml`, with the repository it comes from."""
+ text = (REPO_ROOT / ".pre-commit-config.yaml").read_text()
+
+ return {
+ hook: repository
+ for repository, block in re.findall(r"^ - repo: (\S+)\n((?:(?! - repo: ).*\n)*)", text, re.M)
+ for hook in re.findall(r"^ *- id: ([\w-]+)", block, re.M)
+ }
+
+
+def _development_guide_hook_rows() -> dict[str, str]:
+ """The guide's pre-commit table, each row keyed by each hook its first cell names, or by the cell if it names none."""
+ section = (REPO_ROOT / "docs" / "user-guide" / "development.md").read_text().split("## Pre-Commit", 1)[1]
+ rows = re.findall(r"^\| (?!Hook\b|-)(.+?) \| (.+) \|$", section.split("\n\n## ", 1)[0], re.M)
+
+ named = [
+ (name, cells)
+ for names, cells in rows
+ for name in [code.split()[0] for code in re.findall(r"`([^`]+)`", names)] or [names]
+ ]
+ assert len({name for name, _ in named}) == len(named), named
+
+ return dict(named)
+
+
+def test_the_development_guide_names_every_hook_a_commit_runs():
+ rows = _development_guide_hook_rows()
+ assert _hook_repositories()
+
+ for hook, repository in _hook_repositories().items():
+ assert hook in rows or (repository == HYGIENE_HOOKS_REPOSITORY and "hygiene hooks" in rows), hook
+
+
+def test_the_development_guide_names_no_hook_the_config_lacks():
+ rows = _development_guide_hook_rows()
+
+ assert set(rows) - {"hygiene hooks"} <= set(_hook_repositories())
+ if "hygiene hooks" in rows:
+ assert HYGIENE_HOOKS_REPOSITORY in _hook_repositories().values()
+
+
+def test_the_development_guide_says_which_hooks_are_local():
+ rows = _development_guide_hook_rows()
+ local = {hook for hook, repository in _hook_repositories().items() if repository == "local"}
+
+ assert local
+ assert {hook for hook, cells in rows.items() if cells.startswith("local")} == local
+
+
+def test_the_development_guide_says_which_hooks_run_only_when_asked_for():
+ manual = {hook["id"] for hook in _pre_commit_hooks() if hook.get("stages") == "[manual]"}
+
+ assert manual
+ assert {hook for hook, cells in _development_guide_hook_rows().items() if "manual stage" in cells} == manual
+
+
+def test_the_development_guide_gives_the_command_the_sync_check_hook_runs():
+ row = _development_guide_hook_rows()[_the_sync_check_hook()["id"]]
+ entry = f"`{_the_sync_check_hook()['entry']}`"
+
+ assert entry in row
+ _assert_names_the_sync_check_triggers(row)
+ assert "wiring" in row.replace(entry, "")
+
+
def _workflow_runs() -> list[str]:
"""Every one-line `run:` in the repository's own CI."""
return [
@@ -810,17 +895,14 @@ def test_the_contributing_guide_names_the_check_a_commit_runs():
def test_the_contributing_guide_names_every_file_that_runs_the_check():
"""The catalog, the selection and the pin by name, and the wiring, each one the hook runs on."""
sentence = _the_guide_s_sync_check_sentence()
- named = set(re.findall(r"`([\w.]+\.(?:toml|lock))`", sentence))
- assert named == {"blueprint.toml", "fastro.toml", "pyproject.toml", "uv.lock"}
- for path in named:
- assert re.search(_the_sync_check_hook()["files"], path), path
+ _assert_names_the_sync_check_triggers(sentence)
assert "wiring" in sentence.split(f"`{_the_sync_check_hook()['entry']}`")[0]
def test_the_check_runs_on_no_file_the_contributing_guide_leaves_out():
"""Each trigger is a file the guide names or a wiring file, so a new one fails until the guide names it."""
- named = set(re.findall(r"`([\w.]+\.(?:toml|lock))`", _the_guide_s_sync_check_sentence()))
+ named = _path_spans(_the_guide_s_sync_check_sentence())
wiring = [entry["path"] for entry in _catalog()["wiring"]]
for alternative in _alternatives(_the_sync_check_hook()["files"]):
diff --git a/docs/user-guide/development.md b/docs/user-guide/development.md
index 25c0e10b..04154340 100644
--- a/docs/user-guide/development.md
+++ b/docs/user-guide/development.md
@@ -104,6 +104,7 @@ The repo's `.pre-commit-config.yaml` runs what CI runs, and nothing that fights
| `yesqa` | removes a `noqa` nothing needs any more |
| hygiene hooks | final newlines, trailing whitespace, YAML, large files, private keys, merge markers |
| `mypy_backend`, `mypy_cli` | local hooks, the same invocations CI uses |
+| `fastro_sync_check` | local: `uv run --no-sync fastro sync --check`, on a commit that touches `blueprint.toml`, `fastro.toml`, the wiring, the root `pyproject.toml` or `uv.lock` |
| `unit_test` | local, manual stage: `pytest tests/unit` |
`unit_test` runs the unit tests only — they need no container and finish in seconds. The
From 6739d4d42815e89601ea20a0cf40f60bb5d32391 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Mon, 16 Nov 2026 21:58:17 -0300
Subject: [PATCH 38/71] say in the readme that the quickstart sync installs
fastro, and hold every readme sync to the flags that keep the root dev group
---
README.md | 2 +-
backend/tests/unit/test_blueprint_catalog.py | 10 ++++++++++
2 files changed, 11 insertions(+), 1 deletion(-)
diff --git a/README.md b/README.md
index d0af0a05..f72f94ec 100644
--- a/README.md
+++ b/README.md
@@ -126,7 +126,7 @@ fastapi-boilerplate/
```bash
git clone https://github.com//FastAPI-boilerplate
cd FastAPI-boilerplate
-uv sync --all-packages --all-extras # one venv at the root, both members installed
+uv sync --all-packages --all-extras # one venv at the root: both members, plus fastro
```
Generate a compose file for the deployment shape you want:
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 8d78f0fc..fb5da387 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -856,6 +856,16 @@ def test_the_sync_the_contributing_guide_gives_installs_fastro():
assert set(sync.split()) <= SYNC_THAT_KEEPS_THE_DEV_GROUP, sync
+def test_the_readme_s_quickstart_sync_installs_fastro():
+ """Every sync the README gives keeps the root dev group, and says it brings fastro in."""
+ syncs = re.findall(r"^\s*(?:\$\s+)?(uv sync\b[^#\n]*)(#.*)?$", (REPO_ROOT / "README.md").read_text(), re.M)
+
+ assert syncs
+ for sync, note in syncs:
+ assert set(sync.split()) <= SYNC_THAT_KEEPS_THE_DEV_GROUP, sync
+ assert re.search(r"\bfastro\b", note), note
+
+
def test_the_contributing_guide_names_the_group_that_pins_fastro():
groups = [
group
From 5bce23c2d335fe92cf43736767734e1f88121fdc Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Mon, 16 Nov 2026 22:06:52 -0300
Subject: [PATCH 39/71] name every hook and the unit test hook's command and
directory in the development guide's hook table, and test that the hooks it
says ci runs run what ci runs
---
backend/tests/unit/test_blueprint_catalog.py | 44 ++++++++++++++------
docs/user-guide/development.md | 4 +-
2 files changed, 33 insertions(+), 15 deletions(-)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index fb5da387..c9735a19 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -695,10 +695,6 @@ def test_a_commit_that_touches_nothing_sync_compares_skips_sync_check():
assert not re.search(_the_sync_check_hook()["files"], path), path
-HYGIENE_HOOKS_REPOSITORY = "https://github.com/pre-commit/pre-commit-hooks"
-"""The repository whose hooks the development guide's table names together, as its hygiene hooks."""
-
-
def _hook_repositories() -> dict[str, str]:
"""Each hook id in `.pre-commit-config.yaml`, with the repository it comes from."""
text = (REPO_ROOT / ".pre-commit-config.yaml").read_text()
@@ -726,19 +722,12 @@ def _development_guide_hook_rows() -> dict[str, str]:
def test_the_development_guide_names_every_hook_a_commit_runs():
- rows = _development_guide_hook_rows()
assert _hook_repositories()
-
- for hook, repository in _hook_repositories().items():
- assert hook in rows or (repository == HYGIENE_HOOKS_REPOSITORY and "hygiene hooks" in rows), hook
+ assert set(_hook_repositories()) <= set(_development_guide_hook_rows())
def test_the_development_guide_names_no_hook_the_config_lacks():
- rows = _development_guide_hook_rows()
-
- assert set(rows) - {"hygiene hooks"} <= set(_hook_repositories())
- if "hygiene hooks" in rows:
- assert HYGIENE_HOOKS_REPOSITORY in _hook_repositories().values()
+ assert set(_development_guide_hook_rows()) <= set(_hook_repositories())
def test_the_development_guide_says_which_hooks_are_local():
@@ -765,6 +754,35 @@ def test_the_development_guide_gives_the_command_the_sync_check_hook_runs():
assert "wiring" in row.replace(entry, "")
+def _hook_shell_line(hook: dict[str, str]) -> str:
+ """What a hook runs, without the `bash -c` that lets a local hook change directory first."""
+ found = re.fullmatch(r"bash -c '(.+)'", hook["entry"])
+
+ return found[1] if found else hook["entry"]
+
+
+def test_the_hooks_the_development_guide_says_ci_runs_run_what_ci_runs():
+ rows = _development_guide_hook_rows()
+ claimed = [hook for hook in _pre_commit_hooks() if "entry" in hook and re.search(r"\bCI\b", rows.get(hook["id"], ""))]
+
+ assert claimed
+ for hook in claimed:
+ assert _hook_shell_line(hook) in _workflow_runs(), hook["id"]
+
+
+def test_the_development_guide_gives_the_command_each_manual_hook_runs_and_where():
+ manual = [hook for hook in _pre_commit_hooks() if hook.get("stages") == "[manual]"]
+
+ assert manual
+ for hook in manual:
+ found = re.fullmatch(r"cd (\S+) && (.+)", _hook_shell_line(hook))
+ assert found, hook["id"]
+ directory, command = found.groups()
+ row = _development_guide_hook_rows()[hook["id"]]
+ assert f"`{command}`" in row, row
+ assert f"`{directory}/`" in row, row
+
+
def _workflow_runs() -> list[str]:
"""Every one-line `run:` in the repository's own CI."""
return [
diff --git a/docs/user-guide/development.md b/docs/user-guide/development.md
index 04154340..762e545e 100644
--- a/docs/user-guide/development.md
+++ b/docs/user-guide/development.md
@@ -102,10 +102,10 @@ The repo's `.pre-commit-config.yaml` runs what CI runs, and nothing that fights
| `ruff-check --fix`, `ruff-format` | the same lint and format CI checks |
| `pyupgrade` | rewrites to Python 3.11+ syntax |
| `yesqa` | removes a `noqa` nothing needs any more |
-| hygiene hooks | final newlines, trailing whitespace, YAML, large files, private keys, merge markers |
+| `end-of-file-fixer`, `trailing-whitespace`, `check-yaml`, `check-executables-have-shebangs`, `check-case-conflict`, `check-added-large-files`, `detect-private-key`, `check-merge-conflict` | final newlines, trailing whitespace, YAML, shebangs on executables, file names that differ only in case, large files, private keys, merge markers |
| `mypy_backend`, `mypy_cli` | local hooks, the same invocations CI uses |
| `fastro_sync_check` | local: `uv run --no-sync fastro sync --check`, on a commit that touches `blueprint.toml`, `fastro.toml`, the wiring, the root `pyproject.toml` or `uv.lock` |
-| `unit_test` | local, manual stage: `pytest tests/unit` |
+| `unit_test` | local, manual stage: `uv run --no-sync pytest tests/unit` in `backend/` |
`unit_test` runs the unit tests only — they need no container and finish in seconds. The
integration suite, which starts Postgres through testcontainers, runs in CI and when you run
From 33a0e730d7cc512b3f7690c1e3f995b9427f391a Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Mon, 16 Nov 2026 22:24:48 -0300
Subject: [PATCH 40/71] say in each row of the development guide's hook table
whether ci runs it, and test the claim both ways against the workflows
---
backend/tests/unit/test_blueprint_catalog.py | 40 +++++++++++++++++++-
docs/user-guide/development.md | 8 ++--
2 files changed, 42 insertions(+), 6 deletions(-)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index c9735a19..60c866e1 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -761,13 +761,49 @@ def _hook_shell_line(hook: dict[str, str]) -> str:
return found[1] if found else hook["entry"]
+def _ci_runs_command(command: str) -> bool:
+ """Whether a CI step runs this command, alone or on paths after it."""
+ return any(re.fullmatch(rf"(?:uv run --no-sync )?{re.escape(command)}(?: [^-\s]\S*)*", run) for run in _workflow_runs())
+
+
+def _names_ci(row: str) -> bool:
+ """Whether a row of the development guide's hook table says what CI runs."""
+ return re.search(r"\bCI\b", row) is not None
+
+
+def _ci_runs_hook(hook: dict[str, str]) -> bool:
+ """Whether a CI step runs a local hook's command, as it is or on every path instead of the ones it names."""
+ line = _hook_shell_line(hook)
+
+ return line in _workflow_runs() or re.sub(r"(?: [\w.-]*[/.][\w./-]*)+$", "", line) in _workflow_runs()
+
+
def test_the_hooks_the_development_guide_says_ci_runs_run_what_ci_runs():
rows = _development_guide_hook_rows()
- claimed = [hook for hook in _pre_commit_hooks() if "entry" in hook and re.search(r"\bCI\b", rows.get(hook["id"], ""))]
+ claimed = [hook for hook in _pre_commit_hooks() if _names_ci(rows[hook["id"]])]
assert claimed
for hook in claimed:
- assert _hook_shell_line(hook) in _workflow_runs(), hook["id"]
+ if "entry" in hook:
+ assert _ci_runs_hook(hook), hook["id"]
+ else:
+ commands = [span for span in re.findall(r"`([^`]+)`", rows[hook["id"]]) if " " in span]
+ assert any(command.startswith(hook["id"].replace("-", " ")) for command in commands), hook["id"]
+ for command in commands:
+ assert _ci_runs_command(command), command
+
+
+def test_the_hooks_the_development_guide_leaves_ci_out_of_are_no_ci_step():
+ rows = _development_guide_hook_rows()
+ unclaimed = [hook for hook in _pre_commit_hooks() if not _names_ci(rows[hook["id"]])]
+
+ assert unclaimed
+ for hook in unclaimed:
+ if "entry" in hook:
+ assert not _ci_runs_hook(hook), hook["id"]
+ else:
+ for name in {hook["id"], hook["id"].replace("-", " ")}:
+ assert not any(re.search(rf"\b{re.escape(name)}\b", run) for run in _workflow_runs()), name
def test_the_development_guide_gives_the_command_each_manual_hook_runs_and_where():
diff --git a/docs/user-guide/development.md b/docs/user-guide/development.md
index 762e545e..453fc750 100644
--- a/docs/user-guide/development.md
+++ b/docs/user-guide/development.md
@@ -95,17 +95,17 @@ field reads as an error.
## Pre-Commit
-The repo's `.pre-commit-config.yaml` runs what CI runs, and nothing that fights it:
+The repo's `.pre-commit-config.yaml` runs these hooks. A row that names CI says what CI runs for it; the other hooks are no CI step:
| Hook | What it does |
|------|--------------|
-| `ruff-check --fix`, `ruff-format` | the same lint and format CI checks |
+| `ruff-check --fix`, `ruff-format` | lint and format the files a commit stages, fixing what they can; CI runs `ruff check` and `ruff format --check` |
| `pyupgrade` | rewrites to Python 3.11+ syntax |
| `yesqa` | removes a `noqa` nothing needs any more |
| `end-of-file-fixer`, `trailing-whitespace`, `check-yaml`, `check-executables-have-shebangs`, `check-case-conflict`, `check-added-large-files`, `detect-private-key`, `check-merge-conflict` | final newlines, trailing whitespace, YAML, shebangs on executables, file names that differ only in case, large files, private keys, merge markers |
| `mypy_backend`, `mypy_cli` | local hooks, the same invocations CI uses |
-| `fastro_sync_check` | local: `uv run --no-sync fastro sync --check`, on a commit that touches `blueprint.toml`, `fastro.toml`, the wiring, the root `pyproject.toml` or `uv.lock` |
-| `unit_test` | local, manual stage: `uv run --no-sync pytest tests/unit` in `backend/` |
+| `fastro_sync_check` | local: `uv run --no-sync fastro sync --check`, on a commit that touches `blueprint.toml`, `fastro.toml`, the wiring, the root `pyproject.toml` or `uv.lock`; CI runs the same command |
+| `unit_test` | local, manual stage: `uv run --no-sync pytest tests/unit` in `backend/`; CI runs these tests with the rest, as `uv run --no-sync pytest` in `backend/` |
`unit_test` runs the unit tests only — they need no container and finish in seconds. The
integration suite, which starts Postgres through testcontainers, runs in CI and when you run
From cb28fe03d61f5c5ee9b3fe581964b4fdb6b156fc Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Mon, 16 Nov 2026 22:57:47 -0300
Subject: [PATCH 41/71] correct the development guide's claim that the unit
tests need no container, and test each fact its pre-commit prose states past
the hook table
---
backend/tests/unit/test_blueprint_catalog.py | 121 ++++++++++++++++++-
docs/user-guide/development.md | 12 +-
2 files changed, 125 insertions(+), 8 deletions(-)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 60c866e1..dc613343 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -17,6 +17,7 @@
import itertools
import keyword
import re
+import subprocess
import sys
import tomllib
from collections.abc import Iterable
@@ -26,6 +27,8 @@
import pytest
+from tests.conftest import is_docker_running
+
REPO_ROOT = Path(__file__).resolve().parents[3]
CATALOG = REPO_ROOT / "blueprint.toml"
@@ -706,10 +709,15 @@ def _hook_repositories() -> dict[str, str]:
}
+def _development_guide_pre_commit_section() -> str:
+ guide = (REPO_ROOT / "docs" / "user-guide" / "development.md").read_text()
+
+ return guide.split("## Pre-Commit", 1)[1].split("\n\n## ", 1)[0]
+
+
def _development_guide_hook_rows() -> dict[str, str]:
"""The guide's pre-commit table, each row keyed by each hook its first cell names, or by the cell if it names none."""
- section = (REPO_ROOT / "docs" / "user-guide" / "development.md").read_text().split("## Pre-Commit", 1)[1]
- rows = re.findall(r"^\| (?!Hook\b|-)(.+?) \| (.+) \|$", section.split("\n\n## ", 1)[0], re.M)
+ rows = re.findall(r"^\| (?!Hook\b|-)(.+?) \| (.+) \|$", _development_guide_pre_commit_section(), re.M)
named = [
(name, cells)
@@ -819,6 +827,115 @@ def test_the_development_guide_gives_the_command_each_manual_hook_runs_and_where
assert f"`{directory}/`" in row, row
+def _development_guide_pre_commit_prose() -> str:
+ """The development guide's Pre-Commit section, past its hook table."""
+ return _development_guide_pre_commit_section().rsplit("\n|", 1)[1].split("\n", 1)[1]
+
+
+def _modules_imported_anywhere(path: Path) -> set[str]:
+ """Each module a file imports, at its top or inside a function, a block or a fixture."""
+ modules = set()
+ for node in ast.walk(ast.parse(path.read_text())):
+ if isinstance(node, ast.ImportFrom) and node.module:
+ modules.add(node.module)
+ elif isinstance(node, ast.Import):
+ modules.update(alias.name for alias in node.names)
+
+ return modules
+
+
+def test_every_test_that_starts_a_container_skips_without_docker():
+ """What the development guide means when it says the unit test hook passes without Docker."""
+ tests = REPO_ROOT / "backend" / "tests"
+ starting = [
+ path
+ for path in sorted(tests.rglob("*.py"))
+ if any(re.fullmatch(r"testcontainers(?:\..+)?", module) for module in _modules_imported_anywhere(path))
+ ]
+
+ assert "`testcontainers`" in _development_guide_pre_commit_prose()
+ assert any(path.is_relative_to(tests / "unit") for path in starting)
+ for path in starting:
+ assert re.search(r"if not is_docker_running\(\):\n\s+pytest\.skip\(", path.read_text()), path
+
+
+def test_docker_counts_as_not_running_when_its_client_cannot_connect(monkeypatch):
+ monkeypatch.setenv("DOCKER_HOST", "tcp://127.0.0.1:1")
+ monkeypatch.setattr("testcontainers.core.config.testcontainers_config.tc_properties", {})
+
+ assert is_docker_running() is False
+
+
+def test_the_project_puts_an_attribute_docstring_under_a_module_level_name():
+ """Why the development guide leaves `check-docstring-first` out."""
+ documented = [
+ path
+ for path in sorted((REPO_ROOT / "backend").glob("[st]*/**/*.py"))
+ if any(
+ isinstance(name, ast.Assign | ast.AnnAssign)
+ and isinstance(docstring, ast.Expr)
+ and isinstance(docstring.value, ast.Constant)
+ and isinstance(docstring.value.value, str)
+ for name, docstring in itertools.pairwise(ast.parse(path.read_text()).body)
+ )
+ ]
+
+ assert any(path.is_relative_to(REPO_ROOT / "backend" / "src") for path in documented), documented
+ assert "`check-docstring-first`" in _development_guide_pre_commit_prose()
+
+
+def test_the_hooks_the_development_guide_leaves_out_are_not_in_the_config():
+ left_out = {"mdformat", "blacken-docs", "check-docstring-first"}
+ named = set(re.findall(r"`([\w-]+)`", _development_guide_pre_commit_prose()))
+
+ assert left_out <= named
+ assert not left_out & set(_hook_repositories())
+ assert "ruff-format" in named & set(_hook_repositories())
+
+
+def test_the_extra_the_development_guide_names_installs_pre_commit():
+ prose = _development_guide_pre_commit_prose()
+ extra = re.search(r"`pre-commit` ships in the `([\w-]+)` extra, so `(uv sync[^`]*)`", prose)
+ assert extra, prose
+
+ assert {"--all-packages", "--all-extras"} <= set(extra[2].split())
+ assert any(
+ re.match(r"pre-commit(?![\w.-])", requirement)
+ for member in tomllib.loads((REPO_ROOT / "pyproject.toml").read_text())["tool"]["uv"]["workspace"]["members"]
+ for requirement in tomllib.loads((REPO_ROOT / member / "pyproject.toml").read_text())["project"]
+ .get("optional-dependencies", {})
+ .get(extra[1], [])
+ )
+
+
+def test_each_hook_the_development_guide_runs_by_name_is_in_the_config_at_the_stage_it_gives():
+ runs = re.findall(r"pre-commit run (\w[\w-]*)(.*)$", _development_guide_pre_commit_prose(), re.M)
+ hooks = {hook["id"]: hook for hook in _pre_commit_hooks()}
+
+ assert runs
+ for hook, flags in runs:
+ assert hook in hooks, hook
+ stage = re.search(r"--hook-stage (\w+)", flags)
+ assert hooks[hook].get("stages", "[pre-commit]") == f"[{stage[1] if stage else 'pre-commit'}]", hook
+
+
+def test_each_pre_commit_command_the_development_guide_gives_takes_the_flags_it_passes():
+ prose = _development_guide_pre_commit_prose()
+ commands = re.findall(r"^uv run --no-sync pre-commit (\w+)(.*)$", prose, re.M)
+
+ assert commands
+ for fence in re.findall(r"^```bash\n(.*?)^```$", prose, re.M | re.S):
+ for line in fence.splitlines():
+ assert "pre-commit" not in line or line.startswith("uv run --no-sync pre-commit "), line
+ for subcommand, arguments in commands:
+ usage = subprocess.run(
+ [sys.executable, "-m", "pre_commit", subcommand, "--help"], capture_output=True, text=True, check=False
+ )
+ assert usage.returncode == 0, subcommand
+ for flag in re.findall(r"(? list[str]:
"""Every one-line `run:` in the repository's own CI."""
return [
diff --git a/docs/user-guide/development.md b/docs/user-guide/development.md
index 453fc750..12a2cf5e 100644
--- a/docs/user-guide/development.md
+++ b/docs/user-guide/development.md
@@ -107,17 +107,17 @@ The repo's `.pre-commit-config.yaml` runs these hooks. A row that names CI says
| `fastro_sync_check` | local: `uv run --no-sync fastro sync --check`, on a commit that touches `blueprint.toml`, `fastro.toml`, the wiring, the root `pyproject.toml` or `uv.lock`; CI runs the same command |
| `unit_test` | local, manual stage: `uv run --no-sync pytest tests/unit` in `backend/`; CI runs these tests with the rest, as `uv run --no-sync pytest` in `backend/` |
-`unit_test` runs the unit tests only — they need no container and finish in seconds. The
-integration suite, which starts Postgres through testcontainers, runs in CI and when you run
-`pytest` yourself.
+`unit_test` runs the unit tests only. Some of them start containers through `testcontainers`, and
+every test that starts a container skips when Docker isn't running, so the hook passes without
+Docker. The integration suite runs in CI and when you run `pytest` yourself.
There are no docstring- or markdown-formatting hooks: `ruff-format` owns formatting, and the two
documentation hooks this repo used to carry damaged what they touched — `mdformat` broke MkDocs
content tabs, and `blacken-docs` rewrote code samples into different code.
-`check-docstring-first` is left out for the same reason. This project documents a module-level
-name with an attribute docstring under it, which the hook reads as a second module docstring, so
-it refused 40 files.
+`check-docstring-first` is left out too. This project documents a module-level name with an
+attribute docstring under it, which the hook reads as a second module docstring, so it refuses
+those files.
`pre-commit` ships in the `dev` extra, so `uv sync --all-packages --all-extras` installs it.
Install the git hook once:
From c270f3cf8fd97c81aa54a217e0b1a86f1f33978f Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Mon, 16 Nov 2026 23:25:48 -0300
Subject: [PATCH 42/71] check that the unit test hook passes without docker by
running it against an unreachable docker host, in place of the per-file guard
check
---
backend/tests/unit/test_blueprint_catalog.py | 32 +++++------------
blueprint/tests/test_pre_commit.py | 38 ++++++++++++++++++++
2 files changed, 47 insertions(+), 23 deletions(-)
create mode 100644 blueprint/tests/test_pre_commit.py
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index dc613343..40d2db89 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -832,31 +832,17 @@ def _development_guide_pre_commit_prose() -> str:
return _development_guide_pre_commit_section().rsplit("\n|", 1)[1].split("\n", 1)[1]
-def _modules_imported_anywhere(path: Path) -> set[str]:
- """Each module a file imports, at its top or inside a function, a block or a fixture."""
- modules = set()
- for node in ast.walk(ast.parse(path.read_text())):
- if isinstance(node, ast.ImportFrom) and node.module:
- modules.add(node.module)
- elif isinstance(node, ast.Import):
- modules.update(alias.name for alias in node.names)
-
- return modules
-
-
-def test_every_test_that_starts_a_container_skips_without_docker():
- """What the development guide means when it says the unit test hook passes without Docker."""
- tests = REPO_ROOT / "backend" / "tests"
- starting = [
- path
- for path in sorted(tests.rglob("*.py"))
- if any(re.fullmatch(r"testcontainers(?:\..+)?", module) for module in _modules_imported_anywhere(path))
- ]
+def test_some_unit_tests_start_containers_through_testcontainers():
+ """The development guide's claim; `blueprint/tests/test_pre_commit.py` runs the hook without Docker to show they skip."""
+ unit = REPO_ROOT / "backend" / "tests" / "unit"
assert "`testcontainers`" in _development_guide_pre_commit_prose()
- assert any(path.is_relative_to(tests / "unit") for path in starting)
- for path in starting:
- assert re.search(r"if not is_docker_running\(\):\n\s+pytest\.skip\(", path.read_text()), path
+ assert any(
+ isinstance(node, ast.ImportFrom) and re.fullmatch(r"testcontainers(?:\..+)?", node.module or "")
+ for path in unit.rglob("*.py")
+ if path != Path(__file__).resolve()
+ for node in ast.walk(ast.parse(path.read_text()))
+ )
def test_docker_counts_as_not_running_when_its_client_cannot_connect(monkeypatch):
diff --git a/blueprint/tests/test_pre_commit.py b/blueprint/tests/test_pre_commit.py
new file mode 100644
index 00000000..46200ce2
--- /dev/null
+++ b/blueprint/tests/test_pre_commit.py
@@ -0,0 +1,38 @@
+"""The pre-commit hooks the development guide describes, run the way a contributor runs them."""
+
+import os
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+
+def _unit_test_hook() -> tuple[str, list[str]]:
+ """The directory the unit test hook runs in, and the arguments it gives pytest."""
+ config = (REPO_ROOT / ".pre-commit-config.yaml").read_text()
+ entry = r" +entry: bash -c 'cd (\S+) && uv run --no-sync pytest(.*)'\n"
+ found = re.search(rf"- id: unit_test\n(?: +[\w-]+:.*\n)*?{entry}", config)
+ assert found, config
+
+ return found[1], found[2].split()
+
+
+def test_the_unit_test_hook_passes_without_docker(tmp_path: Path):
+ """Every unit test that starts a container skips when Docker can't be reached, and the rest pass."""
+ directory, arguments = _unit_test_hook()
+ unreachable = {name: value for name, value in os.environ.items() if not name.startswith("TESTCONTAINERS")}
+ unreachable |= {"HOME": str(tmp_path), "DOCKER_HOST": "tcp://127.0.0.1:1"}
+
+ run = subprocess.run(
+ [sys.executable, "-m", "pytest", *arguments, "-q", "-n", "auto", "-p", "no:cacheprovider"],
+ cwd=REPO_ROOT / directory,
+ env=unreachable,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+
+ assert run.returncode == 0, run.stdout[-4000:]
+ assert re.search(r"\b[1-9]\d* skipped\b", run.stdout), run.stdout[-4000:]
From a66c494e5dc7e87f0abe3a0619277a2f5c1cabde Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 17 Nov 2026 00:34:48 -0300
Subject: [PATCH 43/71] read the pre-commit config and the workflows in the
catalog tests with yaml.safe_load instead of regexes, and add pyyaml and
types-pyyaml to the root dev group
---
backend/tests/unit/test_blueprint_catalog.py | 93 +++++++++++++++-----
pyproject.toml | 2 +-
uv.lock | 17 +++-
3 files changed, 89 insertions(+), 23 deletions(-)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 40d2db89..0a7ca7a9 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -26,6 +26,7 @@
from typing import Any
import pytest
+import yaml
from tests.conftest import is_docker_running
@@ -627,14 +628,42 @@ def test_no_project_receives_the_fastro_pin():
assert "fastro" not in backend.get("tool", {}).get("uv", {}).get("sources", {})
-def _pre_commit_hooks() -> list[dict[str, str]]:
- """Each hook's keys, read from its `- id:` block, with the value written on the key's own line."""
- blocks = re.findall(r"^( *)- id: (\S+)\n((?:\1 +[\w-]+:.*\n)*)", (REPO_ROOT / ".pre-commit-config.yaml").read_text(), re.M)
+def _pre_commit_repositories(config: str | None = None) -> list[dict[str, Any]]:
+ """Each `- repo:` entry of `.pre-commit-config.yaml`, parsed."""
+ parsed = yaml.safe_load((REPO_ROOT / ".pre-commit-config.yaml").read_text() if config is None else config)
+ repositories: list[dict[str, Any]] = parsed["repos"]
- return [{"id": hook, **dict(re.findall(r"^ +([\w-]+):[ ]*(.*)$", keys, re.M))} for _, hook, keys in blocks]
+ return repositories
-def _the_sync_check_hook() -> dict[str, str]:
+def _pre_commit_hooks(config: str | None = None) -> list[dict[str, Any]]:
+ return [hook for repository in _pre_commit_repositories(config) for hook in repository["hooks"]]
+
+
+def test_the_pre_commit_reader_reads_what_yaml_means_not_how_it_is_written():
+ hooks = _pre_commit_hooks(
+ "repos:\n"
+ " - repo: local\n"
+ " hooks:\n"
+ ' - id: "commented" # why\n'
+ " # a note\n"
+ " entry: run it # how\n"
+ "\n"
+ " stages: [ 'manual' ]\n"
+ " - id: listed\n"
+ " stages:\n"
+ " - manual # first\n"
+ " - pre-push\n"
+ " pass_filenames: false\n"
+ )
+
+ assert hooks == [
+ {"id": "commented", "entry": "run it", "stages": ["manual"]},
+ {"id": "listed", "stages": ["manual", "pre-push"], "pass_filenames": False},
+ ]
+
+
+def _the_sync_check_hook() -> dict[str, Any]:
hooks = [hook for hook in _pre_commit_hooks() if "fastro sync --check" in hook.get("entry", "")]
assert len(hooks) == 1, hooks
@@ -662,7 +691,7 @@ def test_a_commit_runs_sync_check_on_the_whole_tree():
assert hook["entry"] == "uv run --no-sync fastro sync --check"
assert hook["language"] == "system"
- assert hook["pass_filenames"] == "false"
+ assert hook["pass_filenames"] is False
def test_the_sync_check_hook_runs_at_every_commit():
@@ -700,13 +729,7 @@ def test_a_commit_that_touches_nothing_sync_compares_skips_sync_check():
def _hook_repositories() -> dict[str, str]:
"""Each hook id in `.pre-commit-config.yaml`, with the repository it comes from."""
- text = (REPO_ROOT / ".pre-commit-config.yaml").read_text()
-
- return {
- hook: repository
- for repository, block in re.findall(r"^ - repo: (\S+)\n((?:(?! - repo: ).*\n)*)", text, re.M)
- for hook in re.findall(r"^ *- id: ([\w-]+)", block, re.M)
- }
+ return {hook["id"]: repository["repo"] for repository in _pre_commit_repositories() for hook in repository["hooks"]}
def _development_guide_pre_commit_section() -> str:
@@ -747,7 +770,7 @@ def test_the_development_guide_says_which_hooks_are_local():
def test_the_development_guide_says_which_hooks_run_only_when_asked_for():
- manual = {hook["id"] for hook in _pre_commit_hooks() if hook.get("stages") == "[manual]"}
+ manual = {hook["id"] for hook in _pre_commit_hooks() if hook.get("stages") == ["manual"]}
assert manual
assert {hook for hook, cells in _development_guide_hook_rows().items() if "manual stage" in cells} == manual
@@ -815,7 +838,7 @@ def test_the_hooks_the_development_guide_leaves_ci_out_of_are_no_ci_step():
def test_the_development_guide_gives_the_command_each_manual_hook_runs_and_where():
- manual = [hook for hook in _pre_commit_hooks() if hook.get("stages") == "[manual]"]
+ manual = [hook for hook in _pre_commit_hooks() if hook.get("stages") == ["manual"]]
assert manual
for hook in manual:
@@ -902,7 +925,7 @@ def test_each_hook_the_development_guide_runs_by_name_is_in_the_config_at_the_st
for hook, flags in runs:
assert hook in hooks, hook
stage = re.search(r"--hook-stage (\w+)", flags)
- assert hooks[hook].get("stages", "[pre-commit]") == f"[{stage[1] if stage else 'pre-commit'}]", hook
+ assert hooks[hook].get("stages", ["pre-commit"]) == [stage[1] if stage else "pre-commit"], hook
def test_each_pre_commit_command_the_development_guide_gives_takes_the_flags_it_passes():
@@ -922,15 +945,43 @@ def test_each_pre_commit_command_the_development_guide_gives_takes_the_flags_it_
assert re.search(rf"(? list[str]:
- """Every one-line `run:` in the repository's own CI."""
+def _workflow_runs(workflows: Iterable[str] | None = None) -> list[str]:
+ """Each line every `run:` in the repository's own CI runs, a block's line by line."""
+ if workflows is None:
+ workflows = [workflow.read_text() for workflow in sorted((REPO_ROOT / ".github" / "workflows").glob("*.yml"))]
+
return [
- run.strip()
- for workflow in sorted((REPO_ROOT / ".github" / "workflows").glob("*.yml"))
- for run in re.findall(r"^\s+run: (.+)$", workflow.read_text(), re.M)
+ line.strip()
+ for workflow in workflows
+ for job in yaml.safe_load(workflow)["jobs"].values()
+ for step in job.get("steps", [])
+ for line in str(step.get("run", "")).splitlines()
+ if line.strip()
]
+def test_the_workflow_reader_reads_every_run_and_a_block_line_by_line():
+ workflow = (
+ "jobs:\n"
+ " a:\n"
+ " steps:\n"
+ " - run: uv sync # first\n"
+ " - name: named\n"
+ " run: 'uv run --no-sync pytest'\n"
+ " - name: block\n"
+ " run: |\n"
+ " echo one\n"
+ "\n"
+ " if true; then\n"
+ " echo two\n"
+ " fi\n"
+ " b:\n"
+ " uses: ./.github/workflows/other.yml\n"
+ )
+
+ assert _workflow_runs([workflow]) == ["uv sync", "uv run --no-sync pytest", "echo one", "if true; then", "echo two", "fi"]
+
+
def _defaults_blocks(workflow: str) -> list[str]:
"""Each `defaults:` block of a workflow, at any level, with its value written on the same line or below it."""
lines = workflow.splitlines()
diff --git a/pyproject.toml b/pyproject.toml
index 88cfe6a8..8d55164c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -27,7 +27,7 @@ description = "Workspace root — see backend/ and cli/ for actual packages."
requires-python = ">=3.11"
[dependency-groups]
-dev = ["fastro"]
+dev = ["fastro", "pyyaml>=6.0.2", "types-pyyaml>=6.0.12"]
[tool.uv.workspace]
members = ["backend", "cli"]
diff --git a/uv.lock b/uv.lock
index f3cd0818..c79544cf 100644
--- a/uv.lock
+++ b/uv.lock
@@ -983,12 +983,18 @@ source = { virtual = "." }
[package.dev-dependencies]
dev = [
{ name = "fastro" },
+ { name = "pyyaml" },
+ { name = "types-pyyaml" },
]
[package.metadata]
[package.metadata.requires-dev]
-dev = [{ name = "fastro", git = "https://github.com/benavlabs/fastro?rev=ddda03f1151b3233e083dd2d4354649dc997e4ec" }]
+dev = [
+ { name = "fastro", git = "https://github.com/benavlabs/fastro?rev=ddda03f1151b3233e083dd2d4354649dc997e4ec" },
+ { name = "pyyaml", specifier = ">=6.0.2" },
+ { name = "types-pyyaml", specifier = ">=6.0.12" },
+]
[[package]]
name = "fastapi-cli"
@@ -2797,6 +2803,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/3f/f9/2b3ff4e56e5fa7debfaf9eb135d0da96f3e9a1d5b27222223c7296336e5f/typer-0.25.1-py3-none-any.whl", hash = "sha256:75caa44ed46a03fb2dab8808753ffacdbfea88495e74c85a28c5eefcf5f39c89", size = 58409, upload-time = "2026-04-30T19:32:18.271Z" },
]
+[[package]]
+name = "types-pyyaml"
+version = "6.0.12.20261113"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/4d/8b/ba599d956693dbc98e170f32097128bdea0a17f9d42b0b490fa749c12b1a/types_pyyaml-6.0.12.20261113.tar.gz", hash = "sha256:0828be2580fd94151182364f4d0158e4de62fdbeeb8d4296f7f7d2b6c22bb640", size = 19017, upload-time = "2026-11-13T08:51:21.488Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fd/2e/36fc0941a40ef066dbc8abac41bbbefb41389f547c779aef832aea6b873d/types_pyyaml-6.0.12.20261113-py3-none-any.whl", hash = "sha256:3600749e613748afdc4327f0b17c3296cf880cdbc7335f320007abd9dd815f67", size = 21321, upload-time = "2026-11-13T08:51:20.417Z" },
+]
+
[[package]]
name = "typing-extensions"
version = "4.15.0"
From 44679a6b3e5bb300cb52c5d373eb30f12b4bdd1d Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 17 Nov 2026 01:01:58 -0300
Subject: [PATCH 44/71] remove the left-out path filters from the docs tests,
which only run in the full repo, test that every test reading the docs or
importing a withheld test stays in blueprint_only, and draw the diagram's
sets from verify.sets
---
backend/tests/unit/test_blueprint_catalog.py | 34 ++++++++++++
backend/tests/unit/test_docs_imports.py | 55 ++------------------
backend/tests/unit/test_docs_wiring.py | 24 ++++-----
backend/tests/unit/test_image_contents.py | 18 +------
4 files changed, 48 insertions(+), 83 deletions(-)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index 0a7ca7a9..a1434ba6 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -1053,6 +1053,40 @@ def _contributing_syncs() -> list[str]:
return re.findall(r"^\s*(?:\$\s+)?(uv sync\b.*)$", CONTRIBUTING.read_text(), re.M)
+def _imported_modules(module: str, source: str) -> set[str]:
+ """Each module a file imports, and each name it imports from one, with relative imports resolved."""
+ package = module.split(".")[:-1]
+ imported: set[str] = set()
+ for node in ast.walk(ast.parse(source)):
+ if isinstance(node, ast.Import):
+ imported.update(alias.name for alias in node.names)
+ elif isinstance(node, ast.ImportFrom):
+ anchor = package[: len(package) - node.level + 1] if node.level else []
+ base = ".".join([*anchor, *filter(None, [node.module])])
+ imported.add(base)
+ imported.update(f"{base}.{alias.name}" for alias in node.names)
+
+ return imported
+
+
+def test_every_test_that_reads_the_docs_or_imports_a_withheld_test_stays_in_the_blueprint():
+ backend = REPO_ROOT / "backend"
+ files = {".".join(path.relative_to(backend).with_suffix("").parts): path for path in (backend / "tests").rglob("*.py")}
+ withheld = {module for module, path in files.items() if _withheld(str(path.relative_to(REPO_ROOT)))}
+ reading = []
+ for module, path in sorted(files.items()):
+ source = path.read_text()
+ if re.search(r"""(?:["']|\}/|\.\./)docs["'/]""", source) or withheld & _imported_modules(module, source):
+ reading.append(path)
+
+ assert {f"test_docs_{name}.py" for name in ("imports", "recipes", "scripts", "wiring")} <= {path.name for path in reading}
+ for path in reading:
+ assert _withheld(str(path.relative_to(REPO_ROOT))), (
+ f"{path.relative_to(REPO_ROOT)} reads the docs, which describe every feature, or imports a blueprint-only test, "
+ "so it assumes the full repo: list it under [blueprint].blueprint_only in blueprint.toml"
+ )
+
+
def test_the_contributing_guide_is_the_blueprint_s_own():
assert _withheld("CONTRIBUTING.md")
diff --git a/backend/tests/unit/test_docs_imports.py b/backend/tests/unit/test_docs_imports.py
index 5516fb52..874e1ec2 100644
--- a/backend/tests/unit/test_docs_imports.py
+++ b/backend/tests/unit/test_docs_imports.py
@@ -6,8 +6,7 @@
The sweep checks that the module and the name exist, not that a relative import
counts the right number of dots: a sample rarely says which file it belongs to.
A relative import of a single name, ``.schemas``, is left alone -- which of them it
-means depends on the file it sits in, and in a project with features removed the
-name can turn unique and resolve to the wrong module.
+means depends on the file it sits in.
``ILLUSTRATIVE_MODULES`` lists the modules the guides invent to show how a project of
your own would look.
@@ -15,16 +14,13 @@
import ast
import importlib
-import importlib.util
import re
-import sys
from collections.abc import Iterator
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[3]
DOCS_ROOT = REPO_ROOT / "docs"
SRC_ROOT = REPO_ROOT / "backend" / "src"
-DRILL_PATH = REPO_ROOT / "tools" / "removal_drill.py"
PYTHON_BLOCK = re.compile(r"```python\n(.*?)```", re.DOTALL)
@@ -37,41 +33,6 @@
)
-def _manifest():
- """The drill's feature manifest, which says which paths each feature owns."""
- spec = importlib.util.spec_from_file_location("removal_drill_manifest", DRILL_PATH)
- assert spec is not None and spec.loader is not None
- manifest = importlib.util.module_from_spec(spec)
- sys.modules[spec.name] = manifest
- spec.loader.exec_module(manifest)
-
- return manifest
-
-
-def _paths_of_features_left_out() -> tuple[str, ...]:
- """The paths owned by the features this project doesn't carry, which its docs still show."""
- manifest = _manifest()
- present = {
- name
- for name, feature in manifest.FEATURES.items()
- if (sources := [path for path in feature.paths if path.startswith("backend/src")])
- and all((REPO_ROOT / path).exists() for path in sources)
- }
-
- left_out: list[str] = []
- for name, feature in manifest.FEATURES.items():
- if name not in present:
- left_out.extend(feature.paths)
- for combination, paths in feature.combination_paths.items():
- if name not in present or combination not in present:
- left_out.extend(paths)
-
- return tuple(left_out)
-
-
-LEFT_OUT_PATHS = _paths_of_features_left_out()
-
-
def _import_statements(block: str) -> Iterator[tuple[ast.ImportFrom, int]]:
"""Every ``from ... import ...`` in a code block, with the line it starts on."""
lines = block.splitlines()
@@ -103,8 +64,7 @@ def _module_path(node: ast.ImportFrom) -> Path | None:
An absolute import names its module from ``src``. A relative one names a suffix of
at least two parts, resolved when exactly one module, or one package that would
- hold it, matches. A package the project doesn't carry at all resolves to nothing,
- so a sample for a feature this project removed is left alone.
+ hold it, matches.
"""
parts = (node.module or "").split(".")
if node.level == 0:
@@ -123,7 +83,7 @@ def _module_path(node: ast.ImportFrom) -> Path | None:
if existing.exists():
return existing
- return candidate.with_suffix(".py") if candidate.parent.is_dir() else None
+ return candidate.with_suffix(".py")
suffix = "/".join(parts)
modules = [path for path in SRC_ROOT.rglob(f"{parts[-1]}.py") if str(path).endswith(f"{suffix}.py")]
@@ -160,9 +120,6 @@ def _missing(where: str, node: ast.ImportFrom, path: Path) -> list[str]:
return []
if not path.exists():
- if LEFT_OUT_PATHS and str(path.relative_to(REPO_ROOT)).startswith(LEFT_OUT_PATHS):
- return []
-
return [f"{where}: no module {dotted}"]
module = importlib.import_module(dotted)
@@ -185,11 +142,7 @@ def test_every_documented_project_import_resolves():
def test_the_sweep_reads_the_samples_it_claims_to():
- """An extractor that quietly stopped matching would make the sweep above vacuous.
-
- Counts what every project carries, the documentation, rather than what the
- selected features leave resolvable.
- """
+ """An extractor that quietly stopped matching would make the sweep above vacuous."""
blocks = [block.group(1) for document in DOCS_ROOT.rglob("*.md") for block in PYTHON_BLOCK.finditer(document.read_text())]
statements = [node for block in blocks for node, _ in _import_statements(block)]
diff --git a/backend/tests/unit/test_docs_wiring.py b/backend/tests/unit/test_docs_wiring.py
index ee5ef6c3..85fbd3b8 100644
--- a/backend/tests/unit/test_docs_wiring.py
+++ b/backend/tests/unit/test_docs_wiring.py
@@ -7,10 +7,9 @@
"""
import re
+import tomllib
from pathlib import Path
-from tests.unit.test_docs_imports import LEFT_OUT_PATHS
-
REPO_ROOT = Path(__file__).resolve().parents[3]
WIRING = REPO_ROOT / "backend" / "src" / "wiring"
STRUCTURE = REPO_ROOT / "docs" / "user-guide" / "project-structure.md"
@@ -21,12 +20,7 @@
def _wiring_modules() -> list[str]:
- """The composition root's modules, as a project that carries them has them."""
- return sorted(
- path.name
- for path in WIRING.glob("*.py")
- if path.name != "__init__.py" and f"backend/src/wiring/{path.name}" not in LEFT_OUT_PATHS
- )
+ return sorted(path.name for path in WIRING.glob("*.py") if path.name != "__init__.py")
def _tree_drawing_the_wiring() -> str:
@@ -65,11 +59,11 @@ def test_the_diagram_draws_every_module_of_the_composition_root():
assert [name for name in _wiring_modules() if name not in drawn] == []
-def test_the_diagram_names_every_preset_the_drill_runs():
- """A preset added to the matrix and not to the picture is a diagram that has aged."""
- drill = (REPO_ROOT / "tools" / "removal_drill.py").read_text()
- presets = re.findall(r'^ "([a-z0-9-]+)": \(', drill, re.M)
- drawn = DIAGRAMS.read_text()
+def test_the_diagram_names_every_set_verify_sets_declares():
+ """A set added to `[verify.sets]` and not to the picture is a diagram that has aged."""
+ with (REPO_ROOT / "blueprint.toml").open("rb") as handle:
+ sets = tomllib.load(handle)["verify"]["sets"]
+ drawn = set(re.findall(r">([a-z0-9-]+)", DIAGRAMS.read_text()))
- assert presets, "no presets found in the drill"
- assert [preset for preset in presets if "-" in preset and preset not in drawn] == []
+ assert sets
+ assert [name for name in sets if name not in drawn] == []
diff --git a/backend/tests/unit/test_image_contents.py b/backend/tests/unit/test_image_contents.py
index 425fa24f..adfe5819 100644
--- a/backend/tests/unit/test_image_contents.py
+++ b/backend/tests/unit/test_image_contents.py
@@ -12,8 +12,6 @@
import re
from pathlib import Path
-from tests.unit.test_docs_imports import LEFT_OUT_PATHS
-
REPO_ROOT = Path(__file__).resolve().parents[3]
DOCKERFILE = REPO_ROOT / "backend" / "Dockerfile"
DOCS_ROOT = REPO_ROOT / "docs"
@@ -47,23 +45,9 @@ def test_alembic_finds_its_configuration_from_the_working_directory_the_stages_u
assert "ENV ALEMBIC_CONFIG=/app/alembic.ini" in stage
-def _carried_by_this_project(module: str) -> bool:
- """Whether this project still has the script, rather than having removed its feature.
-
- The documentation describes every feature, so a build without one still shows commands
- for scripts it no longer carries.
- """
- return f"backend/scripts/{module.split('.')[1]}.py" not in LEFT_OUT_PATHS
-
-
def test_every_script_the_docs_run_in_a_container_exists():
"""The module name in the documented command has to name a file the image copies."""
- documented = {
- module
- for page in DOCS_ROOT.rglob("*.md")
- for module in RUN_IN_A_CONTAINER.findall(page.read_text())
- if _carried_by_this_project(module)
- }
+ documented = {module for page in DOCS_ROOT.rglob("*.md") for module in RUN_IN_A_CONTAINER.findall(page.read_text())}
assert documented, "no documented in-container script run found"
assert [module for module in sorted(documented) if not (SCRIPTS / f"{module.split('.')[1]}.py").exists()] == []
From d5b74fb38d2db424f450dda088a8a36a11f598a9 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 17 Nov 2026 02:00:38 -0300
Subject: [PATCH 45/71] cap fastapi below 0.140.7, the first release the app
can't import, and test that every fastapi a project could install is one the
app imports
---
backend/pyproject.toml | 2 +-
backend/tests/unit/test_blueprint_catalog.py | 24 ++++++++++++++++++++
blueprint.toml | 2 +-
docs/changelog.md | 5 ++++
pyproject.toml | 2 +-
uv.lock | 4 +++-
6 files changed, 35 insertions(+), 4 deletions(-)
diff --git a/backend/pyproject.toml b/backend/pyproject.toml
index f26c53ea..27fad392 100644
--- a/backend/pyproject.toml
+++ b/backend/pyproject.toml
@@ -17,7 +17,7 @@ dependencies = [
"asyncpg>=0.30.0",
"crudauth[all]>=0.8.2,<0.9.0",
"cryptography>=42.0.0",
- "fastapi[standard]>=0.115.8",
+ "fastapi[standard]>=0.115.8,<0.140.7",
"fastcrud>=0.21.0",
"greenlet>=3.1.1",
"itsdangerous>=2.2.0",
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index a1434ba6..aa898ce1 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -27,6 +27,7 @@
import pytest
import yaml
+from packaging.requirements import Requirement
from tests.conftest import is_docker_running
@@ -117,6 +118,29 @@ def test_the_dependencies_a_project_could_install_are_the_ones_the_backend_decla
assert _declared_specifiers("dev") == set(backend["project"]["optional-dependencies"]["dev"])
+FASTAPI_THE_APP_NEEDS = {
+ "get_flat_dependant": ("src/infrastructure/cache/utils.py", "0.140.7"),
+ "openapi_prefix": ("src/infrastructure/app_factory.py", "0.145.0"),
+}
+"""Each FastAPI name the app relies on, the file that uses it, and the first release without it."""
+
+
+def test_every_fastapi_a_project_could_install_is_one_the_app_can_import():
+ """A project resolves its dependencies fresh, so the declared range, not the lock, decides which FastAPI it gets."""
+ with (REPO_ROOT / "uv.lock").open("rb") as handle:
+ locked = next(package["version"] for package in tomllib.load(handle)["package"] if package["name"] == "fastapi")
+ ranges = [Requirement(specifier).specifier for specifier in _declared_specifiers() if _distribution(specifier) == "fastapi"]
+
+ assert ranges
+ for name, (path, first_without) in FASTAPI_THE_APP_NEEDS.items():
+ assert name in (REPO_ROOT / "backend" / path).read_text(), (name, path)
+ for allowed in ranges:
+ assert first_without not in allowed, (allowed, name)
+ for allowed in ranges:
+ assert "999.0" not in allowed, allowed
+ assert locked in allowed, (allowed, locked)
+
+
def _distribution(specifier: str) -> str:
"""The distribution a PEP 508 specifier names, without its extras or its version."""
return re.split(r"[\[<>=!~;]", specifier)[0].strip().lower().replace("_", "-")
diff --git a/blueprint.toml b/blueprint.toml
index e288ab91..7d3bafcc 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -39,7 +39,7 @@ runtime = [
"anyio>=4.15.1",
"asyncpg>=0.30.0",
"crudauth[all]>=0.8.2,<0.9.0",
- "fastapi[standard]>=0.115.8",
+ "fastapi[standard]>=0.115.8,<0.140.7",
"fastcrud>=0.21.0",
"greenlet>=3.1.1",
"pydantic>=2.10.6",
diff --git a/docs/changelog.md b/docs/changelog.md
index 8684fe1b..58fceec9 100644
--- a/docs/changelog.md
+++ b/docs/changelog.md
@@ -12,6 +12,11 @@ ___
#### Changed
+- **FastAPI is capped below 0.140.7.** The app imports `get_flat_dependant` from
+ `fastapi.dependencies.utils`, which 0.140.7 removed, and passes `openapi_prefix` to `FastAPI`,
+ which 0.145.0 refuses. A project resolves its own dependencies, so without the cap a new one got
+ the newest FastAPI and couldn't import the app. The lock still holds 0.136.1. A later release
+ moves off both and lifts the cap.
- **`virtualenv` 21.14.13 and `filelock` 4.2.4**, for eighteen advisories published against the
versions the lock held. Both arrive through `pre-commit`, which lives in the `dev` extra, so the
image installs neither and a deployment is unaffected: the advisories are about the environments
diff --git a/pyproject.toml b/pyproject.toml
index 8d55164c..0ffcd34e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -27,7 +27,7 @@ description = "Workspace root — see backend/ and cli/ for actual packages."
requires-python = ">=3.11"
[dependency-groups]
-dev = ["fastro", "pyyaml>=6.0.2", "types-pyyaml>=6.0.12"]
+dev = ["fastro", "packaging>=24.0", "pyyaml>=6.0.2", "types-pyyaml>=6.0.12"]
[tool.uv.workspace]
members = ["backend", "cli"]
diff --git a/uv.lock b/uv.lock
index c79544cf..07f11706 100644
--- a/uv.lock
+++ b/uv.lock
@@ -921,7 +921,7 @@ requires-dist = [
{ name = "crudauth", extras = ["all"], specifier = ">=0.8.2,<0.9.0" },
{ name = "cryptography", specifier = ">=42.0.0" },
{ name = "faker", marker = "extra == 'dev'", specifier = ">=37.1.0" },
- { name = "fastapi", extras = ["standard"], specifier = ">=0.115.8" },
+ { name = "fastapi", extras = ["standard"], specifier = ">=0.115.8,<0.140.7" },
{ name = "fastcrud", specifier = ">=0.21.0" },
{ name = "greenlet", specifier = ">=3.1.1" },
{ name = "httpx", marker = "extra == 'dev'", specifier = ">=0.28.1" },
@@ -983,6 +983,7 @@ source = { virtual = "." }
[package.dev-dependencies]
dev = [
{ name = "fastro" },
+ { name = "packaging" },
{ name = "pyyaml" },
{ name = "types-pyyaml" },
]
@@ -992,6 +993,7 @@ dev = [
[package.metadata.requires-dev]
dev = [
{ name = "fastro", git = "https://github.com/benavlabs/fastro?rev=ddda03f1151b3233e083dd2d4354649dc997e4ec" },
+ { name = "packaging", specifier = ">=24.0" },
{ name = "pyyaml", specifier = ">=6.0.2" },
{ name = "types-pyyaml", specifier = ">=6.0.12" },
]
From 37633accb18f9201f3873d8c526560361c6a89ec Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 17 Nov 2026 02:16:39 -0300
Subject: [PATCH 46/71] register the tracing recipe's installer under
fastro.toml's app contributions and run fastro sync, have install configure
tracing itself, and replace the drill's tracing tests with a blueprint test
that follows the recipe in a copy
---
backend/tests/unit/test_docs_imports.py | 1 -
backend/tests/unit/test_removal_drill.py | 21 -----
blueprint/tests/conftest.py | 42 +++++++++
blueprint/tests/test_fastro.py | 36 ++------
blueprint/tests/test_observability_recipe.py | 95 ++++++++++++++++++++
docs/changelog.md | 5 ++
docs/user-guide/observability.md | 42 ++++-----
7 files changed, 168 insertions(+), 74 deletions(-)
create mode 100644 blueprint/tests/conftest.py
create mode 100644 blueprint/tests/test_observability_recipe.py
diff --git a/backend/tests/unit/test_docs_imports.py b/backend/tests/unit/test_docs_imports.py
index 874e1ec2..22c5104a 100644
--- a/backend/tests/unit/test_docs_imports.py
+++ b/backend/tests/unit/test_docs_imports.py
@@ -29,7 +29,6 @@
"src.modules.reports",
"src.modules.user.routes_v2",
"src.interfaces.api.v2",
- "src.infrastructure.observability",
)
diff --git a/backend/tests/unit/test_removal_drill.py b/backend/tests/unit/test_removal_drill.py
index eb3bce9d..0a9f52a2 100644
--- a/backend/tests/unit/test_removal_drill.py
+++ b/backend/tests/unit/test_removal_drill.py
@@ -254,24 +254,3 @@ def test_the_generator_rebuilds_what_this_project_committed():
continue
assert _without_formatting(getattr(drill, generator)(present)) == _without_formatting(committed.read_text()), name
-
-
-TRACING_RECIPE = BACKEND_ROOT.parent / "docs/user-guide/observability.md"
-"""The one guide that asks a reader to install something of their own on the app."""
-
-
-def test_a_rebuild_leaves_the_composition_root_as_it_is(tmp_path):
- """That recipe wires its installer there, where no regeneration reaches it."""
- project = drill.build("core-only", tmp_path)
-
- rebuilt = project / "backend/src/interfaces/main.py"
-
- assert rebuilt.read_text() == (BACKEND_ROOT / "src/interfaces/main.py").read_text()
-
-
-def test_the_tracing_recipe_wires_itself_outside_the_generated_wiring():
- """Written into ``INSTALLERS`` instead, it would fail the comparison above."""
- recipe = TRACING_RECIPE.read_text()
-
- assert "installers=(*INSTALLERS, tracing_install)" in recipe
- assert "INSTALLERS: tuple" not in recipe
diff --git a/blueprint/tests/conftest.py b/blueprint/tests/conftest.py
new file mode 100644
index 00000000..deb38cfb
--- /dev/null
+++ b/blueprint/tests/conftest.py
@@ -0,0 +1,42 @@
+import shutil
+import subprocess
+import sys
+from collections.abc import Callable
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+Fastro = Callable[..., subprocess.CompletedProcess[str]]
+
+
+@pytest.fixture
+def tracked_tree(tmp_path: Path) -> Path:
+ """A copy of every file git tracks or would track, so a test can change it freely."""
+ destination = tmp_path / "blueprint"
+ listed = subprocess.run(
+ ["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ check=True,
+ ).stdout
+ for name in filter(None, listed.split("\0")):
+ source = REPO_ROOT / name
+ if source.is_file():
+ (destination / name).parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(source, destination / name)
+
+ return destination
+
+
+@pytest.fixture
+def fastro() -> Fastro:
+ """Run the fastro the repository root installs, in a directory of the caller's choosing."""
+
+ def run(*arguments: str, cwd: Path) -> subprocess.CompletedProcess[str]:
+ command = [sys.executable, "-m", "fastro", *arguments]
+ return subprocess.run(command, cwd=cwd, capture_output=True, text=True, check=False)
+
+ return run
diff --git a/blueprint/tests/test_fastro.py b/blueprint/tests/test_fastro.py
index 37e2fa76..4ea1dcd0 100644
--- a/blueprint/tests/test_fastro.py
+++ b/blueprint/tests/test_fastro.py
@@ -1,45 +1,23 @@
"""What the fastro the repository root installs gives the people who work on the blueprint."""
-import shutil
-import subprocess
-import sys
import tomllib
from pathlib import Path
-REPO_ROOT = Path(__file__).resolve().parents[2]
-
-
-def _fastro(*arguments: str, cwd: Path) -> subprocess.CompletedProcess[str]:
- return subprocess.run([sys.executable, "-m", "fastro", *arguments], cwd=cwd, capture_output=True, text=True, check=False)
+from conftest import Fastro
-
-def _tree(destination: Path) -> Path:
- listed = subprocess.run(
- ["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"],
- cwd=REPO_ROOT,
- capture_output=True,
- text=True,
- check=True,
- ).stdout
- for name in filter(None, listed.split("\0")):
- source = REPO_ROOT / name
- if source.is_file():
- (destination / name).parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(source, destination / name)
-
- return destination
+REPO_ROOT = Path(__file__).resolve().parents[2]
-def test_plain_sync_regenerates_what_the_check_compares(tmp_path: Path):
+def test_plain_sync_regenerates_what_the_check_compares(tracked_tree: Path, fastro: Fastro):
"""CONTRIBUTING.md sends a failed `fastro sync --check` to `fastro sync`."""
- tree = _tree(tmp_path / "blueprint")
+ tree = tracked_tree
wiring = tree / tomllib.loads((tree / "blueprint.toml").read_text())["wiring"][0]["path"]
generated = wiring.read_text()
wiring.write_text(generated + "\nedited = True\n")
- assert _fastro("sync", "--check", cwd=tree).returncode == 1
+ assert fastro("sync", "--check", cwd=tree).returncode == 1
- synced = _fastro("sync", cwd=tree)
+ synced = fastro("sync", cwd=tree)
assert synced.returncode == 0, synced.stderr
- assert _fastro("sync", "--check", cwd=tree).returncode == 0
+ assert fastro("sync", "--check", cwd=tree).returncode == 0
diff --git a/blueprint/tests/test_observability_recipe.py b/blueprint/tests/test_observability_recipe.py
new file mode 100644
index 00000000..be4fd69c
--- /dev/null
+++ b/blueprint/tests/test_observability_recipe.py
@@ -0,0 +1,95 @@
+"""The observability guide's tracing recipe, followed in a copy of the repository."""
+
+import ast
+import re
+import tomllib
+from pathlib import Path
+
+from conftest import Fastro
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+RECIPE = REPO_ROOT / "docs" / "user-guide" / "observability.md"
+
+
+def _blocks(language: str) -> list[str]:
+ return [str(block) for block in re.findall(rf"^```{language}\n(.*?)^```$", RECIPE.read_text(), re.M | re.S)]
+
+
+def _block(language: str) -> str:
+ blocks = _blocks(language)
+ assert len(blocks) == 1, f"expected one {language} block in the recipe, found {len(blocks)}"
+
+ return blocks[0]
+
+
+def _python_block_defining(name: str) -> str:
+ for block in _blocks("python"):
+ if any(isinstance(node, ast.FunctionDef) and node.name == name for node in ast.parse(block).body):
+ return block
+ raise AssertionError(f"no python block in the recipe defines {name}()")
+
+
+def _installers_slot() -> tuple[str, str]:
+ """The wiring file whose slot holds the installers point, and that slot's name."""
+ catalog = tomllib.loads((REPO_ROOT / "blueprint.toml").read_text())
+ return next(
+ (wiring["path"], slot["name"])
+ for wiring in catalog["wiring"]
+ for slot in wiring.get("slots", [])
+ if slot.get("point") == "installers"
+ )
+
+
+def test_the_recipe_registers_its_installer_through_fastro_toml_and_a_sync(tracked_tree: Path, fastro: Fastro):
+ project = tracked_tree
+ wiring_file, slot = _installers_slot()
+ registration = _block("toml")
+ reference = re.search(r'installers = \["([\w.]+):(\w+) as (\w+)"\]', registration)
+ assert reference, registration
+ module, function, alias = reference.groups()
+ (project / "backend" / f"{module.replace('.', '/')}.py").write_text(_python_block_defining(function))
+ with (project / "fastro.toml").open("a") as handle:
+ handle.write(f"\n{registration}")
+ wiring_path = project / wiring_file
+
+ synced = fastro("sync", cwd=project)
+ wiring = wiring_path.read_text()
+
+ assert synced.returncode == 0, synced.stdout + synced.stderr
+ assert f"from ..{module.removeprefix('src.')} import {function} as {alias}" in wiring
+ installers = re.search(rf"^{slot}\b.*?= \(\n(.*?)^\)", wiring, re.M | re.S)
+ assert installers, wiring
+ assert installers[1].splitlines()[-1].strip() == f"{alias},", installers[1]
+ recipe = RECIPE.read_text()
+ assert {f"`{alias}`", f"`{slot}`", f"`{wiring_file.removeprefix('backend/')}`", "`fastro sync --check`"} <= set(
+ re.findall(r"`[^`\n]+`", recipe)
+ )
+ assert re.search(rf"^\| [^|]*\| `{re.escape(wiring_file)}` \|$", recipe, re.M)
+ assert re.search(r"^\| [^|]*\| `fastro.toml`, under `\[app.contributes\]` \|$", recipe, re.M)
+ assert fastro("sync", "--check", cwd=project).returncode == 0
+ assert any("fastro sync" in block.splitlines() for block in _blocks("bash"))
+
+ wiring_path.write_text(wiring.replace(f" {alias},\n", ""))
+ assert fastro("sync", "--check", cwd=project).returncode == 1
+ assert fastro("sync", cwd=project).returncode == 0
+ assert wiring_path.read_text() == wiring
+
+
+def test_the_registered_module_is_the_one_the_recipe_writes():
+ registration = _block("toml")
+ module = re.search(r'installers = \["([\w.]+):', registration)
+ assert module, registration
+ path = f"backend/{module[1].replace('.', '/')}.py"
+
+ assert f"`{path.removeprefix('backend/')}`" in RECIPE.read_text()
+ assert re.search(rf'^paths = \["{re.escape(path)}"\]$', registration, re.M), registration
+
+
+def test_the_installer_configures_tracing_before_it_instruments_the_app():
+ """Registered as an installer, `install` is all the app calls, so it has to configure Logfire itself."""
+ module = ast.parse(_python_block_defining("install"))
+ install = next(node for node in module.body if isinstance(node, ast.FunctionDef) and node.name == "install")
+ calls = [ast.unparse(node.func) for node in ast.walk(install) if isinstance(node, ast.Call)]
+
+ assert any(isinstance(node, ast.FunctionDef) and node.name == "configure_tracing" for node in module.body)
+ assert calls.index("configure_tracing") < calls.index("logfire.instrument_fastapi"), calls
diff --git a/docs/changelog.md b/docs/changelog.md
index 58fceec9..c79176b7 100644
--- a/docs/changelog.md
+++ b/docs/changelog.md
@@ -12,6 +12,11 @@ ___
#### Changed
+- **The tracing recipe registers its installer in `fastro.toml`.**
+ [Observability](user-guide/observability.md) used to have you call `configure_tracing()` and add
+ the installer in `src/interfaces/main.py`. Now `install()` configures tracing itself, and you
+ list it under `[app.contributes]` and run `fastro sync`, which adds it to the generated
+ `src/wiring/app.py`.
- **FastAPI is capped below 0.140.7.** The app imports `get_flat_dependant` from
`fastapi.dependencies.utils`, which 0.140.7 removed, and passes `openapi_prefix` to `FastAPI`,
which 0.145.0 refuses. A project resolves its own dependencies, so without the cap a new one got
diff --git a/docs/user-guide/observability.md b/docs/user-guide/observability.md
index ee96e657..75cc9534 100644
--- a/docs/user-guide/observability.md
+++ b/docs/user-guide/observability.md
@@ -59,33 +59,29 @@ def configure_tracing() -> None:
def install(app: FastAPI) -> None:
- """Trace every request this app serves, except the probes."""
+ """Configure tracing, then trace every request this app serves, except the probes."""
+ configure_tracing()
logfire.instrument_fastapi(app, excluded_urls=["/health", "/health/ready"])
```
-Then wire it where this app is composed, in `src/interfaces/main.py`:
+Then register the installer in the project's `fastro.toml`, and regenerate the wiring:
-```python
-from ..infrastructure.observability import configure_tracing, install as tracing_install
-
-configure_tracing()
-
-app = create_application(
- router=router,
- settings=settings,
- lifespan=lifespan_with_security,
- root_routers=ROOT_ROUTERS,
- installers=(*INSTALLERS, tracing_install),
- docs_guard=DOCS_GUARD,
-)
+```toml
+[app]
+paths = ["backend/src/infrastructure/observability.py"]
+
+[app.contributes]
+installers = ["src.infrastructure.observability:install as tracing_install"]
+```
+
+```bash
+fastro sync
```
-Not `src/wiring/app.py`. The removal drill generates the wiring modules from
-`tools/removal_drill.py`, and `tests/unit/test_removal_drill.py` compares what it generates with
-what the project committed, so an installer written into `INSTALLERS` by hand fails that test.
-`main.py` is the composition root, and nothing regenerates it. A project that would rather have
-the generator know about this one makes it a feature
-([below](#if-you-turn-this-into-a-feature)).
+`fastro sync` adds `tracing_install` to `INSTALLERS` in `src/wiring/app.py`, after the features'
+installers, and the app calls it as it's built. Don't write it into `src/wiring/app.py` by hand:
+fastro generates that file from `fastro.toml`, so `fastro sync --check` fails on a hand edit and
+the next `fastro sync` undoes it. `[app].paths` marks the module as your own code.
`send_to_logfire="if-token-present"` is what keeps it off: with no `LOGFIRE_TOKEN` in the
environment, nothing leaves the process, which is the same rule every other optional thing in this
@@ -162,8 +158,8 @@ A project that wants observability to be removable like the others gives it a `F
| Refused-login audit hooks | `backend/src/infrastructure/auth/audit.py` |
| API-key usage rows | `backend/src/modules/api_keys/usage.py` |
| The catch-all handler and its support id | `backend/src/modules/common/utils/error_handler.py` |
-| Where this recipe wires its installer | `backend/src/interfaces/main.py` |
-| Where a feature's installer is wired | `backend/src/wiring/app.py` |
+| Where this recipe registers its installer | `fastro.toml`, under `[app.contributes]` |
+| Where every installer is wired, generated by `fastro sync` | `backend/src/wiring/app.py` |
---
From b03038b4bb3df29478c0e46a0a9ba64632cce12d Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 17 Nov 2026 02:28:07 -0300
Subject: [PATCH 47/71] say in the observability guide how a generated project
adds the tracing installer until fastro syncs projects, test that the pinned
fastro still can't, and test the worker note and the feature section
---
blueprint/tests/test_observability_recipe.py | 89 ++++++++++++++++++++
docs/user-guide/observability.md | 25 ++++--
2 files changed, 105 insertions(+), 9 deletions(-)
diff --git a/blueprint/tests/test_observability_recipe.py b/blueprint/tests/test_observability_recipe.py
index be4fd69c..e9148f5b 100644
--- a/blueprint/tests/test_observability_recipe.py
+++ b/blueprint/tests/test_observability_recipe.py
@@ -5,6 +5,7 @@
import tomllib
from pathlib import Path
+import pytest
from conftest import Fastro
REPO_ROOT = Path(__file__).resolve().parents[2]
@@ -93,3 +94,91 @@ def test_the_installer_configures_tracing_before_it_instruments_the_app():
assert any(isinstance(node, ast.FunctionDef) and node.name == "configure_tracing" for node in module.body)
assert calls.index("configure_tracing") < calls.index("logfire.instrument_fastapi"), calls
+
+
+@pytest.mark.parametrize("arguments", [("sync",), ("sync", "--check")])
+def test_the_pinned_fastro_cannot_sync_a_project_yet(tracked_tree: Path, fastro: Fastro, arguments: tuple[str, ...]):
+ """The recipe's hand-edit fallback is there only while this holds; when it fails, delete that sentence."""
+ config = tracked_tree / "fastro.toml"
+ config.write_text(re.sub(r"^source = true\n", "", config.read_text(), flags=re.M))
+
+ synced = fastro(*arguments, cwd=tracked_tree)
+
+ assert f"`fastro {' '.join(arguments)}`" in RECIPE.read_text()
+ assert synced.returncode != 0
+ assert "fastro sync in a project isn't here yet" in synced.stdout + synced.stderr, (
+ "the pinned fastro syncs projects now: drop the main.py fallback sentence from observability.md"
+ )
+
+
+def test_the_hand_edit_fallback_names_the_lines_main_py_has_and_the_recipe_registers(tracked_tree: Path):
+ recipe = RECIPE.read_text()
+ reference = re.search(r'installers = \["([\w.]+):(\w+) as (\w+)"\]', _block("toml"))
+ assert reference, recipe
+ module, function, alias = reference.groups()
+ importing = f"from ..{module.removeprefix('src.')} import {function} as {alias}"
+ passed, replaced = re.findall(r"`(installers=[^`]+,)`", recipe)
+ main = tracked_tree / "backend" / "src" / "interfaces" / "main.py"
+ source = main.read_text()
+
+ assert f"`{importing}`" in recipe
+ assert f"`{main.relative_to(tracked_tree / 'backend')}`" in recipe
+ assert "`fastro sync`" in recipe and "project-mode sync" in recipe
+ assert source.count(f" {passed}\n") == 1, passed
+ assert replaced == f"installers=(*INSTALLERS, {alias}),", replaced
+ edited = f"{importing}\n{source.replace(f' {passed}', f' {replaced}')}"
+ ast.parse(edited)
+
+
+def test_the_worker_note_names_the_worker_module_and_a_call_configure_tracing_takes():
+ recipe = RECIPE.read_text()
+ command = re.search(r"`taskiq worker (src(?:\.\w+)+):(\w+)`", recipe)
+ assert command, recipe
+ worker = REPO_ROOT / "backend" / f"{command[1].replace('.', '/')}.py"
+ tree = ast.parse(worker.read_text())
+ bound = {
+ target.id
+ for node in tree.body
+ if isinstance(node, ast.Assign)
+ for target in node.targets
+ if isinstance(target, ast.Name)
+ }
+ bound |= {alias.asname or alias.name for node in tree.body if isinstance(node, ast.ImportFrom) for alias in node.names}
+ imported = {node.module for node in ast.walk(tree) if isinstance(node, ast.ImportFrom)}
+ imported |= {alias.name for node in ast.walk(tree) if isinstance(node, ast.Import) for alias in node.names}
+ call = re.search(r"`(configure_tracing\([^`]*\))`", recipe)
+ assert call, recipe
+ configure = next(
+ node
+ for node in ast.parse(_python_block_defining("configure_tracing")).body
+ if isinstance(node, ast.FunctionDef) and node.name == "configure_tracing"
+ )
+ given = ast.parse(call[1], mode="eval").body
+ assert isinstance(given, ast.Call)
+
+ assert command[2] in bound
+ assert f"`{worker.relative_to(REPO_ROOT / 'backend')}`" in recipe
+ assert not any(module and module.endswith("interfaces.main") for module in imported)
+ assert {keyword.arg for keyword in given.keywords} <= {argument.arg for argument in configure.args.args}
+ assert given.keywords
+ defaults = dict(
+ zip([argument.arg for argument in configure.args.args][-len(configure.args.defaults) :], configure.args.defaults)
+ )
+ for keyword in given.keywords:
+ assert ast.literal_eval(keyword.value) != ast.literal_eval(defaults[keyword.arg]), keyword.arg
+
+
+def test_the_feature_section_names_the_tables_a_feature_is_declared_with():
+ """A project's own code is `[app]`; a feature lives in the blueprint's catalog, with these tables."""
+ section = RECIPE.read_text().split("## If you turn this into a feature", 1)[1].split("\n## ", 1)[0]
+ catalog = tomllib.loads((REPO_ROOT / "blueprint.toml").read_text())
+ feature = re.search(r"`\[features\.(\w+)\]`", section)
+ assert feature, section
+ name = feature[1]
+
+ assert "tools/removal_drill.py" not in section
+ assert "`blueprint.toml`" in section and "`[app]`" in section
+ assert "`paths`" in section and f"`[features.{name}.contributes]`" in section
+ assert any(
+ "paths" in declared and "installers" in declared.get("contributes", {}) for declared in catalog["features"].values()
+ )
diff --git a/docs/user-guide/observability.md b/docs/user-guide/observability.md
index 75cc9534..1ae6e926 100644
--- a/docs/user-guide/observability.md
+++ b/docs/user-guide/observability.md
@@ -44,10 +44,10 @@ from .config.settings import settings
from .database.session import get_engine
-def configure_tracing() -> None:
+def configure_tracing(service_name: str = "api") -> None:
"""Configure Logfire and instrument the clients this app talks through."""
logfire.configure(
- service_name="api",
+ service_name=service_name,
environment=settings.ENVIRONMENT.value,
send_to_logfire="if-token-present",
console=False,
@@ -83,6 +83,12 @@ installers, and the app calls it as it's built. Don't write it into `src/wiring/
fastro generates that file from `fastro.toml`, so `fastro sync --check` fails on a hand edit and
the next `fastro sync` undoes it. `[app].paths` marks the module as your own code.
+In a generated project, `fastro sync` and `fastro sync --check` need a fastro release with
+project-mode sync, so until one ships, add
+`from ..infrastructure.observability import install as tracing_install` to `src/interfaces/main.py`
+and change its `installers=INSTALLERS,` line to `installers=(*INSTALLERS, tracing_install),`, then
+undo that edit the first time you run `fastro sync`, or the app installs tracing twice.
+
`send_to_logfire="if-token-present"` is what keeps it off: with no `LOGFIRE_TOKEN` in the
environment, nothing leaves the process, which is the same rule every other optional thing in this
project follows — a setting that enables something is off when unset. `LOGFIRE_TOKEN`,
@@ -91,10 +97,10 @@ are defaults a deployment can override without touching the code.
!!! note "The worker is a second process"
`taskiq worker src.infrastructure.taskiq.worker:default_broker` never imports `main.py`,
- so none of the above runs there. Call `configure_tracing()` in
- `src/infrastructure/taskiq/worker.py` as well, with `service_name="worker"`, and the two
- processes report separately. A task enqueued by a request is not joined to that request's trace
- unless you propagate the context yourself (`logfire.propagate`).
+ so none of the above runs there. Call `configure_tracing(service_name="worker")` in
+ `src/infrastructure/taskiq/worker.py` as well, and the two processes report separately. A task
+ enqueued by a request is not joined to that request's trace unless you propagate the context
+ yourself (`logfire.propagate`).
## What not to send
@@ -144,9 +150,10 @@ proxy's own access logs already cover whether the app is up and how fast it answ
## If you turn this into a feature
-A project that wants observability to be removable like the others gives it a `FEATURES` entry in
-`tools/removal_drill.py` — the `observability` module, its tests, and its contribution to
-`src/wiring/app.py` — and settings that are off when unset. See
+In a project, the module above is your own code, under `[app]`. Observability becomes a removable
+feature only in FastAPI-boilerplate itself, as a `[features.observability]` table in its
+`blueprint.toml`: its `paths` own the module and its tests, `[features.observability.contributes]`
+lists the installer, and its settings are off when unset. See
[Composable Features](composable-features.md).
## Key Files
From b8817f15ca843ac0118936ab720a6bb25d20b15d Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 17 Nov 2026 02:31:45 -0300
Subject: [PATCH 48/71] hold the overlay test's loader in a variable and call
get_source on it, so mypy no longer sees an optional loader
---
blueprint/tests/test_overlay.py | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/blueprint/tests/test_overlay.py b/blueprint/tests/test_overlay.py
index 800d1fcd..4d9c1064 100644
--- a/blueprint/tests/test_overlay.py
+++ b/blueprint/tests/test_overlay.py
@@ -120,8 +120,9 @@ def test_no_two_overlay_files_land_on_one_path():
@pytest.mark.parametrize("path", [str(path.relative_to(OVERLAY)) for path in _files() if path.suffix == ".j2"])
def test_every_template_reads_only_what_the_tool_passes(path: str):
"""Spec 6.2: the context is fixed, so a template that asks for anything else renders nothing."""
- environment = Environment(loader=FileSystemLoader(OVERLAY), undefined=StrictUndefined, keep_trailing_newline=True)
- source = environment.loader.get_source(environment, path)[0]
+ loader = FileSystemLoader(OVERLAY)
+ environment = Environment(loader=loader, undefined=StrictUndefined, keep_trailing_newline=True)
+ source = loader.get_source(environment, path)[0]
assert meta.find_undeclared_variables(environment.parse(source)) <= CONTEXT_NAMES
From 04b505f25a483d740c7c01b859e43362d93e6eba Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 17 Nov 2026 02:37:31 -0300
Subject: [PATCH 49/71] type-check blueprint/tests in ci and test that ci
type-checks every blueprint test directory it runs
---
.github/workflows/type-checking.yml | 6 ++++++
backend/tests/unit/test_blueprint_catalog.py | 19 +++++++++++++++++++
2 files changed, 25 insertions(+)
diff --git a/.github/workflows/type-checking.yml b/.github/workflows/type-checking.yml
index 56698fda..cdcefaa2 100644
--- a/.github/workflows/type-checking.yml
+++ b/.github/workflows/type-checking.yml
@@ -40,3 +40,9 @@ jobs:
env:
ENVIRONMENT: local
SECRET_KEY: test-secret-key-for-testing-only
+
+ - name: Mypy (blueprint tests)
+ run: uv run --no-sync mypy blueprint/tests
+ env:
+ ENVIRONMENT: local
+ SECRET_KEY: test-secret-key-for-testing-only
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index aa898ce1..fe8808b4 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -1006,6 +1006,25 @@ def test_the_workflow_reader_reads_every_run_and_a_block_line_by_line():
assert _workflow_runs([workflow]) == ["uv sync", "uv run --no-sync pytest", "echo one", "if true; then", "echo two", "fi"]
+def test_ci_type_checks_the_blueprint_tests_it_runs():
+ """A test file nobody type-checks can drift from the code it reads, and only fail when it runs."""
+ runs = _workflow_runs()
+ tested = {
+ argument.rstrip("/")
+ for run in runs
+ if run.startswith("uv run --no-sync pytest ")
+ for argument in run.split()[4:]
+ if argument.startswith("blueprint/")
+ }
+ checked = [run.split()[4:] for run in runs if run.startswith("uv run --no-sync mypy ")]
+
+ assert tested
+ for directory in tested:
+ assert any(
+ directory == path.rstrip("/") or directory.startswith(path.rstrip("/") + "/") for paths in checked for path in paths
+ ), directory
+
+
def _defaults_blocks(workflow: str) -> list[str]:
"""Each `defaults:` block of a workflow, at any level, with its value written on the same line or below it."""
lines = workflow.splitlines()
From 3d01bb219057828633247624245bf299e23a9dd7 Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 17 Nov 2026 16:17:20 -0300
Subject: [PATCH 50/71] name the blueprint fastapi-boilerplate in
blueprint.toml and fastro.toml's pin, and pin the new name in the catalog
test
---
backend/tests/unit/test_blueprint_catalog.py | 2 +-
blueprint.toml | 2 +-
blueprint/tests/test_deploy_templates.py | 2 +-
fastro.toml | 2 +-
4 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index fe8808b4..b20d5fee 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -64,7 +64,7 @@ def _drill():
def test_the_catalog_parses():
- assert _catalog()["blueprint"]["name"] == "fastro"
+ assert _catalog()["blueprint"]["name"] == "fastapi-boilerplate"
def test_it_names_itself_the_way_the_spec_allows():
diff --git a/blueprint.toml b/blueprint.toml
index 7d3bafcc..c84035b3 100644
--- a/blueprint.toml
+++ b/blueprint.toml
@@ -1,5 +1,5 @@
[blueprint]
-name = "fastro"
+name = "fastapi-boilerplate"
version = "0.20.0"
schema = 1
requires_fastro = ">=0.1.0.dev0,<0.2"
diff --git a/blueprint/tests/test_deploy_templates.py b/blueprint/tests/test_deploy_templates.py
index 6c3ea73c..fb2c45dc 100644
--- a/blueprint/tests/test_deploy_templates.py
+++ b/blueprint/tests/test_deploy_templates.py
@@ -28,7 +28,7 @@ def _context(
"""The spec 6.2 context, as the tool builds it for a generator."""
return {
"project": {"name": "example", "slug": "example"},
- "blueprint": {"name": "fastro", "version": "0.20.0"},
+ "blueprint": {"name": "fastapi-boilerplate", "version": "0.20.0"},
"fastro": {"version": "0.1.0"},
"features": list(features),
"options": {},
diff --git a/fastro.toml b/fastro.toml
index ee853cbe..07e5abf0 100644
--- a/fastro.toml
+++ b/fastro.toml
@@ -1,6 +1,6 @@
source = true
features = ["accounts", "rbac", "ratelimit", "tiers", "tier_limits", "api_keys", "admin", "cache", "taskiq"]
-blueprint = { name = "fastro", version = "0.20.0" }
+blueprint = { name = "fastapi-boilerplate", version = "0.20.0" }
[project]
name = "fastapi-boilerplate"
From 4d1a889cf835a868556df893c1fbc529cd2c5b1f Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 17 Nov 2026 16:36:28 -0300
Subject: [PATCH 51/71] name the FastAPI-boilerplate blueprint in full in the
overlay's AGENTS.md and README, keep the catalog id and version beside it in
the README, and test both
---
blueprint/overlay/AGENTS.md | 3 ++-
blueprint/overlay/README.md.j2 | 4 ++--
blueprint/tests/test_overlay.py | 14 ++++++++++++++
3 files changed, 18 insertions(+), 3 deletions(-)
diff --git a/blueprint/overlay/AGENTS.md b/blueprint/overlay/AGENTS.md
index 72be0aa3..d64f738b 100644
--- a/blueprint/overlay/AGENTS.md
+++ b/blueprint/overlay/AGENTS.md
@@ -1,6 +1,7 @@
# Working in this project
-A FastAPI backend generated by fastro. `backend/` holds everything that runs.
+A FastAPI backend generated from the FastAPI-boilerplate blueprint by fastro. `backend/` holds
+everything that runs.
## The layers
diff --git a/blueprint/overlay/README.md.j2 b/blueprint/overlay/README.md.j2
index 6660d50e..e965771b 100644
--- a/blueprint/overlay/README.md.j2
+++ b/blueprint/overlay/README.md.j2
@@ -1,7 +1,7 @@
# {{ project.name }}
-A FastAPI backend, generated from the {{ blueprint.name }} blueprint ({{ blueprint.version }}) by
-fastro {{ fastro.version }}.
+A FastAPI backend, generated from the FastAPI-boilerplate blueprint (`{{ blueprint.name }}`
+{{ blueprint.version }}) by fastro {{ fastro.version }}.
{% if features %}
Selected: {{ features | join(", ") }}.
{%- else %}
diff --git a/blueprint/tests/test_overlay.py b/blueprint/tests/test_overlay.py
index 4d9c1064..f533459a 100644
--- a/blueprint/tests/test_overlay.py
+++ b/blueprint/tests/test_overlay.py
@@ -211,6 +211,20 @@ def test_the_readme_names_the_features_a_project_selected():
assert "Selected: accounts, admin." in rendered
+@pytest.mark.parametrize("features", [(), ("accounts", "admin")])
+def test_the_readme_names_the_blueprint_a_project_came_from(features: tuple[str, ...]):
+ """The catalog's `name` is an id; a reader meets the blueprint by its name in full."""
+ environment = Environment(loader=FileSystemLoader(OVERLAY), undefined=StrictUndefined)
+ blueprint = {"name": "a-blueprint-id", "version": "9.8.7"}
+ rendered = environment.get_template(README).render({**_context(features), "blueprint": blueprint})
+
+ assert f"the FastAPI-boilerplate blueprint (`{blueprint['name']}` {blueprint['version']})" in " ".join(rendered.split())
+
+
+def test_the_agents_file_names_the_blueprint_a_project_came_from():
+ assert re.search(r"\bFastAPI-boilerplate\b", (OVERLAY / "AGENTS.md").read_text())
+
+
@pytest.mark.parametrize("path", [str(path.relative_to(OVERLAY)) for path in _files() if path.suffix == ".j2"])
def test_every_fastro_command_a_template_writes_runs_the_tool_that_generated_the_project(path: str):
"""`uvx fastro@` needs nothing installed first and pins the project to the tool it
From e440fc95fdf4e5488d98191eab8201276314ef2c Mon Sep 17 00:00:00 2001
From: Igor Benav
Date: Tue, 17 Nov 2026 16:52:43 -0300
Subject: [PATCH 52/71] call the blueprint FastAPI-boilerplate wherever the
bare tool name stood, rename the conftest alias to FastroRunner, and test
that no tracked file outside the changelog and the cover and card scripts
uses the bare name
---
README.md | 14 ++++----
backend/tests/unit/test_blueprint_catalog.py | 36 ++++++++++++++++++++
blueprint/tests/conftest.py | 4 +--
blueprint/tests/test_fastro.py | 4 +--
blueprint/tests/test_observability_recipe.py | 6 ++--
blueprint/tests/test_overlay.py | 2 +-
docs/fastro-vs-fastroai.md | 12 +++----
docs/index.md | 8 ++---
docs/user-guide/database/neon.md | 2 +-
zensical.toml | 4 +--
10 files changed, 64 insertions(+), 28 deletions(-)
diff --git a/README.md b/README.md
index f72f94ec..ff9b3251 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-
@@ -74,11 +74,11 @@
* **Admin**: [SQLAdmin views](https://benavlabs.github.io/FastAPI-boilerplate/user-guide/admin-panel/) (optional, env-toggled)
* **CLI**: [`bp` tool](https://benavlabs.github.io/FastAPI-boilerplate/cli/) for compose scaffolding, env audits, and plugin extensions
-## Fastro vs FastroAI
+## FastAPI-boilerplate vs FastroAI
-This boilerplate - **Fastro** - is the free, open-source **foundation**: everything you need for a production FastAPI backend. **[FastroAI](https://fastro.ai)** is the paid template built on the same foundation for shipping a **complete SaaS** - Stripe billing (subscriptions, credits, discounts), entitlements, transactional email, and a frontend, all wired together. Building an **AI** product? The PydanticAI agent layer is included too - but every paid feature fits a regular SaaS just as well.
+**FastAPI-boilerplate** is the free, open-source **foundation**: everything you need for a production FastAPI backend. **[FastroAI](https://fastro.ai)** is the paid template built on the same foundation for shipping a **complete SaaS** - Stripe billing (subscriptions, credits, discounts), entitlements, transactional email, and a frontend, all wired together. Building an **AI** product? The PydanticAI agent layer is included too - but every paid feature fits a regular SaaS just as well.
-| | **Fastro** (this repo · free) | **FastroAI** (paid) |
+| | **FastAPI-boilerplate** (this repo · free) | **FastroAI** (paid) |
|---|:---:|:---:|
| FastAPI + SQLAlchemy 2.0, Pydantic v2 | ✓ | ✓ |
| Auth - sessions, OAuth, API keys | ✓ | ✓ **+ JWT** |
@@ -98,12 +98,12 @@ This boilerplate - **Fastro** - is the free, open-source **foundation**: everyth
-
+
-**Stick with Fastro** if you want a clean, hackable FastAPI backend to build on.
+**Stick with FastAPI-boilerplate** if you want a clean, hackable FastAPI backend to build on.
**[Get FastroAI →](https://fastro.ai)** if you're shipping a SaaS - AI or not - and want billing, entitlements, email, auth, and a frontend ready out of the box.
## Repo Layout
diff --git a/backend/tests/unit/test_blueprint_catalog.py b/backend/tests/unit/test_blueprint_catalog.py
index b20d5fee..236ea374 100644
--- a/backend/tests/unit/test_blueprint_catalog.py
+++ b/backend/tests/unit/test_blueprint_catalog.py
@@ -2911,3 +2911,39 @@ def test_the_project_is_named_the_way_its_python_package_is():
backend = tomllib.load(handle)
assert _project()["project"]["name"] == backend["project"]["name"]
+
+
+RETIRED_NAME = "fastro".title()
+
+STILL_CARRYING_THE_RETIRED_NAME = {
+ "docs/changelog.md": "B9 item 15",
+ "docs/assets/build-cover.cjs": "B5",
+ "docs/assets/build-card.cjs": "B5",
+}
+"""Files left as they are until the item named beside each, which rewrites them."""
+
+
+def test_no_tracked_file_calls_the_blueprint_by_its_retired_name():
+ """FastAPI-boilerplate is the blueprint, fastro the tool and FastroAI the paid blueprint: the
+ capitalised tool name, standing alone, names nothing. A wordmark that sets AI in its own
+ `` straight after it still spells FastroAI."""
+ alone = re.compile(rf"\b{RETIRED_NAME}\b(?!]*>AI)")
+ tracked = subprocess.run(["git", "ls-files", "-z"], cwd=REPO_ROOT, capture_output=True, text=True, check=True)
+ found = []
+ carrying = set()
+ for name in filter(None, tracked.stdout.split("\0")):
+ path = REPO_ROOT / name
+ if not path.is_file():
+ continue
+ try:
+ text = path.read_text(encoding="utf-8")
+ except UnicodeDecodeError:
+ continue
+ hits = [f"{name}:{number}" for number, line in enumerate(text.splitlines(), 1) if alone.search(line)]
+ if name in STILL_CARRYING_THE_RETIRED_NAME:
+ carrying |= {name} if hits else set()
+ else:
+ found += hits
+
+ assert not found, found
+ assert carrying == set(STILL_CARRYING_THE_RETIRED_NAME), "drop the exemption of a file that no longer carries it"
diff --git a/blueprint/tests/conftest.py b/blueprint/tests/conftest.py
index deb38cfb..e13b6c19 100644
--- a/blueprint/tests/conftest.py
+++ b/blueprint/tests/conftest.py
@@ -8,7 +8,7 @@
REPO_ROOT = Path(__file__).resolve().parents[2]
-Fastro = Callable[..., subprocess.CompletedProcess[str]]
+FastroRunner = Callable[..., subprocess.CompletedProcess[str]]
@pytest.fixture
@@ -32,7 +32,7 @@ def tracked_tree(tmp_path: Path) -> Path:
@pytest.fixture
-def fastro() -> Fastro:
+def fastro() -> FastroRunner:
"""Run the fastro the repository root installs, in a directory of the caller's choosing."""
def run(*arguments: str, cwd: Path) -> subprocess.CompletedProcess[str]:
diff --git a/blueprint/tests/test_fastro.py b/blueprint/tests/test_fastro.py
index 4ea1dcd0..e6e5ec34 100644
--- a/blueprint/tests/test_fastro.py
+++ b/blueprint/tests/test_fastro.py
@@ -3,12 +3,12 @@
import tomllib
from pathlib import Path
-from conftest import Fastro
+from conftest import FastroRunner
REPO_ROOT = Path(__file__).resolve().parents[2]
-def test_plain_sync_regenerates_what_the_check_compares(tracked_tree: Path, fastro: Fastro):
+def test_plain_sync_regenerates_what_the_check_compares(tracked_tree: Path, fastro: FastroRunner):
"""CONTRIBUTING.md sends a failed `fastro sync --check` to `fastro sync`."""
tree = tracked_tree
wiring = tree / tomllib.loads((tree / "blueprint.toml").read_text())["wiring"][0]["path"]
diff --git a/blueprint/tests/test_observability_recipe.py b/blueprint/tests/test_observability_recipe.py
index e9148f5b..692bcb45 100644
--- a/blueprint/tests/test_observability_recipe.py
+++ b/blueprint/tests/test_observability_recipe.py
@@ -6,7 +6,7 @@
from pathlib import Path
import pytest
-from conftest import Fastro
+from conftest import FastroRunner
REPO_ROOT = Path(__file__).resolve().parents[2]
RECIPE = REPO_ROOT / "docs" / "user-guide" / "observability.md"
@@ -41,7 +41,7 @@ def _installers_slot() -> tuple[str, str]:
)
-def test_the_recipe_registers_its_installer_through_fastro_toml_and_a_sync(tracked_tree: Path, fastro: Fastro):
+def test_the_recipe_registers_its_installer_through_fastro_toml_and_a_sync(tracked_tree: Path, fastro: FastroRunner):
project = tracked_tree
wiring_file, slot = _installers_slot()
registration = _block("toml")
@@ -97,7 +97,7 @@ def test_the_installer_configures_tracing_before_it_instruments_the_app():
@pytest.mark.parametrize("arguments", [("sync",), ("sync", "--check")])
-def test_the_pinned_fastro_cannot_sync_a_project_yet(tracked_tree: Path, fastro: Fastro, arguments: tuple[str, ...]):
+def test_the_pinned_fastro_cannot_sync_a_project_yet(tracked_tree: Path, fastro: FastroRunner, arguments: tuple[str, ...]):
"""The recipe's hand-edit fallback is there only while this holds; when it fails, delete that sentence."""
config = tracked_tree / "fastro.toml"
config.write_text(re.sub(r"^source = true\n", "", config.read_text(), flags=re.M))
diff --git a/blueprint/tests/test_overlay.py b/blueprint/tests/test_overlay.py
index f533459a..2eb5c383 100644
--- a/blueprint/tests/test_overlay.py
+++ b/blueprint/tests/test_overlay.py
@@ -24,7 +24,7 @@
"""Spec 6.2, in full. A template reaching for anything else fails under `StrictUndefined`."""
BUILT_IN_COMMANDS = {"add", "check", "eject", "features", "init", "make", "new", "remove", "sync", "update"}
-"""Fastro's own verbs, which take arguments of their own: `fastro add admin` names a feature, not
+"""fastro's own verbs, which take arguments of their own: `fastro add admin` names a feature, not
a command. Anything else after `fastro` has to be a command the catalog declares, and
`make ` has to name one it has."""
diff --git a/docs/fastro-vs-fastroai.md b/docs/fastro-vs-fastroai.md
index 9d67e720..a1013941 100644
--- a/docs/fastro-vs-fastroai.md
+++ b/docs/fastro-vs-fastroai.md
@@ -1,8 +1,8 @@
-# Fastro vs FastroAI
+# FastAPI-boilerplate vs FastroAI
-This boilerplate - **Fastro** - is the free, open-source **foundation**: everything you need for a production FastAPI backend. **[FastroAI](https://fastro.ai)** is the paid template built on the same foundation for shipping a **complete SaaS** - Stripe billing (subscriptions, credits, discounts), entitlements, transactional email, and a frontend, all wired together. Building an **AI** product? The PydanticAI agent layer is included too - but every paid feature fits a regular SaaS just as well.
+**FastAPI-boilerplate** is the free, open-source **foundation**: everything you need for a production FastAPI backend. **[FastroAI](https://fastro.ai)** is the paid template built on the same foundation for shipping a **complete SaaS** - Stripe billing (subscriptions, credits, discounts), entitlements, transactional email, and a frontend, all wired together. Building an **AI** product? The PydanticAI agent layer is included too - but every paid feature fits a regular SaaS just as well.
-| | **Fastro** (this repo · free) | **FastroAI** (paid) |
+| | **FastAPI-boilerplate** (this repo · free) | **FastroAI** (paid) |
|---|:---:|:---:|
| FastAPI + SQLAlchemy 2.0, Pydantic v2 | ✓ | ✓ |
| Auth - sessions, OAuth, API keys | ✓ | ✓ **+ JWT** |
@@ -20,11 +20,11 @@ This boilerplate - **Fastro** - is the free, open-source **foundation**: everyth
-**Stick with Fastro** if you want a clean, hackable FastAPI backend to build on.
+**Stick with FastAPI-boilerplate** if you want a clean, hackable FastAPI backend to build on.
**[Get FastroAI →](https://fastro.ai)** if you're shipping a SaaS - AI or not - and want billing, entitlements, email, auth, and a frontend ready out of the box, all on the same foundation you already know.
diff --git a/docs/index.md b/docs/index.md
index 882b3ece..f83a3ce0 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -1,8 +1,8 @@
-# Fastro · The Benav Labs FastAPI Boilerplate
+# FastAPI-boilerplate by Benav Labs
-
-
+
+
@@ -130,7 +130,7 @@ Your API will be available at `http://localhost:8000/docs`
## Building a complete SaaS? Meet FastroAI
-Fastro is the free **foundation**. **[FastroAI](https://fastro.ai)** builds on the same base for shipping a full SaaS - Stripe billing (subscriptions, credits, discounts), entitlements, transactional email, a frontend, and AI agents - all wired together, so you don't build them from scratch.
+FastAPI-boilerplate is the free **foundation**. **[FastroAI](https://fastro.ai)** builds on the same base for shipping a full SaaS - Stripe billing (subscriptions, credits, discounts), entitlements, transactional email, a frontend, and AI agents - all wired together, so you don't build them from scratch.