Elffuss BraidHub

kikocis/auto-code-rover public

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