LightRAG/starter/QUICK_START_MULTITENANT.md
Raphael MANSUY fe9b8ec02a
tests: stabilize integration tests + skip external services; fix multi-tenant API behavior and idempotency (#4)
* feat: Implement multi-tenant architecture with tenant and knowledge base models

- Added data models for tenants, knowledge bases, and related configurations.
- Introduced role and permission management for users in the multi-tenant system.
- Created a service layer for managing tenants and knowledge bases, including CRUD operations.
- Developed a tenant-aware instance manager for LightRAG with caching and isolation features.
- Added a migration script to transition existing workspace-based deployments to the new multi-tenant architecture.

* chore: ignore lightrag/api/webui/assets/ directory

* chore: stop tracking lightrag/api/webui/assets (ignore in .gitignore)

* feat: Initialize LightRAG Multi-Tenant Stack with PostgreSQL

- Added README.md for project overview, setup instructions, and architecture details.
- Created docker-compose.yml to define services: PostgreSQL, Redis, LightRAG API, and Web UI.
- Introduced env.example for environment variable configuration.
- Implemented init-postgres.sql for PostgreSQL schema initialization with multi-tenant support.
- Added reproduce_issue.py for testing default tenant access via API.

* feat: Enhance TenantSelector and update related components for improved multi-tenant support

* feat: Enhance testing capabilities and update documentation

- Updated Makefile to include new test commands for various modes (compatibility, isolation, multi-tenant, security, coverage, and dry-run).
- Modified API health check endpoint in Makefile to reflect new port configuration.
- Updated QUICK_START.md and README.md to reflect changes in service URLs and ports.
- Added environment variables for testing modes in env.example.
- Introduced run_all_tests.sh script to automate testing across different modes.
- Created conftest.py for pytest configuration, including database fixtures and mock services.
- Implemented database helper functions for streamlined database operations in tests.
- Added test collection hooks to skip tests based on the current MULTITENANT_MODE.

* feat: Implement multi-tenant support with demo mode enabled by default

- Added multi-tenant configuration to the environment and Docker setup.
- Created pre-configured demo tenants (acme-corp and techstart) for testing.
- Updated API endpoints to support tenant-specific data access.
- Enhanced Makefile commands for better service management and database operations.
- Introduced user-tenant membership system with role-based access control.
- Added comprehensive documentation for multi-tenant setup and usage.
- Fixed issues with document visibility in multi-tenant environments.
- Implemented necessary database migrations for user memberships and legacy support.

* feat(audit): Add final audit report for multi-tenant implementation

- Documented overall assessment, architecture overview, test results, security findings, and recommendations.
- Included detailed findings on critical security issues and architectural concerns.

fix(security): Implement security fixes based on audit findings

- Removed global RAG fallback and enforced strict tenant context.
- Configured super-admin access and required user authentication for tenant access.
- Cleared localStorage on logout and improved error handling in WebUI.

chore(logs): Create task logs for audit and security fixes implementation

- Documented actions, decisions, and next steps for both audit and security fixes.
- Summarized test results and remaining recommendations.

chore(scripts): Enhance development stack management scripts

- Added scripts for cleaning, starting, and stopping the development stack.
- Improved output messages and ensured graceful shutdown of services.

feat(starter): Initialize PostgreSQL with AGE extension support

- Created initialization scripts for PostgreSQL extensions including uuid-ossp, vector, and AGE.
- Ensured successful installation and verification of extensions.

* feat: Implement auto-select for first tenant and KB on initial load in WebUI

- Removed WEBUI_INITIAL_STATE_FIX.md as the issue is resolved.
- Added useTenantInitialization hook to automatically select the first available tenant and KB on app load.
- Integrated the new hook into the Root component of the WebUI.
- Updated RetrievalTesting component to ensure a KB is selected before allowing user interaction.
- Created end-to-end tests for multi-tenant isolation and real service interactions.
- Added scripts for starting, stopping, and cleaning the development stack.
- Enhanced API and tenant routes to support tenant-specific pipeline status initialization.
- Updated constants for backend URL to reflect the correct port.
- Improved error handling and logging in various components.

* feat: Add multi-tenant support with enhanced E2E testing scripts and client functionality

* update client

* Add integration and unit tests for multi-tenant API, models, security, and storage

- Implement integration tests for tenant and knowledge base management endpoints in `test_tenant_api_routes.py`.
- Create unit tests for tenant isolation, model validation, and role permissions in `test_tenant_models.py`.
- Add security tests to enforce role-based permissions and context validation in `test_tenant_security.py`.
- Develop tests for tenant-aware storage operations and context isolation in `test_tenant_storage_phase3.py`.

* feat(e2e): Implement OpenAI model support and database reset functionality

* Add comprehensive test suite for gpt-5-nano compatibility

- Introduced tests for parameter normalization, embeddings, and entity extraction.
- Implemented direct API testing for gpt-5-nano.
- Validated .env configuration loading and OpenAI API connectivity.
- Analyzed reasoning token overhead with various token limits.
- Documented test procedures and expected outcomes in README files.
- Ensured all tests pass for production readiness.

* kg(postgres_impl): ensure AGE extension is loaded in session and configure graph initialization

* dev: add hybrid dev helper scripts, Makefile, docker-compose.dev-db and local development docs

* feat(dev): add dev helper scripts and local development documentation for hybrid setup

* feat(multi-tenant): add detailed specifications and logs for multi-tenant improvements, including UX, backend handling, and ingestion pipeline

* feat(migration): add generated tenant/kb columns, indexes, triggers; drop unused tables; update schema and docs

* test(backward-compat): adapt tests to new StorageNameSpace/TenantService APIs (use concrete dummy storages)

* chore: multi-tenant and UX updates — docs, webui, storage, tenant service adjustments

* tests: stabilize integration tests + skip external services; fix multi-tenant API behavior and idempotency

- gpt5_nano_compatibility: add pytest-asyncio markers, skip when OPENAI key missing, prevent module-level asyncio.run collection, add conftest
- Ollama tests: add server availability check and skip markers; avoid pytest collection warnings by renaming helper classes
- Graph storage tests: rename interactive test functions to avoid pytest collection
- Document & Tenant routes: support external_ids for idempotency; ensure HTTPExceptions are re-raised
- LightRAG core: support external_ids in apipeline_enqueue_documents and idempotent logic
- Tests updated to match API changes (tenant routes & document routes)
- Add logs and scripts for inspection and audit
2025-12-04 16:04:21 +08:00

7.9 KiB

LightRAG Multi-Tenant Docker - Quick Start Guide

🚀 Get Started in 3 Steps

Step 1: Setup Environment

cd starter
make setup           # Initialize .env from template

Step 2: Start Services with Multi-Tenant Demo Mode

make up             # Starts all services (PostgreSQL, Redis, API, WebUI)
make init-db        # Initialize database with 2 demo tenants

Step 3: Access the Services

Web UI:     http://localhost:3001
API Docs:   http://localhost:8000/docs
API Base:   http://localhost:8000

📊 Default Multi-Tenant Configuration

By default, the system starts with MULTITENANT_MODE=demo which provides:

Pre-configured Demo Tenants

Tenant Knowledge Bases Purpose
acme-corp kb-prod, kb-dev Enterprise tenant with production and dev KBs
techstart kb-main, kb-backup Startup tenant with main and backup KBs

Using the Multi-Tenant API

All API requests should include tenant headers:

# Example: Query as acme-corp
curl -X POST http://localhost:8000/api/v1/query \
  -H "X-Tenant-ID: acme-corp" \
  -H "X-KB-ID: kb-prod" \
  -H "Content-Type: application/json" \
  -d '{"query": "your query here"}'

# Example: Query as techstart
curl -X POST http://localhost:8000/api/v1/query \
  -H "X-Tenant-ID: techstart" \
  -H "X-KB-ID: kb-main" \
  -H "Content-Type: application/json" \
  -d '{"query": "your query here"}'

📋 Service Endpoints

Service URL Purpose
Web UI http://localhost:3001 User interface
API Docs http://localhost:8000/docs Interactive API documentation
API Redoc http://localhost:8000/redoc Alternative API docs
API Health http://localhost:8000/health API health check
PostgreSQL internal-only (container network) Database (not exposed to host by default)
Redis localhost:6379 Cache (internal use)

🎯 Useful Make Commands

# Service Management
make up              # Start all services
make down            # Stop all services
make restart         # Restart all services
make status          # Show service status
make logs            # Stream logs from all services
make logs-api        # Stream logs from API only

# Database Operations
make init-db         # Initialize database with multi-tenant schema
make db-shell        # Connect to PostgreSQL shell
make db-backup       # Create database backup
make db-restore      # Restore from backup
make db-reset        # Reset database (WARNING: deletes all data)

# Testing & Health
make api-health      # Check API health
make test            # Run tests for current mode
make test-all-scenarios  # Run all 3 testing scenarios

# Cleanup
make clean           # Remove stopped containers
make reset           # Full system reset (WARNING: deletes volumes)

🔐 Demo Database Credentials (local/dev only)

PostgreSQL User:     lightrag
PostgreSQL Password: lightrag_secure_password
PostgreSQL Database: lightrag_multitenant
PostgreSQL Host:     postgres (inside Docker container)
PostgreSQL Port:     5432 (internal-only; not forwarded to host)

Demo Login:
Username: admin
Password: password

🛠️ Testing Different Modes

Multi-Tenant Demo Mode (DEFAULT)

# Already set in .env as MULTITENANT_MODE=demo
make up
make init-db

# Test with both tenants
curl -H "X-Tenant-ID: acme-corp" -H "X-KB-ID: kb-prod" \
  http://localhost:8000/health

Single-Tenant Isolation Mode

# Switch to single tenant with multiple KBs
echo "MULTITENANT_MODE=on" >> .env
make restart
make init-db

Backward Compatibility Mode

# Switch to single-tenant compatibility (like main branch)
echo "MULTITENANT_MODE=off" >> .env
make restart
make init-db

# No tenant headers required
curl http://localhost:8000/health

📊 Database Tables Created

The initialization script (init-postgres.sql) creates:

Multi-Tenant Metadata:

  • tenants - Tenant information
  • knowledge_bases - KB metadata per tenant

Document Storage (tenant-isolated):

  • documents - Document metadata
  • document_chunks - Document segments
  • document_status - Processing status
  • embeddings_document - Document embeddings

Knowledge Graph (tenant-isolated):

  • entities - Entity records
  • relations - Relationship records
  • embeddings_entity - Entity embeddings
  • embeddings_relation - Relation embeddings

Caching & Storage (tenant-isolated):

  • kv_storage - Key-value cache
  • llm_cache - LLM response cache

All tables use composite keys: (tenant_id, kb_id, id)

🔍 Verify Multi-Tenant Isolation

From the Database

# Connect to database
make db-shell

# Check tenants
SELECT tenant_id, name FROM tenants;

# Check KBs
SELECT tenant_id, kb_id, name FROM knowledge_bases;

# Verify data isolation
SELECT COUNT(*) FROM documents WHERE tenant_id='acme-corp';
SELECT COUNT(*) FROM documents WHERE tenant_id='techstart';

# Exit
\q

From the API

# Health check
curl http://localhost:8000/health

# API docs (shows available endpoints)
curl http://localhost:8000/docs

🆘 Troubleshooting

Services Won't Start

# Check if ports are in use
lsof -i :3001  # WebUI
lsof -i :8000  # API
lsof -i :5432  # PostgreSQL (if published)

# View logs for errors
make logs

# Kill conflicting process and restart
kill -9 <PID>
make restart

Database Connection Issues

# Check PostgreSQL is healthy
make status

# View database logs
make logs-db

# Verify database exists
make db-shell
\l  # List databases
\q  # Exit

API Not Responding

# Check API health
make api-health

# Check API logs
make logs-api

# If needed, restart API
docker compose -p lightrag-multitenant restart lightrag-api

Reset Everything

# WARNING: This deletes all data!
make reset           # Full system reset (stops, removes containers and volumes)
make setup           # Re-initialize
make up              # Start fresh
make init-db         # Initialize with clean database

📚 Configuration Options

Edit .env to customize:

# Testing Mode (MUST be demo, on, or off)
MULTITENANT_MODE=demo    # demo ← DEFAULT for testing with 2 tenants

# Default Tenant/KB (when not provided in headers)
DEFAULT_TENANT=default
DEFAULT_KB=default

# LLM Configuration
LLM_BINDING=openai
LLM_MODEL=gpt-4o-mini
LLM_BINDING_API_KEY=your_key_here

# Embedding Model
EMBEDDING_BINDING=ollama
EMBEDDING_MODEL=bge-m3:latest
EMBEDDING_BINDING_HOST=http://host.docker.internal:11434

# Database
POSTGRES_USER=lightrag
POSTGRES_PASSWORD=lightrag_secure_password
POSTGRES_DATABASE=lightrag_multitenant

# Server Ports
API_PORT=8000
WEBUI_PORT=3001

🎯 Key Features

Multi-Tenant Isolation: Complete data separation between tenants
Multiple KBs per Tenant: Each tenant can have multiple knowledge bases
Composite Keys: Database-level isolation with (tenant_id, kb_id, id)
Vector Search: pgvector with HNSW indexing
Graph Database: Apache AGE for entity relationships
Caching: Redis for LLM response caching
Health Checks: Automatic service health monitoring

📖 More Information

For detailed testing strategies and advanced configuration, see:

  • docs/adr/008-multi-tenant-testing-strategy.md - Complete testing guide
  • QUICK_REFERENCE.md - Command reference guide
  • README.md - Project overview

Performance Tips

  • Use appropriate tenant and KB headers
  • Database indexes are automatically created
  • Vector search uses HNSW for fast similarity search

For Better Caching

  • LLM responses are cached in Redis by default
  • Set ENABLE_LLM_CACHE=true (default)

For Multi-Tenant Workloads

  • Data is automatically isolated by tenant_id and kb_id
  • No risk of cross-tenant data leakage

Last Updated: November 22, 2025
Status: Ready to Use - Multi-Tenant Demo Mode Enabled by Default
Platform: macOS/Linux/Windows (with Docker)