From 040a53956f444a658e280d56004c514998f63af9 Mon Sep 17 00:00:00 2001 From: Toby Jackson Date: Tue, 17 Nov 2026 18:41:30 +0000 Subject: [PATCH 1/5] Build and test native Windows and macOS wheels --- .github/workflows/publish.yml | 164 +++++++++++++++++++++++++++++++++- 1 file changed, 162 insertions(+), 2 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 2b7c9f1..92817d4 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -11,6 +11,10 @@ on: description: Publish the current version after verification (requires an existing release tag) type: boolean default: false + desktop_only: + description: Check only Windows and macOS builds without publishing + type: boolean + default: false permissions: contents: read @@ -31,6 +35,7 @@ env: jobs: build: name: Build and verify Linux x86_64 distributions + if: github.event_name != 'workflow_dispatch' || !inputs.desktop_only runs-on: ubuntu-22.04 timeout-minutes: 30 defaults: @@ -163,6 +168,7 @@ jobs: build-arm64: name: Build and verify Linux ARM64 VAD and experimental MiniLM wheel + if: github.event_name != 'workflow_dispatch' || !inputs.desktop_only runs-on: ubuntu-24.04-arm container: image: quay.io/pypa/manylinux_2_28_aarch64 @@ -268,6 +274,158 @@ jobs: compression-level: 0 retention-days: 14 + build-desktop: + name: Build and verify ${{ matrix.name }} wheel + runs-on: ${{ matrix.runner }} + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - name: Windows x64 + runner: windows-2022 + platform: win_amd64 + artifact: windows-x86_64 + - name: macOS Intel + runner: macos-15-intel + platform: macosx_11_0_x86_64 + artifact: macos-x86_64 + - name: macOS Apple Silicon + runner: macos-15 + platform: macosx_11_0_arm64 + artifact: macos-arm64 + env: + PYTHONUTF8: "1" + TRANSFORMERS_OFFLINE: "1" + MACOSX_DEPLOYMENT_TARGET: "11.0" + AKIKI_EXPECTED_PLATFORM: ${{ matrix.platform }} + AKIKI_VAD_TEST_NATIVE: "1" + AKIKI_MINILM_TEST_NATIVE: "1" + defaults: + run: + shell: bash + steps: + # Preserve exact model and metadata bytes on Windows as well as macOS. + - name: Preserve LF source files + run: git config --global core.autocrlf false + + - name: Check out Python package + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Check out pinned Akiki engine + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: Akiki-AI/akiki-inference + ref: ${{ env.AKIKI_INFERENCE_REV }} + path: .cache/akiki-inference + ssh-key: ${{ secrets.AKIKI_INFERENCE_SSH_KEY }} + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + + - name: Set up Rust + uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + with: + toolchain: "1.98.1" + + - name: Install build tools and cache Cargo dependencies + run: | + python -m pip install build "setuptools>=77.0.3" wheel twine + cargo fetch --locked --manifest-path .cache/akiki-inference/Cargo.toml + + - name: Build native engines offline + run: python tools/build_native.py --inference-dir .cache/akiki-inference + + - name: Select both native libraries + run: | + python - <<'PY' + import os + import sys + from pathlib import Path + + directory = Path(".cache/native-target/release").resolve() + names = ( + ["akiki_vad_engine.dll", "akiki_minilm_engine.dll"] + if sys.platform == "win32" + else ["libakiki_vad_engine.dylib", "libakiki_minilm_engine.dylib"] + ) + libraries = [directory / name for name in names] + assert all(path.is_file() for path in libraries) + with Path(os.environ["GITHUB_ENV"]).open("a", encoding="utf-8") as stream: + stream.write("AKIKI_NATIVE_LIBRARY=" + os.pathsep.join(map(str, libraries)) + "\n") + PY + + - name: Build and verify the native wheel + run: | + python -m build --no-isolation + python verify_dist.py --all-wheels --require-native + python -m twine check --strict dist/* + + - name: Test the installed wheel and both native engines + run: | + python - <<'PY' + import os + import subprocess + import sys + import venv + from pathlib import Path + + root = Path.cwd() + wheels = list((root / "dist").glob("*.whl")) + assert len(wheels) == 1 + wheel = wheels[0] + assert wheel.name.endswith("-" + os.environ["AKIKI_EXPECTED_PLATFORM"] + ".whl"), wheel.name + directory = Path(os.environ["RUNNER_TEMP"]) / "akiki-installed" + venv.EnvBuilder(with_pip=True).create(directory) + executable = directory / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python") + subprocess.run( + [str(executable), "-m", "pip", "install", str(wheel), "pytest", "setuptools>=77.0.3", "wheel"], + check=True, + ) + code = """ + import importlib.util + import sys + from pathlib import Path + import akiki + import numpy as np + from akiki.decision import _load_library + + assert importlib.util.find_spec('onnxruntime') is None + assert importlib.util.find_spec('torch') is None + native = Path(akiki.__file__).parent / 'native' + with akiki.VAD() as vad: + assert vad.engine is akiki.Engine.AKIKI + assert vad.model_precision is akiki.ModelPrecision.INT8 + assert vad.fft_precision is akiki.FFTPrecision.FP32 + assert Path(vad._backend.lib._name).parent == native + assert len(vad.push(np.zeros(256 * 3 + 17, np.float32))) == 3 + assert _load_library()[1].parent == native + print('Installed wheel loads bundled VAD and decision engines with base dependencies only') + """ + import textwrap + + subprocess.run([str(executable), "-I", "-c", textwrap.dedent(code)], cwd=directory, check=True) + subprocess.run( + [str(executable), "-m", "pytest", "-q", "-rs", "-o", "pythonpath="], + cwd=root, + check=True, + ) + PY + + - name: Save the verified native wheel + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: python-distributions-${{ matrix.artifact }} + path: dist/*.whl + if-no-files-found: error + compression-level: 0 + retention-days: 14 + training: name: Verify the private training companion needs: build @@ -350,8 +508,10 @@ jobs: publish: name: Publish to PyPI - if: github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && inputs.publish) - needs: [build, build-arm64, training] + if: >- + github.event_name == 'release' || + (github.event_name == 'workflow_dispatch' && inputs.publish && !inputs.desktop_only) + needs: [build, build-arm64, build-desktop, training] runs-on: ubuntu-latest permissions: contents: read From 5800f76b85ff2ad12f677d831085cce951ed2cc6 Mon Sep 17 00:00:00 2001 From: Toby Jackson Date: Tue, 17 Nov 2026 18:46:25 +0000 Subject: [PATCH 2/5] Validate desktop wheel architectures and normalize metadata newlines --- .github/workflows/publish.yml | 4 +- tests/test_packaging.py | 75 ++++++++++++++++++++++++++++++++++- verify_dist.py | 39 +++++++++++++++++- 3 files changed, 113 insertions(+), 5 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 92817d4..ce235c3 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -547,8 +547,8 @@ jobs: raise SystemExit("Manual publication must use tagged package source; only CI/release docs may differ") PY - - name: Verify both native architectures before publishing - run: python3 verify_dist.py --all-wheels --require-native --require-arm64 + - name: Verify all native platforms before publishing + run: python3 verify_dist.py --all-wheels --require-native --require-arm64 --require-desktop # No environment is set: the PyPI publisher was registered without one. - name: Publish with PyPI Trusted Publishing diff --git a/tests/test_packaging.py b/tests/test_packaging.py index b44bf56..aad164e 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -166,9 +166,9 @@ def packaged_project(tmp_path_factory): return project -def verify_distributions(project, directory): +def verify_distributions(project, directory, *arguments): return subprocess.run( - [sys.executable, str(project / "verify_dist.py"), "--dist-dir", str(directory)], + [sys.executable, str(project / "verify_dist.py"), "--dist-dir", str(directory), *arguments], cwd=project, capture_output=True, text=True, @@ -193,6 +193,77 @@ def test_distributions_exclude_local_work_and_pass_release_verification(packaged assert result.returncode == 0, result.stdout + result.stderr +def test_release_requires_all_desktop_wheels_when_requested(packaged_project): + result = verify_distributions(packaged_project, packaged_project / "dist", "--require-desktop") + assert result.returncode != 0 + assert "Windows x64 and both macOS architecture wheels are required" in result.stderr + + +def test_release_metadata_accepts_windows_line_endings(packaged_project, tmp_path): + for path in (packaged_project / "dist").iterdir(): + shutil.copy2(path, tmp_path / path.name) + wheel = next(tmp_path.glob("*.whl")) + with zipfile.ZipFile(wheel) as archive: + contents = {name: archive.read(name) for name in archive.namelist()} + metadata = next(name for name in contents if name.endswith(".dist-info/METADATA")) + contents[metadata] = contents[metadata].replace(b"\r\n", b"\n").replace(b"\n", b"\r\n") + with zipfile.ZipFile(wheel, "w") as archive: + for name, data in contents.items(): + archive.writestr(name, data) + result = verify_distributions(packaged_project, tmp_path) + assert result.returncode == 0, result.stdout + result.stderr + + +@pytest.mark.parametrize( + "tag,machine,valid", + [ + ("win_amd64", 0x8664, True), + ("win_amd64", 0xAA64, False), + ("macosx_11_0_x86_64", 0x01000007, True), + ("macosx_11_0_x86_64", 0x0100000C, False), + ("macosx_11_0_arm64", 0x0100000C, True), + ("macosx_11_0_arm64", 0x01000007, False), + ], +) +def test_desktop_wheel_verification_checks_binary_architecture( + packaged_project, tmp_path, tag, machine, valid +): + original = next((packaged_project / "dist").glob("*.whl")) + with zipfile.ZipFile(original) as archive: + contents = {name: archive.read(name) for name in archive.namelist()} + metadata = next(name for name in contents if name.endswith(".dist-info/WHEEL")) + contents[metadata] = contents[metadata].replace( + b"Root-Is-Purelib: true", b"Root-Is-Purelib: false" + ) + contents[metadata] = contents[metadata].replace(b"py3-none-any", f"py3-none-{tag}".encode()) + if tag.startswith("win"): + header = bytearray(70) + header[:2] = b"MZ" + struct.pack_into(" 0, "The experimental ARM64 native wheel is missing") +require( + not args.require_desktop + or ( + "win_amd64" in native_platforms + and any(re.fullmatch(r"macosx_\d+_\d+_x86_64", tag) for tag in native_platforms) + and any(re.fullmatch(r"macosx_\d+_\d+_arm64", tag) for tag in native_platforms) + ), + "Windows x64 and both macOS architecture wheels are required", +) with tarfile.open(source) as archive: check_no_local_artifacts(archive.getnames()) From c9976022fc40092a226b76b3c57e55b1c39f3905 Mon Sep 17 00:00:00 2001 From: Toby Jackson Date: Tue, 17 Nov 2026 18:52:32 +0000 Subject: [PATCH 3/5] Document desktop builds and require all release platforms --- docs/releasing.md | 36 ++++++++++++++++++++++++++++++++---- publish.sh | 2 +- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/docs/releasing.md b/docs/releasing.md index 5400a1b..45961fb 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -190,14 +190,41 @@ and that `akiki.decision._load_library()` loads the installed MiniLM library. When no precision is specified, ONNX and PyTorch compatibility engines use FP32; an explicit non-FP32 request must require the Akiki engine. +## Build Windows and macOS wheels + +The release workflow builds Windows x64, macOS Intel, and macOS Apple Silicon wheels. +It uses Windows and macOS GitHub-hosted runners. +No local Windows or Mac computer is required. +Each wheel contains the VAD and decision-model libraries. +The jobs use the pinned engine revision and baseline CPU settings. + +Windows wheels use the `win_amd64` tag. +Mac wheels use separate `macosx_11_0_x86_64` and `macosx_11_0_arm64` tags. +The macOS deployment target is 11.0. CI tests run on macOS 15. +Windows ARM64 is not part of this build matrix. + +Each job installs its wheel into a new virtual environment. +It checks that VAD and decision inference load the bundled native libraries. +It runs the Python tests against the installed package with both native engines required. +Tests generate small synthetic checkpoints. No model is downloaded. +The release verifier checks PE and Mach-O architecture headers against wheel tags. +It preserves exact bundled model checksums. + +For a targeted check, run `publish.yml` manually with `desktop_only` enabled. +Leave `publish` disabled. Desktop-only runs cannot publish a package. +The verified wheels are saved as `python-distributions-windows-x86_64`, +`python-distributions-macos-x86_64`, and `python-distributions-macos-arm64` artifacts. +Private engine source is not included in these artifacts. + ## Publish from GitHub Actions The workflow is `.github/workflows/publish.yml`. It builds and verifies the -portable wheel, source archive, and Linux x86_64 and ARM64 native wheels. +portable wheel, source archive, Linux x86_64 and ARM64 native wheels, +Windows x64 wheel, and both macOS architecture wheels. The current decision runtime supports MiniLM/BERT exports. Its ARM64 support is experimental. ARM64 builds in manylinux_2_28 on a native ARM64 runner. -x86_64 retains the glibc 2.34 floor. Both build jobs must pass before publishing. It tests the +x86_64 retains the glibc 2.34 floor. All native build jobs must pass before publishing. It tests the native loader, Python API, and clean installations before saving the artifacts. Models come exclusively from `src/akiki/models/`; no model is downloaded. @@ -228,7 +255,7 @@ After merging, run the workflow manually on `main` with the `publish` input enab The retry requires an existing GitHub release. It checks that package source matches its version tag; only the workflow and this release document may differ. This preserves the tag -while allowing CI-only repairs. Both native build jobs run again before upload. +while allowing CI-only repairs. All native build jobs run again before upload. The existing PyPI `akiki` project must trust owner `Akiki-AI`, repository `akiki-python`, workflow filename `publish.yml`, with the environment left @@ -279,5 +306,6 @@ Do not store credentials in this repository. ``` The script verifies and uploads all wheels for the current version plus its -source archive. It refuses a release with no native wheel or stale description. +source archive. It requires the Linux, Windows, and macOS native wheels. +It rejects stale descriptions. It does not upload artifacts from previous versions. diff --git a/publish.sh b/publish.sh index c88cab3..57949f2 100755 --- a/publish.sh +++ b/publish.sh @@ -5,7 +5,7 @@ export TMPDIR="${TMPDIR:-$project_root/.cache/tmp}" export UV_CACHE_DIR="${UV_CACHE_DIR:-$project_root/.cache/uv}" export PYTHONDONTWRITEBYTECODE=1 mkdir -p "$TMPDIR" "$UV_CACHE_DIR" -python3 "$project_root/verify_dist.py" --all-wheels --require-native --require-arm64 +python3 "$project_root/verify_dist.py" --all-wheels --require-native --require-arm64 --require-desktop version="$(python3 "$project_root/verify_dist.py" --version)" shopt -s nullglob wheels=("$project_root/dist/akiki-${version}-"*.whl) From 6c63ce2f0f2cd46c3a668ccc5ea1fecec62000f8 Mon Sep 17 00:00:00 2001 From: Toby Jackson Date: Tue, 17 Nov 2026 18:55:25 +0000 Subject: [PATCH 4/5] Derive macOS wheel tags from the bundled native libraries --- setup.py | 25 +++++++++++++++++++++++++ tests/test_packaging.py | 29 +++++++++++++++++++++++++++++ verify_dist.py | 3 ++- 3 files changed, 56 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index c3eb75c..625eded 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,7 @@ """Optionally bundle prebuilt C-ABI libraries in a platform-specific wheel.""" import os +import re import shutil import struct from pathlib import Path @@ -56,6 +57,29 @@ def linux_platform(libraries): return "linux_aarch64" if machine == 183 else "linux_x86_64" +def macos_platform(libraries, tag): + """Use the bundled Mach-O architecture instead of the Python interpreter's tag.""" + if not libraries or not all(path.suffix == ".dylib" for path in libraries): + return None + platform = re.fullmatch(r"(macosx_\d+_\d+)_(?:x86_64|arm64|universal2)", tag) + if platform is None: + raise ValueError("Native macOS libraries require a macOS wheel platform") + machines = set() + for path in libraries: + with path.open("rb") as source: + header = source.read(8) + if len(header) != 8 or header[:4] != b"\xcf\xfa\xed\xfe": + raise ValueError(f"Expected a thin little-endian Mach-O64 library: {path.name}") + machine = int.from_bytes(header[4:8], "little") + if machine not in {0x01000007, 0x0100000C}: + raise ValueError(f"Unsupported Mach-O architecture in {path.name}: {machine}") + machines.add(machine) + if len(machines) != 1: + raise ValueError("Native libraries must have the same architecture") + architecture = "arm64" if machines.pop() == 0x0100000C else "x86_64" + return f"{platform[1]}_{architecture}" + + class BuildPy(build_py): def run(self): super().run() @@ -80,6 +104,7 @@ def get_tag(self): python, abi, platform = super().get_tag() libraries = native_libraries() platform = linux_platform(libraries) or platform + platform = macos_platform(libraries, platform) or platform # ctypes uses the C ABI; this library has no CPython ABI dependency. return ("py3", "none", platform) if libraries else (python, abi, platform) diff --git a/tests/test_packaging.py b/tests/test_packaging.py index aad164e..41675cd 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -52,6 +52,34 @@ def test_mixed_architectures_are_rejected_and_arm64_minilm_is_allowed(tmp_path): assert setup.linux_platform([vad, minilm]) == "linux_aarch64" +@pytest.mark.parametrize("machine,architecture", [(0x01000007, "x86_64"), (0x0100000C, "arm64")]) +def test_macos_wheel_uses_library_architecture_with_universal_python( + tmp_path, monkeypatch, machine, architecture +): + setup = load_script("akiki_setup", "setup.py") + native = tmp_path / "libakiki_vad_engine.dylib" + native.write_bytes(b"\xcf\xfa\xed\xfe" + struct.pack(" Date: Tue, 17 Nov 2026 19:08:34 +0000 Subject: [PATCH 5/5] Retry transient Windows cache replacement failures atomically --- .github/workflows/publish.yml | 9 +++++ src/akiki/_affine_cache.py | 3 +- src/akiki/_atomic.py | 22 +++++++++++ src/akiki/_quantization.py | 3 +- tests/test_atomic.py | 69 +++++++++++++++++++++++++++++++++++ 5 files changed, 104 insertions(+), 2 deletions(-) create mode 100644 src/akiki/_atomic.py create mode 100644 tests/test_atomic.py diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index ce235c3..07b9c8d 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -415,6 +415,15 @@ jobs: cwd=root, check=True, ) + if sys.platform == "win32": + for _ in range(5): + subprocess.run( + [str(executable), "-m", "pytest", "-q", "-o", "pythonpath=", + "tests/test_affine_cache.py::test_concurrent_saves_leave_one_complete_valid_layer", + "tests/test_quantization.py::test_concurrent_first_use_produces_one_valid_variant"], + cwd=root, + check=True, + ) PY - name: Save the verified native wheel diff --git a/src/akiki/_affine_cache.py b/src/akiki/_affine_cache.py index c13f395..8dec36f 100644 --- a/src/akiki/_affine_cache.py +++ b/src/akiki/_affine_cache.py @@ -14,6 +14,7 @@ import numpy as np +from ._atomic import replace_file from ._base_models import BaseModel from ._quantization import default_cache_dir @@ -151,7 +152,7 @@ def __setitem__(self, base: BaseModel, layer: AffineLayer) -> None: ) stream.flush() os.fsync(stream.fileno()) - os.replace(temporary, path) + replace_file(temporary, path) except OSError as error: raise RuntimeError( f"Cannot save trained affine cache entry {path}. " diff --git a/src/akiki/_atomic.py b/src/akiki/_atomic.py new file mode 100644 index 0000000..886f6ae --- /dev/null +++ b/src/akiki/_atomic.py @@ -0,0 +1,22 @@ +"""Replace cache files atomically across supported operating systems.""" + +import os +import sys +import time +from pathlib import Path + + +def replace_file(source: Path, destination: Path) -> None: + """Retry temporary Windows file-sharing failures without removing the destination.""" + for attempt in range(9): + try: + os.replace(source, destination) + return + except PermissionError as error: + if ( + sys.platform != "win32" + or getattr(error, "winerror", None) not in {5, 32, 33} + or attempt == 8 + ): + raise + time.sleep(0.01 * 2**attempt) diff --git a/src/akiki/_quantization.py b/src/akiki/_quantization.py index 69f94f4..f3a7337 100644 --- a/src/akiki/_quantization.py +++ b/src/akiki/_quantization.py @@ -17,6 +17,7 @@ import numpy as np +from ._atomic import replace_file from ._precision import ModelPrecision # AKVAD003 format IDs are fixed independently of enum declaration order. @@ -187,7 +188,7 @@ def _atomic_write(path, data): stream.write(data) stream.flush() os.fsync(stream.fileno()) - os.replace(temporary, path) + replace_file(temporary, path) finally: if temporary is not None: temporary.unlink(missing_ok=True) diff --git a/tests/test_atomic.py b/tests/test_atomic.py new file mode 100644 index 0000000..0a8c029 --- /dev/null +++ b/tests/test_atomic.py @@ -0,0 +1,69 @@ +"""Windows file sharing must preserve complete cache entries during replacement.""" + +import pytest + +from akiki import _atomic + + +def sharing_error(): + error = PermissionError("The destination is temporarily open") + error.winerror = 5 + return error + + +def test_windows_sharing_failures_retry_without_removing_the_valid_entry(tmp_path, monkeypatch): + source, destination = tmp_path / "temporary", tmp_path / "cache" + source.write_bytes(b"new complete data") + destination.write_bytes(b"old complete data") + original = _atomic.os.replace + attempts, delays = [], [] + + def replace(first, second): + attempts.append((first, second)) + assert destination.read_bytes() == b"old complete data" + if len(attempts) < 3: + raise sharing_error() + original(first, second) + + monkeypatch.setattr(_atomic.sys, "platform", "win32") + monkeypatch.setattr(_atomic.os, "replace", replace) + monkeypatch.setattr(_atomic.time, "sleep", delays.append) + _atomic.replace_file(source, destination) + assert len(attempts) == 3 and delays == [0.01, 0.02] + assert destination.read_bytes() == b"new complete data" + assert not source.exists() + + +def test_permanent_windows_failure_is_bounded_and_preserves_both_files(tmp_path, monkeypatch): + source, destination = tmp_path / "temporary", tmp_path / "cache" + source.write_bytes(b"new complete data") + destination.write_bytes(b"old complete data") + attempts, delays = [], [] + + def replace(*paths): + attempts.append(paths) + raise sharing_error() + + monkeypatch.setattr(_atomic.sys, "platform", "win32") + monkeypatch.setattr(_atomic.os, "replace", replace) + monkeypatch.setattr(_atomic.time, "sleep", delays.append) + with pytest.raises(PermissionError): + _atomic.replace_file(source, destination) + assert len(attempts) == 9 and sum(delays) == pytest.approx(2.55) + assert source.read_bytes() == b"new complete data" + assert destination.read_bytes() == b"old complete data" + + +def test_other_platform_failures_raise_without_retry(tmp_path, monkeypatch): + attempts, delays = [], [] + + def replace(*paths): + attempts.append(paths) + raise PermissionError("The directory is not writable") + + monkeypatch.setattr(_atomic.sys, "platform", "linux") + monkeypatch.setattr(_atomic.os, "replace", replace) + monkeypatch.setattr(_atomic.time, "sleep", delays.append) + with pytest.raises(PermissionError, match="not writable"): + _atomic.replace_file(tmp_path / "temporary", tmp_path / "cache") + assert len(attempts) == 1 and not delays