File size: 30,715 Bytes
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
c4e7970
8c10cf2
 
c4e7970
8c10cf2
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4e7970
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c10cf2
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
c4e7970
8c10cf2
 
 
 
 
 
 
 
 
 
c4e7970
 
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
c4e7970
 
8c10cf2
c4e7970
 
8c10cf2
 
 
 
 
 
 
 
c4e7970
 
 
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
#!/usr/bin/env python3
"""
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

# Setup 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
            # Find RESULTS index
            results_idx = parts.index("RESULTS")

            # Model is the next directory after RESULTS
            self.model = parts[results_idx + 1]

            # Task name is the next directory
            task_full = parts[results_idx + 2]

            # Extract architecture from task name
            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:
                # Check in file content for architecture info
                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

        # Extract tokens
        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:
            # Try simpler pattern for LLM calls
            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)),
                }

        # Extract time
        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"""
        # Pattern for agent execution
        agent_pattern = r"\[AGENT\] (.+?)\._execute_core"
        match = re.search(agent_pattern, line)
        if match:
            return match.group(1)

        # Pattern for agent invocation
        agent_pattern2 = r"\[AGENT\] invoke_agent (\w+)"
        match2 = re.search(agent_pattern2, line)
        if match2:
            return match2.group(1)

        # Pattern for agent creation or general agent
        agent_pattern3 = r"\[AGENT\] (?:create_agent )?(\w+)"
        match3 = re.search(agent_pattern3, line)
        if match3 and "tokens:" in line:  # Only if it has token info
            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()

            # Check if architecture is still Unknown, try to extract from content
            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"

            # Find the execution tree section
            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")

            # Find the first line with total time (usually the root SPAN)
            # Improvement: support SPAN lines with an error marker prefix (❌)
            for line in lines:
                # Remove the error marker prefix to match correctly
                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 still not found, try any line that contains time information
            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

            # Parse all agent lines
            # Improvement: support agent lines with an error marker prefix
            for line in lines:
                if "[AGENT]" in line:
                    # Remove the error marker to parse correctly
                    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]
                                )

            # Improvement: even if total time cannot be extracted, treat it as partially successful if agent stats exist
            if self.total_time is None:
                # Check whether we at least have agent data
                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}"
                    )
                    # Use the sum of agent times as an approximate total time
                    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):
            # Skip the RQ- directories
            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
        """
        # Group data by task, architecture, 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)

        # Calculate statistics
        results = []
        for (task, arch, model), times in grouped.items():
            stats = self.calculate_statistics(times)
            # Calculate throughput: tasks per hour
            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,
                }
            )

        # Sort by task, architecture, model
        results.sort(key=lambda x: (x["task"], x["architecture"], x["model"]))

        # Write to CSV
        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
        """
        # Group data by task, architecture, agent, 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"])

        # Calculate statistics
        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"],
                }
            )

        # Sort by task, architecture, agent, model
        results.sort(
            key=lambda x: (x["task"], x["architecture"], x["agent"], x["model"])
        )

        # Write to CSV
        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
        """
        # Group data by task, architecture, 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])

        # Calculate statistics
        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"]),
            }

            # Token statistics: mean and CV
            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)

        # Sort by task, architecture, model
        results.sort(key=lambda x: (x["task"], x["architecture"], x["model"]))

        # Write to CSV
        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
        """
        # Group data by task, architecture, agent, 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])

        # Calculate statistics
        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"]),
            }

            # Token statistics: mean and CV
            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)

        # Sort by task, architecture, agent, model
        results.sort(
            key=lambda x: (x["task"], x["architecture"], x["agent"], x["model"])
        )

        # Write to CSV
        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()
                # Pattern to match retry markers: [RETRYX], [BUSINESS-RETRY], etc.
                # Matches: [RETRY<number>] or [<any_text>RETRY<any_text>]
                retry_patterns = [
                    r"\[RETRY\d+\]",  # [RETRY1], [RETRY2], etc.
                    r"\[.*?RETRY.*?\]",  # [BUSINESS-RETRY], [XXXRETRYXXX], etc.
                ]

                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:
            # Get the directory containing execution_path.md
            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)

            # 1. write_a_book_with_flows
            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"

            # 2. SQL_assistant
            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"

            # 3. self_evaluation_loop_flow
            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"

            # 4. MarkdownValidator
            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"

            # 5. landing_page_generator
            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"

            # 6. intelligent_recruitment_platform
            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"

            # 7. GameBuilder
            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"

            # 8. EmailResponder
            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"

            # Unknown task
            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:
                # Check task success status
                status = self.check_task_success(parser)

                # Check if execution contains retry markers
                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(),  # Convert to 'true' or 'false'
                    "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)

        # Sort by task, architecture, model, and file path
        results.sort(
            key=lambda x: (x["task"], x["architecture"], x["model"], x["file_path"])
        )

        # Write to CSV
        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"""
    # Set paths
    results_dir = "/Users/wzr/TOSEM-2025/RESULTS"
    output_dir = "/Users/wzr/TOSEM-2025/RESULTS/RQ3/performance_reports"

    # Create output directory if it doesn't exist
    os.makedirs(output_dir, exist_ok=True)

    # Initialize analyzer
    logger.info("Starting performance analysis...")
    analyzer = PerformanceAnalyzer(results_dir)

    # Parse all files
    logger.info("Parsing execution path files...")
    analyzer.parse_all_files()

    # Generate reports
    logger.info("Generating reports...")

    # Time 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")
    )

    # Token reports
    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")
    )

    # Detailed token report (per file)
    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()