File size: 47,673 Bytes
89995d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import glob
import json
import logging
import os
import shutil
import subprocess
import sys
import re
import traceback
import tomli as tomllib

# Add the project root to the Python path to ensure we pick up the correct modules
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
sys.path.insert(0, project_root)


from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import List

import helpers, shell

from benchmark import (
    BenchmarkTask,
    Status,
    TokenDetails,
    STATUS_DESCRIPTIONS,
)
from config import config

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    handlers=[logging.StreamHandler(sys.stdout)],
)
logger = logging.getLogger(__name__)


@dataclass
class BenchmarkResult:
    score: float
    diagnostics: List[str]
    status: Status
    used_tokens: TokenDetails | None = None
    exported_passed_tests: List[str] = field(default_factory=list)
    exported_failed_tests: List[str] = field(default_factory=list)
    partial_score: float = 0.0
    pass_rate: float = 0.0
    validation_results: dict[str, bool] = field(default_factory=dict)
    scoring_breakdown: dict = field(default_factory=dict)
    custom_metrics: dict = field(default_factory=dict)

    def to_dict(self):
        data = asdict(self)
        data["status"] = self.status.name
        data["status_description"] = STATUS_DESCRIPTIONS.get(self.status, "")
        custom = data.pop("custom_metrics", {})
        if custom:
            data.update(custom)
        return data


def run_benchmark_task(
    task: BenchmarkTask,
    output_dir: Path | None = None,
    export_tests: bool = False,
    keep_tests: bool = False,
) -> BenchmarkResult:
    emulator_process = None

    repo_name = task.repo_url.split("/")[-1].replace(".git", "")
    work_dir = (
        Path(repo_name) / task.work_dir if task.work_dir else Path("/workspace/testbed")
    )

    if not work_dir.exists():
        logger.error(f"Working directory not found: {work_dir}")
        return BenchmarkResult(
            score=0.0,
            diagnostics=[f"Working directory not found: {work_dir}"],
            status=Status.INFRA_FAILURE_SETUP_ISSUE,
        )

    # Log task execution summary
    logger.info("=" * 70)
    logger.info(f"STARTING BENCHMARK TASK: {task.instance_id}")
    logger.info(f"Repository: {task.repo_url}")
    logger.info(f"Work directory: {work_dir}")
    logger.info(f"Patch file: {task.patch_file}")
    logger.info(f"Test commands: {task.test_commands}")
    if keep_tests:
        logger.info("Keep tests: True")
    os.environ["KEEP_TESTS"] = "true" if keep_tests else "false"
    logger.info("=" * 70)

    try:

        log_file = os.path.join(work_dir, "log.txt")
        emulator_process = None

        # --- Set Java Version ---
        java_home = f"/usr/lib/jvm/java-{task.env_config.jdk_version}-openjdk-amd64"
        logger.info(f"Instance {task.instance_id}: Setting JAVA_HOME to: {java_home}")
        helpers.update_local_properties(work_dir, java_home)

        # --- Repository Setup ---
        logger.info(f"Instance {task.instance_id}: Using working directory: {work_dir}")
        result = shell.run_command("pwd && ls", cwd=str(work_dir))
        logger.debug(f"Instance {task.instance_id}: pwd && ls = {result.stdout}")

        if task.startup_script and task.startup_script.exists():
            logger.info(
                f"Instance {task.instance_id}: Running startup script: {task.startup_script}"
            )
            script_command = f"bash {task.startup_script.resolve().as_posix()}"
            result = shell.run_command(script_command, cwd=str(work_dir))
            logger.info(
                f"Instance {task.instance_id}: Startup script output: {result.stdout}\n{result.stderr}"
            )
            if result.exit_code != 0:
                return BenchmarkResult(
                    score=0.0,
                    diagnostics=[f"Startup script failed: {result.stderr}"],
                    status=Status.INFRA_FAILURE_SETUP_ISSUE,
                )

        # Save current git work to patch
        try:
            subprocess.run(
                "git add -A && git diff --cached --binary > /logs/artifacts/_submission.patch && git reset",
                shell=True,
                cwd=str(work_dir),
                check=False,
            )
        except Exception as e:
            logger.warning(f"Failed to save submission patch: {e}")

        # Revert patterns selection
        if task.revert_patterns is not None:
            revert_patterns = list(task.revert_patterns)
        else:
            # Revert changes to test files
            revert_patterns = [
                # Some tasks expect the agent to make changes to build files, so these should not be reverted.
                # "**/build.gradle.kts",
                # "**/build/**",
                "**/androidTest/**",
                "**/androidTests/**",
                "**/src/*Test/**",
                "**/testFixtures/**",
                "**/[tT]est/**",
                "**/[tT]esting/**",
                "**/[tT]ests/**",
                "**/*Test.*",
                "**/*Tests.*",
                "**/test.*",
                "**/tests.*",
            ]

        exclude_config = ":!*.gradle.kts"
        diagnostics = []
        if task.test_files:
            revert_patterns.extend(task.test_files)

        if not keep_tests:
            # Revert changes to test files.
            for pattern in revert_patterns:
                logger.info(
                    f"Instance {task.instance_id}: Reverting pattern: {pattern}"
                )

                shell.run_command(
                    f"git checkout HEAD -- '{pattern}' '{exclude_config}'",
                    cwd=str(work_dir),
                )

            # Remove untracked test files
            for pattern in revert_patterns:
                logger.info(f"Instance {task.instance_id}: Cleaning pattern: {pattern}")

                shell.run_command(
                    f"git clean -fd '{pattern}' -- '{exclude_config}'",
                    cwd=str(work_dir),
                )

            # Apply test patch
            if task.test_patch_file and task.test_patch_file.exists():
                logger.info(
                    f"Instance {task.instance_id}: Applying test patch: {task.test_patch_file.name}..."
                )
                result = shell.run_command(
                    f"git apply {task.test_patch_file.resolve().as_posix()}",
                    cwd=str(work_dir),
                )
                if result.stdout:
                    logger.info(f"git apply (test) patch stdout: {result.stdout}")
                if result.stderr:
                    logger.info(f"git apply (test) patch stderr: {result.stderr}")
                if result.exit_code != 0:
                    return BenchmarkResult(
                        score=0.0,
                        diagnostics=[f"git apply (test) patch failed: {result.stderr}"],
                        status=Status.INFRA_FAILURE_SETUP_ISSUE,
                    )
        else:
            logger.info(
                f"Instance {task.instance_id}: Skipping reverting and cleaning of test files as keep_tests is enabled."
            )

        # Run after agent commands
        if task.after_agent_commands:
            logger.info(
                f"Instance {task.instance_id}: Running after agent commands: {task.after_agent_commands}"
            )
            if not helpers.run_after_agent_commands(
                task.after_agent_commands, str(work_dir)
            ):
                diagnostics.append("Failed to run after agent commands.")
                return BenchmarkResult(
                    score=0.0,
                    diagnostics=diagnostics,
                    status=Status.AGENT_FAILED_AFTER_CMD,
                )

        # Check project's build status
        if not helpers.can_compile_successfully(task.build_commands, str(work_dir)):
            diagnostics.append("Project failed to compile.")
            return BenchmarkResult(
                score=0.0,
                diagnostics=diagnostics,
                status=Status.AGENT_FAILED_BUILD,
            )

        # Normalize composable lambda hash names in test results.
        pass_to_pass_tests_list = [
            re.sub(
                r"ComposableLambdaImpl@[a-zA-Z0-9]+(?=\))", "ComposableLambdaImpl", s
            )
            for s in task.pass_to_pass_tests or []
        ]
        fail_to_pass_tests_list = [
            re.sub(
                r"ComposableLambdaImpl@[a-zA-Z0-9]+(?=\))", "ComposableLambdaImpl", s
            )
            for s in task.fail_to_pass_tests or []
        ]

        must_pass_tests = set(pass_to_pass_tests_list + fail_to_pass_tests_list)
        all_tests_must_pass = len(must_pass_tests) == 0
        if all_tests_must_pass:
            diagnostics.append(
                "pass_to_pass and fail_to_pass tests are not specified in the yaml, verifying all tests."
            )
        else:
            diagnostics.append(
                f"Verifying {len(pass_to_pass_tests_list)} pass_to_pass tests and {len(fail_to_pass_tests_list)} fail_to_pass tests."
            )

        # Aggregate test results across all command invocations
        all_passed_tests: set[str] = set()
        all_failed_tests: set[str] = set()
        validation_results: dict[str, bool] = {}

        old_fashioned_test_naming = True
        # Structured test names use {TaskName}#Test {testName}({testClass})
        TEST_NAME_REGEX = r"^\w+#Test"
        if (
            fail_to_pass_tests_list
            and re.match(TEST_NAME_REGEX, fail_to_pass_tests_list[0])
        ) or (
            pass_to_pass_tests_list
            and re.match(TEST_NAME_REGEX, pass_to_pass_tests_list[0])
        ):
            old_fashioned_test_naming = False

        test_attempts = 0
        status = Status.AGENT_FAILED_TEST
        # Run tests multiple times to prevent flakes marking a test as failed incorrectly
        while (
            test_attempts < config.emulator_config.test_retry_attempts
            and status != Status.PASSED
        ):
            # Start emulator
            if any("AndroidTest" in t for t in task.test_commands):
                try:
                    emulator_process = helpers.start_and_wait_for_emulator(
                        log_file,
                        task.env_config.emulator_name,
                        timeout_seconds=config.emulator_config.emulator_boot_timeout,
                    )
                except helpers.EmulatorMissingError as e:
                    logger.error(f"Emulator missing: {e}")
                    return BenchmarkResult(
                        score=0.0,
                        diagnostics=[str(e)],
                        status=Status.INFRA_FAILURE_EMULATOR_STARTUP,
                    )
                except Exception as e:
                    logger.error(f"Failed to start emulator: {e}")
                    return BenchmarkResult(
                        score=0.0,
                        diagnostics=[f"Failed to start emulator: {e}"],
                        status=Status.INFRA_FAILURE_EMULATOR_STARTUP,
                    )
            test_attempts = test_attempts + 1
            logger.info("=" * 70)
            logging.info(f"Running test attempt: {test_attempts}")
            diagnostics.append(f"Running test attempt: {test_attempts}")
            logger.info("=" * 70)
            status = _run_tests(
                task,
                work_dir,
                all_tests_must_pass,
                diagnostics,
                all_passed_tests,
                all_failed_tests,
                old_fashioned_test_naming,
            )

            # Guard against flakes by assuming if a test passed on any run, it is a pass
            all_failed_tests = all_failed_tests - all_passed_tests

            # After all commands, check if any must_pass test failed (across all invocations)
            if status == Status.PASSED and not all_tests_must_pass:
                failed_must_pass = must_pass_tests & all_failed_tests
                not_passed_must_pass = must_pass_tests - all_passed_tests
                if failed_must_pass:
                    for failed_test in sorted(failed_must_pass):
                        diagnostics.append(f"Must Pass test failed: '{failed_test}'")
                    status = Status.AGENT_FAILED_TEST
                elif not_passed_must_pass:
                    # It would reach here if:
                    # 1. Build is successful, so all_passed_tests and/or all_failed_tests are non empty.
                    # 2. not_passed_must_pass tests are not in either all_passed_tests or all_failed_tests.
                    # So we can say that gradle did not run those tests.
                    for not_passed_test in sorted(not_passed_must_pass):
                        diagnostics.append(
                            f"Must Pass test wasn't executed: '{not_passed_test}'"
                        )
                    status = Status.AGENT_MISSING_REQUIRED_TEST_RESULTS
            diagnostics.append(f"Test attempt {test_attempts}: {status}")
            logger.info("=" * 70)

        # Get passing and failing tests to calculate f2p and p2p for enriched tasks
        exported_passed_tests: set[str] = set()
        exported_failed_tests: set[str] = set()
        if export_tests:
            # Run tests multiple times to filter out flaky tests
            for test_attempts in range(
                1, config.emulator_config.test_retry_attempts + 1
            ):
                logger.info("=" * 70)
                logging.info(f"Running test attempt: {test_attempts}")
                diagnostics.append(f"Running test attempt: {test_attempts}")
                logger.info("=" * 70)
                _get_test_results(
                    task,
                    work_dir,
                    exported_passed_tests,
                    exported_failed_tests,
                    is_first_attempt=test_attempts == 1,
                )

        validation_results = {}
        global_script_failed = False
        global_script_result = None
        task_script_failed = False
        task_script_result = None

        # Clear any previous validation results file to ensure a clean slate
        check_results_file = Path("/logs/verifier/validate_results.txt")
        if check_results_file.exists():
            try:
                check_results_file.unlink()
                logger.info("Cleared previous validate_results.txt file.")
            except Exception as e:
                logger.error(f"Failed to clear previous check results file: {e}")

        env = os.environ.copy()
        task_scoring = getattr(task, "scoring", None) or {}
        global_checks = task_scoring.get("global_checks") or {}
        if isinstance(global_checks, dict):
            skip_list = global_checks.get("skip", [])
            if isinstance(skip_list, list):
                for check_name in skip_list:
                    env_key = f"SKIP_{str(check_name).upper()}"
                    env[env_key] = "1"

        # 1. Run global validation script (bash)
        global_validation_file = Path(__file__).parent / "scoring" / "validate.sh"
        if global_validation_file.exists():
            logger.info(
                f"Instance {task.instance_id}: Running global validation script: {global_validation_file}"
            )
            os.chmod(global_validation_file, 0o755)
            script_command = f"bash {global_validation_file.resolve().as_posix()}"
            result = shell.run_command(script_command, cwd=str(work_dir), env=env)
            logger.info(
                f"Instance {task.instance_id}: Global validation script output: {result.stdout}\n{result.stderr}"
            )
            global_script_result = result
            if result.exit_code != 0:
                global_script_failed = True
        else:
            logger.info("No global validation script present")

        # 2. Run task-specific validation script (bash)
        if task.validation_file and task.validation_file.exists():
            logger.info(
                f"Instance {task.instance_id}: Running validation script: {task.validation_file}"
            )
            script_command = f"bash {task.validation_file.resolve().as_posix()}"
            result = shell.run_command(script_command, cwd=str(work_dir))
            logger.info(
                f"Instance {task.instance_id}: Validation script output: {result.stdout}\n{result.stderr}"
            )
            if result.exit_code != 0:
                task_script_failed = True
                task_script_result = result
        else:
            logger.info("No task-specific validation script present")

        # 3. Read validation checks results (Flat Text)
        check_results_file = Path("/logs/verifier/validate_results.txt")
        validation_messages = {}
        if check_results_file.exists():
            try:
                with open(check_results_file, "r") as f:
                    for line in f:
                        line = line.strip()
                        if not line or line.startswith("#"):
                            continue
                        k, v = line.split(":", 1)
                        val_str = v.strip()
                        message = ""
                        # If a pipe "|" is present, extract the rich reasoning message
                        if " | " in val_str:
                            val_str, message = val_str.split(" | ", 1)

                        try:
                            validation_results[k.strip()] = float(val_str)
                        except ValueError:
                            validation_results[k.strip()] = (
                                1.0 if val_str.lower() == "pass" else 0.0
                            )
                        if message:
                            validation_messages[k.strip()] = message
                logger.info(f"Loaded check results (txt): {validation_results}")
            except Exception as e:
                logger.error(f"Failed to read check results: {e}")

        code_quality_score = None
        code_quality_violations = None
        code_quality_file = Path("/logs/verifier/code_quality.json")
        if code_quality_file.exists():
            try:
                with open(code_quality_file, "r") as f:
                    cq_data = json.load(f)
                    if "score" in cq_data and cq_data["score"] is not None:
                        code_quality_score = float(cq_data["score"])
                    if (
                        "violations_count" in cq_data
                        and cq_data["violations_count"] is not None
                    ):
                        code_quality_violations = int(cq_data["violations_count"])
                logger.info(
                    f"Loaded check results (code quality): score={code_quality_score}, violations={code_quality_violations}"
                )
            except Exception as e:
                logger.error(f"Failed to read code quality results: {e}")

        # 4. Determine final validation status
        validation_failed = (
            global_script_failed
            or task_script_failed
            or any(v < 1.0 for v in validation_results.values())
        )
        if validation_failed:
            status = Status.AGENT_FAILED_VALIDATION
            if (global_script_failed or task_script_failed) and not validation_results:
                failed_script = (
                    global_script_result if global_script_failed else task_script_result
                )
                diagnostics.append(
                    f"Validation script failed: {failed_script.stdout}|{failed_script.stderr}"
                )
            else:
                failed_checks = [k for k, v in validation_results.items() if v < 1.0]
                for check in failed_checks:
                    diagnostics.append(f"validation failed: {check}")
        else:
            if validation_results:
                logger.info("All validation checks passed.")

        # Calculate partial score
        (
            partial_score,
            scoring_breakdown,
            pass_rate,
        ) = _evaluate_weighted_scoring(
            task,
            all_passed_tests,
            all_failed_tests,
            validation_results,
            all_tests_must_pass,
            must_pass_tests,
            validation_messages=validation_messages,
            code_quality_score=code_quality_score,
            code_quality_violations=code_quality_violations,
        )

        custom_metrics = {}
        if code_quality_score is not None:
            custom_metrics["code_quality_score"] = round(code_quality_score, 4)
            if code_quality_violations is not None:
                custom_metrics["code_quality_violations"] = code_quality_violations

        if status != Status.PASSED:
            return BenchmarkResult(
                score=0.0,
                diagnostics=diagnostics,
                status=status,
                exported_passed_tests=sorted(list(exported_passed_tests)),
                exported_failed_tests=sorted(list(exported_failed_tests)),
                partial_score=partial_score,
                pass_rate=pass_rate,
                validation_results=validation_results,
                scoring_breakdown=scoring_breakdown,
                custom_metrics=custom_metrics,
            )

        if status == Status.PASSED and test_attempts > 1:
            status = Status.PASSED_FLAKY

        return BenchmarkResult(
            score=1.0,
            diagnostics=diagnostics,
            status=status,
            exported_passed_tests=sorted(list(exported_passed_tests)),
            exported_failed_tests=sorted(list(exported_failed_tests)),
            partial_score=partial_score,
            pass_rate=pass_rate,
            validation_results=validation_results,
            scoring_breakdown=scoring_breakdown,
            custom_metrics=custom_metrics,
        )
    except helpers.EmulatorStartupTimeoutError as e:
        return BenchmarkResult(
            score=0.0,
            diagnostics=[
                f"Emulator failed to start within {e.timeout_seconds} seconds"
            ],
            status=Status.INFRA_FAILURE_EMULATOR_TIMEOUT,
        )
    except helpers.EmulatorFailedToStartError as e:
        return BenchmarkResult(
            score=0.0,
            diagnostics=["Emulator failed to start"],
            status=Status.INFRA_FAILURE_EMULATOR_STARTUP,
        )
    finally:
        if output_dir:
            try:
                helpers.copy_build_outputs(work_dir, output_dir)
            except Exception as e:
                logger.error(f"Failed to copy build outputs: {e}")

        if emulator_process:
            logger.info(f"Instance {task.instance_id}: --- Stopping emulator ---")
            emulator_process.terminate()
            try:
                emulator_process.wait(timeout=30)
            except subprocess.TimeoutExpired:
                emulator_process.kill()

        # Cleanup to avoid hangs
        logger.info(
            f"Instance {task.instance_id}: Starting aggressive environment teardown..."
        )
        try:
            gradlew_path = work_dir / "gradlew"
            if gradlew_path.exists():
                subprocess.run(
                    [str(gradlew_path), "--stop"], timeout=30, capture_output=True
                )
            subprocess.run(
                ["pkill", "-9", "-f", "gradle"], timeout=10, capture_output=True
            )
        except Exception:
            pass
        try:
            subprocess.run(["adb", "kill-server"], timeout=10, capture_output=True)
        except Exception:
            pass
        subprocess.run(["pkill", "-9", "-f", "java"], capture_output=True)
        subprocess.run(["pkill", "-9", "-f", "android"], capture_output=True)


def _get_test_results(
    task,
    work_dir,
    exported_passed_tests,
    exported_failed_tests,
    is_first_attempt: bool,
):
    this_attempt_passed: set[str] = set()
    this_attempt_failed: set[str] = set()

    helpers.clean_test_outputs(str(work_dir))
    for command in task.test_commands:
        logger.info(f"Instance {task.instance_id}: Executing: {command}")
        test_result = helpers.run_tests(
            str(work_dir),
            command,
            timeout=config.emulator_config.test_execution_timeout,
            workers=config.emulator_config.gradle_workers,
            remove_task_names=False,
        )

        logger.info(f"--- Command: {command} ---")
        logger.info(f"--- Passed Tests: {len(test_result.passed_tests)} ---")
        for test in sorted(test_result.passed_tests):
            logger.info(f"  {test}")
        logger.info(f"--- Failed Tests: {len(test_result.failed_tests)} ---")
        for test in sorted(test_result.failed_tests):
            logger.info(f"  {test}")

        this_attempt_passed.update(test_result.passed_tests)
        this_attempt_failed.update(test_result.failed_tests)

    if is_first_attempt:
        exported_passed_tests.update(this_attempt_passed)
        exported_failed_tests.update(this_attempt_failed)
    else:
        exported_passed_tests.intersection_update(this_attempt_passed)
        exported_failed_tests.intersection_update(this_attempt_failed)


def _run_tests(
    task,
    work_dir,
    all_tests_must_pass,
    diagnostics,
    all_passed_tests,
    all_failed_tests,
    old_fashioned_test_naming,
):
    helpers.clean_test_outputs(str(work_dir))
    has_build_failure = False
    has_test_failure = False

    for command in task.test_commands:
        logger.info(f"Instance {task.instance_id}: Executing: {command}")
        test_result = helpers.run_tests(
            str(work_dir),
            command,
            timeout=config.emulator_config.test_execution_timeout,
            workers=config.emulator_config.gradle_workers,
            remove_task_names=old_fashioned_test_naming,
        )

        logger.info(f"--- Command: {command} ---")
        logger.info(f"--- Passed Tests: {len(test_result.passed_tests)} ---")
        for test in sorted(test_result.passed_tests):
            logger.info(f"  {test}")
        logger.info(f"--- Failed Tests: {len(test_result.failed_tests)} ---")
        for test in sorted(test_result.failed_tests):
            logger.info(f"  {test}")

        # Aggregate results
        all_passed_tests.update(test_result.passed_tests)
        all_failed_tests.update(test_result.failed_tests)

        # Context: legit/258310/1/common/eval_data_classes.py#67
        # We check result of build command if pass_to_pass + fail_to_pass tests are empty.
        # We also can't prevent flakes in this scenario.
        if not test_result.build_successful:
            diagnostics.append(f"Build failed for command: '{command}'")
            has_build_failure = True

        if len(test_result.failed_tests) > 0:
            logger.warning(f"Test command failed: '{command}'.")
            diagnostics.append(f"Test failed, command: '{command}'")
            has_test_failure = True

    # For all_tests_must_pass mode, fail if any test or build failed.
    # Note: Cannot differentiate between BUILD_FAILED and TEST_FAILED in this case,
    # so marking it as AGENT_FAILED_TEST.
    if all_tests_must_pass and (has_build_failure or has_test_failure):
        return Status.AGENT_FAILED_TEST

    return Status.PASSED


def _evaluate_weighted_scoring(
    task,
    all_passed_tests: set[str],
    all_failed_tests: set[str],
    validation_results: dict[str, float],
    all_tests_must_pass: bool,
    must_pass_tests: set[str],
    validation_messages: dict[str, str] = None,
    code_quality_score: float | None = None,
    code_quality_violations: int | None = None,
) -> tuple[float, dict, float]:
    """Calculates weighted partial score based on categories and multipliers."""
    local_passed = set(all_passed_tests)
    local_failed = set(all_failed_tests)
    local_must_pass = set(must_pass_tests)

    # Add validation results to sets
    for check_name, passed in validation_results.items():
        validation_test_name = f"validate#{check_name}"
        local_must_pass.add(validation_test_name)
        if passed == 1.0:
            local_passed.add(validation_test_name)
        else:
            local_failed.add(validation_test_name)

    # 1. Calculate pass rate and filter tests based on must-pass requirements
    if all_tests_must_pass:
        total_tests = len(local_passed) + len(local_failed)
        pass_rate = len(local_passed) / total_tests if total_tests > 0 else 0.0
    else:
        # Filter out any executed tests that are not part of the task's required tests (e.g. unit tests)
        local_passed = local_passed & local_must_pass
        local_failed = local_failed & local_must_pass

        # Any required test that did not pass (either failed or unexecuted) is a failure
        unpassed_required = local_must_pass - local_passed
        local_failed.update(unpassed_required)

        pass_rate = len(local_passed) / len(local_must_pass) if local_must_pass else 0.0

    pass_rate = round(pass_rate, 4)

    # 2. Get merged scoring configuration
    task_scoring = task.scoring or {}
    scoring_config = _get_merged_scoring_config(task_scoring)

    weights = scoring_config.get("base_weights", {})
    has_custom_weights = bool(weights)

    # 3. Construct all_tests for classification
    all_tests = []
    if all_tests_must_pass:
        # Loop over all executed tests
        executed_tests = local_passed | local_failed
        for check_name in validation_results:
            executed_tests.add(f"validate#{check_name}")

        for t in executed_tests:
            if t.startswith("validate#"):
                check_name = t.split("#", 1)[1]
                if check_name in validation_results:
                    score = validation_results[check_name]
                else:
                    score = 1.0 if t in local_passed else 0.0
            else:
                score = 1.0 if t in local_passed else 0.0
            all_tests.append((t, score))
    else:
        # Loop over all required must-pass tests
        for t in local_must_pass:
            if t.startswith("validate#"):
                check_name = t.split("#", 1)[1]
                if check_name in validation_results:
                    score = validation_results[check_name]
                else:
                    score = 1.0 if t in local_passed else 0.0
            else:
                score = 1.0 if t in local_passed else 0.0
            all_tests.append((t, score))

    if not has_custom_weights:
        # If no weights are defined, consider all possible categories from config plus 'functional'
        possible_categories = (
            set(scoring_config.get("matchers", {}).keys())
            | set(scoring_config.get("exact_matches", {}).keys())
            | {"functional"}
        )
        category_names = sorted(list(possible_categories))
    else:
        category_names = list(weights.keys())

    # 3. Classify tests into categories and identify failed multipliers
    category_stats, failed_multipliers, scoring_logs = _classify_tests_into_categories(
        all_tests,
        scoring_config,
        task,
        category_names,
        validation_messages=validation_messages,
    )

    if not has_custom_weights:
        active_categories = [
            c for c, stats in category_stats.items() if stats["total"] > 0
        ]
        if not active_categories:
            return pass_rate, {}, pass_rate
        equal_weight = round(1.0 / len(active_categories), 4)
        weights = {c: equal_weight for c in active_categories}
        remainder = 1.0 - sum(weights.values())
        if remainder != 0:
            weights[active_categories[-1]] = round(
                weights[active_categories[-1]] + remainder, 4
            )

    # 4. Perform final mathematical aggregation
    partial_score, scoring_breakdown = _calculate_final_weighted_score(
        category_stats,
        failed_multipliers,
        weights,
        scoring_logs,
        pass_rate,
        code_quality_score=code_quality_score,
        code_quality_violations=code_quality_violations,
    )

    return partial_score, scoring_breakdown, pass_rate


def _get_merged_scoring_config(task_scoring: dict) -> dict:
    """Loads common config and merges with task-specific overrides."""
    common_scoring = {}
    # Use script-relative path for portability (works in Docker and Local)
    common_scoring_path = Path(__file__).parent / "scoring/common_scoring.toml"
    if common_scoring_path.exists():
        try:
            with open(common_scoring_path, "rb") as f:
                common_scoring = tomllib.load(f)
        except Exception as e:
            logger.error(f"Error loading common_scoring.toml: {e}")

    # Extraction of rules and matchers
    task_rules = task_scoring.get("rules") or {}
    task_matchers = task_rules.get("matchers") or {}
    common_rules = common_scoring.get("rules") or {}
    common_matchers = common_rules.get("matchers") or {}

    # Start with all task-defined matchers (preserving spec.toml order)
    merged_matchers = dict(task_matchers)

    # Append remaining global default matchers that weren't overridden
    for category, patterns in common_matchers.items():
        if category not in merged_matchers:
            merged_matchers[category] = patterns

    # Merge multipliers
    merged_multipliers = common_scoring.get("multipliers", {}).get("tests", {}).copy()
    if "multipliers" in task_scoring and "tests" in task_scoring["multipliers"]:
        merged_multipliers.update(task_scoring["multipliers"]["tests"])

    # Merge exact matches
    merged_exact = common_rules.get("exact_matches", {}).copy()
    if "exact_matches" in task_rules:
        merged_exact.update(task_rules["exact_matches"])

    # Filter out categories that are not defined in base_weights (if base_weights is specified)
    base_weights = task_scoring.get("base_weights", {})
    if base_weights:
        active_categories = set(base_weights.keys())
        merged_matchers = {
            k: v for k, v in merged_matchers.items() if k in active_categories
        }
        merged_exact = {k: v for k, v in merged_exact.items() if k in active_categories}

    # Merge rules
    merged = {
        "multipliers": merged_multipliers,
        "matchers": merged_matchers,
        "exact_matches": merged_exact,
        "base_weights": base_weights,
    }

    return merged


def _classify_tests_into_categories(
    all_tests: list[tuple[str, float]],
    config: dict,
    task,
    category_names: list[str],
    validation_messages: dict[str, str] = None,
) -> tuple[dict, list[dict], list[str]]:
    """Sorts test results into category statistics and identifies failed multipliers."""
    category_stats = {c: {"passed": 0.0, "total": 0} for c in category_names}
    failed_multipliers = []
    scoring_logs = []

    multipliers = config["multipliers"]
    rules_exact = config["exact_matches"]
    rules_matchers = config["matchers"]

    for test_name, score in all_tests:
        # Check multipliers
        is_multiplier = False
        for mult_test_name, penalty in multipliers.items():
            if mult_test_name in test_name:
                is_multiplier = True
                if score < 1.0:
                    # Extract reasoning message for diagnostics
                    reasoning = "Test failed during benchmark execution."
                    if validation_messages and mult_test_name.startswith("validate#"):
                        check_key = mult_test_name.replace("validate#", "", 1)
                        reasoning = validation_messages.get(check_key, reasoning)

                    failed_multipliers.append(
                        {
                            "name": mult_test_name,
                            "value": penalty,
                            "reasoning": reasoning,
                        }
                    )
                break
        if is_multiplier:
            continue

        matched_category = None

        # Check Exact matches
        matched_exact = [
            cat
            for cat, tests in rules_exact.items()
            if test_name in tests or any(test_name == f"validate#{t}" for t in tests)
        ]
        if matched_exact:
            matched_category = matched_exact[0]
            if len(matched_exact) > 1:
                log_msg = (
                    f"Test '{test_name}' matched multiple EXACT categories: {matched_exact}. "
                    f"Defaulting to '{matched_category}' because it was defined first in the configuration."
                )
                logger.info(log_msg)
                scoring_logs.append(log_msg)

        # Check Regex/Magic matches
        if not matched_category:
            matched_regex = []
            for category, patterns in rules_matchers.items():
                for pattern in patterns:
                    is_match = False
                    if pattern == "^pass_to_pass$":
                        if (
                            task.pass_to_pass_tests
                            and test_name in task.pass_to_pass_tests
                        ):
                            is_match = True
                    elif pattern == "^fail_to_pass$":
                        if (
                            task.fail_to_pass_tests
                            and test_name in task.fail_to_pass_tests
                        ):
                            is_match = True
                    elif pattern in test_name or re.search(pattern, test_name):
                        is_match = True

                    if is_match:
                        matched_regex.append(category)
                        break

            if matched_regex:
                matched_category = matched_regex[0]
                if len(matched_regex) > 1:
                    log_msg = (
                        f"Test '{test_name}' matched multiple REGEX categories: {matched_regex}. "
                        f"Defaulting to '{matched_category}' because it was defined first in the configuration."
                    )
                    logger.info(log_msg)
                    scoring_logs.append(log_msg)

        if not matched_category:
            log_msg = f"WARNING: Test '{test_name}' did not match any category rules. It will be IGNORED and not scored."
            logger.warning(log_msg)
            scoring_logs.append(log_msg)

        if matched_category in category_stats:
            category_stats[matched_category]["total"] += 1
            category_stats[matched_category]["passed"] += score

    return category_stats, failed_multipliers, scoring_logs


def _calculate_final_weighted_score(
    category_stats: dict,
    failed_multipliers: list[dict],
    weights: dict,
    scoring_logs: list[str],
    pass_rate: float,
    code_quality_score: float | None = None,
    code_quality_violations: int | None = None,
) -> tuple[float, dict]:
    """Performs the weighted sum and applies multiplicative penalties."""
    base_score = 0.0
    breakdown_categories = {}

    total_weight = sum(float(w) for w in weights.values())
    if total_weight == 0.0:
        total_weight = 1.0

    for category, raw_weight in weights.items():
        weight = float(raw_weight) / total_weight
        stats = category_stats[category]
        rate = stats["passed"] / stats["total"] if stats["total"] > 0 else 0.0
        contribution = round(rate * weight, 4)
        base_score += contribution

        passed_val = stats["passed"]
        if passed_val == int(passed_val):
            passed_val = int(passed_val)
        else:
            passed_val = round(passed_val, 4)

        breakdown_categories[category] = {
            "passed": passed_val,
            "total": stats["total"],
            "weight": round(weight, 4),
            "raw_weight": float(raw_weight),
            "score": round(rate, 4),
            "contribution": contribution,
        }

    if code_quality_score is not None:
        breakdown_categories["code_quality"] = {
            "passed": round(code_quality_score, 4),
            "total": 1.0,
            "weight": 0.0,
            "raw_weight": 0.0,
            "score": round(code_quality_score, 4),
            "contribution": 0.0,
            "violations_count": (
                code_quality_violations if code_quality_violations is not None else 0
            ),
        }

    base_score = round(base_score, 4)
    final_score = base_score
    for item in failed_multipliers:
        final_score *= float(item["value"])

    final_score = round(final_score, 4)

    breakdown = {
        "base_score": base_score,
        "categories": breakdown_categories,
        "multipliers_applied": failed_multipliers,
        "logs": scoring_logs,
    }

    return final_score, breakdown


def save_benchmark_result(
    instance_id: str,
    result_value: BenchmarkResult,
    verifier_dir: Path,
    artifacts_dir: Path,
):
    verifier_dir.mkdir(parents=True, exist_ok=True)
    artifacts_dir.mkdir(parents=True, exist_ok=True)

    # Create scores and rewards file
    rewards_file = verifier_dir / "reward.txt"
    if result_value.score == 1.0:
        logger.info("=" * 70)
        logger.info(f"TASK COMPLETED: {instance_id} - PASSED (score: 1.0)")
        logger.info("=" * 70)

    else:
        logger.info("=" * 70)
        logger.info(f"TASK COMPLETED: {instance_id} - FAILED (score: 0.0)")
        logger.info("=" * 70)

    logger.info(f"Partial score: {result_value.partial_score}")
    rewards_file.write_text(f"{result_value.partial_score}\n")

    # Extract token counts from trajectory.json if available
    trajectory_file = Path("/logs/agent/trajectory.json")
    if trajectory_file.exists():
        try:
            trajectory_data = json.loads(trajectory_file.read_text())
            final_metrics = trajectory_data.get("final_metrics", {})
            if final_metrics:
                prompt_tokens = final_metrics.get("total_prompt_tokens", 0)
                completion_tokens = final_metrics.get("total_completion_tokens", 0)
                cached_tokens = final_metrics.get("total_cached_tokens", 0)

                result_value.used_tokens = TokenDetails(
                    completion_tokens=completion_tokens,
                    prompt_tokens=prompt_tokens,
                    total_tokens=prompt_tokens + completion_tokens,
                )
                logger.info(
                    f"Extracted tokens from trajectory: prompt={prompt_tokens}, completion={completion_tokens}"
                )
        except Exception as e:
            logger.warning(f"Could not parse trajectory for token details: {e}")

    result_data = {instance_id: result_value.to_dict()}
    scores_file = verifier_dir / "detailed_scores.json"
    scores_file.write_text(json.dumps(result_data, indent=4))

    # Copy to artifacts
    artifacts_scores = artifacts_dir / "_detailed_scores.json"
    shutil.copy(scores_file, artifacts_scores)

    logger.info(
        f"Successfully wrote results to {scores_file} and copied to {artifacts_scores}"
    )


def main(
    spec_toml_file: str,
    export_tests: bool = False,
    keep_tests: bool = False,
    disable_partial_scoring: bool = False,
):
    verifier_dir = Path("/logs/verifier")
    verifier_dir.mkdir(parents=True, exist_ok=True)
    artifacts_dir = Path("/logs/artifacts")
    artifacts_dir.mkdir(parents=True, exist_ok=True)
    task_json_data = {}

    # Read the TOML task specification
    with open(spec_toml_file, "rb") as f:
        task_json_data = tomllib.load(f)

    # Use 'id' as 'instance_id' when the latter is absent.
    if "instance_id" not in task_json_data and "id" in task_json_data:
        task_json_data["instance_id"] = task_json_data["id"]

    instance_id = task_json_data.get("instance_id", "unknown")

    try:
        task = BenchmarkTask.from_json(json_data=task_json_data)
        if task is None:
            logger.error(f"Could not create task '{instance_id}'.")
            raise Exception(f"Task creation failed for {instance_id}")

        instance_id = task.instance_id
        logger.info(f"Successfully created BenchmarkTask object for: {instance_id}")
        if keep_tests:
            logger.info(f"Instance {instance_id}: Using keep_tests=True")

        result_value = run_benchmark_task(
            task=task,
            output_dir=artifacts_dir,
            export_tests=export_tests,
            keep_tests=keep_tests,
        )

        if disable_partial_scoring:
            logger.info(
                "Disabling partial scoring: Overwriting partial_score with binary score."
            )
            result_value.partial_score = result_value.score

        save_benchmark_result(instance_id, result_value, verifier_dir, artifacts_dir)
        sys.exit(0)

    except Exception as e:
        logger.error(f"Error running BenchmarkTask {instance_id}: {e}")
        logger.error(traceback.format_exc())
        result_data = {instance_id: f"Error: {e}"}
        try:
            scores_file = verifier_dir / "detailed_scores.json"
            scores_file.write_text(json.dumps(result_data, indent=4))
            shutil.copy(scores_file, artifacts_dir / "_detailed_scores.json")
        except Exception:
            pass
        sys.exit(0)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Run a benchmark task locally.")
    parser.add_argument(
        "--spec-toml-file",
        "--task-toml-file",
        dest="spec_toml_file",
        type=str,
        default="/tests/spec.toml",
        help="Path to the TOML file containing the task specification.",
    )
    parser.add_argument(
        "--export-tests",
        action="store_true",
        help="Export the test files.",
    )
    parser.add_argument(
        "--keep-tests",
        action="store_true",
        help="Keep test files instead of reverting them.",
    )
    parser.add_argument(
        "--disable-partial-scoring",
        action="store_true",
        help="Disable partial scoring and return binary score.",
    )
    args = parser.parse_args()
    keep_tests = args.keep_tests or os.path.exists("/tmp/open_test.patch")
    if keep_tests:
        logger.info(
            f"keep_tests enabled (args.keep_tests={args.keep_tests}, open_test.patch exists={os.path.exists('/tmp/open_test.patch')})"
        )
    main(
        spec_toml_file=args.spec_toml_file,
        export_tests=args.export_tests,
        keep_tests=keep_tests,
        disable_partial_scoring=args.disable_partial_scoring,
    )