Elffuss BraidHub

kikocis/auto-code-rover public

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