| 1 | """ |
| 2 | Post-process the output of the inference workflow. |
| 3 | """ |
| 4 | |
| 5 | import json |
| 6 | import os |
| 7 | import shutil |
| 8 | import subprocess |
| 9 | from collections import defaultdict |
| 10 | from collections.abc import Mapping |
| 11 | from enum import Enum |
| 12 | from glob import glob |
| 13 | from os.path import join as pjoin |
| 14 | from shutil import move |
| 15 | |
| 16 | from app import utils as apputils |
| 17 | from app.api.patch_utils import apply_edit, parse_edits |
| 18 | from app.model import common |
| 19 | |
| 20 | |
| 21 | def count_and_organize_tasks( |
| 22 | task_list: list[str], task_list_name: str, task_exp_names: list[str], expr_dir: str |
| 23 | ): |
| 24 | """ |
| 25 | A helper for extract_diff_patches. |
| 26 | Generate a message to log the number of tasks in one list. |
| 27 | Also organizes tasks in this list to a new folder in the experiment directory. |
| 28 | |
| 29 | Args: |
| 30 | - task_list: a list of task ids |
| 31 | - task_list_name: name for this list (one of the four categories) |
| 32 | - task_exp_names: list of individual experiment result dir names |
| 33 | - expr_dir: the overall experiment directory. |
| 34 | |
| 35 | Returns: |
| 36 | - message, a string message to be written to log file. |
| 37 | """ |
| 38 | total_num_tasks = len(task_exp_names) |
| 39 | |
| 40 | # (1) get the message ready |
| 41 | message = f"Total number of tasks in {task_list_name}: {len(task_list)}/{total_num_tasks}.\n" |
| 42 | for task in task_list: |
| 43 | message += f"\t {task}\n" |
| 44 | |
| 45 | # (2) create a new dir and move the experiment results of these tasks there |
| 46 | new_dir = pjoin(expr_dir, task_list_name) |
| 47 | os.makedirs(new_dir, exist_ok=True) |
| 48 | for task_exp_name in task_exp_names: |
| 49 | if any([task_exp_name.startswith(x) for x in task_list]): |
| 50 | # this expr dir belongs to a task in the list |
| 51 | old_dir = pjoin(expr_dir, task_exp_name) |
| 52 | shutil.move(old_dir, new_dir) |
| 53 | |
| 54 | return message |
| 55 | |
| 56 | |
| 57 | # track status of patch extraction |
| 58 | class ExtractStatus(str, Enum): |
| 59 | APPLICABLE_PATCH = "APPLICABLE_PATCH" |
| 60 | MATCHED_BUT_EMPTY_ORIGIN = "MATCHED_BUT_EMPTY_ORIGIN" |
| 61 | MATCHED_BUT_EMPTY_DIFF = "MATCHED_BUT_EMPTY_DIFF" |
| 62 | RAW_PATCH_BUT_UNMATCHED = "RAW_PATCH_BUT_UNMATCHED" |
| 63 | RAW_PATCH_BUT_UNPARSED = "RAW_PATCH_BUT_UNPARSED" |
| 64 | NO_PATCH = "NO_PATCH" |
| 65 | IS_VALID_JSON = "IS_VALID_JSON" |
| 66 | NOT_VALID_JSON = "NOT_VALID_JSON" |
| 67 | |
| 68 | def __lt__(self, other): |
| 69 | # order from min to max |
| 70 | order = [ |
| 71 | self.NO_PATCH, |
| 72 | self.RAW_PATCH_BUT_UNPARSED, |
| 73 | self.RAW_PATCH_BUT_UNMATCHED, |
| 74 | self.MATCHED_BUT_EMPTY_DIFF, |
| 75 | self.MATCHED_BUT_EMPTY_ORIGIN, |
| 76 | self.APPLICABLE_PATCH, |
| 77 | ] |
| 78 | self_index = order.index(self) |
| 79 | other_index = order.index(other) |
| 80 | return self_index < other_index |
| 81 | |
| 82 | def __eq__(self, other): |
| 83 | return self is other |
| 84 | |
| 85 | def __hash__(self): |
| 86 | return hash(self.value) |
| 87 | |
| 88 | def to_dir_name(self, expr_dir: str): |
| 89 | return pjoin(expr_dir, self.value.lower()) |
| 90 | |
| 91 | @staticmethod |
| 92 | def max(statuses): |
| 93 | return sorted(statuses)[-1] |
| 94 | |
| 95 | |
| 96 | def record_extract_status(individual_expr_dir: str, extract_status: ExtractStatus): |
| 97 | """ |
| 98 | Write extract status to file, so that we can read it again when |
| 99 | classifying patches |
| 100 | """ |
| 101 | # there is 1-to-1 correspondence between agent_patch_raw and extract_status |
| 102 | # FIXME: it might be better to record these status in memory so they can be easily managed. |
| 103 | record_file = pjoin(individual_expr_dir, "extract_status.json") |
| 104 | if not os.path.isfile(record_file): |
| 105 | # record for the first time |
| 106 | with open(record_file, "w") as f: |
| 107 | json.dump({"extract_status": [extract_status]}, f, indent=4) |
| 108 | else: |
| 109 | with open(record_file) as f: |
| 110 | record = json.load(f) |
| 111 | record["extract_status"].append(extract_status) |
| 112 | with open(record_file, "w") as f: |
| 113 | json.dump(record, f, indent=4) |
| 114 | |
| 115 | |
| 116 | def read_extract_status(individual_expr_dir: str) -> tuple[ExtractStatus, int]: |
| 117 | """ |
| 118 | Read extract status from file. If there are multiple status recorded, read the best one. |
| 119 | Returns: |
| 120 | - The best extract status |
| 121 | - The index of the best status in the list of all statuses. (0-based) |
| 122 | """ |
| 123 | # we should read from the all the record |
| 124 | record_file = pjoin(individual_expr_dir, "extract_status.json") |
| 125 | if not os.path.isfile(record_file): |
| 126 | # if no status file is written, means that we did not even |
| 127 | # reach the state of extracting patches |
| 128 | return ExtractStatus.NO_PATCH, -1 |
| 129 | with open(record_file) as f: |
| 130 | record = json.load(f) |
| 131 | # convert string to enum type |
| 132 | all_status = [ExtractStatus(s) for s in record["extract_status"]] |
| 133 | |
| 134 | best_status = ExtractStatus.max(all_status) |
| 135 | best_idx = all_status.index(best_status) |
| 136 | return best_status, best_idx |
| 137 | |
| 138 | |
| 139 | def get_final_patch_path(individual_expr_dir: str) -> str | None: |
| 140 | """ |
| 141 | Get the final patch path from the individual experiment directory. |
| 142 | If there are multiple extracted patches, need to figure out which one is the best based |
| 143 | on the patch extraction history. |
| 144 | """ |
| 145 | _, best_index = read_extract_status(individual_expr_dir) |
| 146 | best_patch_name = f"extracted_patch_{best_index + 1}.diff" |
| 147 | final_patch_path = pjoin(individual_expr_dir, best_patch_name) |
| 148 | |
| 149 | if not os.path.isfile(final_patch_path): |
| 150 | return None |
| 151 | |
| 152 | return final_patch_path |
| 153 | |
| 154 | |
| 155 | def extract_diff_one_instance( |
| 156 | raw_patch_file: str, extracted_file: str, standalone_mode: bool = False |
| 157 | ) -> tuple[ExtractStatus, str]: |
| 158 | """ |
| 159 | Extract .diff patches for one instance. |
| 160 | Args: |
| 161 | - raw_patch_file: Path to the raw patch file produced by model. |
| 162 | - extracted_file: Path where the extracted diff file goes. |
| 163 | - standalone_mode: If True, the function is called from the special --extract-patch mode. |
| 164 | Specify this to True if using this function as it is for testing. |
| 165 | Returns: |
| 166 | - ExtractStatus. |
| 167 | - An additional string containing more explanation on how patch extraction failed. |
| 168 | If everything is successful, this string is empty. |
| 169 | """ |
| 170 | # (1) get the meta data for this task |
| 171 | task_dir = os.path.dirname(raw_patch_file) |
| 172 | meta_file = pjoin(task_dir, "meta.json") |
| 173 | with open(meta_file) as f: |
| 174 | meta = json.load(f) |
| 175 | |
| 176 | task_info = meta["task_info"] |
| 177 | setup_info = meta["setup_info"] |
| 178 | repo_path = setup_info["repo_path"] # the project dir |
| 179 | base_commit = task_info["base_commit"] # the commit to checkout |
| 180 | |
| 181 | if not os.path.isfile(raw_patch_file): |
| 182 | return ExtractStatus.NO_PATCH, "No raw patch file is found." |
| 183 | |
| 184 | with open(raw_patch_file) as f: |
| 185 | patch_content = f.read() |
| 186 | |
| 187 | # (2) try parsing the edits |
| 188 | try: |
| 189 | edits = parse_edits(patch_content) |
| 190 | except Exception as e: |
| 191 | return ( |
| 192 | ExtractStatus.RAW_PATCH_BUT_UNPARSED, |
| 193 | f"Exception {e} happend when parsing edits.", |
| 194 | ) |
| 195 | |
| 196 | if not edits: |
| 197 | return ExtractStatus.RAW_PATCH_BUT_UNPARSED, "No edits can be parsed." |
| 198 | |
| 199 | # (3) edit parsed. check whether it can match the original program |
| 200 | with apputils.cd(repo_path): |
| 201 | if standalone_mode: |
| 202 | # in special --extract-patch mode |
| 203 | apputils.repo_reset_and_clean_checkout(base_commit) |
| 204 | else: |
| 205 | # extracting patch in the write_patch loop |
| 206 | # we should not reset to base commit, because previous we created a new commit |
| 207 | # containing the test_patch content. We should just clean the changes until HEAD. |
| 208 | apputils.repo_clean_changes() |
| 209 | # try to match and apply each edit |
| 210 | unmatched_edit_indexes = [] |
| 211 | for idx, edit in enumerate(edits): |
| 212 | # NOTE: do not clean here, since we want to accumulate changes from all edits |
| 213 | target_file = edit.filename |
| 214 | # find the target file. The model may only use the short name of the file, |
| 215 | # so we need to search for it here |
| 216 | found_file = apputils.find_file(repo_path, target_file) |
| 217 | if found_file is None: |
| 218 | unmatched_edit_indexes.append(idx) |
| 219 | continue |
| 220 | # try to apply this edit and update the actual file content |
| 221 | applied_file = apply_edit(edit, found_file) |
| 222 | if applied_file is None: |
| 223 | unmatched_edit_indexes.append(idx) |
| 224 | continue |
| 225 | |
| 226 | if len(unmatched_edit_indexes) == len(edits): |
| 227 | # non of the edits can be matched |
| 228 | # there is obvious error, and we definitely cannot extract patch |
| 229 | apputils.repo_clean_changes() |
| 230 | return ( |
| 231 | ExtractStatus.RAW_PATCH_BUT_UNMATCHED, |
| 232 | "None of the edits can match the original program.", |
| 233 | ) |
| 234 | |
| 235 | # let's have a message describing which edits can be matched |
| 236 | if unmatched_edit_indexes: |
| 237 | unmatched_msg = f"Edits number {','.join([str(x+1) for x in unmatched_edit_indexes])} cannot be matched to the original program. " |
| 238 | else: |
| 239 | unmatched_msg = "" |
| 240 | |
| 241 | # at this point, at least some of the edits could be applied (some others may be unmatched) |
| 242 | # we first try to get the diff |
| 243 | diff = apputils.run_command( |
| 244 | ["git", "diff"], stdout=subprocess.PIPE |
| 245 | ).stdout.decode() |
| 246 | |
| 247 | # After extracting diff, we have nothing more to do in the actual code base |
| 248 | apputils.repo_clean_changes() |
| 249 | |
| 250 | if not diff: |
| 251 | # diff file is empty, meaning the patched program is the same as original |
| 252 | # effectively, there is no edits that matched and introduced a real diff |
| 253 | msg = ( |
| 254 | unmatched_msg |
| 255 | + "The matched edits do not introduce any change to the codebase." |
| 256 | ) |
| 257 | return ExtractStatus.MATCHED_BUT_EMPTY_DIFF, msg |
| 258 | |
| 259 | edits_with_empty_before = [ |
| 260 | str(idx + 1) for idx, edit in enumerate(edits) if not edit.before.strip() |
| 261 | ] |
| 262 | if edits_with_empty_before: |
| 263 | numbers = ", ".join(edits_with_empty_before) |
| 264 | msg = f"Please contain **non-whitespace** original code snippet in edits number {numbers}." |
| 265 | return ExtractStatus.MATCHED_BUT_EMPTY_ORIGIN, msg |
| 266 | |
| 267 | # the edits resulted in a non-empty diff. We should at least save and return it |
| 268 | with open(extracted_file, "w") as f: |
| 269 | f.write(diff) |
| 270 | |
| 271 | # if all edits are matched, the `unmatched_msg` is empty string |
| 272 | return ExtractStatus.APPLICABLE_PATCH, unmatched_msg |
| 273 | |
| 274 | |
| 275 | def organize_experiment_results(expr_dir: str): |
| 276 | """ |
| 277 | Assuming patches have already been extracted, organize the experiment result |
| 278 | directories into a few categories and move them there. |
| 279 | """ |
| 280 | # (1) find all the task experiment directories |
| 281 | task_exp_names = [ |
| 282 | x |
| 283 | for x in os.listdir(expr_dir) |
| 284 | if os.path.isdir(pjoin(expr_dir, x)) |
| 285 | and "__" in x # for filtering out other dirs like "applicable_patch" |
| 286 | ] |
| 287 | task_exp_dirs = [pjoin(expr_dir, x) for x in task_exp_names] |
| 288 | |
| 289 | # start organizing |
| 290 | for extract_status in ExtractStatus: |
| 291 | os.makedirs(extract_status.to_dir_name(expr_dir), exist_ok=True) |
| 292 | |
| 293 | for task_dir in task_exp_dirs: |
| 294 | extract_status, _ = read_extract_status(task_dir) |
| 295 | corresponding_dir = extract_status.to_dir_name(expr_dir) |
| 296 | shutil.move(task_dir, corresponding_dir) |
| 297 | |
| 298 | |
| 299 | # NOTE: only used in the special mode of only extracting patches |
| 300 | def extract_diffs_and_organize_tasks(expr_dir: str): |
| 301 | """ |
| 302 | For extracting patches for all instances at one go. |
| 303 | Now, it is mainly used in the special mode of only extracting patches, |
| 304 | since patch extraction of individual instance is tied to the workflow now. |
| 305 | |
| 306 | Extract diff files from raw patches, and classify tasks into categories. |
| 307 | """ |
| 308 | log_file = pjoin(expr_dir, "extract_patches.log") |
| 309 | log_file_handle = open(log_file, "w") |
| 310 | task_exp_names = [ |
| 311 | x |
| 312 | for x in os.listdir(expr_dir) |
| 313 | if os.path.isdir(pjoin(expr_dir, x)) |
| 314 | and "__" in x # for filtering out other dirs like "applicable_patch" |
| 315 | ] |
| 316 | task_exp_dirs = [pjoin(expr_dir, x) for x in task_exp_names] |
| 317 | task_exp_dirs = sorted(task_exp_dirs) |
| 318 | |
| 319 | # actuall we don't need this .... |
| 320 | # BUT: if we want to record how many and which tasks are in each category, |
| 321 | # can use this data structure |
| 322 | # mapping from ExtractStats to a list of task ids |
| 323 | all_extract_stats: Mapping[ExtractStatus, list[str]] = defaultdict(list) |
| 324 | |
| 325 | # let's work on each individual task directory |
| 326 | for task_dir in task_exp_dirs: |
| 327 | # (1) gather some information from the meta file |
| 328 | meta_file = pjoin(task_dir, "meta.json") |
| 329 | with open(meta_file) as f: |
| 330 | meta = json.load(f) |
| 331 | task_id = meta["task_id"] |
| 332 | |
| 333 | log_file_handle.write(f"\n\n\nGoing to extract patch for task {task_id}.\n") |
| 334 | |
| 335 | # (2) find the latest raw patch file |
| 336 | raw_patch_files = [ |
| 337 | x for x in os.listdir(task_dir) if x.startswith("agent_patch_raw_") |
| 338 | ] |
| 339 | if not raw_patch_files: |
| 340 | record_extract_status(task_dir, ExtractStatus.NO_PATCH) |
| 341 | all_extract_stats[ExtractStatus.NO_PATCH].append(task_id) |
| 342 | # no patch files at all |
| 343 | continue |
| 344 | # find the most recent one |
| 345 | numbers = [int(file.split("_")[-1]) for file in raw_patch_files] |
| 346 | numbers.sort() |
| 347 | if not numbers: |
| 348 | # should not happen, but just in case |
| 349 | record_extract_status(task_dir, ExtractStatus.NO_PATCH) |
| 350 | all_extract_stats[ExtractStatus.NO_PATCH].append(task_id) |
| 351 | continue |
| 352 | |
| 353 | all_status = [] |
| 354 | for num in numbers: |
| 355 | raw_patch_file = pjoin(task_dir, f"agent_patch_raw_{num}") |
| 356 | # print(f"Extracting patch for task {task_id} from {raw_patch_file}.") |
| 357 | |
| 358 | print(task_id, num) |
| 359 | # (3) perform the actual extraction |
| 360 | extracted_file = pjoin(task_dir, f"extracted_patch_{num}.diff") |
| 361 | extract_status, _ = extract_diff_one_instance( |
| 362 | raw_patch_file, extracted_file, standalone_mode=True |
| 363 | ) |
| 364 | all_status.append(extract_status) |
| 365 | |
| 366 | record_extract_status(task_dir, extract_status) |
| 367 | all_extract_stats[extract_status].append(task_id) |
| 368 | |
| 369 | log_file_handle.write( |
| 370 | f"\tPatch extraction status: {ExtractStatus.max(all_status)}\n" |
| 371 | ) |
| 372 | |
| 373 | # tasks has been categorized, now move them to specific folder based on the result |
| 374 | organize_experiment_results(expr_dir) |
| 375 | log_file_handle.close() |
| 376 | |
| 377 | |
| 378 | def extract_swe_bench_input(dir: str): |
| 379 | """ |
| 380 | After diff format patch files have been extracted, this function collects |
| 381 | them and writes a single file that can be used by swe-bench. |
| 382 | |
| 383 | Returns: |
| 384 | - path to swe-bench input file. |
| 385 | """ |
| 386 | # only look into applicable_patch dir, since we have already done |
| 387 | # the categorization |
| 388 | applicable_res_dir = pjoin(dir, "applicable_patch") |
| 389 | # figure out what tasks have applicable patch |
| 390 | task_dirs = [ |
| 391 | x |
| 392 | for x in os.listdir(applicable_res_dir) |
| 393 | if os.path.isdir(pjoin(applicable_res_dir, x)) |
| 394 | ] |
| 395 | task_dirs = [pjoin(applicable_res_dir, x) for x in task_dirs] |
| 396 | patch_files = [pjoin(x, "agent_patch_raw") for x in task_dirs] |
| 397 | patch_files = [os.path.abspath(x) for x in patch_files] |
| 398 | |
| 399 | # Diff files have the name extracted_patch_{1,2,3...}.diff |
| 400 | # We take the one with the largest index. This is because |
| 401 | # (1) if there is no validation, then there is at most one such file, |
| 402 | # so just take it |
| 403 | # (2) if there is validation, only the one with the largest index may be correct |
| 404 | diff_files = [] |
| 405 | for x in task_dirs: |
| 406 | extracted_patches = glob(pjoin(x, "extracted_patch_*.diff")) |
| 407 | extracted_patches.sort( |
| 408 | key=lambda name: int(name.removesuffix(".diff").split("_")[-1]), |
| 409 | reverse=True, |
| 410 | ) |
| 411 | diff_files.append(extracted_patches[0]) |
| 412 | |
| 413 | diff_files = [os.path.abspath(x) for x in diff_files] |
| 414 | |
| 415 | patch_files = [x for x in patch_files if os.path.isfile(x)] |
| 416 | diff_files = [x for x in diff_files if os.path.isfile(x)] |
| 417 | |
| 418 | all_results = [] |
| 419 | for diff_file in diff_files: |
| 420 | task_dir = os.path.dirname(diff_file) |
| 421 | meta_file = pjoin(task_dir, "meta.json") |
| 422 | with open(meta_file) as f: |
| 423 | meta = json.load(f) |
| 424 | task_id = meta["task_id"] |
| 425 | this_result = {} |
| 426 | this_result["instance_id"] = task_id |
| 427 | this_result["model_name_or_path"] = common.SELECTED_MODEL.name |
| 428 | with open(diff_file) as f: |
| 429 | diff_content = f.read() |
| 430 | if not diff_content: |
| 431 | # empty diff file, dont bother sending it to swe-bench |
| 432 | continue |
| 433 | this_result["model_patch"] = diff_content |
| 434 | all_results.append(this_result) |
| 435 | |
| 436 | swe_input_file = pjoin(dir, "predictions_for_swebench.json") |
| 437 | with open(swe_input_file, "w") as f: |
| 438 | json.dump(all_results, f, indent=4) |
| 439 | |
| 440 | return swe_input_file |
| 441 | |
| 442 | |
| 443 | def is_valid_json(json_str: str) -> tuple[ExtractStatus, list | dict | None]: |
| 444 | """ |
| 445 | Check whether a json string is valid. |
| 446 | """ |
| 447 | try: |
| 448 | data = json.loads(json_str) |
| 449 | except json.decoder.JSONDecodeError: |
| 450 | return ExtractStatus.NOT_VALID_JSON, None |
| 451 | return ExtractStatus.IS_VALID_JSON, data |
| 452 | |
| 453 | |
| 454 | """ |
| 455 | Main entries of the module. |
| 456 | """ |
| 457 | |
| 458 | |
| 459 | def reextract_organize_and_form_inputs(expr_dir: str): |
| 460 | """ |
| 461 | Move individual experiment dirs out of the categories (applicable_patch, etc.), |
| 462 | before extracting patches and organizng again. |
| 463 | """ |
| 464 | abs_expr_dir = os.path.abspath(expr_dir) |
| 465 | un_classify_expr_dir(abs_expr_dir) |
| 466 | extract_diffs_and_organize_tasks(abs_expr_dir) |
| 467 | |
| 468 | |
| 469 | def un_classify_expr_dir(expr_dir: str): |
| 470 | individual_expr_dirs = [] |
| 471 | for individual_expr_dir in glob(pjoin(expr_dir, "*", "*__*")): |
| 472 | assert "info.log" in os.listdir( |
| 473 | individual_expr_dir |
| 474 | ), f"{individual_expr_dir} has no info.log" |
| 475 | individual_expr_dirs.append(individual_expr_dir) |
| 476 | |
| 477 | for d in individual_expr_dirs: |
| 478 | move(d, expr_dir) |
| 479 | |
| 480 | |
| 481 | def extract_organize_and_form_input(expr_dir): |
| 482 | """ |
| 483 | From a directory of raw experiment result dirs, extract diff patches, organize them into |
| 484 | categories, and form a single file that can be used by swe-bench. |
| 485 | Args: |
| 486 | - expr_dir: the overall experiment directory. |
| 487 | """ |
| 488 | abs_expr_dir = os.path.abspath(expr_dir) |
| 489 | extract_diffs_and_organize_tasks(abs_expr_dir) |
| 490 | extract_swe_bench_input(abs_expr_dir) |
| 491 | |
| 492 | |
| 493 | def organize_and_form_input(expr_dir): |
| 494 | """ |
| 495 | Only organize the experiment directories into a few categories. |
| 496 | Args: |
| 497 | - expr_dir: the overall experiment directory. |
| 498 | """ |
| 499 | organize_experiment_results(expr_dir) |
| 500 | swe_input_file = extract_swe_bench_input(expr_dir) |
| 501 | return swe_input_file |