Elffuss BraidHub

kikocis/auto-code-rover public

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