Elffuss BraidHub

kikocis/auto-code-rover public

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