# Test Failure Analysis Agent A comprehensive AI-powered system for analyzing test failures using the Sponge MCP (Model Context Protocol) Server. This system provides 10 specialized analysis tools to help developers quickly identify, understand, and resolve test failures. ## Features ### 🔍 Analysis Capabilities 1. **Flakiness Detection** - Calculate pass/fail ratios to identify flaky tests 2. **Regression Window Detection** - Find exact moments when tests went from green to red 3. **Log Comparison** - Identify divergence points between passing/failing runs 4. **Error Root Location** - Jump to first ERROR after last INFO message 5. **Cross-Service Log Correlation** - Correlate logs across services using timestamps 6. **Log Anomaly Summarization** - Reduce noise by grouping similar errors 7. **Stack Trace Context** - Provide code context around stack traces 8. **Visual State Inspection** - Return screenshots/videos with action context 9. **Visual Baseline Comparison** - Compare UI states between runs 10. **Concurrency Drift Analysis** - Detect environment aging through duration trends ### 🚀 Analysis Types - **Comprehensive Analysis** - Full deep-dive analysis using all available tools - **Quick Analysis** - Fast triage focusing on immediate issues - **Visual Regression Analysis** - Specialized analysis for UI test failures ## Architecture ``` ┌─────────────────────────────────────┐ │ Test Failure Analysis Agent │ │ (Orchestrates analysis workflow) │ └─────────────┬───────────────────────┘ │ MCP Protocol ▼ ┌─────────────────────────────────────┐ │ Sponge MCP Server │ │ (10 specialized analysis tools) │ └─────────────────────────────────────┘ ``` ## Installation 1. **Clone or copy the files to your project:** ```bash # Files needed: # - sponge_mcp_server.py # - test_failure_analysis_agent.py # - requirements.txt # - mcp_config.json ``` 2. **Install dependencies:** ```bash pip install -r requirements.txt ``` 3. **Set up environment variables (optional):** ```bash cp .env.example .env # Edit .env with your configuration ``` ## Usage ### Command Line Interface ```bash # Comprehensive analysis python test_failure_analysis_agent.py "//service/auth:login_test" \ --failing-invocation "inv_failed_12345" \ --passing-invocation "inv_passed_12344" \ --analysis-type comprehensive # Quick analysis python test_failure_analysis_agent.py "//service/payment:timeout_test" \ --failing-invocation "inv_timeout_67890" \ --analysis-type quick # Visual regression analysis python test_failure_analysis_agent.py "//ui/checkout:visual_test" \ --failing-invocation "inv_ui_failed_11111" \ --passing-invocation "inv_ui_passed_11110" \ --analysis-type visual_regression \ --output report.md ``` ### Programmatic Usage ```python import asyncio from test_failure_analysis_agent import TestFailureAnalysisAgent, AnalysisRequest async def analyze_test_failure(): agent = TestFailureAnalysisAgent() request = AnalysisRequest( target_id="//service/auth:flaky_login_test", failing_invocation_id="inv_failed_12345", passing_invocation_id="inv_passed_12344", analysis_type="comprehensive" ) try: result = await agent.analyze(request) report = agent.generate_report(result) print(report) finally: await agent.disconnect() # Run the analysis asyncio.run(analyze_test_failure()) ``` ### MCP Server Integration The system can be integrated with Kiro or other MCP-compatible tools: ```json { "mcpServers": { "sponge-test-failure-analysis": { "command": "python", "args": ["test_failure_analysis/sponge_mcp_server.py"], "env": { "PYTHONPATH": ".", "FASTMCP_LOG_LEVEL": "INFO" }, "disabled": false, "autoApprove": [ "get_flaky_index", "detect_regression_window", "compare_log_diffs", "locate_error_root" ] } } } ``` ## Demo Run the comprehensive demo to see all features in action: ```bash python demo_test.py ``` This will demonstrate: - Comprehensive analysis workflow - Quick analysis for fast triage - Visual regression analysis - Individual tool testing ## Analysis Tools Reference ### 1. get_flaky_index Calculates pass/fail ratios to identify flaky tests. **Parameters:** - `target_id` (str): Test target identifier - `runs_count` (int): Number of recent runs to analyze (default: 50) **Returns:** - Flaky ratio, confidence level, and recommendations ### 2. detect_regression_window Finds exact moments when tests went from green to red. **Parameters:** - `target_id` (str): Test target identifier - `lookback_days` (int): Days to look back (default: 7) **Returns:** - Regression timestamp, changelist, and confidence ### 3. compare_log_diffs Identifies divergence points between passing/failing runs. **Parameters:** - `failing_invocation_id` (str): Failed run identifier - `passing_invocation_id` (str): Passing run identifier - `build_target` (str): Build target **Returns:** - Divergence point, new errors, and analysis ### 4. locate_error_root Jumps to first ERROR after last INFO message. **Parameters:** - `invocation_id` (str): Run identifier - `build_target` (str): Build target **Returns:** - Error line, line number, and context ### 5. correlate_cross_service_logs Correlates logs across services using timestamps. **Parameters:** - `invocation_id` (str): Run identifier - `service_targets` (List[str]): List of service targets - `time_window` (int): Time window in seconds (default: 300) **Returns:** - Timeline and correlation analysis ### 6. summarize_log_anomalies Reduces noise by grouping similar errors. **Parameters:** - `invocation_id` (str): Run identifier - `build_target` (str): Build target - `min_occurrences` (int): Minimum occurrences to report (default: 2) **Returns:** - Unique errors, patterns, and occurrence counts ### 7. fetch_stack_trace_context Provides code context around stack traces. **Parameters:** - `invocation_id` (str): Run identifier - `build_target` (str): Build target - `context_lines` (int): Lines of context (default: 5) **Returns:** - Stack trace, code context, and analysis ### 8. inspect_visual_state Returns screenshots/videos with action context. **Parameters:** - `invocation_id` (str): Run identifier - `build_target` (str): Build target - `action_name` (str): Action being tested **Returns:** - Screenshots, videos, and visual analysis ### 9. compare_visual_baselines Compares UI states between runs. **Parameters:** - `failing_invocation_id` (str): Failed run identifier - `baseline_invocation_id` (str): Baseline run identifier - `build_target` (str): Build target **Returns:** - Visual differences and regression analysis ### 10. analyze_concurrency_drift Detects environment aging through duration trends. **Parameters:** - `target_id` (str): Test target identifier - `days_back` (int): Days to analyze (default: 30) **Returns:** - Duration trends, drift analysis, and recommendations ## Output Format The agent generates structured reports with: - **Key Findings** - Detailed analysis results from each tool - **Recommendations** - Actionable suggestions based on findings - **Confidence Score** - Overall confidence in the analysis (0.0-1.0) - **Next Steps** - Specific actions to take Example output: ```markdown # Test Failure Analysis Report **Target:** //service/auth:flaky_login_test **Analysis Type:** comprehensive **Confidence Score:** 0.82 ## Key Findings ### Flakiness - **flaky_ratio:** 0.34 - **confidence:** high - **recommendation:** High flakiness detected (34.0%). Consider adding to flaky test list. ### Regression - **changelist:** CL_98042 - **confidence:** high - **analysis:** Regression detected at 2024-01-15T10:30:00 ## Recommendations 1. High flakiness detected - consider stabilizing test 2. Regression detected at CL_98042 3. Primary error location identified - focus debugging here ## Next Steps 1. Add test to flaky test list 2. Review changes in CL_98042 3. Debug the identified error location ``` ## Configuration ### Environment Variables Create a `.env` file with: ```bash # Logging configuration LOG_LEVEL=INFO LOG_FORMAT='%(asctime)s - %(levelname)s - %(message)s' # MCP Server configuration MCP_SERVER_NAME=sponge-test-failure-analysis MCP_SERVER_VERSION=1.0.0 # Analysis configuration DEFAULT_RUNS_COUNT=50 DEFAULT_LOOKBACK_DAYS=7 DEFAULT_TIME_WINDOW=300 ``` ### MCP Configuration The `mcp_config.json` file configures the MCP server integration. Key settings: - **autoApprove**: Tools that don't require user confirmation - **disabled**: Enable/disable the server - **env**: Environment variables for the server process ## Extending the System ### Adding New Analysis Tools 1. **Implement the tool function** in `sponge_mcp_server.py`: ```python def my_new_analysis_tool(param1: str, param2: int) -> Dict[str, Any]: # Your analysis logic here return {"result": "analysis_data"} ``` 2. **Add to ADK_SPONGE_TOOLS**: ```python ADK_SPONGE_TOOLS["my_new_analysis_tool"] = FunctionTool(func=my_new_analysis_tool) ``` 3. **Update the agent** to use the new tool in analysis workflows. ### Custom Analysis Types Add new analysis types by extending the `TestFailureAnalysisAgent` class: ```python async def analyze_custom(self, request: AnalysisRequest) -> AnalysisResult: # Your custom analysis logic findings = {} # ... implement analysis return AnalysisResult(...) ``` ## Troubleshooting ### Common Issues 1. **MCP Connection Failed** - Check that Python is in your PATH - Verify the server script path is correct - Check logs for detailed error messages 2. **Tool Execution Errors** - Ensure all required parameters are provided - Check parameter types match the function signatures - Review server logs for detailed error information 3. **Missing Dependencies** - Run `pip install -r requirements.txt` - Check that all required packages are installed ### Debugging Enable debug logging: ```python import logging logging.basicConfig(level=logging.DEBUG) ``` Check MCP server logs: ```bash python sponge_mcp_server.py 2>&1 | tee server.log ``` ## Contributing 1. Fork the repository 2. Create a feature branch 3. Add tests for new functionality 4. Ensure all tests pass 5. Submit a pull request ## License This project is licensed under the MIT License - see the LICENSE file for details. ## Support For questions, issues, or feature requests: - Create an issue in the repository - Check the troubleshooting section - Review the demo script for usage examples