| |
| """ |
| Analyze RETRY patterns in the BookWriter-A2A project. |
| |
| This script collects: |
| - Error locations |
| - Retry counts |
| - Retry rates |
| |
| Focus: |
| - BUSINESS-RETRY: [BUSINESS-RETRY] |
| - Orchestrator retry: (retry N) |
| |
| A2A-specific notes: |
| - Additional SPAN layers exist (a2a_call_*, *_server_execution) |
| - Chapter SPAN names may include a chapter title (a2a_call_chapter_writer_(chapter_title)) |
| """ |
|
|
| 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 = "BookWriter-A2A" |
|
|
|
|
| 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) |
| elif node_type == "SPAN": |
| |
| node_name = re.sub( |
| r"a2a_call_chapter_writer_\([^)]+\)", "a2a_call_chapter_writer_*", 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 (including BUSINESS-RETRY). |
| |
| A2A note: chapter SPAN names may contain a chapter title and need normalization. |
| |
| Returns: |
| { |
| 'is_retry': bool, |
| 'retry_type': str ('orchestrator' or 'business_logic'), |
| 'retry_number': int (only applicable to orchestrator retries), |
| 'node_type': str, |
| 'node_name': str, |
| 'batch_info': str (BATCH info, if any) |
| } |
| """ |
| |
| clean = re.sub(r"^[│├└─\-\s]+", "", line).strip() |
|
|
| |
| has_business_retry = "[BUSINESS-RETRY]" in clean |
|
|
| |
| orchestrator_retry_match = re.search(r"\(retry\s+(\d+)\)", clean) |
| if not orchestrator_retry_match: |
| orchestrator_retry_match = re.search(r"\[RETRY(\d+)\]", clean) |
|
|
| |
| if not has_business_retry and not orchestrator_retry_match: |
| return {"is_retry": False} |
|
|
| |
| if orchestrator_retry_match: |
| retry_type = "orchestrator" |
| retry_number = int(orchestrator_retry_match.group(1)) |
| else: |
| retry_type = "business_logic" |
| retry_number = 0 |
|
|
| |
| node_match = re.match( |
| r"(?:❌\s*)?\[(SPAN|Chain|AGENT)\]\s+([^\[\]]+?)(?:\s+\[.*)?$", |
| clean, |
| ) |
| if not node_match: |
| return { |
| "is_retry": True, |
| "retry_type": retry_type, |
| "retry_number": retry_number, |
| "node_type": "Unknown", |
| "node_name": "Unknown", |
| "batch_info": "", |
| } |
|
|
| node_type = node_match.group(1) |
| node_name = node_match.group(2).strip() |
|
|
| |
| if node_type == "SPAN" and "a2a_call_chapter_writer_" in node_name: |
| |
| chapter_match = re.search(r"a2a_call_chapter_writer_\(([^)]+)\)", node_name) |
| if chapter_match: |
| chapter_title = chapter_match.group(1) |
| batch_info = f"Chapter: {chapter_title}" |
| else: |
| batch_info = "" |
| |
| node_name = re.sub( |
| r"a2a_call_chapter_writer_\([^)]+\)", "a2a_call_chapter_writer_*", node_name |
| ) |
| else: |
| |
| batch_match = re.search(r"📚BATCH(\d+)", clean) |
| batch_info = f"BATCH{batch_match.group(1)}" if batch_match else "" |
|
|
| |
| chapter_match = re.search(r"\(([^)]+)\)\s*$", clean) |
| if chapter_match: |
| chapter_title = chapter_match.group(1) |
| batch_info = ( |
| f"{batch_info} ({chapter_title})" if batch_info else chapter_title |
| ) |
|
|
| return { |
| "is_retry": True, |
| "retry_type": retry_type, |
| "retry_number": retry_number, |
| "node_type": node_type, |
| "node_name": node_name, |
| "batch_info": batch_info, |
| } |
|
|
|
|
| def analyze_session(md_file: str) -> dict: |
| """Analyze one session's execution_path.md. |
| |
| Returns: |
| { |
| 'has_error': bool, |
| 'has_retry': bool, |
| 'has_orchestrator_retry': bool, |
| 'has_business_retry': bool, |
| 'max_retry_number': int, |
| 'total_orchestrator_retries': int, |
| 'total_business_retries': int, |
| 'errors': [{'node_type': str, 'node_name': str, 'error_msg': str}, ...], |
| 'retries': [{ |
| 'retry_type': str, |
| 'retry_number': int, |
| 'node_type': str, |
| 'node_name': str, |
| 'batch_info': 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_type": retry_info["retry_type"], |
| "retry_number": retry_info["retry_number"], |
| "node_type": retry_info["node_type"], |
| "node_name": retry_info["node_name"], |
| "batch_info": retry_info["batch_info"], |
| } |
| ) |
|
|
| |
| orchestrator_retries = [r for r in retries if r["retry_type"] == "orchestrator"] |
| business_retries = [r for r in retries if r["retry_type"] == "business_logic"] |
|
|
| max_retry = ( |
| max([r["retry_number"] for r in orchestrator_retries]) |
| if orchestrator_retries |
| else 0 |
| ) |
|
|
| return { |
| "has_error": len(errors) > 0, |
| "has_retry": len(retries) > 0, |
| "has_orchestrator_retry": len(orchestrator_retries) > 0, |
| "has_business_retry": len(business_retries) > 0, |
| "max_retry_number": max_retry, |
| "total_orchestrator_retries": len(orchestrator_retries), |
| "total_business_retries": len(business_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, |
| 'sessions_with_orchestrator_retry': int, |
| 'sessions_with_business_retry': int, |
| 'total_orchestrator_retry_attempts': int, |
| 'total_business_retry_attempts': int, |
| 'error_by_agent': {agent_name: count}, |
| 'error_types': {error_msg: count}, |
| 'max_retry_number': int, |
| 'business_retry_chapters': {chapter_info: count}, |
| '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, |
| "sessions_with_orchestrator_retry": 0, |
| "sessions_with_business_retry": 0, |
| "sessions_with_only_orchestrator_retry": 0, |
| "sessions_with_only_business_retry": 0, |
| "sessions_with_both_retries": 0, |
| "total_orchestrator_retry_attempts": 0, |
| "total_business_retry_attempts": 0, |
| "error_by_agent": defaultdict(int), |
| "error_by_node_type": defaultdict(int), |
| "error_types": defaultdict(int), |
| "max_retry_number": 0, |
| "business_retry_chapters": defaultdict(int), |
| "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 |
|
|
| if analysis["has_orchestrator_retry"]: |
| stats["sessions_with_orchestrator_retry"] += 1 |
| stats["total_orchestrator_retry_attempts"] += analysis[ |
| "total_orchestrator_retries" |
| ] |
| stats["max_retry_number"] = max( |
| stats["max_retry_number"], analysis["max_retry_number"] |
| ) |
|
|
| if analysis["has_business_retry"]: |
| stats["sessions_with_business_retry"] += 1 |
| stats["total_business_retry_attempts"] += analysis["total_business_retries"] |
|
|
| |
| if analysis["has_orchestrator_retry"] and not analysis["has_business_retry"]: |
| stats["sessions_with_only_orchestrator_retry"] += 1 |
| elif analysis["has_business_retry"] and not analysis["has_orchestrator_retry"]: |
| stats["sessions_with_only_business_retry"] += 1 |
| elif analysis["has_orchestrator_retry"] and analysis["has_business_retry"]: |
| stats["sessions_with_both_retries"] += 1 |
|
|
| |
| 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 |
|
|
| |
| for retry in analysis["retries"]: |
| if retry["retry_type"] == "business_logic" and retry["batch_info"]: |
| stats["business_retry_chapters"][retry["batch_info"]] += 1 |
|
|
| |
| stats["session_details"].append( |
| { |
| "session": session_dir.name, |
| "has_error": analysis["has_error"], |
| "has_retry": analysis["has_retry"], |
| "has_orchestrator_retry": analysis["has_orchestrator_retry"], |
| "has_business_retry": analysis["has_business_retry"], |
| "orchestrator_retry_count": analysis["total_orchestrator_retries"], |
| "business_retry_count": analysis["total_business_retries"], |
| "errors": analysis["errors"], |
| "retries": analysis["retries"], |
| } |
| ) |
|
|
| |
| total = stats["total_sessions"] |
| stats["retry_rate"] = ( |
| (stats["sessions_with_retry"] / total * 100) if total > 0 else 0 |
| ) |
| stats["orchestrator_retry_rate"] = ( |
| (stats["sessions_with_orchestrator_retry"] / total * 100) if total > 0 else 0 |
| ) |
| stats["business_retry_rate"] = ( |
| (stats["sessions_with_business_retry"] / total * 100) if total > 0 else 0 |
| ) |
| stats["error_rate"] = ( |
| (stats["sessions_with_error"] / total * 100) if total > 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"]) |
| stats["business_retry_chapters"] = dict(stats["business_retry_chapters"]) |
|
|
| return stats |
|
|
|
|
| def print_summary(all_stats): |
| """Print a summary.""" |
| print("\n" + "=" * 120) |
| print(f"RETRY Pattern Analysis Summary - {PROJECT_NAME}") |
| print("=" * 120 + "\n") |
|
|
| |
| print("## Per-model summary\n") |
| header = f"{'Model':<30} {'Total':<10} {'Error%':<10} {'Retry%':<10} {'OrchRetry%':<12} {'BizRetry%':<12} {'OrchCnt':<12} {'BizCnt':<12}" |
| print(header) |
| print("-" * 120) |
|
|
| for stats in all_stats: |
| if stats: |
| print( |
| f"{stats['model']:<30} {stats['total_sessions']:<10} " |
| f"{stats['error_rate']:>8.1f}% {stats['retry_rate']:>8.1f}% " |
| f"{stats['orchestrator_retry_rate']:>10.1f}% {stats['business_retry_rate']:>10.1f}% " |
| f"{stats['total_orchestrator_retry_attempts']:<12} {stats['total_business_retry_attempts']:<12}" |
| ) |
|
|
| print("\n" + "=" * 120) |
|
|
| |
| for stats in all_stats: |
| if not stats: |
| continue |
|
|
| print(f"\n### 📊 {stats['model']}\n") |
| print(f"- **Total sessions**: {stats['total_sessions']}") |
| print( |
| f"- **Sessions with errors**: {stats['sessions_with_error']} ({stats['error_rate']:.1f}%)" |
| ) |
| print( |
| f"- **Sessions with retries**: {stats['sessions_with_retry']} ({stats['retry_rate']:.1f}%)" |
| ) |
| print( |
| f" - OrchestratorRETRY: {stats['sessions_with_orchestrator_retry']} ({stats['orchestrator_retry_rate']:.1f}%) " |
| f"[Only orch: {stats['sessions_with_only_orchestrator_retry']}]" |
| ) |
| print( |
| f" - BUSINESS-RETRY: {stats['sessions_with_business_retry']} ({stats['business_retry_rate']:.1f}%) " |
| f"[Only business: {stats['sessions_with_only_business_retry']}]" |
| ) |
| print(f" - Both: {stats['sessions_with_both_retries']}") |
| print(f"- **Total retries**:") |
| print(f" - OrchestratorRETRY: {stats['total_orchestrator_retry_attempts']}") |
| print(f" - BUSINESS-RETRY: {stats['total_business_retry_attempts']}") |
| print(f"- **Max retry number**: {stats['max_retry_number']}") |
|
|
| if stats["error_by_agent"]: |
| print(f"\n**Agents with errors**:") |
| for agent, count in sorted( |
| stats["error_by_agent"].items(), key=lambda x: x[1], reverse=True |
| )[:5]: |
| print(f" - {agent}: {count}") |
|
|
| if stats["business_retry_chapters"]: |
| print(f"\n**Chapters with BUSINESS-RETRY (top 10)**:") |
| for chapter, count in sorted( |
| stats["business_retry_chapters"].items(), |
| key=lambda x: x[1], |
| reverse=True, |
| )[:10]: |
| print(f" - [{count}] {chapter}") |
|
|
| if stats["error_types"]: |
| print(f"\n**Error types (top 3)**:") |
| for error_type, count in sorted( |
| stats["error_types"].items(), key=lambda x: x[1], reverse=True |
| )[:3]: |
| print(f" - [{count}] {error_type}") |
|
|
| print("\n" + "-" * 120) |
|
|
|
|
| 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✅ Saved detailed JSON: {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(%)", |
| "Orchestrator_Retry_Sessions", |
| "Orchestrator_Retry_Rate(%)", |
| "Only_Orchestrator_Retry_Sessions", |
| "Business_Retry_Sessions", |
| "Business_Retry_Rate(%)", |
| "Only_Business_Retry_Sessions", |
| "Both_Retries_Sessions", |
| "Total_Orchestrator_Retries", |
| "Total_Business_Retries", |
| "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["sessions_with_orchestrator_retry"], |
| f"{stats['orchestrator_retry_rate']:.2f}", |
| stats["sessions_with_only_orchestrator_retry"], |
| stats["sessions_with_business_retry"], |
| f"{stats['business_retry_rate']:.2f}", |
| stats["sessions_with_only_business_retry"], |
| stats["sessions_with_both_retries"], |
| stats["total_orchestrator_retry_attempts"], |
| stats["total_business_retry_attempts"], |
| stats["max_retry_number"], |
| ] |
| ) |
|
|
| print(f"✅ Saved CSV summary: {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"✅ Saved error location stats (by agent): {error_csv_file}") |
|
|
| |
| chapter_csv_file = output_dir / "business_retry_chapters.csv" |
| with open(chapter_csv_file, "w", newline="", encoding="utf-8") as f: |
| writer = csv.writer(f) |
| writer.writerow(["Model", "Chapter_Info", "Retry_Count"]) |
|
|
| for stats in all_stats: |
| if stats and stats["business_retry_chapters"]: |
| for chapter, count in sorted( |
| stats["business_retry_chapters"].items(), |
| key=lambda x: x[1], |
| reverse=True, |
| ): |
| writer.writerow([stats["model"], chapter, count]) |
|
|
| print(f"✅ Saved BUSINESS-RETRY chapter stats: {chapter_csv_file}") |
|
|
|
|
| if __name__ == "__main__": |
| print(f"Starting RETRY pattern analysis - {PROJECT_NAME}...") |
| print("Retry types:") |
| print(" 1. OrchestratorRETRY: (retry N) or [RETRYN]") |
| print(" 2. BUSINESS-RETRY: [BUSINESS-RETRY]\n") |
| print("A2A notes:") |
| print(" - Additional SPAN layers: a2a_call_*, *_server_execution") |
| print( |
| " - Chapter SPAN names may include titles: a2a_call_chapter_writer_(chapter_title)\n" |
| ) |
|
|
| all_stats = [] |
| for model in MODELS: |
| print(f"\n📊 Analyzing model: {model}") |
| stats = collect_model_stats(model) |
| if stats: |
| all_stats.append(stats) |
| print( |
| f" ✅ Done: {stats['total_sessions']} sessions, " |
| f"{stats['sessions_with_error']} errors, " |
| f"{stats['sessions_with_orchestrator_retry']} orch-retries, " |
| f"{stats['sessions_with_business_retry']} business-retries" |
| ) |
| else: |
| print(f" ⚠️ Skipped (directory not found)") |
|
|
| print_summary(all_stats) |
| save_results(all_stats) |
|
|
| print("\n" + "=" * 120) |
| print("✅ Analysis completed!") |
| print("=" * 120) |
|
|