Elffuss BraidHub

kikocis/auto-code-rover public

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