This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Python 3.14 async REST API. FastAPI + SQLAlchemy 2 (async) + PostgreSQL + Alembic. Served by Granian (uvloop). Dependencies managed by uv. Linted with ruff, type-checked with ty (not mypy). Observability via lite-bootstrap (OpenTelemetry, Sentry). DI via modern-di. Repositories via advanced-alchemy.
The development workflow runs inside Docker via just (just --list / read the justfile for the full recipe list). The application service mounts the repo and depends on a db Postgres service. Bare just runs the default pipeline (install + lint + build + test).
Things the recipe names don't make obvious:
just test [args]recreates a clean DB first (alembic downgrade base→upgrade head) and tears the stack down afterward;[args]are passed through topytest.just test-migrations [args]runs thepytest-alembicsuite intests/migrations/against an empty database: single head, upgrade, up/down consistency for every revision, and models matching the migrated schema (alembic checkas a test).just testskips that directory (--ignoreinaddopts,omitin coverage) because it migrates the schema under the transaction-rollback fixture, so the recipe clearsaddopts.just runapplies migrations then starts the app on :8000.just lintauto-fixes (eof-fixer +ruff format+ruff check --fix+ty check); CI (below) is the no-fix gate.
Running a single test (inside container or with DB available):
uv run pytest tests/test_decks.py::test_get_decks -xCI (.github/workflows/main.yml) runs ruff format --check, ruff check --no-fix, ty check, then two Postgres jobs: alembic upgrade head followed by pytest, and the pytest-alembic suite. Match this locally before pushing.
app/__main__.py boots Granian pointing at app.application:build_app (factory). build_app() in app/application.py:
- Creates a
modern_di.Containerwithioc.ALL_GROUPSfromapp/ioc.py. - Builds a
FastAPIBootstrapperfromsettings.api_bootstrapper_config, injecting the SQLAlchemy OpenTelemetry instrumentor. modern_di_fastapi.setup_di(app, container)wires DI scopes onto the FastAPI app.- Includes one
ROUTERper resource (app.api.decks.ROUTER,app.api.cards.ROUTER) under/apiviainclude_routers. Add a new resource by creatingapp/api/<name>.pywith its ownAPIRouter-basedROUTERand registering it there. - Registers
DuplicateKeyError→ 422 handler fromapp/exceptions.py.
app/ioc.py splits providers into three groups, collected in ALL_GROUPS.
Database:
database_engine— singleton-ish primaryAsyncEngine(create_primary_sa_engine,close_sa_enginefinalizer).database_read_engine— singleton-ish readAsyncEnginebuilt fromDB_REPLICA_DSN, or fromDB_DSNwhen it is unset. It runs inAUTOCOMMIT(no BEGIN/ROLLBACK per request) and setsdefault_transaction_read_only=on, so Postgres rejects writes on it. Each statement sees its own snapshot, so a multi-query read (e.g.fetch_with_cards) can see a write that commits in between. Without a replica it is a second pool on the primary, so a process can hold up to2 × db_pool_sizeconnections.dynamic_engine—Scope.REQUEST;choose_sa_enginereturns the read engine forGET/HEADrequests, the primary otherwise (including when there is no request). GET handlers cannot write, and a read right after a write may see replica lag.session—Scope.REQUEST, bound todynamic_engine, finalized byclose_session.transaction—Scope.REQUEST, adb_retry.Transactionoversession. Leaving its block rolls back anything uncommitted and closes the session.
Repositories (Scope.REQUEST): decks_repository and cards_repository, on Database.session with auto_commit=False. The use case commits through transaction.commit().
UseCases (Scope.REQUEST): one provider per use case in app/use_cases/. modern-di fills each dataclass field by its type, so a use case needs no kwargs.
Endpoints inject a use case with FromDI(UseCase) from modern_di_fastapi, call it, and convert the result to a schema. They never touch repositories or the session. Add new providers to the matching group rather than constructing services manually in routes.
pool_pre_ping is off by default (DB_POOL_PRE_PING). A pooled connection that died while idle is handled by db_retry.postgres_retry instead, which saves a round trip on every checkout. That only works if the retried function owns its whole transaction, so every use case has this shape:
@dataclasses.dataclass(kw_only=True, frozen=True, slots=True)
class ListDecksUseCase:
transaction: Transaction
decks_repository: DecksRepository
@postgres_retry
async def __call__(self) -> Sequence[models.Deck]:
async with self.transaction:
decks: typing.Final = await self.decks_repository.get_many()
await self.transaction.commit()
return decks- Every query runs inside
async with self.transaction:. A query before the block leaves the session in a failed transaction on a lost connection, and the retry then fails withPendingRollbackError. - Commit before leaving the block, reads included, and before any early return. Otherwise
__aexit__rolls back, which expires the loaded rows. - A retry runs the whole use case again. If the connection drops during
COMMIT, the write may already have landed. A write that creates rows needs something that makes the second run harmless:CreateDeckUseCasetakes a client-generatedidempotency_key(schemas.DeckCreate, unique ondecks).DecksRepository.get_or_createsends oneINSERT ... ON CONFLICT (idempotency_key) DO UPDATE SET idempotency_key = EXCLUDED.idempotency_key RETURNING *. On a conflict the no-op update leaves the row as it was andRETURNINGhands it back (DO NOTHINGwould return no row), so a retry or a client resend gets the first deck. A concurrent request with the same key waits on the row lock and then gets the same deck. advanced-alchemy's ownupsertandget_or_upsertdo a SELECT followed by an INSERT, so they cost two round trips and lose that race.CreateCardsUseCaserelies on the(deck_id, front)unique constraint. A replay is rejected as a duplicate-key error rather than creating the cards twice.- Updates (
UpdateDeckUseCase,UpdateCardsUseCase) write the same values again, so a replay is harmless.
app/use_cases/ is exempt from ruff's TC rules because modern-di reads the dataclass field annotations at runtime.
app/models.py—BigIntAuditBasefromadvanced_alchemy(autoid,created_at,updated_at). The module aliasesorm_registry.metadataontoorm.DeclarativeBase.metadataso Alembic autogenerate sees both. New models go here.app/repositories.py— SubclassSQLAlchemyAsyncRepositoryService[Model]with a nestedBaseRepository(SQLAlchemyAsyncRepository[Model]). Use cases call the service methods (get_many,get_one,create,update,create_many,upsert_many).app/resources/db.py— engine factories live here and are DI creators: modern-di resolves their parameter annotations at runtime, sopyproject.tomlexemptsapp/resources/from ruff'sTCrules.create_sessionpassesjoin_transaction_mode="create_savepoint". This is inert in production (the session binds to an engine) but enables the test rollback pattern below: when a test binds the session to a connection already in a transaction, the session owns its own savepoint so the outer transaction survives commits — do not "fix" it.migrations/env.pyswaps the asyncpg driver for the syncpostgresqldriver and usesapp.models.METADATAastarget_metadata.
app/settings.py — pydantic_settings.BaseSettings. Env vars are unprefixed (DB_DSN, DB_REPLICA_DSN, SERVICE_DEBUG, SERVICE_ENVIRONMENT, LOG_LEVEL, APP_HOST, APP_PORT, OPENTELEMETRY_ENDPOINT, SENTRY_DSN, CORS_ALLOWED_ORIGINS, ...). api_bootstrapper_config produces a FastAPIConfig for lite-bootstrap.
tests/conftest.py provides the test isolation pattern — read it before adding fixtures:
appfixture builds a fresh app viaLifespanManager.db_sessionopens a connection, begins a transaction, and overridesDatabase.dynamic_enginewith the connection itself, so reads and writes share one rolled-back transaction. Each session built against that connection usesjoin_transaction_mode="create_savepoint", sotransaction.commit()releases the session's own savepoint while the outer transaction is rolled back at teardown — each test starts clean.set_async_session_in_base_sqlalchemy_factorywiresdb_sessionintoSQLAlchemyFactory.__async_session__sopolyfactoryfactories intests/factories.py(DeckModelFactory,CardModelFactory) persist via the rolled-back session. Test modules that use these factories opt in withpytestmark = [pytest.mark.usefixtures("set_async_session_in_base_sqlalchemy_factory")].
pytest.ini_options sets asyncio_mode = "auto" — async tests do not need @pytest.mark.asyncio. Coverage runs by default with --cov-fail-under=100, so just test fails unless tests cover every line of new code.
- Ruff is configured with
select = ["ALL"]and a curated ignore list inpyproject.toml. Don't sprinkle# noqa; prefer fixing or extending the project ignore list if a rule is genuinely wrong for the codebase. - Routes convert ORM objects to schemas explicitly, never via
typing.cast. Single objects:schemas.X.model_validate(instance). Collections:schemas.Xs.from_models(objects)(theCollection[T]seam inapp/schemas.py). Both rely onfrom_attributes=True. - Deck responses are deliberately two-shaped:
list_decks/create_deck/update_deckreturn the lightschemas.Deck(nocards), whileget_deckreturnsschemas.DeckWithCards. The split mirrors loading — lists/writes usenoload(no cards query), detail usesselectinloadviafetch_with_cards— so the type states exactly what each endpoint loads. - Line length is 120.
GitHub issues on modern-python/fastapi-sqlalchemy-template, via gh. See docs/agents/issue-tracker.md.
The five canonical roles, each label string equal to its name. See docs/agents/triage-labels.md.
Single-context: CONTEXT.md and docs/adr/ at the repo root. See docs/agents/domain.md.