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]

Fix: Do not restart env on failure; consolidate close methods

Kilian Lierete610838ef947
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index ed75050a..6a48bd37 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -224,7 +224,7 @@ class Agent:
"""Setup the agent for a new attempt. This includes resetting the model stats."""
if self._i_attempt > 0:
assert self._env is not None # mypy
- self._env.reset_for_new_attempt()
+ self._env.reset()
self.model.reset_stats()
self.add_system_message_to_history()
self.add_demonstrations_to_history()
@@ -571,18 +571,20 @@ class Agent:
)
except RuntimeError as e:
if not self._catch_errors:
+ self._env.close()
raise
observation = e.args[1] if len(e.args) > 1 else ""
observation += "COMMAND FAILED TO EXECUTE. RESTARTING PROCESS."
info["exit_status"] = "exit_environment_error"
self.logger.warning(f"Failed to execute command: {e}\nRESTARTING PROCESS.")
- # todo: Are we doing this here or somewhere else?
- self._env.reset_container()
+ self._env.close()
return observation, True, info
# todo: Should this also be handled in the exit status?
except Exception:
if not self._catch_errors:
+ self._env.close()
raise
+ self._env.close()
observation = "Unknown exception"
self.logger.exception("Unknown exception")
return observation, True, info
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 2c130671..23802f26 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -71,8 +71,9 @@ class SWEEnv:
self._chook.add_hook(hook)
def start(self) -> None:
- """Start the environment"""
+ """Start the environment and reset it to a clean state."""
self._init_deployment()
+ self.reset()
def _copy_repo(self) -> None:
"""Clone/copy repository/codebase in container"""
@@ -88,15 +89,9 @@ class SWEEnv:
# todo: Get rid of return type here?
def reset(self) -> tuple[str | None, dict]:
- """Reset the container between each task instance.
-
- * Clones instance's repository
- * Cleans repository of prior modifications
- * Resets environment variables
- * Check out base commit
-
- Args:
- index: index of task instance to reset to
+ """Reset the environment to a clean state.
+ Gets called by `start`, but can also be called independently to reset the
+ environment to a clean state before a new attempt.
Returns:
observation: output from container
@@ -112,6 +107,7 @@ class SWEEnv:
def _reset_repository(self) -> None:
"""Clean repository of any modifications + Checkout base commit"""
if self.repo is not None:
+ self.logger.debug("Resetting repository %s to commit %s", self.repo.repo_name, self.repo.base_commit)
startup_commands = [
f"cd /{self.repo.repo_name}",
"export ROOT=$(pwd -P)",
@@ -126,15 +122,6 @@ class SWEEnv:
error_msg="Failed to clean repository",
)
- # todo: Shouldn't this be the same as reset meanwhile?
- def reset_for_new_attempt(
- self,
- ) -> None:
- """Compared to `reset`, which prepares the container for a new instance,
- this prepares the container for taking another shot at the same instance.
- """
- self._reset_repository()
-
def close(self) -> None:
"""Shoutdown SWE-ReX deployment etc."""
self.logger.info("Beginning environment shutdown...")
@@ -143,10 +130,6 @@ class SWEEnv:
# MARK: Helper functions #
- def reset_container(self) -> None:
- self.close()
- self._init_deployment()
-
def _init_deployment(
self,
) -> None:
diff --git a/sweagent/run/run_batch.py b/sweagent/run/run_batch.py
index 1a923c93..0db06d3e 100644
--- a/sweagent/run/run_batch.py
+++ b/sweagent/run/run_batch.py
@@ -145,8 +145,6 @@ class RunBatch:
self.logger.info("Starting environment")
env = SWEEnv.from_config(instance.env)
env.start()
- self.logger.info("Resetting environment")
- env.reset()
self.logger.info("Running agent")
self._chooks.on_instance_start(index=0, env=env, problem_statement=instance.problem_statement)
result = self.agent.run(
diff --git a/sweagent/run/run_single.py b/sweagent/run/run_single.py
index 47f271df..337841ec 100644
--- a/sweagent/run/run_single.py
+++ b/sweagent/run/run_single.py
@@ -128,8 +128,6 @@ class RunSingle:
self._chooks.on_start()
self.logger.info("Starting environment")
self.env.start()
- self.logger.info("Resetting environment")
- self.env.reset()
self.logger.info("Running agent")
self._chooks.on_instance_start(index=0, env=self.env, problem_statement=self.problem_statement)
result = self.agent.run(
diff --git a/tests/test_env.py b/tests/test_env.py
index dfaebf01..3ba13c9f 100644
--- a/tests/test_env.py
+++ b/tests/test_env.py
@@ -13,29 +13,28 @@ from .conftest import swe_env_context
@pytest.mark.slow
def test_init_swe_env(test_env_args):
- with swe_env_context(test_env_args) as env:
- env.reset()
+ with swe_env_context(test_env_args):
+ pass
@pytest.mark.slow
def test_init_swe_env_conservative_clone(test_env_args):
with mock.patch.dict("os.environ", {"SWE_AGENT_CLONE_METHOD": "full"}):
- with swe_env_context(test_env_args) as env:
- env.reset()
+ with swe_env_context(test_env_args):
+ pass
@pytest.mark.slow
def test_startup_commands(test_env_args):
test_script = "echo 'hello world'"
test_env_args.startup_commands = [test_script]
- with swe_env_context(test_env_args) as env:
- env.reset()
+ with swe_env_context(test_env_args):
+ pass
@pytest.mark.slow
def test_read_file(tmp_path, test_env_args):
with swe_env_context(test_env_args) as env:
- env.reset()
content = env.read_file(Path("tests/filetoread.txt"))
assert content.splitlines()[-1].strip() == "SWEEnv.read_file"
@@ -50,13 +49,11 @@ def test_env_with_hook(test_env_args):
@pytest.mark.slow
def test_env_communicate_with_handling(test_env_args):
with swe_env_context(test_env_args) as env:
- env.reset()
env.communicate("echo 'hello world'", check=True, error_msg="Failed to echo")
@pytest.mark.slow
def test_env_communicate_with_handling_timeout(test_env_args):
with swe_env_context(test_env_args) as env:
- env.reset()
with pytest.raises(CommandTimeoutError):
env.communicate("sleep 10", check=True, error_msg="Failed to sleep", timeout=0.2)