Skip to content

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]

Various fixes and improved tests for swe-env

Kilian Lieret0f068e31b070
diff --git a/run.py b/run.py
index f5bb6844..2d5a2f69 100644
--- a/run.py
+++ b/run.py
@@ -47,17 +47,12 @@ class ActionsArguments(FlattenedAccess, FrozenSerializable):
# to fix the issue. Please only set this to False if you are sure the commits are
# not fixes or if this is your own repository!
skip_if_commits_reference_issue: bool = True
- # For PRs: If you want to push the branch to a fork (e.g., because you lack
- # permissions to push to the main repo), set this to the URL of the fork.
+ # OBSOLETE. Do not use, will raise error.
push_gh_repo_url: str = ""
def __post_init__(self):
- if not self.skip_if_commits_reference_issue and self.push_gh_repo_url:
- raise ValueError(
- "Overriding `skip_if_commits_reference_issue` when you are "
- "pushing to a fork is not supported. You should manually "
- "apply the patch to the forked repository."
- )
+ if self.push_gh_repo_url:
+ raise ValueError("push_gh_repo_url is obsolete. Use repo_path instead")
@dataclass(frozen=True)
class ScriptArguments(FlattenedAccess, FrozenSerializable):
@@ -151,8 +146,8 @@ def main(args: ScriptArguments):
patch_path = save_patch(traj_dir, instance_id, info)
if args.actions.open_pr and should_open_pr(args, info, token=env._github_token):
env.open_pr(trajectory=trajectory, push_gh_repo_url=args.actions.push_gh_repo_url)
- if args.actions.apply_patch_locally and patch_path is not None and env.record["repo"].startswith("local://"):
- apply_patch(Path(args.environment.data_path.removeprefix("local://")), patch_file=patch_path)
+ if args.actions.apply_patch_locally and patch_path is not None and env.record["repo_type"] == "local":
+ apply_patch(Path(args.environment.repo_path), patch_file=patch_path)
except KeyboardInterrupt:
logger.info("Exiting InterCode environment...")
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 0b31658d..cb39c463 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -25,7 +25,6 @@ from sweagent.environment.utils import (
get_container,
get_gh_issue_data,
get_instances,
- is_github_issue_url,
parse_gh_issue_url,
parse_gh_repo_url,
read_with_timeout,
@@ -66,7 +65,7 @@ class EnvironmentArguments(FrozenSerializable):
timeout: int = 35
verbose: bool = False
no_mirror: bool = False
- # Custom environment setup. Currently only used when data_path is a GitHub URL.
+ # 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 information
@@ -90,7 +89,6 @@ class SWEEnv(gym.Env):
self.logger = logger
self.persistent = args.container_name is not None
self.returncode = None
- self.problem_statement_from_github_issue = is_github_issue_url(args.data_path)
if not self.args.verbose:
self.logger.disabled = True
@@ -132,7 +130,7 @@ class SWEEnv(gym.Env):
"""Name of the local copy of the repository"""
assert self.record is not None
return self.record["repo"].replace("/", "__")
-
+
def _copy_repo(self) -> str:
"""Clone/copy repository/codebase in container
Returns:
@@ -150,7 +148,8 @@ class SWEEnv(gym.Env):
token_prefix = ""
if self._github_token:
token_prefix = f"{self._github_token}@"
- if not self.args.no_mirror and not self.problem_statement_from_github_issue:
+ # fixme: This if statement is brittle and should probably be replaced with better logic
+ if not self.args.no_mirror and self.record["problem_statement_source"] == "swe-bench":
self.logger.info(f"{self._repo_name} not found in container, cloning...")
self.communicate_with_handling(
input=f"git clone https://{token_prefix}github.com/swe-bench/{self._repo_name}.git",
@@ -591,7 +590,8 @@ class SWEEnv(gym.Env):
Creates conda environment and installs third party dependencies to allow code execution
"""
assert self.record is not None # mypy
- if (self.problem_statement_from_github_issue or self.record["repo_type"] == "local") and self.args.environment_setup is None:
+ if (self.record["problem_statement_source"] != "swe-bench" or \
+ self.record["repo_type"] == "local") and self.args.environment_setup is None:
logger.warning((
"install_environment is set to True, but the data path is a GitHub URL "
"without an environment config file (environment_config key/flag). "
diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.py
index 60f11447..22c657a9 100644
--- a/sweagent/environment/utils.py
+++ b/sweagent/environment/utils.py
@@ -397,6 +397,11 @@ class Instance:
version: str
problem_statement: str
instance_id: str
+ # 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.
+ # Values: 'swe-bench' (loaded from json/jsonl for swe-bench style inference),
+ # 'online' (loaded from github issue or similar) or 'local' (loaded from local file)
+ problem_statement_source: str = "swe-bench"
repo_type: str = "github"
def _validate(self):
@@ -424,10 +429,12 @@ class InstanceBuilder:
owner, repo, issue_number = parse_gh_issue_url(issue_url)
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.args["problem_statement"] = Path(file_path).read_text()
self.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
@@ -494,14 +501,17 @@ def get_instances(
Returns:
List of instances as dictionaries
"""
+ def set_missing_keys(instances):
+ return [dataclasses.asdict(Instance(**inst)) for inst in instances]
+
# If file_path is a directory, attempt load from disk
if os.path.isdir(file_path):
try:
dataset_or_dict = load_from_disk(file_path)
if isinstance(dataset_or_dict, dict):
- return dataset_or_dict[split]
- return dataset_or_dict
+ return set_missing_keys(dataset_or_dict[split])
+ return set_missing_keys(dataset_or_dict)
except FileNotFoundError:
# Raised by load_from_disk if the directory is not a dataset directory
pass
@@ -524,9 +534,9 @@ def get_instances(
# If file_path is a file, load the file
if file_path.endswith(".json"):
- return json.load(open(file_path))
+ return set_missing_keys(json.load(open(file_path)))
if file_path.endswith(".jsonl"):
- return [json.loads(x) for x in open(file_path, 'r').readlines()]
+ return set_missing_keys([json.loads(x) for x in open(file_path, 'r').readlines()])
if repo_path:
msg = "repo_path must be empty if data_path is not a github url or local repo url"
@@ -534,7 +544,7 @@ def get_instances(
# Attempt load from HF datasets as a last resort
try:
- return load_dataset(file_path, split=split)
+ return set_missing_keys(load_dataset(file_path, split=split))
except:
raise ValueError(
f"Could not load instances from {file_path}. "
diff --git a/tests/conftest.py b/tests/conftest.py
index 042ccd07..a1410620 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -14,7 +14,20 @@ print("Adjusted path: ", sys.path)
@fixture
-def test_trajectory() -> Path:
- traj_dir = _this_dir / "test_data/trajectories/gpt4__klieret__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/klieret__swe-agent-test-repo-i1.traj"
+def test_data_path() -> Path:
+ p = _this_dir / "test_data"
+ assert p.is_dir()
+ return p
+
+@fixture
+def test_trajectories_path(test_data_path) -> Path:
+ p = test_data_path / "trajectories"
+ assert p.is_dir()
+ return p
+
+
+@fixture
+def test_trajectory(test_trajectories_path):
+ traj_dir = test_trajectories_path / "gpt4__klieret__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1" / "klieret__swe-agent-test-repo-i1.traj"
assert traj_dir.exists()
return json.loads(traj_dir.read_text())
\ No newline at end of file
diff --git a/tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/solution_missing_colon.py b/tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/solution_missing_colon.py
new file mode 100644
index 00000000..ec220afd
--- /dev/null
+++ b/tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/solution_missing_colon.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python3
+
+
+def division(a: float, b: float) -> float:
+ if b == 0:
+ raise ValueError("Cannot divide by zero")
+ return a / b
+
+
+if __name__ == "__main__":
+ try:
+ print(division(23, 0))
+ except ValueError as e:
+ print(e)
+
diff --git a/tests/test_replay.py b/tests/test_replay.py
index 0db63c22..cf4d37e1 100644
--- a/tests/test_replay.py
+++ b/tests/test_replay.py
@@ -1,19 +1,49 @@
+from pathlib import Path
import subprocess
from run_replay import get_args, main
import pytest
+
+def swe_agent_test_repo_clone(tmp_path):
+ local_repo_path = tmp_path / "swe-agent-test-repo"
+ clone_cmd = ["git", "clone", "https://github.com/klieret/swe-agent-test-repo", local_repo_path]
+ subprocess.run(clone_cmd, check=True)
+ return local_repo_path
+
+
+def swe_agent_test_repo_traj(test_trajectories_path) -> Path:
+ p = test_trajectories_path / "gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1" / "6e44b9__sweagenttestrepo-1c2844.traj"
+ assert p.is_file()
+ return p
+
+
+def swe_agent_test_repo_local_problem_stmt(swe_agent_test_repo_clone) -> Path:
+ problem_stmt = swe_agent_test_repo_clone / "problem_statements" / "1.md"
+ assert problem_stmt.is_file()
+ return problem_stmt
+
+
@pytest.mark.slow
-def test_model_replay():
- # fixme: might make sure that path to test data is independent of CWD
[email protected]("problem_statement_source", ["github", "local"])
+def test_model_replay_github_repo(swe_agent_test_repo_traj, problem_statement_source, swe_agent_test_repo_local_problem_stmt):
+ if problem_statement_source == "github":
+ data_path = "https://github.com/klieret/swe-agent-test-repo/issues/1"
+ elif problem_statement_source == "local":
+ data_path = str(swe_agent_test_repo_local_problem_stmt)
args = [
"--traj_path",
- "tests/test_data/trajectories/gpt4__klieret__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/klieret__swe-agent-test-repo-i1.traj",
+ str(swe_agent_test_repo_traj),
"--data_path",
- "https://github.com/klieret/swe-agent-test-repo/issues/1",
+ data_path,
"--config_file",
"config/default_from_url.yaml",
- "--raise_exceptions=True",
+ "--raise_exceptions",
]
+ if problem_statement_source == "local":
+ args.extend(["--repo_path", str("https://github.com/klieret/swe-agent-test-repo/")])
args, remaining_args = get_args(args)
main(**vars(args), forward_args=remaining_args)
@@ -28,23 +58,32 @@ def test_run_cli_help():
@pytest.mark.slow
-def test_model_replay_local_repo(tmp_path):
- local_repo_path = tmp_path / "swe-agent-test-repo"
- clone_cmd = ["git", "clone", "https://github.com/klieret/swe-agent-test-repo", local_repo_path]
- subprocess.run(clone_cmd, check=True)
- assert local_repo_path.is_dir()
- problem_statement_path = local_repo_path / "problem_statements" / "1.md"
- assert problem_statement_path.is_file()
- # fixme: Make path dynamic
[email protected]("problem_statement_source", ["github", "local"])
+def test_model_replay_local_repo(swe_agent_test_repo_clone, swe_agent_test_repo_traj, problem_statement_source):
+ local_repo_path = swe_agent_test_repo_clone
+ if problem_statement_source == "github":
+ problem_statement_path = "https://github.com/klieret/swe-agent-test-repo/issues/1"
+ elif problem_statement_source == "local":
+ problem_statement_path = local_repo_path / "problem_statements" / "1.md"
+ assert problem_statement_path.is_file()
+ else:
+ raise ValueError(problem_statement_source)
+ # fixme: Make traj path dynamic
run_cmd = [
"--traj_path",
- "tests/test_data/trajectories/gpt4__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1/6e44b9__sweagenttestrepo-1c2844.traj",
+ str(swe_agent_test_repo_traj),
"--repo_path",
str(local_repo_path),
"--config_file",
"config/default_from_url.yaml",
"--data_path",
str(problem_statement_path),
+ "--apply_patch",
+ "--raise_exceptions",
]
+ print(run_cmd)
args, remaing_args = get_args(run_cmd)
- main(**vars(args), forward_args=remaing_args)
\ No newline at end of file
+ main(**vars(args), forward_args=remaing_args)
+ solution = (swe_agent_test_repo_traj.parent / "solution_missing_colon.py").read_text().strip()
+ solution_retrieved = (local_repo_path / "tests" / "missing_colon.py").read_text().strip()
+ assert solution == solution_retrieved
diff --git a/tests/test_run.py b/tests/test_run.py
index bb868f02..da3f1689 100644
--- a/tests/test_run.py
+++ b/tests/test_run.py
@@ -6,4 +6,8 @@ def test_run_cli_help():
"run.py",
"--help",
]
- subprocess.run(args, check=True)
\ No newline at end of file
+ subprocess.run(args, check=True)
+
+
+def test_run_obsolete():
+ ...
\ No newline at end of file