Elffuss BraidHub

kikocis/auto-code-rover public

main · 18.3 KiBRawPermalink
1"""
2The main driver.
3"""
4
5import json
6import shutil
7from argparse import ArgumentParser
8from collections.abc import Callable, Mapping, Sequence
9from concurrent.futures import ProcessPoolExecutor
10from datetime import datetime
11from itertools import chain
12from os.path import abspath
13from os.path import join as pjoin
14
15from loguru import logger
16
17from app import globals, globals_mut, inference, log
18from app import utils as apputils
19from app.api.manage import ProjectApiManager
20from app.model import common
21from app.model.register import register_all_models
22from app.post_process import (
23 extract_organize_and_form_input,
24 get_final_patch_path,
25 organize_and_form_input,
26 reextract_organize_and_form_inputs,
27)
28from app.raw_tasks import RawGithubTask, RawLocalTask, RawSweTask, RawTask
29from app.task import Task
30
31
32def get_args(
33 from_command_line_str: str = None, subparser_dest_attr_name: str = "command"
34):
35 parser = ArgumentParser()
36 subparsers = parser.add_subparsers(dest=subparser_dest_attr_name)
37
38 swe_parser = subparsers.add_parser(
39 "swe-bench", help="Run one or multiple swe-bench tasks"
40 )
41 set_swe_parser_args(swe_parser)
42
43 github_parser = subparsers.add_parser(
44 "github-issue", help="Run an online github issue"
45 )
46 set_github_parser_args(github_parser)
47
48 local_parser = subparsers.add_parser("local-issue", help="Run a local issue.")
49 set_local_parser_args(local_parser)
50
51 extract_patches_parser = subparsers.add_parser(
52 "extract-patches", help="Only extract patches from the raw results dir"
53 )
54 extract_patches_parser.add_argument("experiment-dir", type=str)
55
56 re_extract_patches_parser = subparsers.add_parser(
57 "re-extract-patches",
58 help=(
59 "same as extract-patches, except that individual dirs"
60 " are moved out of their categories first"
61 ),
62 )
63 re_extract_patches_parser.add_argument("experiment-dir", type=str)
64
65 if not from_command_line_str:
66 return parser.parse_args()
67 return parser.parse_args(from_command_line_str.split())
68
69
70def main(args, subparser_dest_attr_name: str = "command"):
71
72 ## common options
73 globals.output_dir = args.output_dir
74 if globals.output_dir is not None:
75 globals.output_dir = abspath(globals.output_dir)
76 num_processes: int = int(args.num_processes)
77 # set whether brief or verbose log
78 print_stdout: bool = not args.no_print
79 log.print_stdout = print_stdout
80 # model related
81 common.set_model(args.model)
82 # FIXME: make temperature part of the Model class
83 common.MODEL_TEMP = args.model_temperature
84 # acr related
85 globals.conv_round_limit = args.conv_round_limit
86 globals.enable_layered = args.enable_layered
87 globals.enable_sbfl = args.enable_sbfl
88 globals.enable_validation = args.enable_validation
89 globals.enable_angelic = args.enable_angelic
90 globals.enable_perfect_angelic = args.enable_perfect_angelic
91 globals.only_save_sbfl_result = args.save_sbfl_result
92 globals.disable_patch_generation = args.output_fix_locs
93 globals.context_generation_limit = args.output_fix_limit
94
95 subcommand = getattr(args, subparser_dest_attr_name)
96 if subcommand == "swe-bench":
97 tasks = make_swe_tasks(
98 args.task, args.task_list_file, args.setup_map, args.tasks_map
99 )
100
101 groups = group_swe_tasks_by_env(tasks)
102 run_task_groups(groups, num_processes, organize_output=True)
103 elif subcommand == "github-issue":
104 setup_dir = args.setup_dir
105 if setup_dir is not None:
106 setup_dir = abspath(setup_dir)
107
108 task = RawGithubTask(
109 args.task_id,
110 args.clone_link,
111 args.commit_hash,
112 args.issue_link,
113 setup_dir,
114 args.use_comments,
115 )
116 groups = {"github": [task]}
117 run_task_groups(groups, num_processes)
118 elif subcommand == "local-issue":
119 local_repo = args.local_repo
120 if local_repo is not None:
121 local_repo = abspath(local_repo)
122 issue_file = args.issue_file
123 if issue_file is not None:
124 issue_file = abspath(issue_file)
125 task = RawLocalTask(args.task_id, local_repo, issue_file)
126 groups = {"local": [task]}
127 run_task_groups(groups, num_processes)
128 elif subcommand == "extract-patches":
129 extract_organize_and_form_input(args.experiment_dir)
130 elif subcommand == "re-extract-patches":
131 reextract_organize_and_form_inputs(args.experiment_dir)
132
133
134def set_swe_parser_args(parser: ArgumentParser) -> None:
135 add_task_related_args(parser)
136
137 parser.add_argument(
138 "--setup-map",
139 type=str,
140 help="Path to json file that contains the setup information of the projects.",
141 )
142 parser.add_argument(
143 "--tasks-map",
144 type=str,
145 help="Path to json file that contains the tasks information.",
146 )
147 parser.add_argument(
148 "--task-list-file",
149 type=str,
150 help="Path to the file that contains all tasks ids to be run.",
151 )
152 parser.add_argument("--task", type=str, help="Task id to be run.")
153
154
155def set_github_parser_args(parser: ArgumentParser) -> None:
156 add_task_related_args(parser)
157 parser.add_argument(
158 "--task-id", type=str, help="Assign an id to the current fresh issue task."
159 )
160 parser.add_argument(
161 "--clone-link", type=str, help="The link to the repository to clone."
162 )
163 parser.add_argument(
164 "--commit-hash",
165 type=str,
166 help="The commit hash to checkout. If not specified, the latest commit on default branch will be used.",
167 )
168 parser.add_argument(
169 "--use-comments",
170 action="store_true",
171 default=False,
172 help="Include the comments of the issue.",
173 )
174 parser.add_argument("--issue-link", type=str, help="The link to the issue.")
175 parser.add_argument(
176 "--setup-dir",
177 type=str,
178 help="The directory where repositories should be cloned to.",
179 )
180
181
182def set_local_parser_args(parser: ArgumentParser) -> None:
183 add_task_related_args(parser)
184 parser.add_argument(
185 "--task-id", type=str, help="Assign an id to the current local issue task."
186 )
187 parser.add_argument(
188 "--local-repo", type=str, help="Path to a local copy of the target repo."
189 )
190 parser.add_argument("--issue-file", type=str, help="Path to a local issue file.")
191
192
193def add_task_related_args(parser: ArgumentParser) -> None:
194 parser.add_argument(
195 "--output-dir",
196 type=str,
197 help="Path to the directory that stores the run results.",
198 )
199 parser.add_argument(
200 "--no-print",
201 action="store_true",
202 default=False,
203 help="Do not print most messages to stdout.",
204 )
205
206 def model_parser(name: str):
207 if not isinstance(name, str):
208 raise TypeError(f"Invalid model name: {name}")
209 if name in common.MODEL_HUB.keys():
210 return name
211 if name.startswith("litellm-generic-"):
212 return name
213 raise TypeError(f"Invalid model name: {name}")
214
215 parser.add_argument(
216 "--model",
217 type=model_parser,
218 default="gpt-3.5-turbo-0125",
219 help="The model to use. Currently only OpenAI models are supported.",
220 )
221 parser.add_argument(
222 "--model-temperature",
223 type=float,
224 default=0.0,
225 help="The model temperature to use, for OpenAI models.",
226 )
227 parser.add_argument(
228 "--conv-round-limit",
229 type=int,
230 default=15,
231 help="Conversation round limit for the main agent.",
232 )
233 parser.add_argument(
234 "--enable-layered",
235 action="store_true",
236 default=True,
237 help="Enable layered code search.",
238 )
239 parser.add_argument(
240 "--enable-sbfl", action="store_true", default=False, help="Enable SBFL."
241 )
242 parser.add_argument(
243 "--enable-validation",
244 action="store_true",
245 default=False,
246 help="Enable validation in our workflow.",
247 )
248 parser.add_argument(
249 "--enable-angelic",
250 action="store_true",
251 default=False,
252 help="(Experimental) Enable angelic debugging",
253 )
254 parser.add_argument(
255 "--enable-perfect-angelic",
256 action="store_true",
257 default=False,
258 help="(Experimental) Enable perfect angelic debugging; overrides --enable-angelic",
259 )
260 parser.add_argument(
261 "--save-sbfl-result",
262 action="store_true",
263 default=False,
264 help="Special mode to only save SBFL results for future runs.",
265 )
266 parser.add_argument(
267 "--num-processes",
268 type=str,
269 default=1,
270 help="Number of processes to run the tasks in parallel.",
271 )
272 parser.add_argument(
273 "--output-fix-locs",
274 action="store_true",
275 required=False,
276 default=False,
277 help="Output fix locations to file and do not repair.",
278 )
279 parser.add_argument(
280 "--output-fix-limit",
281 type=int,
282 required=False,
283 default=10,
284 help="Limit output of content retrieval rounds",
285 )
286
287
288def make_swe_tasks(
289 task_id: str | None,
290 task_list_file: str | None,
291 setup_map_file: str,
292 tasks_map_file: str,
293) -> list[RawSweTask]:
294 if task_id is not None and task_list_file is not None:
295 raise ValueError("Cannot specify both task and task-list.")
296
297 all_task_ids = []
298 if task_list_file is not None:
299 all_task_ids = parse_task_list_file(task_list_file)
300 if task_id is not None:
301 all_task_ids = [task_id]
302 if len(all_task_ids) == 0:
303 raise ValueError("No task ids to run.")
304
305 with open(setup_map_file) as f:
306 setup_map = json.load(f)
307 with open(tasks_map_file) as f:
308 tasks_map = json.load(f)
309
310 # Check if all task ids are in the setup and tasks map
311 # This allows failing safely if some tasks are not set up properly
312 missing_task_ids = [
313 x for x in all_task_ids if not (x in setup_map and x in tasks_map)
314 ]
315 if missing_task_ids:
316 # Log the tasks that are not in the setup or tasks map
317 for task_id in sorted(missing_task_ids):
318 log.print_with_time(
319 f"Skipping task {task_id} which was not found in setup or tasks map."
320 )
321 # And drop them from the list of all task ids
322 all_task_ids = filter(lambda x: x not in missing_task_ids, all_task_ids)
323
324 all_task_ids = sorted(all_task_ids)
325
326 # for each task in the list to run, create a Task instance
327 all_tasks = []
328 for task_id in all_task_ids:
329 setup_info = setup_map[task_id]
330 task_info = tasks_map[task_id]
331 task = RawSweTask(task_id, setup_info, task_info)
332 all_tasks.append(task)
333 return all_tasks
334
335
336def parse_task_list_file(task_list_file: str) -> list[str]:
337 """
338 Parse the task list file.
339 The file should contain one task/instance id per line, without other characters.
340 """
341 with open(task_list_file) as f:
342 task_ids = f.readlines()
343 return [x.strip() for x in task_ids]
344
345
346def group_swe_tasks_by_env(tasks: list[RawSweTask]) -> dict[str, list[RawSweTask]]:
347 groups = {}
348 for task in tasks:
349 key = task.setup_info["env_name"]
350 if key not in groups:
351 groups[key] = []
352 groups[key].append(task)
353 return groups
354
355
356def run_task_groups(
357 task_groups: Mapping[str, Sequence[RawTask]],
358 num_processes: int,
359 organize_output: bool = False,
360):
361 """
362 Main entry for running tasks.
363 """
364 all_tasks = list(chain.from_iterable(task_groups.values()))
365 num_tasks = len(all_tasks)
366
367 globals_mut.init_total_num_tasks(num_tasks)
368
369 # print some info about task
370 log.print_with_time(f"Total number of tasks: {num_tasks}")
371 log.print_with_time(f"Total number of processes: {num_processes}")
372 log.print_with_time(f"Task group info: (number of groups: {len(task_groups)})")
373 for key, tasks in task_groups.items():
374 log.print_with_time(f"\t{key}: {len(tasks)} tasks")
375
376 # single process mode
377 if num_processes == 1:
378 log.print_with_time("Running in single process mode.")
379 run_tasks_serial(all_tasks)
380 log.print_with_time("Finished all tasks sequentially.")
381 else:
382 run_task_groups_parallel(task_groups, num_processes)
383
384 if globals.only_save_sbfl_result:
385 log.print_with_time("Only saving SBFL results. Exiting.")
386 return
387
388 if organize_output:
389 # post-process completed experiments to get input file to SWE-bench
390 log.print_with_time("Post-processing completed experiment results.")
391 swe_input_file = organize_and_form_input(globals.output_dir)
392 log.print_with_time(f"SWE-Bench input file created: {swe_input_file}")
393
394
395def run_tasks_serial(tasks: list[RawTask]) -> None:
396 for task in tasks:
397 run_task_in_subprocess(task)
398
399
400def run_task_groups_parallel(
401 task_groups: Mapping[str, Sequence[RawTask]], num_processes: int
402):
403 num_task_groups = len(task_groups)
404 globals_mut.init_total_num_task_groups(num_task_groups)
405 num_processes = min(num_processes, num_task_groups)
406
407 task_group_ids_items = sorted(
408 task_groups.items(), key=lambda x: len(x[1]), reverse=True
409 )
410 log.print_with_time(f"Sorted task groups: {[x[0] for x in task_group_ids_items]}")
411 try:
412 # Use ProcessPoolExecutor instead of multiprocessing.Pool,
413 # to support nested sub-processing
414
415 group_ids, group_tasks = zip(*task_group_ids_items)
416 with ProcessPoolExecutor(num_processes) as executor:
417 executor.map(run_task_group, group_ids, group_tasks)
418 finally:
419 log.print_with_time("Finishing all tasks in the pool.")
420
421
422def run_task_group(task_group_id: str, task_group_items: list[RawTask]) -> None:
423 """
424 Run all tasks in a task group sequentially.
425 Main entry to parallel processing.
426 """
427 log.print_with_time(
428 f"Starting process for task group {task_group_id}. Number of tasks: {len(task_group_items)}."
429 )
430 for task in task_group_items:
431 # within a group, the runs are always sequential
432 run_task_in_subprocess(task)
433 log.print_with_time(globals_mut.incre_task_return_msg())
434
435 log.print_with_time(
436 f"{globals_mut.incre_task_group_return_msg()} Finished task group {task_group_id}."
437 )
438
439
440def run_task_in_subprocess(task: RawTask) -> None:
441 with ProcessPoolExecutor(max_workers=1) as executor:
442 executor.submit(run_raw_task, task)
443
444
445def run_raw_task(
446 task: RawTask, print_callback: Callable[[dict], None] | None = None
447) -> bool:
448 """
449 High-level entry for running one task.
450
451 Args:
452 - task: The Task instance to run.
453
454 Returns:
455 Whether the task completed successfully.
456 """
457 task_id = task.task_id
458
459 start_time_s = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
460 task_output_dir = pjoin(globals.output_dir, f"{task_id}_{start_time_s}")
461 apputils.create_dir_if_not_exists(task_output_dir)
462
463 task.dump_meta_data(task_output_dir)
464
465 log.log_and_always_print(f"============= Running task {task_id} =============")
466
467 run_ok = False
468
469 try:
470 run_ok = do_inference(task.to_task(), task_output_dir, print_callback)
471
472 if run_ok:
473 run_status_message = f"Task {task_id} completed successfully."
474 else:
475 run_status_message = f"Task {task_id} failed without exception."
476 except Exception as e:
477 logger.exception(e)
478 run_status_message = f"Task {task_id} failed with exception: {e}."
479
480 log.log_and_always_print(run_status_message)
481
482 if globals.disable_patch_generation:
483 log.log_and_always_print(
484 f"Patch generation is disabled. Please find fix locations at: {task_output_dir}/fix_locations.json"
485 )
486 else:
487 output_patch_path = pjoin(task_output_dir, "final_patch.diff")
488 final_patch_path = get_final_patch_path(task_output_dir)
489 if final_patch_path is not None:
490 # cppy the final patch to the fixed path
491 shutil.copy2(final_patch_path, output_patch_path)
492
493 log.log_and_always_print(
494 f"Please find the generated patch at: {output_patch_path}"
495 )
496
497 if isinstance(task, RawSweTask):
498 log.log_and_always_print(
499 "[SWE-bench mode] Note that the patch may be move to other paths in SWE-bench mode. "
500 "Please check the SWE-bench input file containing generated patches for all tasks."
501 )
502 else:
503 log.log_and_always_print(
504 "No patch generated. You can try running ACR again."
505 )
506
507 return run_ok
508
509
510def do_inference(
511 python_task: Task,
512 task_output_dir: str,
513 print_callback: Callable[[dict], None] | None = None,
514) -> bool:
515
516 apputils.create_dir_if_not_exists(task_output_dir)
517
518 logger.add(
519 pjoin(task_output_dir, "info.log"),
520 level="DEBUG",
521 format=(
522 "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level>"
523 " | <level>{message}</level>"
524 ),
525 )
526
527 start_time = datetime.now()
528
529 api_manager = ProjectApiManager(python_task, task_output_dir)
530
531 try:
532 if globals.only_save_sbfl_result:
533 _, _, run_ok = api_manager.fault_localization()
534 else:
535 run_ok = inference.run_one_task(
536 api_manager.output_dir,
537 api_manager,
538 python_task.get_issue_statement(),
539 print_callback,
540 )
541
542 api_manager.dump_tool_call_sequence_to_file()
543 api_manager.dump_tool_call_layers_to_file()
544
545 end_time = datetime.now()
546
547 dump_cost(start_time, end_time, task_output_dir, python_task.project_path)
548 finally:
549 python_task.reset_project()
550
551 return run_ok
552
553
554def dump_cost(
555 start_time: datetime, end_time: datetime, task_output_dir: str, project_path: str
556):
557 with apputils.cd(project_path):
558 commit_hash = apputils.get_current_commit_hash()
559 model_stats = common.SELECTED_MODEL.get_overall_exec_stats()
560 stats = {
561 "commit": commit_hash,
562 "start_epoch": start_time.timestamp(),
563 "end_epoch": end_time.timestamp(),
564 "elapsed_seconds": (end_time - start_time).total_seconds(),
565 }
566 stats.update(model_stats)
567
568 with open(pjoin(task_output_dir, "cost.json"), "w") as f:
569 json.dump(stats, f, indent=4)
570
571
572if __name__ == "__main__":
573 logger.remove()
574 register_all_models()
575 args = get_args()
576 main(args)