diff --git a/src/format_bench/workflow.py b/src/format_bench/workflow.py index 16077f3..025305a 100644 --- a/src/format_bench/workflow.py +++ b/src/format_bench/workflow.py @@ -2,6 +2,7 @@ import hashlib import shutil +import stat from datetime import datetime, timezone from pathlib import Path from typing import Iterable @@ -58,9 +59,19 @@ def _create_missing_private_parents(destination: Path) -> None: # LLM contract: EXISTING_ANCESTOR -> PRIVATE_ANCESTORS_READY | FAILED. # Create shallow-to-deep without parents=True so every new level requests - # 0700; any mkdir failure stops before the private run leaf is created. + # 0700. A concurrent private creator is safe; every other mkdir failure + # stops before the private run leaf is created. for directory in reversed(missing): - directory.mkdir(mode=0o700) + try: + directory.mkdir(mode=0o700) + except FileExistsError as error: + existing_mode = directory.stat(follow_symlinks=False).st_mode + if not stat.S_ISDIR(existing_mode): + raise + if stat.S_IMODE(existing_mode) & 0o077: + raise PermissionError( + f"concurrently created run ancestor is not private: {directory}" + ) from error def _safe_format_component( diff --git a/tests/test_workflow.py b/tests/test_workflow.py index 017a4c9..2c371c7 100644 --- a/tests/test_workflow.py +++ b/tests/test_workflow.py @@ -259,6 +259,49 @@ def record_mode( assert (run_dir / "manifest.json").is_file() +@pytest.mark.skipif(os.name != "posix", reason="POSIX directory-mode contract") +@pytest.mark.parametrize( + ("raced_mode", "expected_error"), + ((0o700, None), (0o755, PermissionError)), +) +def test_missing_private_parent_validates_concurrent_creator( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + raced_mode: int, + expected_error: type[Exception] | None, +) -> None: + existing_parent = tmp_path / "existing" + existing_parent.mkdir(mode=0o700) + raced_parent = existing_parent / "runs" + destination = raced_parent / "run" + real_mkdir = Path.mkdir + raced = False + + def race_mkdir( + path: Path, + mode: int = 0o777, + parents: bool = False, + exist_ok: bool = False, + ) -> None: + nonlocal raced + if path == raced_parent and not raced: + real_mkdir(path, mode=raced_mode) + path.chmod(raced_mode) + raced = True + real_mkdir(path, mode=mode, parents=parents, exist_ok=exist_ok) + + monkeypatch.setattr(Path, "mkdir", race_mkdir) + + if expected_error is None: + workflow._create_missing_private_parents(destination) + else: + with pytest.raises(expected_error, match="not private"): + workflow._create_missing_private_parents(destination) + + assert raced is True + assert stat.S_IMODE(raced_parent.stat().st_mode) == raced_mode + + @pytest.mark.skipif(os.name != "posix", reason="POSIX directory-mode contract") @pytest.mark.parametrize("mask", (0o002, 0o000)) def test_prepare_run_creates_missing_default_parent_privately(