LightRAG/write_script.py
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

211 lines
6.2 KiB
Python

content = r"""#!/bin/bash
# ==============================================================================
# LightRAG E2E Test Runner
# ==============================================================================
# This script runs the End-to-End test suite for LightRAG.
# It supports multiple storage backends and configurable LLM models.
#
# Usage: ./e2e/run_isolation_test.sh [options]
#
# Options:
# -b, --backend <type> Storage backend to test (file, postgres, all). Default: file
# -m, --model <name> Ollama model to use. Default: gpt-oss:20b
# -d, --dim <number> Embedding dimension. Default: 1024
# -h, --help Show this help message
# ==============================================================================
# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
BLUE='\033[0;34m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color
# Defaults
BACKEND="file"
LLM_MODEL="gpt-oss:20b"
EMBEDDING_MODEL="bge-m3:latest"
EMBEDDING_DIM="1024"
SERVER_PORT=9621
# Parse Arguments
while [[ "$#" -gt 0 ]]; do
case $1 in
-b|--backend) BACKEND="$2"; shift ;;
-m|--model) LLM_MODEL="$2"; shift ;;
-d|--dim) EMBEDDING_DIM="$2"; shift ;;
-h|--help)
grep "^# " "$0" | cut -c 3-
exit 0
;;
*) echo "Unknown parameter passed: $1"; exit 1 ;;
esac
shift
done
echo -e "${GREEN}Starting LightRAG E2E Test Suite...${NC}"
echo "Backend: $BACKEND"
echo "Model: $LLM_MODEL"
# Function to cleanup server
cleanup_server() {
if lsof -i :$SERVER_PORT > /dev/null; then
echo "Stopping existing server on port $SERVER_PORT..."
lsof -i :$SERVER_PORT | grep Python | awk '{print $2}' | xargs kill -9
sleep 2
echo "Server stopped."
fi
}
# Function to configure environment
configure_env() {
local backend_type=$1
# Common Env Vars
export LLM_BINDING="ollama"
export LLM_MODEL="$LLM_MODEL"
export EMBEDDING_BINDING="ollama"
export EMBEDDING_MODEL="$EMBEDDING_MODEL"
export EMBEDDING_DIM="$EMBEDDING_DIM"
export LIGHTRAG_API_KEY="admin123"
export AUTH_ACCOUNTS="admin:admin123"
echo -e "\n${BLUE}Configuring for Backend: $backend_type${NC}"
if [ "$backend_type" == "file" ]; then
export LIGHTRAG_KV_STORAGE="JsonKVStorage"
export LIGHTRAG_DOC_STATUS_STORAGE="JsonDocStatusStorage"
export LIGHTRAG_GRAPH_STORAGE="NetworkXStorage"
export LIGHTRAG_VECTOR_STORAGE="NanoVectorDBStorage"
# Clean up file storage
echo "Cleaning up local storage (rag_storage)..."
rm -rf rag_storage
elif [ "$backend_type" == "postgres" ]; then
export LIGHTRAG_KV_STORAGE="PGKVStorage"
export LIGHTRAG_DOC_STATUS_STORAGE="PGDocStatusStorage"
export LIGHTRAG_GRAPH_STORAGE="PGGraphStorage"
export LIGHTRAG_VECTOR_STORAGE="PGVectorStorage"
# Ensure Postgres vars are set (defaults if not in env)
export POSTGRES_HOST="${POSTGRES_HOST:-localhost}"
export POSTGRES_PORT="${POSTGRES_PORT:-5432}"
export POSTGRES_USER="${POSTGRES_USER:-lightrag}"
export POSTGRES_PASSWORD="${POSTGRES_PASSWORD:-lightrag_secure_password}"
export POSTGRES_DATABASE="${POSTGRES_DATABASE:-lightrag_multitenant}"
echo "⚠️ Ensure Postgres is running at $POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_DATABASE"
else
echo -e "${RED}Unknown backend: $backend_type${NC}"
exit 1
fi
echo "Environment Configured:"
echo " STORAGE: $backend_type"
echo " LLM: $LLM_MODEL"
}
# Function to wait for server health
wait_for_server() {
echo "Waiting for server to be ready..."
for i in {1..30}; do
if curl -s http://localhost:$SERVER_PORT/health > /dev/null; then
echo -e "${GREEN}Server is up!${NC}"
return 0
fi
# Fallback check if /health doesn't exist yet, check root or docs
if curl -s http://localhost:$SERVER_PORT/docs > /dev/null; then
echo -e "${GREEN}Server is up!${NC}"
return 0
fi
sleep 1
done
echo -e "${RED}Server failed to start within 30 seconds.${NC}"
cat server.log
return 1
}
# Function to run tests
run_test_suite() {
local backend_name=$1
cleanup_server
configure_env "$backend_name"
echo "Starting server..."
nohup python -m lightrag.api.lightrag_server --port $SERVER_PORT > server.log 2>&1 &
SERVER_PID=$!
echo "Server PID: $SERVER_PID"
if ! wait_for_server; then
kill $SERVER_PID 2>/dev/null
return 1
fi
FAILURES=0
# List of tests to run
TESTS=(
"e2e/test_multitenant_isolation.py"
"e2e/test_deletion.py"
"e2e/test_mixed_operations.py"
)
for test_script in "${TESTS[@]}"; do
echo -e "\n${BLUE}==================================================${NC}"
echo -e "${BLUE}Running $test_script [$backend_name]...${NC}"
echo -e "${BLUE}==================================================${NC}"
python "$test_script"
if [ $? -eq 0 ]; then
echo -e "${GREEN}✅ $test_script Passed!${NC}"
else
echo -e "${RED}❌ $test_script Failed!${NC}"
((FAILURES++))
fi
done
echo "Cleaning up server..."
kill $SERVER_PID
wait $SERVER_PID 2>/dev/null
if [ $FAILURES -eq 0 ]; then
echo -e "${GREEN}🎉 All tests passed for $backend_name!${NC}"
return 0
else
echo -e "${RED}💀 $FAILURES test(s) failed for $backend_name.${NC}"
return 1
fi
}
# Main Execution Logic
if [ "$BACKEND" == "all" ]; then
echo "Running tests for ALL backends..."
# Run File
run_test_suite "file"
FILE_EXIT=$?
# Run Postgres
run_test_suite "postgres"
PG_EXIT=$?
if [ $FILE_EXIT -eq 0 ] && [ $PG_EXIT -eq 0 ]; then
echo -e "\n${GREEN}🏆 ALL BACKENDS PASSED!${NC}"
exit 0
else
echo -e "\n${RED}💥 SOME BACKENDS FAILED${NC}"
exit 1
fi
else
run_test_suite "$BACKEND"
exit $?
fi
"""
with open("e2e/run_isolation_test.sh", "w") as f:
f.write(content)