# Velar (internal codename: Miravelt)

> Author: Lokesh Ram Chand, software engineer in Hyderabad. Portfolio: https://lokeshrc.me
> Velar is the public name of the project; "Miravelt" is its internal codename and appears in the API headers and code below.
> Public write-up (preferred for citation): https://lokeshrc.me/blog/grounded-rag-pipeline-milvus-ollama-velar

## 1. Quick Overview

- **One-line description:** A backend-first transaction-intelligence platform that turns a Google Pay PDF statement into categorized transactions, behavioral profiles, anomaly/subscription detection, and grounded (RAG) natural-language explanations — with a Flutter mobile app and a Next.js admin dashboard on top.
- **Project type:** Full-stack product — FastAPI backend (system of record), Flutter mobile client, Next.js admin dashboard (BFF), Next.js marketing landing page.
- **Status:** Pre-production. Built and verified end-to-end on a local Docker stack (MongoDB + Milvus + Ollama). No production deployment or live users yet (`PRD.md`, line 3).
- **Duration:** 2026-06-15 → 2026-09-25 (~3.5 months of active development), 204 commits, all on `main`.
- **Individual / team:** Solo project. `git log` shows a single author across all 204 commits (two committer-name variants of the same person, same email).
- **My role:** Sole engineer — backend architecture, ML/behavioral pipeline, mobile app, admin dashboard, CI/CD, and security hardening.

## 2. Problem / Motivation

- People who pay mostly via UPI (Google Pay in India especially) have a complete transaction history, but only as a flat PDF of "Paid to X / Received from Y" lines — it says *what* happened, never *what it means*.
- Budgeting apps that answer that question typically require bank-account or card linking, which many users won't grant.
- Before this: no bank connection, no card access — the Google Pay statement PDF is deliberately the *only* input (`PRD.md` §2).
- Motivation: build "a financial analyst in your pocket" — read the statement, name the merchants, categorize spend, find recurring payments and anomalies, and explain it, without ever touching a bank API.

## 3. Solution

- A single FastAPI backend ingests a Google Pay "Transaction statement" PDF, parses it with a hand-built regex-based extractor grounded in a real anonymized 19-page/184-transaction sample statement, categorizes every transaction, builds a per-merchant behavioral profile, embeds merchant behavior into a vector store, computes analytics, and generates AI-written (or deterministic fallback) insights — all before the client makes a second request.
- Key features:
  - Deterministic + rule-based merchant/category resolution with a confidence score on every prediction (never a false "100% sure").
  - A trust/memory state machine (EPHEMERAL → TEMPORARY → PERMANENT → ARCHIVED) so a merchant is only trusted after repeated encounters.
  - Statistical behavioral feature extraction (amount entropy, temporal buckets, periodicity/coefficient-of-variation) feeding subscription and anomaly detection.
  - Unsupervised merchant clustering (UMAP + HDBSCAN) and a knowledge graph (NetworkX) over merchant relationships.
  - Grounded RAG explainability (`/v1/explain`) that is architecturally forbidden from calling the LLM without retrieved context.
  - A Flutter mobile app presenting all of this as periods, signals, and activity — no bank-style dashboard clutter.
  - A Next.js admin dashboard (BFF, not a second backend) for operators to manage users, jobs, statements, and releases.

## 4. My Contributions

Solo-built, so this section is the full system, not a share of it. Concretely, I designed and implemented:

- The FastAPI backend's full 15-phase pipeline (ingestion → resolution → memory → behavior → embeddings/clustering → feedback/active learning → RAG explainability → analytics → observability), `~10,300` lines of Python across `app.py`, 14 routers, and 20+ domain packages (`engines/`, `services/`, `memory/`, `behaviour/`, `features/`, `clustering/`, `analytics/`, `rag/`, `feedback/`, `repositories/`, `database/`, `milvus/`, `embeddings/`, `graphs/`, `training/`, `evaluation/`, `tasks/`, `core/`).
- The statement-ingestion product surface end to end: a hand-rolled PDF parser (`statements/pdf_parser.py`) reverse-engineered against a real Google Pay statement, an async job-polling contract, idempotent re-upload via unique Mongo indexes, and cascading delete.
- The two-layer + JWT auth model (API key, admin key, access/refresh JWTs with rotation and reuse detection) and a defense-in-depth security stack: Argon2id hashing, HMAC request signing, device attestation scaffolding (Play Integrity / App Attest), DLP redaction, prompt-injection filtering on LLM I/O, and rate limiting.
- The Flutter mobile client (~15,600 lines of Dart across 13 feature modules) using Clean Architecture and classic Riverpod state management.
- The Next.js admin dashboard (~1,500 lines of TS/TSX) as a strict BFF — no backend secret or JWT ever reaches the browser.
- A production-hardening and security-remediation pass: fixed an event-loop-blocking bug (measured 35.9 s `/live` stall during upload), a false-positive recurring-payment bug (69/92 merchants misclassified), a broken `/v1/categorize` endpoint, missing Mongo indexes, plaintext credentials in a compose file, and multiple CVEs across the dependency tree (verified via `pip-audit`).
- The CI/CD pipeline (GitHub Actions: gitleaks, ruff, pip-audit, pytest against a real MongoDB service container, Flutter analyze/test, hadolint + Trivy image scan, tag-gated Coolify deploy webhooks).
- The full documentation set (`ARCHITECTURE.md`, `PRD.md`, `docs/` — 16+ numbered engineering docs, a per-endpoint API reference, and a legal/compliance checklist).

## 5. Technical Stack

### Languages
Python 3.12 (backend), Dart (Flutter mobile), TypeScript (admin dashboard + marketing site).

### Frameworks / Libraries
- **Backend:** FastAPI 0.140, Uvicorn (ASGI), Pydantic v2 / Pydantic Settings, SlowAPI (rate limiting), `prometheus-fastapi-instrumentator`.
- **Mobile:** Flutter, Riverpod (classic, not codegen), `go_router`, Dio, Freezed/`json_serializable`.
- **Admin dashboard:** Next.js 16 (App Router, Server Actions), React 19, `iron-session`, Tailwind CSS 4.
- **Marketing site:** Next.js 16, Framer Motion, shadcn/ui.

### Database
MongoDB (via Motor, async) as the system of record, with GridFS for original PDF blobs; Milvus (`pymilvus.MilvusClient`) as the vector store for merchant-behavior embeddings.

### Infrastructure / Cloud
Docker (multi-stage, non-root runtime image), Docker Compose (local / staging / production variants), Redis (optional — caching, distributed rate limiting, Celery broker), Celery (beat-scheduled batch pipelines), Coolify (deploy target via webhook), GitHub Actions (CI).

### Tools
Ollama (self-hosted LLM + embedding inference), Ruff (lint), pre-commit + gitleaks (secret scanning), pip-audit, Trivy, hadolint, pytest.

### APIs / Services
Ollama HTTP API (`/api/generate`, `/api/embeddings`), Google Play Integrity API and Apple App Attest / DeviceCheck (device attestation, scaffolded).

### AI / ML
- Ollama-hosted LLM (`llama3`) for grounded RAG explanations and statement insight generation, with strict-JSON prompting and a deterministic-fallback path.
- Ollama embeddings (`nomic-embed-text`) → Milvus semantic search over merchant behavior.
- UMAP (dimensionality reduction) + HDBSCAN (density clustering) for unsupervised merchant discovery (`clustering/`).
- Classical ML baselines: scikit-learn, LightGBM, XGBoost (`training/train.py`), with SHAP for explainability (`evaluation/metrics.py`).
- LoRA fine-tuning via HuggingFace Transformers + PEFT (`training/finetune.py`) — offline, not in the live request path.
- NetworkX knowledge graph over merchant co-occurrence/behavior relationships.

## 6. Architecture

Three (really four, counting the marketing site) deployables share one backend contract:

```
Flutter app (frontend/)       ─┐
                                ├─ X-Miravelt-API-Key + JWT ──▶  FastAPI monolith (app.py)  ──▶  MongoDB (system of record)
Next.js admin-dashboard        ─┘  (BFF, server-only)                  │                    ──▶  Milvus (vector search)
Next.js landing-page (marketing, no backend calls)                     └────────────────    ──▶  Ollama (embeddings + LLM)
```

- **`app.py`** is a single FastAPI process (one Uvicorn worker). Routers, ML engines, and statement processing all run in the same process; Celery + Redis exist only to *schedule* batch pipelines when `REDIS_URI` is set — they never run request-path work.
- **`admin-dashboard/`** is a BFF, not a second backend: no business logic, no direct datastore access. Every page/action calls the FastAPI backend over HTTP, server-side only.
- **`frontend/`** is the Flutter mobile client — the actual product surface end users touch.
- MongoDB is the one hard dependency (`/ready` fails without it); Milvus and Ollama are designed to degrade specific features rather than crash the app.

**Major components and communication:**
- Routers (`routers/*.py`) stay thin — parse input, delegate to a domain function, return.
- Business logic lives in `engines/` (deterministic rules), `services/` (resolution-style lookups), or a domain's own package (`memory/`, `behaviour/`, `analytics/`, `rag/`).
- Persistence goes through `repositories/` for most collections (users, refresh tokens, statements, jobs, transactions, releases, profiles); a few legacy call sites still query MongoDB directly — documented, intentional tech debt (`ARCHITECTURE.md` §3).
- Two auth layers run independently on nearly every router: `X-Miravelt-API-Key` (identifies the calling app) and JWT access/refresh tokens (identifies the end user); a separate `X-Miravelt-Admin-Key` gates operator-only routes and never falls back to the client key.

**Representative data flow — statement ingestion (the primary product surface):**
`POST /statements/upload` → PDF validated/decrypted on a worker thread (fails fast, 422) → stored in GridFS → `Statement(PENDING)` + `Job(QUEUED)` created, `202` returned → `BackgroundTasks` runs the pipeline: parse → categorize (rule engine) → persist transactions → refresh merchant behavior profiles → embed + write to Milvus → compute analytics → generate insights (Ollama, else computed) → mark `Job` `COMPLETED`. The client polls `GET /jobs/{id}`; a server restart fails any interrupted job cleanly rather than leaving it stuck `RUNNING`.

## 7. Technical Implementation

### Backend
Single async FastAPI service, 14 routers (`auth`, `v1`, `admin`, `analytics`, `app_updates`, `devices`, `jobs`, `memory`, `observability`, `pipelines`, `rag`, `statements`, `users`), each requiring `X-Miravelt-API-Key` except `/health`, `/live`, `/ready`, `/metrics`. No blocking or CPU-heavy work runs on the event loop — PDF parsing and Milvus calls go through `asyncio.to_thread` after a measured incident where a single upload froze `/live` for 35.9 s.

### Frontend (mobile)
Flutter app using Clean Architecture, feature-first (`lib/features/<feature>/{data,domain,presentation}`), classic Riverpod (not the code-generator variant, due to an unresolved `riverpod_generator`/`analyzer` conflict). Router starts on `/splash` and holds while the stored session is checked, so a signed-in user never sees a login flash. A hidden "Developer settings" panel (tap the version 5×) lets QA point a release build at a local/staging backend without a debug build.

### Database
MongoDB via Motor (async driver); GridFS for original PDF retention (auto-deleted after `PDF_RETENTION_DAYS`, default 90). Indexes include a unique partial index on `transactions.(user_id, reference_number)` for idempotent statement re-upload, `users.email` unique, `refresh_tokens.token_hash` unique, and a TTL index on `refresh_tokens.expires_at` so Mongo itself sweeps expired sessions.

### Authentication / Authorization
Three independent checks, composed rather than substituted for each other:
1. `X-Miravelt-API-Key` — identifies the calling application (`core/security.py::validate_api_key`, `secrets.compare_digest`).
2. `X-Miravelt-Admin-Key` — gates `routers/pipelines.py` and `routers/admin.py`; deliberately never falls back to the client key.
3. JWT access tokens (HS256, 15-minute default lifetime, `sub`/`type`/`iat`/`exp`/`jti` claims) plus opaque, SHA-256-hashed, single-use refresh tokens (30-day default) with rotation and theft/reuse detection — a replayed refresh token revokes every other active session for that user.

Passwords are hashed with Argon2id (`argon2-cffi`); login runs password verification even for a nonexistent email (against a throwaway hash) so response timing can't be used to enumerate accounts.

### APIs
REST/JSON over FastAPI, OpenAPI/Swagger auto-generated at `/docs` with both auth schemes registered. Endpoints span statement upload/processing, transaction categorization/feedback, analytics, RAG explanation, memory/trust inspection, batch pipeline triggers, and admin operations (users, jobs, statements, releases).

### AI / ML
- **Categorization:** deterministic regex-based rule engine over a curated merchant-alias table, with a business-keyword fallback (e.g. "canteen", "pharmacy") for unmatched merchants, and honest `Uncategorized`/confidence-0.0 for the rest.
- **Explainability (RAG):** `rag/retriever.py` does a Milvus semantic search for similar merchant behaviors, then pulls the merchant's structured profile, behavior pattern, and recent feedback from MongoDB; `rag/context_builder.py` assembles an XML-tagged grounded prompt; `rag/generator.py` calls Ollama. Zero Milvus hits short-circuits before Ollama is ever called (`NO_CONTEXT_AVAILABLE`).
- **Statement insights:** Ollama-generated first, with a deterministic fallback computed from the same persisted analytics if the LLM fails or returns malformed output — insights are never invented and never come back empty.
- **Clustering:** UMAP projects merchant-behavior vectors to a lower dimension, HDBSCAN clusters them, evaluated with the Davies-Bouldin index.
- **LLM safety:** input/output validated through `core/llm_safety.py` — a `pydantic` schema constrains explanation output shape/length, and a regex-based prompt-injection filter flags suspicious input patterns (e.g. "ignore previous instructions") before it reaches the model.

### Caching
`core/cache.py`'s cache-aside `@cached` decorator, Redis-backed, applied to `routers/analytics.py`'s four read endpoints (3-minute TTL); degrades to a no-op with `REDIS_URI` unset. Never applied to `/v1/explain`, whose correctness depends on always-current retrieved context.

### Background Jobs
Statement processing runs in-process via `fastapi.BackgroundTasks` (one worker), by design — the product's client contract ("create a job, poll it") is decoupled from the execution mechanism, so a real task queue could replace it later with zero API change. Separately, Celery + Redis (when `REDIS_URI` is set) run the batch pipelines (behavior profiling, embedding sync, memory decay, clustering, knowledge-graph rebuild, and retraining-queue checks) on a beat schedule, alongside the pre-existing manual `/v1/pipelines/*` admin-key-gated trigger endpoints.

### Other important implementation details
- **Memory/trust state machine:** a merchant profile promotes EPHEMERAL → TEMPORARY at 3 encounters, → PERMANENT at 10, with a separate decay engine archiving stale profiles.
- **Periodicity/subscription detection:** scores distinct payment timestamps by coefficient of variation of the inter-payment interval, requiring 3+ occurrences and treating sub-daily gaps as bursts, not schedules — flags a subscription only when the interval clusters tightly around ~30 or ~365 days.
- **Confidence wall:** every categorization carries a numeric confidence (0.95 alias match, 0.6 keyword match, 0.0 unmatched, 1.0 user correction, `None` for credits), and a `ConfidenceEngine` actively rejects out-of-vocabulary predictions rather than letting a low-confidence guess pollute analytics.

## 8. Algorithms & Data Structures

- **Regex-based finite matching** (rule engine, merchant resolver, PDF record extraction) — pre-compiled patterns for O(1) amortized startup cost, whole-word boundaries to avoid partial-token false matches.
- **Coefficient of variation (CV = σ/μ) over inter-event intervals**, inverted to a 0–1 periodicity score (`1 / (1 + CV)`) — chosen over naive frequency counting because it's insensitive to the *number* of payments and sensitive to their *regularity*, which is what actually distinguishes a subscription from occasional repeat purchases.
- **A finite-state machine** (4 states: EPHEMERAL, TEMPORARY, PERMANENT, ARCHIVED) with threshold-based, one-directional promotion (except decay-driven archival) — chosen over a raw "trust score" so downstream code can reason about discrete, testable states instead of a continuous value.
- **UMAP** (nonlinear dimensionality reduction, preserves local structure better than PCA/t-SNE for downstream density clustering) → **HDBSCAN** (density-based clustering that doesn't require specifying cluster count up front and naturally labels sparse/noisy points as outliers) — evaluated with the **Davies-Bouldin index** (lower = better-separated clusters).
- **NetworkX graph** over merchant relationships for the knowledge-graph phase (`graphs/graph_builder.py`).
- **SHAP** for post-hoc feature-attribution explainability on the classical ML baseline models (`evaluation/metrics.py`).
- **Vector similarity search** (Milvus) for semantic retrieval in the RAG pipeline — approximate nearest-neighbor lookup over merchant-behavior embeddings, top-k configurable.

## 9. Engineering Decisions

### Decision 1 — Two separate API keys instead of one
- **Problem:** the mobile app's API key ships inside the client binary and is trivially extractable; some endpoints (batch pipelines, release publishing) must never be reachable by anything holding only that key.
- **Options considered:** one shared key for everything; role claims inside the JWT; a fully separate admin auth service.
- **Chosen:** a second, server-only `X-Miravelt-Admin-Key` that never falls back to the client key, checked independently of the JWT layer.
- **Trade-off:** one more secret to provision/rotate, but a leaked client binary can never reach operator-only endpoints — the alternative (JWT role claims) would still require the client key to be sufficient to *reach* the route, which is exactly what needed to be prevented.

### Decision 2 — Statement processing stays in-process (`BackgroundTasks`), not Celery, even though Celery exists in the stack
- **Problem:** statement processing needs to run asynchronously after a `202` response, but a real task queue is real infrastructure to operate.
- **Options considered:** Celery + Redis for statement jobs too; a bespoke thread pool; `BackgroundTasks`.
- **Chosen:** `BackgroundTasks`, with the client contract ("create a job, poll `GET /jobs/{id}`") deliberately decoupled from the execution mechanism.
- **Trade-off:** a server restart kills any in-flight job (mitigated by failing it cleanly at startup rather than leaving it stuck), and horizontal scaling isn't possible until this moves to a real queue — an accepted, documented limitation rather than premature infrastructure. Celery is still used, but only for the separately-scheduled batch pipelines, not statement processing — keeping "one home per responsibility."

### Decision 3 — `/v1/explain` refuses to call the LLM without retrieved context
- **Problem:** an LLM asked to explain a transaction it has no data on will confidently fabricate a plausible-sounding but false explanation.
- **Options considered:** let the LLM answer generically when no context is found; return a generic "no data" message; retry with a broader search.
- **Chosen:** a hard short-circuit (`NO_CONTEXT_AVAILABLE`) before Ollama is ever called when Milvus returns zero hits.
- **Trade-off:** a strictly worse user-facing answer in the no-data case ("I don't have data on this" instead of a plausible guess), traded deliberately for zero-hallucination as a hard product guarantee.

### Decision 4 — Admin dashboard as a BFF, never a second backend
- **Problem:** the admin dashboard needs backend credentials (admin key, JWTs) to operate, but browser-side JavaScript can't be trusted to hold secrets.
- **Options considered:** call the FastAPI backend directly from the browser with a dashboard-specific public key; build a full second backend with its own auth.
- **Chosen:** Next.js Server Actions/Route Handlers as the only place credentials are attached (`"server-only"` guarded files); the browser only ever holds an httpOnly, encrypted session cookie.
- **Trade-off:** every dashboard read/write is an extra network hop through the Next.js server, but no backend secret or raw JWT can ever leak through a browser devtools inspection or XSS.

## 10. Challenges

### Challenge 1 — Silent PDF text-extraction corruption
- **Problem:** the statement parser needed to reliably split Google Pay's PDF export into structured records, but initial extraction produced garbled merchant names.
- **Investigation:** compared `pdfplumber`'s output at several `x_tolerance` settings against a real, anonymized 19-page/184-transaction sample statement; found the library's default tolerance (3) collapses inter-word spacing entirely on this statement's font — `"Paid to Toni and Guy"` extracted as `"PaidtoToniandGuy"`.
- **Solution:** call `extract_text(x_tolerance=1)` specifically, then match the resulting 3-line-per-transaction structure with a purpose-built multi-line regex instead of table/column-position heuristics.
- **Result:** parsing the sample statement and summing DEBIT/CREDIT amounts reconciles *exactly* against the statement's own printed Sent/Received totals — verified as a test assertion, not a one-time manual check.

### Challenge 2 — Nearly every merchant reported as a "recurring payment"
- **Problem:** the periodicity/subscription detector was flagging 69 of 92 merchants as recurring — clearly wrong.
- **Investigation:** traced it to timestamp collisions — the same statement uploaded more than once (or by different users) produced identical transaction timestamps, and zero-day gaps between "different" transactions scored as a perfectly regular (score 1.0) schedule.
- **Solution:** de-duplicate to distinct timestamps before scoring, treat sub-daily average gaps as bursts rather than schedules, and require 3+ occurrences within a single statement for a statement-level recurring flag.
- **Result:** recurring-payment detection now reflects genuine periodicity instead of upload-count artifacts.

### Challenge 3 — A single upload could freeze the entire server
- **Problem:** on a constrained 2-CPU Docker host, a `/live` liveness probe sent mid-upload once waited 35.9 seconds for a response.
- **Investigation:** traced to `pdfplumber` text extraction (pure-Python, CPU-bound) and blocking `pymilvus` calls running directly on the asyncio event loop inside a single-worker Uvicorn process — CPU-bound work on the loop blocks *every* concurrent request, not just the one that triggered it.
- **Solution:** moved PDF parsing, transaction parsing, and Milvus calls onto worker threads via `asyncio.to_thread`.
- **Result:** the server stays responsive to health checks and other requests during processing; documented as a hard architectural invariant going forward ("no blocking or CPU-heavy work on the event loop").

### Challenge 4 — A red CI pipeline and a broken core endpoint
- **Problem:** `/v1/categorize` was silently broken (reading a Pydantic model with `.get()`, a `time.timezone.utc` typo, writing Python object references instead of resolved values to Mongo), and CI never actually ran the test suite successfully.
- **Investigation:** `pytest` in CI defaulted `ENVIRONMENT` to `"production"`, which turned on HTTPS enforcement and rejected every plain-HTTP `TestClient` request with `400 https_required` before it reached a route — masking every other test failure behind an unrelated one.
- **Solution:** fixed the three independent bugs in the categorize handler, set `ENFORCE_HTTPS=false` explicitly in the CI job's environment, and pinned Ruff to match the pre-commit config.
- **Result:** the endpoint works end-to-end (`test_categorize_valid_payload`), and CI now runs a real green suite against a live `mongo:6.0` service container on every push.

## 11. Performance & Scale

Measured on a local Docker stack, Pixel 7 physical device, release build (`PRD.md` §7) — no production traffic exists yet, so these are local/dev-environment measurements, not live numbers:

| Area | Measured |
|---|---|
| Cold start to first frame | 390–700 ms |
| Sign-in (login + profile + periods) | ~0.8 s (0.35 + 0.21 + 0.25 s) |
| Upload acceptance (202) | Seconds; was 30–40 s before moving PDF parsing off the event loop |
| Full statement processing (6-month statement) | ~70 s, dominated by LLM insight generation on CPU |
| Liveness stall during upload (before fix) | 35.9 s — the incident that drove Challenge 3 above |
| Statement reconciliation accuracy | Exact match against a real statement's printed totals (₹80,634.04 sent / ₹28,975 received) |

Dataset used for parser validation: one real, anonymized Google Pay statement, 19 pages, 184 transactions, spanning Jan–Jun 2026.

## 12. Testing

- **Backend:** `pytest` + FastAPI's `TestClient`, run directly against the real `app` object (module-scoped fixture triggers the real `lifespan`, so tests exercise real MongoDB connections — nothing is mocked). 61 test functions in `test_api.py` covering health checks, both auth layers (API key + JWT, including rotation/reuse/expiry/malformed-token edge cases), rate limiting, categorization, memory-state promotion, the confidence wall, analytics, feedback → retraining-queue triggering, RAG safety, the full statement-upload → job → transactions → analytics → insights → feedback → delete lifecycle, and app-release publishing/download.
- **Frontend:** `flutter analyze` + `flutter test` (widget/unit tests under `test/features/`, mirroring the `lib/` feature structure, with shared fakes for HTTP and secure storage in `test/support/`).
- **CI enforcement:** every push/PR runs gitleaks (secret scan), Ruff (lint), pip-audit (dependency vulnerabilities), the full pytest suite against a real `mongo:6.0` service container, Flutter analyze/test, and — gated on lint+test passing — hadolint (Dockerfile lint) + a `docker build` + Trivy image scan.
- **Manual:** `scripts/test_pipeline.sh`, a curl-driven end-to-end smoke test against a running server.
- **Known gap (honest, not hidden):** the rule engine, feature extractors (entropy/CV/periodicity math), and most batch-pipeline engines (behavior, clustering, embeddings, graph builder, training) have no direct unit tests — they're exercised indirectly through the API-level tests and were manually verified end-to-end against a live MongoDB during the hardening pass, but don't have dedicated `pytest` coverage yet.

## 13. Security

- **Three independent auth checks**, composed not substituted: app-level API key, user-level JWT, and a separate admin key that never falls back to the client key (see §9, Decision 1).
- **Password storage:** Argon2id via `argon2-cffi` (OWASP's current top recommendation), constant-time verification, and timing-attack-resistant login (verifies against a throwaway hash even for a nonexistent email).
- **Refresh-token security:** opaque (not JWT) tokens, only a SHA-256 hash persisted, single-use with rotation, and reuse detection that revokes every other active session for the user on a suspected-theft signal.
- **Request signing (scaffolded):** HMAC-SHA256 request signing with nonce-based replay protection (`core/request_signing.py`), gated behind a `REQUEST_SIGNING_REQUIRED` flag for future tightening.
- **Device attestation (scaffolded):** Google Play Integrity and Apple App Attest/DeviceCheck verification (`core/device_attestation.py`), gated behind `DEVICE_ATTESTATION_REQUIRED`.
- **LLM input/output safety:** a regex-based prompt-injection filter on inbound text (`core/llm_safety.py`) and a Pydantic-validated, length-bounded schema on LLM output before it's ever returned to a client.
- **DLP redaction:** a dedicated redactor (`core/dlp_redaction.py`) strips SSNs, card numbers, account numbers, emails, phone numbers, JWTs, and API keys from logs/response payloads.
- **Input validation:** centralized request-size/body limits (`MAX_REQUEST_BODY_BYTES`, PDF/APK-specific ceilings) and string-length constraints in `core/config.py`/`core/input_validation.py`.
- **Rate limiting:** SlowAPI, per-IP, with tighter limits on auth endpoints (`5/min` register, `10/min` login) than the global default (`100/min`); becomes distributed (Redis-backed) rather than per-process once `REDIS_URI` is set.
- **Secrets never reach the browser:** the admin dashboard's `"server-only"`-guarded files are the sole place any backend secret or JWT is attached to a request — enforced by code review discipline and documented as a hard invariant (`ARCHITECTURE.md` §6).
- **Secret hygiene:** gitleaks in pre-commit and CI; a previously committed plaintext MongoDB credential was found and remediated (variable substitution + a documented rotation requirement for the exposed credential).
- **Dependency/image scanning:** `pip-audit` (Python deps), Trivy (container image), hadolint (Dockerfile), all wired into CI.
- **Privacy by design:** no bank or card access at all; PDF retention is opt-in and auto-expires after 90 days; the statement is the only data source ever ingested.

## 14. Deployment

- **Hosting:** Docker containers, deployed via Coolify (webhook-triggered from CI).
- **CI/CD:** GitHub Actions — `main` branch pushes (all checks green) trigger an automatic staging deploy webhook; `vX.Y.Z` tags (all checks green) trigger a production deploy webhook gated by a GitHub Environment's required reviewers. Both stages no-op gracefully if their webhook secret isn't configured, matching the codebase's general "degrade, don't hard-fail" posture.
- **Docker:** multi-stage build — a `builder` stage compiles/installs dependencies, a slim `runtime` stage (non-root `miravelt` system user) copies only the installed packages and app code. Health-checked against `/live` (never `/health`) specifically so a transient Mongo/Milvus/Ollama outage doesn't trigger a restart-loop.
- **Environments:** `docker-compose_local.yaml` (dev — Mongo only, Milvus/Ollama run separately), `docker-compose.staging.yaml`, `docker-compose_production.yaml` (credential-free, `${VAR:?required}` substitution only).
- **Monitoring:** Prometheus metrics via `prometheus-fastapi-instrumentator`; split liveness (`/live`) vs. readiness (`/ready`, gated only on MongoDB) so dependency outages degrade features instead of killing the process.
- **Config:** fail-fast `Settings` (Pydantic Settings) — the app refuses to start on a missing or weak required secret (e.g. a `JWT_SECRET_KEY` under 32 characters), never on a silently-defaulted one.
- **Domain:** none live yet — `PRD.md` §10 explicitly lists "no production deployment" and "no live host" as open pre-launch risks.

## 15. Results / Impact

Honest accounting, per `PRD.md`'s own status line: **pre-production, no live deployment or users yet.** What exists and is verifiable:

- A fully built, internally-consistent three-app product (backend + mobile + admin dashboard) plus a marketing site, all in one repository, with the entire mobile golden path (register → upload → Analysing → Overview → drill-down → correction) shipped and working against the local stack per `PRD.md` §5.
- A documented, verified hardening pass: every previously-tracked critical/high/medium defect fixed and verified (`docs/16-known-issues-tech-debt.md`), a measured 35.9 s event-loop stall eliminated, all known CVEs in pinned dependencies patched (`pip-audit`-verified), and a real green CI pipeline (secret scan, lint, dependency audit, 61-test suite against live MongoDB, Flutter analyze/test, container scan).
- A statement parser whose output reconciles *exactly* against a real statement's own printed totals — a concrete, checkable correctness claim rather than a vibes-based "it seems to work."
- No user-facing or business metrics exist yet (`PRD.md` §8 explicitly lists activation/time-to-insight/categorization-quality/return-use as "proposed — not yet instrumented").

## 16. What I Learned

- **Technical:** how much correctness work sits between "the LLM/ML pipeline runs" and "the LLM/ML pipeline can be trusted" — the grounded-RAG guard, the confidence wall, and the deterministic-insight fallback all exist because an ungrounded generation looks fine until it silently invents a number.
- **Engineering:** async Python correctness is mostly about *what you didn't wrap in `asyncio.to_thread`* — a single blocking library call inside an `async def` handler degrades the entire process, not just that request, which only became visible under a real measured incident, not code review.
- **Testing discipline:** a test suite that imports the real app and hits a real database (rather than mocking everything) caught infrastructure-level bugs (the CI `ENFORCE_HTTPS` issue, the startup import crash) that a fully mocked suite would have hidden.
- **Mistakes / what I'd do differently:** several routers still bypass the repository layer for direct MongoDB access (`routers/v1.py`, `routers/pipelines.py`) — convenient early on, now documented tech debt that should have had a repository from the start; training/fine-tuning scripts still run on synthetic data rather than a real Mongo-backed data-assembly pipeline, which I'd sequence earlier next time since it blocks any real model-quality claim.

## 17. Future Improvements

- **Planned / open features (from `PRD.md` §10 and `docs/16-known-issues-tech-debt.md` §16.5):**
  - Self-serve account deletion (currently support-ticket only).
  - A registered share-target so a PDF can be shared directly from the Google Pay app into Miravelt.
  - Wiring `/v1/explain` into the mobile app (the endpoint exists and is tested; the client doesn't call it yet).
  - A production deployment with a real host, Play Console listing, and issued production API keys.
- **Known limitations:**
  - Statement processing is in-process (`BackgroundTasks`, one worker) — a restart loses in-flight jobs (failed cleanly, not silently) and horizontal scaling needs a real task queue first.
  - Training pipelines (`training/train.py`, `training/finetune.py`) generate synthetic data rather than querying real transaction/feedback history.
  - Observability endpoints (`routers/observability.py`) are stubs pending an actual ML-observability platform (e.g. Evidently AI/MLflow).
  - Theme setting (Light/Dark/Auto) is stored but has almost no visible effect — screens use fixed surfaces.
- **Technical debt:** a handful of legacy direct-MongoDB access sites outside the repository pattern; caching not yet applied to the two most expensive read paths (`/v1/explain`, `/v1/resolve`).
- **Potential redesigns:** move statement processing onto the already-present Celery/Redis infrastructure to remove the single-process constraint entirely.

## 18. Evidence & Links

- **Repository:** `git@github.com:lokeshramchand-ctrl/velar-backend.git`.
- **Documentation:** `ARCHITECTURE.md`, `PRD.md`, `DESIGN_SYSTEM.md`, `docs/README.md` (indexes 16+ numbered engineering docs plus a per-endpoint API reference and a legal/compliance checklist) — all in-repo, not published externally.
- **No live demo / deployment** exists yet (see §15).
- **Key commits/evidence for specific claims:** see §21 below — every claim there cites a specific file.

## 21. Facts / Claims

- Solo project, 204 commits, single author across the full git history.
  Evidence: `git log --format='%an <%ae>'` — 100% one author/email.

- Active development window 2026-06-15 to 2026-09-25 (~3.5 months).
  Evidence: `git log --reverse` first commit date vs. `git log -1` latest commit date.

- Backend is ~10,300 lines of Python across the repo (excluding `frontend/`).
  Evidence: `find . -name "*.py" ... | xargs wc -l` → 10,309 total.

- Flutter mobile app is ~15,600 lines of Dart across 13 feature modules.
  Evidence: `find frontend/lib -name "*.dart" | xargs wc -l` → 15,624 total; `frontend/lib/features/` directory listing.

- Admin dashboard is ~1,500 lines of TypeScript/TSX.
  Evidence: `find admin-dashboard/src -name "*.ts*" | xargs wc -l` → 1,511 total.

- 61 backend test functions in a single pytest file, run against a real MongoDB, nothing mocked.
  Evidence: `test_api.py` (61 `def test_...` matches); module-scoped `client` fixture triggers the real FastAPI `lifespan`.

- CI runs gitleaks, ruff, pip-audit, pytest (against `mongo:6.0` service container), Flutter analyze/test, hadolint + Trivy, and tag/branch-gated Coolify deploy webhooks.
  Evidence: `.github/workflows/ci.yml`.

- Statement parser reconciles exactly against a real Google Pay statement's printed totals (₹80,634.04 sent / ₹28,975 received, 19 pages, 184 transactions, Jan–Jun 2026).
  Evidence: `docs/23-statements-pipeline.md` §23.3; `mock/gpay_statement_20260101_20260630.pdf`.

- A measured 35.9-second `/live` liveness stall occurred during a statement upload before PDF parsing/Milvus calls were moved to `asyncio.to_thread`.
  Evidence: `ARCHITECTURE.md` §3; `docs/16-known-issues-tech-debt.md` §16.3 ("Statement upload froze the whole server").

- A periodicity-detection bug previously flagged 69 of 92 merchants as "recurring" due to duplicate-upload timestamp collisions; fixed by de-duplicating timestamps and requiring 3+ occurrences.
  Evidence: `docs/16-known-issues-tech-debt.md` §16.3; `features/periodicity.py`.

- Two independent, non-substitutable auth layers (API key + JWT) plus a separate admin key that never falls back to the client key.
  Evidence: `core/security.py::validate_api_key`/`validate_admin_key`, `core/jwt_auth.py`, `docs/22-authentication.md`.

- Refresh tokens are opaque (not JWTs), SHA-256-hashed at rest, single-use, with reuse detection that revokes every session for the user.
  Evidence: `docs/22-authentication.md` §22.3.

- Passwords hashed with Argon2id via `argon2-cffi`.
  Evidence: `requirements.txt` (`argon2-cffi==25.1.0`); `docs/22-authentication.md` §22.4.

- `/v1/explain` is architecturally forbidden from calling the LLM without retrieved Milvus context.
  Evidence: `rag/retriever.py`; `ARCHITECTURE.md` §3 ("NO_CONTEXT_AVAILABLE short-circuit").

- Project status is pre-production with no live deployment or users as of the most recent update.
  Evidence: `PRD.md` line 3 ("Status: pre-production... No production deployment exists yet").

- Security modules present and implemented: HMAC request signing (`core/request_signing.py`), device attestation for Play Integrity/App Attest (`core/device_attestation.py`), DLP redaction (`core/dlp_redaction.py`), LLM prompt-injection filtering (`core/llm_safety.py`).
  Evidence: file contents read directly, `core/` directory listing (2,255 total lines across 18 modules).

## 22. Keywords

FastAPI, Python 3.12, Async I/O, MongoDB, Motor, GridFS, Milvus, Vector Search, RAG (Retrieval-Augmented Generation), Ollama, LLM, Embeddings, UMAP, HDBSCAN, Clustering, NetworkX, Knowledge Graph, scikit-learn, LightGBM, XGBoost, SHAP, LoRA Fine-Tuning, HuggingFace Transformers/PEFT, Celery, Redis, Docker, Multi-stage Docker Build, GitHub Actions, CI/CD, Coolify, Prometheus, JWT Authentication, Argon2id, HMAC Request Signing, Rate Limiting, SlowAPI, Device Attestation, DLP Redaction, Flutter, Dart, Riverpod, Clean Architecture, go_router, Next.js 16, React 19, Server Actions, BFF (Backend-for-Frontend), TypeScript, PDF Parsing, pdfplumber, pypdf, REST API, OpenAPI/Swagger, pytest, Argon2, Regex Engines, Finite State Machines, Statistical Anomaly Detection, Subscription Detection.
