Skip to content

Make an interrupted worktree checkout retryable - #1779

Closed
eowca wants to merge 4 commits into
mainfrom
lean178/1417-retry-interrupted-checkout
Closed

eowca wants to merge 4 commits into
mainfrom
lean178/1417-retry-interrupted-checkout

Conversation

@eowca

@eowca eowca commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Make an interrupted worktree checkout retryable

Context and goal

  • Context: Git registers a linked worktree before it checks out the files.
  • Problem: An interrupt during initial checkout can leave a partial worktree and an occupied branch.
  • Goal: Let the operator retry the same slug after interrupting Git during checkout.

Closes #1417

Acceptance

  • Interrupt Git after worktree registration with one checkout barrier. A second start at the same base succeeds without manual cleanup.
  • Preserve refusals for occupied slugs with user changes or an existing handoff.
  • Cleanup is limited to the invocation's own checkout.

Base

Base: d9fc8ab

Validation

Recorded for 01aef9204619

  • uv run --group dev ruff check src tests: exit 0
  • uv run --group dev tach check: exit 0
  • uv run --python 3.14 python scripts/check_architecture_docs.py: exit 0
  • scripts/size_budget.sh: exit 0
  • uv run --group dev pytest -q: exit 0

Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

Review

  • primary, claude, 421a1eb, request_changes
  • delta, claude, 53d35d2, approve
  • delta, claude, 01aef92, approve

Superseded by #1934, which carries the reviewed checkout recovery onto main’s Unicode path handling.

Architecture-Review: unchanged; start still owns a single branch and linked worktree at the resolved base.
Co-Authored-By: Codex <noreply@openai.com>

@loopzero-feder-positronics loopzero-feder-positronics Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

loopzero primary review by claude on 421a1eb4d2ac8d3a7bff9aa8359119b0649265b4, 44.8s: request_changes (0 critical, 1 important, 4 suggestion)

Settings per native call (launch configuration and CLI claims, not backend attestation):

  • Call 1: requested model claude-opus-5-5 (effort medium); CLI-reported model claude-opus-5-5 (effort unknown); configured model claude-opus-5-5 (effort medium)

Native Claude output is retained in the restricted local review receipt.

Comment thread src/loopzero/worktree.py Resolved
Comment thread src/loopzero/_proc.py Outdated
stdout, stderr = _read_output_tail(proc, tail_chars, timeout), ""
except BaseException:
if graceful_interrupt and os.name == "posix":
with suppress(ProcessLookupError, subprocess.TimeoutExpired):

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: A second interrupt during the graceful wait skips the SIGKILL and the reap

With graceful_interrupt, the handler calls proc.wait(timeout=5) inside a suppress(ProcessLookupError, TimeoutExpired). If a second Ctrl-C or the unwind exception from SIGTERM arrives during that wait, the new exception leaves the except BaseException handler. The killpg(SIGKILL) and the final proc.wait() never run, so the child process group can stay alive and unreaped. That breaks the guarantee the comment below describes ("Popen's context exit can skip reaping"). Fix: wrap the graceful step in try: ... finally: so the SIGKILL and the reap always happen.

Comment thread src/loopzero/worktree.py
_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.

Comment thread tests/test_worktree.py Outdated
def interrupt_after_add(cwd, *args, **kwargs):
output = run_git(cwd, *args, **kwargs)
if args[:2] == ("worktree", "add"):
if args[:2] == ("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: No test covers the new detached-resume path

The existing retry test now raises after switch, so the worktree is already on the branch when it resumes. The new subprocess test interrupts during checkout, which Git cleans up completely, so the second start creates a fresh worktree. Neither test reaches the new detached branch of _resumable_checkout: the gitdir backlink check, refusal when the branch exists, and resume through git switch -c. Before this change the test interrupted right after worktree add, and that is exactly the state this path handles. Fix: keep a parametrized case that raises after ("worktree", "add"), and add a refusal case where the branch already exists.

Comment thread src/loopzero/worktree.py Outdated
return None
if ((wt / ".git").is_symlink() or (admin / backlink).resolve() != (wt / ".git").resolve()
or _branch_exists(repo_root, expected_branch)
or _git(wt, "branch", "--show-current")):

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: Redundant branch --show-current check

In the detached branch, fields[2] == "detached" from the porcelain listing already shows that HEAD is detached. The extra _git(wt, "branch", "--show-current") is one more subprocess and one more condition in an already dense test. Consider removing it.

Architecture-Review: unchanged; task handoffs continue to use UTF-8 and checkout signals still unwind before ownership is published.
Co-Authored-By: Codex <noreply@openai.com>

@loopzero-feder-positronics loopzero-feder-positronics Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

loopzero delta review by claude on 53d35d2298510389dcb545831836a9a814a324db, 21.9s: approve (0 critical, 0 important, 2 suggestion)

Settings per native call (launch configuration and CLI claims, not backend attestation):

  • Call 1: requested model claude-opus-5-5 (effort medium); CLI-reported model claude-opus-5-5 (effort unknown); configured model claude-opus-5-5 (effort medium)

Native Claude output is retained in the restricted local review receipt.

Comment thread src/loopzero/_proc.py
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.

Comment thread tests/test_worktree.py
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.

@eowca

eowca commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

waits for test headroom after #1663

eowca and others added 2 commits November 26, 2026 14:20
Architecture-Review: unchanged; recovery still verifies the registered checkout and keeps Git path handling intact.
Co-Authored-By: Codex <noreply@openai.com>
Co-Authored-By: Codex <noreply@openai.com>

@loopzero-feder-positronics loopzero-feder-positronics Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

loopzero delta review by claude on 01aef9204619d7ec9e1d1f6555d8d20787fd1afe, 16.8s: approve (0 critical, 0 important, 1 suggestion)

Settings per native call (launch configuration and CLI claims, not backend attestation):

  • Call 1: requested model claude-opus-5-5 (effort medium); CLI-reported model claude-opus-5-5 (effort unknown); configured model claude-opus-5-5 (effort medium)

Native Claude output is retained in the restricted local review receipt.

Comment thread src/loopzero/worktree.py
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.

@eowca
eowca marked this pull request as ready for review November 26, 2026 13:57
@eowca eowca closed this Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Let start retry the same slug after an interrupted Git checkout

1 participant