File size: 15,622 Bytes
35765b5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 |
"""
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())
|