Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions src/loopzero/_proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ def run(
encoding: str | None = None,
preserve_newlines: bool = False,
tail_chars: int | None = None,
graceful_interrupt: bool = False,
pass_fds: tuple[int, ...] = (),
) -> Completed:
"""Run `argv` (never through a shell) with an environment stripped to the allowlist.
Expand Down Expand Up @@ -198,13 +199,19 @@ def run(
stdout, stderr = (proc.communicate(stdin, timeout=timeout) if tail_chars is None
else (_read_output_tail(proc, tail_chars, timeout), ""))
except BaseException:
if os.name == "posix":
with suppress(ProcessLookupError):
os.killpg(proc.pid, signal.SIGKILL)
else:
proc.kill()
# Popen's context exit can skip reaping after KeyboardInterrupt.
proc.wait()
try:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: No test covers a second interrupt during graceful shutdown

The new try/finally means SIGKILL and the reap still run when a second KeyboardInterrupt (or any other exception) arrives during os.killpg(SIGTERM) / proc.wait(timeout=5). That is the reason for this change, but no test in the diff exercises it. If the try/finally were later flattened again, nothing would catch the orphaned process group. Suggested fix: add a small test that monkeypatches proc.wait so the first call (the one with a timeout) raises KeyboardInterrupt, then asserts the child was killed and reaped. One gap remains: a third interrupt during the final proc.wait() in the finally block can still escape without reaping. That is acceptable, but it would help to say so in the comment.

if graceful_interrupt and os.name == "posix":
with suppress(ProcessLookupError, subprocess.TimeoutExpired):
os.killpg(proc.pid, signal.SIGTERM)
proc.wait(timeout=5)
finally:
if os.name == "posix":
with suppress(ProcessLookupError):
os.killpg(proc.pid, signal.SIGKILL)
else:
proc.kill()
# Popen's context exit can skip reaping after KeyboardInterrupt.
proc.wait()
raise
except FileNotFoundError as exc:
if exc.filename == str(cwd):
Expand Down
49 changes: 37 additions & 12 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from select import select
from uuid import uuid4

from loopzero._proc import build_env, run, run_git_paths
from loopzero._proc import build_env, defer_sigterm, run, run_git_paths

GIT_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GIT_SSH_COMMAND", "SSH_AUTH_SOCK")
_ABSOLUTE_COMMON_DIR = ("rev-parse", "--path-format=absolute", "--git-common-dir")
Expand Down Expand Up @@ -61,13 +61,14 @@ def __init__(self, command: tuple[str, ...], tail: str) -> None:

def _git(
cwd: Path, *args: str, timeout: float = 120,
preserve_whitespace: bool = False, preserve_newlines: bool = False,
preserve_whitespace: bool = False, preserve_newlines: bool = False, graceful_interrupt: bool = False,
) -> str:
argv = ("git", *args)
if preserve_whitespace:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: _git drops graceful_interrupt when preserve_whitespace is set

After the merge, _git only passes graceful_interrupt on the run(...) branch. The run_git_paths(...) branch ignores it, and run_git_paths has no parameter to take it. Today no caller sets both flags. The two graceful_interrupt=True calls are worktree add and switch at lines 273 and 276, and neither sets preserve_whitespace, so nothing breaks yet. The risk is that a future caller sets both flags and loses the SIGTERM-first interrupt handling without any warning. Smallest fix: add graceful_interrupt to run_git_paths and pass it through from _git. If that isn't wanted, raise ValueError in _git when both flags are set.

done = run_git_paths(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout)
else:
done = run(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout, preserve_newlines=preserve_newlines)
done = run(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout,
preserve_newlines=preserve_newlines, graceful_interrupt=graceful_interrupt)
if done.exit_code != 0:
raise GitError(argv, done.stderr or done.stdout)
return done.stdout if preserve_newlines or preserve_whitespace else done.stdout.strip()
Expand Down Expand Up @@ -247,36 +248,60 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path:
) from None
raise
_git(repo_root, "update-ref", "--no-deref", f"refs/remotes/origin/{base_branch}", base)
detached = not existing
if existing:
existing_head = _resumable_head(repo_root, wt, branch)
if existing_head is None:
checkout = _resumable_checkout(repo_root, wt, branch)
if checkout is None:
raise WorktreeError(refusal)
existing_head, detached = checkout
if existing_head != base:
raise WorktreeError(
f"cannot resume start at {wt}: existing HEAD {existing_head} does not match "
f"origin/{base_branch} at {base}; run loopzero start with a new slug"
)
_ensure_excludes(repo_root)
if not existing:
wt.parent.mkdir(parents=True, exist_ok=True)
_git(repo_root, "worktree", "add", "--quiet", "-b", branch, str(wt), base)
_prepare_checkout(repo_root, wt, branch, base, existing=existing, detached=detached)
_initialize_task(task, _TASK_TEMPLATE.format(
title=title_from_slug(slug), base_branch=base_branch, base=base))
return wt


def _resumable_head(repo_root: Path, wt: Path, expected_branch: str) -> str | None:
def _prepare_checkout(repo_root: Path, wt: Path, branch: str, base: str, *, existing: bool, detached: bool) -> None:
if not existing:
wt.parent.mkdir(parents=True, exist_ok=True)
# Let Git clean up the interrupted checkout before creating the final branch.
_git(repo_root, "worktree", "add", "--quiet", "--detach", str(wt), base, graceful_interrupt=True)
if detached:
with defer_sigterm():
_git(wt, "switch", "--quiet", "-c", branch, graceful_interrupt=True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: An interrupt in the middle of git switch -c can still leave a slug that can't be retried

defer_sigterm only holds back SIGTERM to the parent. A Ctrl-C still raises KeyboardInterrupt, and graceful_interrupt then sends SIGTERM to git switch. If git dies after it creates refs/heads/<branch> but before it updates HEAD, the worktree stays detached while the branch exists. _resumable_checkout then returns None because of _branch_exists, and the user has to clean up by hand. The window is small. To close it, also defer SIGINT around the switch, or on resume accept a detached worktree whose branch already points at the detached HEAD.



def _resumable_checkout(repo_root: Path, wt: Path, expected_branch: str) -> tuple[str, bool] | None:
registered = _git(repo_root, "worktree", "list", "--porcelain", "-z", preserve_whitespace=True).split("\0\0")
path_field = f"worktree {wt.resolve()}\0"
fields = next((item for item in registered if item.startswith(path_field)), "").split("\0")
if (len(fields) != 3 or fields[2] != f"branch refs/heads/{expected_branch}"
if (len(fields) != 3 or fields[2] not in ("detached", f"branch refs/heads/{expected_branch}")
or not (wt / ".git").is_file()):
return None
common = _git(repo_root, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True)
if _git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True) != common or branch(wt) != expected_branch:
if _git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True) != common:
return None
detached = fields[2] == "detached"
if detached:
admin = Path(_git(wt, "rev-parse", "--absolute-git-dir", preserve_whitespace=True))
try:
backlink = os.fsdecode((admin / "gitdir").read_bytes().removesuffix(b"\n"))
except OSError:
return None
if ((wt / ".git").is_symlink() or (admin / backlink).resolve() != (wt / ".git").resolve()
or _branch_exists(repo_root, expected_branch)):
return None
elif branch(wt) != expected_branch:
return None
current_head = head(wt)
return current_head if fields[1] == f"HEAD {current_head}" and not is_dirty(wt) else None
if fields[1] != f"HEAD {current_head}" or is_dirty(wt):
return None
return current_head, detached


def _initialize_task(task: Path, text: str) -> None:
Expand Down
33 changes: 29 additions & 4 deletions tests/test_worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

from __future__ import annotations

import shlex
import subprocess
import sys
from pathlib import Path

import pytest
Expand Down Expand Up @@ -90,7 +92,7 @@ def interleave(path, *args, **kwargs):
assert base_section.strip().splitlines() == [f"main @ {upstream}", f"Base: {upstream}"]


@pytest.mark.parametrize("state", ["same-base", "dirty", "moved-base"])
@pytest.mark.parametrize("state", ["same-base", "dirty", "moved-base", "detached"])
def test_start_retries_after_git_creates_worktree(repo, monkeypatch, state):
repo = repo.rename(repo.with_name("repo\rreturn"))
base = commit_on_origin(repo, "base-change")
Expand All @@ -99,7 +101,8 @@ def test_start_retries_after_git_creates_worktree(repo, monkeypatch, state):

def interrupt_after_add(cwd, *args, **kwargs):
output = run_git(cwd, *args, **kwargs)
if args[:2] == ("worktree", "add"):
interrupted_step = ("worktree", "add") if state == "detached" else ("switch", "--quiet")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: The detached case only covers an interrupt after worktree add returns

The test raises KeyboardInterrupt after run_git has finished worktree add, so the checkout is already complete and clean. That tests the resumable detached path, which the _resumable_checkout change targets. It does not cover an interrupt during the checkout itself, which is the scenario named in the acceptance criteria. In that case files are missing, is_dirty returns true, and the retry is refused unless Git's graceful cleanup has already removed the worktree. Suggested fix: rename or comment the parametrize case to say it covers the gap between worktree add and switch. Point to whichever test covers the in-checkout barrier, if one exists.

if args[:2] == interrupted_step:
raise KeyboardInterrupt
return output

Expand All @@ -108,9 +111,10 @@ def interrupt_after_add(cwd, *args, **kwargs):
with pytest.raises(KeyboardInterrupt):
worktree.start(repo, "my-task", "main")
task = worktree.task_file(wt)
assert (worktree.branch(wt), worktree.head(wt)) == ("lz/my-task", base)
current_branch = git(wt, "branch", "--show-current").strip()
assert (current_branch, worktree.head(wt)) == ("" if state == "detached" else "lz/my-task", base)
assert not task.exists()
if state == "same-base":
if state in {"same-base", "detached"}:
assert worktree.start(repo, "my-task", "main") == wt
assert worktree.base_sha(wt) == base
text = task.read_text()
Expand Down Expand Up @@ -303,3 +307,24 @@ def test_abandoned_worktree_guide(repo: Path, tmp_path: Path, state: str) -> Non
assert git(repo, "ls-remote", "origin", "refs/heads/lz/abandoned").split() == [
head, "refs/heads/lz/abandoned"
]


def test_start_retries_after_git_checkout_interrupt(repo, tmp_path):
(repo / ".gitattributes").write_text("README.md filter=paused\n")
(repo / "workflow.toml").write_text('[repo]\nname="owner/repo"\n')
git(repo, "add", ".gitattributes", "workflow.toml")
git(repo, "commit", "-qm", "add checkout barrier")
git(repo, "push", "-q", "origin", "main")
pid_file, entered = tmp_path / "starter.pid", tmp_path / "checkout-entered"
git(repo, "config", "filter.paused.smudge",
f'cat >/dev/null; : > {shlex.quote(str(entered))}; '
f'kill -INT "$(cat {shlex.quote(str(pid_file))})"; exec sleep 30')
start = ("import os, sys; from pathlib import Path; from loopzero.cli import main; "
"Path(sys.argv[1]).write_text(str(os.getpid())); sys.exit(main(['start', 'paused']))")
command = [sys.executable, "-c", start, str(pid_file)]
first = subprocess.run(command, cwd=repo, capture_output=True, timeout=8, check=False)
assert entered.exists() and first.returncode in (-2, 130)
git(repo, "config", "--unset", "filter.paused.smudge")
resumed = subprocess.run(command, cwd=repo, capture_output=True, timeout=8, check=False)
assert resumed.returncode == 0, resumed.stderr
assert worktree.task_file(worktree.worktree_dir(repo, "paused")).is_file()
Loading