Spaces:
Paused

miracle / docs /architecture.md
dushyantsingh0
backend stabilization
9f4dea0
|
Raw History Blame Contribute Delete
11 kB
# System Architecture
## Overview
Nexus is structured as a monolith-in-a-container: a single Docker image runs the FastAPI API server, two ARQ background worker processes, an embedded Redis instance (for pub/sub), and the compiled React frontend served as static files. This keeps deployment simple while maintaining clean internal separation between layers.
```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Docker Container β”‚
β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ Gunicorn β”‚ β”‚ ARQ Regular β”‚ β”‚ ARQ Heavy β”‚ β”‚
β”‚ β”‚ (4 uvicorn β”‚ β”‚ Worker β”‚ β”‚ Worker β”‚ β”‚
β”‚ β”‚ workers) β”‚ β”‚ (SLA, notify) β”‚ β”‚ (AI, embed) β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ Local Redis (pub/sub, ephemeral) β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ β”‚ β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”
β”‚ PostgreSQL β”‚ β”‚ Redis β”‚ β”‚ Ollama β”‚
β”‚ (Supabase/ β”‚ β”‚ (Upstash, β”‚ β”‚ (local, β”‚
β”‚ Neon) β”‚ β”‚ cloud) β”‚ β”‚ embeddings)β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```
---
## Layer responsibilities
### API layer (`api/v1/`)
Twenty FastAPI router modules handle HTTP and WebSocket traffic. Each router depends on `core/deps.py` for JWT validation and workspace-context resolution. Business logic is delegated to the services layer or directly to SQLAlchemy queries for simple CRUD. Routers never import from one another.
Key routers:
| Router | Lines | Responsibility |
|---|---|---|
| `auth.py` | 554 | Registration, login, refresh, password reset, admin provisioning |
| `tickets.py` | 267 | Ticket CRUD, status transitions, assignment |
| `messages.py` | 352 | Thread messages, internal/public flagging |
| `kb.py` | 1,213 | KB article CRUD, versioning, semantic search, bulk sync |
| `nexus.py` | 607 | Master agent query interface (RBAC-isolated) |
| `nexus_stream.py` | 222 | Streaming SSE responses for long AI operations |
| `dashboard.py` | 487 | Workspace telemetry and AI-generated insights |
| `reports.py` | 657 | SLA audit, personnel analytics, sentiment reports |
| `websockets.py` | 85 | WebSocket upgrade and pub/sub subscription |
### Services layer (`services/`)
Stateless async classes that encapsulate workspace-aware business logic. The `TicketService` handles hybrid search, role-based field sanitization (customers see different fields than staff), and telemetry aggregation. Services receive a `db: AsyncSession` via dependency injection and are the only layer that issues complex queries.
### Core infrastructure (`core/`)
| Module | Purpose |
|---|---|
| `config.py` | Pydantic `BaseSettings`; all env var parsing with computed URL properties |
| `database.py` | Two SQLAlchemy engine configs: `AsyncAdaptedQueuePool` (API, max 70) and `NullPool` (workers) |
| `deps.py` | FastAPI dependencies β€” JWT decode, workspace-context resolution, role gate |
| `security.py` | Password hashing (bcrypt), token generation, JTI-based revocation |
| `cache.py` | L1 in-process LRU (2 048 entries) + L2 Redis + semantic vector cache |
| `websockets.py` | Redis pub/sub manager; fanout to workspace and ticket-scoped channels |
| `permissions.py` | Role-hierarchy helpers used by route guards and agent output masking |
| `audit.py` | Append-only compliance log for sensitive actions |
| `observability.py` | OpenTelemetry OTLP tracing instrumentation |
### Models (`models/`)
Thirty SQLAlchemy models. All use UUID primary keys, UTC timestamps (`created_at`, `updated_at`), and a `deleted_at` soft-delete column. Key entities:
```
Workspace ──< UserWorkspace >── User
β”‚
β”Œβ”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”
Ticket NexusThread
β”‚ β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β” NexusInteraction
Message Attachment Escalation
β”‚
Feedback
Project ──< KBArticle ──< KBArticleChunk
└──< KBArticleVersion
└──< KnowledgeInsight
WorkerJob NexusMemory NexusCheckpoint Notification
```
Search optimization on `Ticket` and `KBArticle`:
- `TSVECTOR` computed column + GIN index for full-text search
- `pgvector` column + HNSW index (768-dim) for semantic similarity
- `content_hash` for deduplication
---
## Request lifecycle
```
Client
β”‚
β–Ό
Gunicorn/Uvicorn
β”‚
β–Ό
FastAPI middleware stack
β”œβ”€ Security headers (HSTS, CSP, X-Frame-Options)
β”œβ”€ CORS (workspace-domain aware)
β”œβ”€ GZip compression
└─ Trusted proxy (RFC-1918 forwarded headers)
β”‚
β–Ό
Router (api/v1/*.py)
β”œβ”€ JWT decode β†’ resolve workspace + role (core/deps.py)
β”œβ”€ RBAC gate (core/permissions.py)
β”‚
β”œβ”€ [cache hit] β†’ return L1/L2 cached response
β”‚
β”œβ”€ Service / direct DB query (AsyncSession)
β”‚
β”œβ”€ [side effects] β†’ enqueue ARQ job (core/tasks.py)
β”‚
└─ Return Pydantic schema response
```
---
## Caching strategy
Three layers operate in order:
1. **L1 β€” in-process LRU** (`core/cache.py`): LRU dict with 2 048 slots. Zero-latency for hot read paths (workspace metadata, KB article headers). Invalidated on write within the same process; other Gunicorn workers invalidate on next L2 miss.
2. **L2 β€” Redis** (Upstash): Serialized JSON with configurable TTLs. Used for search results, dashboard telemetry, and KB chunk metadata.
3. **Semantic cache** (`core/cache.py`): Stores LLM response + embedding for recent queries. Incoming query is embedded and compared against cached embeddings via cosine similarity threshold (β‰₯ 0.92). A cache hit bypasses the LLM entirely.
Cache invalidation is write-through: mutations call `cache.invalidate(key)` which deletes from both L1 and L2.
---
## Real-time events (WebSocket pub/sub)
```
API write (e.g. new message)
β”‚
β–Ό
core/websockets.py ──publish──▢ Local Redis channel
β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Subscriber loop β”‚ (one per uvicorn worker)
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β–Ό β–Ό β–Ό
WS client 1 WS client 2 WS client N
```
Two channel namespaces:
- `workspace:{workspace_id}` β€” workspace-wide events (ticket status, SLA alerts, insight ready)
- `ticket:{ticket_id}` β€” thread-level events (new message, assignment change)
Local Redis (not Upstash) is used for pub/sub because it requires a persistent TCP connection. Upstash's HTTP-based Redis does not support `SUBSCRIBE`.
---
## Background workers (ARQ)
Two independent worker processes read from separate ARQ queues:
**Regular worker** β€” high concurrency, sub-second jobs:
- `monitor_sla_thresholds` (cron, every 5 min)
- `notify_mentions` (on-demand)
- `record_system_heartbeat` (cron, every 30 s)
- `send_triple_notification` (on-demand, batch)
**Heavy worker** β€” concurrency 1–2, 120 s timeout:
- `auto_summarize_ticket` β€” dual LLM summaries (customer-facing + internal)
- `index_kb_article` β€” chunk, embed, and HNSW-index a KB article
- `crystallize_memory` β€” LLM summarization of long agent conversation histories
- `generate_workspace_insights` β€” aggregate analytics β†’ LLM narrative
- `harvest_expertise_task` β€” extract structured knowledge from resolved tickets
Job deduplication: a Redis-backed latch in `tasks/system.py` prevents the same job type from queuing twice for the same entity.
---
## Security model
- **Transport**: TLS terminated at the reverse proxy (HF Spaces / Railway ingress).
- **Auth**: JWT HS256 with access (60 min) + refresh (7 day) token pair. Logout stores the JTI in Redis with matching TTL (token blocklist).
- **RBAC**: Roles resolved per-workspace from `UserWorkspace.role`. Six roles in hierarchy: `SUPERADMIN > SC_ADMIN > SC_LEAD > SC_AGENT > CUSTOMER_ADMIN > CUSTOMER_USER`.
- **Workspace isolation**: All DB queries are scoped by `workspace_id` extracted from the JWT. Customers cannot read staff-internal fields (sanitized in `TicketService`).
- **Agent output masking**: `agents/security.py` strips sensitive fields from LLM responses based on the requesting user's role before the response is returned.
- **Input validation**: Pydantic schemas at every boundary; SQLAlchemy parameterized queries prevent SQL injection.
- **Audit log**: `core/audit.py` appends an immutable record for sensitive operations.
---
## Further reading
- [Hybrid search design](backend_insights/02_hybrid_search.md)
- [Semantic caching](backend_insights/04_semantic_caching.md)
- [Multi-tenant governance](backend_insights/05_multi_tenant_governance.md)
- [Real-time sync](backend_insights/13_realtime_sync.md)
- [DB schema design](backend_insights/11_db_schema_design.md)
- [ARQ worker scaling](backend_insights/12_scaling_arq_workers.md)
- [SLA enforcement](backend_insights/09_sla_enforcement.md)