Spaces:
Sleeping
Sleeping
File size: 11,492 Bytes
dce5ebb | 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 | # 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 |