SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]
Speed up evaluation by caching task environments as docker images (#317)
Oleh Shliazhko2a0c164004d6
diff --git a/run.py b/run.pyindex f21d0027..8fad2e6d 100644--- a/run.py+++ b/run.py@@ -475,6 +475,7 @@ def get_args(args=None) -> ScriptArguments:split="dev",verbose=True,install_environment=True,+ cache_task_images=False,),skip_existing=True,agent=AgentArguments(diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex c9b7b668..d9bd4eaa 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -22,6 +22,7 @@ from sweagent.environment.utils import (PROCESS_DONE_MARKER_END,PROCESS_DONE_MARKER_START,InvalidGithubURL,+ image_exists,copy_anything_to_container,copy_file_to_container,format_trajectory_markdown,@@ -56,7 +57,7 @@ logger.propagate = Falseclass EnvironmentArguments(FrozenSerializable):"""Configure data sources and setup instructions for the environment in which we solve the tasks."""- # Source of issue statement/problem statement. To run over a batch of issues: Path to a data file+ # Source of issue statement/problem statement. To run over a batch of issues: Path to a data file# (`json`, `jsonl`) or directory. To run over single issue: github issue url or path to markdown file# with problem statement or problem statement as text prefixed with `text://`.data_path: str@@ -70,12 +71,13 @@ class EnvironmentArguments(FrozenSerializable):timeout: int = 35verbose: bool = Falseno_mirror: bool = False+ cache_task_images: bool = False# Custom environment setup. Currently only used when data_path points to a single issue.# This needs to be either a string pointing to a yaml file (with yaml, yml file extension)# or a shell script (with sh extension).# See https://github.com/princeton-nlp/SWE-agent/pull/153 for more informationenvironment_setup: Optional[str] = None- # Only used when running on single issue. Path to local repository or github repository.+ # Only used when running on single issue. Path to local repository or github repository.repo_path: str = ""@@ -83,10 +85,10 @@ class EnvironmentArguments(FrozenSerializable):class EnvHook:def on_init(self):...-+def on_copy_repo_started(self, *, repo_type: str, repo_path: str):...-+def on_install_env_started(self):...@@ -140,6 +142,14 @@ class SWEEnv(gym.Env):self.image_name = args.image_nameself._reset_container()+ # Prepare image tag prefix for cached task environments+ if self.args.cache_task_images:+ logger.info("Task environment caching enabled")+ tag = f"{self.args.data_path.replace('/', '_')}__{self.args.split}__{self.args.base_commit or 'head'}__"+ assert len(tag) < 128, f"Cached image tag {tag} too long, probably due to long data path or base commit hash."+ image_name_without_tag = self.image_name.split(":")[0]+ self.cached_image_prefix = f"{image_name_without_tag}:{tag}"+# Set timeoutself.timeout = self.args.timeoutself.idx = 0@@ -155,7 +165,7 @@ class SWEEnv(gym.Env):"""Name of the local copy of the repository"""assert self.record is not Nonereturn self.record["repo"].replace("/", "__")-+def _copy_repo(self) -> str:"""Clone/copy repository/codebase in containerReturns:@@ -222,6 +232,21 @@ class SWEEnv(gym.Env):### Reset Container ###+ if self.args.cache_task_images:+ cached_image = f"{self.cached_image_prefix}{index}"+ if image_exists(cached_image):+ logger.info(f"Restore environment from cached image {cached_image}")+ self.close() # stop current container+ self._init_container(cached_image=cached_image)+ self.communicate("export $(xargs </.env)")+ envs = self.communicate("env")+ logger.debug(f"Environment variables restored from the image:\n{envs}\n")+ if apply_test_patch:+ self._apply_test_patch()+ return None, info+ else:+ logger.info(f"Cached image {cached_image} not found, rebuilding task environment...")+# Clone repository if not already clonedself.communicate(input="cd /")folders = self.communicate(input="ls").split("\n")@@ -280,24 +305,34 @@ class SWEEnv(gym.Env):error_msg="Failed to install flake8 (lint library)")- # Apply test patch for oracle setting+ if self.args.cache_task_images:+ envs = self.communicate("env")+ logger.debug(f"Environment variables to save:\n{envs}\n")+ self.communicate("env >> /.env")+ self.container_obj.commit(cached_image)+ logger.info(f"Container with environment {self.container_obj.id} cached as image {cached_image}")+if apply_test_patch:- path_to_patch = "test.patch"- with open(path_to_patch, "w") as f:- f.write(self.record["test_patch"])- subprocess.run(+ self._apply_test_patch()+ # Write any metadata to info if necessary+ return None, info++ def _apply_test_patch(self):+ """+ Apply test patch for oracle setting+ """+ path_to_patch = "test.patch"+ with open(path_to_patch, "w") as f:+ f.write(self.record["test_patch"])+ subprocess.run(f"docker cp {path_to_patch} {self.container_name}:/root/test.patch",shell=True,)- self.communicate_with_handling(+ self.communicate_with_handling(input="git apply /root/test.patch",error_msg="Failed to apply test patch correctly")- os.remove(path_to_patch)--- # Write any metadata to info if necessary- return None, info+ os.remove(path_to_patch)def step(self, action: str) -> Tuple[Optional[str], int, bool, dict]:"""@@ -427,10 +462,15 @@ class SWEEnv(gym.Env):self.container_obj = Noneself._reset_container()- def _init_container(self) -> None:+ def _init_container(self, cached_image: Optional[str] = None) -> None:"""- Handles container initialization. Defines container name and creates it+ Handles container initialization. Defines container name and creates it.+ If cached_image is provided, it will use that image name instead of the default."""+ image_name = self.image_name+ if cached_image is not None:+ image_name = cached_image+ logger.info(f"Using cached image: {image_name}")if self.container_name is None:process_id = str(os.getpid())current_time = str(datetime.datetime.now())@@ -438,14 +478,14 @@ class SWEEnv(gym.Env):hash_object = hashlib.sha256(unique_string.encode())# Cannot have colons/slashes in container name, but those are important in image names# i.e., when we want swe-agent to pull the image from dockerhub- image_name_sanitized = self.image_name.replace("/", "-")+ image_name_sanitized = image_name.replace("/", "-")image_name_sanitized = image_name_sanitized.replace(":", "-")self.container_name = f"{image_name_sanitized}-{hash_object.hexdigest()[:10]}"self.container, self.parent_pids = get_container(- self.container_name, self.image_name, persistent=self.persistent+ self.container_name, image_name, persistent=self.persistent)try:- client = docker.from_env()+ client = docker.from_env(timeout=600)except docker.errors.DockerException as e:if "Error while fetching server API version" in str(e):raise RuntimeError(@@ -502,7 +542,7 @@ class SWEEnv(gym.Env):)raise RuntimeError("Failed to communicate with container")- buffer, exit_code = read_with_timeout_experimental(self.container, timeout_duration)+ buffer, exit_code = read_with_timeout_experimental(self.container, timeout_duration)self.returncode = int(exit_code)return buffer@@ -634,9 +674,9 @@ class SWEEnv(gym.Env):elif location == "container":raise NotImplementedErrorraise ValueError(f"Invalid 'location': {location}")-+def _run_shell_script_host(self, script_path: Path) -> None:- """Run shell script file (located on host) in container"""+ """Run shell script file (located on host) in container"""if not script_path.is_file():raise FileNotFoundError(f"Script not found at {script_path}")shell_commands = Path(script_path).read_text().splitlines()@@ -840,7 +880,7 @@ class SWEEnv(gym.Env):def open_pr(self, *, trajectory, _dry_run: bool=False):"""Create PR to repository-+Args:trajectory: Trajectory of actions taken by the agent_dry_run: Whether to actually push anything or just simulate it@@ -848,7 +888,7 @@ class SWEEnv(gym.Env):logger.info("Opening PR")# todo: have better way of handling this# Adding random string suffix to avoid name conflicts if we had a previously failed run- issue_url = self.args.data_path+ issue_url = self.args.data_pathtry:issue = get_gh_issue_data(issue_url, token=self._github_token)except InvalidGithubURL as e:@@ -913,7 +953,7 @@ class SWEEnv(gym.Env):timeout_duration=10,)body = (- f"This is a PR opened by AI tool [SWE Agent](https://github.com/princeton-nlp/SWE-agent/) "+ f"This is a PR opened by AI tool [SWE Agent](https://github.com/princeton-nlp/SWE-agent/) "f"to close [#{issue.number}]({issue_url}) ({issue.title}).\n\nCloses #{issue.number}.")body += "\n\n" + format_trajectory_markdown(trajectory)diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.pyindex 197401b2..0ac2e72b 100644--- a/sweagent/environment/utils.py+++ b/sweagent/environment/utils.py@@ -104,7 +104,7 @@ def copy_file_to_container(container, contents, container_path):def copy_anything_to_container(container, host_path: str, container_path: str) -> None:"""Copy files or directories from host to container-+Note: Will need to set ownership on the copied files in the container."""if not Path(host_path).exists():@@ -348,7 +348,29 @@ def get_container(ctr_name: str, image_name: str, persistent: bool = False) -> TReturns:Container object"""- # Let's first check that the image exists and give some better error messages+ if not image_exists(image_name):+ msg = (+ f"Image {image_name} not found. Please ensure it is built and available. "+ "Please double-check that you followed all installation/setup instructions from the "+ "readme."+ )+ raise RuntimeError(msg)++ if persistent:+ return _get_persistent_container(ctr_name, image_name)+ else:+ return _get_non_persistent_container(ctr_name, image_name)+++def image_exists(image_name):+ """+ Check that the image exists and give some better error messages.++ Arguments:+ image_name (str): Name of image+ Returns:+ bool: True if image exists+ """try:client = docker.from_env()except docker.errors.DockerException as e:@@ -367,27 +389,18 @@ def get_container(ctr_name: str, image_name: str, persistent: bool = False) -> T)raise RuntimeError(msg) from eraise- filtered_images = client.images.list(filters={'reference': image_name})- if len(filtered_images) == 0:- msg = (- f"Image {image_name} not found. Please ensure it is built and available. "- "Please double-check that you followed all installation/setup instructions from the "- "readme."- )- raise RuntimeError(msg)- elif len(filtered_images) > 1:- logger.warning(f"Multiple images found for {image_name}, that's weird.")- attrs = filtered_images[0].attrs+ filterred_images = client.images.list(filters={'reference': image_name})+ if len(filterred_images) == 0:+ return False+ elif len(filterred_images) > 1:+ RuntimeError(f"Multiple images found for {image_name}, that's weird.")+ attrs = filterred_images[0].attrsif attrs is not None:logger.info(f"Found image {image_name} with tags: {attrs['RepoTags']}, created: {attrs['Created']} "f"for {attrs['Os']} {attrs['Architecture']}.")-- if persistent:- return _get_persistent_container(ctr_name, image_name)- else:- return _get_non_persistent_container(ctr_name, image_name)+ return Truedef get_commit(api: GhApi, owner: str, repo: str, ref: Optional[str] = None):@@ -454,7 +467,7 @@ def get_problem_statement_from_github_issue(owner: str, repo: str, issue_number:class InstanceBuilder:def __init__(self, token: Optional[str] = None):- """This helper class is used to build the data for an instance object,+ """This helper class is used to build the data for an instance object,retrieving problem statements from github issues or local files and settingrepo paths from github urls or local paths."""@@ -468,7 +481,7 @@ class InstanceBuilder:self.args["problem_statement"] = get_problem_statement_from_github_issue(owner, repo, issue_number, token=self.token)self.args["instance_id"] = f"{owner}__{repo}-i{issue_number}"self.args["problem_statement_source"] = "online"-+def set_problem_statement_from_file(self, file_path: str):self.set_problem_statement_from_text(Path(file_path).read_text())@@ -476,9 +489,9 @@ class InstanceBuilder:self.args["problem_statement"] = textself.args["instance_id"] = hashlib.sha256(self.args["problem_statement"].encode()).hexdigest()[:6]self.args["problem_statement_source"] = "local"-+def set_problem_statement(self, data_path: str ):- """Get problem statement for a single instance from a github issue url or a+ """Get problem statement for a single instance from a github issue url or apath to a markdown or text file."""if data_path.startswith("text://"):@@ -489,7 +502,7 @@ class InstanceBuilder:return self.set_problem_statement_from_file(data_path)msg = f"Not sure how to get problem statement from {data_path=}."raise ValueError(msg)-+def set_repo_info_from_gh_url(self, url: str, base_commit: Optional[str] = None):owner, repo = parse_gh_repo_url(url)self.args["repo"] = f"{owner}/{repo}"@@ -502,7 +515,7 @@ class InstanceBuilder:f"Base commit reference {base_commit} resolved to commit hash {self.args['base_commit']}")self.args["version"] = self.args["base_commit"][:7]-+def set_repo_info_from_local_path(self, path: str, base_commit: Optional[str] = None):self.args["repo"] = str(Path(path).resolve())self.args["repo_type"] = "local"@@ -519,7 +532,7 @@ class InstanceBuilder:raise ValueError(msg)self.args["base_commit"] = repo.head.object.hexshaself.args["version"] = self.args["base_commit"][:7]-+def set_repo_info(self, repo: str, base_commit: Optional[str] = None):if is_github_repo_url(repo):self.set_repo_info_from_gh_url(repo, base_commit=base_commit)@@ -527,10 +540,10 @@ class InstanceBuilder:self.set_repo_info_from_local_path(repo, base_commit=base_commit)else:raise ValueError(f"Could not determine repo path from {repo=}.")-+def set_from_dict(self, instance_dict: Dict[str, Any]):self.args |= instance_dict-+def set_missing_fields(self):# todo: This field is only needed while swe_env is using some questionable logic# to determine whether to clone from a mirror or not. This should be removed in the future.@@ -538,9 +551,9 @@ class InstanceBuilder:# 'online' (loaded from github issue or similar) or 'local' (loaded from local file)if "problem_statement_source" not in self.args:self.args["problem_statement_source"] = "swe-bench"- if "repo_type" not in self.args:+ if "repo_type" not in self.args:self.args["repo_type"] = "github"-+def validate(self):required_fields = ["problem_statement",@@ -558,17 +571,17 @@ class InstanceBuilder:raise ValueError(f"Invalid repo type: {self.args['repo_type']=}")if self.args["repo_type"] == "github" and self.args["repo"].count("/") != 1:raise ValueError(f"Invalid repo format for {self.args['repo_type']=}: {self.args['repo']=}")-+def build(self) -> Dict[str, Any]:self.set_missing_fields()self.validate()return self.args-+def get_instances(- file_path: str,- base_commit: Optional[str] = None,- split: Optional[str] = None,+ file_path: str,+ base_commit: Optional[str] = None,+ split: Optional[str] = None,token: Optional[str] = None,*,repo_path: str = "",@@ -625,6 +638,22 @@ def get_instances(# Raised by load_from_disk if the directory is not a dataset directorypass+ # The next if statement is very brittle logic to determine if we're processing a single instance+ if (Path(file_path).is_file() and Path(file_path).suffix in ['.md', '.txt']) or is_github_issue_url(file_path) or file_path.startswith("text://"):+ ib = InstanceBuilder(token=token)+ ib.set_problem_statement(file_path)+ if repo_path:+ ib.set_repo_info(repo_path, base_commit=base_commit)+ elif is_github_repo_url(file_path):+ ib.set_repo_info_from_gh_url(file_path)+ else:+ raise ValueError(f"Could not determine repo path from {file_path=}, {repo_path=}")++ return [ib.build()]++ if base_commit is not None:+ raise ValueError("base_commit must be None if data_path is not a github issue url")+# If file_path is a file, load the fileif file_path.endswith(".json"):return postproc_instance_list(json.load(open(file_path)))@@ -696,6 +725,6 @@ def format_trajectory_markdown(trajectory: List[Dict[str, str]]):suffix = ["","</details>",- ]+ ]return "\n".join(prefix) + "\n\n---\n\n".join(steps) + "\n".join(suffix)