Skip to content
Merged
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
4 changes: 3 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,9 @@ Git configuration so URL rewrites cannot change its destination.
After confirmed remote deletion or absence, cleanup deletes the matching
`origin/lz/<slug>` tracking ref only if it still points to the merged head.
An already-merged PR can resume cleanup from its task worktree. Local removal
requires a clean worktree at the merged PR head with no ignored user files.
requires a clean worktree with no ignored user files. A Git ref lock keeps the
worktree at the merged PR head during removal. Cleanup then deletes the branch
only if it still points at that head.
Hosted eligibility trusts the configured publisher's projection and live identity,
state, head and latest ordering. It cannot recompute private raw or defeat a
coherent forgery by a trusted publisher/editor; native claims do not attest the
Expand Down
4 changes: 1 addition & 3 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1185,10 +1185,8 @@ def _cleanup(wt: Path, pr: github.PR) -> None:
name = None
try:
_repo_root(wt)
if worktree.head(wt) != pr.head_sha:
raise worktree.WorktreeError("local HEAD differs from merged PR head")
name = worktree.branch(wt)
worktree.cleanup(wt)
worktree.cleanup(wt, pr.head_sha)
except (worktree.WorktreeError, OSError) as exc:
retry = CLEANUP_RETRY if wt.exists() else ""
if not retry and name is not None:
Expand Down
64 changes: 53 additions & 11 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@
import errno
import re
import stat
import subprocess
import tempfile
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from select import select
from uuid import uuid4

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

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 @@ -259,13 +263,31 @@ def merges_since(wt: Path, sha: str) -> list[str]:
return _git(Path(wt), "rev-list", "--first-parent", "--reverse", "--merges", f"{sha}..HEAD").split()


def cleanup(wt: Path) -> None:
"""Remove the worktree and branch if there are no local user files."""
wt = Path(wt).absolute()
if not wt.exists():
raise WorktreeError(f"no such worktree: {wt}")
if is_dirty(wt):
raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}")
@contextmanager
def _lock_verified_ref(wt: Path, ref: str, expected_head: str) -> Iterator[None]:
argv = ("git", "update-ref", "--stdin")
with subprocess.Popen(
argv, cwd=wt, env=build_env(GIT_ENV), stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", errors="surrogateescape",

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: Merging stderr into the transaction's stdout turns any Git warning into a refusal

Stderr is merged into stdout, and the code only accepts the first line if it is exactly prepare: ok\n. If Git prints anything first, such as a config or deprecation warning, response will not match and cleanup is refused. That fails safe, but cleanup can never succeed in that environment, and the error shows only the warning line. Also, if Git exits without output, readline() returns "" and the error message has no detail. Smallest fix: send stderr to a separate pipe and read stdout until prepare: ok. On failure, include the stderr output in GitError.

) as transaction:
assert transaction.stdin is not None and transaction.stdout is not None
try:
transaction.stdin.write(f"option no-deref\nverify {ref} {expected_head}\nprepare\n")
transaction.stdin.flush()
if not select([transaction.stdout], [], [], 30)[0]:
raise GitError(argv, "timed out verifying the merged branch")
response = transaction.stdout.readline()
if response != "prepare: ok\n":
raise GitError(argv, response)
yield
finally:
try:
transaction.communicate("abort\n", timeout=5)
except subprocess.TimeoutExpired:
transaction.terminate()


def _require_no_ignored_user_files(wt: Path) -> None:
ignored = _git(
wt, "ls-files", "--others", "--ignored", "--exclude-standard", "-z", preserve_newlines=True
)
Expand All @@ -277,10 +299,30 @@ def cleanup(wt: Path) -> None:
):
continue
raise WorktreeError(f"worktree contains ignored file {path!r}, refusing to remove: {wt}")
name, gd = branch(wt), (wt / _git(wt, "rev-parse", "--git-common-dir")).resolve()
_git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt)) # never the primary checkout


def cleanup(wt: Path, expected_head: str) -> None:
"""Remove a clean merged worktree and its branch if it has no local user files."""
wt = Path(wt).absolute()
if not wt.exists():
raise WorktreeError(f"no such worktree: {wt}")
if head(wt) != expected_head:
raise WorktreeError("local HEAD differs from merged PR head")
name = branch(wt)
gd = Path(_git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True))
ref = f"refs/heads/{name}"
with _lock_verified_ref(wt, ref, expected_head):
if branch(wt) != name:

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 ref lock does not stop HEAD being detached or switched before removal

The verify lock only prevents updates to refs/heads/<name>. It does not prevent changes to the worktree's HEAD symref. The branch(wt) != name check runs once, before is_dirty, the ignored-file scan and worktree remove. If someone runs git checkout --detach and commits on the detached HEAD in that window, git worktree remove still succeeds and that commit becomes unreachable. The window is narrow and outside this task's acceptance criterion, which covers commits on the branch. A cheap way to narrow it further: re-read head(wt) and branch(wt) right before worktree remove.

raise WorktreeError("local branch changed during merge cleanup")
if is_dirty(wt):
raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}")
_require_no_ignored_user_files(wt)
_git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt)) # never the primary checkout
worktrees = _git(gd, f"--git-dir={gd}", "worktree", "list", "--porcelain", "-z")

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 check that the branch is checked out elsewhere can race with branch deletion

Before this change, branch -D refused atomically when the branch was checked out in another worktree. update-ref -d does not refuse in that case, so the code now runs a separate worktree list check first. Someone could run git worktree add <path> lz/<slug> between that check and update-ref -d. The new worktree's HEAD would then point to a deleted ref. The old SHA guard keeps the commits safe, but that worktree ends up on an unborn branch. The risk is low. A comment noting this trade-off would be enough.

if f"branch {ref}" in worktrees.split("\0"):
raise WorktreeError(f"local branch {name!r} is checked out in another worktree")
try:
_git(gd, f"--git-dir={gd}", "branch", "-D", name)
_git(gd, f"--git-dir={gd}", "update-ref", "--no-deref", "-d", ref, expected_head)
except GitError:
if _git(gd, f"--git-dir={gd}", "branch", "--list", "--", name):
raise
40 changes: 20 additions & 20 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3495,7 +3495,7 @@ def test_merge_warns_when_cleanup_fails(wt, gh, capsys, monkeypatch, head, remov
arm_squash_merge(gh, head, wt, merge_json(state="MERGED", head=head, sha="d" * 40))
gh.respond("api -X", "")

def fail_cleanup(path):
def fail_cleanup(path, _expected_head):
if removed:
shutil.rmtree(path)
raise cli.worktree.WorktreeError(error)
Expand All @@ -3514,17 +3514,15 @@ def test_cleanup_hints_name_branch_and_configured_repo_without_commands(
branch = "lz/fix$version"
monkeypatch.setattr(cli, "_repo_root", lambda _wt: tmp_path)
monkeypatch.setattr(cli.worktree, "branch", lambda _wt: branch)
gone = tmp_path / "gone"
monkeypatch.setattr(cli.worktree, "cleanup", lambda *_: (_ for _ in ()).throw(
cli.worktree.WorktreeError("cannot lock ref")))
monkeypatch.setattr(cli.worktree, "head", lambda _wt: "a" * 40)
cli._cleanup(gone, SimpleNamespace(head_sha="a" * 40))
cli._cleanup(tmp_path / "gone", SimpleNamespace(head_sha="a" * 40))
assert capsys.readouterr().err.rstrip().endswith(
"delete local branch 'lz/fix$version' if it still points at the merged head")

monkeypatch.setattr(cli.github, "delete_remote_branch", lambda *_: (_ for _ in ()).throw(
cli.github.GhError(("gh", "api"), "HTTP 500")))
cli._cleanup_remote_refs(gone, SimpleNamespace(repo="acme/widgets"), branch, "a" * 40)
cli._cleanup_remote_refs(tmp_path / "gone", SimpleNamespace(repo="acme/widgets"), branch, "a" * 40)
assert capsys.readouterr().err.rstrip().endswith(
"delete 'lz/fix$version' in acme/widgets if it still points at the merged head")

Expand Down Expand Up @@ -4688,17 +4686,19 @@ def test_dirty_check_does_not_claim_committed_receipt(wt, capsys):
assert "receipt produced:" not in out


@pytest.mark.parametrize("case", ["dirty", "unpushed"])
def test_cleanup_preserves_local_work(wt, case, capsys):
@pytest.mark.parametrize("case", ["dirty", "unpushed", "after-head-read"])
def test_cleanup_preserves_local_work(wt, case, capsys, monkeypatch):
pr = SimpleNamespace(head_sha=cli.worktree.head(wt))
if case == "dirty":
(wt / "untracked").write_text("keep me")
else:
git(wt, "commit", "--allow-empty", "-m", "local after merge")
if case == "after-head-read":
monkeypatch.setattr(cli.worktree, "head", lambda _wt: pr.head_sha)
cli._cleanup(wt, pr)
assert wt.exists()
err = capsys.readouterr().err
assert ("worktree is dirty" if case == "dirty" else "local HEAD differs") in err
diagnostic = {"dirty": "worktree is dirty", "unpushed": "local HEAD differs", "after-head-read": "but expected"}
assert diagnostic[case] in capsys.readouterr().err


def _closed_unmerged_wait(monkeypatch, reads, steps=0):
Expand Down Expand Up @@ -4754,26 +4754,26 @@ def interrupt(staged, dest):
assert list(path.parent.iterdir()) == [path]


def test_already_merged_finishes_partial_cleanup(wt, repo, gh, capsys, monkeypatch, head):
@pytest.mark.parametrize("moved", [False, True])
def test_already_merged_finishes_partial_cleanup(wt, repo, gh, capsys, monkeypatch, head, moved):
cli._review_file(wt, head, "primary").write_text("{broken")
arm_pr(gh, head, isDraft=False, state="MERGED")
gh.append(f"api repos/{REPO}/pulls/7", merge_json(state="MERGED", head=head, sha="c" * 40))
ref = f"api repos/{REPO}/git/ref/heads/lz/t1"
gh.fail(ref, "gh: Not Found (HTTP 404)")

gh.fail(f"api repos/{REPO}/git/ref/heads/lz/t1", "gh: Not Found (HTTP 404)")
original = cli.worktree._git
advanced = git(wt, "commit-tree", f"{head}^{{tree}}", "-p", head, "-m", "newer").strip()

def cleanup_git(cwd, *args, **kwargs):
result = original(cwd, *args, **kwargs)
if args[1:3] == ("worktree", "remove"):
git(repo, "branch", "-D", "lz/t1")
return result
if args[1:3] == ("update-ref", "--no-deref"):
update = ("update-ref", "refs/heads/lz/t1", advanced) if moved else ("branch", "-D", "lz/t1")
git(repo, *update)
return original(cwd, *args, **kwargs)

monkeypatch.setattr(cli.worktree, "_git", cleanup_git)
code, out, err = run(capsys, "merge")
assert code == 0 and "was already merged" in out and err == ""
assert not wt.exists()
assert not git(repo, "branch", "--list", "lz/t1")
assert code == 0 and "was already merged" in out and not wt.exists()
assert ("but expected" in err) if moved else err == ""
assert git(repo, "branch", "--list", "lz/t1", "--format=%(objectname)").strip() == (advanced if moved else "")
assert not any(call["argv"][:2] == ["api", "-X"] for call in gh.calls)


Expand Down
6 changes: 3 additions & 3 deletions tests/test_worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ def test_task_helpers_errors(repo: Path) -> None:
def test_cleanup_removes_worktree_and_branch(repo: Path, monkeypatch) -> None:
wt, calls, real = worktree.start(repo, "done", "main"), [], worktree._git
monkeypatch.setattr(worktree, "_git", lambda d, *a, **k: calls.append((d, a)) or real(d, *a, **k))
worktree.cleanup(wt) # #439: no cleanup git runs in (or -C) the primary checkout
worktree.cleanup(wt, worktree.head(wt)) # #439: no cleanup git runs in (or -C) the primary checkout
assert calls and all(Path(d).resolve() != repo.resolve() and "-C" not in a for d, a in calls)
assert not wt.exists() and not git(repo, "branch", "--list", "lz/done") and "done" not in git(repo, "worktree", "list")

Expand All @@ -273,13 +273,13 @@ def test_cleanup_preserves_user_files(repo: Path, file: str) -> None:
wt = worktree.start(repo, "dirty", "main")
(wt / file).write_text("x")
with pytest.raises(worktree.WorktreeError, match="worktree is dirty" if file == "scratch.txt" else "ignored file"):
worktree.cleanup(wt)
worktree.cleanup(wt, worktree.head(wt))
assert (wt / file).read_text() == "x" and "lz/dirty" in git(repo, "branch", "--list", "lz/dirty")


def test_cleanup_missing_worktree(repo: Path) -> None:
with pytest.raises(worktree.WorktreeError, match="no such worktree"):
worktree.cleanup(repo / ".worktrees" / "ghost")
worktree.cleanup(repo / ".worktrees" / "ghost", worktree.head(repo))


@pytest.mark.parametrize("state", ["clean", "dirty", "divergent", "unpublished", "remote-moved", "stash"])
Expand Down
Loading