| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
import pickle # ruff:ignore[suspicious-pickle-import] # round-trip uses bytes produced in this test |
| 5 |
import socket |
| 6 |
import stat |
| 7 |
import sys |
| 8 |
import time |
| 9 |
from errno import EACCES, EEXIST, EIO, ENOENT, ESTALE, EXDEV |
| 10 |
from pathlib import Path |
| 11 |
from typing import TYPE_CHECKING, Final |
| 12 |
|
| 13 |
import pytest |
| 14 |
|
| 15 |
if sys.version_info >= (3, 11): |
| 16 |
from builtins import BaseExceptionGroup # pragma: >=3.11 cover |
| 17 |
else: # pragma: <3.11 cover |
| 18 |
from exceptiongroup import BaseExceptionGroup |
| 19 |
|
| 20 |
from capabilities import CAPABILITIES |
| 21 |
|
| 22 |
import filelock._strict |
| 23 |
from filelock import SoftFileLock, SoftFileLockProtocolError, StrictSoftFileLock, Timeout |
| 24 |
from filelock._strict import _probe_link_follow_symlinks, _relative_identity |
| 25 |
|
| 26 |
# These cases inject a failure into a directory-fd cleanup step or the reaper race, both of which only run where the |
| 27 |
# protocol uses dir_fd descriptors. Without dir_fd those branches never execute and the injected fault never fires; the |
| 28 |
# cleanup path is covered there instead by the passing stress, contention and release tests. |
| 29 |
_NEEDS_DIR_FD: Final[pytest.MarkDecorator] = pytest.mark.skipif( |
| 30 |
os.open not in os.supports_dir_fd, |
| 31 |
reason="injects a fault into the dir_fd cleanup path, which a runtime without dir_fd never executes", |
| 32 |
) |
| 33 |
|
| 34 |
# Narrower still: GraalPy takes os.open relative to a directory descriptor but not os.link, so the backend never opens |
| 35 |
# the directory these two faults are counted against. |
| 36 |
_NEEDS_LINK_DIR_FD: Final[pytest.MarkDecorator] = pytest.mark.skipif( |
| 37 |
not CAPABILITIES["link-dir-fd"], |
| 38 |
reason="counts the directory the dir_fd link path opens, which a runtime without link dir_fd never opens", |
| 39 |
) |
| 40 |
|
| 41 |
if TYPE_CHECKING: |
| 42 |
from collections.abc import Iterator |
| 43 |
|
| 44 |
from pytest_mock import MockerFixture |
| 45 |
|
| 46 |
_PathValue = str | bytes | os.PathLike[str] | os.PathLike[bytes] |
| 47 |
|
| 48 |
|
| 49 |
pytestmark = pytest.mark.requires_hard_links |
| 50 |
|
| 51 |
|
| 52 |
def test_strict_soft_protocol_error_pickles() -> None: |
| 53 |
error = SoftFileLockProtocolError("resource.lock", "held-v2-claim", "unknown version") |
| 54 |
|
| 55 |
restored = pickle.loads(pickle.dumps(error)) # ruff:ignore[suspicious-pickle-usage] # input comes from the preceding local value |
| 56 |
|
| 57 |
assert (type(restored), restored.lock_file, restored.claim_name, restored.reason, str(restored)) == ( |
| 58 |
SoftFileLockProtocolError, |
| 59 |
"resource.lock", |
| 60 |
"held-v2-claim", |
| 61 |
"unknown version", |
| 62 |
"Invalid strict soft-lock state at resource.lock: claim 'held-v2-claim': unknown version", |
| 63 |
) |
| 64 |
|
| 65 |
|
| 66 |
def test_strict_soft_claims_empty_before_first_acquire(tmp_path: Path) -> None: |
| 67 |
assert StrictSoftFileLock(tmp_path / "resource.lock").claims == () |
| 68 |
|
| 69 |
|
| 70 |
def test_strict_soft_intent_token_collision_does_not_claim_lock(tmp_path: Path, mocker: MockerFixture) -> None: |
| 71 |
lock_path = tmp_path / "resource.lock" |
| 72 |
_initialize_protocol(lock_path) |
| 73 |
|
| 74 |
def collide_intent( |
| 75 |
_source: _PathValue, |
| 76 |
_destination: _PathValue, |
| 77 |
**_options: int | bool | None, |
| 78 |
) -> None: |
| 79 |
# The intent link is the only link this flow attempts before it fails closed, so colliding it unconditionally |
| 80 |
# is equivalent to matching on the intent- prefix. |
| 81 |
raise FileExistsError(EEXIST, "claim exists") |
| 82 |
|
| 83 |
mocker.patch("filelock._strict.os.link", side_effect=collide_intent) |
| 84 |
lock = StrictSoftFileLock(lock_path, timeout=0) |
| 85 |
|
| 86 |
with pytest.raises(Timeout): |
| 87 |
lock.acquire() |
| 88 |
assert (lock.claims, lock.is_locked) == ((), False) |
| 89 |
|
| 90 |
|
| 91 |
def test_strict_soft_held_publication_failure_rolls_back_intent(tmp_path: Path, mocker: MockerFixture) -> None: |
| 92 |
lock_path = tmp_path / "resource.lock" |
| 93 |
_initialize_protocol(lock_path) |
| 94 |
real_link = os.link |
| 95 |
|
| 96 |
def fail_held( |
| 97 |
source: _PathValue, |
| 98 |
destination: _PathValue, |
| 99 |
*, |
| 100 |
src_dir_fd: int | None = None, |
| 101 |
dst_dir_fd: int | None = None, |
| 102 |
follow_symlinks: bool = True, |
| 103 |
) -> None: |
| 104 |
if Path(os.fsdecode(destination)).name.startswith("held-"): |
| 105 |
raise OSError(EXDEV, "hard links unavailable") |
| 106 |
real_link( |
| 107 |
source, |
| 108 |
destination, |
| 109 |
src_dir_fd=src_dir_fd, |
| 110 |
dst_dir_fd=dst_dir_fd, |
| 111 |
follow_symlinks=follow_symlinks, |
| 112 |
) |
| 113 |
|
| 114 |
mocker.patch("filelock._strict.os.link", side_effect=fail_held) |
| 115 |
lock = StrictSoftFileLock(lock_path) |
| 116 |
|
| 117 |
with pytest.raises(SoftFileLockProtocolError, match="hard-link publication"): |
| 118 |
lock.acquire() |
| 119 |
assert (lock.claims, lock.is_locked) == ((), False) |
| 120 |
|
| 121 |
|
| 122 |
def test_strict_soft_held_collision_does_not_delete_foreign_claim(tmp_path: Path, mocker: MockerFixture) -> None: |
| 123 |
lock_path = tmp_path / "resource.lock" |
| 124 |
_initialize_protocol(lock_path) |
| 125 |
real_link = os.link |
| 126 |
|
| 127 |
def publish_foreign_held( |
| 128 |
source: _PathValue, |
| 129 |
destination: _PathValue, |
| 130 |
*, |
| 131 |
src_dir_fd: int | None = None, |
| 132 |
dst_dir_fd: int | None = None, |
| 133 |
follow_symlinks: bool = True, |
| 134 |
) -> None: |
| 135 |
real_link( |
| 136 |
source, |
| 137 |
destination, |
| 138 |
src_dir_fd=src_dir_fd, |
| 139 |
dst_dir_fd=dst_dir_fd, |
| 140 |
follow_symlinks=follow_symlinks, |
| 141 |
) |
| 142 |
if Path(os.fsdecode(destination)).name.startswith("held-"): |
| 143 |
raise FileExistsError(EEXIST, "foreign claim won") |
| 144 |
|
| 145 |
mocker.patch("filelock._strict.os.link", side_effect=publish_foreign_held) |
| 146 |
|
| 147 |
with pytest.raises(FileExistsError, match="foreign claim won"): |
| 148 |
StrictSoftFileLock(lock_path).acquire() |
| 149 |
claims = StrictSoftFileLock(lock_path).claims |
| 150 |
assert (len(claims), claims[0].state) == (1, "held") |
| 151 |
|
| 152 |
|
| 153 |
@pytest.mark.parametrize("scan_to_empty", [pytest.param(2, id="intent"), pytest.param(3, id="held")]) |
| 154 |
def test_strict_soft_force_break_during_doorway_backs_off( |
| 155 |
tmp_path: Path, mocker: MockerFixture, scan_to_empty: int |
| 156 |
) -> None: |
| 157 |
lock_path = tmp_path / "resource.lock" |
| 158 |
_initialize_protocol(lock_path) |
| 159 |
real_scandir = os.scandir |
| 160 |
scans = 0 |
| 161 |
|
| 162 |
def break_before_scan(path: str | os.PathLike[str]) -> Iterator[os.DirEntry[str]]: |
| 163 |
nonlocal scans |
| 164 |
scans += 1 |
| 165 |
if scans == scan_to_empty: |
| 166 |
for claim in Path(os.fsdecode(path)).glob("*.claim"): |
| 167 |
claim.unlink() |
| 168 |
return real_scandir(path) |
| 169 |
|
| 170 |
mocker.patch("filelock._strict.os.scandir", side_effect=break_before_scan) |
| 171 |
lock = StrictSoftFileLock(lock_path, timeout=0) |
| 172 |
|
| 173 |
with pytest.raises(Timeout): |
| 174 |
lock.acquire() |
| 175 |
assert (lock.claims, lock.is_locked) == ((), False) |
| 176 |
|
| 177 |
|
| 178 |
def test_strict_soft_force_break_held_during_doorway_backs_off(tmp_path: Path, mocker: MockerFixture) -> None: |
| 179 |
lock_path = tmp_path / "resource.lock" |
| 180 |
_initialize_protocol(lock_path) |
| 181 |
real_scandir = os.scandir |
| 182 |
scans = 0 |
| 183 |
|
| 184 |
def break_held_before_final_scan(path: str | os.PathLike[str]) -> Iterator[os.DirEntry[str]]: |
| 185 |
nonlocal scans |
| 186 |
scans += 1 |
| 187 |
if scans == 3: |
| 188 |
for claim in Path(os.fsdecode(path)).glob("held-*.claim"): |
| 189 |
claim.unlink() |
| 190 |
return real_scandir(path) |
| 191 |
|
| 192 |
mocker.patch("filelock._strict.os.scandir", side_effect=break_held_before_final_scan) |
| 193 |
lock = StrictSoftFileLock(lock_path, timeout=0) |
| 194 |
|
| 195 |
with pytest.raises(Timeout): |
| 196 |
lock.acquire() |
| 197 |
assert (lock.claims, lock.is_locked) == ((), False) |
| 198 |
|
| 199 |
|
| 200 |
@_NEEDS_DIR_FD # pragma: needs dir-fd |
| 201 |
def test_strict_soft_reaper_removes_private_before_publication(tmp_path: Path, mocker: MockerFixture) -> None: |
| 202 |
lock_path = tmp_path / "resource.lock" |
| 203 |
_initialize_protocol(lock_path) |
| 204 |
token = "0" * 32 |
| 205 |
private_path = _private_claim_path(lock_path, token) |
| 206 |
real_link = os.link |
| 207 |
|
| 208 |
def reap_before_link( |
| 209 |
source: _PathValue, |
| 210 |
destination: _PathValue, |
| 211 |
*, |
| 212 |
src_dir_fd: int | None = None, |
| 213 |
dst_dir_fd: int | None = None, |
| 214 |
follow_symlinks: bool = True, |
| 215 |
) -> None: |
| 216 |
# The reaped private record aborts the acquisition at the intent link, so no held link ever reaches here. |
| 217 |
if Path(os.fsdecode(destination)).name.startswith("intent-"): # pragma: no branch |
| 218 |
os.utime(private_path, (0, 0)) |
| 219 |
assert StrictSoftFileLock(lock_path).claims == () |
| 220 |
real_link( |
| 221 |
source, |
| 222 |
destination, |
| 223 |
src_dir_fd=src_dir_fd, |
| 224 |
dst_dir_fd=dst_dir_fd, |
| 225 |
follow_symlinks=follow_symlinks, |
| 226 |
) |
| 227 |
|
| 228 |
mocker.patch("filelock._strict.secrets.token_hex", return_value=token) |
| 229 |
mocker.patch("filelock._strict.os.link", side_effect=reap_before_link) |
| 230 |
lock = StrictSoftFileLock(lock_path, timeout=0) |
| 231 |
|
| 232 |
with pytest.raises(Timeout): |
| 233 |
lock.acquire() |
| 234 |
assert (lock.claims, lock.is_locked, private_path.exists()) == ((), False, False) |
| 235 |
|
| 236 |
|
| 237 |
def test_strict_soft_reaper_removes_private_after_publication(tmp_path: Path, mocker: MockerFixture) -> None: |
| 238 |
lock_path = tmp_path / "resource.lock" |
| 239 |
_initialize_protocol(lock_path) |
| 240 |
token = "0" * 32 |
| 241 |
private_path = _private_claim_path(lock_path, token) |
| 242 |
real_link = os.link |
| 243 |
|
| 244 |
def reap_after_link( |
| 245 |
source: _PathValue, |
| 246 |
destination: _PathValue, |
| 247 |
*, |
| 248 |
src_dir_fd: int | None = None, |
| 249 |
dst_dir_fd: int | None = None, |
| 250 |
follow_symlinks: bool = True, |
| 251 |
) -> None: |
| 252 |
real_link( |
| 253 |
source, |
| 254 |
destination, |
| 255 |
src_dir_fd=src_dir_fd, |
| 256 |
dst_dir_fd=dst_dir_fd, |
| 257 |
follow_symlinks=follow_symlinks, |
| 258 |
) |
| 259 |
if Path(os.fsdecode(destination)).name.startswith("intent-"): |
| 260 |
assert len(StrictSoftFileLock(lock_path).claims) == 1 |
| 261 |
|
| 262 |
mocker.patch("filelock._strict.secrets.token_hex", return_value=token) |
| 263 |
mocker.patch("filelock._strict.os.link", side_effect=reap_after_link) |
| 264 |
|
| 265 |
with StrictSoftFileLock(lock_path, timeout=0) as lock: |
| 266 |
assert (lock.claims[0].state, private_path.exists()) == ("held", False) |
| 267 |
|
| 268 |
|
| 269 |
@_NEEDS_DIR_FD # pragma: needs dir-fd |
| 270 |
def test_strict_soft_reaper_replacement_only_aborts_publisher(tmp_path: Path, mocker: MockerFixture) -> None: |
| 271 |
lock_path = tmp_path / "resource.lock" |
| 272 |
_initialize_protocol(lock_path) |
| 273 |
token = "0" * 32 |
| 274 |
private_path = _private_claim_path(lock_path, token) |
| 275 |
displaced_path = private_path.with_suffix(".displaced") |
| 276 |
real_link = os.link |
| 277 |
real_unlink = Path.unlink |
| 278 |
replaced = False |
| 279 |
|
| 280 |
def replace_before_unlink(path: Path, *, missing_ok: bool = False) -> None: |
| 281 |
nonlocal replaced |
| 282 |
if path == private_path and not replaced: |
| 283 |
replaced = True |
| 284 |
path.replace(displaced_path) |
| 285 |
path.write_bytes(b"replacement publisher") |
| 286 |
return |
| 287 |
real_unlink(path, missing_ok=missing_ok) |
| 288 |
|
| 289 |
def reap_before_link( |
| 290 |
source: _PathValue, |
| 291 |
destination: _PathValue, |
| 292 |
*, |
| 293 |
src_dir_fd: int | None = None, |
| 294 |
dst_dir_fd: int | None = None, |
| 295 |
follow_symlinks: bool = True, |
| 296 |
) -> None: |
| 297 |
# The reaped private record aborts the acquisition at the intent link, so no held link ever reaches here. |
| 298 |
if Path(os.fsdecode(destination)).name.startswith("intent-"): # pragma: no branch |
| 299 |
os.utime(private_path, (0, 0)) |
| 300 |
assert StrictSoftFileLock(lock_path).claims == () |
| 301 |
real_link( |
| 302 |
source, |
| 303 |
destination, |
| 304 |
src_dir_fd=src_dir_fd, |
| 305 |
dst_dir_fd=dst_dir_fd, |
| 306 |
follow_symlinks=follow_symlinks, |
| 307 |
) |
| 308 |
|
| 309 |
mocker.patch("filelock._strict.secrets.token_hex", return_value=token) |
| 310 |
mocker.patch("filelock._strict.os.link", side_effect=reap_before_link) |
| 311 |
mocker.patch.object(Path, "unlink", autospec=True, side_effect=replace_before_unlink) |
| 312 |
lock = StrictSoftFileLock(lock_path, timeout=0) |
| 313 |
|
| 314 |
with pytest.raises(Timeout): |
| 315 |
lock.acquire() |
| 316 |
with pytest.raises(SoftFileLockProtocolError, match="malformed claim record"): |
| 317 |
_ = lock.claims |
| 318 |
public_path = private_path.parent / f"intent-v1-{token}.claim" |
| 319 |
assert ( |
| 320 |
replaced, |
| 321 |
lock.is_locked, |
| 322 |
private_path.exists(), |
| 323 |
public_path.read_bytes(), |
| 324 |
displaced_path.exists(), |
| 325 |
) == ( |
| 326 |
True, |
| 327 |
False, |
| 328 |
False, |
| 329 |
b"replacement publisher", |
| 330 |
True, |
| 331 |
) |
| 332 |
|
| 333 |
|
| 334 |
def test_strict_soft_private_close_failure_leaves_public_claim(tmp_path: Path, mocker: MockerFixture) -> None: |
| 335 |
lock_path = tmp_path / "resource.lock" |
| 336 |
_initialize_protocol(lock_path) |
| 337 |
real_close = os.close |
| 338 |
real_open_relative = filelock._strict._open_relative |
| 339 |
private_fd: int | None = None |
| 340 |
|
| 341 |
def capture_private_record(directory_ref: tuple[str, int | None], name: str, flags: int, mode: int) -> int: |
| 342 |
nonlocal private_fd |
| 343 |
private_fd = real_open_relative(directory_ref, name, flags, mode) |
| 344 |
return private_fd |
| 345 |
|
| 346 |
# filelock._strict.os is the os module, so this patches os.close process-wide. Key the fault to the descriptor |
| 347 |
# under test rather than to call order: a background thread closing first would otherwise consume it, which is how |
| 348 |
# a soft-rw heartbeat still winding down turned these injections red on GraalPy. |
| 349 |
def fail_private_close(fd: int) -> None: |
| 350 |
real_close(fd) |
| 351 |
if fd == private_fd: |
| 352 |
raise OSError(EIO, "private close failed") |
| 353 |
|
| 354 |
mocker.patch("filelock._strict._open_relative", side_effect=capture_private_record) |
| 355 |
mocker.patch("filelock._strict.os.close", side_effect=fail_private_close) |
| 356 |
lock = StrictSoftFileLock(lock_path) |
| 357 |
|
| 358 |
with pytest.raises(OSError, match="private close failed"): |
| 359 |
lock.acquire() |
| 360 |
assert ([claim.state for claim in lock.claims], lock.is_locked) == (["intent"], False) |
| 361 |
|
| 362 |
|
| 363 |
@_NEEDS_DIR_FD # pragma: needs dir-fd |
| 364 |
def test_strict_soft_link_and_directory_close_failures_preserve_both(tmp_path: Path, mocker: MockerFixture) -> None: |
| 365 |
lock_path = tmp_path / "resource.lock" |
| 366 |
_initialize_protocol(lock_path) |
| 367 |
real_close = os.close |
| 368 |
real_fstat = os.fstat |
| 369 |
directory_close_failed = False |
| 370 |
|
| 371 |
def fail_directory_close(fd: int) -> None: |
| 372 |
nonlocal directory_close_failed |
| 373 |
is_directory = stat.S_ISDIR(real_fstat(fd).st_mode) |
| 374 |
real_close(fd) |
| 375 |
if is_directory and not directory_close_failed: |
| 376 |
directory_close_failed = True |
| 377 |
raise OSError(EIO, "directory close failed") |
| 378 |
|
| 379 |
mocker.patch("filelock._strict.os.link", side_effect=OSError(EIO, "link failed")) |
| 380 |
mocker.patch("filelock._strict.os.close", side_effect=fail_directory_close) |
| 381 |
lock = StrictSoftFileLock(lock_path) |
| 382 |
|
| 383 |
with pytest.raises(BaseExceptionGroup) as raised: |
| 384 |
lock.acquire() |
| 385 |
assert ([str(error) for error in raised.value.exceptions], lock.claims, lock.is_locked) == ( |
| 386 |
["[Errno 5] link failed", "[Errno 5] directory close failed"], |
| 387 |
(), |
| 388 |
False, |
| 389 |
) |
| 390 |
|
| 391 |
|
| 392 |
@_NEEDS_DIR_FD # pragma: needs dir-fd |
| 393 |
@_NEEDS_LINK_DIR_FD # pragma: needs link-dir-fd |
| 394 |
def test_strict_soft_held_directory_close_failure_leaves_both_claims(tmp_path: Path, mocker: MockerFixture) -> None: |
| 395 |
lock_path = tmp_path / "resource.lock" |
| 396 |
_initialize_protocol(lock_path) |
| 397 |
real_close = os.close |
| 398 |
real_fstat = os.fstat |
| 399 |
directory_closes = 0 |
| 400 |
|
| 401 |
def fail_second_directory_close(fd: int) -> None: |
| 402 |
nonlocal directory_closes |
| 403 |
is_directory = stat.S_ISDIR(real_fstat(fd).st_mode) |
| 404 |
real_close(fd) |
| 405 |
if is_directory: |
| 406 |
directory_closes += 1 |
| 407 |
if directory_closes == 2: |
| 408 |
raise OSError(EIO, "held directory close failed") |
| 409 |
|
| 410 |
mocker.patch("filelock._strict.os.close", side_effect=fail_second_directory_close) |
| 411 |
lock = StrictSoftFileLock(lock_path) |
| 412 |
|
| 413 |
with pytest.raises(OSError, match="held directory close failed"): |
| 414 |
lock.acquire() |
| 415 |
assert ([claim.state for claim in lock.claims], lock.is_locked) == (["held", "intent"], False) |
| 416 |
|
| 417 |
|
| 418 |
@pytest.mark.parametrize( |
| 419 |
"node", |
| 420 |
[ |
| 421 |
pytest.param("directory", id="directory"), |
| 422 |
pytest.param( |
| 423 |
"symlink", |
| 424 |
id="symlink", |
| 425 |
marks=pytest.mark.skipif(not CAPABILITIES["symlink"], reason="stages the private record as a symlink"), |
| 426 |
), |
| 427 |
], |
| 428 |
) |
| 429 |
def test_strict_soft_reaper_leaves_non_regular_private_node(tmp_path: Path, node: str) -> None: |
| 430 |
lock_path = tmp_path / "resource.lock" |
| 431 |
_initialize_protocol(lock_path) |
| 432 |
private_path = _private_claim_path(lock_path, "0" * 32) |
| 433 |
if node == "directory": |
| 434 |
private_path.mkdir() |
| 435 |
else: |
| 436 |
private_path.symlink_to(tmp_path / "missing") # pragma: needs symlink |
| 437 |
|
| 438 |
with pytest.raises(SoftFileLockProtocolError, match="cannot list claim directory"): |
| 439 |
_ = StrictSoftFileLock(lock_path).claims |
| 440 |
assert private_path.is_dir() if node == "directory" else private_path.is_symlink() |
| 441 |
|
| 442 |
|
| 443 |
def test_strict_soft_reaper_does_not_retry_sharing_error(tmp_path: Path, mocker: MockerFixture) -> None: |
| 444 |
lock_path = tmp_path / "resource.lock" |
| 445 |
_initialize_protocol(lock_path) |
| 446 |
private_path = _private_claim_path(lock_path, "0" * 32) |
| 447 |
private_path.write_bytes(b"abandoned") |
| 448 |
os.utime(private_path, (0, 0)) |
| 449 |
unlink = mocker.patch.object( |
| 450 |
Path, |
| 451 |
"unlink", |
| 452 |
autospec=True, |
| 453 |
side_effect=PermissionError(EACCES, "sharing violation"), |
| 454 |
) |
| 455 |
|
| 456 |
started = time.perf_counter() |
| 457 |
assert StrictSoftFileLock(lock_path).claims == () |
| 458 |
elapsed = time.perf_counter() - started |
| 459 |
assert (unlink.call_count, elapsed < 0.1, private_path.exists()) == (1, True, True) |
| 460 |
|
| 461 |
|
| 462 |
@_NEEDS_DIR_FD # pragma: needs dir-fd |
| 463 |
def test_strict_soft_release_error_keeps_remaining_claim(tmp_path: Path, mocker: MockerFixture) -> None: |
| 464 |
lock_path = tmp_path / "resource.lock" |
| 465 |
lock = StrictSoftFileLock(lock_path) |
| 466 |
lock.acquire() |
| 467 |
claim_name = lock.claims[0].name |
| 468 |
real_unlink = Path.unlink |
| 469 |
failed = False |
| 470 |
|
| 471 |
def fail_once(path: Path, *, missing_ok: bool = False) -> None: |
| 472 |
nonlocal failed |
| 473 |
if not failed: |
| 474 |
failed = True |
| 475 |
assert path.name == claim_name |
| 476 |
raise PermissionError(EACCES, "claim is not writable") |
| 477 |
real_unlink(path, missing_ok=missing_ok) |
| 478 |
|
| 479 |
mocker.patch("filelock._strict._UNLINK_SUPPORTS_DIR_FD", new=False) |
| 480 |
mocker.patch.object(Path, "unlink", autospec=True, side_effect=fail_once) |
| 481 |
with pytest.raises(PermissionError, match="claim is not writable"): |
| 482 |
lock.release() |
| 483 |
assert (lock.is_locked, [claim.name for claim in lock.claims]) == (True, [claim_name]) |
| 484 |
|
| 485 |
lock.release() |
| 486 |
assert (lock.is_locked, lock.claims) == (False, ()) |
| 487 |
|
| 488 |
|
| 489 |
@_NEEDS_DIR_FD # pragma: needs dir-fd |
| 490 |
def test_strict_soft_release_commits_before_directory_close_error(tmp_path: Path, mocker: MockerFixture) -> None: |
| 491 |
lock_path = tmp_path / "resource.lock" |
| 492 |
lock = StrictSoftFileLock(lock_path) |
| 493 |
lock.acquire() |
| 494 |
real_close = os.close |
| 495 |
real_fstat = os.fstat |
| 496 |
directory_close_failed = False |
| 497 |
|
| 498 |
def fail_directory_close(fd: int) -> None: |
| 499 |
nonlocal directory_close_failed |
| 500 |
is_directory = stat.S_ISDIR(real_fstat(fd).st_mode) |
| 501 |
real_close(fd) |
| 502 |
if is_directory and not directory_close_failed: |
| 503 |
directory_close_failed = True |
| 504 |
raise OSError(EIO, "directory close failed") |
| 505 |
|
| 506 |
close_mock = mocker.patch("filelock._strict.os.close", side_effect=fail_directory_close) |
| 507 |
|
| 508 |
with pytest.raises(OSError, match="directory close failed"): |
| 509 |
lock.release() |
| 510 |
mocker.stop(close_mock) |
| 511 |
assert (lock.is_locked, lock.lock_counter, lock.claims) == (False, 0, ()) |
| 512 |
with StrictSoftFileLock(lock_path, timeout=0) as contender: |
| 513 |
assert contender.is_locked |
| 514 |
|
| 515 |
|
| 516 |
@_NEEDS_DIR_FD # pragma: needs dir-fd |
| 517 |
def test_strict_soft_release_preserves_unlink_and_directory_close_errors(tmp_path: Path, mocker: MockerFixture) -> None: |
| 518 |
lock_path = tmp_path / "resource.lock" |
| 519 |
lock = StrictSoftFileLock(lock_path) |
| 520 |
lock.acquire() |
| 521 |
real_close = os.close |
| 522 |
real_fstat = os.fstat |
| 523 |
real_unlink = os.unlink |
| 524 |
directory_close_failed = False |
| 525 |
|
| 526 |
def fail_claim_unlink(path: _PathValue, *, dir_fd: int | None = None) -> None: |
| 527 |
if Path(os.fsdecode(path)).name.startswith("held-"): |
| 528 |
raise PermissionError(EACCES, "claim unlink failed") |
| 529 |
real_unlink(path, dir_fd=dir_fd) |
| 530 |
|
| 531 |
def fail_directory_close(fd: int) -> None: |
| 532 |
nonlocal directory_close_failed |
| 533 |
is_directory = stat.S_ISDIR(real_fstat(fd).st_mode) |
| 534 |
real_close(fd) |
| 535 |
if is_directory and not directory_close_failed: |
| 536 |
directory_close_failed = True |
| 537 |
raise OSError(EIO, "directory close failed") |
| 538 |
|
| 539 |
unlink_mock = mocker.patch("filelock._strict.os.unlink", side_effect=fail_claim_unlink) |
| 540 |
supports_dir_fd_mock = mocker.patch.object(os, "supports_dir_fd", os.supports_dir_fd | {unlink_mock}) |
| 541 |
close_mock = mocker.patch("filelock._strict.os.close", side_effect=fail_directory_close) |
| 542 |
|
| 543 |
with pytest.raises(BaseExceptionGroup) as raised: |
| 544 |
lock.release() |
| 545 |
mocker.stop(unlink_mock) |
| 546 |
mocker.stop(supports_dir_fd_mock) |
| 547 |
mocker.stop(close_mock) |
| 548 |
assert ( |
| 549 |
[str(error) for error in raised.value.exceptions], |
| 550 |
lock.is_locked, |
| 551 |
lock.lock_counter, |
| 552 |
[claim.state for claim in lock.claims], |
| 553 |
) == ( |
| 554 |
["[Errno 13] claim unlink failed", "[Errno 5] directory close failed"], |
| 555 |
True, |
| 556 |
1, |
| 557 |
["held"], |
| 558 |
) |
| 559 |
lock.release() |
| 560 |
|
| 561 |
|
| 562 |
@_NEEDS_DIR_FD # pragma: needs dir-fd |
| 563 |
def test_strict_soft_doorway_preserves_every_claim_cleanup_error(tmp_path: Path, mocker: MockerFixture) -> None: |
| 564 |
lock_path = tmp_path / "resource.lock" |
| 565 |
_initialize_protocol(lock_path) |
| 566 |
owner_token = "f" * 32 |
| 567 |
competitor_token = "0" * 32 |
| 568 |
competitor_name = f"held-v1-{competitor_token}.claim" |
| 569 |
real_close = os.close |
| 570 |
real_fstat = os.fstat |
| 571 |
real_scandir = os.scandir |
| 572 |
real_unlink = os.unlink |
| 573 |
scans = 0 |
| 574 |
cleanup_name: str | None = None |
| 575 |
|
| 576 |
def add_competitor_before_final_scan(path: str | os.PathLike[str]) -> Iterator[os.DirEntry[str]]: |
| 577 |
nonlocal scans |
| 578 |
scans += 1 |
| 579 |
if scans == 3: |
| 580 |
Path(path, competitor_name).write_text( |
| 581 |
f"filelock-strict-v1\n{competitor_token}\n{os.getpid()}\n{socket.gethostname().encode().hex()}\n4242\n", |
| 582 |
encoding="ascii", |
| 583 |
newline="", |
| 584 |
) |
| 585 |
return real_scandir(path) |
| 586 |
|
| 587 |
def fail_held_unlink(path: _PathValue, *, dir_fd: int | None = None) -> None: |
| 588 |
nonlocal cleanup_name |
| 589 |
cleanup_name = Path(os.fsdecode(path)).name |
| 590 |
if cleanup_name == f"held-v1-{owner_token}.claim": |
| 591 |
raise PermissionError(EACCES, "held unlink failed") |
| 592 |
real_unlink(path, dir_fd=dir_fd) |
| 593 |
|
| 594 |
def fail_cleanup_directory_close(fd: int) -> None: |
| 595 |
is_directory = stat.S_ISDIR(real_fstat(fd).st_mode) |
| 596 |
real_close(fd) |
| 597 |
if is_directory and cleanup_name == f"intent-v1-{owner_token}.claim": |
| 598 |
raise OSError(EIO, "intent directory close failed") |
| 599 |
if is_directory and cleanup_name == f"held-v1-{owner_token}.claim": |
| 600 |
raise OSError(EIO, "held directory close failed") |
| 601 |
|
| 602 |
mocker.patch("filelock._strict.secrets.token_hex", return_value=owner_token) |
| 603 |
mocker.patch("filelock._strict.os.scandir", side_effect=add_competitor_before_final_scan) |
| 604 |
unlink_mock = mocker.patch("filelock._strict.os.unlink", side_effect=fail_held_unlink) |
| 605 |
supports_dir_fd_mock = mocker.patch.object(os, "supports_dir_fd", os.supports_dir_fd | {unlink_mock}) |
| 606 |
close_mock = mocker.patch("filelock._strict.os.close", side_effect=fail_cleanup_directory_close) |
| 607 |
lock = StrictSoftFileLock(lock_path) |
| 608 |
|
| 609 |
with pytest.raises(BaseExceptionGroup) as raised: |
| 610 |
lock.acquire() |
| 611 |
mocker.stop(unlink_mock) |
| 612 |
mocker.stop(supports_dir_fd_mock) |
| 613 |
mocker.stop(close_mock) |
| 614 |
assert ( |
| 615 |
_leaf_error_messages(raised.value), |
| 616 |
[claim.name for claim in lock.claims], |
| 617 |
lock.is_locked, |
| 618 |
) == ( |
| 619 |
[ |
| 620 |
"[Errno 13] held unlink failed", |
| 621 |
"[Errno 5] held directory close failed", |
| 622 |
"[Errno 5] intent directory close failed", |
| 623 |
], |
| 624 |
[competitor_name, f"held-v1-{owner_token}.claim"], |
| 625 |
True, |
| 626 |
) |
| 627 |
lock.release(force=True) |
| 628 |
lock.force_break(competitor_name) |
| 629 |
|
| 630 |
|
| 631 |
@pytest.mark.parametrize( |
| 632 |
("sentinel", "acquires"), |
| 633 |
[ |
| 634 |
pytest.param(b"1\nfilelock-strict-v1\x00\n0\n", True, id="strict-winner"), |
| 635 |
pytest.param(b"legacy partial", False, id="legacy-winner"), |
| 636 |
], |
| 637 |
) |
| 638 |
def test_strict_soft_sentinel_publication_race( |
| 639 |
tmp_path: Path, mocker: MockerFixture, sentinel: bytes, *, acquires: bool |
| 640 |
) -> None: |
| 641 |
lock_path = tmp_path / "resource.lock" |
| 642 |
real_link = os.link |
| 643 |
raced = False |
| 644 |
|
| 645 |
def publish_competitor( |
| 646 |
source: _PathValue, |
| 647 |
destination: _PathValue, |
| 648 |
*, |
| 649 |
src_dir_fd: int | None = None, |
| 650 |
dst_dir_fd: int | None = None, |
| 651 |
follow_symlinks: bool = True, |
| 652 |
) -> None: |
| 653 |
nonlocal raced |
| 654 |
if not raced: |
| 655 |
raced = True |
| 656 |
lock_path.write_bytes(sentinel) |
| 657 |
raise FileExistsError(EEXIST, "sentinel exists") |
| 658 |
real_link( |
| 659 |
source, |
| 660 |
destination, |
| 661 |
src_dir_fd=src_dir_fd, |
| 662 |
dst_dir_fd=dst_dir_fd, |
| 663 |
follow_symlinks=follow_symlinks, |
| 664 |
) |
| 665 |
|
| 666 |
mocker.patch("filelock._strict.os.link", side_effect=publish_competitor) |
| 667 |
lock = StrictSoftFileLock(lock_path, timeout=0) |
| 668 |
|
| 669 |
if acquires: |
| 670 |
with lock: |
| 671 |
assert lock.is_locked |
| 672 |
else: |
| 673 |
with pytest.raises(Timeout): |
| 674 |
lock.acquire() |
| 675 |
assert lock_path.read_bytes() == sentinel |
| 676 |
|
| 677 |
|
| 678 |
def test_strict_soft_sentinel_uses_unique_private_names(tmp_path: Path, mocker: MockerFixture) -> None: |
| 679 |
lock_path = tmp_path / "resource.lock" |
| 680 |
private_names: list[str] = [] |
| 681 |
|
| 682 |
def reject_publication(source: _PathValue, _destination: _PathValue, **_options: int | bool | None) -> None: |
| 683 |
private_names.append(Path(os.fsdecode(source)).name) |
| 684 |
raise OSError(EIO, "publication failed") |
| 685 |
|
| 686 |
mocker.patch("filelock._strict.secrets.token_hex", side_effect=["0" * 32, "1" * 32]) |
| 687 |
mocker.patch("filelock._strict.os.link", side_effect=reject_publication) |
| 688 |
|
| 689 |
for _attempt in range(2): |
| 690 |
with pytest.raises(OSError, match="publication failed"): |
| 691 |
StrictSoftFileLock(lock_path).acquire() |
| 692 |
assert private_names == [ |
| 693 |
".resource.lock.private-v1-00000000000000000000000000000000.tmp", |
| 694 |
".resource.lock.private-v1-11111111111111111111111111111111.tmp", |
| 695 |
] |
| 696 |
|
| 697 |
|
| 698 |
def test_strict_soft_existing_non_regular_sentinel_blocks(tmp_path: Path) -> None: |
| 699 |
lock_path = tmp_path / "resource.lock" |
| 700 |
lock_path.mkdir() |
| 701 |
|
| 702 |
with pytest.raises(Timeout): |
| 703 |
StrictSoftFileLock(lock_path, timeout=0).acquire() |
| 704 |
|
| 705 |
|
| 706 |
def test_strict_soft_sentinel_race_with_non_regular_winner_blocks(tmp_path: Path, mocker: MockerFixture) -> None: |
| 707 |
lock_path = tmp_path / "resource.lock" |
| 708 |
|
| 709 |
def publish_directory( |
| 710 |
_source: _PathValue, |
| 711 |
_destination: _PathValue, |
| 712 |
**_options: int | bool | None, |
| 713 |
) -> None: |
| 714 |
lock_path.mkdir() |
| 715 |
raise FileExistsError(EEXIST, "sentinel exists") |
| 716 |
|
| 717 |
mocker.patch("filelock._strict.os.link", side_effect=publish_directory) |
| 718 |
|
| 719 |
with pytest.raises(Timeout): |
| 720 |
StrictSoftFileLock(lock_path, timeout=0).acquire() |
| 721 |
assert lock_path.is_dir() |
| 722 |
|
| 723 |
|
| 724 |
@_NEEDS_DIR_FD # pragma: needs dir-fd |
| 725 |
def test_strict_soft_sentinel_remains_after_private_cleanup_failure(tmp_path: Path, mocker: MockerFixture) -> None: |
| 726 |
lock_path = tmp_path / "resource.lock" |
| 727 |
real_unlink = os.unlink |
| 728 |
failed = False |
| 729 |
|
| 730 |
def fail_first_private_cleanup(path: _PathValue, *, dir_fd: int | None = None) -> None: |
| 731 |
nonlocal failed |
| 732 |
if not failed and Path(os.fsdecode(path)).name.startswith(".resource.lock.private-"): |
| 733 |
failed = True |
| 734 |
raise OSError(EIO, "private cleanup failed") |
| 735 |
real_unlink(path, dir_fd=dir_fd) |
| 736 |
|
| 737 |
mocker.patch("filelock._strict.os.unlink", side_effect=fail_first_private_cleanup) |
| 738 |
|
| 739 |
with pytest.raises(OSError, match="private cleanup failed"): |
| 740 |
StrictSoftFileLock(lock_path).acquire() |
| 741 |
with pytest.raises(Timeout): |
| 742 |
SoftFileLock(lock_path, timeout=0).acquire() |
| 743 |
with StrictSoftFileLock(lock_path, timeout=0) as strict: |
| 744 |
assert (lock_path.read_bytes(), strict.is_locked) == (b"1\nfilelock-strict-v1\x00\n0\n", True) |
| 745 |
|
| 746 |
|
| 747 |
def test_strict_soft_claim_directory_read_error_fails_closed(tmp_path: Path, mocker: MockerFixture) -> None: |
| 748 |
lock_path = tmp_path / "resource.lock" |
| 749 |
_initialize_protocol(lock_path) |
| 750 |
mocker.patch("filelock._strict.os.scandir", side_effect=PermissionError(EACCES, "cannot list")) |
| 751 |
|
| 752 |
with pytest.raises(SoftFileLockProtocolError, match="cannot list claim directory"): |
| 753 |
StrictSoftFileLock(lock_path).acquire() |
| 754 |
|
| 755 |
|
| 756 |
@pytest.mark.parametrize( |
| 757 |
"content", |
| 758 |
[ |
| 759 |
pytest.param(b"filelock-strict-v1\n" + b"0" * 32 + b"\n0\n00\n4242\n", id="zero-pid"), |
| 760 |
pytest.param(b"filelock-strict-v1\n" + b"1" * 32 + b"\n1\n00\n4242\n", id="wrong-token"), |
| 761 |
pytest.param(b"filelock-strict-v1\n" + b"0" * 32 + b"\n1\n686f7374\nnot-int\n", id="non-integer-start"), |
| 762 |
pytest.param(b"filelock-strict-v1\n" + b"0" * 32 + b"\n1\n686f7374\n-5\n", id="negative-start"), |
| 763 |
pytest.param(b"filelock-strict-v1\n" + b"0" * 32 + b"\n1\n686f7374\n007\n", id="noncanonical-start"), |
| 764 |
], |
| 765 |
) |
| 766 |
def test_strict_soft_structurally_invalid_record_fails_closed(tmp_path: Path, content: bytes) -> None: |
| 767 |
lock_path = tmp_path / "resource.lock" |
| 768 |
claims = Path(f"{lock_path}.filelock") / "claims" |
| 769 |
claims.mkdir(parents=True) |
| 770 |
(claims / f"held-v1-{'0' * 32}.claim").write_bytes(content) |
| 771 |
|
| 772 |
with pytest.raises(SoftFileLockProtocolError, match="malformed claim record"): |
| 773 |
StrictSoftFileLock(lock_path).acquire() |
| 774 |
|
| 775 |
|
| 776 |
def test_strict_soft_accepts_maximum_pid(tmp_path: Path) -> None: |
| 777 |
lock_path = tmp_path / "resource.lock" |
| 778 |
token = "0" * 32 |
| 779 |
claims = Path(f"{lock_path}.filelock") / "claims" |
| 780 |
claims.mkdir(parents=True) |
| 781 |
(claims / f"held-v1-{token}.claim").write_text( |
| 782 |
f"filelock-strict-v1\n{token}\n2147483647\n686f7374\n4242\n", |
| 783 |
encoding="ascii", |
| 784 |
newline="", |
| 785 |
) |
| 786 |
|
| 787 |
assert StrictSoftFileLock(lock_path).claims[0].pid == 2**31 - 1 |
| 788 |
|
| 789 |
|
| 790 |
@pytest.mark.parametrize( |
| 791 |
("pid", "hostname_hex"), |
| 792 |
[ |
| 793 |
pytest.param("01", "686f7374", id="leading-zero-pid"), |
| 794 |
pytest.param("2147483648", "686f7374", id="pid-above-signed-int"), |
| 795 |
pytest.param("1", "686F7374", id="uppercase-hostname-hex"), |
| 796 |
pytest.param("1", "20686f737420", id="spaced-hostname"), |
| 797 |
pytest.param("1", "686f737400", id="null-hostname"), |
| 798 |
pytest.param("1", "1b686f7374", id="escape-hostname"), |
| 799 |
], |
| 800 |
) |
| 801 |
def test_strict_soft_rejects_noncanonical_owner_record(tmp_path: Path, pid: str, hostname_hex: str) -> None: |
| 802 |
lock_path = tmp_path / "resource.lock" |
| 803 |
token = "0" * 32 |
| 804 |
claims = Path(f"{lock_path}.filelock") / "claims" |
| 805 |
claims.mkdir(parents=True) |
| 806 |
(claims / f"held-v1-{token}.claim").write_text( |
| 807 |
f"filelock-strict-v1\n{token}\n{pid}\n{hostname_hex}\n4242\n", |
| 808 |
encoding="ascii", |
| 809 |
newline="", |
| 810 |
) |
| 811 |
|
| 812 |
with pytest.raises(SoftFileLockProtocolError, match="malformed claim record"): |
| 813 |
_ = StrictSoftFileLock(lock_path).claims |
| 814 |
|
| 815 |
|
| 816 |
@pytest.mark.parametrize( |
| 817 |
"node", |
| 818 |
[ |
| 819 |
pytest.param("directory", id="non-regular"), |
| 820 |
pytest.param("oversized", id="oversized"), |
| 821 |
], |
| 822 |
) |
| 823 |
def test_strict_soft_invalid_record_node_fails_closed(tmp_path: Path, node: str) -> None: |
| 824 |
lock_path = tmp_path / "resource.lock" |
| 825 |
claims = Path(f"{lock_path}.filelock") / "claims" |
| 826 |
claims.mkdir(parents=True) |
| 827 |
claim = claims / f"held-v1-{'0' * 32}.claim" |
| 828 |
if node == "directory": |
| 829 |
claim.mkdir() |
| 830 |
else: |
| 831 |
claim.write_bytes(b"x" * 1025) |
| 832 |
|
| 833 |
with pytest.raises(SoftFileLockProtocolError, match="cannot read claim"): |
| 834 |
StrictSoftFileLock(lock_path).acquire() |
| 835 |
|
| 836 |
|
| 837 |
@pytest.mark.parametrize( |
| 838 |
("replacement", "message"), |
| 839 |
[ |
| 840 |
pytest.param("file", "changed while opening", id="different-file"), |
| 841 |
pytest.param("directory", "is not a regular file", id="directory"), |
| 842 |
], |
| 843 |
) |
| 844 |
def test_strict_soft_claim_replaced_while_opening_fails_closed( |
| 845 |
tmp_path: Path, mocker: MockerFixture, replacement: str, message: str |
| 846 |
) -> None: |
| 847 |
lock_path = tmp_path / "resource.lock" |
| 848 |
claims = Path(f"{lock_path}.filelock") / "claims" |
| 849 |
claims.mkdir(parents=True) |
| 850 |
claim = claims / f"held-v1-{'0' * 32}.claim" |
| 851 |
record = b"filelock-strict-v1\n" + b"0" * 32 + b"\n1\n686f7374\n" |
| 852 |
claim.write_bytes(record) |
| 853 |
real_open = os.open |
| 854 |
replaced = False |
| 855 |
|
| 856 |
def replace_before_open( |
| 857 |
path: _PathValue, |
| 858 |
flags: int, |
| 859 |
mode: int = 0o777, |
| 860 |
*, |
| 861 |
dir_fd: int | None = None, |
| 862 |
) -> int: |
| 863 |
nonlocal replaced |
| 864 |
if not replaced and os.fsdecode(path) == str(claim): |
| 865 |
replaced = True |
| 866 |
claim.replace(claim.with_name(f".{claim.name}.replaced")) |
| 867 |
if replacement == "file": |
| 868 |
claim.write_bytes(record) |
| 869 |
else: |
| 870 |
claim.mkdir() |
| 871 |
return real_open(path, flags, mode, dir_fd=dir_fd) |
| 872 |
|
| 873 |
mocker.patch("filelock._strict.os.open", side_effect=replace_before_open) |
| 874 |
|
| 875 |
with pytest.raises(SoftFileLockProtocolError, match=message): |
| 876 |
StrictSoftFileLock(lock_path).acquire() |
| 877 |
|
| 878 |
|
| 879 |
def _write_held_claim(claims: Path) -> Path: |
| 880 |
claims.mkdir(parents=True) |
| 881 |
claim = claims / f"held-v1-{'0' * 32}.claim" |
| 882 |
claim.write_bytes(b"filelock-strict-v1\n" + b"0" * 32 + b"\n1\n686f7374\n\n") |
| 883 |
return claim |
| 884 |
|
| 885 |
|
| 886 |
def _open_raising_for(claim: Path, error: OSError, mocker: MockerFixture) -> None: |
| 887 |
real_open = os.open |
| 888 |
|
| 889 |
def failing_open(path: _PathValue, flags: int, mode: int = 0o777, *, dir_fd: int | None = None) -> int: |
| 890 |
if os.fsdecode(path) == str(claim): |
| 891 |
raise error |
| 892 |
# The flows using this helper open only the single target claim, so the passthrough never runs. |
| 893 |
return real_open(path, flags, mode, dir_fd=dir_fd) # pragma: no cover |
| 894 |
|
| 895 |
mocker.patch("filelock._strict.os.open", side_effect=failing_open) |
| 896 |
|
| 897 |
|
| 898 |
def test_strict_soft_stale_claim_read_is_skipped(tmp_path: Path, mocker: MockerFixture) -> None: |
| 899 |
# An NFS peer that unlinks its own claim leaves this client's cached filehandle stale, so the open returns ESTALE |
| 900 |
# rather than ENOENT. A stale handle that outlives revalidation is a vanished claim, not an unreadable one. |
| 901 |
lock_path = tmp_path / "resource.lock" |
| 902 |
claim = _write_held_claim(Path(f"{lock_path}.filelock") / "claims") |
| 903 |
mocker.patch("filelock._strict._CLAIM_READ_GRACE", 0.02) |
| 904 |
_open_raising_for(claim, OSError(ESTALE, "Stale file handle"), mocker) |
| 905 |
|
| 906 |
assert StrictSoftFileLock(lock_path).claims == () |
| 907 |
|
| 908 |
|
| 909 |
def test_strict_soft_stale_claim_read_revalidates_to_gone(tmp_path: Path, mocker: MockerFixture) -> None: |
| 910 |
lock_path = tmp_path / "resource.lock" |
| 911 |
claim = _write_held_claim(Path(f"{lock_path}.filelock") / "claims") |
| 912 |
real_open = os.open |
| 913 |
stale_raised = False |
| 914 |
|
| 915 |
def stale_then_vanish(path: _PathValue, flags: int, mode: int = 0o777, *, dir_fd: int | None = None) -> int: |
| 916 |
nonlocal stale_raised |
| 917 |
if not stale_raised and os.fsdecode(path) == str(claim): |
| 918 |
stale_raised = True |
| 919 |
claim.unlink() |
| 920 |
raise OSError(ESTALE, "Stale file handle") |
| 921 |
# The retry re-lstats the vanished claim and fails there before reopening, so this passthrough never runs. |
| 922 |
return real_open(path, flags, mode, dir_fd=dir_fd) # pragma: no cover |
| 923 |
|
| 924 |
mocker.patch("filelock._strict.os.open", side_effect=stale_then_vanish) |
| 925 |
|
| 926 |
assert StrictSoftFileLock(lock_path).claims == () |
| 927 |
assert stale_raised |
| 928 |
|
| 929 |
|
| 930 |
def test_strict_soft_io_error_claim_read_fails_closed(tmp_path: Path, mocker: MockerFixture) -> None: |
| 931 |
lock_path = tmp_path / "resource.lock" |
| 932 |
claim = _write_held_claim(Path(f"{lock_path}.filelock") / "claims") |
| 933 |
_open_raising_for(claim, OSError(EIO, "I/O error"), mocker) |
| 934 |
|
| 935 |
with pytest.raises(SoftFileLockProtocolError, match="cannot read claim"): |
| 936 |
_ = StrictSoftFileLock(lock_path).claims |
| 937 |
|
| 938 |
|
| 939 |
def test_strict_soft_directory_inspection_error_fails_closed(tmp_path: Path, mocker: MockerFixture) -> None: |
| 940 |
real_mkdir = Path.mkdir |
| 941 |
|
| 942 |
def fail_protocol_mkdir(path: Path, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None: |
| 943 |
if str(path).endswith(".filelock"): |
| 944 |
raise FileExistsError |
| 945 |
real_mkdir(path, mode=mode, parents=parents, exist_ok=exist_ok) |
| 946 |
|
| 947 |
mocker.patch.object(Path, "mkdir", autospec=True, side_effect=fail_protocol_mkdir) |
| 948 |
mocker.patch.object(Path, "lstat", autospec=True, side_effect=PermissionError(EACCES, "cannot inspect")) |
| 949 |
|
| 950 |
with pytest.raises(SoftFileLockProtocolError, match="cannot inspect"): |
| 951 |
StrictSoftFileLock(tmp_path / "resource.lock").acquire() |
| 952 |
|
| 953 |
|
| 954 |
def _initialize_protocol(lock_path: Path) -> None: |
| 955 |
with StrictSoftFileLock(lock_path): |
| 956 |
pass |
| 957 |
|
| 958 |
|
| 959 |
def _private_claim_path(lock_path: Path, token: str) -> Path: |
| 960 |
return Path(f"{lock_path}.filelock") / "claims" / f".intent-v1-{token}.claim.private-v1-{token}.tmp" |
| 961 |
|
| 962 |
|
| 963 |
def _leaf_error_messages(error: BaseException) -> list[str]: # pragma: needs dir-fd |
| 964 |
if isinstance(error, BaseExceptionGroup): |
| 965 |
return [message for child in error.exceptions for message in _leaf_error_messages(child)] |
| 966 |
return [str(error)] |
| 967 |
|
| 968 |
|
| 969 |
@pytest.mark.parametrize( |
| 970 |
"error", |
| 971 |
[ |
| 972 |
pytest.param(OSError(EACCES, "denied"), id="oserror"), |
| 973 |
pytest.param(NotImplementedError("no follow_symlinks"), id="notimplemented"), |
| 974 |
pytest.param(ValueError("bad option"), id="valueerror"), |
| 975 |
], |
| 976 |
) |
| 977 |
def test_strict_soft_link_follow_probe_reports_unhonored(mocker: MockerFixture, error: Exception) -> None: |
| 978 |
mocker.patch("filelock._strict.os.link", side_effect=error) |
| 979 |
|
| 980 |
assert _probe_link_follow_symlinks() is False |
| 981 |
|
| 982 |
|
| 983 |
def test_strict_soft_sentinel_inspection_and_close_failure_group(tmp_path: Path, mocker: MockerFixture) -> None: |
| 984 |
lock_path = tmp_path / "resource.lock" |
| 985 |
_initialize_protocol(lock_path) |
| 986 |
real_fstat = os.fstat |
| 987 |
real_close = os.close |
| 988 |
real_open_sentinel = filelock._strict._open_sentinel |
| 989 |
sentinel_fd: int | None = None |
| 990 |
|
| 991 |
def capture_sentinel(path: Path) -> int | None: |
| 992 |
nonlocal sentinel_fd |
| 993 |
sentinel_fd = real_open_sentinel(path) |
| 994 |
return sentinel_fd |
| 995 |
|
| 996 |
# The record read inside _open_sentinel stats the same descriptor, but it runs before the capture above, so |
| 997 |
# keying on the descriptor still leaves _acquire's own inspection as the first stat to fail. |
| 998 |
def fail_sentinel_inspection(fd: int) -> os.stat_result: |
| 999 |
if fd == sentinel_fd: |
| 1000 |
raise OSError(EIO, "sentinel inspection failed") |
| 1001 |
return real_fstat(fd) |
| 1002 |
|
| 1003 |
def fail_sentinel_close(fd: int) -> None: |
| 1004 |
if fd == sentinel_fd: |
| 1005 |
raise OSError(EIO, "sentinel close failed") |
| 1006 |
# Only the sentinel descriptor is closed in this flow, so the passthrough never runs. |
| 1007 |
real_close(fd) # pragma: no cover |
| 1008 |
|
| 1009 |
mocker.patch("filelock._strict._open_sentinel", side_effect=capture_sentinel) |
| 1010 |
mocker.patch("filelock._strict.os.fstat", side_effect=fail_sentinel_inspection) |
| 1011 |
mocker.patch("filelock._strict.os.close", side_effect=fail_sentinel_close) |
| 1012 |
lock = StrictSoftFileLock(lock_path) |
| 1013 |
|
| 1014 |
with pytest.raises(BaseExceptionGroup) as raised: |
| 1015 |
lock.acquire() |
| 1016 |
assert ([str(error) for error in raised.value.exceptions], lock.is_locked) == ( |
| 1017 |
["[Errno 5] sentinel inspection failed", "[Errno 5] sentinel close failed"], |
| 1018 |
False, |
| 1019 |
) |
| 1020 |
|
| 1021 |
|
| 1022 |
@_NEEDS_DIR_FD # pragma: needs dir-fd |
| 1023 |
@pytest.mark.parametrize("initialized", [pytest.param(False, id="sentinel"), pytest.param(True, id="intent")]) |
| 1024 |
def test_strict_soft_publication_directory_close_failure( |
| 1025 |
tmp_path: Path, mocker: MockerFixture, initialized: bool |
| 1026 |
) -> None: |
| 1027 |
lock_path = tmp_path / "resource.lock" |
| 1028 |
if initialized: |
| 1029 |
_initialize_protocol(lock_path) |
| 1030 |
real_close = os.close |
| 1031 |
real_fstat = os.fstat |
| 1032 |
closed = False |
| 1033 |
|
| 1034 |
def fail_first_directory_close(fd: int) -> None: |
| 1035 |
nonlocal closed |
| 1036 |
is_directory = stat.S_ISDIR(real_fstat(fd).st_mode) |
| 1037 |
real_close(fd) |
| 1038 |
if is_directory and not closed: |
| 1039 |
closed = True |
| 1040 |
raise OSError(EIO, "publication directory close failed") |
| 1041 |
|
| 1042 |
mocker.patch("filelock._strict.os.close", side_effect=fail_first_directory_close) |
| 1043 |
lock = StrictSoftFileLock(lock_path, timeout=0) |
| 1044 |
|
| 1045 |
with pytest.raises(OSError, match="publication directory close failed"): |
| 1046 |
lock.acquire() |
| 1047 |
assert lock.is_locked is False |
| 1048 |
|
| 1049 |
|
| 1050 |
@_NEEDS_DIR_FD # pragma: needs dir-fd |
| 1051 |
def test_strict_soft_force_break_directory_close_failure(tmp_path: Path, mocker: MockerFixture) -> None: |
| 1052 |
lock_path = tmp_path / "resource.lock" |
| 1053 |
lock = StrictSoftFileLock(lock_path) |
| 1054 |
lock.acquire() |
| 1055 |
claim_name = lock.claims[0].name |
| 1056 |
real_close = os.close |
| 1057 |
real_fstat = os.fstat |
| 1058 |
closed = False |
| 1059 |
|
| 1060 |
def fail_directory_close(fd: int) -> None: |
| 1061 |
nonlocal closed |
| 1062 |
is_directory = stat.S_ISDIR(real_fstat(fd).st_mode) |
| 1063 |
real_close(fd) |
| 1064 |
if is_directory and not closed: |
| 1065 |
closed = True |
| 1066 |
raise OSError(EIO, "force break directory close failed") |
| 1067 |
|
| 1068 |
mocker.patch("filelock._strict.os.close", side_effect=fail_directory_close) |
| 1069 |
|
| 1070 |
with pytest.raises(OSError, match="force break directory close failed"): |
| 1071 |
lock.force_break(claim_name) |
| 1072 |
lock.release() |
| 1073 |
assert (lock.is_locked, lock.claims) == (False, ()) |
| 1074 |
|
| 1075 |
|
| 1076 |
def test_strict_soft_release_sentinel_close_failure(tmp_path: Path, mocker: MockerFixture) -> None: |
| 1077 |
lock_path = tmp_path / "resource.lock" |
| 1078 |
lock = StrictSoftFileLock(lock_path) |
| 1079 |
lock.acquire() |
| 1080 |
sentinel_fd = lock._context.lock_file_fd |
| 1081 |
real_close = os.close |
| 1082 |
|
| 1083 |
def fail_sentinel_close(fd: int) -> None: |
| 1084 |
if fd == sentinel_fd: |
| 1085 |
raise OSError(EIO, "sentinel close failed") |
| 1086 |
# Only posix release closes a second, non-sentinel descriptor (the dir_fd); win32 closes only the sentinel. |
| 1087 |
real_close(fd) # pragma: needs dir-fd |
| 1088 |
|
| 1089 |
mocker.patch("filelock._strict.os.close", side_effect=fail_sentinel_close) |
| 1090 |
|
| 1091 |
with pytest.raises(OSError, match="sentinel close failed"): |
| 1092 |
lock.release() |
| 1093 |
assert (lock.is_locked, lock.claims) == (False, ()) |
| 1094 |
|
| 1095 |
|
| 1096 |
def test_strict_soft_discard_sentinel_close_failure(tmp_path: Path, mocker: MockerFixture) -> None: |
| 1097 |
lock_path = tmp_path / "resource.lock" |
| 1098 |
_initialize_protocol(lock_path) |
| 1099 |
_write_foreign_claim(Path(f"{lock_path}.filelock") / "claims", "a" * 32) |
| 1100 |
real_close = os.close |
| 1101 |
closes = 0 |
| 1102 |
|
| 1103 |
def fail_second_close(fd: int) -> None: |
| 1104 |
nonlocal closes |
| 1105 |
closes += 1 |
| 1106 |
if closes == 2: |
| 1107 |
raise OSError(EIO, "doorway sentinel close failed") |
| 1108 |
real_close(fd) |
| 1109 |
|
| 1110 |
mocker.patch("filelock._strict.os.close", side_effect=fail_second_close) |
| 1111 |
lock = StrictSoftFileLock(lock_path) |
| 1112 |
|
| 1113 |
with pytest.raises(OSError, match="doorway sentinel close failed"): |
| 1114 |
lock.acquire() |
| 1115 |
assert (lock.is_locked, [claim.state for claim in lock.claims]) == (False, ["held"]) |
| 1116 |
|
| 1117 |
|
| 1118 |
@pytest.mark.parametrize("initialized", [pytest.param(False, id="sentinel"), pytest.param(True, id="intent")]) |
| 1119 |
def test_strict_soft_publication_record_replaced_aborts( |
| 1120 |
tmp_path: Path, mocker: MockerFixture, initialized: bool |
| 1121 |
) -> None: |
| 1122 |
lock_path = tmp_path / "resource.lock" |
| 1123 |
if initialized: |
| 1124 |
_initialize_protocol(lock_path) |
| 1125 |
real_identity = _relative_identity |
| 1126 |
|
| 1127 |
def mismatch_public(directory_ref: tuple[str, int | None], name: str) -> tuple[int, int] | None: |
| 1128 |
identity = real_identity(directory_ref, name) |
| 1129 |
if identity is not None and not name.startswith("."): |
| 1130 |
return identity[0], identity[1] + 1 |
| 1131 |
return identity |
| 1132 |
|
| 1133 |
mocker.patch("filelock._strict._relative_identity", side_effect=mismatch_public) |
| 1134 |
lock = StrictSoftFileLock(lock_path, timeout=0) |
| 1135 |
|
| 1136 |
with pytest.raises(Timeout): |
| 1137 |
lock.acquire() |
| 1138 |
assert lock.is_locked is False |
| 1139 |
|
| 1140 |
|
| 1141 |
def test_strict_soft_publication_record_reclaimed_aborts(tmp_path: Path, mocker: MockerFixture) -> None: |
| 1142 |
lock_path = tmp_path / "resource.lock" |
| 1143 |
_initialize_protocol(lock_path) |
| 1144 |
real_identity = _relative_identity |
| 1145 |
|
| 1146 |
def source_gone(directory_ref: tuple[str, int | None], name: str) -> tuple[int, int] | None: |
| 1147 |
if name.startswith("."): |
| 1148 |
return None |
| 1149 |
# Only the dot-prefixed private record is inspected in this flow, so this passthrough never runs. |
| 1150 |
return real_identity(directory_ref, name) # pragma: no cover |
| 1151 |
|
| 1152 |
mocker.patch("filelock._strict._relative_identity", side_effect=source_gone) |
| 1153 |
mocker.patch("filelock._strict._link_relative", side_effect=FileNotFoundError(ENOENT, "source vanished")) |
| 1154 |
lock = StrictSoftFileLock(lock_path, timeout=0) |
| 1155 |
|
| 1156 |
with pytest.raises(Timeout): |
| 1157 |
lock.acquire() |
| 1158 |
assert lock.is_locked is False |
| 1159 |
|
| 1160 |
|
| 1161 |
def test_strict_soft_private_inspection_failure_unlinks_vanished_record(tmp_path: Path, mocker: MockerFixture) -> None: |
| 1162 |
lock_path = tmp_path / "resource.lock" |
| 1163 |
_initialize_protocol(lock_path) |
| 1164 |
real_fstat = os.fstat |
| 1165 |
fstats = 0 |
| 1166 |
|
| 1167 |
def fail_private_inspection(fd: int) -> os.stat_result: |
| 1168 |
nonlocal fstats |
| 1169 |
fstats += 1 |
| 1170 |
if fstats == 3: |
| 1171 |
raise OSError(EIO, "private inspection failed") |
| 1172 |
return real_fstat(fd) |
| 1173 |
|
| 1174 |
mocker.patch("filelock._strict.os.fstat", side_effect=fail_private_inspection) |
| 1175 |
mocker.patch("filelock._strict._unlink_relative", side_effect=FileNotFoundError(ENOENT, "record gone")) |
| 1176 |
lock = StrictSoftFileLock(lock_path) |
| 1177 |
|
| 1178 |
with pytest.raises(OSError, match="private inspection failed"): |
| 1179 |
lock.acquire() |
| 1180 |
assert lock.is_locked is False |
| 1181 |
|
| 1182 |
|
| 1183 |
def test_strict_soft_private_record_reclaimed_after_close_is_tolerated(tmp_path: Path, mocker: MockerFixture) -> None: |
| 1184 |
lock_path = tmp_path / "resource.lock" |
| 1185 |
_initialize_protocol(lock_path) |
| 1186 |
real_close = os.close |
| 1187 |
real_open_relative = filelock._strict._open_relative |
| 1188 |
private_records: dict[int, Path] = {} |
| 1189 |
|
| 1190 |
def capture_private_record(directory_ref: tuple[str, int | None], name: str, flags: int, mode: int) -> int: |
| 1191 |
fd = real_open_relative(directory_ref, name, flags, mode) |
| 1192 |
private_records[fd] = Path(directory_ref[0], name) |
| 1193 |
return fd |
| 1194 |
|
| 1195 |
def reclaim_on_close(fd: int) -> None: |
| 1196 |
real_close(fd) |
| 1197 |
if (record := private_records.pop(fd, None)) is not None: |
| 1198 |
record.unlink() |
| 1199 |
|
| 1200 |
mocker.patch("filelock._strict._open_relative", side_effect=capture_private_record) |
| 1201 |
mocker.patch("filelock._strict.os.close", side_effect=reclaim_on_close) |
| 1202 |
lock = StrictSoftFileLock(lock_path, timeout=0) |
| 1203 |
|
| 1204 |
lock.acquire() |
| 1205 |
assert lock.is_locked is True |
| 1206 |
lock.release() |
| 1207 |
assert lock.is_locked is False |
| 1208 |
|
| 1209 |
|
| 1210 |
def test_strict_soft_record_finalization_close_and_unlink_failures_group(tmp_path: Path, mocker: MockerFixture) -> None: |
| 1211 |
lock_path = tmp_path / "resource.lock" |
| 1212 |
_initialize_protocol(lock_path) |
| 1213 |
real_close = os.close |
| 1214 |
real_open_relative = filelock._strict._open_relative |
| 1215 |
private_fd: int | None = None |
| 1216 |
|
| 1217 |
def capture_private_record(directory_ref: tuple[str, int | None], name: str, flags: int, mode: int) -> int: |
| 1218 |
nonlocal private_fd |
| 1219 |
private_fd = real_open_relative(directory_ref, name, flags, mode) |
| 1220 |
return private_fd |
| 1221 |
|
| 1222 |
def fail_private_close(fd: int) -> None: |
| 1223 |
real_close(fd) |
| 1224 |
if fd == private_fd: |
| 1225 |
raise OSError(EIO, "private close failed") |
| 1226 |
|
| 1227 |
mocker.patch("filelock._strict._open_relative", side_effect=capture_private_record) |
| 1228 |
mocker.patch("filelock._strict.os.close", side_effect=fail_private_close) |
| 1229 |
mocker.patch("filelock._strict._unlink_relative", side_effect=PermissionError(EACCES, "unlink denied")) |
| 1230 |
lock = StrictSoftFileLock(lock_path) |
| 1231 |
|
| 1232 |
with pytest.raises(BaseExceptionGroup) as raised: |
| 1233 |
lock.acquire() |
| 1234 |
assert (sorted(str(error) for error in raised.value.exceptions), lock.is_locked) == ( |
| 1235 |
["[Errno 13] unlink denied", "[Errno 5] private close failed"], |
| 1236 |
False, |
| 1237 |
) |
| 1238 |
|
| 1239 |
|
| 1240 |
def test_strict_soft_release_claim_unlink_failures_group(tmp_path: Path, mocker: MockerFixture) -> None: |
| 1241 |
lock_path = tmp_path / "resource.lock" |
| 1242 |
lock = StrictSoftFileLock(lock_path) |
| 1243 |
lock.acquire() |
| 1244 |
unlink_mock = mocker.patch( |
| 1245 |
"filelock._strict._unlink_in_directory", |
| 1246 |
side_effect=PermissionError(EACCES, "claim unlink denied"), |
| 1247 |
) |
| 1248 |
|
| 1249 |
with pytest.raises(BaseExceptionGroup) as raised: |
| 1250 |
lock.release() |
| 1251 |
assert ([str(error) for error in raised.value.exceptions], lock.is_locked, len(lock.claims)) == ( |
| 1252 |
["[Errno 13] claim unlink denied", "[Errno 13] claim unlink denied"], |
| 1253 |
True, |
| 1254 |
2, |
| 1255 |
) |
| 1256 |
|
| 1257 |
mocker.stop(unlink_mock) |
| 1258 |
lock.release() |
| 1259 |
assert (lock.is_locked, lock.claims) == (False, ()) |
| 1260 |
|
| 1261 |
|
| 1262 |
def test_strict_soft_doorway_claim_unlink_failure_commits_owned(tmp_path: Path, mocker: MockerFixture) -> None: |
| 1263 |
lock_path = tmp_path / "resource.lock" |
| 1264 |
_initialize_protocol(lock_path) |
| 1265 |
owner_token = "f" * 32 |
| 1266 |
competitor_name = f"held-v1-{'0' * 32}.claim" |
| 1267 |
intent_name = f"intent-v1-{owner_token}.claim" |
| 1268 |
real_scandir = os.scandir |
| 1269 |
injected = False |
| 1270 |
|
| 1271 |
def add_competitor_once_intent_is_published(path: str | os.PathLike[str]) -> Iterator[os.DirEntry[str]]: |
| 1272 |
# Key on directory content, not scandir call count: the setup and publication paths scan a differing number |
| 1273 |
# of times per platform, so plant the held competitor on the first rescan that already lists our own intent. |
| 1274 |
nonlocal injected |
| 1275 |
directory = Path(os.fsdecode(path)) |
| 1276 |
if not injected: |
| 1277 |
with real_scandir(directory) as entries: |
| 1278 |
intent_published = any(entry.name == intent_name for entry in entries) |
| 1279 |
if intent_published: |
| 1280 |
_write_foreign_claim(directory, "0" * 32) |
| 1281 |
injected = True |
| 1282 |
return real_scandir(directory) |
| 1283 |
|
| 1284 |
real_unlink_in_directory = filelock._strict._unlink_in_directory |
| 1285 |
|
| 1286 |
def deny_only_the_owned_intent_unlink(directory: Path, name: str) -> BaseException | None: |
| 1287 |
# Fail only the doorway's own intent-claim unlink. A blanket failure also breaks the Windows-only private |
| 1288 |
# record cleanup inside publication (_unlink_relative unlinks a differently named private file there), firing |
| 1289 |
# the fault before the doorway ever discards and masking the commit-owned path this test targets. |
| 1290 |
if name == intent_name: |
| 1291 |
raise PermissionError(EACCES, "intent unlink denied") |
| 1292 |
return real_unlink_in_directory(directory, name) # pragma: lacks dir-fd |
| 1293 |
|
| 1294 |
mocker.patch("filelock._strict.secrets.token_hex", return_value=owner_token) |
| 1295 |
scandir_mock = mocker.patch("filelock._strict.os.scandir", side_effect=add_competitor_once_intent_is_published) |
| 1296 |
unlink_mock = mocker.patch("filelock._strict._unlink_in_directory", side_effect=deny_only_the_owned_intent_unlink) |
| 1297 |
lock = StrictSoftFileLock(lock_path) |
| 1298 |
|
| 1299 |
with pytest.raises(PermissionError, match="intent unlink denied"): |
| 1300 |
lock.acquire() |
| 1301 |
assert (lock.is_locked, sorted(claim.name for claim in lock.claims)) == ( |
| 1302 |
True, |
| 1303 |
[competitor_name, f"intent-v1-{owner_token}.claim"], |
| 1304 |
) |
| 1305 |
|
| 1306 |
mocker.stop(scandir_mock) |
| 1307 |
mocker.stop(unlink_mock) |
| 1308 |
lock.release(force=True) |
| 1309 |
lock.force_break(competitor_name) |
| 1310 |
|
| 1311 |
|
| 1312 |
def test_strict_soft_permission_denied_claim_read_fails_closed(tmp_path: Path, mocker: MockerFixture) -> None: |
| 1313 |
lock_path = tmp_path / "resource.lock" |
| 1314 |
claim = _write_held_claim(Path(f"{lock_path}.filelock") / "claims") |
| 1315 |
mocker.patch("filelock._strict._CLAIM_READ_GRACE", 0.02) |
| 1316 |
_open_raising_for(claim, PermissionError(EACCES, "sharing violation"), mocker) |
| 1317 |
|
| 1318 |
with pytest.raises(SoftFileLockProtocolError, match="cannot read claim"): |
| 1319 |
_ = StrictSoftFileLock(lock_path).claims |
| 1320 |
|
| 1321 |
|
| 1322 |
def test_strict_soft_claim_read_retries_after_a_slow_denied_attempt(tmp_path: Path, mocker: MockerFixture) -> None: |
| 1323 |
# The grace window opens at the first pending result, so a first attempt that itself outlasts the window still |
| 1324 |
# gets a retry rather than failing closed on a transient denial. |
| 1325 |
lock_path = tmp_path / "resource.lock" |
| 1326 |
claim = _write_held_claim(Path(f"{lock_path}.filelock") / "claims") |
| 1327 |
mocker.patch("filelock._strict._CLAIM_READ_GRACE", 0.02) |
| 1328 |
real_open = os.open |
| 1329 |
denied = False |
| 1330 |
|
| 1331 |
def deny_slowly_once(path: _PathValue, flags: int, mode: int = 0o777, *, dir_fd: int | None = None) -> int: |
| 1332 |
nonlocal denied |
| 1333 |
if not denied and os.fsdecode(path) == str(claim): |
| 1334 |
denied = True |
| 1335 |
time.sleep(0.05) |
| 1336 |
raise PermissionError(EACCES, "sharing violation") |
| 1337 |
return real_open(path, flags, mode, dir_fd=dir_fd) |
| 1338 |
|
| 1339 |
mocker.patch("filelock._strict.os.open", side_effect=deny_slowly_once) |
| 1340 |
|
| 1341 |
assert ([found.name for found in StrictSoftFileLock(lock_path).claims], denied) == ([claim.name], True) |
| 1342 |
|
| 1343 |
|
| 1344 |
def test_strict_soft_ignores_malformed_private_record_name(tmp_path: Path) -> None: |
| 1345 |
lock_path = tmp_path / "resource.lock" |
| 1346 |
claims = Path(f"{lock_path}.filelock") / "claims" |
| 1347 |
claims.mkdir(parents=True) |
| 1348 |
(claims / ".decoy.tmp").write_bytes(b"junk") |
| 1349 |
|
| 1350 |
assert StrictSoftFileLock(lock_path).claims == () |
| 1351 |
|
| 1352 |
|
| 1353 |
def test_strict_soft_record_read_and_close_failure_group(tmp_path: Path, mocker: MockerFixture) -> None: |
| 1354 |
lock_path = tmp_path / "resource.lock" |
| 1355 |
claims = Path(f"{lock_path}.filelock") / "claims" |
| 1356 |
claims.mkdir(parents=True) |
| 1357 |
(claims / f"held-v1-{'0' * 32}.claim").write_bytes(b"x" * 1025) |
| 1358 |
real_close = os.close |
| 1359 |
|
| 1360 |
def fail_close(fd: int) -> None: |
| 1361 |
# Reading the single oversized claim closes exactly one descriptor, so failing every close still fails once. |
| 1362 |
real_close(fd) |
| 1363 |
raise OSError(EIO, "record close failed") |
| 1364 |
|
| 1365 |
mocker.patch("filelock._strict.os.close", side_effect=fail_close) |
| 1366 |
|
| 1367 |
with pytest.raises(BaseExceptionGroup) as raised: |
| 1368 |
_ = StrictSoftFileLock(lock_path).claims |
| 1369 |
messages = [str(error) for error in raised.value.exceptions] |
| 1370 |
assert ( |
| 1371 |
any("exceeds 1024 bytes" in message for message in messages), |
| 1372 |
"[Errno 5] record close failed" in messages, |
| 1373 |
) == ( |
| 1374 |
True, |
| 1375 |
True, |
| 1376 |
) |
| 1377 |
|
| 1378 |
|
| 1379 |
def test_strict_soft_acquires_without_dir_fd(tmp_path: Path, mocker: MockerFixture) -> None: |
| 1380 |
lock_path = tmp_path / "resource.lock" |
| 1381 |
mocker.patch("filelock._strict._OPEN_SUPPORTS_DIR_FD", new=False) |
| 1382 |
mocker.patch("filelock._strict._UNLINK_SUPPORTS_DIR_FD", new=False) |
| 1383 |
mocker.patch("filelock._strict._STAT_SUPPORTS_DIR_FD", new=False) |
| 1384 |
mocker.patch("filelock._strict._LINK_SUPPORTS_DIR_FD", new=False) |
| 1385 |
|
| 1386 |
with StrictSoftFileLock(lock_path) as lock: |
| 1387 |
assert (lock.is_locked, [claim.state for claim in lock.claims]) == (True, ["held", "intent"]) |
| 1388 |
assert StrictSoftFileLock(lock_path).claims == () |
| 1389 |
|
| 1390 |
|
| 1391 |
@_NEEDS_DIR_FD # pragma: needs dir-fd |
| 1392 |
@_NEEDS_LINK_DIR_FD # pragma: needs link-dir-fd |
| 1393 |
def test_strict_soft_held_link_and_directory_close_failure(tmp_path: Path, mocker: MockerFixture) -> None: |
| 1394 |
lock_path = tmp_path / "resource.lock" |
| 1395 |
_initialize_protocol(lock_path) |
| 1396 |
real_close = os.close |
| 1397 |
real_fstat = os.fstat |
| 1398 |
real_link = os.link |
| 1399 |
held_failed = False |
| 1400 |
directory_closed = False |
| 1401 |
|
| 1402 |
def fail_held_link( |
| 1403 |
source: _PathValue, |
| 1404 |
destination: _PathValue, |
| 1405 |
*, |
| 1406 |
src_dir_fd: int | None = None, |
| 1407 |
dst_dir_fd: int | None = None, |
| 1408 |
follow_symlinks: bool = True, |
| 1409 |
) -> None: |
| 1410 |
nonlocal held_failed |
| 1411 |
if Path(os.fsdecode(destination)).name.startswith("held-"): |
| 1412 |
held_failed = True |
| 1413 |
raise OSError(EIO, "held link failed") |
| 1414 |
real_link(source, destination, src_dir_fd=src_dir_fd, dst_dir_fd=dst_dir_fd, follow_symlinks=follow_symlinks) |
| 1415 |
|
| 1416 |
def fail_directory_close_after_held(fd: int) -> None: |
| 1417 |
nonlocal directory_closed |
| 1418 |
is_directory = stat.S_ISDIR(real_fstat(fd).st_mode) |
| 1419 |
real_close(fd) |
| 1420 |
if is_directory and held_failed and not directory_closed: |
| 1421 |
directory_closed = True |
| 1422 |
raise OSError(EIO, "held link directory close failed") |
| 1423 |
|
| 1424 |
mocker.patch("filelock._strict.os.link", side_effect=fail_held_link) |
| 1425 |
mocker.patch("filelock._strict.os.close", side_effect=fail_directory_close_after_held) |
| 1426 |
lock = StrictSoftFileLock(lock_path) |
| 1427 |
|
| 1428 |
with pytest.raises(BaseExceptionGroup) as raised: |
| 1429 |
lock.acquire() |
| 1430 |
assert ([str(error) for error in raised.value.exceptions], lock.is_locked, lock.claims) == ( |
| 1431 |
["[Errno 5] held link failed", "[Errno 5] held link directory close failed"], |
| 1432 |
False, |
| 1433 |
(), |
| 1434 |
) |
| 1435 |
|
| 1436 |
|
| 1437 |
def test_strict_soft_opened_record_non_regular_fails_closed(tmp_path: Path, mocker: MockerFixture) -> None: |
| 1438 |
lock_path = tmp_path / "resource.lock" |
| 1439 |
claims = Path(f"{lock_path}.filelock") / "claims" |
| 1440 |
claims.mkdir(parents=True) |
| 1441 |
(claims / f"held-v1-{'0' * 32}.claim").write_bytes(b"filelock-strict-v1\n" + b"0" * 32 + b"\n1\n686f7374\n4242\n") |
| 1442 |
real_fstat = os.fstat |
| 1443 |
|
| 1444 |
def non_regular_fstat(fd: int) -> os.stat_result: |
| 1445 |
original = real_fstat(fd) |
| 1446 |
return os.stat_result((stat.S_IFIFO | 0o644, *original[1:])) |
| 1447 |
|
| 1448 |
mocker.patch("filelock._strict.os.fstat", side_effect=non_regular_fstat) |
| 1449 |
|
| 1450 |
with pytest.raises(SoftFileLockProtocolError, match="is not a regular file"): |
| 1451 |
_ = StrictSoftFileLock(lock_path).claims |
| 1452 |
|
| 1453 |
|
| 1454 |
def _write_foreign_claim(claims: Path, token: str, state: str = "held") -> Path: |
| 1455 |
claim = claims / f"{state}-v1-{token}.claim" |
| 1456 |
claim.write_bytes(b"filelock-strict-v1\n" + token.encode() + f"\n{os.getpid()}\n686f7374\n4242\n".encode()) |
| 1457 |
return claim |