| 1 | from __future__ import annotations |
| 2 | |
| 3 | import os |
| 4 | import subprocess |
| 5 | from abc import ABC, abstractmethod |
| 6 | from dataclasses import dataclass |
| 7 | from os.path import join as pjoin |
| 8 | from tempfile import mkstemp |
| 9 | |
| 10 | import app.utils as apputils |
| 11 | from app import globals, log |
| 12 | from app import utils as app_utils |
| 13 | from app.api.eval_helper import ( |
| 14 | ResolvedStatus, |
| 15 | get_eval_report, |
| 16 | get_logs_eval, |
| 17 | get_resolution_status, |
| 18 | ) |
| 19 | from app.log import log_and_print |
| 20 | |
| 21 | |
| 22 | class Task(ABC): |
| 23 | @property |
| 24 | @abstractmethod |
| 25 | def project_path(self) -> str: |
| 26 | raise NotImplementedError("abstract method") |
| 27 | |
| 28 | @abstractmethod |
| 29 | def get_issue_statement(self) -> str: |
| 30 | raise NotImplementedError("abstract method") |
| 31 | |
| 32 | @abstractmethod |
| 33 | def setup_project(self) -> None: |
| 34 | """Set up the project before starting to resolve the task.""" |
| 35 | raise NotImplementedError("abstract method") |
| 36 | |
| 37 | @abstractmethod |
| 38 | def reset_project(self) -> None: |
| 39 | """Reset project to initial state.""" |
| 40 | raise NotImplementedError("abstract method") |
| 41 | |
| 42 | @abstractmethod |
| 43 | def validate(self, patch_file: str) -> tuple[bool, str, str]: |
| 44 | """ |
| 45 | Returns: |
| 46 | - Whether this patch has made the test suite pass. |
| 47 | - Error message when running the test suite. |
| 48 | - Path of written log file |
| 49 | """ |
| 50 | raise NotImplementedError |
| 51 | |
| 52 | |
| 53 | @dataclass(kw_only=True) |
| 54 | class SweTask(Task): |
| 55 | task_id: str |
| 56 | problem_statement: str |
| 57 | repo_path: str |
| 58 | commit: str |
| 59 | env_name: str |
| 60 | repo_name: str |
| 61 | pre_install_cmds: list[str] |
| 62 | install_cmd: str |
| 63 | test_cmd: str |
| 64 | test_patch: str |
| 65 | testcases_passing: list[str] |
| 66 | testcases_failing: list[str] |
| 67 | |
| 68 | @property |
| 69 | def project_path(self) -> str: |
| 70 | return self.repo_path |
| 71 | |
| 72 | @project_path.setter |
| 73 | def project_path(self, value: str) -> None: |
| 74 | self.repo_path = value |
| 75 | |
| 76 | def get_issue_statement(self) -> str: |
| 77 | return self.problem_statement |
| 78 | |
| 79 | def setup_project(self) -> None: |
| 80 | # get the correct version of the project and commit-specific pip install |
| 81 | task = self |
| 82 | with apputils.cd(task.project_path): |
| 83 | apputils.repo_reset_and_clean_checkout(task.commit) |
| 84 | |
| 85 | # Install task-specific dependencies |
| 86 | do_install = ( |
| 87 | globals.enable_sbfl |
| 88 | or globals.enable_validation |
| 89 | or globals.only_save_sbfl_result |
| 90 | ) |
| 91 | if do_install: |
| 92 | self._do_install() |
| 93 | |
| 94 | # apply the test modifications to this task |
| 95 | self._apply_test_patch() |
| 96 | |
| 97 | # commit the current changes, so that resetting later do not erase them |
| 98 | with apputils.cd(task.project_path): |
| 99 | apputils.repo_commit_current_changes() |
| 100 | |
| 101 | def reset_project(self) -> None: |
| 102 | with apputils.cd(self.repo_path): |
| 103 | apputils.repo_reset_and_clean_checkout(self.commit) |
| 104 | |
| 105 | def _do_install(self): |
| 106 | """Do left-over install commands after setting up. |
| 107 | The commands being run here are 'pre_install' and 'install' defined in |
| 108 | harness/constants.py file in SWE-bench. |
| 109 | """ |
| 110 | task = self |
| 111 | if not task.pre_install_cmds and not task.install_cmd: |
| 112 | # no command for installation, skip |
| 113 | return |
| 114 | with apputils.cd(task.project_path): |
| 115 | # (0) For matplotlib, qhull tarball download |
| 116 | # just fails, so we need to pre-install the system version and use it |
| 117 | if "matplotlib" in task.task_id: |
| 118 | with open("mplsetup.cfg", "w") as f: |
| 119 | f.write("[libs]\nsystem_qhull = true") |
| 120 | # (1) pre-install |
| 121 | for cmd in task.pre_install_cmds: |
| 122 | cp = apputils.run_string_cmd_in_conda( |
| 123 | cmd, task.env_name, capture_output=True, text=True |
| 124 | ) |
| 125 | if cp.returncode != 0: |
| 126 | log_and_print(cp.stderr) |
| 127 | raise RuntimeError(f"Command {cmd} failed.") |
| 128 | |
| 129 | # (2) install |
| 130 | cp = apputils.run_string_cmd_in_conda( |
| 131 | task.install_cmd, task.env_name, capture_output=True, text=True |
| 132 | ) |
| 133 | if cp.returncode != 0: |
| 134 | log_and_print(cp.stderr) |
| 135 | raise RuntimeError(f"Command {task.install_cmd} failed.") |
| 136 | # (3) xmlrunner for our custom run_test; coverage required for fault localization |
| 137 | other_install_cmd = ( |
| 138 | "python -m pip install xmlrunner coverage pytest pytest-cov" |
| 139 | ) |
| 140 | cp = apputils.run_string_cmd_in_conda( |
| 141 | other_install_cmd, task.env_name, capture_output=True, text=True |
| 142 | ) |
| 143 | if cp.returncode != 0: |
| 144 | log_and_print(cp.stderr) |
| 145 | raise RuntimeError(f"Command {other_install_cmd} failed.") |
| 146 | |
| 147 | def _apply_test_patch(self) -> None: |
| 148 | """ |
| 149 | Apply the patch to testcases, as supplied by the benchmark. |
| 150 | This step brings in all the new tests and testcase modifications. |
| 151 | """ |
| 152 | task = self |
| 153 | |
| 154 | if not task.test_patch: |
| 155 | # no patches to tests are found |
| 156 | return |
| 157 | with apputils.cd(task.project_path): |
| 158 | # (1) write test_patch to a temp file |
| 159 | test_patch_path = pjoin(task.project_path, "swe_bench_tests.patch") |
| 160 | with open(test_patch_path, "w") as f: |
| 161 | f.write(task.test_patch) |
| 162 | # (2) apply these patches |
| 163 | # FIXME: check for failure here |
| 164 | apply_cmd = ["git", "apply", test_patch_path] |
| 165 | cp = apputils.run_command(apply_cmd, capture_output=True, text=True) |
| 166 | if cp.returncode != 0: |
| 167 | log_and_print(cp.stderr) |
| 168 | raise RuntimeError(f"Command {apply_cmd} failed.") |
| 169 | # (3) remove the temp file, which is not so important |
| 170 | os.remove(test_patch_path) |
| 171 | |
| 172 | def validate(self, patch_file: str) -> tuple[bool, str, str]: |
| 173 | # (1) apply the patch to source code |
| 174 | with app_utils.cd(self.project_path): |
| 175 | apply_cmd = ["git", "apply", patch_file] |
| 176 | cp = app_utils.run_command(apply_cmd, capture_output=False, text=True) |
| 177 | if cp.returncode != 0: |
| 178 | # patch application failed |
| 179 | raise RuntimeError(f"Error applying patch: {cp.stderr}") |
| 180 | |
| 181 | # (2) run the modified program against the test suite |
| 182 | log_and_print("[Validation] Applied patch. Going to run test suite.") |
| 183 | |
| 184 | _, log_file = mkstemp(suffix=".log", prefix="pyval-", text=True) |
| 185 | tests_passed, msg = self._run_test_suite_for_correctness(log_file) |
| 186 | |
| 187 | # (3) revert the patch to source code |
| 188 | with app_utils.cd(self.project_path): |
| 189 | app_utils.repo_clean_changes() |
| 190 | |
| 191 | log_and_print( |
| 192 | f"[Validation] Finishing. Result is {tests_passed}. Message: {msg}." |
| 193 | ) |
| 194 | return tests_passed, msg, log_file |
| 195 | |
| 196 | def _run_test_suite_for_correctness(self, log_file: str) -> tuple[bool, str]: |
| 197 | """ |
| 198 | Run the developer test suite, and record pass/fail results. |
| 199 | The goal is to check correctness of a patched program, while returning |
| 200 | the error message from the failed tests. |
| 201 | |
| 202 | Returns: |
| 203 | - True if all tests passed; False otherwise. |
| 204 | - A message associated with the failure reason. Empty string if all tests passed. |
| 205 | """ |
| 206 | TESTS_ERROR = ">>>>> Tests Errored" |
| 207 | TESTS_FAILED = ">>>>> Some Tests Failed" |
| 208 | TESTS_PASSED = ">>>>> All Tests Passed" |
| 209 | TESTS_TIMEOUT = ">>>>> Tests Timed Out" |
| 210 | |
| 211 | error_message = "" |
| 212 | |
| 213 | # Run test suite and check whether passing tests still pass and |
| 214 | # failing tests become passing. |
| 215 | # This part is heavily referenced from SWE-bench code |
| 216 | with app_utils.cd(self.project_path): |
| 217 | try: |
| 218 | cp = app_utils.run_string_cmd_in_conda( |
| 219 | self.test_cmd, |
| 220 | self.env_name, |
| 221 | timeout=globals.test_exec_timeout, |
| 222 | capture_output=True, |
| 223 | text=True, |
| 224 | ) |
| 225 | with open(log_file, "w") as f: |
| 226 | f.write("Output:\n") |
| 227 | f.write(cp.stdout) |
| 228 | f.write(cp.stderr) |
| 229 | if cp.returncode != 0: |
| 230 | f.write(f"\n{TESTS_FAILED}\n") |
| 231 | else: |
| 232 | f.write(f"\n{TESTS_PASSED}\n") |
| 233 | except subprocess.TimeoutExpired: |
| 234 | with open(log_file, "a") as f: |
| 235 | f.write( |
| 236 | f"{TESTS_TIMEOUT} after {globals.test_exec_timeout} seconds\n" |
| 237 | ) |
| 238 | except Exception as e: |
| 239 | |
| 240 | # Test command run failed. This does not necessarily mean that tests |
| 241 | # failed. However, we regard this as failure in execution. |
| 242 | |
| 243 | with open(log_file, "a") as f: |
| 244 | f.write(f"{TESTS_ERROR}: {e}") |
| 245 | |
| 246 | # Now test log has been written; process it |
| 247 | eval_status, parse_ok = get_logs_eval(self.repo_name, log_file) |
| 248 | log.log_and_print(f"[Run test-suite] Result of parsing test log: {parse_ok}") |
| 249 | log.log_and_print(f"[Run test-suite] Eval status: {eval_status}") |
| 250 | |
| 251 | if not parse_ok: |
| 252 | # log file says test execution has error |
| 253 | with open(log_file) as f: |
| 254 | error_message = f.read() |
| 255 | return False, error_message |
| 256 | |
| 257 | eval_ref = { |
| 258 | "FAIL_TO_PASS": self.testcases_failing, |
| 259 | "PASS_TO_PASS": self.testcases_passing, |
| 260 | } |
| 261 | eval_result = get_eval_report(eval_status, eval_ref) |
| 262 | log.log_and_print(f"[Run test-suite] Eval result: {eval_result}") |
| 263 | |
| 264 | resolution_status = get_resolution_status(eval_result) |
| 265 | log.log_and_print(f"[Run test-suite] Resolution status: {resolution_status}") |
| 266 | if resolution_status == ResolvedStatus.FULL: |
| 267 | log.log_and_print("[Run test-suite] Returning True since all resolved.") |
| 268 | return True, "" |
| 269 | |
| 270 | else: |
| 271 | # FIXME: The current failure message is simple; maybe can add failure reasons to it |
| 272 | log.log_and_print( |
| 273 | "[Run test-suite] Returning False since some tests failed." |
| 274 | ) |
| 275 | error_message = "Some tests have failed." |
| 276 | return False, error_message |
| 277 | |
| 278 | |
| 279 | @dataclass(kw_only=True) |
| 280 | class PlainTask(Task): |
| 281 | """ |
| 282 | Tasks that only contain a codebase and an issue descripion (no test suite). |
| 283 | """ |
| 284 | |
| 285 | commit_hash: str |
| 286 | local_path: str |
| 287 | problem_statement: str |
| 288 | |
| 289 | @property |
| 290 | def project_path(self) -> str: |
| 291 | return self.local_path |
| 292 | |
| 293 | def setup_project(self) -> None: |
| 294 | with apputils.cd(self.project_path): |
| 295 | apputils.repo_reset_and_clean_checkout(self.commit_hash) |
| 296 | |
| 297 | def reset_project(self) -> None: |
| 298 | with apputils.cd(self.project_path): |
| 299 | apputils.repo_reset_and_clean_checkout(self.commit_hash) |
| 300 | |
| 301 | def get_issue_statement(self) -> str: |
| 302 | return self.problem_statement |
| 303 | |
| 304 | def validate(self, patch_file: str) -> tuple[bool, str, str]: |
| 305 | raise NotImplementedError("Cannot do validation for live issues for now") |