Skip to content

Git Sync: a timed-out HTTPS clone/fetch overruns its timeout, orphans the git helper, and a killed clone breaks every later cycle #799

Todo

Description

@neubig

This issue was created by an AI agent (OpenHands) on behalf of @neubig.

Summary

When a Git Sync git clone or git fetch over HTTP(S) hits git_sync_git_timeout_seconds, three things go wrong in git_sync/client.py:

  1. The timeout is not a hard bound. _run_git_once kills only the top-level git process and then awaits proc.wait(). The transport helper (git remote-http / git-remote-https) inherited git's stdout/stderr pipes. On Python 3.12, asyncio.subprocess.Process.wait() only resolves once all pipes are closed. As a result the call blocks until the helper exits, and if the connection is stalled that can take forever. The error still says timed out after {timeout}s.
  2. The helper is orphaned. It is reparented to PID 1 and keeps its stalled connection open. Nothing reaps it.
  3. A clone killed by the timeout leaves a checkout that never recovers. The partial .git has HEAD → refs/heads/.invalid and remote.origin.url, but no remote.origin.fetch refspec. ensure_repo accepts any existing .git directory as a valid checkout, so every later cycle in that workdir fails at git symbolic-ref --short HEAD until someone deletes the directory.

There is also no stall detection. Git is not given http.lowSpeedLimit/http.lowSpeedTime, so a transfer that has stopped sending bytes uses the whole timeout budget, the same as a slow transfer that is still making progress.

This is not the same as #491 (an SSH clone/fetch stalling at zero bytes when spawned from asyncio). Open PR #493 (moving to subprocess.run in an executor) would make the timeout bounded again. It would not reap the helper and would not fix the stuck partial clone.

Impact

  • One stalled HTTPS transfer can keep a Git Sync cycle running far past its configured timeout. git_sync_loop runs due orgs one after another in a single task. That means one stalled org also holds up the cycles of every other org on that replica for the same time.
  • While the stalled cycle is still running, its lease (max(300 s, 5 × timeout)) can expire. Another replica can then start a second cycle for the same org.
  • Each stall leaves an orphaned git remote-http process and its socket in the service container.
  • After the first clone of an org's repo times out, that workdir can no longer sync. Every cycle that runs there records git command failed (128): git symbolic-ref --short HEAD … No such ref: HEAD in last_error, and repository updates are never imported. In local mode the workspace is persistent, so this lasts until someone deletes {workspace}/git-sync by hand. In cloud mode it lasts for the life of the pod that ran the failed clone.

Root cause

Timeout handling only kills the direct child. It then waits on a call that also waits for the grandchild's inherited pipes (client.py#L184-L205):

proc = await asyncio.create_subprocess_exec(
    *full_args, ..., stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
)
...
try:
    stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
except TimeoutError:
    proc.kill()          # kills `git` only, not `git remote-http`
    await proc.wait()    # resolves only after every pipe is closed
    raise GitSyncError(f"git command timed out after {timeout}s: ...")

In CPython 3.12, BaseSubprocessTransport wakes wait() futures in _call_connection_lost. That runs from _try_finish only when every pipe is disconnected. The helper still holds the write ends of the stdout/stderr pipes, so wait() does not return until the helper exits. The production image uses python:3.12-slim (containers/Dockerfile#L1).

ensure_repo treats any .git directory as a finished clone (client.py#L323-L344):

if (workdir / ".git").is_dir():
    current_url = await _current_origin_url(workdir, timeout)
    ...
    return
workdir.mkdir(parents=True, exist_ok=True)
await _run_git(["clone", "--origin", "origin", repo_url, "."], ...)

When git clone is SIGKILLed it cannot clean up the directory it was filling. The next pull then runs git fetch --prune origin. With no fetch refspec, this creates no origin/* refs. _remote_branch_exists returns False, and git symbolic-ref --short HEAD fails on the .invalid placeholder (client.py#L368-L383). The cycle calls these two functions on every run (loop.py#L1319-L1320). Orgs are processed sequentially (loop.py#L1559), and the lease TTL is max(300, 5 × timeout) (loop.py#L1163-L1169).

Nothing passes http.lowSpeedLimit / http.lowSpeedTime (see _auth_config_args and _non_interactive_env), so curl never aborts a transfer that has stopped making progress.

Reproduction

The external boundary is a local smart-HTTP git server: the existing tests/private_git_server.py (git http-backend), with auth turned off. It holds the first matching request open for 15 s without sending a byte, then serves normally. Everything else is the real git_sync.client code and real git.

Save this as tests/test_repro_git_stall.py and run:

uv sync
uv run python -m pytest tests/test_repro_git_stall.py -p no:randomly -s -q
"""Git Sync against an HTTP git remote that stalls once, then serves normally."""

import asyncio
import subprocess
import threading
import time
from pathlib import Path

import pytest

from openhands.automation.git_sync.client import GitSyncError, ensure_repo, pull
from tests.private_git_server import PrivateGitServer, _GitHandler, make_bare_repo


STALL_SECONDS = 15


class _StallOnce(_GitHandler):
    """Holds the first request of the chosen kind open without answering."""

    stall_method: str = "GET"
    stalled = threading.Event()

    def _authorized_user(self) -> str | None:
        return "anon"

    def _serve(self) -> None:
        if self.command == self.stall_method and not self.stalled.is_set():
            self.stalled.set()
            time.sleep(STALL_SECONDS)  # a stalled transfer: no bytes sent
            return
        super()._serve()


def _server(root: Path, method: str) -> PrivateGitServer:
    server = PrivateGitServer(root, "")
    server._httpd.RequestHandlerClass = type(
        "_H",
        (_StallOnce,),
        {"git_server": server, "stall_method": method, "stalled": threading.Event()},
    )
    return server


def _git_helpers_for(port: int) -> list[str]:
    ps = subprocess.run(["ps", "-eo", "pid,ppid,args"], capture_output=True, text=True)
    return [line for line in ps.stdout.splitlines() if f"127.0.0.1:{port}/" in line]


@pytest.mark.asyncio
async def test_fetch_timeout_is_a_hard_bound(tmp_path):
    make_bare_repo(tmp_path, "repo", {"automations/a/automation.yaml": "a\n"})
    with _server(tmp_path, "POST") as server:
        workdir = tmp_path / "checkout"
        # A local clone, then point origin at the stalling HTTP remote.
        subprocess.run(
            ["git", "clone", "-q", str(tmp_path / "repo.git"), str(workdir)], check=True
        )
        subprocess.run(
            ["git", "remote", "set-url", "origin", f"{server.url}/repo.git"],
            cwd=workdir,
            check=True,
        )

        start = time.monotonic()
        with pytest.raises(GitSyncError, match="timed out after 2"):
            await pull(workdir, "main", "", timeout=2)
        elapsed = time.monotonic() - start
        print(f"\npull(timeout=2) raised after {elapsed:.1f}s")
        assert elapsed < 6, f"timeout=2 took {elapsed:.1f}s"


@pytest.mark.asyncio
async def test_orphaned_helper_outlives_the_timeout(tmp_path):
    make_bare_repo(tmp_path, "repo", {"automations/a/automation.yaml": "a\n"})
    with _server(tmp_path, "POST") as server:
        port = server._httpd.server_address[1]
        workdir = tmp_path / "checkout"
        subprocess.run(
            ["git", "clone", "-q", str(tmp_path / "repo.git"), str(workdir)], check=True
        )
        subprocess.run(
            ["git", "remote", "set-url", "origin", f"{server.url}/repo.git"],
            cwd=workdir,
            check=True,
        )
        task = asyncio.create_task(pull(workdir, "main", "", timeout=2))
        await asyncio.sleep(5)  # well past the 2 s timeout
        helpers = _git_helpers_for(port)
        print(f"\n3 s after the timeout: pull done={task.done()}, helpers={helpers}")
        with pytest.raises(GitSyncError):
            await task
        assert helpers == []


@pytest.mark.asyncio
async def test_next_cycle_recovers_after_a_clone_timeout(tmp_path):
    sha = make_bare_repo(tmp_path, "repo", {"automations/a/automation.yaml": "a\n"})
    with _server(tmp_path, "GET") as server:
        url = f"{server.url}/repo.git"
        workdir = tmp_path / "checkout"
        with pytest.raises(GitSyncError, match="timed out"):
            await ensure_repo(workdir, url, "main", "", timeout=2)
        print("\nleft behind:", (workdir / ".git/HEAD").read_text().strip())

        # Next cycle, remote healthy: same calls `_run_sync_cycle_leased` makes.
        await ensure_repo(workdir, url, "main", "", timeout=30)
        assert await pull(workdir, "main", "", timeout=30) == sha

Output on main at 19c4ea6 (Python 3.12.16, git 2.47.3):

tests/test_repro_git_stall.py
pull(timeout=2) raised after 15.0s
F
3 s after the timeout: pull done=False, helpers=['   3395       1 /usr/lib/git-core/git remote-http origin http://127.0.0.1:46513/repo.git', '   3396    3395 /usr/lib/git-core/git-remote-http origin http://127.0.0.1:46513/repo.git']
F
left behind: ref: refs/heads/.invalid
F
...
E   AssertionError: timeout=2 took 15.0s
...
E     Left contains 2 more items, first extra item: '   3395       1 /usr/lib/git-core/git remote-http origin http://127.0.0.1:46513/repo.git'
...
openhands/automation/git_sync/client.py:378: in pull
    current_branch = await _run_git(
E   openhands.automation.git_sync.client.GitSyncError: git command failed (128): git symbolic-ref --short HEAD
E   fatal: No such ref: HEAD
FAILED tests/test_repro_git_stall.py::test_fetch_timeout_is_a_hard_bound
FAILED tests/test_repro_git_stall.py::test_orphaned_helper_outlives_the_timeout
FAILED tests/test_repro_git_stall.py::test_next_cycle_recovers_after_a_clone_timeout
3 failed in 45.92s

I also ran the same stall with git -c http.lowSpeedLimit=1000 -c http.lowSpeedTime=2 fetch --prune origin. Git aborted it after about 3 s with curl 28 Operation too slow, which confirms that git's own stall detection works against this fixture.

The fetch case on its own leaves the checkout intact: after the timeout the next pull applies the update, and nothing is imported in the failed cycle because the import runs after pull. Only the clone case gets stuck.

Expected behavior

  • A git command never takes much longer than its timeout. On timeout, the whole process group is killed and reaped.
  • A transfer that has stopped making progress fails quickly. A slow transfer that is still progressing can use the full timeout.
  • A clone that fails or times out leaves no partial .git, so the next cycle (or an in-cycle retry) clones again and applies the repository's state.

Suggested fix

In git_sync/client.py:

  1. Spawn git with start_new_session=True. On timeout, os.killpg(proc.pid, SIGKILL) and then wait. That reaps the helper and closes the inherited pipes, which makes wait() return. Alternatively, bound the post-kill wait and read the return code directly.
  2. Pass -c http.lowSpeedLimit=<bytes> -c http.lowSpeedTime=<secs> for network commands (clone, fetch, push, ls-remote), so a stall fails with a clear error well within the budget. Keep the overall timeout as the hard cap. Optionally retry a stalled network command once if enough budget is left.
  3. In ensure_repo, clone into a temp directory next to the workdir and rename it into place only on success. Also treat a .git with no valid HEAD or no remote.origin.fetch as absent: delete it and clone again.

Acceptance criteria

  • With a remote that stalls without sending bytes, pull(timeout=T) and ensure_repo(timeout=T) raise within about T seconds plus a small grace period.
  • After a timeout, no git / git-remote-http(s) process for that command is left running.
  • After a clone timeout, the next ensure_repo + pull against a healthy remote returns the remote HEAD (the third test above passes).
  • A stalled transfer is detected before the full timeout when progress has stopped, while a slow transfer that keeps sending data still completes within the timeout.
  • Dirty automation state is not cleared by a timed-out cycle (already true today; keep it covered).

OpenHands AI triage

The following comments and acceptance criteria were added by the OpenHands AI agent.

Triage

Verified at 19c4ea6: _run_git_once (openhands/automation/git_sync/client.py:184-206) kills only the direct git child and then awaits proc.wait(), which on the production python:3.12-slim-trixie image resolves only after the grandchild HTTP transport helper closes its inherited pipes; nothing in git_sync sets start_new_session, kills a process group, or passes http.lowSpeedLimit/http.lowSpeedTime; and ensure_repo (client.py:323-334) treats any existing .git directory as a finished clone with no HEAD or remote.origin.fetch validation, so a SIGKILLed clone (HEAD -> refs/heads/.invalid) fails every later pull at symbolic-ref --short HEAD (client.py:379). The loop citations (loop.py:1319-1320, 1559, 1163-1169) match. The reproduction drives the real client against the repo's own smart-HTTP fixture (tests/private_git_server.py) and shows all three failures.

Bounded scope: timeout enforcement, child-process cleanup, stall detection for network git commands, and clone-failure recovery in openhands/automation/git_sync/client.py, with tests following the existing git_sync test fixtures. Repairing an already-broken workdir goes through the same validation-and-re-clone path, so no separate migration is needed.

Non-goals: no change to the lease TTL or to sequential per-org processing in loop.py; no redesign of SSH spawning (tracked by #491 and open PR #493, which bounds the direct-child timeout via subprocess.run but neither reaps the helper nor repairs partial clones); no change to auth-scheme retry or credential redaction; no new user-facing configuration is required (stall-detection values may be internal defaults).

Acceptance Criteria

  • With a remote that holds a request open without sending bytes (the issue's stall fixture), pull(timeout=T) and ensure_repo(timeout=T) raise GitSyncError "timed out" within approximately T seconds plus a bounded grace (reproduction measured 15.0s for T=2 today; the bound must make T=2 finish well under the 15s stall, e.g. under 6s as in the reproduction's assertion).
  • After such a timeout, no git, git-remote-http, or git-remote-https process belonging to that command is left running (reproduction checks ps output filtered by the fixture server's port).
  • After a clone times out against the stalling remote, a subsequent ensure_repo + pull against a healthy remote returns the remote HEAD sha (the reproduction's third test passes).
  • An already-broken workdir (.git present, HEAD -> refs/heads/.invalid, no remote.origin.fetch) is treated as absent and re-cloned on the next cycle instead of failing git symbolic-ref --short HEAD forever.
  • A zero-progress transfer fails before the full timeout budget elapses, while a slow transfer that keeps sending data still completes within the same timeout, both through the real client.
  • A timed-out cycle leaves dirty automation flags intact, and dirty automations are still exported on the next successful cycle (current behavior preserved).
  • Existing git_sync client tests (auth-scheme retry, URL-credential redaction, timeout error text) pass unchanged in behavior except where the timeout path itself changes.

Activity

  1. added
    bug
    on Nov 24, 2026
  2. added
    priority:medium
    ready-for-dev
    on Nov 24, 2026
  3. self-assigned this
    on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugpriority:mediumready-for-dev

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions