| |
| """ |
| Analyze RETRY patterns in the EmailResponder-MCP project. |
| Collect statistics on error locations, retry counts, retry rates, etc. |
| """ |
|
|
| import os |
| import re |
| from pathlib import Path |
| from collections import defaultdict |
| import json |
| import csv |
|
|
| |
| BASE_DIR = Path("/Users/wzr/TOSEM-2025/RESULTS") |
| MODELS = [ |
| "DeepSeek-R1", |
| "DeepSeek-V3-1", |
| "GPT-4o-mini", |
| "GPT-5", |
| "Gemini-2.5-flash", |
| "Gemini-2.5-flash-nothinking", |
| "Qwen3-235b", |
| ] |
| PROJECT_NAME = "EmailResponder-MCP" |
|
|
|
|
| def extract_error_info(line: str) -> dict: |
| """Extract error information from an error line. |
| |
| Returns: |
| {'has_error': bool, 'node_type': str, 'node_name': str, 'error_msg': str} |
| """ |
| |
| clean = re.sub(r"^[│├└\-\s]+", "", line).strip() |
|
|
| |
| if "❌" not in clean: |
| return {"has_error": False} |
|
|
| |
| clean = clean.split("❌", 1)[1].lstrip() |
|
|
| |
| node_match = re.match( |
| r"\[(SPAN|Chain|AGENT|Tool|LLM)\]\s+([^\[\]]+?)(?:\s+\[ERROR:(.*))?$", |
| clean, |
| ) |
| if not node_match: |
| return { |
| "has_error": True, |
| "node_type": "Unknown", |
| "node_name": "Unknown", |
| "error_msg": "", |
| } |
|
|
| node_type = node_match.group(1) |
| node_name = node_match.group(2).strip() |
| error_msg = node_match.group(3).strip() if node_match.group(3) else "" |
|
|
| |
| if node_type == "AGENT": |
| node_name = re.sub(r"\._execute_core$", "", node_name) |
| elif node_type == "Tool": |
| node_name = re.sub(r"\._use$", "", node_name) |
| elif node_type == "Chain": |
| node_name = re.sub(r"Crew_[a-f0-9\-]+\.kickoff", "Crew***.kickoff", node_name) |
|
|
| return { |
| "has_error": True, |
| "node_type": node_type, |
| "node_name": node_name, |
| "error_msg": error_msg, |
| } |
|
|
|
|
| def extract_retry_info(line: str) -> dict: |
| """Extract RETRY information from a RETRY line. |
| |
| Returns: |
| {'is_retry': bool, 'retry_number': int, 'node_type': str, 'node_name': str} |
| """ |
| |
| clean = re.sub(r"^[│├└─\s]+", "", line).strip() |
|
|
| |
| retry_match = re.search(r"\(retry\s+(\d+)\)", clean) |
| if not retry_match: |
| retry_match = re.search(r"\[RETRY(\d+)\]", clean) |
|
|
| if not retry_match: |
| return {"is_retry": False} |
|
|
| retry_number = int(retry_match.group(1)) |
|
|
| |
| node_match = re.match( |
| r"\[(SPAN|Chain|AGENT)\]\s+([^\[\]]+?)(?:\s+\(retry\s+\d+\))?(?:\s+\[RETRY\d+\])?\s*(?:\[.*)?$", |
| clean, |
| ) |
| if not node_match: |
| return { |
| "is_retry": True, |
| "retry_number": retry_number, |
| "node_type": "Unknown", |
| "node_name": "Unknown", |
| } |
|
|
| node_type = node_match.group(1) |
| node_name = node_match.group(2).strip() |
|
|
| return { |
| "is_retry": True, |
| "retry_number": retry_number, |
| "node_type": node_type, |
| "node_name": node_name, |
| } |
|
|
|
|
| def analyze_session(md_file: str) -> dict: |
| """Analyze a single session's execution_path.md. |
| |
| Returns: |
| { |
| 'has_error': bool, |
| 'has_retry': bool, |
| 'max_retry_number': int, |
| 'total_retries': int, |
| 'errors': [{'node_type': str, 'node_name': str, 'error_msg': str}, ...], |
| 'retries': [{'retry_number': int, 'node_type': str, 'node_name': str}, ...] |
| } |
| """ |
| if not os.path.exists(md_file): |
| return None |
|
|
| with open(md_file, "r", encoding="utf-8") as f: |
| content = f.read() |
|
|
| |
| tree_match = re.search( |
| r"## Execution Path Tree.*?```\n(.*?)```", content, re.DOTALL |
| ) |
| if not tree_match: |
| return None |
|
|
| tree_content = tree_match.group(1) |
|
|
| errors = [] |
| retries = [] |
|
|
| for line in tree_content.split("\n"): |
| if not line.strip(): |
| continue |
|
|
| |
| error_info = extract_error_info(line) |
| if error_info["has_error"]: |
| errors.append( |
| { |
| "node_type": error_info.get("node_type", "Unknown"), |
| "node_name": error_info.get("node_name", "Unknown"), |
| "error_msg": error_info.get("error_msg", ""), |
| } |
| ) |
|
|
| |
| retry_info = extract_retry_info(line) |
| if retry_info["is_retry"]: |
| retries.append( |
| { |
| "retry_number": retry_info["retry_number"], |
| "node_type": retry_info["node_type"], |
| "node_name": retry_info["node_name"], |
| } |
| ) |
|
|
| max_retry = max([r["retry_number"] for r in retries]) if retries else 0 |
|
|
| return { |
| "has_error": len(errors) > 0, |
| "has_retry": len(retries) > 0, |
| "max_retry_number": max_retry, |
| "total_retries": len(retries), |
| "errors": errors, |
| "retries": retries, |
| } |
|
|
|
|
| def collect_model_stats(model_name: str) -> dict: |
| """Collect RETRY statistics for a single model. |
| |
| Returns: |
| { |
| 'model': str, |
| 'total_sessions': int, |
| 'sessions_with_error': int, |
| 'sessions_with_retry': int, |
| 'total_retry_attempts': int, |
| 'retry_rate': float, |
| 'error_by_agent': {agent_name: count}, |
| 'error_types': {error_msg: count}, |
| 'max_retry_number': int, |
| 'session_details': [...] |
| } |
| """ |
| test_results_dir = BASE_DIR / model_name / PROJECT_NAME / "test_results" |
|
|
| if not test_results_dir.exists(): |
| return None |
|
|
| stats = { |
| "model": model_name, |
| "total_sessions": 0, |
| "sessions_with_error": 0, |
| "sessions_with_retry": 0, |
| "total_retry_attempts": 0, |
| "error_by_agent": defaultdict(int), |
| "error_by_node_type": defaultdict(int), |
| "error_types": defaultdict(int), |
| "max_retry_number": 0, |
| "session_details": [], |
| } |
|
|
| for session_dir in sorted(test_results_dir.iterdir()): |
| if not session_dir.is_dir(): |
| continue |
|
|
| exec_path_file = session_dir / "execution_path.md" |
| if not exec_path_file.exists(): |
| continue |
|
|
| stats["total_sessions"] += 1 |
|
|
| analysis = analyze_session(str(exec_path_file)) |
| if not analysis: |
| continue |
|
|
| |
| if analysis["has_error"]: |
| stats["sessions_with_error"] += 1 |
|
|
| if analysis["has_retry"]: |
| stats["sessions_with_retry"] += 1 |
| stats["total_retry_attempts"] += analysis["total_retries"] |
| stats["max_retry_number"] = max( |
| stats["max_retry_number"], analysis["max_retry_number"] |
| ) |
|
|
| |
| for error in analysis["errors"]: |
| if error["node_type"] == "AGENT": |
| stats["error_by_agent"][error["node_name"]] += 1 |
| stats["error_by_node_type"][error["node_type"]] += 1 |
|
|
| |
| error_msg = error["error_msg"] |
| if error_msg: |
| |
| error_type = ( |
| error_msg[:100] |
| if len(error_msg) <= 100 |
| else error_msg[:100] + "..." |
| ) |
| stats["error_types"][error_type] += 1 |
|
|
| |
| stats["session_details"].append( |
| { |
| "session": session_dir.name, |
| "has_error": analysis["has_error"], |
| "has_retry": analysis["has_retry"], |
| "retry_count": analysis["total_retries"], |
| "errors": analysis["errors"], |
| "retries": analysis["retries"], |
| } |
| ) |
|
|
| |
| stats["retry_rate"] = ( |
| (stats["sessions_with_retry"] / stats["total_sessions"] * 100) |
| if stats["total_sessions"] > 0 |
| else 0 |
| ) |
| stats["error_rate"] = ( |
| (stats["sessions_with_error"] / stats["total_sessions"] * 100) |
| if stats["total_sessions"] > 0 |
| else 0 |
| ) |
|
|
| |
| stats["error_by_agent"] = dict(stats["error_by_agent"]) |
| stats["error_by_node_type"] = dict(stats["error_by_node_type"]) |
| stats["error_types"] = dict(stats["error_types"]) |
|
|
| return stats |
|
|
|
|
| def print_summary(all_stats): |
| """Print statistics summary.""" |
| print("\n" + "=" * 100) |
| print(f"RETRY Pattern Analysis Summary - {PROJECT_NAME}") |
| print("=" * 100 + "\n") |
|
|
| |
| print("## Model Statistics\n") |
| print( |
| f"{'Model':<35} {'Total Sessions':<14} {'Error Rate':<12} {'Retry Rate':<12} {'Total Retries':<14} {'Max Retry':<10}" |
| ) |
| print("-" * 100) |
|
|
| for stats in all_stats: |
| if stats: |
| print( |
| f"{stats['model']:<35} {stats['total_sessions']:<14} " |
| f"{stats['error_rate']:>10.1f}% {stats['retry_rate']:>10.1f}% " |
| f"{stats['total_retry_attempts']:<14} {stats['max_retry_number']:<10}" |
| ) |
|
|
| print("\n" + "=" * 100) |
|
|
| |
| for stats in all_stats: |
| if not stats or stats["sessions_with_error"] == 0: |
| continue |
|
|
| print(f"\n### {stats['model']}\n") |
| print(f"- Total Sessions: {stats['total_sessions']}") |
| print( |
| f"- Sessions with Error: {stats['sessions_with_error']} ({stats['error_rate']:.1f}%)" |
| ) |
| print( |
| f"- Sessions with Retry: {stats['sessions_with_retry']} ({stats['retry_rate']:.1f}%)" |
| ) |
| print(f"- Total Retry Attempts: {stats['total_retry_attempts']}") |
| print(f"- Max Retry Number: {stats['max_retry_number']}") |
|
|
| if stats["error_by_agent"]: |
| print(f"\nErrors by Agent:") |
| for agent, count in sorted( |
| stats["error_by_agent"].items(), key=lambda x: x[1], reverse=True |
| ): |
| print(f" - {agent}: {count} times") |
|
|
| if stats["error_by_node_type"]: |
| print(f"\nErrors by Node Type:") |
| for node_type, count in sorted( |
| stats["error_by_node_type"].items(), key=lambda x: x[1], reverse=True |
| ): |
| print(f" - {node_type}: {count} times") |
|
|
| if stats["error_types"]: |
| print(f"\nError Types (Top 5):") |
| for error_type, count in sorted( |
| stats["error_types"].items(), key=lambda x: x[1], reverse=True |
| )[:5]: |
| print(f" - [{count} times] {error_type}") |
|
|
| print("\n" + "-" * 100) |
|
|
|
|
| def save_results(all_stats): |
| """Save results to files.""" |
| output_dir = Path(__file__).parent |
|
|
| |
| json_file = output_dir / "retry_analysis.json" |
| json_data = [] |
| for stats in all_stats: |
| if stats: |
| json_data.append(stats) |
|
|
| with open(json_file, "w", encoding="utf-8") as f: |
| json.dump(json_data, f, indent=2, ensure_ascii=False) |
| print(f"\n[OK] JSON detailed results saved: {json_file}") |
|
|
| |
| csv_file = output_dir / "retry_summary.csv" |
| with open(csv_file, "w", newline="", encoding="utf-8") as f: |
| writer = csv.writer(f) |
| writer.writerow( |
| [ |
| "Model", |
| "Total_Sessions", |
| "Sessions_With_Error", |
| "Error_Rate(%)", |
| "Sessions_With_Retry", |
| "Retry_Rate(%)", |
| "Total_Retry_Attempts", |
| "Max_Retry_Number", |
| ] |
| ) |
|
|
| for stats in all_stats: |
| if stats: |
| writer.writerow( |
| [ |
| stats["model"], |
| stats["total_sessions"], |
| stats["sessions_with_error"], |
| f"{stats['error_rate']:.2f}", |
| stats["sessions_with_retry"], |
| f"{stats['retry_rate']:.2f}", |
| stats["total_retry_attempts"], |
| stats["max_retry_number"], |
| ] |
| ) |
|
|
| print(f"[OK] CSV summary saved: {csv_file}") |
|
|
| |
| error_csv_file = output_dir / "error_by_agent.csv" |
| with open(error_csv_file, "w", newline="", encoding="utf-8") as f: |
| writer = csv.writer(f) |
| writer.writerow(["Model", "Agent_Name", "Error_Count"]) |
|
|
| for stats in all_stats: |
| if stats and stats["error_by_agent"]: |
| for agent, count in sorted( |
| stats["error_by_agent"].items(), key=lambda x: x[1], reverse=True |
| ): |
| writer.writerow([stats["model"], agent, count]) |
|
|
| print(f"[OK] Error location statistics saved: {error_csv_file}") |
|
|
|
|
| if __name__ == "__main__": |
| print(f"Starting RETRY pattern analysis - {PROJECT_NAME}...") |
|
|
| all_stats = [] |
| for model in MODELS: |
| print(f"\nAnalyzing model: {model}") |
| stats = collect_model_stats(model) |
| if stats: |
| all_stats.append(stats) |
| print( |
| f" [OK] Completed: {stats['total_sessions']} sessions, " |
| f"{stats['sessions_with_error']} errors, " |
| f"{stats['sessions_with_retry']} retries" |
| ) |
| else: |
| print(f" [WARN] Skipped (directory does not exist)") |
|
|
| print_summary(all_stats) |
| save_results(all_stats) |
|
|
| print("\n" + "=" * 100) |
| print("[OK] Analysis completed!") |
| print("=" * 100) |
|
|