Skip to content

Commit 794e0f2

Browse files
committed
🐛 fix(api): retry release on the same hold
An interrupted release can resume after another thread has acquired the lock at the same depth. Check the acquisition generation under the transition gate before retrying. Fixes #1004
1 parent 20d9386 commit 794e0f2

4 files changed

Lines changed: 208 additions & 14 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
A failed lock acquisition rolls back the level it was taking. During a synchronous acquire, calling ``release()`` from
22
a hook or signal handler to drop that level raises :exc:`RuntimeError`. A balanced nested ``with lock:`` remains valid.
3+
4+
An interrupted release on a shared instance can only retry the hold it started releasing.

‎src/filelock/_api.py‎

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1167,6 +1167,7 @@ def _poll_until_acquired(
11671167
if not self.is_locked:
11681168
self._try_break_expired_lock()
11691169
_LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename)
1170+
self._context.lock_generation += 1
11701171
self._acquire_with_fork_tracking()
11711172
self._raise_if_inherited()
11721173
self._raise_if_voided()
@@ -1453,22 +1454,25 @@ def release(self, force: bool = False) -> None: # ruff:ignore[boolean-type-hint
14531454
running, and a ``thread_local=False`` lock while any other thread runs.
14541455
14551456
"""
1456-
counter_before: int | None = None
1457-
try:
1458-
counter_before = self._context.lock_counter
1459-
self._release_current(force=force)
1460-
except BaseException as release_error:
1461-
# A handler that raised after release() began and before the backend changed anything leaves the counter as
1462-
# it was; only then does a second attempt release the hold the caller gave up. A failed system call keeps it
1463-
# for an explicit retry, and a changed counter means a nested level or the backend's own retry already ran.
1464-
if (
1465-
counter_before is not None
1466-
and counter_before == self._context.lock_counter
1467-
and self._context.lock_file_fd is not None
1468-
and not is_system_call_failure(release_error)
1457+
release_snapshot: tuple[int, int] | None = None
1458+
transition_entered = False
1459+
try: # ruff:ignore[too-many-statements-in-try-clause] # gate-entry signals and release failures need separate recovery
1460+
release_snapshot = (self._context.lock_generation, self._context.lock_counter)
1461+
with (
1462+
contextlib.nullcontext()
1463+
if self._settings.thread_local or self._context.lock_file_fd is None
1464+
else self._transition_lock
14691465
):
1470-
with contextlib.suppress(Exception):
1466+
try:
1467+
transition_entered = True
1468+
release_snapshot = (self._context.lock_generation, self._context.lock_counter)
14711469
self._release_current(force=force)
1470+
except BaseException as release_error:
1471+
self._retry_interrupted_release(release_snapshot, release_error, force=force, transition_held=True)
1472+
raise
1473+
except BaseException as release_error:
1474+
if not transition_entered:
1475+
self._retry_interrupted_release(release_snapshot, release_error, force=force, transition_held=False)
14721476
raise
14731477
if force:
14741478
self._release_thread_holds(exited_only=True)
@@ -1532,6 +1536,19 @@ def _finish_interrupted_release(self) -> None:
15321536
def _hold_state(self) -> FileLockContext:
15331537
return self._context.current if isinstance(self._context, ThreadLocalFileContext) else self._context
15341538

1539+
def _retry_interrupted_release(
1540+
self, snapshot: tuple[int, int] | None, release_error: BaseException, *, force: bool, transition_held: bool
1541+
) -> None:
1542+
# A retry can only touch the original hold; a later acquirer may restore the same recursion depth.
1543+
if snapshot is None or self._context.lock_file_fd is None or is_system_call_failure(release_error):
1544+
return
1545+
with (
1546+
contextlib.suppress(Exception),
1547+
contextlib.nullcontext() if transition_held or self._settings.thread_local else self._transition_lock,
1548+
):
1549+
if snapshot == (self._context.lock_generation, self._context.lock_counter):
1550+
self._release_current(force=force)
1551+
15351552
def _release_thread_holds(self, *, exited_only: bool) -> None:
15361553
if not isinstance(context := self._context, ThreadLocalFileContext):
15371554
return
@@ -2132,6 +2149,7 @@ class FileLockContext: # simplint: ignore[too-many-attributes] # its fields ar
21322149
#: The lease claim of this hold, kept with it so a cross-thread release stops the right heartbeat.
21332150
lease_claim: LeaseClaim | None = None
21342151

2152+
lock_generation: int = field(default=0, kw_only=True)
21352153
in_flight: list[_InFlight] = field(default_factory=list, kw_only=True, repr=False)
21362154

21372155

‎tests/test_filelock.py‎

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1647,6 +1647,140 @@ def unlock_then_reenter(fd: int, operation: int) -> None:
16471647
assert ([call.args for call in close.call_args_list], lock.is_locked) == ([(unlocked[0],)], False)
16481648

16491649

1650+
def test_reentered_release_keeps_the_outer_hold_until_unlock(tmp_path: Path, mocker: MockerFixture) -> None:
1651+
lock_path = str(tmp_path / "a.lock")
1652+
lock = FileLock(lock_path, is_singleton=False)
1653+
peer = FileLock(lock_path, is_singleton=False)
1654+
lock.acquire()
1655+
pending = [None]
1656+
observed: list[bool] = []
1657+
1658+
def release_after_reentry(*_args: object) -> None:
1659+
if pending:
1660+
pending.pop()
1661+
lock.release(force=True)
1662+
observed.append(lock.is_locked)
1663+
with pytest.raises(Timeout):
1664+
peer.acquire(blocking=False)
1665+
1666+
mocker.patch("filelock._api._LOGGER.debug", autospec=True, side_effect=release_after_reentry)
1667+
lock.release()
1668+
assert (observed, lock.is_locked) == ([True], False)
1669+
with peer:
1670+
assert peer.is_locked
1671+
1672+
1673+
def test_interrupted_release_keeps_a_new_threads_hold(tmp_path: Path, mocker: MockerFixture) -> None:
1674+
lock_path = str(tmp_path / "a.lock")
1675+
lock = FileLock(lock_path, thread_local=False, is_singleton=False)
1676+
lock.acquire()
1677+
start, attempting, entered, finish = (threading.Event() for _ in range(4))
1678+
1679+
def hold_after_release() -> None:
1680+
start.wait()
1681+
attempting.set()
1682+
with lock:
1683+
entered.set()
1684+
finish.wait()
1685+
1686+
worker = threading.Thread(target=hold_after_release, daemon=True)
1687+
worker.start()
1688+
release_current = lock._release_current
1689+
pending = [None]
1690+
1691+
def release_then_interrupt(*, force: bool) -> None:
1692+
release_current(force=force)
1693+
if pending:
1694+
pending.pop()
1695+
start.set()
1696+
assert attempting.wait(1)
1697+
assert not entered.wait(0.1)
1698+
raise KeyboardInterrupt
1699+
1700+
mocker.patch.object(lock, "_release_current", side_effect=release_then_interrupt, autospec=True)
1701+
try:
1702+
with pytest.raises(KeyboardInterrupt):
1703+
lock.release()
1704+
assert entered.wait(1)
1705+
with pytest.raises(Timeout):
1706+
FileLock(lock_path, is_singleton=False).acquire(blocking=False)
1707+
assert lock.is_locked
1708+
finally:
1709+
finish.set()
1710+
worker.join(2)
1711+
lock.release(force=True)
1712+
1713+
1714+
def test_interrupted_release_while_entering_the_gate_retries(
1715+
tmp_path: Path, mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch
1716+
) -> None:
1717+
lock_path = str(tmp_path / "a.lock")
1718+
lock = FileLock(lock_path, thread_local=False, is_singleton=False)
1719+
lock.acquire()
1720+
transition = lock._transition_lock
1721+
gate = mocker.create_autospec(transition, instance=True)
1722+
pending = [None]
1723+
1724+
def enter_gate() -> bool:
1725+
if pending:
1726+
pending.pop()
1727+
raise KeyboardInterrupt
1728+
return transition.acquire()
1729+
1730+
gate.__enter__.side_effect = enter_gate
1731+
gate.__exit__.side_effect = lambda *_args: transition.release()
1732+
monkeypatch.setattr(lock, "_transition_lock", gate)
1733+
with pytest.raises(KeyboardInterrupt):
1734+
lock.release()
1735+
assert not lock.is_locked
1736+
with FileLock(lock_path, blocking=False, is_singleton=False):
1737+
pass
1738+
1739+
1740+
def test_interrupted_release_retries_after_another_thread_nests(tmp_path: Path, mocker: MockerFixture) -> None:
1741+
lock_path = str(tmp_path / "a.lock")
1742+
lock = FileLock(lock_path, thread_local=False, is_singleton=False)
1743+
lock.acquire()
1744+
lock.acquire()
1745+
start, attempting, entered, finish = (threading.Event() for _ in range(4))
1746+
release_current = lock._release_current
1747+
pending = [None]
1748+
1749+
def nest() -> None:
1750+
start.wait()
1751+
attempting.set()
1752+
with lock:
1753+
entered.set()
1754+
finish.wait()
1755+
1756+
worker = threading.Thread(target=nest, daemon=True)
1757+
worker.start()
1758+
1759+
def interrupt_after_nested_hold(*, force: bool) -> None:
1760+
release_current(force=force)
1761+
if pending:
1762+
pending.pop()
1763+
start.set()
1764+
assert attempting.wait(1)
1765+
assert not entered.wait(0.1)
1766+
raise KeyboardInterrupt
1767+
1768+
mocker.patch.object(lock, "_release_current", side_effect=interrupt_after_nested_hold, autospec=True)
1769+
try:
1770+
with pytest.raises(KeyboardInterrupt):
1771+
lock.release()
1772+
assert entered.wait(1)
1773+
finish.set()
1774+
worker.join(2)
1775+
assert lock.is_locked
1776+
with pytest.raises(Timeout):
1777+
FileLock(lock_path, is_singleton=False).acquire(blocking=False)
1778+
finally:
1779+
finish.set()
1780+
worker.join(2)
1781+
lock.release(force=True)
1782+
1783+
16501784
@pytest.mark.parametrize("lock_type", [FileLock, SoftFileLock, MarkerSoftFileLock, SoftFileLease])
16511785
@pytest.mark.parametrize("thread_local", [pytest.param(True, id="thread_local"), pytest.param(False, id="shared")])
16521786
def test_release_interrupted_at_any_call_leaves_the_lock_usable(

‎tests/test_fork_backends.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import os
55
import subprocess # ruff:ignore[suspicious-subprocess-import] # isolated interpreter controls child callback registration order
66
import sys
7+
import threading
78
from errno import EBADF
89
from typing import TYPE_CHECKING, NoReturn, cast
910

@@ -61,6 +62,45 @@ def probe_child() -> NoReturn:
6162
return fork_process(probe_child)
6263

6364

65+
def test_direct_descriptor_backend_keeps_new_hold_on_interrupted_release(tmp_path: Path, mocker: MockerFixture) -> None:
66+
lock_path = tmp_path / "third-party.lock"
67+
lock = _DescriptorLock(str(lock_path), thread_local=False, is_singleton=False)
68+
lock.acquire()
69+
start, entered, finish = (threading.Event() for _ in range(3))
70+
71+
def hold_replacement() -> None:
72+
start.wait()
73+
with lock:
74+
entered.set()
75+
finish.wait()
76+
77+
worker = threading.Thread(target=hold_replacement, daemon=True)
78+
worker.start()
79+
release_current = lock._release_current
80+
pending = [None]
81+
82+
def release_then_interrupt(*, force: bool) -> None:
83+
release_current(force=force)
84+
if pending:
85+
pending.pop()
86+
start.set()
87+
assert not entered.wait(0.1)
88+
raise KeyboardInterrupt
89+
90+
mocker.patch.object(lock, "_release_current", side_effect=release_then_interrupt, autospec=True)
91+
try:
92+
with pytest.raises(KeyboardInterrupt):
93+
lock.release()
94+
assert entered.wait(1)
95+
fd = lock._context.lock_file_fd
96+
assert fd is not None
97+
assert os.fstat(fd).st_ino == lock_path.stat().st_ino
98+
finally:
99+
finish.set()
100+
worker.join(2)
101+
lock.release(force=True)
102+
103+
64104
@NEEDS_FORK # pragma: needs fork
65105
def test_unlock_failure_keeps_descriptor_registered(tmp_path: Path) -> None:
66106
descriptors: list[int] = []

0 commit comments

Comments
 (0)