Spaces:
Paused
Paused
Download scripts/validate_integration_new.py from VAH6002/ai_data_scientist: direct link, hf CLI and curl.
- Browser
- Download file 23.7 kB
-
https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/scripts/validate_integration_new.py
- Command line
-
hf download hf://spaces/VAH6002/ai_data_scientist/scripts/validate_integration_new.py
-
curl -L -o validate_integration_new.py https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/scripts/validate_integration_new.py
23.7 kB
| #!/usr/bin/env python3 | |
| """ | |
| Integration validation script for MCP AI Data Scientist. | |
| Validates that all components are properly integrated and working together. | |
| """ | |
| import asyncio | |
| import sys | |
| import os | |
| import json | |
| import time | |
| from pathlib import Path | |
| from datetime import datetime | |
| from typing import Dict, Any, List | |
| # Add project root to path | |
| project_root = Path(__file__).parent.parent | |
| sys.path.insert(0, str(project_root)) | |
| from shared.config import settings | |
| from shared.database import test_database_connection | |
| from shared.integration_coordinator import integration_coordinator | |
| from shared.monitoring import monitoring_system, record_metric | |
| from shared.error_handling import error_handler, ErrorContext | |
| class IntegrationValidator: | |
| """Comprehensive integration validator.""" | |
| def __init__(self): | |
| self.validation_results = {} | |
| self.start_time = datetime.now() | |
| async def run_all_validations(self) -> Dict[str, Any]: | |
| """Run all integration validations.""" | |
| print("🔍 MCP AI Data Scientist Integration Validation") | |
| print("=" * 60) | |
| validations = [ | |
| ("Database Connection", self._validate_database), | |
| ("Configuration", self._validate_configuration), | |
| ("Component Imports", self._validate_imports), | |
| ("Integration Coordinator", self._validate_integration_coordinator), | |
| ("Monitoring System", self._validate_monitoring), | |
| ("Error Handling", self._validate_error_handling), | |
| ("MCP Server Configs", self._validate_mcp_configs), | |
| ("API Endpoints", self._validate_api_endpoints), | |
| ("Streamlit Components", self._validate_streamlit), | |
| ("End-to-End Pipeline", self._validate_pipeline) | |
| ] | |
| for name, validation_func in validations: | |
| print(f"\n🧪 {name}...") | |
| try: | |
| result = await validation_func() | |
| if result["success"]: | |
| print(f" ✅ {result['message']}") | |
| else: | |
| print(f" ❌ {result['message']}") | |
| self.validation_results[name] = result | |
| except Exception as e: | |
| error_result = { | |
| "success": False, | |
| "message": f"Validation error: {str(e)}", | |
| "details": {} | |
| } | |
| print(f" ❌ {error_result['message']}") | |
| self.validation_results[name] = error_result | |
| # Generate summary | |
| return self._generate_summary() | |
| async def _validate_database(self) -> Dict[str, Any]: | |
| """Validate database connectivity and schema.""" | |
| try: | |
| # Test basic connection | |
| db_ok = await test_database_connection() | |
| if not db_ok: | |
| return { | |
| "success": False, | |
| "message": "Database connection failed", | |
| "details": {} | |
| } | |
| # Test schema validation | |
| from shared.database import get_database_connection | |
| async with get_database_connection() as conn: | |
| # Check for key tables | |
| tables_to_check = ['users', 'analysis_sessions', 'user_datasets'] | |
| existing_tables = [] | |
| for table in tables_to_check: | |
| exists = await conn.fetchval( | |
| "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = $1)", | |
| table | |
| ) | |
| if exists: | |
| existing_tables.append(table) | |
| return { | |
| "success": True, | |
| "message": f"Database connection OK, {len(existing_tables)}/{len(tables_to_check)} tables found", | |
| "details": { | |
| "existing_tables": existing_tables, | |
| "missing_tables": list(set(tables_to_check) - set(existing_tables)) | |
| } | |
| } | |
| except Exception as e: | |
| return { | |
| "success": False, | |
| "message": f"Database validation failed: {str(e)}", | |
| "details": {} | |
| } | |
| async def _validate_configuration(self) -> Dict[str, Any]: | |
| """Validate system configuration.""" | |
| try: | |
| required_settings = [ | |
| 'database_url', 'fastapi_host', 'fastapi_port', | |
| 'upload_dir', 'log_level', 'mcp_servers' | |
| ] | |
| missing_settings = [] | |
| for setting in required_settings: | |
| if not hasattr(settings, setting) or getattr(settings, setting) is None: | |
| missing_settings.append(setting) | |
| if missing_settings: | |
| return { | |
| "success": False, | |
| "message": f"Missing required settings: {missing_settings}", | |
| "details": {"missing_settings": missing_settings} | |
| } | |
| # Validate MCP server configurations | |
| mcp_servers = settings.mcp_servers | |
| if not mcp_servers: | |
| return { | |
| "success": False, | |
| "message": "No MCP servers configured", | |
| "details": {} | |
| } | |
| return { | |
| "success": True, | |
| "message": f"Configuration valid, {len(mcp_servers)} MCP servers configured", | |
| "details": { | |
| "mcp_servers": list(mcp_servers.keys()), | |
| "upload_dir": str(settings.upload_dir), | |
| "log_level": settings.log_level | |
| } | |
| } | |
| except Exception as e: | |
| return { | |
| "success": False, | |
| "message": f"Configuration validation failed: {str(e)}", | |
| "details": {} | |
| } | |
| async def _validate_imports(self) -> Dict[str, Any]: | |
| """Validate that all components can be imported.""" | |
| try: | |
| import_tests = [ | |
| ("orchestrator.main", "app"), | |
| ("orchestrator.analysis_orchestrator", "AnalysisOrchestrator"), | |
| ("orchestrator.mcp_client_manager", "MCPClientManager"), | |
| ("orchestrator.sse_manager", "SSEManager"), | |
| ("shared.monitoring", "monitoring_system"), | |
| ("shared.error_handling", "error_handler"), | |
| ("shared.integration_coordinator", "integration_coordinator"), | |
| ("streamlit_app.main", "main"), | |
| ("streamlit_app.utils.api_client", "APIClient") | |
| ] | |
| successful_imports = [] | |
| failed_imports = [] | |
| for module_name, class_name in import_tests: | |
| try: | |
| module = __import__(module_name, fromlist=[class_name]) | |
| getattr(module, class_name) | |
| successful_imports.append(f"{module_name}.{class_name}") | |
| except Exception as e: | |
| failed_imports.append(f"{module_name}.{class_name}: {str(e)}") | |
| if failed_imports: | |
| return { | |
| "success": False, | |
| "message": f"Import failures: {len(failed_imports)}/{len(import_tests)}", | |
| "details": { | |
| "successful": successful_imports, | |
| "failed": failed_imports | |
| } | |
| } | |
| return { | |
| "success": True, | |
| "message": f"All imports successful: {len(successful_imports)}/{len(import_tests)}", | |
| "details": {"successful_imports": successful_imports} | |
| } | |
| except Exception as e: | |
| return { | |
| "success": False, | |
| "message": f"Import validation failed: {str(e)}", | |
| "details": {} | |
| } | |
| async def _validate_integration_coordinator(self) -> Dict[str, Any]: | |
| """Validate integration coordinator functionality.""" | |
| try: | |
| # Test initialization | |
| success = await integration_coordinator.initialize_system() | |
| if not success: | |
| return { | |
| "success": False, | |
| "message": "Integration coordinator initialization failed", | |
| "details": {} | |
| } | |
| # Get system status | |
| status = integration_coordinator.get_system_status() | |
| # Shutdown | |
| await integration_coordinator.shutdown_system() | |
| return { | |
| "success": True, | |
| "message": "Integration coordinator working correctly", | |
| "details": { | |
| "initialization_complete": status.get("initialization_complete", False), | |
| "components_status": status.get("components_status", {}) | |
| } | |
| } | |
| except Exception as e: | |
| return { | |
| "success": False, | |
| "message": f"Integration coordinator validation failed: {str(e)}", | |
| "details": {} | |
| } | |
| async def _validate_monitoring(self) -> Dict[str, Any]: | |
| """Validate monitoring system.""" | |
| try: | |
| # Start monitoring | |
| await monitoring_system.start_monitoring() | |
| # Record test metric | |
| record_metric("validation.test_metric", 42.0, tags={"test": "true"}) | |
| # Check metrics were recorded | |
| latest_values = monitoring_system.metrics_collector.get_latest_values() | |
| # Stop monitoring | |
| await monitoring_system.stop_monitoring() | |
| if "validation.test_metric" not in latest_values: | |
| return { | |
| "success": False, | |
| "message": "Monitoring system not recording metrics", | |
| "details": {} | |
| } | |
| return { | |
| "success": True, | |
| "message": "Monitoring system working correctly", | |
| "details": { | |
| "metrics_recorded": len(latest_values), | |
| "test_metric_value": latest_values.get("validation.test_metric") | |
| } | |
| } | |
| except Exception as e: | |
| return { | |
| "success": False, | |
| "message": f"Monitoring validation failed: {str(e)}", | |
| "details": {} | |
| } | |
| async def _validate_error_handling(self) -> Dict[str, Any]: | |
| """Validate error handling system.""" | |
| try: | |
| # Generate test error | |
| test_error = ValueError("Validation test error") | |
| # Handle error | |
| error_info = await error_handler.handle_error( | |
| test_error, | |
| ErrorContext( | |
| component="validation", | |
| operation="test_error_handling" | |
| ), | |
| attempt_recovery=False | |
| ) | |
| if not error_info or not error_info.error_id: | |
| return { | |
| "success": False, | |
| "message": "Error handling system not working", | |
| "details": {} | |
| } | |
| return { | |
| "success": True, | |
| "message": "Error handling system working correctly", | |
| "details": { | |
| "error_id": error_info.error_id, | |
| "category": error_info.category.value, | |
| "severity": error_info.severity.value | |
| } | |
| } | |
| except Exception as e: | |
| return { | |
| "success": False, | |
| "message": f"Error handling validation failed: {str(e)}", | |
| "details": {} | |
| } | |
| async def _validate_mcp_configs(self) -> Dict[str, Any]: | |
| """Validate MCP server configurations.""" | |
| try: | |
| required_servers = [ | |
| 'data_cleaning', 'hypothesis_testing', 'preprocessing', | |
| 'feature_engineering', 'model_training', 'action_generation' | |
| ] | |
| configured_servers = list(settings.mcp_servers.keys()) | |
| missing_servers = set(required_servers) - set(configured_servers) | |
| if missing_servers: | |
| return { | |
| "success": False, | |
| "message": f"Missing MCP servers: {missing_servers}", | |
| "details": { | |
| "configured": configured_servers, | |
| "missing": list(missing_servers) | |
| } | |
| } | |
| # Validate server configurations | |
| config_issues = [] | |
| for server_name, config in settings.mcp_servers.items(): | |
| required_keys = ['host', 'port'] | |
| missing_keys = [key for key in required_keys if key not in config] | |
| if missing_keys: | |
| config_issues.append(f"{server_name}: missing {missing_keys}") | |
| if config_issues: | |
| return { | |
| "success": False, | |
| "message": f"MCP configuration issues: {config_issues}", | |
| "details": {"issues": config_issues} | |
| } | |
| return { | |
| "success": True, | |
| "message": f"All {len(configured_servers)} MCP servers properly configured", | |
| "details": {"configured_servers": configured_servers} | |
| } | |
| except Exception as e: | |
| return { | |
| "success": False, | |
| "message": f"MCP config validation failed: {str(e)}", | |
| "details": {} | |
| } | |
| async def _validate_api_endpoints(self) -> Dict[str, Any]: | |
| """Validate API endpoint structure.""" | |
| try: | |
| from orchestrator.main import app | |
| # Get all routes | |
| routes = [] | |
| for route in app.routes: | |
| if hasattr(route, 'path') and hasattr(route, 'methods'): | |
| routes.append({ | |
| "path": route.path, | |
| "methods": list(route.methods) if route.methods else [] | |
| }) | |
| # Check for required endpoints | |
| required_endpoints = [ | |
| "/health", | |
| "/analysis/start", | |
| "/analysis/{session_id}/status", | |
| "/analysis/{session_id}/results", | |
| "/events/stream" | |
| ] | |
| existing_paths = [route["path"] for route in routes] | |
| missing_endpoints = [ | |
| endpoint for endpoint in required_endpoints | |
| if endpoint not in existing_paths | |
| ] | |
| if missing_endpoints: | |
| return { | |
| "success": False, | |
| "message": f"Missing API endpoints: {missing_endpoints}", | |
| "details": { | |
| "existing_endpoints": existing_paths, | |
| "missing_endpoints": missing_endpoints | |
| } | |
| } | |
| return { | |
| "success": True, | |
| "message": f"All required API endpoints present: {len(routes)} total routes", | |
| "details": {"total_routes": len(routes)} | |
| } | |
| except Exception as e: | |
| return { | |
| "success": False, | |
| "message": f"API endpoint validation failed: {str(e)}", | |
| "details": {} | |
| } | |
| async def _validate_streamlit(self) -> Dict[str, Any]: | |
| """Validate Streamlit components.""" | |
| try: | |
| # Test Streamlit component imports | |
| components_to_test = [ | |
| ('streamlit_app.components.auth', 'AuthManager'), | |
| ('streamlit_app.components.file_upload', 'FileUploadComponent'), | |
| ('streamlit_app.utils.api_client', 'APIClient'), | |
| ('streamlit_app.utils.sse_client', 'SSEClient') | |
| ] | |
| successful_imports = [] | |
| failed_imports = [] | |
| for module_name, class_name in components_to_test: | |
| try: | |
| module = __import__(module_name, fromlist=[class_name]) | |
| getattr(module, class_name) | |
| successful_imports.append(f"{module_name}.{class_name}") | |
| except Exception as e: | |
| failed_imports.append(f"{module_name}.{class_name}: {str(e)}") | |
| # Test main Streamlit app | |
| try: | |
| import streamlit_app.main | |
| main_app_ok = True | |
| except Exception as e: | |
| main_app_ok = False | |
| failed_imports.append(f"streamlit_app.main: {str(e)}") | |
| success_rate = len(successful_imports) / len(components_to_test) | |
| return { | |
| "success": success_rate >= 0.8, # Allow some failures for optional components | |
| "message": f"Streamlit validation: {len(successful_imports)}/{len(components_to_test)} components OK", | |
| "details": { | |
| "successful_imports": successful_imports, | |
| "failed_imports": failed_imports, | |
| "main_app_ok": main_app_ok | |
| } | |
| } | |
| except Exception as e: | |
| return { | |
| "success": False, | |
| "message": f"Streamlit validation failed: {str(e)}", | |
| "details": {} | |
| } | |
| async def _validate_pipeline(self) -> Dict[str, Any]: | |
| """Validate end-to-end pipeline structure.""" | |
| try: | |
| from orchestrator.analysis_orchestrator import AnalysisOrchestrator | |
| from orchestrator.mcp_client_manager import MCPClientManager | |
| from orchestrator.sse_manager import SSEManager | |
| from orchestrator.session_manager_simple import SessionManager | |
| # Test component creation | |
| mcp_client = MCPClientManager() | |
| sse_manager = SSEManager() | |
| session_manager = SessionManager() | |
| orchestrator = AnalysisOrchestrator(mcp_client, sse_manager, session_manager) | |
| # Verify pipeline stages | |
| if not hasattr(orchestrator, 'pipeline_stages'): | |
| return { | |
| "success": False, | |
| "message": "Pipeline stages not configured", | |
| "details": {} | |
| } | |
| expected_stages = 6 # Number of expected pipeline stages | |
| actual_stages = len(orchestrator.pipeline_stages) | |
| if actual_stages != expected_stages: | |
| return { | |
| "success": False, | |
| "message": f"Pipeline stage count mismatch: expected {expected_stages}, got {actual_stages}", | |
| "details": { | |
| "expected_stages": expected_stages, | |
| "actual_stages": actual_stages, | |
| "pipeline_stages": list(orchestrator.pipeline_stages.keys()) | |
| } | |
| } | |
| return { | |
| "success": True, | |
| "message": f"Pipeline structure valid: {actual_stages} stages configured", | |
| "details": { | |
| "pipeline_stages": list(orchestrator.pipeline_stages.keys()), | |
| "stage_count": actual_stages | |
| } | |
| } | |
| except Exception as e: | |
| return { | |
| "success": False, | |
| "message": f"Pipeline validation failed: {str(e)}", | |
| "details": {} | |
| } | |
| def _generate_summary(self) -> Dict[str, Any]: | |
| """Generate validation summary.""" | |
| end_time = datetime.now() | |
| duration = end_time - self.start_time | |
| successful_validations = [ | |
| name for name, result in self.validation_results.items() | |
| if result.get("success", False) | |
| ] | |
| failed_validations = [ | |
| name for name, result in self.validation_results.items() | |
| if not result.get("success", False) | |
| ] | |
| overall_success = len(failed_validations) == 0 | |
| summary = { | |
| "overall_success": overall_success, | |
| "start_time": self.start_time.isoformat(), | |
| "end_time": end_time.isoformat(), | |
| "duration_seconds": duration.total_seconds(), | |
| "total_validations": len(self.validation_results), | |
| "successful_validations": len(successful_validations), | |
| "failed_validations": len(failed_validations), | |
| "validation_results": self.validation_results, | |
| "successful_validation_names": successful_validations, | |
| "failed_validation_names": failed_validations | |
| } | |
| # Print summary | |
| print("\n" + "=" * 60) | |
| print("📊 VALIDATION SUMMARY") | |
| print("=" * 60) | |
| print(f"Overall Status: {'✅ PASSED' if overall_success else '❌ FAILED'}") | |
| print(f"Duration: {duration.total_seconds():.2f} seconds") | |
| print(f"Validations: {len(successful_validations)}/{len(self.validation_results)} passed") | |
| if failed_validations: | |
| print(f"\n❌ Failed Validations:") | |
| for name in failed_validations: | |
| print(f" • {name}") | |
| print("=" * 60) | |
| return summary | |
| async def main(): | |
| """Main validation function.""" | |
| validator = IntegrationValidator() | |
| try: | |
| summary = await validator.run_all_validations() | |
| # Save detailed report | |
| report_file = Path("integration_validation_report.json") | |
| with open(report_file, 'w') as f: | |
| json.dump(summary, f, indent=2, default=str) | |
| print(f"\n📄 Detailed report saved to: {report_file}") | |
| # Exit with appropriate code | |
| return summary["overall_success"] | |
| except Exception as e: | |
| print(f"\n❌ Validation failed with error: {e}") | |
| return False | |
| if __name__ == "__main__": | |
| success = asyncio.run(main()) | |
| sys.exit(0 if success else 1) |