Skip to content

Commit be6d538

Browse files
committed
🐛 fix(lease): record lost claim at release
The heartbeat treats its first marker mismatch as provisional because a peer's exchange may be rolled back. Release could stop it before a second check and leave a superseded holder's compromise unset. Check the held inode before clearing the claim. An unlinked inode proves the marker change survived the exchange; a linked inode or failed probe does not. Fixes #1026
1 parent c7d62e7 commit be6d538

9 files changed

Lines changed: 274 additions & 21 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
On POSIX, :class:`~filelock.SoftFileLease` now records a claim taken before release even when the heartbeat has not
2+
reported it. ``on_compromise`` remains a heartbeat-thread callback; callers can inspect ``compromise`` after release.

‎docs/concepts.rst‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -652,9 +652,9 @@ Ownership scope per lock
652652
:meth:`force_break <filelock.StrictSoftFileLock.force_break>`. This is the fail-closed contract.
653653
* - :class:`SoftFileLease <filelock.SoftFileLease>`
654654
- A claim that *expires*; a peer may take it while the previous holder still runs
655-
- A heartbeat refreshes the claim; ``on_compromise`` fires when it is lost. Overlap is permitted by design, so a
656-
lease is a hint about who *should* work, not a guarantee that only one worker does. A forked child holds no
657-
claim.
655+
- A heartbeat refreshes the claim and calls ``on_compromise`` when it detects loss. Release can record a loss in
656+
``compromise`` without calling back. Overlap is permitted by design, so a lease is a hint about who *should* work,
657+
not a guarantee that only one worker does. A forked child holds no claim.
658658
* - :class:`ReadWriteLock <filelock.ReadWriteLock>`
659659
- The acquisition object; state lives in a local SQLite database
660660
- Requires a local filesystem the SQLite VFS supports. A forked child must build a fresh instance. Crash recovery
@@ -718,7 +718,7 @@ claim by age, a strict lock needs no liveness guess; a claim it cannot read with
718718

719719
A :class:`SoftFileLease <filelock.SoftFileLease>` can expire while its holder is still working. If the heartbeat
720720
detects a lost claim, it calls ``on_compromise``. Further acquires on that instance raise ``RuntimeError`` until the
721-
holder releases it.
721+
holder releases it. If release discovers the loss, it records ``compromise`` after the work ends.
722722

723723
The :attr:`token <filelock.SoftFileLease.token>` identifies the claim. It does **not** fence the protected resource.
724724
A paused holder can resume and write after another process takes the lease. Fencing requires a linearizable resource

‎docs/how-to.rst‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1139,13 +1139,14 @@ still be alive. A crashed holder leaves a marker no contender removes; clear it
11391139
:meth:`force_break <filelock.StrictSoftFileLock.force_break>`, which voids mutual exclusion for whoever is still
11401140
running.
11411141

1142-
:class:`SoftFileLease <filelock.SoftFileLease>` trades exclusion for progress. The holder refreshes its claim, and a
1143-
peer takes the marker once it has watched it go ``lease_duration`` seconds without a refresh, timed on the peer's own
1144-
monotonic clock so clock skew between hosts cannot expire a live claim. A peer reclaims a same-host lease or
1145-
``MarkerSoftFileLock`` owner that is provably dead at once. The expired holder keeps running and keeps using
1146-
whatever the lock protects, so a lease says who *should* be working, not who alone is. ``on_compromise`` fires when the
1147-
claim is lost. :attr:`token <filelock.SoftFileLease.token>` names a claim but does not fence one: to reject a superseded
1148-
holder, the protected resource must be linearizable and fence on a monotonic generation it controls.
1142+
The heartbeat refreshes the lease marker while work runs. A peer can take the marker after it sees no refresh for
1143+
``lease_duration`` seconds on its own monotonic clock. A peer on the same host can reclaim a lease or
1144+
``MarkerSoftFileLock`` immediately if the owner has died.
1145+
1146+
The heartbeat calls ``on_compromise`` when it detects a lost claim. Release can also record the loss in
1147+
:attr:`compromise <filelock.SoftFileLease.compromise>` after work ends. An expired holder can continue writing.
1148+
The :attr:`token <filelock.SoftFileLease.token>` identifies the claim. To reject stale writes, the resource must
1149+
atomically check a generation it controls.
11491150

11501151
.. code-block:: python
11511152

‎docs/index.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ Choose the right lock for your use case:
9595
Expiring claim with a heartbeat, for when overlap is acceptable and progress matters more than exclusion.
9696

9797
- ✓ A peer can take over a wedged holder
98-
- ✓ ``on_compromise`` callback on claim loss
98+
- ✓ Heartbeat callback on observed loss; ``compromise`` can also report loss at release
9999
- ✓ Fence the resource: a token names a claim, it does not fence one
100100

101101
.. grid-item-card::

‎docs/tutorials.rst‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -436,8 +436,9 @@ claim by age, so a crashed holder's claim is cleared only by an operator:
436436
stale.force_break(claim.name)
437437
438438
:class:`SoftFileLease <filelock.SoftFileLease>` trades exclusion for progress. Its claim expires, so a peer can take over
439-
if a holder wedges; a callback fires when this process loses its claim. A lease token names a claim but does not fence
440-
the protected resource, so fence any resource an expired holder could still write:
439+
if a holder wedges. The heartbeat calls back when it detects a lost claim while work runs. Release can also record loss
440+
in :attr:`compromise <filelock.SoftFileLease.compromise>` after work ends, without calling back. A lease token names a
441+
claim but does not fence the protected resource, so fence any resource an expired holder could still write:
441442

442443
.. code-block:: python
443444

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ ini_options.pythonpath = [
232232
"tasks",
233233
]
234234
ini_options.markers = [
235-
"requires_hard_links: exercises StrictSoftFileLock, which needs os.link; skipped where it is missing (Termux/Android)",
235+
"requires_hard_links: needs os.link; skipped where it is missing (Termux/Android)",
236236
]
237237
ini_options.filterwarnings = [
238238
"error",

‎src/filelock/_lease.py‎

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -168,14 +168,16 @@ def _claim(self) -> LeaseClaim:
168168
@property
169169
def compromise(self) -> LeaseCompromise | None:
170170
"""
171-
The loss of claim the heartbeat observed.
171+
The loss of claim the heartbeat observed or release could prove.
172172
173173
The value outlives ``release()``, so a holder can check after leaving the ``with`` block whether its work may
174174
have overlapped a successor; the next acquisition resets it, as :attr:`SoftReadWriteLock.compromise
175175
<filelock.SoftReadWriteLock.compromise>` does. Until the lost claim is released, acquiring on this instance
176176
raises :class:`RuntimeError` instead of joining it.
177177
178-
The :class:`LeaseCompromise` of the latest claim, or ``None`` while that claim holds or held to its release.
178+
The :class:`LeaseCompromise` of the latest claim, or ``None`` when no loss was observed. Release can record a
179+
claim taken before the heartbeat's second check. It does not call ``on_compromise``: that callback runs on the
180+
heartbeat thread to stop work in progress.
179181
180182
"""
181183
return self._claim.compromise
@@ -286,9 +288,52 @@ def _raise_if_hold_unusable(self) -> None:
286288

287289
def _release(self) -> None:
288290
self._stop_heartbeat()
291+
if sys.platform != "win32": # pragma: win32 no cover
292+
self._record_unreported_loss()
289293
self._claim.token = None
290294
super()._release()
291295

296+
def _record_unreported_loss(self) -> None: # pragma: win32 no cover
297+
if (
298+
(token := self._claim.token) is None
299+
or self._claim.compromise is not None
300+
or (identity := self._context.lock_file_fd_identity) is None
301+
):
302+
return
303+
fd = self._context.lock_file_fd
304+
assert fd is not None # ruff:ignore[assert] # _release runs only while the descriptor is held
305+
with suppress(OSError):
306+
try:
307+
marker = os.lstat(self._lock_path)
308+
except FileNotFoundError:
309+
reason: CompromiseReason = "marker-missing"
310+
else:
311+
if (marker.st_dev, marker.st_ino) == identity:
312+
return
313+
reason = "owner-changed"
314+
held = os.fstat(fd)
315+
if held.st_nlink:
316+
if reason == "marker-missing" and _parent_is_missing(self._lock_path):
317+
return
318+
if reason == "owner-changed" and self._marker_has_break_name(held):
319+
return
320+
# An exchange or directory rename can roll back while fstat runs.
321+
with suppress(FileNotFoundError):
322+
if os.path.samestat(os.lstat(self._lock_path), held):
323+
return
324+
self._claim.compromise = LeaseCompromise(lock_file=self.lock_file, token=token, reason=reason)
325+
326+
def _marker_has_break_name(self, held: os.stat_result) -> bool: # pragma: win32 no cover
327+
# An exchange keeps the old inode under the contender's break name until that contender commits or rolls back.
328+
prefix = f"{pathlib.Path(self._lock_path).name}.break."
329+
with os.scandir(pathlib.Path(self._lock_path).parent) as names:
330+
for name in names:
331+
if name.name.startswith(prefix):
332+
with suppress(FileNotFoundError):
333+
if os.path.samestat(name.stat(follow_symlinks=False), held):
334+
return True
335+
return False
336+
292337
def _reset_after_fork_in_child(self) -> None: # pragma: forked child
293338
super()._reset_after_fork_in_child()
294339
# As in __init__: two child threads lazily creating a shared claim could each get one.

‎tests/conftest.py‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,10 @@ def acquire_after_reclaim(lock: BaseFileLock) -> None:
7070

7171

7272
def pytest_collection_modifyitems(items: list[pytest.Item]) -> None:
73-
# StrictSoftFileLock publishes claims with hard links, so tests marked requires_hard_links cannot run where
74-
# os.link is missing (Termux/Android CPython ships without it). The no-hard-link degradation itself is covered by
75-
# the os.link tests in test_filelock.py, which carry no marker and run everywhere.
73+
# Tests marked requires_hard_links cannot run where os.link is missing (Termux/Android CPython ships without it).
74+
# The no-hard-link degradation itself is covered by the os.link tests in test_filelock.py, which run everywhere.
7675
if not hasattr(os, "link"): # pragma: no cover # the body runs only on Termux/Android, absent from the CI matrix
77-
skip = pytest.mark.skip(reason="StrictSoftFileLock requires os.link (hard links), absent on Termux/Android")
76+
skip = pytest.mark.skip(reason="test requires os.link (hard links), absent on Termux/Android")
7877
for item in items:
7978
if item.get_closest_marker("requires_hard_links") is not None:
8079
item.add_marker(skip)

‎tests/test_soft_lease.py‎

Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,211 @@ def _wait_until(condition: Callable[[], bool]) -> None:
493493
time.sleep(_HEARTBEAT / 2) # simplint: ignore[sleep-in-test] # needs a compromise signal
494494

495495

496+
@NEEDS_UNLINK_OPEN_FILE # pragma: needs unlink-open-file
497+
def test_lease_release_records_a_missing_marker_before_the_next_heartbeat(
498+
marker: Path,
499+
) -> None:
500+
reports = _Reports()
501+
lease = SoftFileLease(marker, lease_duration=30, heartbeat_interval=29, on_compromise=reports)
502+
503+
with lease:
504+
token = lease.token
505+
assert token is not None
506+
marker.unlink()
507+
508+
assert lease.compromise == LeaseCompromise(lock_file=str(marker), token=token, reason="marker-missing")
509+
assert reports.seen == []
510+
511+
512+
@NEEDS_UNLINK_OPEN_FILE
513+
def test_lease_release_records_a_replacement_before_the_next_heartbeat( # pragma: needs unlink-open-file
514+
marker: Path,
515+
) -> None:
516+
reports = _Reports()
517+
lease = SoftFileLease(marker, lease_duration=30, heartbeat_interval=29, on_compromise=reports)
518+
peer = SoftFileLease(marker, timeout=0, lease_duration=30, heartbeat_interval=29)
519+
520+
try:
521+
with lease:
522+
token = lease.token
523+
assert token is not None
524+
marker.unlink()
525+
peer.acquire()
526+
assert lease.compromise == LeaseCompromise(lock_file=str(marker), token=token, reason="owner-changed")
527+
assert reports.seen == []
528+
finally:
529+
peer.release()
530+
531+
532+
@pytest.mark.requires_hard_links # pragma: needs hard-link
533+
@NEEDS_UNLINK_OPEN_FILE
534+
def test_lease_release_records_a_missing_marker_with_an_extra_link( # pragma: needs unlink-open-file
535+
marker: Path,
536+
) -> None:
537+
lease = SoftFileLease(marker, lease_duration=30, heartbeat_interval=29)
538+
alias = marker.with_name("alias")
539+
540+
with lease:
541+
token = lease.token
542+
assert token is not None
543+
os.link(marker, alias)
544+
marker.unlink()
545+
546+
assert lease.compromise == LeaseCompromise(lock_file=str(marker), token=token, reason="marker-missing")
547+
alias.unlink()
548+
549+
550+
@NEEDS_UNLINK_OPEN_FILE
551+
def test_lease_release_records_a_replacement_with_an_unrelated_break_name( # pragma: needs unlink-open-file
552+
marker: Path,
553+
) -> None:
554+
lease = SoftFileLease(marker, lease_duration=30, heartbeat_interval=29)
555+
peer = SoftFileLease(marker, timeout=0, lease_duration=30, heartbeat_interval=29)
556+
alias = marker.with_name("alias")
557+
unrelated_break = marker.with_name(f"{marker.name}.break.{os.getpid()}.00000000000000000000000000000000")
558+
unrelated_break.write_text("unrelated", encoding="utf-8")
559+
560+
try:
561+
with lease:
562+
token = lease.token
563+
assert token is not None
564+
marker.rename(alias)
565+
peer.acquire()
566+
assert lease.compromise == LeaseCompromise(lock_file=str(marker), token=token, reason="owner-changed")
567+
finally:
568+
peer.release()
569+
alias.unlink()
570+
unrelated_break.unlink()
571+
572+
573+
@NEEDS_UNLINK_OPEN_FILE
574+
def test_lease_release_records_loss_after_the_first_heartbeat_miss( # pragma: needs unlink-open-file
575+
marker: Path, mocker: MockerFixture
576+
) -> None:
577+
first_miss = Event()
578+
reports = _Reports()
579+
lease = SoftFileLease(marker, lease_duration=30, heartbeat_interval=2, on_compromise=reports)
580+
peer = SoftFileLease(marker, timeout=0, lease_duration=30, heartbeat_interval=29)
581+
582+
try:
583+
with lease:
584+
token = lease.token
585+
assert token is not None
586+
held = os.lstat(marker)
587+
original_lstat = os.lstat
588+
holder_thread = threading.current_thread()
589+
590+
def signal_first_miss(path: str | os.PathLike[str], *, dir_fd: int | None = None) -> os.stat_result:
591+
result = original_lstat(path, dir_fd=dir_fd)
592+
if (
593+
os.fspath(path) == str(marker)
594+
and threading.current_thread() is not holder_thread
595+
and (result.st_dev, result.st_ino) != (held.st_dev, held.st_ino)
596+
):
597+
first_miss.set()
598+
return result
599+
600+
mocker.patch("filelock._lease.os.lstat", side_effect=signal_first_miss, autospec=True)
601+
marker.unlink()
602+
peer.acquire()
603+
assert first_miss.wait(5)
604+
assert reports.seen == []
605+
assert lease.compromise == LeaseCompromise(lock_file=str(marker), token=token, reason="owner-changed")
606+
assert reports.seen == []
607+
finally:
608+
peer.release()
609+
610+
611+
@pytest.mark.skipif(sys.platform == "win32", reason="Windows cannot rename an open marker")
612+
def test_lease_release_does_not_report_a_provisional_break(marker: Path) -> None: # pragma: win32 no cover
613+
lease = SoftFileLease(marker, lease_duration=30, heartbeat_interval=29)
614+
aside = marker.with_name(f"{marker.name}.break.{os.getpid()}.pending")
615+
616+
with lease:
617+
marker.rename(aside)
618+
marker.write_text("peer", encoding="utf-8")
619+
620+
assert lease.compromise is None
621+
622+
623+
@pytest.mark.skipif(sys.platform == "win32", reason="Windows cannot rename an open marker")
624+
def test_lease_release_does_not_report_a_rolled_back_break( # pragma: win32 no cover
625+
marker: Path, mocker: MockerFixture
626+
) -> None:
627+
lease = SoftFileLease(marker, lease_duration=30, heartbeat_interval=29)
628+
aside = marker.with_name(f"{marker.name}.break.{os.getpid()}.pending")
629+
fstat = os.fstat
630+
first = iter([True])
631+
632+
def restore(fd: int) -> os.stat_result:
633+
if next(first, False):
634+
marker.unlink()
635+
aside.rename(marker)
636+
return fstat(fd)
637+
638+
with lease:
639+
marker.rename(aside)
640+
marker.write_text("peer", encoding="utf-8")
641+
mocker.patch("filelock._lease.os.fstat", side_effect=restore, autospec=True)
642+
643+
assert lease.compromise is None
644+
assert not marker.exists()
645+
646+
647+
@pytest.mark.skipif(sys.platform == "win32", reason="Windows cannot rename a directory with an open marker")
648+
def test_lease_release_does_not_report_a_renamed_directory(marker: Path) -> None: # pragma: win32 no cover
649+
lease = SoftFileLease(marker, lease_duration=30, heartbeat_interval=29)
650+
moved = marker.parent.with_name(f"{marker.parent.name}-moved")
651+
652+
with lease:
653+
marker.parent.rename(moved)
654+
655+
assert lease.compromise is None
656+
(moved / marker.name).unlink()
657+
658+
659+
@pytest.mark.skipif(sys.platform == "win32", reason="Windows cannot rename a directory with an open marker")
660+
def test_lease_release_does_not_report_a_restored_directory( # pragma: win32 no cover
661+
marker: Path, mocker: MockerFixture
662+
) -> None:
663+
lease = SoftFileLease(marker, lease_duration=30, heartbeat_interval=29)
664+
moved = marker.parent.with_name(f"{marker.parent.name}-moved")
665+
fstat = os.fstat
666+
first = iter([True])
667+
668+
def restore(fd: int) -> os.stat_result:
669+
if next(first, False):
670+
moved.rename(marker.parent)
671+
return fstat(fd)
672+
673+
with lease:
674+
marker.parent.rename(moved)
675+
mocker.patch("filelock._lease.os.fstat", side_effect=restore, autospec=True)
676+
677+
assert lease.compromise is None
678+
assert not marker.exists()
679+
680+
681+
@pytest.mark.skipif(sys.platform == "win32", reason="Release probes the marker only on POSIX")
682+
def test_lease_release_does_not_report_an_unreadable_marker(
683+
marker: Path, mocker: MockerFixture
684+
) -> None: # pragma: win32 no cover
685+
lease = SoftFileLease(marker, lease_duration=30, heartbeat_interval=29)
686+
lstat = os.lstat
687+
first = iter([True])
688+
689+
def fail_once(path: str | os.PathLike[str], *, dir_fd: int | None = None) -> os.stat_result:
690+
if os.fspath(path) == str(marker) and next(first, False):
691+
raise OSError(EIO, "Input/output error")
692+
return lstat(path, dir_fd=dir_fd)
693+
694+
with lease:
695+
mocker.patch("filelock._lease.os.lstat", side_effect=fail_once, autospec=True)
696+
697+
assert lease.compromise is None
698+
assert not marker.exists()
699+
700+
496701
def test_lease_holds_an_uncompromised_claim(marker: Path, mocker: MockerFixture) -> None:
497702
refreshes = _count_refreshes(mocker)
498703
lease = _lease(marker)

0 commit comments

Comments
 (0)