Spaces:
Sleeping
Sleeping
File size: 13,930 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 | """
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
""" |