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]

Switch to fast communicate and sparse clone by default (#530)

Kilian Lieret0a4a93871aa7
diff --git a/docs/config/env.md b/docs/config/env.md
index c7d8cc31..059eee44 100644
--- a/docs/config/env.md
+++ b/docs/config/env.md
@@ -7,9 +7,11 @@
This page details all environment variables that are currently in use by SWE-agent.
* All API keys (for LMs and GitHub) can be set as an environment variable. See [here](../installation/keys.md) for more information.
-* [Experimental] `SWE_AGENT_EXPERIMENTAL_COMMUNICATE` switches to a faster way of communicating with running docker
- shell sessions. This has not been tested on SWE-bench, so it might sometimes break.
- However, it can be very useful when running on single issues.
-* [Experimental] `SWE_AGENT_EXPERIMENTAL_CLONE`: Uses sparse clones
-* `SWE_AGENT_DOCKER_START_UP_DELAY`: Number of seconds to wait after starting a docker container
-* `SWE_AGENT_CONFIG_ROOT`: Used to resolve relative paths in the [config](config.md)
\ No newline at end of file
+* `SWE_AGENT_CONFIG_ROOT`: Used to resolve relative paths in the [config](config.md)
+
+!!! warning "Unstable"
+ The following variables might still be subject to change
+
+* `SWE_AGENT_COMMUNICATE_METHOD`: Determines how SWE-agent communicates with the running process in the docker container: `end-marker` (default, fast) or `processes` (legacy, slow, more tested)
+* `SWE_AGENT_CLONE_METHOD`: `sparse` (default) or `full`. When using persistent containers or running over multiple problem statements, we fall back to `full`.
+* `SWE_AGENT_DOCKER_START_UP_DELAY`: Number of seconds to wait after starting a docker container
\ No newline at end of file
diff --git a/docs/usage/cl_tutorial.md b/docs/usage/cl_tutorial.md
index 8fd3e228..02599bd0 100644
--- a/docs/usage/cl_tutorial.md
+++ b/docs/usage/cl_tutorial.md
@@ -119,23 +119,13 @@ The config file can have the following keys:
## Speeding up SWE-agent
+!!! tip "Speed up in v0.6"
+ SWE-agent v0.6 saw major speedups. Please upgrade to the latest version.
+
If you solve multiple issues from the same repository/in the same environment, you can specify the
`--cache_task_images` flag. This will create a persistent docker image with the initialized environment
required for the problem.
-We are also testing several changes that speed up SWE-agent. They can be enabled as [environment variables](../config/env.md) or added to `keys.cfg`:
-
-```bash
-# Faster communication with docker container
-export SWE_AGENT_EXPERIMENTAL_COMMUNICATE="1"
-# Sparse git clone
-export SWE_AGENT_EXPERIMENTAL_CLONE="1"
-# Reduce time for docker startup
-export SWE_AGENT_DOCKER_START_UP_DELAY="1"
-```
-
-See [environment variables](../config/env.md) for more details.
-
## Taking actions
* As mentioned [above](#specifying-the-repository), you can use `--apply_patch_locally` to have SWE-agent apply successful solution attempts to local files.
diff --git a/sweagent/api/server.py b/sweagent/api/server.py
index 4e63c03a..a648132f 100644
--- a/sweagent/api/server.py
+++ b/sweagent/api/server.py
@@ -11,7 +11,6 @@ except ImportError as e:
import atexit
import copy
import json
-import os
import sys
import tempfile
import time
@@ -26,7 +25,6 @@ from flask import Flask, make_response, render_template, request, session
from flask_cors import CORS
from flask_socketio import SocketIO
-import sweagent.environment.utils as env_utils
from sweagent import CONFIG_DIR, PACKAGE_DIR
from sweagent.agent.agents import AgentArguments
from sweagent.agent.models import ModelArguments
@@ -49,9 +47,6 @@ app.config["SESSION_TYPE"] = "memcache"
THREADS: dict[str, MainThread] = {}
-os.environ["SWE_AGENT_EXPERIMENTAL_COMMUNICATE"] = "1"
-env_utils.DOCKER_START_UP_DELAY = 1
-
def ensure_session_id_set():
"""Ensures a session ID is set for this user"""
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 272867e1..852b7d79 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -238,7 +238,11 @@ class SWEEnv(gym.Env):
else:
logger.info("Trying to clone from non-mirror...")
clone_url = f"https://{token_prefix}github.com/{self.record['repo']}.git"
- if not keys_config.get("SWE_AGENT_EXPERIMENTAL_CLONE"):
+ clone_method = keys_config.get("SWE_AGENT_CLONE_METHOD", default="sparse", choices=["sparse", "full"])
+ if len(self.data) > 1 or self.persistent:
+ msg = "Falling back to full cloning method due to multiple instances or persistent container"
+ logger.debug(msg)
+ if clone_method == "full":
self.communicate_with_handling(
input=f"git clone {clone_url} {self._repo_name}",
error_msg="Failed to clone repository from conservative method",
@@ -642,7 +646,10 @@ class SWEEnv(gym.Env):
input: str,
timeout_duration=25,
) -> str:
- if "SWE_AGENT_EXPERIMENTAL_COMMUNICATE" in keys_config:
+ communicate_method = keys_config.get(
+ "SWE_AGENT_COMMUNICATE_METHOD", default="end-marker", choices=["end-marker", "processes"]
+ )
+ if communicate_method == "end-marker":
return self._communicate_experimental(input, timeout_duration)
try:
self.returncode = None
diff --git a/sweagent/utils/config.py b/sweagent/utils/config.py
index 97576201..8e218390 100644
--- a/sweagent/utils/config.py
+++ b/sweagent/utils/config.py
@@ -49,12 +49,26 @@ class Config:
else:
logger.error(f"keys.cfg not found in {PACKAGE_DIR}")
- def get(self, key: str, default=None) -> Any:
+ def get(self, key: str, default=None, choices: list[Any] | None = None) -> Any:
+ """Get a key from environment variables or keys.cfg.
+
+ Args:
+ key: The key to retrieve.
+ default: The default value to return if the key is not found.
+ choices: If provided, the value must be one of the choices.
+ """
+
+ def check_choices(value):
+ if choices is not None and value not in choices:
+ msg = f"Value {value} for key {key} not in {choices}"
+ raise ValueError(msg)
+ return value
+
if key in os.environ:
- return os.environ[key]
+ return check_choices(os.environ[key])
if self._keys_cfg is not None and key in self._keys_cfg:
- return self._keys_cfg[key]
- return default
+ return check_choices(self._keys_cfg[key])
+ return check_choices(default)
def __getitem__(self, key: str) -> Any:
if key in os.environ:
diff --git a/tests/conftest.py b/tests/conftest.py
index e3d4b8cd..03563c03 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,23 +1,17 @@
from __future__ import annotations
import json
-import os
import sys
from pathlib import Path
import pytest
-import sweagent.environment.utils as env_utils
-
# this is a hack and should be removed when we have a better solution
_this_dir = Path(__file__).resolve().parent
root_dir = _this_dir.parent
package_dir = root_dir / "sweagent"
sys.path.insert(0, str(root_dir))
sys.path.insert(1, str(package_dir))
-os.environ["SWE_AGENT_EXPERIMENTAL_COMMUNICATE"] = "1"
-os.environ["SWE_AGENT_EXPERIMENTAL_CLONE"] = "1"
-env_utils.DOCKER_START_UP_DELAY = 1
@pytest.fixture()
diff --git a/tests/test_env.py b/tests/test_env.py
index 3236dbdb..94f57cc1 100644
--- a/tests/test_env.py
+++ b/tests/test_env.py
@@ -27,7 +27,8 @@ def test_env_args(
data_path=str(data_path),
repo_path=str(local_repo_path),
image_name="sweagent/swe-agent:latest",
- container_name="test-container-134245890345098",
+ container_name="test-container-this-is-a-random-string",
+ verbose=True,
)
yield test_env_args
# Cleanup (after session ends)
@@ -57,7 +58,7 @@ def test_init_swe_env(test_env_args):
@pytest.mark.slow()
def test_init_swe_env_conservative_clone(test_env_args):
- with mock.patch.dict("os.environ", {"SWE_AGENT_EXPERIMENTAL_CLONE": ""}):
+ with mock.patch.dict("os.environ", {"SWE_AGENT_CLONE_METHOD": "full"}):
with swe_env_context(test_env_args) as env:
env.reset()
@@ -142,7 +143,7 @@ def test_interrupt_close(test_env_args):
@pytest.mark.slow()
def test_communicate_old(test_env_args):
- with mock.patch.dict("os.environ", {"SWE_AGENT_EXPERIMENTAL_COMMUNICATE": ""}):
+ with mock.patch.dict("os.environ", {"SWE_AGENT_COMMUNICATE_METHOD": "processes"}):
with swe_env_context(test_env_args) as env:
env.reset()
diff --git a/tests/test_run.py b/tests/test_run.py
index 69f9c081..541968ac 100644
--- a/tests/test_run.py
+++ b/tests/test_run.py
@@ -1,6 +1,8 @@
from __future__ import annotations
+import dataclasses
import json
+import logging
import os
import subprocess
from pathlib import Path
@@ -8,6 +10,7 @@ from typing import Any
import pytest
+import docker
from run import ActionsArguments, Main, MainHook, OpenPRHook, ScriptArguments
from sweagent.agent.agents import Agent, AgentArguments, AgentHook
from sweagent.agent.models import ModelArguments
@@ -108,7 +111,7 @@ def test_script_args():
verbose=True,
install_environment=True,
),
- skip_existing=True,
+ skip_existing=False,
agent=AgentArguments(
model=ModelArguments(
model_name="instant_empty_submit",
@@ -126,7 +129,7 @@ def test_script_args():
@pytest.mark.slow()
-def test_exception_raised(test_script_args):
+def test_exception_raised(test_script_args: ScriptArguments):
assert test_script_args.raise_exceptions
main = Main(test_script_args)
main.add_hook(RaisesExceptionHook())
@@ -151,21 +154,54 @@ class CreateFakeLogFile(MainHook):
@pytest.mark.slow()
-def test_existing_corrupted_args(test_script_args):
+def test_existing_corrupted_args(test_script_args: ScriptArguments):
main = Main(test_script_args)
main.add_hook(CreateFakeLogFile())
main.main()
@pytest.mark.slow()
-def test_main_hook(test_script_args):
+def test_main_hook(test_script_args: ScriptArguments):
main = Main(test_script_args)
main.add_hook(MainHook())
main.main()
@pytest.mark.slow()
-def test_agent_with_hook(test_script_args):
+def test_agent_with_hook(test_script_args: ScriptArguments):
main = Main(test_script_args)
main.agent.add_hook(AgentHook())
main.main()
+
+
+PERSISTENT_CONTAINER_NAME = "sweagent-test-persistent-container"
+
+
+def _cleanup_persistent_container():
+ yield
+ client = docker.from_env()
+ container = client.containers.get(PERSISTENT_CONTAINER_NAME)
+ container.remove(force=True)
+
+
[email protected]("_cleanup_persistent_container")
+def test_agent_persistent_container(test_script_args: ScriptArguments, capsys):
+ test_script_args = dataclasses.replace(
+ test_script_args,
+ environment=dataclasses.replace(test_script_args.environment, container_name=PERSISTENT_CONTAINER_NAME),
+ )
+ assert test_script_args.environment.verbose
+ main = Main(test_script_args)
+ assert main.env.logger.isEnabledFor(logging.DEBUG)
+ main.main()
+ captured = capsys.readouterr()
+ print("---")
+ print(captured.out)
+ print("---")
+ print(captured.err)
+ print("---")
+ text = captured.out + captured.err
+ assert "Trying to clone from non-mirror..." in text
+ assert "Falling back to full cloning method" in text
diff --git a/tests/test_utils.py b/tests/test_utils.py
index c9a32748..ee260c9f 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -35,6 +35,26 @@ def test_retrieve_from_env(tmp_path):
assert config["MY_KEY"] == "VALUE"
+def test_retrieve_choices():
+ """Check that a valueerror is raised if the value is not in the choices."""
+ match = "Value.*not in.*"
+ config = Config()
+ with pytest.raises(ValueError, match=match):
+ config.get("DOESNTEXIST", default="x", choices=["a", "b", "c"])
+ with pytest.raises(ValueError, match=match):
+ with mock.patch.dict("os.environ", {"MY_KEY": "VALUE"}):
+ config.get("DOESNTEXIST", choices=["a", "b", "c"])
+
+
+def test_retrieve_choices_config_file(tmp_path):
+ match = "Value.*not in.*"
+ tmp_keys_cfg = tmp_path / "keys.cfg"
+ tmp_keys_cfg.write_text("MY_KEY: 'VALUE'\n")
+ config = Config(keys_cfg_path=tmp_keys_cfg)
+ with pytest.raises(ValueError, match=match):
+ config.get("MY_KEY", choices=["a", "b", "c"])
+
+
def test_convert_path_to_abspath():
assert convert_path_to_abspath("sadf") == REPO_ROOT / "sadf"
assert convert_path_to_abspath("/sadf") == Path("/sadf")