ADR 0001 — Adopt Django as the backend HTTP / orchestration framework¶
- Status: accepted
- Date: 2026-05-03
- Spec: specs/011-django-backend
- Constitution clauses amended: §2 Tech Stack (Locked), §11 Continuous Evolution — mission-drift guard
Historical note (2026-09-05, BL-20260602-04). This ADR describes the FastAPI package
backend/app/, which spec 011 deleted (T-016) in favour of the Django project packagebackend/law_ai/. Itsbackend/app/...paths are rendered as inline code rather than links: the files are gone, and the hrefs 404'd. The decision itself stands as accepted; only the dead links changed.
Context¶
Through specs 001 → 010, the Law AI backend was a FastAPI application under backend/app/ — five routers (backend/app/api/health.py, backend/app/api/agents.py, backend/app/api/analysis.py, backend/app/api/graph.py, backend/app/api/lsat.py), an env-driven API-key middleware in backend/app/core/security.py, JSONL audit logging in backend/app/core/audit_store.py, and ad-hoc SQL/Cypher migrations in backend/app/db/postgres_migrations/ and backend/app/db/neo4j_migrations/. FastAPI delivered the surface area we needed quickly, but four pressures have accumulated:
- No first-class admin UI for HITL queues. Spec 004's
pending_reviewtable and the audit log have no review surface; BL-20260429-15 (HITL approve/reject) and BL-20260429-14 (run drill-down) keep being deferred because we would have to hand-roll CRUD + auth + permissions for each. - Auth has plateaued at API keys. Specs 008/009 shipped per-router env-keyed auth (
backend/app/core/security.py) but cannot grow into per-user roles, rotation, audit trails, or rate limits (BL-20260430-09) without effectively re-implementingdjango.contrib.auth. - Background work has no home. IngestionScout.run_and_commit (
backend/app/ingestion/scout.py) does its low-confidence quarantine inline in the request path; spec 005's tutor and spec 010's LangGraph workflow have no broker for retries, scheduling, or fan-out. - Streaming is blocked. Three open backlog items (BL-20260503-03, BL-20260429-24, BL-20260429-16) want SSE/WebSocket push. FastAPI can do these but we have nothing standardized; Django Channels gives us one ASGI consumer pattern repo-wide.
The previous version of docs/constitution.md §2 explicitly locked the backend to FastAPI and §11 mission-drift guard explicitly forbade "Django-style frameworks" in BACKLOG promotions. This ADR amends both clauses.
Decision¶
Replace FastAPI with Django 5 (ASGI via daphne) + Django REST Framework + Channels + Celery as the backend HTTP / orchestration layer. The product runtime LLM remains Ollama (local-first, open weights) per docs/constitution.md §1 — this ADR concerns the backend platform, not the product runtime. Specifically:
- HTTP layer: Django + DRF replaces FastAPI routers.
drf-pydanticlets us reuse the existing Pydantic request/response models so frontend/lib/api.ts sees zero JSON-shape change. - ORM: Django ORM (async) manages new Postgres tables (
audit.AuditEvent,ingestionapp.PendingReview,core.ApiToken). Existing raw SQL migrations are encoded asRunSQLoperations inside the initial Django migration so a freshmake migratereproduces today's schema. - Neo4j layer: unchanged. The async neo4j driver and the Cypher helpers in
backend/app/db/are relocated tobackend/law_ai/core/neo4j/with no logic change. - Auth:
core.ApiTokenmodel + custom DRFApiKeyAuthentication+HasScopepermission preserve the spec-008/009 env-driven UX via an idempotentmanage.py seed_api_keyscommand. - Async: fully ASGI via daphne. All current
async defview bodies (notablyawait asyncio.gather(LegalAnalyst.run, PrecedentHunter.run)) port directly. Celery handles background work (ingestion quarantine, JSONL audit fallback). Channels exposes/ws/agents/{run_id}for future agent-trace streaming. - Agent runtime: framework-agnostic. CrewAI crews, LangGraph workflows, and Pydantic domain models move under
backend/law_ai/agents_runtime/with no logic change. The@logged_nodedecorator andregister_all_agents()keep their signatures so the agent code is unchanged beyond import paths. - Constitution: §2 backend stack list updated; §11 mission-drift guard reworded to forbid "frameworks not listed in §2" (the previous explicit "Django-style frameworks" phrasing is dropped).
The migration is a big-bang cutover on a long-lived feature branch (feat/011-django-backend) with green CI per commit; backend/app/ is deleted in the final commit (spec 011 T-016).
Consequences¶
Positive
- Django admin lights up
PendingReviewtriage and audit browsing for free, unblocking BL-20260429-15 and BL-20260429-14. django.contrib.authis the foundation for future JWT/OAuth (BL-20260503-13) and per-token rate limiting (BL-20260503-12).- Celery (Redis broker) standardizes background work; ingestion quarantine moves out of the request path.
- Channels gives us one consumer pattern for all future agent-trace streaming work (BL-20260429-24, BL-20260503-03, BL-20260429-16).
- Django migrations replace ad-hoc SQL files;
manage.py check --deployadds an explicit production hardening gate. - Constitutional ambiguity is removed: the ADR + amended §2 + amended §11 prevent future
/specifyagents from "correcting" the stack back to FastAPI.
Negative / Risks
- Larger framework surface (admin, auth, ORM, signals, migrations, middleware) — more to learn and lint.
- Django async ORM has rough edges around transactions; mitigated by keeping ORM writes single-row and using
sync_to_asyncfor complex flows (spec 011 R-1). drf-pydanticis a small dependency; pinned and a hand-written-serializer fallback is documented (spec 011 R-2).- LangGraph checkpointer schema collision with Django migrations — mitigated by isolating the checkpointer in its own
langgraphPostgres schema (spec 011 FR-13, AC-6). - Big-bang merge non-buildability risk — mitigated by branch protection (green CI per commit) and by deleting
backend/app/only after the test rewrite passes (spec 011 R-4).
Neutral
- The HTTP contract (
/health,/api/agents/*,/api/analysis,/api/graph/*,/api/lsat/*,X-API-Keysemantics, response JSON shapes) is preserved 1:1; frontend/lib/api.ts and the Vitest suite under frontend/tests/ require no changes. - LegalBench score is expected at parity (≥ 0 pp delta on
core_reasoningandprecedent_retrieval); the agent runtime moves but does not change. Spec 011 NFR-LEGALBENCH-1 makes any regression > 1 pp blocking.
Alternatives Considered¶
| Alternative | Why rejected |
|---|---|
| Stay on FastAPI | The four pressures listed under Context are not addressable without re-implementing meaningful pieces of Django (admin, auth, migrations, ORM-backed permissions). Each individual backlog item gets cheaper after the move. |
| Django + django-ninja instead of DRF | django-ninja matches FastAPI's ergonomics best (decorator-based, native Pydantic) but DRF is the ecosystem-standard auth/permission/serialization layer and integrates more cleanly with admin actions. We pay a small ergonomics tax for a much larger ecosystem. |
| Django plain views (no DRF) | Lightest dependency footprint but we would hand-roll auth, permissions, and response negotiation. Net loss vs. DRF. |
| Hybrid (Django for admin, FastAPI for APIs) | Long-term dual-stack maintenance cost; reverse-proxy plumbing; two test infrastructures. Rejected by the planning interview. |
| Strangler-fig migration (parallel FastAPI + Django) | Lower per-PR risk but multiplies the time the codebase is split across two frameworks. The user explicitly chose big-bang at the planning interview. |
Adopt neomodel Neo4j OGM as part of the same refactor |
OGM adds a maintenance-risk dependency and obscures the Cypher we lean on for graph traversal. Out of scope for this ADR. |
Supersedes / Superseded by¶
- Supersedes: the previous "FastAPI-locked" wording in docs/constitution.md §2 and the "Django-style frameworks must be rejected" wording in §11.
- Superseded by: none.
References¶
- specs/011-django-backend/spec.md — full functional + non-functional requirements, acceptance criteria, and risk register.
- specs/011-django-backend/plan.md — architecture diagram, component change list, alternatives matrix, rollout plan.
- specs/011-django-backend/tasks.md — T-001 through T-016 implementation sequence.
- docs/constitution.md — amended in the same PR as this ADR.
- BACKLOG.md — items unblocked by this decision (BL-20260503-09 through BL-20260503-18).