Repository navigation
Keep local receipts in the task worktree #1589
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -18,13 +18,13 @@ | |
| import random | ||
| import re | ||
| import sys | ||
| import tempfile | ||
| import time | ||
| from collections.abc import Callable, Iterator | ||
| from contextlib import contextmanager | ||
| from contextlib import contextmanager, suppress | ||
| from datetime import UTC, datetime | ||
| from functools import partial, wraps | ||
| from pathlib import Path | ||
| from uuid import uuid4 | ||
|
|
||
| from loopzero import _proc, eligibility, github, mergify, runners, sandbox, worktree | ||
| from loopzero import config as config_mod | ||
|
|
@@ -353,20 +353,19 @@ def _print_receipt(wt: Path, report: CheckReport, action: str) -> None: | |
|
|
||
|
|
||
| @contextmanager | ||
| def _lock_task_state(wt: Path) -> Iterator[None]: | ||
| def _lock_task_state(wt: Path) -> Iterator[int]: | ||
| directory = wt / ".loopzero" | ||
| directory.mkdir(parents=True, exist_ok=True) | ||
| fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY) | ||
| fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) | ||
| try: | ||
| fcntl.flock(fd, fcntl.LOCK_EX) | ||
| yield | ||
| yield fd | ||
| finally: | ||
| os.close(fd) | ||
|
|
||
|
|
||
| def _save_report(wt: Path, report: CheckReport) -> str | None: | ||
| """Publish the receipt or return the current HEAD if the result is stale.""" | ||
| path = wt / CHECKS_FILE | ||
| payload = { | ||
| "head": report.head, | ||
| "dirty": report.dirty, | ||
|
|
@@ -376,27 +375,26 @@ def _save_report(wt: Path, report: CheckReport) -> str | None: | |
| } | ||
| if report.settings_sha256 is not None: | ||
| payload["settings_sha256"] = report.settings_sha256 | ||
| with _lock_task_state(wt): | ||
| with _lock_task_state(wt) as directory: | ||
| current_head = worktree.head(wt) | ||
| if report.head != current_head: | ||
| return current_head | ||
| _write_json_atomically(path, payload) | ||
| _write_json_atomically(directory, CHECKS_FILE.name, payload) | ||
| return None | ||
|
|
||
|
|
||
| def _write_json_atomically(path: Path, payload: dict) -> None: | ||
| with tempfile.NamedTemporaryFile( | ||
| mode="w", encoding="utf-8", dir=path.parent, prefix=f".{path.name}-", delete=False | ||
| ) as stream: | ||
| temp = Path(stream.name) | ||
| try: | ||
| def _write_json_atomically(directory: int, name: str, payload: dict) -> None: | ||
| temp = f".{name}-{uuid4().hex}" | ||
| fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600, dir_fd=directory) | ||
| try: | ||
| with os.fdopen(fd, "w", encoding="utf-8") as stream: | ||
| stream.write(json.dumps(payload, indent=2) + "\n") | ||
| stream.flush() | ||
| os.fsync(stream.fileno()) | ||
| stream.close() | ||
| os.replace(temp, path) | ||
| finally: | ||
| temp.unlink(missing_ok=True) | ||
| os.replace(temp, name, src_dir_fd=directory, dst_dir_fd=directory) | ||
| finally: | ||
| with suppress(FileNotFoundError): | ||
| os.unlink(temp, dir_fd=directory) | ||
|
|
||
|
|
||
| def _load_report(wt: Path) -> CheckReport | None: | ||
|
|
@@ -1108,14 +1106,14 @@ def _review_file(wt: Path, head: str, kind: str) -> Path: | |
|
|
||
| def _save_review(wt: Path, result: ReviewResult, publication: dict | None = None) -> None: | ||
| path = _review_file(wt, result.head, result.kind) | ||
| path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) | ||
| path.parent.chmod(0o700) | ||
| data = dataclasses.asdict(result) | ||
| if publication is not None: | ||
| data["publication"] = publication | ||
| if path.is_symlink(): | ||
| raise OSError(f"refusing to replace symbolic link: {path}") | ||
| _write_json_atomically(path, data) | ||
| with _lock_task_state(wt) as directory: | ||
| os.fchmod(directory, 0o700) | ||
| if path.is_symlink(): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: Symlink pre-check uses the path, not the locked directory fd Both receipts are now published with |
||
| raise OSError(f"refusing to replace symbolic link: {path}") | ||
| _write_json_atomically(directory, path.name, data) | ||
|
|
||
|
|
||
| def _load_review(wt: Path, head: str, kind: str) -> ReviewResult: | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4694,23 +4694,35 @@ def test_wait_rechecks_closed_unmerged_pr(monkeypatch, final) -> None: | |
| assert _closed_unmerged_wait(monkeypatch, reads, steps=1) == final | ||
|
|
||
|
|
||
| def test_checks_report_survives_failed_publication(tmp_path, monkeypatch): | ||
| @pytest.mark.parametrize("redirected", [False, True]) | ||
| def test_checks_report_survives_failed_publication(tmp_path, monkeypatch, redirected): | ||
| path = tmp_path / cli.CHECKS_FILE | ||
| monkeypatch.setattr(cli.worktree, "head", lambda _: next(heads)) | ||
| heads = iter(("a" * 40, "b" * 40)) | ||
| cli._save_report(tmp_path, CheckReport("a" * 40, False, ())) | ||
|
|
||
| def interrupt(staged, dest): | ||
| assert Path(staged).parent == dest.parent | ||
| assert json.loads(Path(staged).read_text())["head"] == "b" * 40 | ||
| assert json.loads(dest.read_text())["head"] == "a" * 40 | ||
| def interrupt(staged, dest, *, src_dir_fd, dst_dir_fd): | ||
| assert src_dir_fd == dst_dir_fd and dest == path.name | ||
| assert json.loads(path.with_name(staged).read_text())["head"] == "b" * 40 | ||
| assert json.loads(path.read_text())["head"] == "a" * 40 | ||
| raise OSError("publication interrupted") | ||
|
|
||
| if redirected: | ||
| external = path.parent.rename(tmp_path / "external") | ||
| path.parent.symlink_to(external, target_is_directory=True) | ||
| monkeypatch.setattr(cli.os, "replace", interrupt) | ||
| with pytest.raises(OSError, match="publication interrupted"): | ||
| with pytest.raises(OSError, match="Not a directory" if redirected else "publication interrupted"): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: Test expects one platform's error for a refused symlink In the redirected case, the test matches "Not a directory". That message comes from Linux, which returns ENOTDIR when |
||
| cli._save_report(tmp_path, CheckReport("b" * 40, False, ())) | ||
| assert json.loads(path.read_text())["head"] == "a" * 40 | ||
| assert list(path.parent.iterdir()) == [path] | ||
| if redirected: | ||
| external.chmod(0o755) | ||
| review = ReviewResult("claude", "a" * 40, "primary", "approve", (), "") | ||
| receipt = cli._review_file(tmp_path, review.head, review.kind) | ||
| receipt.write_text("user file") | ||
| with pytest.raises(OSError, match="Not a directory"): | ||
| cli._save_review(tmp_path, review) | ||
| assert receipt.read_text() == "user file" and external.stat().st_mode & 0o777 == 0o755 | ||
|
|
||
|
|
||
| def test_already_merged_finishes_partial_cleanup(wt, repo, gh, capsys, monkeypatch, head): | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion: New review-state directory is not private until after creation
Before this change,
_save_reviewcreated.loopzerowithmode=0o700. Now_lock_task_statecreates it with the umask default (usually 0o755), and_save_reviewonly fixes it withfchmod(0o700)once the directory is open. Staged files are 0o600, so the exposure is small. Still,_lock_task_statecould passmode=0o700tomkdirso a newly created directory starts out private for every caller.