File size: 33,008 Bytes
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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
#!/usr/bin/env python3

import csv
import re
from pathlib import Path
from typing import Dict, List, Optional
from collections import defaultdict


class TraceNode:
    def __init__(
        self,
        node_type: str,
        name: str,
        time: Optional[float] = None,
        tokens: Optional[Dict[str, int]] = None,
        raw_line: str = "",
    ):
        self.type = node_type
        self.name = name
        self.time = time
        self.tokens = tokens or {}
        self.raw_line = raw_line
        self.children: List["TraceNode"] = []
        self.parent: Optional["TraceNode"] = None
        self.depth: int = 0
        self.in_mcp_subtree: bool = False

    def add_child(self, child: "TraceNode") -> None:
        child.parent = self
        self.children.append(child)


class ExecutionTreeParser:
    def __init__(self, md_file_path: str):
        self.file_path = Path(md_file_path)
        self.model: Optional[str] = None
        self.project: Optional[str] = None
        self.session_id: str = self.file_path.parent.name
        self.root: Optional[TraceNode] = None

    def _extract_metadata_from_path(self) -> None:
        parts = self.file_path.parts
        if "RESULTS" in parts:
            idx = parts.index("RESULTS")
            if idx + 2 < len(parts):
                self.model = parts[idx + 1]
                self.project = parts[idx + 2]

    @staticmethod
    def _parse_tokens(line: str) -> Optional[Dict[str, int]]:
        agg_pattern = r"\[∑ tokens: \((\d+)→(\d+) \[REASONING:(\d+), OUTPUT:(\d+)\], total: (\d+)\)"
        m = re.search(agg_pattern, line)
        if not m:
            llm_pattern = (
                r"\((\d+)→(\d+) \[REASONING:(\d+), OUTPUT:(\d+)\], total: (\d+)\)"
            )
            m = re.search(llm_pattern, line)
        if not m:
            return None
        return {
            "input": int(m.group(1)),
            "output": int(m.group(2)),
            "reasoning": int(m.group(3)),
            "result": int(m.group(4)),
            "total": int(m.group(5)),
        }

    @staticmethod
    def _parse_time(line: str) -> Optional[float]:
        m = re.search(r"time:\s*([\d.]+)s", line)
        if m:
            return float(m.group(1))
        m = re.search(r"∑\s*time:\s*([\d.]+)(ms|s)", line)
        if m:
            val = float(m.group(1))
            return val / 1000.0 if m.group(2) == "ms" else val
        m = re.search(r"\[([\d.]+)(ms|s)\]", line)
        if m:
            val = float(m.group(1))
            return val / 1000.0 if m.group(2) == "ms" else val
        return None

    @staticmethod
    def _clean_content_line(line: str) -> str:
        clean = re.sub(r"^[│├└─\s]+", "", line).strip()
        if not clean:
            return ""
        clean = re.sub(r"^❌\s+", "", clean)
        clean = re.sub(r"\s*\(retry\s+\d+\)", "", clean)
        clean = re.sub(r"\s*\[RETRY\d+\]", "", clean)
        clean = re.sub(r"\s*\[ERROR:[^\]]*\]", "", clean)
        return clean.strip()

    @staticmethod
    def _parse_node_from_content(line: str, raw_line: str) -> Optional[TraceNode]:
        if not line:
            return None
        if line.startswith("[Task Created]"):
            time_val = ExecutionTreeParser._parse_time(line)
            return TraceNode(
                "Task Created", "Task Created", time=time_val, raw_line=raw_line
            )
        if line.startswith("[Crew Created]"):
            time_val = ExecutionTreeParser._parse_time(line)
            return TraceNode(
                "Crew Created", "Crew Created", time=time_val, raw_line=raw_line
            )
        if line.startswith("[SPAN]"):
            m = re.match(r"\[SPAN\]\s+([^\[]+)", line)
            name = m.group(1).strip() if m else "SPAN"
            tokens = ExecutionTreeParser._parse_tokens(line)
            time_val = ExecutionTreeParser._parse_time(line)
            return TraceNode(
                "SPAN", name, time=time_val, tokens=tokens, raw_line=raw_line
            )
        if line.startswith("[Chain]"):
            m = re.match(r"\[Chain\]\s+([^\[]+)", line)
            name = m.group(1).strip() if m else "Chain"
            time_val = ExecutionTreeParser._parse_time(line)
            return TraceNode("Chain", name, time=time_val, raw_line=raw_line)
        if line.startswith("[AGENT]"):
            m = re.match(r"\[AGENT\]\s+(.+?)(?:\s+\[|$)", line)
            name = m.group(1).strip() if m else "AGENT"
            tokens = ExecutionTreeParser._parse_tokens(line)
            time_val = ExecutionTreeParser._parse_time(line)
            return TraceNode(
                "AGENT", name, time=time_val, tokens=tokens, raw_line=raw_line
            )
        if line.startswith("[Tool]"):
            m = re.match(r"\[Tool\]\s+([^\[]+?)(?:\s+\[|\s+@@@|$)", line)
            name = m.group(1).strip() if m else "Tool"
            time_val = ExecutionTreeParser._parse_time(line)
            return TraceNode("Tool", name, time=time_val, raw_line=raw_line)
        if line.startswith("[LLM]"):
            m = re.match(r"\[LLM\]\s+([^\(\[]+)", line)
            name = m.group(1).strip() if m else "LLM"
            tokens = ExecutionTreeParser._parse_tokens(line)
            time_val = ExecutionTreeParser._parse_time(line)
            return TraceNode(
                "LLM", name, time=time_val, tokens=tokens, raw_line=raw_line
            )
        return None

    def _mark_mcp_subtrees(self) -> None:
        if not self.root:
            return

        def dfs(node: TraceNode, in_mcp: bool) -> None:
            if node.type == "SPAN" and "mcp" in node.name:
                in_mcp = True
            node.in_mcp_subtree = in_mcp
            for ch in node.children:
                dfs(ch, in_mcp)

        dfs(self.root, False)

    def parse(self) -> Optional[TraceNode]:
        if not self.file_path.exists():
            return None
        text = self.file_path.read_text(encoding="utf-8")
        m = re.search(r"## Execution Path Tree.*?```\n(.*?)```", text, re.DOTALL)
        if not m:
            return None
        block = m.group(1)
        stack: List[TraceNode] = []
        self.root = None
        for raw in block.splitlines():
            if not raw.strip():
                continue
            pm = re.match(r"^([│├└─\s]*)", raw)
            prefix = pm.group(1) if pm else ""
            depth = len(prefix)
            clean = self._clean_content_line(raw)
            node = self._parse_node_from_content(clean, raw)
            if node is None:
                continue
            node.depth = depth
            while stack and stack[-1].depth >= depth:
                stack.pop()
            if stack:
                stack[-1].add_child(node)
            else:
                if self.root is None:
                    self.root = node
            stack.append(node)
        self._extract_metadata_from_path()
        self._mark_mcp_subtrees()
        return self.root


def iter_nodes(root: TraceNode):
    stack = [root]
    while stack:
        node = stack.pop()
        yield node
        for ch in reversed(node.children):
            stack.append(ch)


def compute_retry_time(root: TraceNode) -> float:
    """Sum time (seconds) of nodes marked as RETRY.

    Rules:
    - A node is considered a RETRY attempt if its raw_line contains "(retry N)" or "[RETRYN]".
    - Only nodes with time are counted; MCP subtrees are skipped.
    - Use the node's own time as the cost of that RETRY attempt (do not additionally sum its children).
    """

    total = 0.0
    retry_pattern = re.compile(r"\(retry\s+\d+\)|\[RETRY\d+\]")
    for node in iter_nodes(root):
        if node.in_mcp_subtree:
            continue
        if node.time is None:
            continue
        if retry_pattern.search(node.raw_line):
            total += node.time
    return total


def iter_subtree(root: TraceNode):
    """Iterate the subtree rooted at `root` (including `root`)."""

    stack = [root]
    while stack:
        node = stack.pop()
        yield node
        for ch in reversed(node.children):
            stack.append(ch)


def compute_llm_overhead_for_subtree(root: TraceNode) -> float:
    """Compute LLM time (seconds) within the given subtree, reusing the global LLM rules."""

    total = 0.0
    for node in iter_subtree(root):
        if node.in_mcp_subtree:
            continue
        if node.type == "LLM":
            parent = node.parent
            if (
                parent
                and parent.type == "LLM"
                and len(parent.children) == 1
                and parent.children[0] is node
                and parent.tokens
                and node.tokens
                and parent.tokens.get("total") == node.tokens.get("total")
                and parent.time is not None
                and node.time is not None
                and abs(parent.time - node.time) < 1e-6
            ):
                # AutoGen nested LLM dedup: keep the parent node only
                continue
            if node.time is not None:
                total += node.time
    return total


def compute_tool_overhead_for_subtree(root: TraceNode) -> float:
    """Compute Tool time (seconds) within the given subtree, reusing the global Tool rules."""

    total = 0.0
    for node in iter_subtree(root):
        if node.in_mcp_subtree:
            continue
        if node.type == "Chain" and node.name == "tools":
            # LangGraph: use the [Chain] tools container time
            p = node.parent
            while p is not None and not (p.type == "Chain" and p.name == "LangGraph"):
                p = p.parent
            if p is not None and node.time is not None:
                total += node.time
        elif node.type == "Tool":
            # CrewAI / AutoGen: sum Tool nodes; Tools under LangGraph are handled by the container above
            if _is_under_langgraph_tools(node):
                continue
            if node.time is not None:
                total += node.time
    return total


def compute_langgraph_format_output_time_for_subtree(root: TraceNode) -> float:
    """Compute LangGraph [Chain] format_output time (seconds) within the given subtree."""

    total = 0.0
    for node in iter_subtree(root):
        if node.in_mcp_subtree:
            continue
        if (
            node.type == "Chain"
            and node.name == "format_output"
            and node.time is not None
        ):
            total += node.time
    return total


def find_orchestrator(root: TraceNode) -> TraceNode:
    for node in iter_nodes(root):
        if node.type == "SPAN" and "orchestrator" in node.name:
            return node
    return root


def compute_llm_overhead(root: TraceNode) -> float:
    total = 0.0
    for node in iter_nodes(root):
        if node.in_mcp_subtree:
            continue
        if node.type == "LLM":
            parent = node.parent
            if (
                parent
                and parent.type == "LLM"
                and len(parent.children) == 1
                and parent.children[0] is node
                and parent.tokens
                and node.tokens
                and parent.tokens.get("total") == node.tokens.get("total")
                and parent.time is not None
                and node.time is not None
                and abs(parent.time - node.time) < 1e-6
            ):
                continue
            if node.time is not None:
                total += node.time
    return total


def _is_under_langgraph_tools(node: TraceNode) -> bool:
    p = node.parent
    seen_tools = False
    while p is not None:
        if p.type == "Chain" and p.name == "tools":
            seen_tools = True
        if seen_tools and p.type == "Chain" and p.name == "LangGraph":
            return True
        p = p.parent
    return False


def compute_tool_overhead(root: TraceNode) -> float:
    total = 0.0
    for node in iter_nodes(root):
        if node.in_mcp_subtree:
            continue
        if node.type == "Chain" and node.name == "tools":
            p = node.parent
            while p is not None and not (p.type == "Chain" and p.name == "LangGraph"):
                p = p.parent
            if p is not None and node.time is not None:
                total += node.time
        elif node.type == "Tool":
            if _is_under_langgraph_tools(node):
                continue
            if node.time is not None:
                total += node.time
    return total


def compute_a2a_overhead(root: TraceNode) -> float:
    total = 0.0
    for node in iter_nodes(root):
        if node.type == "SPAN" and node.name.startswith("a2a_call_"):
            if node.time is None:
                continue
            server = None
            for ch in node.children:
                if ch.type == "SPAN" and ("server_execution" in ch.name):
                    server = ch
                    break
            if server is not None and server.time is not None:
                diff = node.time - server.time
                if diff > 0:
                    total += diff
    return total


def _sum_mcp_time(node: TraceNode) -> float:
    total = 0.0
    stack = [node]
    while stack:
        n = stack.pop()
        if n is not node and n.in_mcp_subtree and n.time is not None:
            total += n.time
        for ch in n.children:
            stack.append(ch)
    return total


def _find_framework_child(server_node: TraceNode) -> Optional[TraceNode]:
    for ch in server_node.children:
        if ch.type == "Chain" and ch.name == "LangGraph":
            return ch
        if ch.type == "Chain" and re.match(r"Crew_.*\.kickoff", ch.name):
            return ch
        if ch.type == "AGENT" and ch.name.startswith("invoke_agent "):
            return ch
    return None


def compute_server_overhead(root: TraceNode) -> float:
    total = 0.0
    for node in iter_nodes(root):
        if node.type == "SPAN" and "server_execution" in node.name:
            if node.time is None:
                continue
            framework = _find_framework_child(node)
            framework_time = (
                framework.time if framework and framework.time is not None else 0.0
            )
            mcp_time = _sum_mcp_time(node)
            diff = node.time - framework_time - mcp_time
            if diff > 0:
                total += diff
    return total


def compute_framework_breakdown(root: TraceNode) -> (float, float, float):
    """Compute orchestration overhead for three frameworks: LangGraph / CrewAI kickoff / AutoGen invoke_agent."""

    lg_total = 0.0
    crew_total = 0.0
    autogen_total = 0.0

    for node in iter_nodes(root):
        if node.in_mcp_subtree or node.time is None:
            continue
        if node.type == "Chain" and node.name == "LangGraph":
            children_time = sum(
                (ch.time or 0.0) for ch in node.children if not ch.in_mcp_subtree
            )
            diff = node.time - children_time
            if diff > 0:
                lg_total += diff
        elif node.type == "Chain" and re.match(r"Crew_.*\.kickoff", node.name):
            children_time = sum(
                (ch.time or 0.0) for ch in node.children if not ch.in_mcp_subtree
            )
            diff = node.time - children_time
            if diff > 0:
                crew_total += diff
        elif node.type == "AGENT" and node.name.startswith("invoke_agent "):
            children_time = sum(
                (ch.time or 0.0) for ch in node.children if not ch.in_mcp_subtree
            )
            diff = node.time - children_time
            if diff > 0:
                autogen_total += diff

    return lg_total, crew_total, autogen_total


def compute_framework_overhead(root: TraceNode) -> float:
    """Kept for backward compatibility: return the sum of orchestration overhead across frameworks."""

    lg_total, crew_total, autogen_total = compute_framework_breakdown(root)
    return lg_total + crew_total + autogen_total


def analyze_file(path: Path) -> Optional[Dict[str, float]]:
    parser = ExecutionTreeParser(str(path))
    root = parser.parse()
    if root is None:
        return None
    orch = find_orchestrator(root)
    total_time_s = orch.time if orch.time is not None else None
    if total_time_s is None or total_time_s <= 0:
        return None
    # All internal computations use seconds (s)
    llm_s = compute_llm_overhead(root)
    tool_s = compute_tool_overhead(root)
    a2a_s = compute_a2a_overhead(root)
    # Compute per-framework overheads
    lg_fw_s, crew_fw_s, autogen_fw_s = compute_framework_breakdown(root)
    framework_s = lg_fw_s + crew_fw_s + autogen_fw_s
    server_s = compute_server_overhead(root)
    retry_s = compute_retry_time(root)
    classified_s = llm_s + tool_s + a2a_s + framework_s + server_s
    residual_s = total_time_s - classified_s

    # Compute ratios in seconds first (unit-independent)
    llm_ratio = llm_s / total_time_s
    tool_ratio = tool_s / total_time_s
    a2a_ratio = a2a_s / total_time_s
    framework_ratio = framework_s / total_time_s
    server_ratio = server_s / total_time_s
    residual_ratio = residual_s / total_time_s
    retry_ratio = retry_s / total_time_s if total_time_s > 0 else 0.0

    # Convert time to milliseconds (integer ms) for CSV output
    def to_ms(x: float) -> int:
        return int(round(x * 1000.0))

    total_time = to_ms(total_time_s)
    llm = to_ms(llm_s)
    tool = to_ms(tool_s)
    a2a = to_ms(a2a_s)
    lg_fw = to_ms(lg_fw_s)
    crew_fw = to_ms(crew_fw_s)
    autogen_fw = to_ms(autogen_fw_s)
    framework = lg_fw + crew_fw + autogen_fw
    server = to_ms(server_s)
    retry_time = to_ms(retry_s)
    classified = llm + tool + a2a + framework + server
    residual = total_time - classified
    result: Dict[str, float] = {
        "model": parser.model or "",
        "project": parser.project or "",
        "session_id": parser.session_id,
        "orchestrator_time": total_time,
        "LLM_OVERHEAD": llm,
        "Tool_OVERHEAD": tool,
        "A2A_OVERHEAD": a2a,
        "Framework_OVERHEAD": framework,
        "LangGraph_Framework_OVERHEAD": lg_fw,
        "CrewAI_Framework_OVERHEAD": crew_fw,
        "AutoGen_Framework_OVERHEAD": autogen_fw,
        "Server_OVERHEAD": server,
        "retry_time_ms": retry_time,
        "total_classified": classified,
        "residual": residual,
    }
    result.update(
        {
            "LLM_ratio": llm_ratio,
            "Tool_ratio": tool_ratio,
            "A2A_ratio": a2a_ratio,
            "Framework_ratio": framework_ratio,
            "Server_ratio": server_ratio,
            "residual_ratio": residual_ratio,
            "retry_ratio_vs_orch": retry_ratio,
        }
    )
    return result


def find_results_root() -> Path:
    p = Path(__file__).resolve()
    for parent in p.parents:
        if parent.name == "RESULTS":
            return parent
    return p.parent.parent.parent


def collect_execution_paths(results_dir: Path, project_name: str) -> List[Path]:
    paths: List[Path] = []
    for model_dir in results_dir.iterdir():
        if not model_dir.is_dir():
            continue
        proj_dir = model_dir / project_name / "test_results"
        if not proj_dir.exists():
            continue
        for session_dir in proj_dir.iterdir():
            if not session_dir.is_dir():
                continue
            ep = session_dir / "execution_path.md"
            if ep.exists():
                paths.append(ep)
    paths.sort()
    return paths


def write_model_summary(rows: List[Dict[str, float]], out_path: Path) -> None:
    """Aggregate per-run time breakdown results by model and write a summary CSV.

    Aggregation:
    - For each model:
      - Sum total time and each component time.
      - Compute component shares as: component_share = total_component / total_orchestrator.
    This matches the table style in the document (holistic share instead of averaging per-run shares).
    """

    agg = defaultdict(
        lambda: {
            "count": 0,
            "total_orchestrator_time": 0.0,
            "total_LLM_OVERHEAD": 0.0,
            "total_Tool_OVERHEAD": 0.0,
            "total_A2A_OVERHEAD": 0.0,
            "total_Framework_OVERHEAD": 0.0,
            "total_LangGraph_Framework_OVERHEAD": 0.0,
            "total_CrewAI_Framework_OVERHEAD": 0.0,
            "total_AutoGen_Framework_OVERHEAD": 0.0,
            "total_Server_OVERHEAD": 0.0,
            "total_retry_time_ms": 0.0,
            "total_classified": 0.0,
            "total_residual": 0.0,
        }
    )

    for row in rows:
        model = str(row.get("model", ""))
        m = agg[model]
        m["count"] += 1
        m["total_orchestrator_time"] += float(row.get("orchestrator_time", 0.0))
        m["total_LLM_OVERHEAD"] += float(row.get("LLM_OVERHEAD", 0.0))
        m["total_Tool_OVERHEAD"] += float(row.get("Tool_OVERHEAD", 0.0))
        m["total_A2A_OVERHEAD"] += float(row.get("A2A_OVERHEAD", 0.0))
        m["total_Framework_OVERHEAD"] += float(row.get("Framework_OVERHEAD", 0.0))
        m["total_LangGraph_Framework_OVERHEAD"] += float(
            row.get("LangGraph_Framework_OVERHEAD", 0.0)
        )
        m["total_CrewAI_Framework_OVERHEAD"] += float(
            row.get("CrewAI_Framework_OVERHEAD", 0.0)
        )
        m["total_AutoGen_Framework_OVERHEAD"] += float(
            row.get("AutoGen_Framework_OVERHEAD", 0.0)
        )
        m["total_Server_OVERHEAD"] += float(row.get("Server_OVERHEAD", 0.0))
        m["total_retry_time_ms"] += float(row.get("retry_time_ms", 0.0))
        m["total_classified"] += float(row.get("total_classified", 0.0))
        m["total_residual"] += float(row.get("residual", 0.0))

    summary_rows: List[Dict[str, float]] = []
    retry_rows: List[Dict[str, float]] = []
    for model, m in sorted(agg.items(), key=lambda kv: kv[0]):
        total_time = m["total_orchestrator_time"] or 1e-9  # ms, kept for comparison

        llm = m["total_LLM_OVERHEAD"]
        tool = m["total_Tool_OVERHEAD"]
        a2a = m["total_A2A_OVERHEAD"]
        framework = m["total_Framework_OVERHEAD"]
        lg_fw = m["total_LangGraph_Framework_OVERHEAD"]
        crew_fw = m["total_CrewAI_Framework_OVERHEAD"]
        autogen_fw = m["total_AutoGen_Framework_OVERHEAD"]
        server = m["total_Server_OVERHEAD"]
        residual = m["total_residual"]
        retry_total = m["total_retry_time_ms"]

        # Total component time (LLM + Tool + A2A + Framework + Server + residual), in ms
        components_time = llm + tool + a2a + framework + server + residual
        denom = components_time or 1e-9

        # Component shares (use components_time as denominator so the sum is ~1)
        llm_share = llm / denom
        tool_share = tool / denom
        a2a_share = a2a / denom
        framework_share = framework / denom
        lg_share = lg_fw / denom
        crew_share = crew_fw / denom
        autogen_share = autogen_fw / denom
        server_share = server / denom
        residual_share = residual / denom

        # RETRY share relative to total orchestrator time (in ms)
        retry_share_vs_orch = retry_total / (total_time or 1e-9)

        # Sum of major component shares (sanity check, should be close to 1)
        sum_component_shares = (
            llm_share
            + tool_share
            + a2a_share
            + framework_share
            + server_share
            + residual_share
        )

        summary_rows.append(
            {
                "model": model,
                "count": m["count"],
                "total_orchestrator_time": total_time,
                "total_LLM_OVERHEAD": llm,
                "total_Tool_OVERHEAD": tool,
                "total_A2A_OVERHEAD": a2a,
                "total_Framework_OVERHEAD": framework,
                "total_LangGraph_Framework_OVERHEAD": lg_fw,
                "total_CrewAI_Framework_OVERHEAD": crew_fw,
                "total_AutoGen_Framework_OVERHEAD": autogen_fw,
                "total_Server_OVERHEAD": server,
                "total_retry_time_ms": retry_total,
                "total_classified": m["total_classified"],
                "total_residual": residual,
                "total_components_time": components_time,
                # Component shares relative to total time
                "LLM_share": llm_share,
                "Tool_share": tool_share,
                "A2A_share": a2a_share,
                "Framework_share": framework_share,
                "LangGraph_Framework_share": lg_share,
                "CrewAI_Framework_share": crew_share,
                "AutoGen_Framework_share": autogen_share,
                "Server_share": server_share,
                "residual_share": residual_share,
                "retry_share_vs_orch": retry_share_vs_orch,
                "sum_component_shares": sum_component_shares,
            }
        )

        # RETRY-focused compact row: written to retry_breakdown_summary_by_model.csv
        retry_rows.append(
            {
                "model": model,
                "count": m["count"],
                "total_orchestrator_time_ms": total_time,
                "total_retry_time_ms": retry_total,
                "retry_share_vs_orch": retry_share_vs_orch,
            }
        )

    if not summary_rows:
        return

    # Main per-model summary table
    fieldnames = list(summary_rows[0].keys())
    with out_path.open("w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(summary_rows)

    # Dedicated RETRY cost summary table (one row per model)
    if retry_rows:
        retry_out_path = out_path.with_name("retry_breakdown_summary_by_model.csv")
        retry_fieldnames = list(retry_rows[0].keys())
        with retry_out_path.open("w", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(f, fieldnames=retry_fieldnames)
            writer.writeheader()
            writer.writerows(retry_rows)


def _infer_langgraph_agent_name(node: TraceNode) -> str:
    """Walk upwards from a LangGraph container to find the nearest SPAN as the business agent name."""

    p = node.parent
    while p is not None:
        if p.type == "SPAN":
            name = p.name
            # Remove common server_execution suffix
            name = re.sub(r"_server_execution$", "", name)
            return name
        p = p.parent
    return "LangGraph"


def _normalize_crewai_agent_name(name: str) -> str:
    """Normalize CrewAI agent names.

    Handle variants like "Senior Candidate Evaluator._execute_core" or
    "Senior Candidate Evaluator._execute_core]" and normalize to
    "Senior Candidate Evaluator".
    """

    # Strip trailing _execute_core or _execute_core]
    name = re.sub(r"\._execute_core\]?$", "", name)
    return name.strip()


def collect_agent_llm_tool_breakdown(exec_paths: List[Path]) -> List[Dict[str, float]]:
    """Aggregate LLM/Tool time (ms) by (model, framework, agent_name).

    - LangGraph: treat [Chain] LangGraph as the container; sum LLM/Tool and format_output in its subtree.
    - CrewAI: use direct child [AGENT] xxx._execute_core under [Chain] Crew***.kickoff as the container.
    - AutoGen: use [AGENT] invoke_agent xxx as the container.
    """

    agg = defaultdict(
        lambda: {
            "llm_s": 0.0,
            "tool_s": 0.0,
            "format_output_s": 0.0,
            "occurrences": 0,
        }
    )

    for ep in exec_paths:
        parser = ExecutionTreeParser(str(ep))
        root = parser.parse()
        if root is None:
            continue
        model = parser.model or ""

        for node in iter_nodes(root):
            if node.in_mcp_subtree:
                continue

            # Treat the LangGraph container as one agent
            if node.type == "Chain" and node.name == "LangGraph":
                framework = "LangGraph"
                agent_name = _infer_langgraph_agent_name(node)
                llm_s = compute_llm_overhead_for_subtree(node)
                tool_s = compute_tool_overhead_for_subtree(node)
                fmt_s = compute_langgraph_format_output_time_for_subtree(node)
                if llm_s == 0.0 and tool_s == 0.0 and fmt_s == 0.0:
                    continue
                key = (model, framework, agent_name)
                m = agg[key]
                m["llm_s"] += llm_s
                m["tool_s"] += tool_s
                m["format_output_s"] += fmt_s
                m["occurrences"] += 1

            # CrewAI: each direct child AGENT under kickoff is treated as an agent
            elif node.type == "Chain" and re.match(r"Crew_.*\.kickoff", node.name):
                for ch in node.children:
                    if ch.in_mcp_subtree or ch.type != "AGENT":
                        continue
                    framework = "CrewAI"
                    agent_name = _normalize_crewai_agent_name(ch.name)
                    llm_s = compute_llm_overhead_for_subtree(ch)
                    tool_s = compute_tool_overhead_for_subtree(ch)
                    fmt_s = 0.0
                    if llm_s == 0.0 and tool_s == 0.0:
                        continue
                    key = (model, framework, agent_name)
                    m = agg[key]
                    m["llm_s"] += llm_s
                    m["tool_s"] += tool_s
                    m["format_output_s"] += fmt_s
                    m["occurrences"] += 1

            # AutoGen: invoke_agent is treated as an agent
            elif node.type == "AGENT" and node.name.startswith("invoke_agent "):
                framework = "AutoGen"
                agent_name = node.name[len("invoke_agent ") :]
                llm_s = compute_llm_overhead_for_subtree(node)
                tool_s = compute_tool_overhead_for_subtree(node)
                fmt_s = 0.0
                if llm_s == 0.0 and tool_s == 0.0:
                    continue
                key = (model, framework, agent_name)
                m = agg[key]
                m["llm_s"] += llm_s
                m["tool_s"] += tool_s
                m["format_output_s"] += fmt_s
                m["occurrences"] += 1

    rows: List[Dict[str, float]] = []
    for (model, framework, agent_name), st in sorted(
        agg.items(), key=lambda kv: (kv[0][0], kv[0][1], kv[0][2])
    ):
        llm_ms = int(round(st["llm_s"] * 1000.0))
        tool_ms = int(round(st["tool_s"] * 1000.0))
        fmt_ms = int(round(st["format_output_s"] * 1000.0))
        total_ms = llm_ms + tool_ms + fmt_ms
        denom = total_ms or 1e-9
        rows.append(
            {
                "model": model,
                "framework": framework,
                "agent_name": agent_name,
                "occurrences": st["occurrences"],
                "total_llm_time_ms": llm_ms,
                "total_tool_time_ms": tool_ms,
                "total_format_output_time_ms": fmt_ms,
                "total_agent_llm_tool_time_ms": total_ms,
                "llm_share_in_agent": llm_ms / denom,
                "tool_share_in_agent": tool_ms / denom,
                "format_output_share_in_agent": fmt_ms / denom,
            }
        )

    return rows


def main() -> None:
    results_dir = find_results_root()
    project_name = "RecruitmentAssistant-H_A2A"
    exec_paths = collect_execution_paths(results_dir, project_name)
    rows: List[Dict[str, float]] = []
    for ep in exec_paths:
        metrics = analyze_file(ep)
        if metrics is not None:
            rows.append(metrics)
    out_dir = Path(__file__).resolve().parent
    per_run_path = out_dir / "performance_breakdown_summary.csv"
    per_model_path = out_dir / "performance_breakdown_summary_by_model.csv"
    agent_path = out_dir / "agent_llm_tool_breakdown_by_model.csv"

    if rows:
        # Per-run detailed table (one row per run)
        fieldnames = list(rows[0].keys())
        with per_run_path.open("w", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(f, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(rows)
        print(f"written {len(rows)} rows to {per_run_path}")

        # Per-model aggregated summary table
        write_model_summary(rows, per_model_path)
        print(f"written model summary to {per_model_path}")

        # Agent-level LLM/Tool breakdown (grouped by model × agent)
        agent_rows = collect_agent_llm_tool_breakdown(exec_paths)
        if agent_rows:
            agent_fieldnames = list(agent_rows[0].keys())
            with agent_path.open("w", newline="", encoding="utf-8") as f:
                writer = csv.DictWriter(f, fieldnames=agent_fieldnames)
                writer.writeheader()
                writer.writerows(agent_rows)
            print(f"written agent LLM/Tool breakdown to {agent_path}")
    else:
        print("no valid execution_path.md found")


if __name__ == "__main__":
    main()