Elffuss BraidHub

kikocis/auto-code-rover public

bb93e5a19c96 · 11.0 KiBRawPermalink
1from __future__ import annotations
2
3import os
4import subprocess
5from abc import ABC, abstractmethod
6from dataclasses import dataclass
7from os.path import join as pjoin
8from tempfile import mkstemp
9
10import app.utils as apputils
11from app import globals, log
12from app import utils as app_utils
13from app.api.eval_helper import (
14 ResolvedStatus,
15 get_eval_report,
16 get_logs_eval,
17 get_resolution_status,
18)
19from app.log import log_and_print
20
21
22class 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)
54class 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,
132 task.env_name,
133 capture_output=True,
134 text=True,
135 )
136 if cp.returncode != 0:
137 log_and_print(cp.stderr)
138 raise RuntimeError(f"Command {task.install_cmd} failed.")
139 # (3) xmlrunner for our custom run_test; coverage required for fault localization
140 other_install_cmd = (
141 "python -m pip install xmlrunner coverage pytest pytest-cov"
142 )
143 cp = apputils.run_string_cmd_in_conda(
144 other_install_cmd,
145 task.env_name,
146 capture_output=True,
147 text=True,
148 )
149 if cp.returncode != 0:
150 log_and_print(cp.stderr)
151 raise RuntimeError(f"Command {other_install_cmd} failed.")
152
153 def _apply_test_patch(self) -> None:
154 """
155 Apply the patch to testcases, as supplied by the benchmark.
156 This step brings in all the new tests and testcase modifications.
157 """
158 task = self
159
160 if not task.test_patch:
161 # no patches to tests are found
162 return
163 with apputils.cd(task.project_path):
164 # (1) write test_patch to a temp file
165 test_patch_path = pjoin(task.project_path, "swe_bench_tests.patch")
166 with open(test_patch_path, "w") as f:
167 f.write(task.test_patch)
168 # (2) apply these patches
169 # FIXME: check for failure here
170 apply_cmd = ["git", "apply", test_patch_path]
171 cp = apputils.run_command(apply_cmd, capture_output=True, text=True)
172 if cp.returncode != 0:
173 log_and_print(cp.stderr)
174 raise RuntimeError(f"Command {apply_cmd} failed.")
175 # (3) remove the temp file, which is not so important
176 os.remove(test_patch_path)
177
178 def validate(self, patch_file: str) -> tuple[bool, str, str]:
179 # (1) apply the patch to source code
180 with app_utils.cd(self.project_path):
181 apply_cmd = ["git", "apply", patch_file]
182 cp = app_utils.run_command(apply_cmd, capture_output=False, text=True)
183 if cp.returncode != 0:
184 # patch application failed
185 raise RuntimeError(f"Error applying patch: {cp.stderr}")
186
187 # (2) run the modified program against the test suite
188 log_and_print("[Validation] Applied patch. Going to run test suite.")
189
190 _, log_file = mkstemp(suffix=".log", prefix="pyval-", text=True)
191 tests_passed, msg = self._run_test_suite_for_correctness(log_file)
192
193 # (3) revert the patch to source code
194 with app_utils.cd(self.project_path):
195 app_utils.repo_clean_changes()
196
197 log_and_print(
198 f"[Validation] Finishing. Result is {tests_passed}. Message: {msg}.",
199 )
200 return tests_passed, msg, log_file
201
202 def _run_test_suite_for_correctness(self, log_file: str) -> tuple[bool, str]:
203 """
204 Run the developer test suite, and record pass/fail results.
205 The goal is to check correctness of a patched program, while returning
206 the error message from the failed tests.
207
208 Returns:
209 - True if all tests passed; False otherwise.
210 - A message associated with the failure reason. Empty string if all tests passed.
211 """
212 TESTS_ERROR = ">>>>> Tests Errored"
213 TESTS_FAILED = ">>>>> Some Tests Failed"
214 TESTS_PASSED = ">>>>> All Tests Passed"
215 TESTS_TIMEOUT = ">>>>> Tests Timed Out"
216
217 error_message = ""
218
219 # Run test suite and check whether passing tests still pass and
220 # failing tests become passing.
221 # This part is heavily referenced from SWE-bench code
222 with app_utils.cd(self.project_path):
223 try:
224 cp = app_utils.run_string_cmd_in_conda(
225 self.test_cmd,
226 self.env_name,
227 timeout=globals.test_exec_timeout,
228 capture_output=True,
229 text=True,
230 )
231 with open(log_file, "w") as f:
232 f.write("Output:\n")
233 f.write(cp.stdout)
234 f.write(cp.stderr)
235 if cp.returncode != 0:
236 f.write(f"\n{TESTS_FAILED}\n")
237 else:
238 f.write(f"\n{TESTS_PASSED}\n")
239 except subprocess.TimeoutExpired:
240 with open(log_file, "a") as f:
241 f.write(
242 f"{TESTS_TIMEOUT} after {globals.test_exec_timeout} seconds\n"
243 )
244 except Exception as e:
245
246 # Test command run failed. This does not necessarily mean that tests
247 # failed. However, we regard this as failure in execution.
248
249 with open(log_file, "a") as f:
250 f.write(f"{TESTS_ERROR}: {e}")
251
252 # Now test log has been written; process it
253 eval_status, parse_ok = get_logs_eval(self.repo_name, log_file)
254 log.log_and_print(f"[Run test-suite] Result of parsing test log: {parse_ok}")
255 log.log_and_print(f"[Run test-suite] Eval status: {eval_status}")
256
257 if not parse_ok:
258 # log file says test execution has error
259 with open(log_file) as f:
260 error_message = f.read()
261 return False, error_message
262
263 eval_ref = {
264 "FAIL_TO_PASS": self.testcases_failing,
265 "PASS_TO_PASS": self.testcases_passing,
266 }
267 eval_result = get_eval_report(eval_status, eval_ref)
268 log.log_and_print(f"[Run test-suite] Eval result: {eval_result}")
269
270 resolution_status = get_resolution_status(eval_result)
271 log.log_and_print(f"[Run test-suite] Resolution status: {resolution_status}")
272 if resolution_status == ResolvedStatus.FULL:
273 log.log_and_print("[Run test-suite] Returning True since all resolved.")
274 return True, ""
275
276 else:
277 # FIXME: The current failure message is simple; maybe can add failure reasons to it
278 log.log_and_print(
279 "[Run test-suite] Returning False since some tests failed."
280 )
281 error_message = "Some tests have failed."
282 return False, error_message
283
284
285@dataclass(kw_only=True)
286class PlainTask(Task):
287 """
288 Tasks that only contain a codebase and an issue descripion (no test suite).
289 """
290
291 commit_hash: str
292 local_path: str
293 problem_statement: str
294
295 @property
296 def project_path(self) -> str:
297 return self.local_path
298
299 def setup_project(self) -> None:
300 with apputils.cd(self.project_path):
301 apputils.repo_reset_and_clean_checkout(self.commit_hash)
302
303 def reset_project(self) -> None:
304 with apputils.cd(self.project_path):
305 apputils.repo_reset_and_clean_checkout(self.commit_hash)
306
307 def get_issue_statement(self) -> str:
308 return self.problem_statement
309
310 def validate(self, patch_file: str) -> tuple[bool, str, str]:
311 raise NotImplementedError("Cannot do validation for live issues for now")