From 649f3eafb3f34e56cddae582a5f9535e1c9fe734 Mon Sep 17 00:00:00 2001 From: Abhiraj Adhikary Date: Mon, 16 Nov 2026 22:34:51 +0530 Subject: [PATCH 1/2] chore(github): add copilot code review instructions for obliq-api --- .github/copilot-instructions.md | 106 ++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 .github/copilot-instructions.md diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..d849582 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,106 @@ +# GitHub Copilot Instructions for obliq-api + +This repository contains **obliq-api**, a high-performance FastAPI microservice wrapping the `obliq-ocr` engine (RapidOCR + PyMuPDF), built to process mixed-format tax documents, invoices, bills, and challans uniformly across distributed enterprise services for small and mid-sized CA firms at [OBLIQ.in](https://obliq.in). + +When assisting with code generation, chat, or reviewing pull requests, strictly adhere to the standards, architecture, and constraints below. + +--- + +## 1. Architectural Guidelines & Async Discipline + +- **Framework & Runtime:** Python 3.11 (`>=3.11,<3.12`), FastAPI, Uvicorn/Gunicorn on Hugging Face Spaces (ZeroGPU / CPU). +- **Asynchronous Execution:** + - All route handlers, service methods, database queries, and Redis calls must be fully asynchronous (`async` / `await`). + - **No Blocking Operations in Async Handlers:** Heavy synchronous CPU work (such as OCR extraction, large PDF page rendering, or disk hashing) must never run bare in an async handler. Always offload to background threads (`asyncio.to_thread`) or background workers. + - Blocking filesystem calls (like `pathlib.Path.mkdir` or synchronous file read/write) inside async routes should be handled with caution to prevent event loop starvation. +- **Dependencies & Singletons:** + - Inject services using FastAPI's dependency injection system (`Depends(...)`). + - Avoid global mutable state. Use accessors in `obliq_api.dependencies` (e.g., `get_job_store`, `get_rate_limiter`, `get_ocr_engine`, `get_db`). + +--- + +## 2. Multi-Tenancy & Security Rules + +- **Strict Tenant & Organization Isolation:** + - Every authenticated request is scoped to an `organisation_id` via `AuthContext`. + - Database queries involving tenant-owned resources (API keys, jobs, usage records, credits) **must explicitly filter by `organisation_id`**. Never rely on client-supplied IDs without verifying organization ownership. +- **Authentication & API Keys:** + - Live keys start with prefix `obliq_live_`; internal service keys start with `obliq_internal_`. + - **API Token Hashing vs. Password Hashing:** + - High-entropy API keys (144 bits of randomness via `secrets.token_urlsafe(24)`) use fast keyed hashing (`hashlib.blake2b` / HMAC) for high-throughput lookup performance without CPU denial-of-service. Do NOT suggest replacing fast keyed token lookups with slow password-hashing algorithms like bcrypt. + - User account passwords (human-entered) are strictly hashed using bcrypt via `passlib.context.CryptContext` in `src/obliq_api/auth/keys.py`. +- **Zero Committed Secrets:** + - Never commit credentials, connection strings, JWT secrets, or tokens to the repository. + - All secrets must be loaded through `obliq_api.config.Settings` (Pydantic Settings reading environment variables). +- **Document Privacy & Ephemeral Storage:** + - Uploaded tax files and invoices contain sensitive financial PII. + - Temporary files created during extraction must be stored in isolated directories and **guaranteed to be deleted** in a `finally` block or context manager upon completion or failure. + +--- + +## 3. API Contract & Error Handling + +- **Unified Error Envelope:** + All error responses (4xx and 5xx) must conform to the unified error schema defined in `obliq_api.schemas.common.ErrorResponse`: + ```json + { + "error": { + "code": "invalid_api_key", + "message": "The provided API key is invalid or revoked.", + "details": [] + } + } + ``` +- **Custom Exceptions:** + - All domain and application exceptions must inherit from `ObliqError` in `obliq_api.exceptions` (e.g., `AuthenticationError`, `RateLimitExceededError`, `NotFoundError`, `PayloadTooLargeError`, `UnsupportedMediaTypeError`). + - Exceptions map to standardized HTTP status codes and machine-readable error codes. Do not return bare strings or non-standard error structures. + +--- + +## 4. Database Models & SQLAlchemy 2.0 + +- **SQLAlchemy 2.0 Typing:** + - Use `Mapped[...]` and `mapped_column(...)` exclusively for ORM models. + - For UUID primary/foreign keys in PostgreSQL, use Python's native `uuid.UUID` in type annotations: + ```python + import uuid + from sqlalchemy.dialects.postgresql import UUID as PG_UUID + + id: Mapped[uuid.UUID] = mapped_column( + PG_UUID(as_uuid=True), primary_key=True, default=uuid.uuid4 + ) + ``` + *Never use dialect `Mapped[UUID]` directly as a mapped type, as this breaks Mypy static analysis.* +- **Migrations:** + - Any database schema modification must be accompanied by an Alembic migration in `alembic/versions/`. + - Migrations must be backward-compatible (non-blocking for rolling deployments). + +--- + +## 5. Code Quality, Typing & Testing Standards + +- **Code Formatting & Linting:** + - Formatted and linted using **Ruff** with line length 100 (`target-version = "py311"`). + - Code must pass `ruff check .` and `ruff format --check .` cleanly. +- **Type Safety:** + - Strict type hints on all public functions, classes, and router endpoints. + - Must pass `mypy src` with zero errors. +- **Testing & Coverage:** + - Tests use `pytest` and `pytest-asyncio`. + - Minimum test coverage requirement is **60.0%** (enforced in CI with `--cov=obliq_api`). + - Unit and contract tests must never connect to live external dependencies (Neon PostgreSQL, Upstash Redis, or Hugging Face Spaces). Always use the mock fixtures defined in `tests/conftest.py` (`MockJobStore`, `MockRateLimiter`, `MockOCREngine`, mock database session). + - Test files must use synthetic dummy fixtures (e.g. `tests/fixtures/golden_fixture.pdf`), never real client documents or financial data. + +--- + +## 6. Git & Pull Request Guidelines + +- **Conventional Commits:** + - All commit messages and PR titles must adhere to Conventional Commits: + `feat:`, `fix:`, `refactor:`, `perf:`, `test:`, `docs:`, `ci:`, `chore:`. +- **Review Scope:** + - When reviewing pull requests, prioritize: + 1. Tenant isolation & data privacy (financial document safety). + 2. Async performance (preventing event loop blocking). + 3. Error handling consistency (unified envelope). + 4. Test coverage & mock isolation. From 31be34ed0c4a3009ddb39b7a74304dc76117593e Mon Sep 17 00:00:00 2001 From: Abhiraj Adhikary Date: Tue, 17 Nov 2026 00:01:23 +0530 Subject: [PATCH 2/2] style(docs): format python snippet in copilot instructions for ruff format --- .github/copilot-instructions.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index d849582..510a0bd 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -66,9 +66,7 @@ When assisting with code generation, chat, or reviewing pull requests, strictly import uuid from sqlalchemy.dialects.postgresql import UUID as PG_UUID - id: Mapped[uuid.UUID] = mapped_column( - PG_UUID(as_uuid=True), primary_key=True, default=uuid.uuid4 - ) + id: Mapped[uuid.UUID] = mapped_column(PG_UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) ``` *Never use dialect `Mapped[UUID]` directly as a mapped type, as this breaks Mypy static analysis.* - **Migrations:**