# varunmundas-de-stack/convai-nl2sql architecture

> Architecture diagram of the GitHub repository varunmundas-de-stack/convai-nl2sql, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-06-01). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/varunmundas-de-stack/convai-nl2sql
- Repository: https://github.com/varunmundas-de-stack/convai-nl2sql

## Overview

1. **System boundary**
   This repo is a full-stack NL-to-SQL analytics platform. The main runtime path is: browser UI → FastAPI backend → Cube.js semantic layer → PostgreSQL warehouse → JSON response back to the UI. Around that core are supporting subsystems for authentication, clarification, insight generation, caching/session memory, RLHF feedback, and ETL ingestion.

2. **Frontend surface**
   The frontend is a Next.js 14 app under `frontend/src/app` with three primary user experiences: the conversational entry point (`/`), a KPI dashboard (`/dashboard`), and an insights view (`/insights` plus detail pages). The React components in `frontend/src/components` render chat bubbles, clarification prompts, charts, tables, and feedback controls. `frontend/src/services/api.ts` is the single HTTP client boundary to the backend.

3. **Backend entry points**
   The FastAPI app in `backend/app/main.py` is the main integration layer. It exposes routes for query execution, clarification continuation, retries, catalog discovery, insights, dashboard KPIs, auth, and RLHF/feedback. This is the place where request-level concerns meet the business pipeline.

4. **Security and tenant isolation**
   Authentication is JWT-based (`backend/app/security/auth.py`), with backend-side token issuance and request context handling. A second, Cube-specific JWT is minted per request so the browser does not directly hold Cube credentials. Row-level access control is enforced at the semantic-query layer via Cube.js query rewriting, driven by user role/hierarchy metadata stored in the backend security modules.

5. **Core NL2SQL orchestration**
   The main query flow is implemented as a staged pipeline in `backend/app/pipeline` and supported by the DSPy-based agent stack in `backend/app/dspy_pipeline`. A user question is turned into a structured Query Context Object, merged with any prior session context, optionally paused for clarification, validated against the catalog and RBAC rules, converted into a Cube query, executed, then summarized into a narrative plus chart recommendation.

6. **Intent understanding and query normalization**
   The `backend/app/services/intent` package and the DSPy agent modules cover extraction, decomposition, classification, scope handling, dimension selection, metric selection, time-window interpretation, and validation. The important architectural boundary here is that free-form language is normalized into a constrained internal schema before any warehouse query is allowed.

7. **Semantic query execution**
   `backend/app/services/cube` turns validated intent into Cube.js load queries. Cube.js itself is the semantic/data-access boundary: the model in `cube/model/cubes` defines facts and dimensions, and Cube translates the request into optimized SQL against PostgreSQL. This keeps the backend from constructing raw SQL directly for the main analytics path.

8. **Data warehouse and semantic model**
   PostgreSQL is the system of record for analytics data. The `cube/data` scripts initialize and seed the warehouse, while `cube/model` defines the business semantics over fact tables such as primary and secondary sales plus shared dimension tables. The Cube layer sits on top of this warehouse and is the main contract for analytics consumers.

9. **State, caching, and conversational memory**
   Redis is used for session state and conversational context, enabling follow-up questions to inherit prior intent. The backend also has cache/memory-related services (`cache_manager`, `redis_session`, `memory_manager`) to avoid recomputing common queries and to preserve short-term user context. The README describes a layered cache strategy, which is important because it changes the runtime path for repeated questions.

10. **Insights and proactive analytics**
   There is a separate insights subsystem under `backend/app/insights_router.py`, `backend/app/insight_generator.py`, and `backend/app/services/insights`. It appears to generate role-aware alerts and narrative insights from the warehouse, independent of the interactive chat flow. The `backend/app/intel` package adds scheduled, stepwise processing for profile/watch/execute/detect/narrate/store workflows, which suggests background intelligence jobs rather than user-triggered queries.

11. **RLHF and feedback loop**
   The `backend/app/rlhf` package is a distinct feedback/experimentation loop. It includes feedback collection, prompt management, A/B routing, scheduling, and a SQLite-backed store (`backend/rlhf.db`). This subsystem sits beside the main query pipeline and is used to refine prompts and responses over time.

12. **ETL and data onboarding**
   New source data is ingested through `backend/etl/cpg_etl.py` and the Dockerized watch-mode ETL service described in the README. CSV files dropped into a watched directory are upserted into dimension and fact tables, then archived. This is the data onboarding boundary that feeds the warehouse used by Cube.js and the analytics pipeline.

13. **Infrastructure and deployment**
   The app is containerized with Docker Compose, with separate services for frontend, backend, Cube.js, PostgreSQL, Redis, and the ETL watcher. The repo also includes AWS deployment scripts and Nginx config under `aws-deploy`, so the deployment topology is a multi-service single-host setup rather than a serverless architecture.

14. **Testing and contract protection**
   The backend test suite includes API end-to-end tests, catalog contract tests, clarification tests, intent validation, and data sanity checks. That indicates the repo relies heavily on schema/catalog correctness and pipeline behavior stability, which are critical architectural contracts for a natural-language analytics system.

Main entry points: [`backend/app/main.py`](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/main.py) (FastAPI app), [`backend/app/pipeline/runner.py`](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/pipeline/runner.py) (NL2SQL pipeline), [`docker-compose.yml`](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/docker-compose.yml) (Deployment), [`frontend/src/app`](https://github.com/varunmundas-de-stack/convai-nl2sql/tree/main/frontend/src/app) (App shell)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_frontend["Frontend"]
  node_frontend_app["App shell<br/>nextjs app"]
  node_frontend_chat["Chat UI<br/>conversation UI"]
  node_frontend_dashboard["Dashboard<br/>kpi view<br/>[page.tsx]"]
  node_frontend_insights["Insights views<br/>insights ui"]
  node_frontend_rlhf["RLHF page<br/>feedback ui<br/>[page.tsx]"]
  node_frontend_api["API client<br/>http client<br/>[api.ts]"]
  node_frontend_state["Conversation state<br/>client state<br/>[conversation.ts]"]
end

subgraph group_backend["Backend"]
  node_backend_main["FastAPI app<br/>api gateway<br/>[main.py]"]
  node_backend_security["Security<br/>authz/authn<br/>[auth.py]"]
  node_backend_pipeline["NL2SQL pipeline<br/>orchestrator<br/>[runner.py]"]
  node_backend_intent["Intent stack<br/>nl2sql intent"]
  node_backend_qco["QCO store<br/>session/qco<br/>[qco_store.py]"]
  node_backend_cube["Cube adapter<br/>semantic query"]
  node_backend_cache["Memory & cache<br/>session/cache<br/>[cache_manager.py]"]
  node_backend_insights["Insights engine<br/>proactive analytics<br/>[insight_engine.py]"]
  node_backend_rlhf["RLHF loop<br/>feedback pipeline<br/>[router.py]"]
  node_backend_intel["Intel jobs<br/>background workflow<br/>[scheduler.py]"]
  node_backend_llm["LLM service<br/>model gateway<br/>[service.py]"]
end

subgraph group_analytics["Analytics Stack"]
  node_cube_model["Cube model<br/>semantic model"]
  node_warehouse[("PostgreSQL<br/>warehouse")]
end

subgraph group_infra["Infrastructure"]
  node_etl_ingest["ETL ingest<br/>data onboarding<br/>[cpg_etl.py]"]
  node_deploy["Deployment<br/>docker/ops<br/>[docker-compose.yml]"]
end

node_frontend_app -->|"renders"| node_frontend_chat
node_frontend_app -->|"renders"| node_frontend_dashboard
node_frontend_app -->|"renders"| node_frontend_insights
node_frontend_app -->|"renders"| node_frontend_rlhf
node_frontend_chat -->|"calls"| node_frontend_api
node_frontend_dashboard -->|"calls"| node_frontend_api
node_frontend_insights -->|"calls"| node_frontend_api
node_frontend_rlhf -->|"calls"| node_frontend_api
node_frontend_chat -->|"uses"| node_frontend_state
node_frontend_api -->|"HTTP"| node_backend_main
node_backend_main -->|"authenticates"| node_backend_security
node_backend_main -->|"orchestrates"| node_backend_pipeline
node_backend_main -->|"serves"| node_backend_insights
node_backend_main -->|"routes"| node_backend_rlhf
node_backend_main -->|"schedules"| node_backend_intel
node_backend_pipeline -->|"normalizes"| node_backend_intent
node_backend_pipeline -->|"persists"| node_backend_qco
node_backend_pipeline -->|"reuses"| node_backend_cache
node_backend_pipeline -->|"queries"| node_backend_cube
node_backend_pipeline -->|"summarizes"| node_backend_llm
node_backend_intent -->|"interprets"| node_backend_llm
node_backend_cube -->|"targets"| node_cube_model
node_cube_model -->|"reads"| node_warehouse
node_etl_ingest -->|"loads"| node_warehouse
node_backend_insights -->|"refines"| node_backend_llm
node_backend_insights -->|"reads"| node_backend_cube
node_backend_rlhf -->|"tunes"| node_backend_llm
node_backend_intel -->|"analyzes"| node_backend_cube
node_backend_security -->|"tracks"| node_backend_cache
node_deploy -.->|"deploys"| node_frontend_app
node_deploy -.->|"deploys"| node_backend_main
node_deploy -.->|"deploys"| node_cube_model
node_deploy -.->|"deploys"| node_warehouse
node_deploy -.->|"deploys"| node_etl_ingest

click node_frontend_app "https://github.com/varunmundas-de-stack/convai-nl2sql/tree/main/frontend/src/app"
click node_frontend_chat "https://github.com/varunmundas-de-stack/convai-nl2sql/tree/main/frontend/src/components"
click node_frontend_dashboard "https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/frontend/src/app/dashboard/page.tsx"
click node_frontend_insights "https://github.com/varunmundas-de-stack/convai-nl2sql/tree/main/frontend/src/app/insights"
click node_frontend_rlhf "https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/frontend/src/app/rlhf/page.tsx"
click node_frontend_api "https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/frontend/src/services/api.ts"
click node_frontend_state "https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/frontend/src/state/conversation.ts"
click node_backend_main "https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/main.py"
click node_backend_security "https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/security/auth.py"
click node_backend_pipeline "https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/pipeline/runner.py"
click node_backend_intent "https://github.com/varunmundas-de-stack/convai-nl2sql/tree/main/backend/app/services/intent"
click node_backend_qco "https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/pipeline/qco_store.py"
click node_backend_cube "https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/services/cube/cube_query_builder.py"
click node_backend_cache "https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/services/cache_manager.py"
click node_backend_insights "https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/services/insights/insight_engine.py"
click node_backend_rlhf "https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/rlhf/router.py"
click node_backend_intel "https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/intel/scheduler.py"
click node_backend_llm "https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/llm/service.py"
click node_cube_model "https://github.com/varunmundas-de-stack/convai-nl2sql/tree/main/cube/model/cubes"
click node_warehouse "https://github.com/varunmundas-de-stack/convai-nl2sql/tree/main/cube/data"
click node_etl_ingest "https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/etl/cpg_etl.py"
click node_deploy "https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/docker-compose.yml"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_frontend_app,node_frontend_chat,node_frontend_dashboard,node_frontend_insights,node_frontend_rlhf,node_frontend_api,node_frontend_state toneBlue
class node_backend_main,node_backend_security,node_backend_pipeline,node_backend_intent,node_backend_qco,node_backend_cube,node_backend_cache,node_backend_insights,node_backend_rlhf,node_backend_intel,node_backend_llm toneAmber
class node_cube_model,node_warehouse toneMint
class node_etl_ingest,node_deploy toneRose
```

## Components

### Frontend

Next.js user interfaces and browser-side state.

- [App shell](https://github.com/varunmundas-de-stack/convai-nl2sql/tree/main/frontend/src/app): nextjs app · Top-level Next.js routes and layout for the conversational analytics UI. · `frontend/src/app`
- [Chat UI](https://github.com/varunmundas-de-stack/convai-nl2sql/tree/main/frontend/src/components): conversation UI · Conversation entry point, message rendering, clarification prompts, retries, and feedback controls. · `frontend/src/components`
- [Dashboard](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/frontend/src/app/dashboard/page.tsx): kpi view · KPI-focused analytics surface for summary metrics and charts. · `frontend/src/app/dashboard/page.tsx`
- [Insights views](https://github.com/varunmundas-de-stack/convai-nl2sql/tree/main/frontend/src/app/insights): insights ui · Insights list and detail pages for proactive analytics content. · `frontend/src/app/insights`
- [RLHF page](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/frontend/src/app/rlhf/page.tsx): feedback ui · Frontend surface for feedback and experimentation workflows. · `frontend/src/app/rlhf/page.tsx`
- [API client](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/frontend/src/services/api.ts): http client · Single browser-to-backend HTTP boundary. · `frontend/src/services/api.ts`
- [Conversation state](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/frontend/src/state/conversation.ts): client state · Browser-side conversation state and parsing helpers. · `frontend/src/state/conversation.ts`

### Backend

FastAPI orchestration, security, analytics, insights, and feedback services.

- [FastAPI app](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/main.py): api gateway · Main backend integration layer for query execution, clarification, insights, dashboards, auth, and feedback routes. · `backend/app/main.py`
- [Security](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/security/auth.py): authz/authn · JWT auth, request context, and tenant metadata handling. · `backend/app/security/auth.py`
- [NL2SQL pipeline](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/pipeline/runner.py): orchestrator · Staged query orchestration from question to validated query context and response. · `backend/app/pipeline/runner.py`
- [Intent stack](https://github.com/varunmundas-de-stack/convai-nl2sql/tree/main/backend/app/services/intent): nl2sql intent · Extraction, classification, decomposition, normalization, and validation of user questions. · `backend/app/services/intent`
- [QCO store](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/pipeline/qco_store.py): session/qco · Persistent query context and state management across follow-up turns. · `backend/app/pipeline/qco_store.py`
- [Cube adapter](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/services/cube/cube_query_builder.py): semantic query · Builds Cube load queries from validated intent and period planning. · `backend/app/services/cube/cube_query_builder.py`
- [Memory & cache](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/services/cache_manager.py): session/cache · Redis session handling, cache manager, and short-term conversational memory. · `backend/app/services/cache_manager.py`
- [Insights engine](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/services/insights/insight_engine.py): proactive analytics · Role-aware insight generation, refinement, and visual spec construction. · `backend/app/services/insights/insight_engine.py`
- [RLHF loop](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/rlhf/router.py): feedback pipeline · Feedback collection, prompt management, routing, A/B logic, and refinement. · `backend/app/rlhf/router.py`
- [Intel jobs](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/intel/scheduler.py): background workflow · Scheduled stepwise profile, watch, execute, detect, narrate, and store workflows. · `backend/app/intel/scheduler.py`
- [LLM service](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/app/llm/service.py): model gateway · Backend wrapper around LLM calls used by query, insight, and refinement flows. · `backend/app/llm/service.py`

### Analytics Stack

Cube semantic layer and PostgreSQL warehouse.

- [Cube model](https://github.com/varunmundas-de-stack/convai-nl2sql/tree/main/cube/model/cubes): semantic model · Cube.js dimensions, facts, and views defining the analytics contract. · `cube/model/cubes`
- [PostgreSQL](https://github.com/varunmundas-de-stack/convai-nl2sql/tree/main/cube/data): warehouse · System of record for analytics facts and dimensions. · `cube/data`

### Infrastructure

ETL, deployment, and runtime support.

- [ETL ingest](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/backend/etl/cpg_etl.py): data onboarding · CSV/watch-mode ingestion and warehouse loading for new source data. · `backend/etl/cpg_etl.py`
- [Deployment](https://github.com/varunmundas-de-stack/convai-nl2sql/blob/main/docker-compose.yml): docker/ops · Compose-based multi-service deployment and AWS/Nginx packaging. · `docker-compose.yml`

## Connections

- App shell → Chat UI: renders · Top-level routes compose the conversational experience.
- App shell → Dashboard: renders · Dashboard route surfaces KPI analytics.
- App shell → Insights views: renders · Insights routes show proactive analytics content.
- App shell → RLHF page: renders · RLHF route exposes feedback workflows.
- Chat UI → API client: calls · All browser requests go through the shared API client.
- Dashboard → API client: calls · Dashboard data is fetched from the backend.
- Insights views → API client: calls · Insights pages fetch backend-generated insight data.
- RLHF page → API client: calls · Feedback interactions are submitted to backend routes.
- Chat UI → Conversation state: uses · Conversation state supports follow-up questions and clarification.
- API client → FastAPI app: HTTP · Browser traffic terminates at the FastAPI application.
- FastAPI app → Security: authenticates · Request handling is protected by JWT and tenant context.
- FastAPI app → NL2SQL pipeline: orchestrates · Main NL2SQL requests enter the staged query pipeline.
- FastAPI app → Insights engine: serves · Insight routes produce proactive analytics responses.
- FastAPI app → RLHF loop: routes · Feedback and experimentation endpoints are separated from core query flow.
- FastAPI app → Intel jobs: schedules · Background intelligence workflows are exposed through the backend.
- NL2SQL pipeline → Intent stack: normalizes · Free-form language is converted into constrained intent structures.
- NL2SQL pipeline → QCO store: persists · Structured query context is stored across turns.
- NL2SQL pipeline → Memory & cache: reuses · Session and cache layers shortcut repeated work and preserve context.
- NL2SQL pipeline → Cube adapter: queries · Validated intent is converted into semantic Cube queries.
- NL2SQL pipeline → LLM service: summarizes · LLM calls generate narratives and clarifications.
- Intent stack → LLM service: interprets · LLM-backed agents support classification and validation steps.
- Cube adapter → Cube model: targets · Cube queries execute against the semantic model.
- Cube model → PostgreSQL: reads · Cube translates semantic requests into SQL over PostgreSQL.
- ETL ingest → PostgreSQL: loads · ETL populates the warehouse with source data and dimensions.
- Insights engine → LLM service: refines · Narratives and visual specifications are generated and refined with model assistance.
- Insights engine → Cube adapter: reads · Insights are computed from warehouse-backed semantic queries.
- RLHF loop → LLM service: tunes · Feedback loop updates prompts and routing behavior.
- Intel jobs → Cube adapter: analyzes · Scheduled jobs execute data-driven detection and narration steps.
- Security → Memory & cache: tracks · Context and tenant state can be reused across requests.
- Deployment → App shell: deploys · Compose and AWS packaging include the frontend service.
- Deployment → FastAPI app: deploys · Compose and AWS packaging include the backend service.
- Deployment → Cube model: deploys · Cube service is part of the deployment topology.
- Deployment → PostgreSQL: deploys · PostgreSQL is provisioned as a core service.
- Deployment → ETL ingest: deploys · Watch-mode ETL runs alongside the application stack.
