diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 8916bc2a..dd9bb32b 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -8,6 +8,7 @@ import re import stat import subprocess +import time from collections.abc import Iterator from contextlib import contextmanager, suppress from pathlib import Path @@ -111,7 +112,15 @@ def _local_state_directory(wt: Path, *, create: bool = False, lock: bool = False raise WorktreeError(f"local state directory is not a directory or is a symbolic link: {path}") from exc try: if lock: - fcntl.flock(fd, fcntl.LOCK_EX) + deadline = time.monotonic() + 60 + while (remaining := deadline - time.monotonic()) > 0: + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + time.sleep(min(0.1, remaining)) + else: + raise TimeoutError(f"task state is busy in {wt}; retry when the other command finishes") yield fd finally: os.close(fd) diff --git a/tests/test_cli.py b/tests/test_cli.py index e790e384..f9f62e24 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4699,6 +4699,25 @@ def test_wait_rechecks_closed_unmerged_pr(monkeypatch, final) -> None: assert _closed_unmerged_wait(monkeypatch, reads, steps=1) == final +def test_task_state_lock_times_out_with_a_live_holder(git_repo, monkeypatch): + now = 0.0 + + def advance(seconds): + nonlocal now + now += seconds + + monkeypatch.setattr(cli.worktree, "time", SimpleNamespace(monotonic=lambda: now, sleep=advance)) + with cli.worktree.lock_local_state(git_repo): + with ( + pytest.raises(TimeoutError, match=r"task state is busy.*retry"), + cli.worktree.lock_local_state(git_repo), + ): + pytest.fail("contender acquired a held directory lock") + assert now == 60 + with cli.worktree.lock_local_state(git_repo): + assert now == 60 + + @pytest.mark.parametrize("redirected", [False, True]) def test_checks_report_survives_failed_publication(git_repo, tmp_path, monkeypatch, redirected): path = git_repo / cli.CHECKS_FILE