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]
no output timeout
Talor Abramovich1e58453d2186
diff --git a/docker/swe-ctf.Dockerfile b/docker/swe-ctf.Dockerfileindex d2782354..3240e9b7 100644--- a/docker/swe-ctf.Dockerfile+++ b/docker/swe-ctf.Dockerfile@@ -64,6 +64,7 @@ RUN pip install -r /root/requirements.txt && rm -f /root/requirements.txtRUN cd /opt && git clone https://github.com/RsaCtfTool/RsaCtfTool.git && apt-get install -y libgmp3-dev libmpc-dev && cd RsaCtfTool && pip3 install -r "requirements.txt"COPY docker/number_theory__fixed /opt/RsaCtfTool/lib/number_theory.pyENV PATH=$PATH:/opt/RsaCtfTool+ENV PYTHONUNBUFFERED=1WORKDIR /diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex c399e5e3..24c4b54a 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -36,6 +36,7 @@ from sweagent.environment.utils import (PROCESS_DONE_MARKER_END,PROCESS_DONE_MARKER_START,InvalidGithubURL,+ NoOutputTimeoutError,PatchFormatter,attach_network_interface_to_container,copy_anything_to_container,@@ -59,6 +60,7 @@ from sweagent.utils.log import default_logger, get_loggerLONG_TIMEOUT = float(keys_config.get("SWE_AGENT_ENV_LONG_TIMEOUT", 500))AGENT_ACTION_TIMEOUT = float(keys_config.get("SWE_AGENT_ACTION_TIMEOUT", 25))+AGENT_ACTION_NO_OUTPUT_TIMEOUT = float(keys_config.get("SWE_AGENT_ACTION_NO_OUTPUT_TIMEOUT", AGENT_ACTION_TIMEOUT))PATH_TO_REQS = "/root/requirements.txt"PATH_TO_ENV_YML = "/root/environment.yml"@@ -521,12 +523,20 @@ class SWEEnv(gym.Env):else:try:observation += self.communicate_session(- command, self.args.interactive_sessions_config[session_name].terminal_prompt_pattern+ command,+ self.args.interactive_sessions_config[session_name].terminal_prompt_pattern,+ AGENT_ACTION_TIMEOUT,+ AGENT_ACTION_NO_OUTPUT_TIMEOUT,)- except TimeoutError:+ except TimeoutError as e:try:observation = self.interrupt_interactive(session_name=session_name)observation += "\nEXECUTION TIMED OUT"+ observation += (+ f" BECAUSE NO OUTPUT WAS PRODUCED FOR MORE THAN {AGENT_ACTION_NO_OUTPUT_TIMEOUT} SECONDS"+ if isinstance(e, NoOutputTimeoutError)+ else f" BECAUSE THE COMMAND WAS RUNNING FOR MORE THAN {AGENT_ACTION_TIMEOUT} SECONDS"+ )except Exception as e:observation += ("\nEXECUTION TIMED OUT AND INTERRUPT FAILED. TERMINATING INTERACTIVE SESSION."@@ -600,12 +610,22 @@ class SWEEnv(gym.Env):# Attempt to run action in containerobservation = ""try:- observation = self.communicate(input=action, timeout_duration=AGENT_ACTION_TIMEOUT, set_last_action=True)+ observation = self.communicate(+ input=action,+ timeout_duration=AGENT_ACTION_TIMEOUT,+ no_output_timeout_duration=AGENT_ACTION_NO_OUTPUT_TIMEOUT,+ set_last_action=True,+ )except TimeoutError as e:try:observation += e.args[1] if len(e.args) > 1 else ""observation += self.interrupt()observation += "\nEXECUTION TIMED OUT"+ observation += (+ f" BECAUSE NO OUTPUT WAS PRODUCED FOR MORE THAN {AGENT_ACTION_NO_OUTPUT_TIMEOUT} SECONDS"+ if isinstance(e, NoOutputTimeoutError)+ else f" BECAUSE THE COMMAND WAS RUNNING FOR MORE THAN {AGENT_ACTION_TIMEOUT} SECONDS"+ )except RuntimeError as e:observation += "\nEXECUTION TIMED OUT AND INTERRUPT FAILED. RESTARTING PROCESS."info["exit_status"] = "early_exit"@@ -841,6 +861,7 @@ class SWEEnv(gym.Env):self,input: str,timeout_duration: int | float = 25,+ no_output_timeout_duration: int | float = 25,) -> str:"""Experimental version of `_communicate`"""assert self.container is not None@@ -863,7 +884,9 @@ class SWEEnv(gym.Env):raise RuntimeError(msg)try:- buffer, exit_code = read_with_timeout_experimental(self.container, timeout_duration)+ buffer, exit_code = read_with_timeout_experimental(+ self.container, timeout_duration, no_output_timeout_duration+ )except Exception:msg = f"Read with timeout failed on input:\n---\n{input}\n---"self.logger.error(msg)@@ -890,19 +913,21 @@ class SWEEnv(gym.Env):self,input: str,timeout_duration: int | float = 25,+ no_output_timeout_duration: int | float = 25,) -> str:"""Runs command in container and returns outputArgs:input: command to run in containertimeout_duration: duration to wait for output+ no_output_timeout_duration: duration to wait when the process stopped produce any output"""assert self.container is not Nonecommunicate_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)+ return self._communicate_experimental(input, timeout_duration, no_output_timeout_duration)try:self.returncode = Nonecmd = input if input.endswith("\n") else input + "\n"@@ -940,7 +965,14 @@ class SWEEnv(gym.Env):output = self._communicate(f"/bin/bash -n <<'EOF'\n{input}\nEOF\n")return output, self.returncode == 0- def communicate(self, input: str, timeout_duration: int | float = 25, *, set_last_action: bool = False) -> str:+ def communicate(+ self,+ input: str,+ timeout_duration: int | float = 25,+ no_output_timeout_duration: int | float | None = None,+ *,+ set_last_action: bool = False,+ ) -> str:"""Sends input to container and returns output@@ -952,6 +984,8 @@ class SWEEnv(gym.Env):Returns:output: output from container"""+ if no_output_timeout_duration is None:+ no_output_timeout_duration = timeout_durationif input.strip() != "exit":self.logger.log(logging.TRACE, "Input:\n%s", input) # type: ignoreoutput, valid = self._check_syntax(input)@@ -960,6 +994,7 @@ class SWEEnv(gym.Env):output = self._communicate(input,timeout_duration=timeout_duration,+ no_output_timeout_duration=no_output_timeout_duration,)self.logger.log(logging.TRACE, "Output:\n%s", output) # type: ignoreself.communicate_output = output@@ -968,7 +1003,7 @@ class SWEEnv(gym.Env):# handling.last_action_string = shlex.quote(input.strip())input = f"export LAST_ACTION={last_action_string}"- self._communicate(input, timeout_duration=5)+ self._communicate(input, timeout_duration=5, no_output_timeout_duration=5)return outputelse:self.container.terminate()@@ -996,7 +1031,13 @@ class SWEEnv(gym.Env):raise RuntimeError(msg)return logs- def communicate_session(self, input: str, terminal_pattern: str, timeout_duration: int | float = 25) -> str:+ def communicate_session(+ self,+ input: str,+ terminal_pattern: str,+ timeout_duration: int | float = 25,+ no_output_timeout_duration: int | float = 25,+ ) -> str:"""Sends input to interactive_session and returns output@@ -1033,7 +1074,7 @@ class SWEEnv(gym.Env):try:buffer = read_session_with_timeout(- self.interactive_session.session_process, terminal_pattern, timeout_duration+ self.interactive_session.session_process, terminal_pattern, timeout_duration, no_output_timeout_duration)except Exception:msg = f"Read with timeout failed on input:\n---\n{input}\n---"@@ -1398,6 +1439,9 @@ class SWEEnv(gym.Env):self.interactive_session.session_process,terminal_pattern=self.args.interactive_sessions_config[session_name].terminal_prompt_pattern,timeout_duration=self.args.interactive_sessions_config[session_name].timeout_duration_on_interrupt,+ no_output_timeout_duration=self.args.interactive_sessions_config[+ session_name+ ].timeout_duration_on_interrupt,)def interrupt(self) -> str:@@ -1408,7 +1452,9 @@ class SWEEnv(gym.Env):assert self.container_obj is not Nonepids = self.get_pids()for pid, _ in pids:- self.container_obj.exec_run(f"kill -9 {pid}")+ # Sending signal several times ensures that the process is dead+ for _ in range(3):+ self.container_obj.exec_run(f"kill -9 {pid}")try:observation = read_with_timeout(self.container, self.get_pids, 20)except TimeoutError:diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.pyindex cb93757f..b98e653b 100644--- a/sweagent/environment/utils.py+++ b/sweagent/environment/utils.py@@ -46,6 +46,9 @@ CTF_CHALLENGES_CATEGORIES = {logger = get_logger("env_utils")+class NoOutputTimeoutError(TimeoutError): ...++def get_data_path_name(data_path: str) -> str:"""if data_path is a file, return the file stemelif it's a github url, return the owner__repo_name@@ -212,7 +215,9 @@ def _check_for_too_many_non_unicode_bytes(buffer: bytes):raise UnicodeError(msg)-def read_with_timeout_experimental(container: subprocess.Popen, timeout_duration: int | float) -> tuple[str, str]:+def read_with_timeout_experimental(+ container: subprocess.Popen, timeout_duration: int | float, no_output_timeout_duration: int | float+) -> tuple[str, str]:"""Read data from a subprocess with a timeout.This function uses a file descriptor to read data from the subprocess in a non-blocking way.@@ -223,6 +228,7 @@ def read_with_timeout_experimental(container: subprocess.Popen, timeout_durationArgs:container: The subprocess container.timeout_duration: The timeout duration in seconds.+ no_output_timeout_duration: The timeout duration to wait if no output is produced, in seconds.Returns:Output and exit code, both as strings (!)@@ -232,7 +238,9 @@ def read_with_timeout_experimental(container: subprocess.Popen, timeout_duration"""buffer = b""fd = container.stdout.fileno()- end_time = time.time() + timeout_duration+ start_time = time.time()+ end_time = start_time + timeout_duration+ end_time_no_output = start_time + no_output_timeout_duration# Select is not available on windowsis_windows = platform.system() == "Windows"@@ -247,7 +255,9 @@ def read_with_timeout_experimental(container: subprocess.Popen, timeout_durationreturn Truereturn bool(select.select([fd], [], [], 0.01)[0])- while time.time() < end_time:+ process_done = False++ while time.time() < min(end_time, end_time_no_output):if ready_to_read(fd):try:data = os.read(fd, 4096)@@ -255,8 +265,10 @@ def read_with_timeout_experimental(container: subprocess.Popen, timeout_durationlogger.error("BlockingIOError while reading from subprocess.", exc_info=True)breakif data:+ end_time_no_output = time.time() + no_output_timeout_durationbuffer += dataif PROCESS_DONE_MARKER_START in buffer.decode("utf-8", errors="backslashreplace").replace("\r\n", "\n"):+ process_done = Truebreaktime.sleep(0.01) # Prevents CPU hogging@@ -264,11 +276,17 @@ def read_with_timeout_experimental(container: subprocess.Popen, timeout_durationbody = "\n".join(line for line in decoded.splitlines() if not line.startswith(PROCESS_DONE_MARKER_START))if container.poll() is not None:- msg = f"Subprocess exited unexpectedly.\nCurrent buffer: {buffer.decode()}"+ msg = f"Subprocess exited unexpectedly.\nCurrent buffer: {decoded}"raise RuntimeError(msg)- if time.time() >= end_time:- msg = f"Timeout reached while reading from subprocess.\nCurrent buffer: {buffer.decode()}"- raise TimeoutError(msg, body)++ current_time = time.time()+ if not process_done and current_time >= min(end_time, end_time_no_output):+ if current_time >= end_time:+ msg = f"Timeout reached while reading from subprocess.\nCurrent buffer: {decoded}"+ raise TimeoutError(msg, body)+ else:+ msg = f"No output timeout reached while reading from subprocess.\nCurrent buffer: {decoded}"+ raise NoOutputTimeoutError(msg, body)_check_for_too_many_non_unicode_bytes(buffer=buffer)_results = PROCESS_DONE_REGEX.search(decoded)@@ -276,10 +294,15 @@ def read_with_timeout_experimental(container: subprocess.Popen, timeout_durationmsg = f"Could not find process done marker in last line: {decoded=}, {body=}"raise ValueError(msg)exit_code = _results.group(1)- return body, exit_code+ return body.replace(f"{PROCESS_DONE_MARKER_START}{exit_code}{PROCESS_DONE_MARKER_END}", ""), exit_code-def read_session_with_timeout(session: subprocess.Popen, terminal_pattern: str, timeout_duration: int | float) -> str:+def read_session_with_timeout(+ session: subprocess.Popen,+ terminal_pattern: str,+ timeout_duration: int | float,+ no_output_timeout_duration: int | float,+) -> str:"""Read data from a subprocess with a timeout.This function uses a file descriptor to read data from the subprocess in a non-blocking way.@@ -297,7 +320,9 @@ def read_session_with_timeout(session: subprocess.Popen, terminal_pattern: str,"""buffer = b""fd = session.stdout.fileno()- end_time = time.time() + timeout_duration+ start_time = time.time()+ end_time = start_time + timeout_duration+ end_time_no_output = start_time + no_output_timeout_duration# Select is not available on windowsimport select@@ -305,7 +330,8 @@ def read_session_with_timeout(session: subprocess.Popen, terminal_pattern: str,def ready_to_read(fd) -> bool:return bool(select.select([fd], [], [], 0.01)[0])- while time.time() < end_time:+ command_done = False+ while time.time() < min(end_time, end_time_no_output):if ready_to_read(fd):try:data = os.read(fd, 4096)@@ -313,20 +339,29 @@ def read_session_with_timeout(session: subprocess.Popen, terminal_pattern: str,logger.error("BlockingIOError while reading from subprocess.", exc_info=True)breakif data:+ end_time_no_output = time.time() + no_output_timeout_durationbuffer += dataif terminal_pattern in buffer.decode("utf-8", errors="backslashreplace").replace("\r\n", "\n"):+ command_done = Truebreaktime.sleep(0.01) # Prevents CPU hogging+ decoded = buffer.decode("utf-8", errors="backslashreplace").replace("\r\n", "\n")+ body = "\n".join(line for line in decoded.splitlines() if not line.startswith(terminal_pattern))+if session.poll() is not None:- msg = f"Subprocess exited unexpectedly.\nCurrent buffer: {buffer.decode()}"+ msg = f"Subprocess exited unexpectedly.\nCurrent buffer: {decoded}"raise RuntimeError(msg)- if time.time() >= end_time:- msg = f"Timeout reached while reading from subprocess.\nCurrent buffer: {buffer.decode()}"- raise TimeoutError(msg)+ current_time = time.time()+ if not command_done and current_time >= min(end_time, end_time_no_output):+ if current_time >= end_time:+ msg = f"Timeout reached while reading from subprocess.\nCurrent buffer: {decoded}"+ raise TimeoutError(msg, body)+ else:+ msg = f"No output timeout reached while reading from subprocess.\nCurrent buffer: {decoded}"+ raise NoOutputTimeoutError(msg, body)- decoded = buffer.decode("utf-8", errors="backslashreplace").replace("\r\n", "\n")- return "\n".join(line for line in decoded.splitlines() if not line.startswith(terminal_pattern))+ return bodydef get_background_pids(container_obj: Container):