Spaces:
Paused
Download docs/architecture.md from 3SCError404/miracle: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/spaces/3SCError404/miracle/resolve/main/docs/architecture.md
- Command line
-
hf download hf://spaces/3SCError404/miracle/docs/architecture.md
-
curl -L -o architecture.md https://huggingface.co/spaces/3SCError404/miracle/resolve/main/docs/architecture.md
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:
TSVECTORcomputed column + GIN index for full-text searchpgvectorcolumn + HNSW index (768-dim) for semantic similaritycontent_hashfor 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:
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.L2 β Redis (Upstash): Serialized JSON with configurable TTLs. Used for search results, dashboard telemetry, and KB chunk metadata.
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 articlecrystallize_memoryβ LLM summarization of long agent conversation historiesgenerate_workspace_insightsβ aggregate analytics β LLM narrativeharvest_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_idextracted from the JWT. Customers cannot read staff-internal fields (sanitized inTicketService). - Agent output masking:
agents/security.pystrips 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.pyappends an immutable record for sensitive operations.