Debian Codegraph @

tests/test_soft_lease.py

raw
1 from __future__ import annotations
2
3 import itertools
4 import os
5 import socket
6 import time
7 from contextlib import suppress
8 from errno import EIO, ENOENT
9 from threading import Thread
10 from types import SimpleNamespace
11 from typing import TYPE_CHECKING, cast
12
13 import pytest
14
15 from filelock import (
16 FileLock,
17 LeaseCompromise,
18 LeaseSettingsMismatch,
19 SoftFileLease,
20 StrictSoftFileLock,
21 Timeout,
22 )
23 from tests.capability_marks import NEEDS_UNLINK_OPEN_FILE
24
25 if TYPE_CHECKING:
26 from collections.abc import Callable
27 from pathlib import Path
28
29 from pytest_mock import MockerFixture
30
31 #: Short enough to keep the suite quick, long enough that a loaded runner still refreshes twice before expiry.
32 _DURATION: float = 0.9
33 _HEARTBEAT: float = 0.1
34
35 #: Taking a claim from a live holder means removing its marker while the holder still has it open. Where that is
36 #: refused, a lease only reclaims once the holder exits and its handle closes.
37
38
39 @pytest.fixture
40 def marker(tmp_path: Path) -> Path:
41 return tmp_path / "a.lock"
42
43
44 def _lease(
45 marker: Path,
46 *,
47 lease_duration: float = _DURATION,
48 timeout: float = 0.3,
49 on_compromise: Callable[[LeaseCompromise], None] | None = None,
50 ) -> SoftFileLease:
51 return SoftFileLease(
52 str(marker),
53 timeout=timeout,
54 lease_duration=lease_duration,
55 heartbeat_interval=_HEARTBEAT,
56 on_compromise=on_compromise,
57 )
58
59
60 def test_lease_publishes_its_claim(marker: Path) -> None:
61 lease = _lease(marker)
62
63 with lease:
64 owner = lease.owner
65 assert owner is not None
66 assert (owner.pid, owner.hostname, owner.mode, owner.lease_duration) == (
67 os.getpid(),
68 socket.gethostname(),
69 "lease",
70 _DURATION,
71 )
72 assert owner.token == lease.token
73
74
75 def test_lease_token_names_the_claim_only_while_held(marker: Path) -> None:
76 lease = _lease(marker)
77
78 with lease:
79 held = lease.token
80
81 assert held is not None
82 assert lease.token is None
83
84
85 def test_lease_token_names_no_claim_after_a_contended_acquire(marker: Path) -> None:
86 contender = _lease(marker, timeout=0)
87
88 with _lease(marker):
89 with pytest.raises(Timeout):
90 contender.acquire()
91 assert contender.token is None
92
93
94 def test_lease_token_names_no_claim_after_an_acquire_that_raises(tmp_path: Path) -> None:
95 # The one path no rollback covers: a raise before the acquire holds a descriptor.
96 (blocker := tmp_path / "blocker").touch()
97 lease = _lease(blocker / "resource.lock")
98
99 with pytest.raises(FileExistsError):
100 lease.acquire()
101
102 assert lease.token is None
103
104
105 def test_lease_heartbeat_keeps_a_live_claim_past_its_duration(marker: Path) -> None:
106 holder = _lease(marker)
107
108 with holder:
109 time.sleep(_DURATION * 1.5) # only a refreshing heartbeat keeps the claim past this
110 with pytest.raises(Timeout):
111 _lease(marker).acquire()
112
113
114 @NEEDS_UNLINK_OPEN_FILE # pragma: needs unlink-open-file
115 def test_lease_peer_takes_an_expired_claim(marker: Path, mocker: MockerFixture) -> None:
116 # A wedged holder: its marker stays on disk, but no refresh ever lands on it again, so the claim ages out.
117 mocker.patch("filelock._lease.touch")
118 holder = _lease(marker)
119 holder.acquire()
120
121 try:
122 peer = _lease(marker, timeout=_DURATION * 5)
123 with peer:
124 assert peer.is_lock_held_by_us
125 assert peer.token != holder.token
126 finally:
127 holder.release()
128
129
130 def test_lease_self_heals_a_malformed_marker(marker: Path) -> None:
131 # A partial write or a foreign file leaves a marker the lease parser cannot read. Rather than block every
132 # contender until timeout, the base self-heal evicts it once it ages past the malformed grace window.
133 marker.write_text("not a protocol 2 record\n", encoding="utf-8")
134 os.utime(marker, (0, 0))
135
136 with _lease(marker) as lease:
137 assert lease.is_lock_held_by_us
138
139
140 def test_lease_reclaims_a_dead_same_host_holder(marker: Path) -> None:
141 marker.write_text(
142 f"filelock/2\npid=999999\nhost={socket.gethostname()}\nmode=lease\ntoken=abc\nduration={_DURATION!r}\n",
143 encoding="utf-8",
144 )
145
146 with _lease(marker) as lease:
147 assert lease.is_lock_held_by_us
148
149
150 @NEEDS_UNLINK_OPEN_FILE
151 def test_lease_reports_compromise_when_the_marker_vanishes(marker: Path) -> None: # pragma: needs unlink-open-file
152 seen: list[LeaseCompromise] = []
153 lease = _lease(marker, on_compromise=seen.append)
154
155 with lease:
156 token = lease.token
157 marker.unlink()
158 time.sleep(_HEARTBEAT * 5)
159
160 assert [(c.reason, c.token, c.lock_file) for c in seen] == [("marker-missing", token, str(marker))]
161
162
163 @NEEDS_UNLINK_OPEN_FILE
164 def test_lease_reports_compromise_when_a_peer_takes_over(marker: Path) -> None: # pragma: needs unlink-open-file
165 seen: list[LeaseCompromise] = []
166 holder = _lease(marker, on_compromise=seen.append)
167 peer = _lease(marker)
168
169 try:
170 with holder:
171 marker.unlink()
172 peer.acquire() # a peer publishes a fresh marker at the same path
173 time.sleep(_HEARTBEAT * 5)
174 assert [c.reason for c in seen] == ["owner-changed"]
175 finally:
176 peer.release() # stop the peer's heartbeat here, so its release log never lands in a later test's caplog
177
178
179 def test_lease_reports_compromise_when_a_refresh_fails(marker: Path, mocker: MockerFixture) -> None:
180 seen: list[LeaseCompromise] = []
181 failure = OSError("cannot touch the marker")
182 mocker.patch("filelock._lease.touch", side_effect=failure)
183 lease = _lease(marker, on_compromise=seen.append)
184
185 with lease:
186 # A starved heartbeat can miss one refresh margin; the failure is deduplicated, so it still reports once.
187 deadline = time.monotonic() + _DURATION * 20
188 while not seen and time.monotonic() < deadline:
189 time.sleep(_HEARTBEAT)
190
191 assert [(c.reason, c.error) for c in seen] == [("refresh-failed", failure)]
192
193
194 @pytest.mark.parametrize("target", [pytest.param("touch", id="touch"), pytest.param("os.lstat", id="lstat")])
195 def test_lease_tolerates_a_transient_refresh_error(marker: Path, mocker: MockerFixture, target: str) -> None:
196 # A transient ESTALE/EIO on the refresh path that recovers before the lease could lapse must not raise a
197 # compromise: the marker was ours last tick, so retry rather than tell the holder to abandon its work.
198 import filelock._lease as lease_mod
199
200 ticks = itertools.count()
201 real = cast("Callable[..., object]", lease_mod.touch if target == "touch" else os.lstat)
202
203 def flaky(path: str, *args: object, **kwargs: object) -> object:
204 if path.endswith(marker.name) and next(ticks) < 2:
205 raise OSError(EIO, "Input/output error")
206 return real(path, *args, **kwargs)
207
208 mocker.patch(f"filelock._lease.{target}", side_effect=flaky)
209 seen: list[LeaseCompromise] = []
210 lease = _lease(marker, on_compromise=seen.append)
211 with lease:
212 time.sleep(_HEARTBEAT * 6) # several ticks: the first two fail, the rest recover
213 assert seen == []
214 assert lease.compromise is None
215
216
217 @NEEDS_UNLINK_OPEN_FILE
218 def test_lease_reports_one_compromise_per_claim(marker: Path) -> None: # pragma: needs unlink-open-file
219 seen: list[LeaseCompromise] = []
220 lease = _lease(marker, on_compromise=seen.append)
221
222 with lease:
223 marker.unlink()
224 time.sleep(_HEARTBEAT * 6) # several refreshes fail, but the holder is told once
225
226 assert len(seen) == 1
227
228
229 @NEEDS_UNLINK_OPEN_FILE
230 def test_lease_records_the_compromise_without_a_callback(marker: Path) -> None: # pragma: needs unlink-open-file
231 lease = _lease(marker)
232
233 with lease:
234 marker.unlink()
235 time.sleep(_HEARTBEAT * 5)
236 compromise = lease.compromise
237
238 assert compromise is not None
239 assert compromise.reason == "marker-missing"
240
241
242 def test_lease_holds_an_uncompromised_claim(marker: Path) -> None:
243 lease = _lease(marker)
244
245 with lease:
246 time.sleep(_HEARTBEAT * 3)
247 assert lease.compromise is None
248
249
250 @NEEDS_UNLINK_OPEN_FILE
251 def test_lease_can_be_released_from_the_compromise_callback(marker: Path) -> None: # pragma: needs unlink-open-file
252 # The callback runs on the heartbeat thread, so releasing from it needs a context that thread can see, and it must
253 # not deadlock joining itself.
254 holder: list[SoftFileLease] = []
255
256 def release_the_claim(_: LeaseCompromise) -> None:
257 holder[0].release()
258
259 lease = SoftFileLease(
260 str(marker),
261 thread_local=False,
262 lease_duration=_DURATION,
263 heartbeat_interval=_HEARTBEAT,
264 on_compromise=release_the_claim,
265 )
266 holder.append(lease)
267 lease.acquire()
268
269 marker.unlink()
270 time.sleep(_HEARTBEAT * 5)
271
272 assert lease.compromise is not None
273 assert not lease.is_locked
274
275
276 @NEEDS_UNLINK_OPEN_FILE # pragma: needs unlink-open-file
277 def test_lease_release_from_the_callback_needs_a_shared_context(marker: Path) -> None:
278 # With the default thread-local context the heartbeat thread sees no claim of its own, so its release() does
279 # nothing. Pin the trap the docstring warns about.
280 holder: list[SoftFileLease] = []
281
282 def release_the_claim(_: LeaseCompromise) -> None:
283 holder[0].release()
284
285 lease = _lease(marker, on_compromise=release_the_claim)
286 holder.append(lease)
287 lease.acquire()
288
289 try:
290 marker.unlink()
291 time.sleep(_HEARTBEAT * 5)
292 assert lease.is_locked, "a thread-local release() from the heartbeat thread silently did nothing"
293 finally:
294 lease.release()
295
296
297 def test_lease_records_a_compromise_without_a_callback_deterministically(marker: Path, mocker: MockerFixture) -> None:
298 # With no callback the heartbeat still records the loss on the lease so a holder can poll .compromise. A refresh
299 # that keeps failing drives the loss on every platform without depending on a peer taking the marker.
300 mocker.patch("filelock._lease.touch", side_effect=OSError("cannot touch the marker"))
301 lease = _lease(marker)
302
303 with lease:
304 deadline = time.monotonic() + _DURATION * 20
305 while lease.compromise is None and time.monotonic() < deadline:
306 time.sleep(_HEARTBEAT)
307
308 assert lease.compromise is not None
309 assert lease.compromise.reason == "refresh-failed"
310
311
312 def test_lease_release_from_the_callback_does_not_join_itself(marker: Path, mocker: MockerFixture) -> None:
313 # The callback runs on the heartbeat thread, so releasing there must skip joining that thread onto itself. A shared
314 # context lets the thread see the claim, and a failing refresh drives the loss deterministically on every platform.
315 mocker.patch("filelock._lease.touch", side_effect=OSError("cannot touch the marker"))
316 holder: list[SoftFileLease] = []
317
318 def release_the_claim(_: LeaseCompromise) -> None:
319 holder[0].release()
320
321 lease = SoftFileLease(
322 str(marker),
323 thread_local=False,
324 lease_duration=_DURATION,
325 heartbeat_interval=_HEARTBEAT,
326 on_compromise=release_the_claim,
327 )
328 holder.append(lease)
329 lease.acquire()
330
331 deadline = time.monotonic() + _DURATION * 20
332 while lease.is_locked and time.monotonic() < deadline:
333 time.sleep(_HEARTBEAT)
334
335 assert lease.compromise is not None
336 assert not lease.is_locked
337
338
339 def test_lease_keeps_its_claim_when_another_thread_fails_to_acquire(marker: Path) -> None:
340 # The context is thread-local, so a second thread contending on the same lease object must leave the holder's
341 # claim alone: a torn-down heartbeat stops refreshing the marker and a peer takes it while the holder still holds.
342 holder = _lease(marker)
343
344 def contend() -> None:
345 with suppress(Timeout):
346 holder.acquire()
347
348 with holder:
349 token = holder.token
350 contender = Thread(target=contend)
351 contender.start()
352 contender.join()
353
354 assert holder.token == token
355 time.sleep(_DURATION * 1.5) # only a surviving heartbeat keeps the claim past this
356 with pytest.raises(Timeout):
357 _lease(marker).acquire()
358
359
360 def test_lease_hands_back_the_claim_when_the_heartbeat_cannot_start(marker: Path, mocker: MockerFixture) -> None:
361 # A heartbeat thread the OS refuses (an rlimit reached) must not leave the claim behind: a peer would evict the
362 # unrefreshed marker and acquire while this instance still believed it held the lease, and the acquire rollback
363 # would raise joining a thread that never started.
364 mocker.patch.object(Thread, "start", side_effect=RuntimeError("can't start new thread"))
365 lease = _lease(marker)
366 with pytest.raises(RuntimeError, match="can't start new thread"):
367 lease.acquire()
368
369 assert not lease.is_locked
370 assert not marker.exists()
371 lease.release(force=True) # nothing was left to release, so this must not raise
372
373
374 def test_lease_release_stops_a_heartbeat_recorded_before_its_thread_starts(marker: Path, mocker: MockerFixture) -> None:
375 # A shared, non-thread-local claim lets a release() run while an acquire has recorded its heartbeat but not yet
376 # started the thread. Stubbing start() as a no-op freezes that window: release() must stop the heartbeat without
377 # raising on a join of the unstarted thread, and must still unlink the marker so a peer cannot take a claim we
378 # let go.
379 mocker.patch.object(Thread, "start")
380 lease = SoftFileLease(
381 str(marker), timeout=0.3, lease_duration=_DURATION, heartbeat_interval=_HEARTBEAT, thread_local=False
382 )
383 lease.acquire()
384 assert lease.is_locked
385
386 lease.release() # must not raise joining a thread that never started
387
388 assert not lease.is_locked
389 assert not marker.exists()
390
391
392 def test_lease_rejects_a_peer_configured_with_another_duration(marker: Path) -> None:
393 holder = _lease(marker)
394
395 with holder, pytest.raises(LeaseSettingsMismatch, match="must agree on lease_duration"):
396 _lease(marker, lease_duration=_DURATION * 3).acquire()
397
398
399 @pytest.mark.requires_hard_links
400 def test_lease_does_not_expire_a_strict_holder(marker: Path) -> None: # pragma: needs hard-link
401 # A strict holder never agreed to be superseded by age, so a lease contender waits it out instead.
402 with StrictSoftFileLock(str(marker)):
403 with pytest.raises(Timeout):
404 _lease(marker, timeout=_DURATION * 2).acquire()
405 assert marker.exists()
406
407
408 @pytest.mark.parametrize(
409 ("lease_duration", "heartbeat_interval", "error", "message"),
410 [
411 pytest.param(0, None, ValueError, "lease_duration must be positive", id="zero-duration"),
412 pytest.param(-1, None, ValueError, "lease_duration must be positive", id="negative-duration"),
413 pytest.param(float("nan"), _HEARTBEAT, ValueError, "positive and finite", id="nan-duration"),
414 pytest.param(float("inf"), _HEARTBEAT, ValueError, "positive and finite", id="infinite-duration"),
415 pytest.param(float("-inf"), _HEARTBEAT, ValueError, "positive and finite", id="negative-infinite-duration"),
416 pytest.param(True, None, TypeError, "number, not bool", id="true-duration"),
417 pytest.param(False, None, TypeError, "number, not bool", id="false-duration"),
418 pytest.param(_DURATION, 0, ValueError, "heartbeat_interval must be positive", id="zero-heartbeat"),
419 pytest.param(_DURATION, _DURATION, ValueError, "below lease_duration", id="heartbeat-equals-duration"),
420 pytest.param(_DURATION, _DURATION * 2, ValueError, "below lease_duration", id="heartbeat-over-duration"),
421 ],
422 )
423 def test_lease_rejects_incoherent_settings(
424 marker: Path,
425 lease_duration: float,
426 heartbeat_interval: float | None,
427 error: type[Exception],
428 message: str,
429 ) -> None:
430 with pytest.raises(error, match=message):
431 SoftFileLease(str(marker), lease_duration=lease_duration, heartbeat_interval=heartbeat_interval)
432
433
434 def test_lease_defaults_the_heartbeat_below_the_duration(marker: Path) -> None:
435 lease = SoftFileLease(str(marker), lease_duration=30)
436
437 assert lease.lease_duration == 30
438
439
440 def test_lease_drops_lifetime_with_a_warning(marker: Path) -> None:
441 with pytest.warns(UserWarning, match="lease_duration sets when a lease expires"):
442 lease = SoftFileLease(str(marker), lease_duration=_DURATION, lifetime=5)
443
444 assert lease.lifetime is None
445
446
447 def test_lease_supersedes_a_live_holder_once_its_claim_ages_out(marker: Path, mocker: MockerFixture) -> None:
448 # A live holder whose refresh stalled keeps its marker, yet a contender takes it once the marker ages past
449 # lease_duration. Windows cannot delete a live holder's open marker, so drive the age branch with a non-stale
450 # owner and an aged marker rather than a real second process.
451 mocker.patch("filelock._lease.owner_is_stale", return_value=False)
452 marker.write_text(
453 f"filelock/2\npid={os.getpid()}\nhost={socket.gethostname()}\nmode=lease\ntoken=stalled\nduration={_DURATION!r}\n",
454 encoding="utf-8",
455 )
456 aged = time.time() - (_DURATION + 5)
457 os.utime(marker, (aged, aged))
458
459 with _lease(marker) as contender:
460 assert contender.is_lock_held_by_us
461 assert contender.token not in {None, "stalled"}
462
463
464 def test_lease_reports_marker_missing_when_a_refresh_cannot_stat_it(marker: Path, mocker: MockerFixture) -> None:
465 # A vanished marker surfaces as FileNotFoundError from the refresh stat. Windows keeps an open marker undeletable,
466 # so inject the missing stat at the agnostic os.lstat call rather than unlinking a held file.
467 seen: list[LeaseCompromise] = []
468 lease = _lease(marker, on_compromise=seen.append)
469 lease.acquire()
470 token = lease.token
471 real_lstat = cast("Callable[..., os.stat_result]", os.lstat)
472 missing = False
473
474 def lstat(path: object, *args: object, **kwargs: object) -> object:
475 if missing and str(path).endswith(marker.name):
476 raise FileNotFoundError(ENOENT, "No such file or directory", marker.name)
477 return real_lstat(path, *args, **kwargs)
478
479 mocker.patch("filelock._lease.os.lstat", side_effect=lstat)
480 try:
481 missing = True
482 time.sleep(_HEARTBEAT * 4)
483 finally:
484 missing = False
485 lease.release()
486
487 assert [(c.reason, c.token, c.lock_file) for c in seen] == [("marker-missing", token, str(marker))]
488
489
490 def test_lease_reports_owner_changed_when_the_marker_identity_shifts(marker: Path, mocker: MockerFixture) -> None:
491 # A peer that took the expired claim replaces the marker, so the refresh stat names a different inode. Drive that
492 # agnostically by returning a stat whose identity differs from the one the holder verified at acquire.
493 seen: list[LeaseCompromise] = []
494 lease = _lease(marker, on_compromise=seen.append)
495 lease.acquire()
496 token = lease.token
497 real_lstat = cast("Callable[..., os.stat_result]", os.lstat)
498 shifted = False
499
500 def lstat(path: object, *args: object, **kwargs: object) -> object:
501 st = real_lstat(path, *args, **kwargs)
502 if shifted and str(path).endswith(marker.name):
503 return SimpleNamespace(st_dev=st.st_dev, st_ino=st.st_ino + 1)
504 return st
505
506 mocker.patch("filelock._lease.os.lstat", side_effect=lstat)
507 try:
508 shifted = True
509 time.sleep(_HEARTBEAT * 4)
510 finally:
511 shifted = False
512 lease.release()
513
514 assert [(c.reason, c.token) for c in seen] == [("owner-changed", token)]
515
516
517 def test_native_lock_rejects_a_lease_duration(marker: Path) -> None:
518 # A kernel lock lives on the inode, so no pathname age can revoke it; the option must not even be accepted. The
519 # rejection happens at runtime, so reach it the way a caller without a type checker would.
520 construct = cast("Callable[..., FileLock]", FileLock)
521
522 with pytest.raises(TypeError, match="does not support non-default lock options: lease_duration"):
523 construct(str(marker), lease_duration=5)