Spaces:
Sleeping
Sleeping
Download test_failure_analysis/kiro_integration_example.py from VAH6002/Test_Failure_Analysis_Agent: direct link, hf CLI and curl.
- Browser
- Download file 13.9 kB
-
https://huggingface.co/spaces/VAH6002/Test_Failure_Analysis_Agent/resolve/main/test_failure_analysis/kiro_integration_example.py
- Command line
-
hf download hf://spaces/VAH6002/Test_Failure_Analysis_Agent/test_failure_analysis/kiro_integration_example.py
-
curl -L -o kiro_integration_example.py https://huggingface.co/spaces/VAH6002/Test_Failure_Analysis_Agent/resolve/main/test_failure_analysis/kiro_integration_example.py
13.9 kB
| """ | |
| Example of how to integrate the Test Failure Analysis Agent with Kiro | |
| This shows how to use the MCP tools through Kiro's interface | |
| """ | |
| import json | |
| from typing import Dict, Any, List | |
| class KiroTestFailureAnalysisIntegration: | |
| """ | |
| Integration class for using Test Failure Analysis tools in Kiro | |
| This would be used within Kiro's agent system | |
| """ | |
| def __init__(self, mcp_client): | |
| """Initialize with Kiro's MCP client""" | |
| self.mcp_client = mcp_client | |
| self.server_name = "sponge-test-failure-analysis" | |
| async def analyze_test_failure(self, target_id: str, failing_invocation_id: str = None, | |
| passing_invocation_id: str = None) -> Dict[str, Any]: | |
| """ | |
| Main entry point for test failure analysis in Kiro | |
| """ | |
| analysis_results = {} | |
| recommendations = [] | |
| # Step 1: Check for flakiness | |
| flaky_result = await self._call_tool("get_flaky_index", { | |
| "target_id": target_id, | |
| "runs_count": 50 | |
| }) | |
| analysis_results["flakiness"] = flaky_result | |
| if flaky_result.get("flaky_ratio", 0) > 0.2: | |
| recommendations.append({ | |
| "type": "flakiness", | |
| "severity": "high", | |
| "message": f"Test shows {flaky_result['flaky_ratio']:.1%} failure rate - consider stabilizing", | |
| "action": "add_to_flaky_list" | |
| }) | |
| # Step 2: Look for regression | |
| regression_result = await self._call_tool("detect_regression_window", { | |
| "target_id": target_id, | |
| "lookback_days": 7 | |
| }) | |
| analysis_results["regression"] = regression_result | |
| if regression_result.get("confidence") == "high": | |
| recommendations.append({ | |
| "type": "regression", | |
| "severity": "high", | |
| "message": f"Regression detected at {regression_result.get('changelist')}", | |
| "action": "review_changelist" | |
| }) | |
| # Step 3: Analyze logs if we have invocation IDs | |
| if failing_invocation_id: | |
| error_root = await self._call_tool("locate_error_root", { | |
| "invocation_id": failing_invocation_id, | |
| "build_target": target_id | |
| }) | |
| analysis_results["error_root"] = error_root | |
| if error_root.get("error_line"): | |
| recommendations.append({ | |
| "type": "error_location", | |
| "severity": "medium", | |
| "message": f"Primary error: {error_root['error_line']}", | |
| "action": "debug_error_location" | |
| }) | |
| if failing_invocation_id and passing_invocation_id: | |
| log_diff = await self._call_tool("compare_log_diffs", { | |
| "failing_invocation_id": failing_invocation_id, | |
| "passing_invocation_id": passing_invocation_id, | |
| "build_target": target_id | |
| }) | |
| analysis_results["log_comparison"] = log_diff | |
| if log_diff.get("new_errors"): | |
| recommendations.append({ | |
| "type": "new_errors", | |
| "severity": "medium", | |
| "message": f"Found {len(log_diff['new_errors'])} new errors in failing run", | |
| "action": "investigate_errors" | |
| }) | |
| # Step 4: Check for performance drift | |
| drift_result = await self._call_tool("analyze_concurrency_drift", { | |
| "target_id": target_id, | |
| "days_back": 30 | |
| }) | |
| analysis_results["performance_drift"] = drift_result | |
| drift_pct = drift_result.get("duration_trend", {}).get("drift_percentage", 0) | |
| if abs(drift_pct) > 20: | |
| recommendations.append({ | |
| "type": "performance_drift", | |
| "severity": "medium", | |
| "message": f"Performance drift of {drift_pct:.1f}% detected", | |
| "action": "refresh_environment" | |
| }) | |
| return { | |
| "target_id": target_id, | |
| "analysis_results": analysis_results, | |
| "recommendations": recommendations, | |
| "confidence_score": self._calculate_confidence(analysis_results), | |
| "next_steps": self._generate_next_steps(recommendations) | |
| } | |
| async def analyze_visual_regression(self, target_id: str, failing_invocation_id: str, | |
| baseline_invocation_id: str = None) -> Dict[str, Any]: | |
| """Specialized visual regression analysis for UI tests""" | |
| # Inspect visual state | |
| visual_state = await self._call_tool("inspect_visual_state", { | |
| "invocation_id": failing_invocation_id, | |
| "build_target": target_id, | |
| "action_name": "ui_interaction" | |
| }) | |
| results = {"visual_state": visual_state} | |
| recommendations = [] | |
| # Compare with baseline if available | |
| if baseline_invocation_id: | |
| visual_comparison = await self._call_tool("compare_visual_baselines", { | |
| "failing_invocation_id": failing_invocation_id, | |
| "baseline_invocation_id": baseline_invocation_id, | |
| "build_target": target_id | |
| }) | |
| results["visual_comparison"] = visual_comparison | |
| if visual_comparison.get("regression_detected"): | |
| recommendations.append({ | |
| "type": "visual_regression", | |
| "severity": "high", | |
| "message": "Visual regression detected - UI elements have changed", | |
| "action": "review_ui_changes" | |
| }) | |
| return { | |
| "target_id": target_id, | |
| "analysis_type": "visual_regression", | |
| "results": results, | |
| "recommendations": recommendations | |
| } | |
| async def get_stack_trace_analysis(self, invocation_id: str, build_target: str) -> Dict[str, Any]: | |
| """Get detailed stack trace analysis with code context""" | |
| stack_trace_result = await self._call_tool("fetch_stack_trace_context", { | |
| "invocation_id": invocation_id, | |
| "build_target": build_target, | |
| "context_lines": 5 | |
| }) | |
| return { | |
| "invocation_id": invocation_id, | |
| "stack_trace": stack_trace_result.get("stack_trace", []), | |
| "code_context": stack_trace_result.get("code_context", {}), | |
| "analysis": stack_trace_result.get("analysis", ""), | |
| "suggested_fix": stack_trace_result.get("suggested_fix", "") | |
| } | |
| async def correlate_service_failures(self, invocation_id: str, | |
| service_targets: List[str]) -> Dict[str, Any]: | |
| """Correlate failures across multiple services""" | |
| correlation_result = await self._call_tool("correlate_cross_service_logs", { | |
| "invocation_id": invocation_id, | |
| "service_targets": service_targets, | |
| "time_window": 300 | |
| }) | |
| return { | |
| "invocation_id": invocation_id, | |
| "services": service_targets, | |
| "timeline": correlation_result.get("timeline", []), | |
| "correlation_analysis": correlation_result.get("correlation_analysis", "") | |
| } | |
| async def _call_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]: | |
| """Call a tool on the MCP server""" | |
| try: | |
| result = await self.mcp_client.call_tool( | |
| server_name=self.server_name, | |
| tool_name=tool_name, | |
| arguments=arguments | |
| ) | |
| if result and result.content: | |
| return json.loads(result.content[0].text) | |
| return {} | |
| except Exception as e: | |
| return {"error": str(e)} | |
| def _calculate_confidence(self, analysis_results: Dict[str, Any]) -> float: | |
| """Calculate overall confidence score""" | |
| confidence_factors = [] | |
| # Flakiness confidence | |
| flaky_data = analysis_results.get("flakiness", {}) | |
| if flaky_data.get("confidence") == "high": | |
| confidence_factors.append(0.9) | |
| elif flaky_data.get("confidence") == "medium": | |
| confidence_factors.append(0.7) | |
| # Regression confidence | |
| regression_data = analysis_results.get("regression", {}) | |
| if regression_data.get("confidence") == "high": | |
| confidence_factors.append(0.9) | |
| elif regression_data.get("confidence") == "medium": | |
| confidence_factors.append(0.7) | |
| # Error analysis confidence | |
| if analysis_results.get("error_root", {}).get("error_line"): | |
| confidence_factors.append(0.8) | |
| # Log comparison confidence | |
| if analysis_results.get("log_comparison", {}).get("new_errors"): | |
| confidence_factors.append(0.7) | |
| return sum(confidence_factors) / len(confidence_factors) if confidence_factors else 0.5 | |
| def _generate_next_steps(self, recommendations: List[Dict[str, Any]]) -> List[str]: | |
| """Generate actionable next steps""" | |
| next_steps = [] | |
| for rec in recommendations: | |
| if rec["action"] == "add_to_flaky_list": | |
| next_steps.append("Add test to flaky test list and investigate stability") | |
| elif rec["action"] == "review_changelist": | |
| next_steps.append("Review recent code changes for potential issues") | |
| elif rec["action"] == "debug_error_location": | |
| next_steps.append("Debug the identified error location with additional logging") | |
| elif rec["action"] == "investigate_errors": | |
| next_steps.append("Investigate new error patterns in failing runs") | |
| elif rec["action"] == "refresh_environment": | |
| next_steps.append("Consider refreshing test environment due to performance drift") | |
| elif rec["action"] == "review_ui_changes": | |
| next_steps.append("Review UI changes and update test expectations if needed") | |
| if not next_steps: | |
| next_steps = ["Monitor test for additional failures and patterns"] | |
| return next_steps | |
| # Example usage in Kiro agent | |
| async def kiro_agent_example(mcp_client, user_request: str): | |
| """ | |
| Example of how this would be used in a Kiro agent | |
| """ | |
| integration = KiroTestFailureAnalysisIntegration(mcp_client) | |
| # Parse user request (simplified) | |
| if "analyze test failure" in user_request.lower(): | |
| # Extract test target from user request | |
| target_id = "//service/auth:login_test" # Would be extracted from request | |
| # Perform analysis | |
| result = await integration.analyze_test_failure( | |
| target_id=target_id, | |
| failing_invocation_id="inv_failed_12345", | |
| passing_invocation_id="inv_passed_12344" | |
| ) | |
| # Format response for user | |
| response = f""" | |
| # Test Failure Analysis Results | |
| **Target:** {result['target_id']} | |
| **Confidence Score:** {result['confidence_score']:.2f} | |
| ## Key Findings | |
| """ | |
| for rec in result['recommendations']: | |
| severity_emoji = "🚨" if rec['severity'] == 'high' else "⚠️" | |
| response += f"\n{severity_emoji} **{rec['type'].title()}:** {rec['message']}" | |
| response += "\n\n## Next Steps\n" | |
| for i, step in enumerate(result['next_steps'], 1): | |
| response += f"{i}. {step}\n" | |
| return response | |
| elif "visual regression" in user_request.lower(): | |
| # Handle visual regression analysis | |
| result = await integration.analyze_visual_regression( | |
| target_id="//ui/checkout:test", | |
| failing_invocation_id="inv_ui_failed_123", | |
| baseline_invocation_id="inv_ui_passed_122" | |
| ) | |
| return f"Visual regression analysis completed for {result['target_id']}" | |
| else: | |
| return "I can help analyze test failures. Try asking 'analyze test failure for [target]'" | |
| # Kiro Hook Example | |
| KIRO_HOOK_CONFIG = { | |
| "name": "Test Failure Analysis", | |
| "description": "Automatically analyze test failures when they occur", | |
| "trigger": "on_test_failure", | |
| "action": "analyze_test_failure", | |
| "auto_run": True, | |
| "parameters": { | |
| "analysis_type": "comprehensive", | |
| "include_visual_analysis": True | |
| } | |
| } | |
| # Kiro Steering Example | |
| KIRO_STEERING_CONTENT = """ | |
| # Test Failure Analysis Guidelines | |
| When analyzing test failures, always: | |
| 1. **Start with flakiness detection** - Check if the test has a history of intermittent failures | |
| 2. **Look for regression windows** - Identify when the test started failing | |
| 3. **Compare logs** - Find differences between passing and failing runs | |
| 4. **Locate error roots** - Jump to the primary error location | |
| 5. **Check for drift** - Analyze performance trends over time | |
| ## Integration with Development Workflow | |
| - For flaky tests (>20% failure rate): Add to flaky test list | |
| - For regressions: Review the identified changelist | |
| - For new errors: Investigate error patterns and add logging | |
| - For performance drift: Consider environment refresh | |
| ## Visual Regression Analysis | |
| For UI tests, always include: | |
| - Visual state inspection | |
| - Baseline comparison | |
| - Element difference analysis | |
| """ |