""" Vector Query End-to-End Test - Run with: python test_vector_query.py This test: 1. Creates a project with users, tasks, and log entries 2. Generates embeddings and stores them in the vector store 3. Tests various smart queries against the populated data Requires GEMINI_API_KEY environment variable. """ import asyncio import sys from datetime import datetime, timedelta, timezone sys.path.insert(0, '.') from sqlalchemy import text from app.database import init_db, SessionLocal from app.models import User, Task, LogEntry, TaskStatus, ActorType, ActionType, ProjectMembership from app.vectorstore import init_vectorstore, add_embedding, delete_by_project, count_embeddings from app.llm import get_embedding # Test project ID (fixed for easy cleanup) TEST_PROJECT_ID = "vector-test-project-001" async def setup_test_environment(): """Create test users, project, tasks, and log entries with embeddings.""" print("\n" + "=" * 60) print(" SETTING UP TEST ENVIRONMENT") print("=" * 60) init_db() init_vectorstore() # Clean up any previous test data print("\n[1] Cleaning up previous test data...") delete_by_project(TEST_PROJECT_ID) db = SessionLocal() try: # Delete existing test project and related data db.execute(text(f"DELETE FROM log_entries WHERE project_id = '{TEST_PROJECT_ID}'")) db.execute(text(f"DELETE FROM tasks WHERE project_id = '{TEST_PROJECT_ID}'")) db.execute(text(f"DELETE FROM project_memberships WHERE project_id = '{TEST_PROJECT_ID}'")) db.execute(text(f"DELETE FROM projects WHERE id = '{TEST_PROJECT_ID}'")) db.commit() except: db.rollback() finally: db.close() db = SessionLocal() try: # Create users print("\n[2] Creating test users...") user_alice = User( id="user-alice-001", first_name="Alice", last_name="Developer" ) user_bob = User( id="user-bob-001", first_name="Bob", last_name="Engineer" ) db.add(user_alice) db.add(user_bob) db.commit() print(f" Created: {user_alice.name} ({user_alice.id})") print(f" Created: {user_bob.name} ({user_bob.id})") # Create project print("\n[3] Creating test project...") from app.models import Project project = Project( id=TEST_PROJECT_ID, name="E-Commerce Platform", description="Building an online shopping platform", created_by=user_alice.id ) db.add(project) db.commit() print(f" Created: {project.name} ({project.id})") # Add memberships print("\n[4] Adding project memberships...") membership1 = ProjectMembership(project_id=TEST_PROJECT_ID, user_id=user_alice.id, role="owner") membership2 = ProjectMembership(project_id=TEST_PROJECT_ID, user_id=user_bob.id, role="member") db.add(membership1) db.add(membership2) db.commit() print(f" Added Alice as owner") print(f" Added Bob as member") # Create tasks print("\n[5] Creating tasks...") tasks_data = [ { "id": "task-auth-001", "title": "Implement User Authentication", "description": "Build JWT-based login and registration system", "assigned_to": user_alice.id, "status": TaskStatus.done, "completed_at": datetime.now(timezone.utc) - timedelta(days=2) }, { "id": "task-cart-001", "title": "Build Shopping Cart", "description": "Create cart functionality with add/remove items", "assigned_to": user_bob.id, "status": TaskStatus.done, "completed_at": datetime.now(timezone.utc) - timedelta(days=1) }, { "id": "task-checkout-001", "title": "Implement Checkout Flow", "description": "Payment integration and order processing", "assigned_to": user_alice.id, "status": TaskStatus.in_progress }, { "id": "task-tests-001", "title": "Write Unit Tests", "description": "Create test coverage for auth and cart modules", "assigned_to": user_bob.id, "status": TaskStatus.done, "completed_at": datetime.now(timezone.utc) - timedelta(hours=5) } ] for t in tasks_data: task = Task( id=t["id"], project_id=TEST_PROJECT_ID, title=t["title"], description=t["description"], assigned_to=t["assigned_to"], status=t["status"], completed_at=t.get("completed_at") ) db.add(task) print(f" Created: {task.title} ({task.status.value})") db.commit() # Create log entries with embeddings print("\n[6] Creating log entries and embeddings...") log_entries_data = [ { "id": "log-auth-001", "task_id": "task-auth-001", "user_id": user_alice.id, "raw_input": "Implemented JWT authentication with access and refresh tokens. Added password hashing using bcrypt.", "generated_doc": "Authentication system implemented using JWT tokens. The system generates short-lived access tokens (15 min) and long-lived refresh tokens (7 days). Passwords are securely hashed using bcrypt with salt rounds of 12. Login endpoint validates credentials and returns both tokens. Refresh endpoint allows obtaining new access tokens.", "tags": ["auth", "jwt", "security", "bcrypt"], "hours_ago": 48 }, { "id": "log-cart-001", "task_id": "task-cart-001", "user_id": user_bob.id, "raw_input": "Built shopping cart with Redux state management. Added add/remove/update quantity functions.", "generated_doc": "Shopping cart functionality using Redux for state management. Cart persists to localStorage. Features include: adding products with quantities, removing items, updating quantities, calculating totals with tax, and applying discount codes. Cart state syncs across browser tabs.", "tags": ["cart", "redux", "frontend", "state"], "hours_ago": 24 }, { "id": "log-api-001", "task_id": "task-auth-001", "user_id": user_alice.id, "raw_input": "Created REST API endpoints for user profile management.", "generated_doc": "REST API endpoints for user profiles. GET /api/users/me returns current user. PUT /api/users/me updates profile fields (name, avatar, preferences). Password change requires current password verification. All endpoints require valid JWT in Authorization header.", "tags": ["api", "rest", "profile", "user"], "hours_ago": 36 }, { "id": "log-tests-001", "task_id": "task-tests-001", "user_id": user_bob.id, "raw_input": "Wrote unit tests for authentication and cart modules. Achieved 85% coverage.", "generated_doc": "Unit test suite for authentication and cart modules. Auth tests cover: login success/failure, token refresh, password validation, protected routes. Cart tests cover: add/remove items, quantity updates, price calculations, discount application. Using Jest with React Testing Library. Coverage at 85%.", "tags": ["tests", "jest", "coverage", "unit-tests"], "hours_ago": 5 }, { "id": "log-today-001", "task_id": "task-checkout-001", "user_id": user_alice.id, "raw_input": "Started working on Stripe payment integration for checkout.", "generated_doc": "Began Stripe payment integration. Set up Stripe SDK and test account. Created payment intent endpoint. Working on client-side card element component. Next: handle payment confirmation and webhooks for order updates.", "tags": ["checkout", "stripe", "payments", "integration"], "hours_ago": 2 } ] for entry_data in log_entries_data: # Create log entry entry = LogEntry( id=entry_data["id"], project_id=TEST_PROJECT_ID, task_id=entry_data["task_id"], user_id=entry_data["user_id"], actor_type=ActorType.human, action_type=ActionType.task_completed, raw_input=entry_data["raw_input"], generated_doc=entry_data["generated_doc"], tags=entry_data["tags"], created_at=datetime.now(timezone.utc) - timedelta(hours=entry_data["hours_ago"]) ) db.add(entry) db.commit() # Create embedding text_to_embed = f""" Task: {entry_data['raw_input']} Documentation: {entry_data['generated_doc']} Tags: {', '.join(entry_data['tags'])} """ embedding = await get_embedding(text_to_embed) add_embedding( log_entry_id=entry_data["id"], text=text_to_embed, embedding=embedding, metadata={ "project_id": TEST_PROJECT_ID, "user_id": entry_data["user_id"], "task_id": entry_data["task_id"], "created_at": entry.created_at.isoformat() } ) print(f" Created: {entry_data['id']} + embedding") db.commit() # Verify embeddings embed_count = count_embeddings(TEST_PROJECT_ID) print(f"\n Total embeddings stored: {embed_count}") return { "project_id": TEST_PROJECT_ID, "user_alice_id": user_alice.id, "user_bob_id": user_bob.id } finally: db.close() async def run_test_queries(test_data): """Run various queries against the test data.""" print("\n" + "=" * 60) print(" RUNNING TEST QUERIES") print("=" * 60) from app.smart_query import smart_query queries = [ { "query": "What did I do yesterday?", "user_id": test_data["user_alice_id"], "description": "User activity query (yesterday)" }, { "query": "What did Bob work on?", "user_id": test_data["user_alice_id"], "description": "Other user's activity" }, { "query": "How does authentication work?", "user_id": test_data["user_alice_id"], "description": "Semantic search for auth" }, { "query": "Status of the checkout task?", "user_id": test_data["user_alice_id"], "description": "Task status query" }, { "query": "Did Bob complete the shopping cart?", "user_id": test_data["user_alice_id"], "description": "Task completion check" }, { "query": "What tests were written?", "user_id": test_data["user_bob_id"], "description": "Semantic search for tests" }, { "query": "What payment system is being used?", "user_id": test_data["user_alice_id"], "description": "Semantic search for payments" }, { "query": "Who are the team members?", "user_id": test_data["user_alice_id"], "description": "List users query" } ] results = [] for i, q in enumerate(queries, 1): print(f"\n[Query {i}] {q['description']}") print(f" Question: \"{q['query']}\"") print(f" User: {q['user_id']}") try: result = await smart_query( project_id=test_data["project_id"], query=q["query"], current_user_id=q["user_id"], current_datetime=datetime.now(timezone.utc).isoformat() ) print(f"\n Tools Used: {result.get('tools_used', [])}") print(f"\n Answer:") answer = result.get("answer", "No answer") # Print answer with word wrap for line in answer.split('\n'): print(f" {line}") if result.get("sources"): print(f"\n Sources ({len(result['sources'])}):") for src in result["sources"][:3]: print(f" - [{src.get('type', 'unknown')}] {src.get('summary', 'No summary')[:60]}...") results.append({"query": q, "result": result, "success": True}) except Exception as e: print(f"\n ERROR: {str(e)}") results.append({"query": q, "error": str(e), "success": False}) print("\n" + "-" * 60) return results def print_summary(results): """Print test summary.""" print("\n" + "=" * 60) print(" TEST SUMMARY") print("=" * 60) successful = sum(1 for r in results if r["success"]) failed = len(results) - successful print(f"\n Total queries: {len(results)}") print(f" Successful: {successful}") print(f" Failed: {failed}") if failed > 0: print("\n Failed queries:") for r in results: if not r["success"]: print(f" - {r['query']['description']}: {r.get('error', 'Unknown error')}") def cleanup(): """Clean up test data.""" print("\n[CLEANUP] Removing test data...") try: delete_by_project(TEST_PROJECT_ID) db = SessionLocal() try: db.execute(text(f"DELETE FROM log_entries WHERE project_id = '{TEST_PROJECT_ID}'")) db.execute(text(f"DELETE FROM tasks WHERE project_id = '{TEST_PROJECT_ID}'")) db.execute(text(f"DELETE FROM project_memberships WHERE project_id = '{TEST_PROJECT_ID}'")) db.execute(text(f"DELETE FROM projects WHERE id = '{TEST_PROJECT_ID}'")) db.commit() print(" Cleanup complete.") finally: db.close() except Exception as e: print(f" Cleanup error: {e}") async def main(): print("=" * 60) print(" VECTOR QUERY END-TO-END TEST") print(" Tests smart_query against populated vector store") print("=" * 60) try: # Setup test_data = await setup_test_environment() # Run queries results = await run_test_queries(test_data) # Summary print_summary(results) except Exception as e: print(f"\nFATAL ERROR: {e}") import traceback traceback.print_exc() finally: # Ask about cleanup print("\n" + "=" * 60) response = input("Clean up test data? (y/n): ").strip().lower() if response == 'y': cleanup() else: print(f"Test data retained. Project ID: {TEST_PROJECT_ID}") print("Run cleanup manually or delete project from database.") if __name__ == "__main__": asyncio.run(main())