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]
Fixes to run_batch.py & related tests
Kilian Lieretece448c93ef7
diff --git a/sweagent/environment/config/problem_statement.py b/sweagent/environment/config/problem_statement.pyindex 3e8eb396..40350fe6 100644--- a/sweagent/environment/config/problem_statement.py+++ b/sweagent/environment/config/problem_statement.py@@ -1,7 +1,7 @@import hashlibimport uuidfrom pathlib import Path-from typing import Literal, Protocol+from typing import Annotated, Any, Literal, Protocolfrom pydantic import BaseModel, Field@@ -26,31 +26,33 @@ class EmptyProblemStatement(BaseModel):return ""-# todo: Make id overridableclass TextProblemStatement(BaseModel):text: str = ""type: Literal["text"] = "text""""Discriminator for (de)serialization/CLI. Do not change."""- @property- def id(self) -> str:- return hashlib.sha256(self.text.encode()).hexdigest()[:6]+ id: str = None # type: ignore++ def model_post_init(self, __context: Any) -> None:+ if self.id is None:+ self.id = hashlib.sha256(self.text.encode()).hexdigest()[:6]def get_problem_statement(self) -> str:return self.text-# todo: Make id overridableclass FileProblemStatement(BaseModel):path: str = ""type: Literal["text_file"] = "text_file""""Discriminator for (de)serialization/CLI. Do not change."""- @property- def id(self) -> str:- return hashlib.sha256(self.get_problem_statement().encode()).hexdigest()[:6]+ id: str = None # type: ignore++ def model_post_init(self, __context: Any) -> None:+ if self.id is None:+ self.id = hashlib.sha256(self.get_problem_statement().encode()).hexdigest()[:6]def get_problem_statement(self) -> str:return Path(self.path).read_text()@@ -74,4 +76,6 @@ class GithubIssue(BaseModel):)-ProblemStatementConfig = TextProblemStatement | GithubIssue | EmptyProblemStatement | FileProblemStatement+ProblemStatementConfig = Annotated[+ TextProblemStatement | GithubIssue | EmptyProblemStatement | FileProblemStatement, Field(union_mode="left_to_right")+]diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex 1507b9f7..2905fd75 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -31,6 +31,9 @@ class EnvironmentConfig(BaseModel):repo: RepoConfig | None = Nonestartup_commands: list[str] = []+ class Config:+ extra = "forbid"+class SWEEnv:name = "swe_main"diff --git a/sweagent/run/batch_instances.py b/sweagent/run/batch_instances.pyindex cdf2949b..3ec5051e 100644--- a/sweagent/run/batch_instances.py+++ b/sweagent/run/batch_instances.py@@ -2,9 +2,10 @@ import jsonimport refrom abc import ABC, abstractmethodfrom pathlib import Path-from typing import Any, Literal+from typing import Annotated, Any, Literal-from pydantic import BaseModel, TypeAdapter+import yaml+from pydantic import BaseModel, Field, TypeAdapterfrom sweagent.environment.config.deployment import DeploymentConfig, LocalDeploymentConfigfrom sweagent.environment.config.problem_statement import ProblemStatementConfig, TextProblemStatement@@ -26,12 +27,14 @@ def _load_file(path: Path) -> Any:from datasets import load_from_diskreturn load_from_disk(path)- elif path.stem == "json":+ if path.suffix == ".json":return json.loads(path.read_text())- elif path.stem == "jsonl":+ if path.suffix == ".jsonl":return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]- else:- raise NotImplementedError+ if path.suffix == ".yaml":+ return yaml.safe_load(path.read_text())+ msg = f"Unsupported file extension: {path.suffix}"+ raise NotImplementedError(msg)class BatchInstance(BaseModel):@@ -67,7 +70,7 @@ class SimpleBatchInstance(BaseModel):deployment = LocalDeploymentConfig(**deployment_kwargs)else:deployment = TypeAdapter(DeploymentConfig).validate_python(dict(image=self.image_name, **deployment_kwargs))- problem_statement = TextProblemStatement(text=self.problem_statement)+ problem_statement = TextProblemStatement(text=self.problem_statement, id=self.id)return BatchInstance(env=EnvironmentConfig(deployment=deployment, repo=None), problem_statement=problem_statement)@@ -77,33 +80,34 @@ class InstancesFromFile(BaseModel, AbstractInstanceSource):"""Load instances from a file."""path: Path- instance_filter: str = ".*"+ filter: str = ".*"- deployment: dict[str, Any]+ deployment: dict[str, Any] = Field(default_factory=dict)"""Any options for one of the `DeploymentConfig` subclasses."""simple: Literal[True] = True"""Convenience discriminator for (de)serialization/CLI. Do not change."""- type: Literal["simple_file"]+ type: Literal["file"] = "file""""Discriminator for (de)serialization/CLI. Do not change."""def get_instance_configs(self) -> list[BatchInstance]:instance_dicts = _load_file(self.path)simple_instances = [SimpleBatchInstance(**instance_dict) for instance_dict in instance_dicts]- return [instance.to_full_batch_instance(self.deployment) for instance in simple_instances]+ instances = [instance.to_full_batch_instance(self.deployment) for instance in simple_instances]+ return _filter_batch_items(instances, self.filter)class InstancesFromHuggingFace(BaseModel, AbstractInstanceSource):"""Load instances from HuggingFace."""dataset_name: str- split: str- instance_filter: str = ".*"+ split: str = "dev"+ filter: str = ".*"deployment: dict[str, Any]"""Any options for one of the `DeploymentConfig` subclasses."""- type: Literal["simple_huggingface"]+ type: Literal["huggingface"] = "huggingface""""Discriminator for (de)serialization/CLI. Do not change."""def get_instance_configs(self) -> list[BatchInstance]:@@ -111,7 +115,8 @@ class InstancesFromHuggingFace(BaseModel, AbstractInstanceSource):ds: list[dict[str, Any]] = load_dataset(self.dataset_name, split=self.split) # type: ignoresimple_instances: list[SimpleBatchInstance] = [SimpleBatchInstance(**instance) for instance in ds]- return [instance.to_full_batch_instance(self.deployment) for instance in simple_instances]+ instances = [instance.to_full_batch_instance(self.deployment) for instance in simple_instances]+ return _filter_batch_items(instances, self.filter)class SWEBenchInstances(BaseModel, AbstractInstanceSource):@@ -122,9 +127,11 @@ class SWEBenchInstances(BaseModel, AbstractInstanceSource):deployment: dict[str, Any]"""Any options for one of the `DeploymentConfig` subclasses."""- type: Literal["swe_bench"]+ type: Literal["swe_bench"] = "swe_bench""""Discriminator for (de)serialization/CLI. Do not change."""+ filter: str = ".*"+def get_instance_configs(self) -> list[BatchInstance]:raise NotImplementedError@@ -135,18 +142,18 @@ class ExpertInstancesFromFile(BaseModel, AbstractInstanceSource):"""path: Path- instance_filter: str = ".*"+ filter: str = ".*"- type: Literal["expert_file"]+ type: Literal["expert_file"] = "expert_file""""Discriminator for (de)serialization/CLI. Do not change."""def get_instance_configs(self) -> list[BatchInstance]:instance_dicts = _load_file(self.path)- instances = [- BatchInstance(env=EnvironmentConfig(**instance_dict), problem_statement=TextProblemStatement(text=""))- for instance_dict in instance_dicts- ]- return _filter_batch_items(instances, self.instance_filter)+ instances = [BatchInstance(**instance_dict) for instance_dict in instance_dicts]+ return _filter_batch_items(instances, self.filter)-BatchInstanceSourceConfig = ExpertInstancesFromFile | InstancesFromHuggingFace | InstancesFromFile | SWEBenchInstances+BatchInstanceSourceConfig = Annotated[+ InstancesFromHuggingFace | InstancesFromFile | SWEBenchInstances | ExpertInstancesFromFile,+ Field(union_mode="left_to_right"),+]diff --git a/sweagent/run/hooks/apply_patch.py b/sweagent/run/hooks/apply_patch.pyindex e37717a7..acaade5b 100644--- a/sweagent/run/hooks/apply_patch.py+++ b/sweagent/run/hooks/apply_patch.py@@ -23,12 +23,10 @@ class SaveApplyPatchHook(RunHook):def on_init(self, *, run):self._traj_dir = Path(run.traj_dir)- self._apply_patch_locally = run.actions.apply_patch_locally- self._env = run.env- self._problem_statement = run.problem_statementdef on_instance_start(self, *, index: int, env: SWEEnv, problem_statement: ProblemStatementConfig):self._env = env+ self._problem_statement = problem_statementdef on_instance_completed(self, *, result: AgentRunResult):instance_id = self._problem_statement.iddiff --git a/sweagent/run/run_batch.py b/sweagent/run/run_batch.pyindex 450c5bad..dd95ebf5 100644--- a/sweagent/run/run_batch.py+++ b/sweagent/run/run_batch.py@@ -8,6 +8,7 @@ import tracebackfrom pathlib import Pathfrom typing import Self+from pydantic import Fieldfrom pydantic_settings import BaseSettingsfrom sweagent.agent.agents import Agent, AgentConfig@@ -21,7 +22,7 @@ from sweagent.utils.log import get_loggerclass RunBatchConfig(BaseSettings):- instances: BatchInstanceSourceConfig+ instances: BatchInstanceSourceConfig = Field(union_mode="left_to_right")agent: AgentConfig = AgentConfig(model=ModelArguments(name="human"), next_step_template="Observation: {observation}")@@ -64,8 +65,19 @@ class RunBatch:@classmethoddef from_config(cls, config: RunBatchConfig) -> Self:+ logger = get_logger("RunBatch", emoji="🏃")+ logger.debug("Loading instances from %s", f"{config.instances!r}")+ instances = config.instances.get_instance_configs()+ logger.info("Loaded %d instances", len(instances))+ if not instances:+ msg = (+ "No instances to run. You might want to check your instance_filter "+ "(if supported by your instance source)"+ )+ raise ValueError(msg)+ logger.debug("The first instance is %s", f"{instances[0]!r}")return cls(- instances=config.instances.get_instance_configs(),+ instances=instances,agent=Agent("main", config.agent),traj_dir=config.traj_dir,raise_exceptions=config.raise_exceptions,@@ -105,6 +117,7 @@ class RunBatch:def _run_instance(self, instance: BatchInstance):if self.should_skip(instance):return+ self.logger.info("Starting to run on instance %s", instance.problem_statement.id)self.logger.info("Starting environment")env = SWEEnv.from_config(instance.env)env.start()diff --git a/sweagent/run/run_single.py b/sweagent/run/run_single.pyindex be90eeef..bb49a604 100644--- a/sweagent/run/run_single.py+++ b/sweagent/run/run_single.py@@ -45,6 +45,9 @@ class RunSingleConfig(BaseSettings):# todo: implement thisprint_config: bool = True+ class Config:+ extra = "forbid"+class RunSingle:def __init__(diff --git a/tests/test_data/data_sources/expert_instances.yaml b/tests/test_data/data_sources/expert_instances.yamlnew file mode 100644index 00000000..7615fc0b--- /dev/null+++ b/tests/test_data/data_sources/expert_instances.yaml@@ -0,0 +1,14 @@+- env:+ deployment:+ type: docker+ problem_statement:+ type: text+ text: "A simple test problem"+ id: "simple_test_problem"+- env:+ deployment:+ type: docker+ problem_statement:+ type: text+ text: "A simple test problem 2"+ id: "simple_test_problem_2"\ No newline at end of filediff --git a/tests/test_data/data_sources/simple_instances.yaml b/tests/test_data/data_sources/simple_instances.yamlnew file mode 100644index 00000000..98602f89--- /dev/null+++ b/tests/test_data/data_sources/simple_instances.yaml@@ -0,0 +1,3 @@+- image_name: "sweagent/swe-agent:latest"+ problem_statement: "A simple test problem"+ id: "simple_test_problem"diff --git a/tests/test_run.py b/tests/test_run.pyindex 87db113c..c7a1253e 100644--- a/tests/test_run.py+++ b/tests/test_run.py@@ -1,15 +1,6 @@from __future__ import annotationsimport subprocess-from pathlib import Path--import pytest--from sweagent.agent.agents import AgentConfig-from sweagent.environment.swe_env import EnvironmentConfig-from sweagent.run.common import BasicCLI-from sweagent.run.hooks.abstract import RunHook-from sweagent.run.run_single import RunSingle, RunSingleConfigdef test_run_cli_no_arg_error():@@ -44,84 +35,3 @@ def test_run_cli_subcommand_help():output = subprocess.run(args, check=True, capture_output=True)assert output.returncode == 0assert "--config" in output.stdout.decode()---class RaisesExceptionHook(RunHook):- def on_instance_start(self, *args, **kwargs):- msg = "test exception"- raise ValueError(msg)---def test_run_single_raises_exception():- rs = RunSingle.from_config(RunSingleConfig())- rs.add_hook(RaisesExceptionHook())- with pytest.raises(ValueError, match="test exception"):- rs.run()---def agent_config_with_commands():- ac = AgentConfig()- ac.command_files = [- f"config/commands/{name}"- for name in ["defaults.sh", "search.sh", "edit_linting.sh", "_split_string.py", "submit.sh"]- ]- return ac---def test_run_ies(agent_config_with_commands):- # ies = instant empty submit- ac = agent_config_with_commands- ac.model.name = "instant_empty_submit"- rsc = RunSingleConfig(- env=EnvironmentConfig(),- agent=ac,- )- rs = RunSingle.from_config(rsc)- rs.run()--[email protected]("repo", ["local", "github"])[email protected]("problem_statement_source", ["github", "local", "text"])-def test_run_ies_repo_ps_matrix(- tmpdir,- swe_agent_test_repo_clone,- repo,- problem_statement_source,-):- output_formats = ["traj", "pred", "patch"]- for fmt in output_formats:- assert not list(Path(tmpdir).glob(f"*.{fmt}"))- if problem_statement_source == "github":- ps_args = ["--problem_statement.url", "https://github.com/swe-agent/test-repo/issues/1"]- elif problem_statement_source == "local":- ps_args = ["--problem_statement.path", str(swe_agent_test_repo_clone / "problem_statements" / "1.md")]- elif problem_statement_source == "text":- ps_args = ["--problem_statement.text='this is a test'"]- else:- raise ValueError(problem_statement_source)- if repo == "local":- repo_args = ["--env.repo.path", str(swe_agent_test_repo_clone)]- elif repo == "github":- repo_args = ["--env.repo.url", "https://github.com/swe-agent/test-repo"]- else:- raise ValueError(repo)- args = [- "--agent.model.name=instant_empty_submit",- "--raise_exceptions=True",- *ps_args,- *repo_args,- ]- print(args)- rs_config = BasicCLI(RunSingleConfig).get_args(args)- print(rs_config)- rs = RunSingle.from_config(rs_config) # type: ignore- with tmpdir.as_cwd():- # Test that we can run run.py also independently from repo dir- rs.run()- for fmt in output_formats:- assert len(list(Path(tmpdir).glob(f"*.{fmt}"))) == 1- print(fmt, list(Path(tmpdir).iterdir()))diff --git a/tests/test_run_batch.py b/tests/test_run_batch.pynew file mode 100644index 00000000..be6e1b19--- /dev/null+++ b/tests/test_run_batch.py@@ -0,0 +1,88 @@+from pathlib import Path++import pytest++from sweagent.run.run import main+++def test_expert_instances(test_data_sources_path: Path, tmp_path: Path):+ ds_path = test_data_sources_path / "expert_instances.yaml"+ assert ds_path.exists()+ cmd = [+ "run-batch",+ "--agent.model.name",+ "instant_empty_submit",+ "--instances.type",+ "expert_file",+ "--instances.path",+ str(ds_path),+ "--traj_dir",+ str(tmp_path),+ "--raise_exceptions",+ "True",+ ]+ main(cmd)+ for _id in ["simple_test_problem", "simple_test_problem_2"]:+ assert (tmp_path / f"{_id}.traj").exists(), list(tmp_path.iterdir())+++def test_simple_instances(test_data_sources_path: Path, tmp_path: Path):+ ds_path = test_data_sources_path / "simple_instances.yaml"+ assert ds_path.exists()+ cmd = [+ "run-batch",+ "--agent.model.name",+ "instant_empty_submit",+ "--instances.path",+ str(ds_path),+ "--traj_dir",+ str(tmp_path),+ "--raise_exceptions",+ "True",+ ]+ main(cmd)+ assert (tmp_path / "simple_test_problem.traj").exists(), list(tmp_path.iterdir())+++def test_empty_instances_simple(test_data_sources_path: Path, tmp_path: Path):+ ds_path = test_data_sources_path / "simple_instances.yaml"+ assert ds_path.exists()+ cmd = [+ "run-batch",+ "--agent.model.name",+ "instant_empty_submit",+ "--instances.path",+ str(ds_path),+ "--traj_dir",+ str(tmp_path),+ "--raise_exceptions",+ "True",+ "--instances.filter",+ "doesnotmatch",+ ]+ with pytest.raises(ValueError, match="No instances to run"):+ main(cmd)+++def test_empty_instances_expert(test_data_sources_path: Path, tmp_path: Path):+ ds_path = test_data_sources_path / "expert_instances.yaml"+ assert ds_path.exists()+ cmd = [+ "run-batch",+ "--agent.model.name",+ "instant_empty_submit",+ "--instances.path",+ str(ds_path),+ "--instances.type",+ "expert_file",+ "--traj_dir",+ str(tmp_path),+ "--raise_exceptions",+ "True",+ "--instances.filter",+ "doesnotmatch",+ ]+ with pytest.raises(ValueError, match="No instances to run"):+ main(cmd)diff --git a/tests/test_replay.py b/tests/test_run_replay.pysimilarity index 94%rename from tests/test_replay.pyrename to tests/test_run_replay.pyindex d12f677c..2a7cccbd 100644--- a/tests/test_replay.py+++ b/tests/test_run_replay.py@@ -28,8 +28,8 @@ def test_replay(rr_config):def test_run_cli_help():args = [- "python",- "sweagent/run/run_replay.py",+ "sweagent",+ "run-replay","--help",]subprocess.run(args, check=True)diff --git a/tests/test_run_single.py b/tests/test_run_single.pynew file mode 100644index 00000000..4385281a--- /dev/null+++ b/tests/test_run_single.py@@ -0,0 +1,95 @@+from __future__ import annotations++from pathlib import Path++import pytest++from sweagent.agent.agents import AgentConfig+from sweagent.environment.swe_env import EnvironmentConfig+from sweagent.run.common import BasicCLI+from sweagent.run.hooks.abstract import RunHook+from sweagent.run.run_single import RunSingle, RunSingleConfig+++class RaisesExceptionHook(RunHook):+ def on_instance_start(self, *args, **kwargs):+ msg = "test exception"+ raise ValueError(msg)+++def test_run_single_raises_exception():+ rs = RunSingle.from_config(RunSingleConfig())+ rs.add_hook(RaisesExceptionHook())+ with pytest.raises(ValueError, match="test exception"):+ rs.run()+++def agent_config_with_commands():+ ac = AgentConfig()+ ac.command_files = [+ f"config/commands/{name}"+ for name in ["defaults.sh", "search.sh", "edit_linting.sh", "_split_string.py", "submit.sh"]+ ]+ return ac+++def test_run_ies(agent_config_with_commands):+ # ies = instant empty submit+ ac = agent_config_with_commands+ ac.model.name = "instant_empty_submit"+ rsc = RunSingleConfig(+ env=EnvironmentConfig(),+ agent=ac,+ )+ rs = RunSingle.from_config(rsc)+ rs.run()++[email protected]("repo", ["local", "github"])[email protected]("problem_statement_source", ["github", "local", "text"])+def test_run_ies_repo_ps_matrix(+ tmpdir,+ swe_agent_test_repo_clone,+ repo,+ problem_statement_source,+):+ output_formats = ["traj", "pred", "patch"]+ for fmt in output_formats:+ assert not list(Path(tmpdir).glob(f"*.{fmt}"))+ if problem_statement_source == "github":+ ps_args = ["--problem_statement.url", "https://github.com/swe-agent/test-repo/issues/1"]+ elif problem_statement_source == "local":+ ps_args = ["--problem_statement.path", str(swe_agent_test_repo_clone / "problem_statements" / "1.md")]+ elif problem_statement_source == "text":+ ps_args = ["--problem_statement.text='this is a test'"]+ else:+ raise ValueError(problem_statement_source)+ if repo == "local":+ repo_args = ["--env.repo.path", str(swe_agent_test_repo_clone)]+ elif repo == "github":+ repo_args = ["--env.repo.url", "https://github.com/swe-agent/test-repo"]+ else:+ raise ValueError(repo)+ args = [+ "--agent.model.name=instant_empty_submit",+ "--raise_exceptions=True",+ "--print_config=False",+ "--traj_dir",+ str(tmpdir),+ *ps_args,+ *repo_args,+ ]+ print(args)+ rs_config = BasicCLI(RunSingleConfig).get_args(args)+ print(rs_config)+ rs = RunSingle.from_config(rs_config) # type: ignore+ with tmpdir.as_cwd():+ # Test that we can run run.py also independently from repo dir+ rs.run()+ for fmt in output_formats:+ assert len(list(Path(tmpdir).glob(f"*.{fmt}"))) == 1+ print(fmt, list(Path(tmpdir).iterdir()))