summaryrefslogtreecommitdiffstats
path: root/.github/scripts/tests/generate-summary.py
blob: 9a569cf5c0a210b9b506d02cf7e21ad46525f3ee (plain) (blame)
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
#!/usr/bin/env python3
import argparse
import dataclasses
import json
import math
import os
import re
import sys
import traceback
from enum import Enum
from operator import attrgetter
from typing import List, Dict
from jinja2 import Environment, FileSystemLoader, StrictUndefined
from get_test_history import get_test_history
from error_type_utils import (
    is_not_launched_issue,
    is_timeout_issue,
    is_xfailed_issue,
    source_has_tag,
)

_ANALYTICS_DIR = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'analytics'))
if _ANALYTICS_DIR not in sys.path:
    sys.path.insert(0, _ANALYTICS_DIR)
from testowners_utils import get_testowners_for_tests  # noqa: E402


def load_owner_area_mapping():
    """Load owner to area label mapping from JSON config file."""
    try:
        script_dir = os.path.dirname(os.path.abspath(__file__))
        config_dir = os.path.join(script_dir, '..', '..', 'config')
        mapping_file = os.path.join(config_dir, 'owner_area_mapping.json')
        with open(mapping_file, 'r') as f:
            return json.load(f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Warning: Could not load owner area mapping: {e}")
        return {}

class TestStatus(Enum):
    PASS = 0
    FAIL = 1
    ERROR = 2
    SKIP = 3
    MUTE = 4

    @property
    def is_error(self):
        return self in (TestStatus.FAIL, TestStatus.ERROR, TestStatus.MUTE)

    def __lt__(self, other):
        return self.value < other.value


@dataclasses.dataclass
class TestResult:
    classname: str
    name: str
    status: TestStatus
    log_urls: Dict[str, str]
    elapsed: float
    count_of_passed: int
    owners: str
    status_description: str
    stderr_url: str = ""
    log_url: str = ""
    error_type: str = ""
    is_sanitizer_issue: bool = False
    is_timeout_issue: bool = False
    is_xfailed_issue: bool = False
    is_verify_issue: bool = False
    is_possible_oom: bool = False
    is_not_launched: bool = False

    @property
    def status_display(self):
        base = {
            TestStatus.PASS: "PASS",
            TestStatus.FAIL: "FAIL",
            TestStatus.ERROR: "ERROR",
            TestStatus.SKIP: "SKIP",
            TestStatus.MUTE: "MUTE",
        }[self.status]
        return base

    @property
    def elapsed_display(self):
        # Round up to 1 decimal place: 10.545s -> 10.6s (ceiling to 0.1)
        elapsed_rounded = math.ceil(self.elapsed * 10) / 10
        m, s = divmod(elapsed_rounded, 60)
        parts = []
        if m > 0:
            parts.append(f'{int(m)}m')
        parts.append(f"{s:.1f}s")
        return ' '.join(parts)

    def __str__(self):
        return f"{self.full_name:<138} {self.status_display}"

    @property
    def full_name(self):
        if self.classname:
            return f"{self.classname}/{self.name}"
        return self.name

    @classmethod
    def from_build_results_report(cls, result):
        """
        Create TestResult from build-results-report JSON result.
        
        Required fields: path, status
        Optional fields: name, subtest_name, error_type, rich-snippet, properties, links, metrics
        """
        # Validate required fields
        path_str = result.get("path")
        if path_str is None:
            raise ValueError(f"Missing required field 'path' in result: {result}")
        
        status_str = result.get("status")
        if status_str is None:
            raise ValueError(f"Missing required field 'status' in result: {result}")
        
        # Extract fields
        name_part = result.get("name")
        subtest_name = result.get("subtest_name")
        error_type = result.get("error_type")
        status_description = result.get("rich-snippet")
        properties = result.get("properties")
        metrics = result.get("metrics")
        
        classname = path_str
        if subtest_name and subtest_name.strip():
            if name_part:
                name = f"{name_part}.{subtest_name}"
            else:
                name = subtest_name
        else:
            name = name_part or ""
        
        # Status normalization (OK->PASSED, NOT_LAUNCHED->SKIPPED, mute->MUTE) is done by transform_build_results.py
        # Map status to TestStatus enum
        if status_str == "MUTE":
            status = TestStatus.MUTE
        elif status_str == "FAILED":
            status = TestStatus.FAIL
        elif status_str == "ERROR":
            status = TestStatus.ERROR
        elif status_str == "SKIPPED":
            status = TestStatus.SKIP
        else:
            status = TestStatus.PASS
        
        # Extract log URLs from links (updated by transform_build_results.py with URLs)
        # Links format: {"log": ["https://..."], "stdout": ["https://..."], "logsdir": ["https://..."]}
        links = result.get("links", {})
        
        def get_link_url(link_type):
            if link_type in links and isinstance(links[link_type], list) and len(links[link_type]) > 0:
                return links[link_type][0]  # Take first URL from array
            return None
        
        log_urls = {
            'Log': get_link_url("Log"),
            'log': get_link_url("log"),
            'logsdir': get_link_url("logsdir"),
            'stdout': get_link_url("stdout"),
            'stderr': get_link_url("stderr"),
        }
        log_urls = {k: v for k, v in log_urls.items() if v}
        log_url = get_link_url("log") or get_link_url("Log") or ""

        # Get duration from result (same as upload_tests_results.py)
        duration = result.get("duration", 0)
        try:
            elapsed = float(duration)
        except (TypeError, ValueError):
            elapsed = 0.0
        
        return cls(
            classname=classname,
            name=name,
            status=status,
            log_urls=log_urls,
            elapsed=elapsed,
            count_of_passed=0,
            owners='',
            status_description=status_description or '',
            stderr_url=log_urls.get('stderr', ''),
            log_url=log_url,
            error_type=error_type or '',
            # is_sanitizer_issue, is_verify_issue and is_possible_oom are set in gen_summary from error_type.
            is_sanitizer_issue=False,
            is_timeout_issue=is_timeout_issue(error_type),
            is_xfailed_issue=is_xfailed_issue(error_type),
            is_verify_issue=False,
            is_possible_oom=False,
            # NOT_LAUNCHED can be in SKIPPED or MUTE status (if muted after being NOT_LAUNCHED)
            is_not_launched=is_not_launched_issue(error_type, status.name)
        )


class TestSummaryLine:
    def __init__(self, title):
        self.title = title
        self.tests = []
        self.is_failed = False
        self.report_fn = self.report_url = None
        self.counter = {s: 0 for s in TestStatus}

    def add(self, test: TestResult):
        self.is_failed |= test.status in (TestStatus.ERROR, TestStatus.FAIL)
        self.counter[test.status] += 1
        self.tests.append(test)

    def add_report(self, fn, url):
        self.report_fn = fn
        self.report_url = url

    @property
    def test_count(self):
        return len(self.tests)

    @property
    def passed(self):
        return self.counter[TestStatus.PASS]

    @property
    def errors(self):
        return self.counter[TestStatus.ERROR]

    @property
    def failed(self):
        return self.counter[TestStatus.FAIL]

    @property
    def skipped(self):
        return self.counter[TestStatus.SKIP]

    @property
    def muted(self):
        return self.counter[TestStatus.MUTE]


class TestSummary:
    def __init__(self, is_retry: bool):
        self.lines: List[TestSummaryLine] = []
        self.is_failed = False
        self.is_retry = is_retry
        self.dmesg_has_oom = False
        self.oom_dmesg_url = None

    def add_line(self, line: TestSummaryLine):
        self.is_failed |= line.is_failed
        self.lines.append(line)

    def render_line(self, items):
        return f"| {' | '.join(items)} |"

    def render(self, add_footnote=False, is_retry=False):
        github_srv = os.environ.get("GITHUB_SERVER_URL", "https://github.com")
        repo = os.environ.get("GITHUB_REPOSITORY", "ydb-platform/ydb")

        footnote_url = f"{github_srv}/{repo}/tree/main/.github/config/muted_ya.txt"

        footnote = "[^1]" if add_footnote else f'<sup>[?]({footnote_url} "All mute rules are defined here")</sup>'

        columns = [
            "TESTS", "PASSED", "ERRORS", "FAILED", "SKIPPED", f"MUTED{footnote}"
        ]

        need_first_column = len(self.lines) > 1

        if need_first_column:
            columns.insert(0, "")

        result = []

        result.append(self.render_line(columns))

        if need_first_column:
            result.append(self.render_line([':---'] + ['---:'] * (len(columns) - 1)))
        else:
            result.append(self.render_line(['---:'] * len(columns)))

        for line in self.lines:
            report_url = line.report_url
            row = []
            if need_first_column:
                row.append(line.title)
            row.extend([
                render_pm(f"{line.test_count}" + (" (only retried tests)" if self.is_retry else ""), f"{report_url}", 0),
                render_pm(line.passed, f"{report_url}#PASS", 0),
                render_pm(line.errors, f"{report_url}#ERROR", 0),
                render_pm(line.failed, f"{report_url}#FAIL", 0),
                render_pm(line.skipped, f"{report_url}#SKIP", 0),
                render_pm(line.muted, f"{report_url}#MUTE", 0),
            ])
            result.append(self.render_line(row))

        if add_footnote:
            result.append("")
            result.append(f"[^1]: All mute rules are defined [here]({footnote_url}).")
        
        return result


def render_pm(value, url, diff=None):
    if value:
        text = f"[{value}]({url})"
    else:
        text = str(value)

    if diff is not None and diff != 0:
        if diff == 0:
            sign = "±"
        elif diff < 0:
            sign = "-"
        else:
            sign = "+"

        text = f"{text} {sign}{abs(diff)}"

    return text


def render_testlist_html(rows, fn, build_preset, branch, pr_number=None, workflow_run_id=None):
    TEMPLATES_PATH = os.path.join(os.path.dirname(__file__), "templates")

    env = Environment(loader=FileSystemLoader(TEMPLATES_PATH), undefined=StrictUndefined)

    status_test = {}
    has_any_log = set()

    for t in rows:
        status_test.setdefault(t.status, []).append(t)
        if any(t.log_urls.values()):
            has_any_log.add(t.status)

    for status in status_test.keys():
        status_test[status].sort(key=attrgetter("full_name"))

    status_order = [TestStatus.ERROR, TestStatus.FAIL, TestStatus.SKIP, TestStatus.MUTE, TestStatus.PASS]

    # remove status group without tests
    status_order = [s for s in status_order if s in status_test]

    # get testowners
    all_tests = [test for status in status_order for test in status_test.get(status)]
        
    get_testowners_for_tests(all_tests)
    
    # statuses for history
    status_for_history = [TestStatus.FAIL, TestStatus.MUTE, TestStatus.ERROR]
    status_for_history = [s for s in status_for_history if s in status_test]
    
    tests_names_for_history = []
    history= {}
    tests_in_statuses = [test for status in status_for_history for test in status_test.get(status)]
    
    # get tests for history
    for test in tests_in_statuses:
        tests_names_for_history.append(test.full_name)

    try:
        # Get history for last 4 days instead of last N runs
        history = get_test_history(tests_names_for_history, 4, build_preset, branch)
    except Exception:
        print(traceback.format_exc())
   
    # Calculate success rate for each test
    def calculate_success_rate(test_history):
        """Calculate success rate separately for pr-check and other runs"""
        pr_check_runs = []
        other_runs = []
        
        for timestamp, run_data in test_history.items():
            job_name = run_data.get("job_name", "").lower()
            # Check if it's a pr-check run (common patterns: pr-check, pr_check, pr/check, etc.)
            is_pr_check = "pr-check" in job_name or "pr_check" in job_name or "pr/check" in job_name
            
            if is_pr_check:
                pr_check_runs.append(run_data)
            else:
                other_runs.append(run_data)
        
        def calc_rate(runs):
            if not runs:
                return None
            passed = sum(1 for r in runs if r.get("status") == "passed")
            total = len(runs)
            return {
                "rate": round(passed / total * 100, 1) if total > 0 else 0,
                "passed": passed,
                "total": total
            }
        
        return {
            "pr_check": calc_rate(pr_check_runs),
            "other": calc_rate(other_runs)
        }
    
    # Calculate success rates for all tests with history
    test_success_rates = {}
    
    print(f"Processing history for {len(history)} tests with history data")
    print(f"Total tests in statuses: {len(tests_in_statuses)}")
    
    for test in tests_in_statuses:
        if test.full_name in history:
            test_history = history[test.full_name]
            if test_history:  # Check that history is not empty
                rates = calculate_success_rate(test_history)
                test_success_rates[test.full_name] = rates
                # Also update count_of_passed for backward compatibility
                test.count_of_passed = len(
                    [
                        history[test.full_name][x]
                        for x in history[test.full_name]
                        if history[test.full_name][x]["status"] == "passed"
                    ]
                )
    
    print(f"Calculated success rates for {len(test_success_rates)} tests")
    
    # sorted by test name
    for current_status in status_for_history:
        status_test.get(current_status,[]).sort(key=lambda val: (val.full_name, ))

    build_preset_params = '--build unknown_build_type'
    if build_preset == 'release-asan' :
        build_preset_params = '--build "release" --sanitize="address" -DDEBUGINFO_LINES_ONLY'
    elif build_preset == 'release-msan':
        build_preset_params = '--build "release" --sanitize="memory" -DDEBUGINFO_LINES_ONLY'
    elif build_preset == 'release-tsan':   
        build_preset_params = '--build "release" --sanitize="thread" -DDEBUGINFO_LINES_ONLY'
    elif build_preset == 'relwithdebinfo':
        build_preset_params = '--build "relwithdebinfo"'
    
    # Get GitHub server URL and repository from environment
    github_server_url = os.environ.get("GITHUB_SERVER_URL", "https://github.com")
    github_repository = os.environ.get("GITHUB_REPOSITORY", "ydb-platform/ydb")
    
    # For commit SHA, prioritize the actual head commit over merge commit
    # In PR context, GITHUB_HEAD_SHA contains the actual commit being tested
    github_sha = os.environ.get("GITHUB_HEAD_SHA", "")
    
    # Construct PR and workflow URLs if the information is available
    pr_url = None
    workflow_url = None
    
    if pr_number:
        pr_url = f"{github_server_url}/{github_repository}/pull/{pr_number}"
    
    if workflow_run_id:
        workflow_url = f"{github_server_url}/{github_repository}/actions/runs/{workflow_run_id}"
    
    # Load owner to area mapping
    owner_area_mapping = load_owner_area_mapping()
    
    # Prepare history data for JavaScript (without status_description to reduce HTML size)
    # Store status_description separately - only for failed/error/mute entries to save space
    history_for_js = {}
    history_descriptions = {}  # Separate object for status descriptions (only non-empty, failed/error/mute)
    if history:
        for test_name, test_history in history.items():
            history_for_js[test_name] = {}
            history_descriptions[test_name] = {}
            for timestamp, hist_data in test_history.items():
                timestamp_str = str(timestamp)
                status = hist_data.get("status", "")
                history_for_js[test_name][timestamp_str] = {
                    "status": status,
                    "date": hist_data.get("datetime", ""),
                    "commit": hist_data.get("commit", ""),
                    "job_name": hist_data.get("job_name", ""),
                    "job_id": hist_data.get("job_id", ""),
                    "branch": hist_data.get("branch", "")
                    # status_description removed to reduce HTML size - stored separately
                }
                # Store description separately (only for failed/error/mute and if not empty to save space)
                desc = hist_data.get("status_description", "")
                if desc and desc.strip() and status in ("failure", "error", "mute"):
                    history_descriptions[test_name][timestamp_str] = desc
    
    # Prepare test descriptions for current tests (without embedding in HTML to reduce size)
    # Store only for tests with errors (FAIL, ERROR, MUTE, SKIP) and if not empty
    test_descriptions = {}
    for test in all_tests:
        if test.status in (TestStatus.FAIL, TestStatus.ERROR, TestStatus.MUTE, TestStatus.SKIP):
            desc = test.status_description
            if desc and desc.strip():
                test_descriptions[test.full_name] = desc
    
    # Save data to separate JSON file to reduce HTML size
    # fn is the full path to HTML file (e.g., /path/to/public_dir/try_1/ya-test.html)
    data_file = fn.replace('.html', '_data.json')
    data_to_save = {
        'history_for_js': history_for_js,
        'history_descriptions': history_descriptions,
        'test_descriptions': test_descriptions,
        'test_success_rates': test_success_rates
    }
    with open(data_file, "w", encoding="utf-8") as f:
        json.dump(data_to_save, f, separators=(',', ':'))  # Minified JSON
    
    # Calculate data file URL (relative to HTML file location)
    # JSON file is in the same directory as HTML file, so we use just the filename
    # This way fetch() in browser will load JSON from the same directory as HTML
    # Example: if HTML is at /path/to/try_1/ya-test.html,
    #          JSON is at /path/to/try_1/ya-test_data.json,
    #          and URL should be "ya-test_data.json" (relative to HTML location)
    data_file_url = os.path.basename(data_file)
        
    content = env.get_template("summary.html").render(
        status_order=status_order,
        tests=status_test,
        has_any_log=has_any_log,
        history=history,  # Keep for template checks (test.full_name in history)
        history_for_js={},  # Empty - will be loaded from JSON
        history_descriptions={},  # Empty - will be loaded from JSON
        test_descriptions={},  # Empty - will be loaded from JSON
        test_success_rates={},  # Empty - will be loaded from JSON
        data_file_url=data_file_url,  # URL to JSON data file
        build_preset=build_preset,
        build_preset_params=build_preset_params,
        branch=branch,
        pr_number=pr_number,
        pr_url=pr_url,
        workflow_run_id=workflow_run_id,
        workflow_url=workflow_url,
        owner_area_mapping=owner_area_mapping,
        commit_sha=github_sha
    )

    with open(fn, "w", encoding="utf-8") as fp:
        fp.write(content)


def write_summary(summary: TestSummary):
    summary_fn = os.environ.get("GITHUB_STEP_SUMMARY")
    if summary_fn:
        fp = open(summary_fn, "at")
    else:
        fp = sys.stdout

    for line in summary.render(add_footnote=True):
        fp.write(f"{line}\n")

    fp.write("\n")

    if summary_fn:
        fp.close()


def _list_build_results_report_files(path):
    """Return paths to build-results-report JSON files."""
    import glob

    if os.path.isfile(path):
        return [path]
    files = glob.glob(os.path.join(path, "**/report.json"), recursive=True)
    if not files:
        files = glob.glob(os.path.join(path, "report.json"))
    return files


def iter_build_results_files(path):
    """Iterate over build-results-report JSON files"""
    for fn in _list_build_results_report_files(path):
        try:
            with open(fn, 'r') as f:
                report = json.load(f)
            
            for result in report.get("results") or []:
                # Only include results that have a status field (indicates it's a test/check)
                # Filtering (suite, build, configure) is done by transform_build_results.py
                status = result.get("status")
                if not status:
                    continue
                
                yield fn, result
        except (json.JSONDecodeError, KeyError) as e:
            print(f"Warning: Unable to parse {fn}: {e}", file=sys.stderr)
            continue


# Did dmesg show ANY OOM-killer event during this try?
_OOM_DMESG_EVIDENCE_RE = re.compile(
    r'\b(?:Out of memory:\s+Killed process|invoked oom-killer|Memory cgroup out of memory)\b',
    re.IGNORECASE,
)


def _dmesg_has_oom(oom_dmesg_log):
    """True if the per-try dmesg dump contains any OOM-killer evidence."""
    if not oom_dmesg_log:
        return False
    try:
        if not os.path.isfile(oom_dmesg_log) or os.path.getsize(oom_dmesg_log) == 0:
            return False
        with open(oom_dmesg_log, 'r', encoding='utf-8', errors='replace') as f:
            return _OOM_DMESG_EVIDENCE_RE.search(f.read()) is not None
    except OSError:
        return False


def gen_summary(public_dir, public_dir_url, paths, is_retry: bool, build_preset, branch, pr_number=None, workflow_run_id=None, oom_dmesg_log=None):
    summary = TestSummary(is_retry=is_retry)
    summary.dmesg_has_oom = _dmesg_has_oom(oom_dmesg_log)
    if summary.dmesg_has_oom and oom_dmesg_log:
        try:
            if os.path.isabs(oom_dmesg_log) and os.path.commonpath([oom_dmesg_log, public_dir]) == os.path.abspath(public_dir):
                rel = os.path.relpath(oom_dmesg_log, public_dir)
                summary.oom_dmesg_url = f"{public_dir_url}/{rel}"
        except ValueError:
            pass
    if summary.dmesg_has_oom:
        print(f"[oom] dmesg evidence found in {oom_dmesg_log}", flush=True)

    for title, html_fn, path in paths:
        summary_line = TestSummaryLine(title)

        for _fn, result in iter_build_results_files(path):
            test_result = TestResult.from_build_results_report(result)
            summary_line.add(test_result)

        for test in summary_line.tests:
            if not test.status.is_error:
                continue
            et = test.error_type
            test.is_sanitizer_issue = source_has_tag(et, "SANITIZER")
            test.is_verify_issue = source_has_tag(et, "VERIFY")
            test.is_possible_oom = source_has_tag(et, "POSSIBLE_OOM")

        if os.path.isabs(html_fn):
            html_fn = os.path.relpath(html_fn, public_dir)
        report_url = f"{public_dir_url}/{html_fn}"

        render_testlist_html(summary_line.tests, os.path.join(public_dir, html_fn), build_preset, branch, pr_number, workflow_run_id)
        summary_line.add_report(html_fn, report_url)
        summary.add_line(summary_line)

    return summary


def get_comment_text(summary: TestSummary, summary_links: str, is_last_retry: bool, is_test_result_ignored: bool)->tuple[str, list[str]]:
    color = "red"
    if summary.is_failed:
        if is_test_result_ignored:
            color = "yellow"
            result = f"Some tests failed, follow the links below. This fail is not in blocking policy yet"
        else:
            color = "red" if is_last_retry else "yellow"
            result = f"Some tests failed, follow the links below."
        if not is_last_retry:
            result += " Going to retry failed tests..."
    else:
        color = "green"
        result = f"Tests successful."

    body = []

    body.append(result)

    # Surface OOM evidence from dmesg in the report header.
    if getattr(summary, "dmesg_has_oom", False):
        link = (
            f" See [oom_dmesg.txt]({summary.oom_dmesg_url})."
            if getattr(summary, "oom_dmesg_url", None)
            else ""
        )
        body.append(
            f":warning: **OOM detected** in dmesg during this try. "
            f"Tests killed by SIGKILL are flagged with the 'possible OOM' badge.{link}"
        )

    if not is_last_retry:
        body.append("")
        body.append("<details>")
        body.append("")

    with open(summary_links) as f:
        links = f.readlines()
    
    links.sort()
    links = [line.split(" ", 1)[1].strip() for line in links]

    if links:
        body.append("")
        body.append(" | ".join(links))
    
    body.extend(summary.render())

    if not is_last_retry:
        body.append("")
        body.append("</details>")
        body.append("")
    else:
        body.append("")

    return color, body


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--public_dir", required=True)
    parser.add_argument("--public_dir_url", required=True)
    parser.add_argument("--summary_links", required=True)
    parser.add_argument('--build_preset', default="default-linux-x86-64-relwithdebinfo", required=False)
    parser.add_argument('--branch', default="main", required=False)
    parser.add_argument('--status_report_file', required=False)
    parser.add_argument('--is_retry', required=True, type=int)
    parser.add_argument('--is_last_retry', required=True, type=int)
    parser.add_argument('--is_test_result_ignored', required=True, type=int)
    parser.add_argument('--comment_color_file', required=True)
    parser.add_argument('--comment_text_file', required=True)
    parser.add_argument('--pr_number', required=False, type=int, help="Pull request number")
    parser.add_argument('--workflow_run_id', required=False, help="GitHub workflow run ID")
    parser.add_argument('--oom_dmesg_log', required=False, default=None,
                        help="Path to per-try dmesg OOM dump for OOM badge correlation.")
    parser.add_argument("args", nargs="+", metavar="TITLE html_out build-results-report-path")
    args = parser.parse_args()

    if len(args.args) % 3 != 0:
        print("Invalid argument count")
        raise SystemExit(-1)

    paths = iter(args.args)
    title_path = list(zip(paths, paths, paths))

    summary = gen_summary(args.public_dir,
                          args.public_dir_url,
                          title_path,
                          is_retry=bool(args.is_retry),
                          build_preset=args.build_preset,
                          branch=args.branch,
                          pr_number=args.pr_number,
                          workflow_run_id=args.workflow_run_id,
                          oom_dmesg_log=args.oom_dmesg_log,
                          )
    write_summary(summary)

    if summary.is_failed and not args.is_test_result_ignored:
        overall_status = "failure"
    else:
        overall_status = "success"

    color, text = get_comment_text(summary, args.summary_links, is_last_retry=bool(args.is_last_retry), is_test_result_ignored=args.is_test_result_ignored)

    with open(args.comment_color_file, "w") as f:
        f.write(color)

    with open(args.comment_text_file, "w") as f:
        f.write('\n'.join(text))
        f.write('\n')

    if args.status_report_file:
        with open(args.status_report_file, "w") as f:
            f.write(overall_status)


if __name__ == "__main__":
    main()