LightRAG/docs/LOCAL_DEVELOPMENT.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

312 lines
9.8 KiB
Markdown

# LightRAG Local Development Guide
This guide explains how to run LightRAG in **hybrid development mode**:
- **PostgreSQL + Redis** run in Docker containers
- **API Server + WebUI** run natively on your machine
This setup provides the best development experience with hot-reloading for the WebUI and easy debugging of the Python API.
## 🚀 Quick Start
```bash
# Start everything with one command
make dev
# Or use the script directly
./dev-start.sh
```
## 📋 Prerequisites
- **Docker** - For PostgreSQL and Redis
- **Python 3.10+** - For the API server
- **Bun or npm** - For the WebUI (Bun preferred for speed)
- **curl** - For health checks
## ⚙️ Configuration
All configuration is read from the `.env` file at the project root.
### Key Settings
```bash
# Database (Docker containers will use these)
POSTGRES_HOST=localhost
POSTGRES_PORT=15432
POSTGRES_USER=lightrag
POSTGRES_PASSWORD=lightrag123
POSTGRES_DATABASE=lightrag_multitenant
# Redis
REDIS_URI=redis://localhost:16379
# Authentication
AUTH_USER=admin
AUTH_PASS=admin123
# LLM Configuration (OpenAI example)
LLM_BINDING=openai
LLM_MODEL=gpt-4o-mini
LLM_BINDING_API_KEY=sk-your-key-here
# Embedding Configuration
EMBEDDING_BINDING=openai
EMBEDDING_MODEL=text-embedding-3-small
EMBEDDING_DIM=1536
EMBEDDING_BINDING_API_KEY=sk-your-key-here
```
## 📡 Service URLs
When the stack is running:
| Service | URL |
|---------|-----|
| **WebUI** | http://localhost:5173 |
| **API Server** | http://localhost:9621 |
| **API Documentation** | http://localhost:9621/docs |
| **Health Check** | http://localhost:9621/health |
## 🔐 Login Credentials
Default development credentials (configurable in `.env`):
- **Username:** `admin`
- **Password:** `admin123`
## 🛠️ Available Commands
### Full Stack (Recommended)
```bash
make dev # Start everything
You can also auto-confirm killing any processes/containers occupying dev ports (dangerous in shared environments):
```bash
make dev CONFIRM_KILL=yes # or
./dev-start.sh --yes
```
The script will then stop containers/processes using the dev ports before starting.
make dev-stop # Stop everything
make dev-status # Check what's running
make dev-logs # View all logs
make dev-logs-api # View API logs only
make dev-logs-webui # View WebUI logs only
```
### Database Only
If you want to run only the databases (e.g., for custom API development):
```bash
make db-only # Start PostgreSQL + Redis
make db-stop # Stop databases
make db-shell # Connect to PostgreSQL CLI
make db-logs # View database logs
make clean-db # Delete all data (⚠️ destructive!)
```
### Setup & Utilities
```bash
make install # Install all dependencies
make test # Run tests
make lint # Run linters
```
## 📁 Files Created
| File | Purpose |
|------|---------|
| `dev-start.sh` | Main startup script |
| `dev-stop.sh` | Graceful shutdown script |
| `dev-status.sh` | Status check script |
| `docker-compose.dev-db.yml` | Docker Compose for databases only |
| `Makefile` | Convenient make commands |
## 🔄 How It Works
1. **Docker Compose** starts PostgreSQL (with AGE graph extension) and Redis
2. **Python** runs the LightRAG API server natively
3. **Bun/npm** runs the Vite dev server for the WebUI with hot-reload
This architecture means:
- Database data persists in Docker volumes
- API changes can be tested with a simple restart
- WebUI changes are reflected immediately (hot-reload)
## 🐛 Troubleshooting
### Port Already in Use
```bash
# Check what's using a port
lsof -i :9621
lsof -i :5173
# Kill the process
kill -9 <PID>
# Or let the scripts handle it
make dev-stop
make dev
```
### Database Connection Issues
```bash
# Check if PostgreSQL is running
docker ps | grep postgres
# View PostgreSQL logs
docker logs lightrag-dev-postgres
# Connect directly
docker exec -it lightrag-dev-postgres psql -U lightrag -d lightrag_multitenant
```
### WebUI Not Loading
```bash
# Check WebUI logs
tail -f /tmp/lightrag-dev-webui.log
# Reinstall dependencies
cd lightrag_webui && bun install
```
### API Server Crashes
```bash
# Check API logs
tail -f /tmp/lightrag-dev-api.log
# Common issues:
# - Missing LLM_BINDING_API_KEY in .env
# - Database not ready yet (wait a few seconds)
# - Python dependencies missing (run: pip install -e .)
```
## 🔧 Advanced: Manual Start
If you prefer to run services manually:
```bash
# 1. Start databases
docker compose -f docker-compose.dev-db.yml up -d
# 2. Start API server (in one terminal)
python -m lightrag.api.lightrag_server --host 0.0.0.0 --port 9621
# 3. Start WebUI (in another terminal)
cd lightrag_webui
VITE_API_BASE_URL=http://localhost:9621 bun run dev
```
## 📊 Architecture Diagram
```
┌─────────────────────────────────────────────────────────────────┐
│ Your Machine │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────┐ ┌─────────────────────────────────┐ │
│ │ WebUI (Vite) │◄──────►│ LightRAG API Server │ │
│ │ localhost:5173│ │ localhost:9621 │ │
│ │ (Native) │ │ (Native Python) │ │
│ └─────────────────┘ └──────────────┬──────────────────┘ │
│ │ │
│ ┌─────────────────────────────────────────┴───────────────────┐ │
│ │ Docker │ │
│ │ ┌─────────────────────┐ ┌─────────────────────┐ │ │
│ │ │ PostgreSQL │ │ Redis │ │ │
│ │ │ localhost:15432 │ │ localhost:16379 │ │ │
│ │ │ + AGE Graph Ext │ │ │ │ │
│ │ └─────────────────────┘ └─────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
```
## 🆚 Comparison with Other Setups
| Feature | `make dev` (Hybrid) | `starter/make up` (Full Docker) | `scripts/start-dev-stack.sh` |
|---------|---------------------|----------------------------------|------------------------------|
| Databases | Docker | Docker | Docker |
| API Server | Native | Docker | Native |
| WebUI | Native | Docker | Native |
| Hot Reload | ✅ Yes | ❌ No | ✅ Yes |
| Uses root .env | ✅ Yes | ❌ Uses starter/.env | ❌ Hardcoded |
| Easy debugging | ✅ Yes | ❌ Harder | ✅ Yes |
## 🔀 Multi-Tenant Development & Testing
LightRAG supports multi-tenant operation with workspace isolation. Here's how to test the multi-tenant features:
### Running Multi-Tenant Tests
```bash
# Run the isolation test suite
./e2e/run_isolation_test.sh
# Run specific multi-tenant tests
python -m pytest tests/test_idempotency.py -v
python -m pytest e2e/test_multitenant_isolation.py -v
```
### Testing Tenant State Management
The WebUI includes state management features for multi-tenant UX:
1. **URL State Sync**: Navigate to documents with URL parameters:
```
http://localhost:5173/documents#page=2&filter=processed
```
2. **Session Persistence**: Tenant selection persists in session storage
- Switch between tenants without losing document page state
- "Last selected" hint shows on tenant selection page
3. **Cross-Tab Sync**: Changes propagate across browser tabs via storage events
### Testing Idempotent Document Ingestion
```bash
# Test with curl - first insertion
curl -X POST "http://localhost:9621/documents/text" \
-H "Content-Type: application/json" \
-H "X-Tenant-ID: test-tenant" \
-H "X-KB-ID: kb-1" \
-H "Authorization: Bearer your-token" \
-d '{
"text": "Document content here",
"external_id": "doc-unique-id-123"
}'
# Second insertion with same external_id returns existing document (no duplicate)
curl -X POST "http://localhost:9621/documents/text" \
-H "Content-Type: application/json" \
-H "X-Tenant-ID: test-tenant" \
-H "X-KB-ID: kb-1" \
-H "Authorization: Bearer your-token" \
-d '{
"text": "Different content - will be ignored",
"external_id": "doc-unique-id-123"
}'
```
### Multi-Tenant Architecture
See [Multi-Tenant UX Documentation](./0004-multi-tenant-ux-state-management.md) for:
- State management architecture
- URL synchronization patterns
- Idempotency implementation details
- API examples
## 📝 Notes
- Log files are stored in `/tmp/lightrag-dev-*.log`
- PID files are stored in `/tmp/lightrag-dev-*.pid`
- Database data is persisted in Docker volumes (`lightrag_dev_postgres_data`, `lightrag_dev_redis_data`)