| |
| """ |
| Performance Breakdown Analysis Script |
| |
| This script analyzes execution_path.md files from different models and tasks, |
| extracting time and token statistics grouped by task, architecture, model, and agent. |
| """ |
|
|
| import os |
| import re |
| import csv |
| import json |
| import numpy as np |
| from pathlib import Path |
| from collections import defaultdict |
| from typing import Dict, List, Tuple, Optional |
| import logging |
|
|
| |
| logging.basicConfig( |
| level=logging.INFO, |
| format="%(asctime)s - %(levelname)s - %(message)s", |
| handlers=[logging.StreamHandler()], |
| ) |
| logger = logging.getLogger(__name__) |
|
|
|
|
| class ExecutionPathParser: |
| """Parser for execution_path.md files""" |
|
|
| def __init__(self, file_path: str): |
| self.file_path = file_path |
| self.model = None |
| self.task = None |
| self.architecture = None |
| self.total_time = None |
| self.total_tokens = { |
| "input": 0, |
| "output": 0, |
| "reasoning": 0, |
| "result": 0, |
| "total": 0, |
| } |
| self.agent_stats = defaultdict( |
| lambda: { |
| "time": [], |
| "tokens": { |
| "input": [], |
| "output": [], |
| "reasoning": [], |
| "result": [], |
| "total": [], |
| }, |
| } |
| ) |
|
|
| def extract_metadata_from_path(self): |
| """Extract model, task, and architecture from file path""" |
| try: |
| parts = Path(self.file_path).parts |
| |
| results_idx = parts.index("RESULTS") |
|
|
| |
| self.model = parts[results_idx + 1] |
|
|
| |
| task_full = parts[results_idx + 2] |
|
|
| |
| if "-MCP" in task_full: |
| self.architecture = "MCP" |
| self.task = task_full.replace("-MCP", "") |
| elif "-A2A_mix" in task_full: |
| self.architecture = "A2A_mix" |
| self.task = task_full.replace("-A2A_mix", "") |
| elif "-A2A" in task_full: |
| self.architecture = "A2A" |
| self.task = task_full.replace("-A2A", "") |
| else: |
| |
| self.task = task_full |
| self.architecture = "Unknown" |
|
|
| logger.debug( |
| f"Extracted: model={self.model}, task={self.task}, arch={self.architecture}" |
| ) |
| return True |
| except Exception as e: |
| logger.error(f"Failed to extract metadata from path {self.file_path}: {e}") |
| return False |
|
|
| def parse_tokens_time(self, line: str) -> Tuple[Optional[Dict], Optional[float]]: |
| """ |
| Parse tokens and time from a line like: |
| [SPAN] name [∑ tokens: (input→output [REASONING:reasoning, OUTPUT:result], total: total), time: 123.45s] |
| """ |
| tokens_dict = None |
| time_val = None |
|
|
| |
| token_pattern = r"\[∑ tokens: \((\d+)→(\d+) \[REASONING:(\d+), OUTPUT:(\d+)\], total: (\d+)\)" |
| token_match = re.search(token_pattern, line) |
| if token_match: |
| tokens_dict = { |
| "input": int(token_match.group(1)), |
| "output": int(token_match.group(2)), |
| "reasoning": int(token_match.group(3)), |
| "result": int(token_match.group(4)), |
| "total": int(token_match.group(5)), |
| } |
| else: |
| |
| token_pattern2 = ( |
| r"\((\d+)→(\d+) \[REASONING:(\d+), OUTPUT:(\d+)\], total: (\d+)\)" |
| ) |
| token_match2 = re.search(token_pattern2, line) |
| if token_match2: |
| tokens_dict = { |
| "input": int(token_match2.group(1)), |
| "output": int(token_match2.group(2)), |
| "reasoning": int(token_match2.group(3)), |
| "result": int(token_match2.group(4)), |
| "total": int(token_match2.group(5)), |
| } |
|
|
| |
| time_pattern = r"time: ([\d.]+)s\]" |
| time_match = re.search(time_pattern, line) |
| if time_match: |
| time_val = float(time_match.group(1)) |
|
|
| return tokens_dict, time_val |
|
|
| def extract_agent_name(self, line: str) -> Optional[str]: |
| """Extract agent name from a line""" |
| |
| agent_pattern = r"\[AGENT\] (.+?)\._execute_core" |
| match = re.search(agent_pattern, line) |
| if match: |
| return match.group(1) |
|
|
| |
| agent_pattern2 = r"\[AGENT\] invoke_agent (\w+)" |
| match2 = re.search(agent_pattern2, line) |
| if match2: |
| return match2.group(1) |
|
|
| |
| agent_pattern3 = r"\[AGENT\] (?:create_agent )?(\w+)" |
| match3 = re.search(agent_pattern3, line) |
| if match3 and "tokens:" in line: |
| return match3.group(1) |
|
|
| return None |
|
|
| def parse_file(self) -> bool: |
| """Parse the execution_path.md file""" |
| try: |
| if not self.extract_metadata_from_path(): |
| return False |
|
|
| with open(self.file_path, "r", encoding="utf-8") as f: |
| content = f.read() |
|
|
| |
| if self.architecture == "Unknown": |
| if "A2A_mix" in content: |
| self.architecture = "A2A_mix" |
| elif ( |
| "Project Type**: A2A" in content or "Project Type**: A2A" in content |
| ): |
| self.architecture = "A2A" |
| elif "MCP" in content: |
| self.architecture = "MCP" |
|
|
| |
| tree_start = content.find("## Execution Path Tree") |
| if tree_start == -1: |
| logger.warning(f"No execution tree found in {self.file_path}") |
| return False |
|
|
| tree_section = content[tree_start:] |
| lines = tree_section.split("\n") |
|
|
| |
| |
| for line in lines: |
| |
| clean_line = line.replace("❌ ", "") |
| if ( |
| "[SPAN]" in clean_line or "[Chain]" in clean_line |
| ) and "time:" in clean_line: |
| tokens, time = self.parse_tokens_time(clean_line) |
| if time and self.total_time is None: |
| self.total_time = time |
| if tokens: |
| self.total_tokens = tokens |
| break |
|
|
| |
| if self.total_time is None: |
| for line in lines: |
| clean_line = line.replace("❌ ", "") |
| if "time:" in clean_line and "[∑" in clean_line: |
| tokens, time = self.parse_tokens_time(clean_line) |
| if time: |
| self.total_time = time |
| logger.info( |
| f"Extracted time from error/alternative node: {self.file_path}" |
| ) |
| if tokens: |
| self.total_tokens = tokens |
| break |
|
|
| |
| |
| for line in lines: |
| if "[AGENT]" in line: |
| |
| clean_line = line.replace("❌ ", "") |
| agent_name = self.extract_agent_name(clean_line) |
| tokens, time = self.parse_tokens_time(clean_line) |
|
|
| if agent_name: |
| if time is not None: |
| self.agent_stats[agent_name]["time"].append(time) |
| if tokens: |
| for key in [ |
| "input", |
| "output", |
| "reasoning", |
| "result", |
| "total", |
| ]: |
| self.agent_stats[agent_name]["tokens"][key].append( |
| tokens[key] |
| ) |
|
|
| |
| if self.total_time is None: |
| |
| if not self.agent_stats: |
| logger.warning( |
| f"Could not extract total time or agent stats from {self.file_path}" |
| ) |
| return False |
| else: |
| logger.warning( |
| f"Could not extract total time, but found agent stats in {self.file_path}" |
| ) |
| |
| all_agent_times = [] |
| for agent_data in self.agent_stats.values(): |
| all_agent_times.extend(agent_data["time"]) |
| if all_agent_times: |
| self.total_time = sum(all_agent_times) |
| logger.info( |
| f"Approximated total time from agent stats: {self.total_time}s" |
| ) |
|
|
| logger.info( |
| f"Successfully parsed {self.file_path}: {self.model}/{self.task}/{self.architecture}, time={self.total_time}s" |
| ) |
| return True |
|
|
| except Exception as e: |
| logger.error(f"Failed to parse {self.file_path}: {e}", exc_info=True) |
| return False |
|
|
|
|
| class PerformanceAnalyzer: |
| """Analyzer for performance statistics""" |
|
|
| def __init__(self, results_dir: str): |
| self.results_dir = results_dir |
| self.data = [] |
| self.failed_files = [] |
|
|
| def find_all_execution_paths(self) -> List[str]: |
| """Find all execution_path.md files""" |
| execution_paths = [] |
| for root, dirs, files in os.walk(self.results_dir): |
| |
| if "RQ-" in root: |
| continue |
| if "execution_path.md" in files: |
| execution_paths.append(os.path.join(root, "execution_path.md")) |
|
|
| logger.info(f"Found {len(execution_paths)} execution_path.md files") |
| return execution_paths |
|
|
| def parse_all_files(self): |
| """Parse all execution path files""" |
| files = self.find_all_execution_paths() |
|
|
| for file_path in files: |
| parser = ExecutionPathParser(file_path) |
| if parser.parse_file(): |
| self.data.append(parser) |
| else: |
| self.failed_files.append(file_path) |
|
|
| logger.info( |
| f"Successfully parsed {len(self.data)} files, {len(self.failed_files)} failed" |
| ) |
|
|
| def calculate_statistics(self, values: List[float]) -> Dict[str, float]: |
| """Calculate mean, P90, P99, CV (for time metrics)""" |
| if not values: |
| return {"mean": 0, "p90": 0, "p99": 0, "cv": 0} |
|
|
| mean_val = np.mean(values) |
| std_val = np.std(values, ddof=1) if len(values) > 1 else 0 |
| cv = (std_val / mean_val * 100) if mean_val > 0 else 0 |
|
|
| return { |
| "mean": mean_val, |
| "p90": np.percentile(values, 90), |
| "p99": np.percentile(values, 99), |
| "cv": cv, |
| } |
|
|
| def calculate_mean_and_cv(self, values: List[float]) -> Dict[str, float]: |
| """Calculate mean and CV (for token metrics)""" |
| if not values: |
| return {"mean": 0, "cv": 0} |
|
|
| mean_val = np.mean(values) |
| std_val = np.std(values, ddof=1) if len(values) > 1 else 0 |
| cv = (std_val / mean_val * 100) if mean_val > 0 else 0 |
|
|
| return {"mean": mean_val, "cv": cv} |
|
|
| def generate_task_time_report(self, output_file: str): |
| """ |
| Generate CSV report for task completion time grouped by task, architecture, and model |
| """ |
| |
| grouped = defaultdict(list) |
| for parser in self.data: |
| key = (parser.task, parser.architecture, parser.model) |
| if parser.total_time: |
| grouped[key].append(parser.total_time) |
|
|
| |
| results = [] |
| for (task, arch, model), times in grouped.items(): |
| stats = self.calculate_statistics(times) |
| |
| throughput = 3600 / stats["mean"] if stats["mean"] > 0 else 0 |
| results.append( |
| { |
| "task": task, |
| "architecture": arch, |
| "model": model, |
| "count": len(times), |
| "mean_time": stats["mean"], |
| "p90_time": stats["p90"], |
| "p99_time": stats["p99"], |
| "cv_time": stats["cv"], |
| "throughput_tasks_per_hour": throughput, |
| } |
| ) |
|
|
| |
| results.sort(key=lambda x: (x["task"], x["architecture"], x["model"])) |
|
|
| |
| with open(output_file, "w", newline="", encoding="utf-8") as f: |
| writer = csv.DictWriter( |
| f, |
| fieldnames=[ |
| "task", |
| "architecture", |
| "model", |
| "count", |
| "mean_time", |
| "p90_time", |
| "p99_time", |
| "cv_time", |
| "throughput_tasks_per_hour", |
| ], |
| ) |
| writer.writeheader() |
| writer.writerows(results) |
|
|
| logger.info(f"Task time report written to {output_file}") |
|
|
| def generate_agent_time_report(self, output_file: str): |
| """ |
| Generate CSV report for agent time grouped by task, architecture, agent, and model |
| """ |
| |
| grouped = defaultdict(list) |
| for parser in self.data: |
| for agent_name, stats in parser.agent_stats.items(): |
| if stats["time"]: |
| key = (parser.task, parser.architecture, agent_name, parser.model) |
| grouped[key].extend(stats["time"]) |
|
|
| |
| results = [] |
| for (task, arch, agent, model), times in grouped.items(): |
| stats = self.calculate_statistics(times) |
| results.append( |
| { |
| "task": task, |
| "architecture": arch, |
| "agent": agent, |
| "model": model, |
| "count": len(times), |
| "mean_time": stats["mean"], |
| "p90_time": stats["p90"], |
| "p99_time": stats["p99"], |
| "cv_time": stats["cv"], |
| } |
| ) |
|
|
| |
| results.sort( |
| key=lambda x: (x["task"], x["architecture"], x["agent"], x["model"]) |
| ) |
|
|
| |
| with open(output_file, "w", newline="", encoding="utf-8") as f: |
| writer = csv.DictWriter( |
| f, |
| fieldnames=[ |
| "task", |
| "architecture", |
| "agent", |
| "model", |
| "count", |
| "mean_time", |
| "p90_time", |
| "p99_time", |
| "cv_time", |
| ], |
| ) |
| writer.writeheader() |
| writer.writerows(results) |
|
|
| logger.info(f"Agent time report written to {output_file}") |
|
|
| def generate_task_token_report(self, output_file: str): |
| """ |
| Generate CSV report for task token usage grouped by task, architecture, and model |
| """ |
| |
| grouped = defaultdict( |
| lambda: { |
| "input": [], |
| "output": [], |
| "reasoning": [], |
| "result": [], |
| "total": [], |
| } |
| ) |
|
|
| for parser in self.data: |
| key = (parser.task, parser.architecture, parser.model) |
| if parser.total_tokens["total"] > 0: |
| for token_type in ["input", "output", "reasoning", "result", "total"]: |
| grouped[key][token_type].append(parser.total_tokens[token_type]) |
|
|
| |
| results = [] |
| for (task, arch, model), token_data in grouped.items(): |
| if not token_data["total"]: |
| continue |
|
|
| result = { |
| "task": task, |
| "architecture": arch, |
| "model": model, |
| "count": len(token_data["total"]), |
| } |
|
|
| |
| for token_type in ["input", "output", "reasoning", "result", "total"]: |
| token_stats = self.calculate_mean_and_cv(token_data[token_type]) |
| result[f"mean_{token_type}"] = token_stats["mean"] |
| result[f"cv_{token_type}"] = token_stats["cv"] |
|
|
| results.append(result) |
|
|
| |
| results.sort(key=lambda x: (x["task"], x["architecture"], x["model"])) |
|
|
| |
| fieldnames = ["task", "architecture", "model", "count"] |
| for token_type in ["input", "output", "reasoning", "result", "total"]: |
| fieldnames.extend([f"mean_{token_type}", f"cv_{token_type}"]) |
|
|
| with open(output_file, "w", newline="", encoding="utf-8") as f: |
| writer = csv.DictWriter(f, fieldnames=fieldnames) |
| writer.writeheader() |
| writer.writerows(results) |
|
|
| logger.info(f"Task token report written to {output_file}") |
|
|
| def generate_agent_token_report(self, output_file: str): |
| """ |
| Generate CSV report for agent token usage grouped by task, architecture, agent, and model |
| """ |
| |
| grouped = defaultdict( |
| lambda: { |
| "input": [], |
| "output": [], |
| "reasoning": [], |
| "result": [], |
| "total": [], |
| } |
| ) |
|
|
| for parser in self.data: |
| for agent_name, stats in parser.agent_stats.items(): |
| if stats["tokens"]["total"]: |
| key = (parser.task, parser.architecture, agent_name, parser.model) |
| for token_type in [ |
| "input", |
| "output", |
| "reasoning", |
| "result", |
| "total", |
| ]: |
| grouped[key][token_type].extend(stats["tokens"][token_type]) |
|
|
| |
| results = [] |
| for (task, arch, agent, model), token_data in grouped.items(): |
| if not token_data["total"]: |
| continue |
|
|
| result = { |
| "task": task, |
| "architecture": arch, |
| "agent": agent, |
| "model": model, |
| "count": len(token_data["total"]), |
| } |
|
|
| |
| for token_type in ["input", "output", "reasoning", "result", "total"]: |
| token_stats = self.calculate_mean_and_cv(token_data[token_type]) |
| result[f"mean_{token_type}"] = token_stats["mean"] |
| result[f"cv_{token_type}"] = token_stats["cv"] |
|
|
| results.append(result) |
|
|
| |
| results.sort( |
| key=lambda x: (x["task"], x["architecture"], x["agent"], x["model"]) |
| ) |
|
|
| |
| fieldnames = ["task", "architecture", "agent", "model", "count"] |
| for token_type in ["input", "output", "reasoning", "result", "total"]: |
| fieldnames.extend([f"mean_{token_type}", f"cv_{token_type}"]) |
|
|
| with open(output_file, "w", newline="", encoding="utf-8") as f: |
| writer = csv.DictWriter(f, fieldnames=fieldnames) |
| writer.writeheader() |
| writer.writerows(results) |
|
|
| logger.info(f"Agent token report written to {output_file}") |
|
|
| def check_has_retry(self, parser: ExecutionPathParser) -> bool: |
| """ |
| Check if execution_path.md contains retry markers like [RETRY1], [BUSINESS-RETRY] etc. |
| Returns True if retry markers found, False otherwise |
| """ |
| try: |
| with open(parser.file_path, "r", encoding="utf-8") as f: |
| content = f.read() |
| |
| |
| retry_patterns = [ |
| r"\[RETRY\d+\]", |
| r"\[.*?RETRY.*?\]", |
| ] |
|
|
| for pattern in retry_patterns: |
| if re.search(pattern, content): |
| return True |
| return False |
| except Exception as e: |
| logger.error(f"Error checking retry markers for {parser.file_path}: {e}") |
| return False |
|
|
| def check_task_success(self, parser: ExecutionPathParser) -> str: |
| """ |
| Check if a task execution was successful based on task-specific criteria |
| Returns 'success' or 'fail' |
| """ |
| try: |
| |
| session_dir = Path(parser.file_path).parent |
| task = parser.task |
|
|
| if task.endswith("-H_A2A"): |
| task = task[: -len("-H_A2A")] |
|
|
| task_aliases = { |
| "BookWriter": "write_a_book_with_flows", |
| "SQLAssistant": "SQL_assistant", |
| "SocialMediaManager": "self_evaluation_loop_flow", |
| "LandingPageGenerator": "landing_page_generator", |
| "RecruitmentAssistant": "intelligent_recruitment_platform", |
| "EmailResponder": "EmailResponder", |
| "GameBuilder": "GameBuilder", |
| "MarkdownValidator": "MarkdownValidator", |
| } |
| task = task_aliases.get(task, task) |
|
|
| |
| if task == "write_a_book_with_flows": |
| chapters_dir = session_dir / "chapters" |
| if chapters_dir.exists() and chapters_dir.is_dir(): |
| md_files = list(chapters_dir.glob("*.md")) |
| if len(md_files) >= 1: |
| return "success" |
| return "fail" |
|
|
| |
| elif task == "SQL_assistant": |
| with open(parser.file_path, "r", encoding="utf-8") as f: |
| content = f.read() |
| if re.search(r"\[Tool\]\s+get_database_schema", content): |
| return "success" |
| return "fail" |
|
|
| |
| elif task == "self_evaluation_loop_flow": |
| metadata_file = session_dir / "metadata.json" |
| if metadata_file.exists(): |
| with open(metadata_file, "r", encoding="utf-8") as f: |
| metadata = json.load(f) |
| if metadata.get("status") == "success": |
| return "success" |
| return "fail" |
|
|
| |
| elif task == "MarkdownValidator": |
| execution_info_file = session_dir / "execution_info.json" |
| if execution_info_file.exists(): |
| with open(execution_info_file, "r", encoding="utf-8") as f: |
| exec_info = json.load(f) |
| if exec_info.get("success", False): |
| return "success" |
| return "fail" |
|
|
| |
| elif task == "landing_page_generator": |
| html_validation_file = session_dir / "html_validation.json" |
| if html_validation_file.exists(): |
| with open(html_validation_file, "r", encoding="utf-8") as f: |
| validation = json.load(f) |
| if validation.get("file_exists", False): |
| return "success" |
| return "fail" |
|
|
| |
| elif task == "intelligent_recruitment_platform": |
| reports_dir = session_dir / "reports" |
| if reports_dir.exists() and reports_dir.is_dir(): |
| md_files = list(reports_dir.glob("*.md")) |
| if len(md_files) >= 2: |
| return "success" |
| return "fail" |
|
|
| |
| elif task == "GameBuilder": |
| validation_result_file = session_dir / "validation_result.json" |
| if validation_result_file.exists(): |
| with open(validation_result_file, "r", encoding="utf-8") as f: |
| validation = json.load(f) |
| if validation.get("validation_successful", False): |
| return "success" |
| return "fail" |
|
|
| |
| elif task == "EmailResponder": |
| execution_log_file = session_dir / "execution_log.json" |
| if execution_log_file.exists(): |
| with open(execution_log_file, "r", encoding="utf-8") as f: |
| exec_log = json.load(f) |
| if exec_log.get("success", False): |
| return "success" |
| return "fail" |
|
|
| |
| else: |
| logger.warning(f"Unknown task type for success check: {task}") |
| return "fail" |
|
|
| except Exception as e: |
| logger.error(f"Error checking task success for {parser.file_path}: {e}") |
| return "error" |
|
|
| def generate_task_token_details(self, output_file: str): |
| """ |
| Generate detailed CSV report with token usage for each individual execution_path.md file |
| """ |
| results = [] |
|
|
| for parser in self.data: |
| if parser.total_tokens["total"] > 0: |
| |
| status = self.check_task_success(parser) |
|
|
| |
| has_retry = self.check_has_retry(parser) |
|
|
| result = { |
| "file_path": parser.file_path, |
| "task": parser.task, |
| "architecture": parser.architecture, |
| "model": parser.model, |
| "status": status, |
| "with_retry": str( |
| has_retry |
| ).lower(), |
| "input_tokens": parser.total_tokens["input"], |
| "output_tokens": parser.total_tokens["output"], |
| "reasoning_tokens": parser.total_tokens["reasoning"], |
| "result_tokens": parser.total_tokens["result"], |
| "total_tokens": parser.total_tokens["total"], |
| } |
| results.append(result) |
|
|
| |
| results.sort( |
| key=lambda x: (x["task"], x["architecture"], x["model"], x["file_path"]) |
| ) |
|
|
| |
| with open(output_file, "w", newline="", encoding="utf-8") as f: |
| writer = csv.DictWriter( |
| f, |
| fieldnames=[ |
| "file_path", |
| "task", |
| "architecture", |
| "model", |
| "status", |
| "with_retry", |
| "input_tokens", |
| "output_tokens", |
| "reasoning_tokens", |
| "result_tokens", |
| "total_tokens", |
| ], |
| ) |
| writer.writeheader() |
| writer.writerows(results) |
|
|
| logger.info(f"Detailed task token report written to {output_file}") |
|
|
|
|
| def main(): |
| """Main execution function""" |
| |
| results_dir = "/Users/wzr/TOSEM-2025/RESULTS" |
| output_dir = "/Users/wzr/TOSEM-2025/RESULTS/RQ3/performance_reports" |
|
|
| |
| os.makedirs(output_dir, exist_ok=True) |
|
|
| |
| logger.info("Starting performance analysis...") |
| analyzer = PerformanceAnalyzer(results_dir) |
|
|
| |
| logger.info("Parsing execution path files...") |
| analyzer.parse_all_files() |
|
|
| |
| logger.info("Generating reports...") |
|
|
| |
| analyzer.generate_task_time_report( |
| os.path.join(output_dir, "task_time_statistics.csv") |
| ) |
| analyzer.generate_agent_time_report( |
| os.path.join(output_dir, "agent_time_statistics.csv") |
| ) |
|
|
| |
| analyzer.generate_task_token_report( |
| os.path.join(output_dir, "task_token_statistics.csv") |
| ) |
| analyzer.generate_agent_token_report( |
| os.path.join(output_dir, "agent_token_statistics.csv") |
| ) |
|
|
| |
| analyzer.generate_task_token_details( |
| os.path.join(output_dir, "task_token_statistics-DETAILS.csv") |
| ) |
|
|
| logger.info("Analysis complete!") |
| logger.info(f"Total files processed: {len(analyzer.data)}") |
| logger.info(f"Failed files: {len(analyzer.failed_files)}") |
| logger.info(f"Reports saved to: {output_dir}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|