diff --git a/.pr/491-main-linux.png b/.pr/491-main-linux.png new file mode 100644 index 00000000..1a29e4c3 Binary files /dev/null and b/.pr/491-main-linux.png differ diff --git a/.pr/491-pr-linux.png b/.pr/491-pr-linux.png new file mode 100644 index 00000000..dc0232c6 Binary files /dev/null and b/.pr/491-pr-linux.png differ diff --git a/.pr/repro491.sh b/.pr/repro491.sh new file mode 100755 index 00000000..25e577d8 --- /dev/null +++ b/.pr/repro491.sh @@ -0,0 +1,24 @@ +#!/bin/bash +# automation#491 reproduction attempt: git clone over SSH (local sshd, ~9 MB repo) +# 1) the issue's standalone asyncio.create_subprocess_exec script +# 2) Git Sync through the running automation service (uvicorn) +# usage: repro491.sh +REPO=$1; TAG=$2; rm -rf ~/run/$TAG +export GIT_SSH_COMMAND="$HOME/sshtest/ssh_wrap.sh -o BatchMode=yes" +URL="ssh://openhands@127.0.0.1:2222/home/openhands/sshtest/repo.git" +echo "checkout: $(git -C $REPO rev-parse --short HEAD) $(uname -s) $(uname -r | cut -d- -f1) $($REPO/.venv/bin/python --version) remote: $URL" +echo "\$ python repro_from_issue.py # asyncio.create_subprocess_exec git clone, 25s timeout" +echo " $($REPO/.venv/bin/python ~/sshtest/repro491.py $URL)" +export AUTOMATION_GIT_SYNC_REPO_URL=$URL AUTOMATION_GIT_SYNC_BRANCH=gitsync-test +~/run/start_stack.sh $REPO $TAG >/dev/null 2>&1 +until curl -sf localhost:8010/ready >/dev/null; do sleep 2; done +H="Authorization: Bearer dev-local-key"; B=localhost:8010/api/automation/v1 +echo "\$ curl -X POST $B/git-sync/sync # service under uvicorn"; curl -s -X POST -H "$H" $B/git-sync/sync; echo +START=$(date +%s); sleep 2 +while curl -s -H "$H" $B/git-sync/status | grep -q '"sync_in_progress":true'; do sleep 1; done +echo " (sync cycle finished after $(( $(date +%s) - START + 2 ))s)" +curl -s -H "$H" $B/git-sync/status | python3 -c ' +import json,sys; d=json.load(sys.stdin) +for k in ["last_synced_commit","last_error"]: + print(f" {k}: {d.get(k)}")' +kill $(cat ~/run/$TAG/*.pid) diff --git a/.pr/repro_from_issue.py b/.pr/repro_from_issue.py new file mode 100644 index 00000000..9cdee9c5 --- /dev/null +++ b/.pr/repro_from_issue.py @@ -0,0 +1,15 @@ +import asyncio, os, time, shutil, sys +URL = sys.argv[1] +async def main(): + dest = "/tmp/repro491-clone"; shutil.rmtree(dest, ignore_errors=True) + env = {**os.environ, "GIT_TERMINAL_PROMPT": "0"} + proc = await asyncio.create_subprocess_exec( + "git", "clone", "--origin", "origin", URL, dest, + env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + start = time.time() + try: + await asyncio.wait_for(proc.communicate(), timeout=25) + print("rc", proc.returncode, "in %.1fs" % (time.time()-start)) + except asyncio.TimeoutError: + proc.kill(); await proc.wait(); print("TIMED OUT after", time.time()-start) +asyncio.run(main()) diff --git a/openhands/automation/git_sync/client.py b/openhands/automation/git_sync/client.py index bc62ea22..1b499c1f 100644 --- a/openhands/automation/git_sync/client.py +++ b/openhands/automation/git_sync/client.py @@ -1,7 +1,13 @@ """Async wrapper around the `git` CLI. -Commands run via `create_subprocess_exec` with an argument list, never a shell -string. The auth token goes per-invocation through `-c http.extraHeader`, so it +Commands run as a blocking `subprocess.run` in the default thread-pool +executor, with an argument list, never a shell string. `clone`/`fetch` over SSH +were reported to stall with no data transferred when spawned through +`asyncio.create_subprocess_exec` (#491, macOS), while the same command in a +shell or via `subprocess.run` completed; a worker thread avoids asyncio's +subprocess machinery altogether. + +The auth token goes per-invocation through `-c http.extraHeader`, so it reaches neither the checkout nor a log line; credentials an operator embeds in the repo URL are ordinary arguments, so `redact_url_credentials` strips those from everything this module raises or logs. The token itself is persisted @@ -14,6 +20,7 @@ import logging import os import re +import subprocess from pathlib import Path from typing import Final @@ -181,32 +188,31 @@ async def _run_git_once( logged_args = ["git", *(redact_url_credentials(arg) for arg in args)] logger.debug("Running: %s (cwd=%s)", " ".join(logged_args), cwd) - try: - proc = await asyncio.create_subprocess_exec( - *full_args, + def _blocking_run() -> subprocess.CompletedProcess[bytes]: + return subprocess.run( + full_args, cwd=str(cwd) if cwd else None, env=_non_interactive_env(), - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE, + capture_output=True, + timeout=timeout, ) - except FileNotFoundError as e: - raise GitSyncError("git executable not found") from e try: - stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout) - except TimeoutError: - proc.kill() - await proc.wait() + result = await asyncio.get_running_loop().run_in_executor(None, _blocking_run) + except FileNotFoundError as e: + raise GitSyncError("git executable not found") from e + except subprocess.TimeoutExpired: + # subprocess.run has already killed and reaped the process. raise GitSyncError( f"git command timed out after {timeout}s: {' '.join(logged_args)}" ) from None - if proc.returncode != 0: + if result.returncode != 0: # git echoes the remote URL back in its own failure messages, so stderr # needs the same redaction as the argv. - details = redact_url_credentials(stderr.decode(errors="replace").strip()) + details = redact_url_credentials(result.stderr.decode(errors="replace").strip()) message = ( - f"git command failed ({proc.returncode}): {' '.join(logged_args)}\n" + f"git command failed ({result.returncode}): {' '.join(logged_args)}\n" f"{details}" ) # Auth/access failures are persistent; the loop backs off on GitAuthError @@ -214,7 +220,7 @@ async def _run_git_once( if _looks_like_auth_failure(details): raise GitAuthError(message) raise GitSyncError(message) - return stdout.decode(errors="replace") + return result.stdout.decode(errors="replace") async def check_remote_access( diff --git a/tests/test_git_sync_client.py b/tests/test_git_sync_client.py index 83682509..39518d8d 100644 --- a/tests/test_git_sync_client.py +++ b/tests/test_git_sync_client.py @@ -357,13 +357,13 @@ async def test_run_git_passes_the_non_interactive_env_to_the_subprocess( `env=` from the subprocess call would silently allow that again. """ captured: dict[str, str] = {} - real_exec = asyncio.create_subprocess_exec + real_run = subprocess.run - async def spy(*args, **kwargs): + def spy(args, **kwargs): captured.update(kwargs.get("env") or {}) - return await real_exec(*args, **kwargs) + return real_run(args, **kwargs) - monkeypatch.setattr(asyncio, "create_subprocess_exec", spy) + monkeypatch.setattr(subprocess, "run", spy) workdir = tmp_path / "clone" await ensure_repo(workdir, _repo_url(origin), "main", token="", timeout=30) @@ -382,6 +382,48 @@ def test_non_interactive_env_disables_every_prompt(self): assert "PATH" in env +class TestSubprocessRunner: + """#491: clone/fetch over SSH stalled under `asyncio.create_subprocess_exec`.""" + + async def test_clone_and_fetch_do_not_use_asyncio_subprocesses( + self, tmp_path, origin, monkeypatch + ): + async def forbidden(*args, **kwargs): + raise AssertionError("git must not run via asyncio.create_subprocess_exec") + + monkeypatch.setattr(asyncio, "create_subprocess_exec", forbidden) + + workdir = tmp_path / "clone" + await ensure_repo(workdir, _repo_url(origin), "main", token="", timeout=30) + await pull(workdir, "main", token="", timeout=30) + + async def test_a_slow_git_command_does_not_block_the_event_loop( + self, tmp_path, monkeypatch + ): + hang = tmp_path / "hang.sh" + hang.write_text("#!/bin/sh\nsleep 30\n") + hang.chmod(0o755) + monkeypatch.setenv("GIT_SSH_COMMAND", str(hang)) + ticks = 0 + + async def ticker(): + nonlocal ticks + while True: + await asyncio.sleep(0.05) + ticks += 1 + + task = asyncio.create_task(ticker()) + try: + with pytest.raises(GitSyncError, match="timed out after 1.0s"): + await check_remote_access( + "ssh://git@example.invalid/org/repo.git", "main", "", timeout=1.0 + ) + finally: + task.cancel() + # The loop kept running while git waited in its worker thread. + assert ticks >= 10 + + class TestCurrentHead: async def test_none_on_unborn_branch(self, tmp_path, origin): workdir = tmp_path / "clone" @@ -427,13 +469,13 @@ async def test_leaves_no_checkout_behind(self, tmp_path, origin, monkeypatch): """`ls-remote` and nothing else: a check must not clone, and must not run any command that could write to the remote.""" commands: list[list[str]] = [] - real_exec = asyncio.create_subprocess_exec + real_run = subprocess.run - async def spy(*args, **kwargs): + def spy(args, **kwargs): commands.append(list(args)) - return await real_exec(*args, **kwargs) + return real_run(args, **kwargs) - monkeypatch.setattr(asyncio, "create_subprocess_exec", spy) + monkeypatch.setattr(subprocess, "run", spy) monkeypatch.chdir(tmp_path) await check_remote_access(_repo_url(origin), "main", token="", timeout=30) @@ -553,15 +595,9 @@ def rejecting_exec(self, monkeypatch): way a remote refuses them: a 401 turns into git's username prompt, which the non-interactive env converts into this exact stderr.""" state = {"rejected": {"basic"}, "headers": []} - real_exec = asyncio.create_subprocess_exec - - class Rejected: - returncode = 128 + real_run = subprocess.run - async def communicate(self): - return b"", TestAuthScheme.REJECTED - - async def spy(*args, **kwargs): + def spy(args, **kwargs): headers = [ arg.removeprefix("http.extraHeader=") for arg in args @@ -571,7 +607,9 @@ async def spy(*args, **kwargs): state["headers"].append(header) scheme = header.split()[1].lower() if header else None if scheme in state["rejected"]: - return Rejected() + return subprocess.CompletedProcess( + args, 128, b"", TestAuthScheme.REJECTED + ) stripped = [ arg for index, arg in enumerate(args) @@ -580,9 +618,9 @@ async def spy(*args, **kwargs): or (arg == "-c" and str(args[index + 1]).startswith("http.extra")) ) ] - return await real_exec(*stripped, **kwargs) + return real_run(stripped, **kwargs) - monkeypatch.setattr(asyncio, "create_subprocess_exec", spy) + monkeypatch.setattr(subprocess, "run", spy) return state def test_basic_header_names_x_access_token(self):