Skip to content

fix: run git_sync subprocesses via executor to avoid asyncio hang on clone/fetch - #493

Open
DanCRichards wants to merge 3 commits into
OpenHands:mainfrom
DanCRichards:fix/git-sync-asyncio-subprocess-hang
Open

DanCRichards wants to merge 3 commits into
OpenHands:mainfrom
DanCRichards:fix/git-sync-asyncio-subprocess-hang

Conversation

@DanCRichards

@DanCRichards DanCRichards commented Sep 18, 2026 •

Copy link
Copy Markdown

Summary

  • git_sync/client.py's _run_git() spawned every git subprocess via asyncio.create_subprocess_exec, which reliably stalls at 0 bytes transferred for git clone/git fetch over an SSH remote (small commands like ls-remote are unaffected). See git_sync: asyncio.create_subprocess_exec hangs indefinitely on git clone/fetch over SSH #491 for the full investigation, ruled-out causes, and isolated repro.
  • Swaps _run_git() to a blocking subprocess.run(...) executed via loop.run_in_executor(None, ...), preserving the same timeout/error semantics (subprocess.TimeoutExpired → GitSyncError, non-zero exit → GitSyncError with redacted stderr).

Test plan

  • Verified end-to-end against a real AWS CodeCommit SSH remote: git_sync now completes successfully (last_synced_commit populated, last_error: null), where it failed 100% of the time before with the same repo/credentials/timeout.
  • python3 -m py_compile on the changed file.

HUMAN: I ran the full agent-canvas + automation stack locally and drove the git-sync test myself against our real AWS CodeCommit repo. Before this change I hit the same git command timed out failure on every retry (including with the timeout raised well past what a normal clone should need); after applying the fix and restarting the stack, I triggered a fresh sync and watched it complete successfully end-to-end via the live /git-sync/status API, with a real commit SHA populated and no error. I reviewed the diff in client.py and the reasoning for the executor-based approach before asking for this PR to be opened.

Fixes #491

Update (13 November): merged with main, review feedback addressed

Pushed on top of the original commit (no force-push):

  • Merged main. The conflict with feat(git-sync): back off and quiet down on persistent auth failures #536 is resolved: the subprocess.run path keeps the GitAuthError classification (_looks_like_auth_failure), so the auth-failure backoff still works, and the basic→bearer auth retry in _run_git still wraps it.
  • Tests (review item 1). The three spies in tests/test_git_sync_client.py (non-interactive env, ls-remote-only check, auth-scheme fallback) now patch subprocess.run instead of asyncio.create_subprocess_exec. New TestSubprocessRunner:
    • clone + fetch succeed when asyncio.create_subprocess_exec is replaced with a function that fails (acceptance criterion 2);
    • a git command that hangs times out after its timeout, and the event loop keeps running while it waits in the worker thread.
  • capture_output=True (ruff UP022).

uv run python -m pytest tests/test_git_sync_client.py tests/test_git_sync.py tests/test_git_sync_backoff.py tests/test_git_sync_router.py -n 4: 203 passed. pre-commit passes on the changed files.

Live check on Linux (real SSH remote)

I could not reproduce the stall on Linux. I used a local sshd serving a ~9 MB repo, BatchMode=yes, and Python 3.12/3.13. The issue's standalone script and a Git Sync cycle through the running service both clone in a few seconds on main too. The original report is macOS + CodeCommit, which I can't run here. So this evidence shows the change works and does not regress Linux. It does not prove the macOS root cause. That comes from the author's end-to-end CodeCommit verification above. Scripts: .pr/repro491.sh.

main 949c001 (Linux) this PR 66be6a2 (Linux)
main pr

Trade-off from the review: a git command running in the default executor keeps a worker thread busy until it exits or hits its timeout. On shutdown, asyncio waits for that thread. subprocess.run kills the child on timeout, so that wait is bounded by the git timeout. Git Sync runs one org at a time, so it uses at most one executor thread.

This update was made by an AI agent (OpenHands) on behalf of Graham Neubig.

Jev-Fast-Audit

⚡ Jev fast audit · estimates · 0.31s · commit 720d331
Strongest signal: No primary concern selected.
Evidence: No primary concern to locate.
Coverage: ⚠️ reduced context — partial coverage; 11/11 hunks, 6/6 files (missing patch: 2).

All estimates and evidence
Estimate Likelihood / value Direct evidence
SQL injection 3.0% No direct hunk selected
Command injection 7.0% No direct hunk selected
Weakened authentication 5.0% No direct hunk selected
Weakened authorization 5.0% No direct hunk selected
Contract regression 12.0% No direct hunk selected
Data loss 6.0% No direct hunk selected
Sensitive data disclosure 6.0% No direct hunk selected
Unexpected data transfer 4.0% No direct hunk selected
Credential misuse 7.0% No direct hunk selected
Untrusted instruction authority 3.0% No direct hunk selected
Package source redirection 4.0% No direct hunk selected
Unverified remote execution 18.0% No direct hunk selected
Privileged environment access 9.0% No direct hunk selected
Security assessment bypass 5.0% No direct hunk selected
Prohibited workload 2.0% No direct hunk selected
Primary concern None selected; confidence 89.0% No primary concern to locate

@all-hands-bot

Copy link
Copy Markdown
Contributor

👋 This PR needs a couple of things fixed before OpenHands can review it:

  • the PR description's HUMAN: section needs at least 20 characters describing what you tested, not just the template placeholder

Push an update once this is addressed and this check re-runs automatically.

This is an automated check - no AI was used to generate this comment.

@all-hands-bot

Copy link
Copy Markdown
Contributor

🚦 CI is currently failing on this PR's latest commit.

Please fix the failing checks before OpenHands reviews it - this is re-checked automatically once you push a new commit. (A maintainer can also request @all-hands-bot as a reviewer to have it reviewed regardless of CI status.)

This is an automated check - no AI was used to generate this comment.

@all-hands-bot

all-hands-bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

🚦 CI is currently failing on this PR's latest commit.

Please fix the failing checks before OpenHands reviews it - this is re-checked automatically once you push a new commit. (A maintainer can also request @all-hands-bot as a reviewer to have it reviewed regardless of CI status.)

This is an automated check - no AI was used to generate this comment.

…clone/fetch

asyncio.create_subprocess_exec reliably stalls at 0 bytes transferred for
git clone/fetch over an SSH remote (reproduced in isolation, independent of
this app, with both PIPE and real file-handle stdout/stderr; --quiet made no
difference). Small commands like ls-remote are unaffected via the same
mechanism, so this is specific to the long-lived duplex data stream a git
child process keeps open through its own ssh child.

Swap _run_git() to a classic blocking subprocess.run(...) executed via
loop.run_in_executor(None, ...), preserving the same timeout/error semantics.
Verified end-to-end against a real CodeCommit SSH remote: git_sync now
completes successfully where it failed 100% of the time before.

Fixes OpenHands#491
@DanCRichards
DanCRichards force-pushed the fix/git-sync-asyncio-subprocess-hang branch from 63e4e75 to b8f5301 Compare September 18, 2026 14:10

@enyst enyst left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm an AI agent (Claude, based on Opus 5.5) helping Engel Nyst (@enyst) with project work.

Requesting changes: this head breaks two existing tests and conflicts with main's auth-failure handling.

  1. Two tests fail. tests/test_git_sync_client.py spies on asyncio.create_subprocess_exec in test_run_git_passes_the_non_interactive_env_to_the_subprocess and test_leaves_no_checkout_behind. With _run_git on subprocess.run, both fail (assert None == '0' and assert 0 == 1). Running that file in a detached worktree: 17 passed and 2 failed on this head, 19 passed with the base client.py. Main still has both spies (lines 358 and 428), so they need to spy on subprocess.run instead.
  2. Conflict with #536, merged 2026-09-30. Main's _run_git now raises GitAuthError when _looks_like_auth_failure(details) matches, and the sync loop backs off on that error. The rebase has to keep that classification in the new result.returncode != 0 branch. Taking this side as-is would quietly disable the backoff.

On CI: Validate PR description fails because the linked issue #491 lacks the ready-for-dev label. That's a triage gate, not a code failure. ci, Run tests, and Docker are action_required and haven't run, which is why the test failures above don't show yet.

Main hasn't fixed or otherwise changed the hang: _run_git still uses asyncio.create_subprocess_exec and proc.communicate(), and #536 only added error classification. I couldn't reproduce the SSH stall here (no SSH remote), so the root cause is unverified. #491 reports it on macOS; a Linux reproduction would show whether production deployments are affected. The approach looks low-risk. subprocess.run kills the child on TimeoutExpired, so timeout behavior is preserved. The one new behavior is at shutdown: a git command running in the default executor keeps its thread busy until git exits or times out (60s by default), and asyncio's executor shutdown waits for it.

Comment thread openhands/automation/git_sync/client.py Resolved
Keep main's GitAuthError classification (OpenHands#536) on the subprocess.run path,
use capture_output, and move the test spies from asyncio.create_subprocess_exec
to subprocess.run. Add regression tests that clone/fetch never use asyncio
subprocesses and that a slow git command does not block the event loop.

Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
@github-actions

Copy link
Copy Markdown
Contributor

📁 PR Artifacts Notice

This PR adds or changes temporary PR-specific documents under .pr/. They stay on this branch for review. After this PR merges, the next release PR removes them from main.

@neubig
neubig requested a review from all-hands-bot November 13, 2026 23:58
@neubig

neubig commented Nov 13, 2026

Copy link
Copy Markdown
Member

@enyst Both points from your review are addressed in 66be6a2 (merge of main, no force-push). (1) The three asyncio.create_subprocess_exec spies in tests/test_git_sync_client.py now spy on subprocess.run. A new TestSubprocessRunner checks that clone and fetch never touch asyncio subprocesses and that a hanging git command times out without blocking the event loop. (2) The GitAuthError classification from #536 is kept. The PR description has an update section with test results and a Linux SSH check. I could not reproduce the hang itself on Linux.

This comment was created by an AI agent (OpenHands) on behalf of Graham Neubig.

@neubig
neubig requested review from all-hands-bot and removed request for all-hands-bot November 14, 2026 01:04

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This review was posted by an AI agent (OpenHands).

Scope gate: git_sync/ is explicitly owned by this repository (AGENTS.md: the Automation Service owns git sync; the SDK, Canvas, and extensions repos do not). No maintainer decision needed; proceeding with the technical review.

Review of the change (git_sync/client.py::_run_git_once):

  • The swap from asyncio.create_subprocess_exec to blocking subprocess.run in the default executor preserves every observable semantic I traced against main: same argv/env/cwd and no shell, FileNotFoundError still maps to GitSyncError("git executable not found") (worker-thread exceptions propagate through run_in_executor to the awaiter), subprocess.TimeoutExpired still maps to GitSyncError with the same message, and subprocess.run kills and reaps the child on timeout (POSIX kill() + wait()), matching the old proc.kill(); await proc.wait() path.
  • The GitAuthError classification from #536 is preserved on the new path (_looks_like_auth_failure on redacted stderr inside _run_git_once), the basic→bearer retry in _run_git still wraps it, and git_sync/loop.py's backoff (isinstance(e, GitAuthError) → consecutive_auth_failures, log suppression past threshold) is unchanged and still functions.
  • The executor trade-off is bounded and documented: git sync runs one org at a time, the default timeout is 60 s, and subprocess.run kills the child at timeout, so a mid-flight command delays shutdown by at most ~one git timeout. That is strictly better than the old cancel path, which left the git child orphaned while the task unwound.
  • Tests were updated coherently: the three spies now patch subprocess.run with a signature matching the production call, and the new TestSubprocessRunner covers both acceptance criteria with real behavior — asserting clone/fetch never touch asyncio subprocess machinery, and that the event loop keeps ticking while a hung git command runs out its 1 s timeout.

Test evidence: uv run python -m pytest tests/test_git_sync_client.py tests/test_git_sync_backoff.py → 65 passed; tests/test_git_sync.py → 80 passed (this sandbox has no Docker daemon, so the router-test fixtures cannot start here; the repo's required unit-tests and ci/backend checks are green on this exact head, and the router suites are covered there). No tracked files were modified.

State checks: head still 720d331f4f57a33825eb6dde8415491e36de8c5b; PR title/body match the described change; all 9 checks pass; review feedback from @enyst (auth classification + test spies) is addressed in 66be6a2 as claimed; linked issue #491 is open with bug/ready-for-dev. The .pr/ evidence files follow the documented PR-artifacts convention and are cleaned up by the release flow.

No material issues found.

✅ APPROVED

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: fix A bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

git_sync: asyncio.create_subprocess_exec hangs indefinitely on git clone/fetch over SSH

5 participants