Instruction file imported from DarshanPatel24/enterprise-knowledge-hub (
.github/instructions/backend.instructions.md). Copyright stays with the author.
Backend Engineering Instructions (FastAPI + Python)
Layering and Boundaries
- Respect Clean Architecture layers:
- domain: pure entities and value objects, no framework imports.
- data: SQL and vector access primitives (connection, models, clients).
- repositories: persistence operations using the data layer only.
- services: business orchestration; depend on repositories and other services.
- api: thin HTTP layer; validate input, call services, return schemas.
- jobs: scheduled/background orchestration; reuse services.
- API route handlers must not contain business logic.
- Services must not run raw SQL or talk to Qdrant directly except via data/repository abstractions.
Dependency Injection
- Compose dependencies through FastAPI
Dependsand a central provider module. - Inject repositories and services; do not instantiate them inline in routes.
- Make external clients (SQL, Qdrant, Ollama, embeddings) swappable behind interfaces.
Typing and Models
- All public functions/methods require complete type hints.
- Use Pydantic models for:
- request and response payloads
- configuration/settings
- cross-service data contracts
- Keep domain entities separate from API schemas.
Error Handling
- Define explicit exception types for domain, security, and infrastructure errors.
- Map exceptions to consistent HTTP responses in middleware.
- Never swallow exceptions silently; log with context and correlation ID.
Logging and Observability
- Use structured logging (key/value), not f-string log spam.
- Attach correlation IDs to each request and propagate through services.
- Emit timing/metrics for ingestion, retrieval, and generation paths.
- Never log secrets or full document/chunk contents.
Data Access Rules
- SQL Server is the source of truth; Qdrant stores vectors and retrieval metadata.
- Use parameterized queries exclusively.
- Keep stable
document_idandchunk_ididentifiers across SQL and Qdrant. - All writes that affect both stores must be idempotent and reconcilable.
Retrieval and Security Rules
- Chat path is anonymous; do not require a principal for query execution.
- Classification is ingestion-time metadata in the current model, not a per-user query-time gate.
- Hybrid pipeline order: dense + BM25, RRF fusion, rerank (optional), context build.
- Generation must be grounded and include citations; return the exact fallback sentence when no evidence exists.
Performance and Reliability
- Use async I/O for network/database operations where supported.
- Apply retry with backoff for transient failures.
- Guard external runtimes (Ollama) with timeouts and graceful degradation.
Testing
- Provide unit tests for services and repositories (mock external systems).
- Provide integration tests for ingestion, retrieval, and generation flows.
- Provide security tests for authorization boundaries.