Elffuss BraidHub

kikocis/auto-code-rover public

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