From 333dee411ed651c955276643587ed1bc94662562 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Fri, 20 Nov 2026 00:55:16 -0800 Subject: [PATCH 1/8] =?UTF-8?q?=F0=9F=90=9B=20fix(async):=20wake=20table?= =?UTF-8?q?=20waiters=20on=20close?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closing one singleton wrapper left its pending acquires asleep when another wrapper held the lock. Associate each admission ticket with its wrapper so close can wake its own waiters, then check the wrapper state before admission. Fixes #1061 --- .../+async-close-table-wait.bugfix.rst | 2 + docs/how-to.rst | 9 +-- src/filelock/_async.py | 28 ++++++-- src/filelock/_async_read_write.py | 4 ++ src/filelock/_soft_rw/_async.py | 4 ++ tests/soft_rw/test_soft_rw_async.py | 47 ++++++++++++ tests/test_async_read_write.py | 71 +++++++++++++++++++ 7 files changed, 155 insertions(+), 10 deletions(-) create mode 100644 docs/changelog/+async-close-table-wait.bugfix.rst diff --git a/docs/changelog/+async-close-table-wait.bugfix.rst b/docs/changelog/+async-close-table-wait.bugfix.rst new file mode 100644 index 000000000..96c334a42 --- /dev/null +++ b/docs/changelog/+async-close-table-wait.bugfix.rst @@ -0,0 +1,2 @@ +A successful close of an ``AsyncReadWriteLock`` or ``AsyncSoftReadWriteLock`` wrapper now wakes its task-table waiters +while another singleton wrapper still holds the lock. diff --git a/docs/how-to.rst b/docs/how-to.rst index c9eda127c..728d0fab0 100644 --- a/docs/how-to.rst +++ b/docs/how-to.rst @@ -795,7 +795,8 @@ time of the call rather than at construction: With the default ``is_singleton=True`` every wrapper on a path shares one lock, so ``close()`` ends only the holds of tasks that acquired through that wrapper. Tasks holding through another wrapper, and synchronous ``ReadWriteLock`` users -of the same path, keep their locks. +of the same path, keep their locks. An acquire waiting for another async wrapper's hold wakes and raises the closed +error. Low-level ``acquire_read``/``acquire_write``/``release`` methods are also available: @@ -825,9 +826,9 @@ For a shared filesystem whose marker and cache behavior has been verified, use It takes the same tuning as its synchronous peer plus the async pair, so the full signature is ``AsyncSoftReadWriteLock(lock_file, timeout=-1, *, blocking=True, is_singleton=True, heartbeat_interval=30.0, -stale_threshold=None, poll_interval=0.25, on_compromise=None, loop=None, executor=None)``. It has no SQLite thread affinity to respect, so -``executor=None`` means the loop's default executor: it creates nothing and owns nothing, and its ``close()`` only -delegates to the synchronous lock. +stale_threshold=None, poll_interval=0.25, on_compromise=None, loop=None, executor=None)``. It has no SQLite thread +affinity to respect, so ``executor=None`` means the loop's default executor: it creates nothing and owns nothing. Its +``close()`` ends this wrapper's holds and wakes acquires waiting for another async wrapper's hold. ************************************** Detect stale locks (soft locks only) diff --git a/src/filelock/_async.py b/src/filelock/_async.py index cd96f3147..0730543bf 100644 --- a/src/filelock/_async.py +++ b/src/filelock/_async.py @@ -200,7 +200,7 @@ def __init__(self) -> None: self._waiting_writers = 0 #: One ticket per waiting call, settled on the next state change. A call that stops waiting takes its own out, #: so one that times out or is canceled leaves nothing behind. - self._waiters: dict[ConcurrentFuture[None], None] = {} + self._waiters: dict[ConcurrentFuture[None], Hashable | None] = {} async def acquire( # ruff:ignore[too-many-arguments] # one keyword per piece of wrapper state the table consults self, @@ -212,6 +212,7 @@ async def acquire( # ruff:ignore[too-many-arguments] # one keyword per piece o via: Hashable, enter: Callable[[float], Awaitable[None]], joinable: Callable[[], bool], + raise_if_unusable: Callable[[], None], ) -> None: task = _current_task() timeout = resolve_read_write_timeout(timeout, blocking=blocking) @@ -220,7 +221,13 @@ async def acquire( # ruff:ignore[too-many-arguments] # one keyword per piece o try: while isinstance( admission := self._admit( - task, mode, lock_file, via=via, joinable=joinable, waiting_writer=waiting_writer + task, + mode, + lock_file, + via=via, + joinable=joinable, + waiting_writer=waiting_writer, + raise_if_unusable=raise_if_unusable, ), ConcurrentFuture, ): @@ -258,8 +265,10 @@ def _admit( # ruff:ignore[too-many-arguments] # the acquire's state, passed th via: Hashable, joinable: Callable[[], bool], waiting_writer: bool, + raise_if_unusable: Callable[[], None], ) -> Literal["held", "enter"] | ConcurrentFuture[None]: with self._lock: + raise_if_unusable() # A "held" answer trusts the backend level. Once the backend lost it, the holds are gone and the next task # has to take the lock again. if self._mode is not None and not self._transitioning and not joinable(): @@ -283,12 +292,12 @@ def _admit( # ruff:ignore[too-many-arguments] # the acquire's state, passed th if not self._holds and (mode == "write" or not writers_ahead): self._transitioning, self._mode = True, mode return "enter" - return self._ticket() + return self._ticket(via) - def _ticket(self) -> ConcurrentFuture[None]: + def _ticket(self, via: Hashable | None) -> ConcurrentFuture[None]: # Called under the table lock, in the section that decided to wait, so no state change slips in between. ticket: ConcurrentFuture[None] = ConcurrentFuture() - self._waiters[ticket] = None + self._waiters[ticket] = via return ticket def _forget(self, ticket: ConcurrentFuture[None]) -> None: @@ -314,6 +323,13 @@ def _finish_transition( self._holds.setdefault(task, _TaskHold(depths={})).depths.update(hold.depths) self._notify() + def wake_via(self, via: Hashable) -> None: + with self._lock: + for ticket, waiting_via in tuple(self._waiters.items()): + if waiting_via is via: + del self._waiters[ticket] + ticket.set_result(None) + async def release( self, *, @@ -408,7 +424,7 @@ def _drop_holds_via( # backend level) and the dropped holds. The table stays transitioning while that mode is left. with self._lock: if self._transitioning: - return self._ticket() + return self._ticket(None) if via is None: dropped = dict(self._holds) self._holds.clear() diff --git a/src/filelock/_async_read_write.py b/src/filelock/_async_read_write.py index dfd9d3f99..da185e217 100644 --- a/src/filelock/_async_read_write.py +++ b/src/filelock/_async_read_write.py @@ -226,6 +226,7 @@ def joinable() -> bool: via=self._via, enter=enter, joinable=joinable, + raise_if_unusable=self._raise_if_unusable, ) @property @@ -356,6 +357,7 @@ async def acquire_write( async def close(self) -> None: """ End the holds of the tasks that acquired through this instance and release the lock once no task holds it. + A successful close wakes tasks waiting for this wrapper's turn in the shared ownership table. After calling this method, the lock instance is no longer usable. With ``is_singleton=False`` it also closes the underlying SQLite connection. A singleton wrapper leaves the shared :class:`ReadWriteLock` open, so tasks that @@ -384,6 +386,8 @@ async def close(self) -> None: else: self._shutdown_owned_executor() raise + finally: + self._owners.wake_via(self._via) # Wait for the worker to exit rather than letting it drain in the background: a caller that forks right # after closing deserves a single-threaded process, and os.fork warns about any surviving thread. if self._owns_executor: diff --git a/src/filelock/_soft_rw/_async.py b/src/filelock/_soft_rw/_async.py index 95100cc3b..5a05cdb74 100644 --- a/src/filelock/_soft_rw/_async.py +++ b/src/filelock/_soft_rw/_async.py @@ -238,6 +238,7 @@ def joinable() -> bool: via=self._via, enter=enter, joinable=joinable, + raise_if_unusable=self._raise_if_unusable, ) async def _run_acquire(self, acquire: functools.partial[AcquireReturnProxy]) -> None: @@ -351,6 +352,7 @@ async def acquire_write( async def close(self) -> None: """ End the holds of the tasks that acquired through this instance and release the lock once no task holds it. + A successful close wakes tasks waiting for this wrapper's turn in the shared ownership table. Idempotent. After calling this method the instance can no longer acquire locks. With ``is_singleton=False`` it also closes the underlying :class:`SoftReadWriteLock`. A singleton wrapper leaves the shared one open, so tasks @@ -375,6 +377,8 @@ async def close(self) -> None: if not isinstance(error, asyncio.CancelledError) and self._backend_holds(): self._closed = False raise + finally: + self._owners.wake_via(self._via) def _reset_after_fork_in_child(self) -> None: # pragma: forked child self._creator_pid = -1 diff --git a/tests/soft_rw/test_soft_rw_async.py b/tests/soft_rw/test_soft_rw_async.py index 7a270c6c3..9b7b76ab7 100644 --- a/tests/soft_rw/test_soft_rw_async.py +++ b/tests/soft_rw/test_soft_rw_async.py @@ -835,6 +835,53 @@ def park() -> None: await asyncio.create_task(lock.acquire_read(timeout=5)) +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("held_mode", "waiting_mode"), + [pytest.param("write", "read", id="reader"), pytest.param("read", "write", id="writer")], +) +async def test_async_soft_close_wakes_its_table_waiter( + tmp_path: Path, held_mode: Literal["read", "write"], waiting_mode: Literal["read", "write"] +) -> None: + holder, closing = _make(tmp_path, is_singleton=True), _make(tmp_path, is_singleton=True) + await getattr(holder, f"acquire_{held_mode}")() + acquiring = asyncio.create_task(getattr(closing, f"acquire_{waiting_mode}")()) + try: + assert not (await asyncio.wait((acquiring,), timeout=0.05))[0] + + await closing.close() + + assert acquiring in (await asyncio.wait((acquiring,), timeout=1))[0] + with pytest.raises(RuntimeError, match="has been closed"): + await acquiring + finally: + await holder.close() + await asyncio.gather(acquiring, return_exceptions=True) + + +@pytest.mark.asyncio +async def test_async_soft_close_of_waiting_writer_unblocks_other_readers(tmp_path: Path) -> None: + holder, closing, reader = (_make(tmp_path, is_singleton=True) for _ in range(3)) + await holder.acquire_read() + acquiring_write = asyncio.create_task(closing.acquire_write()) + await asyncio.wait((acquiring_write,), timeout=0.05) + acquiring_read = asyncio.create_task(reader.acquire_read()) + try: + assert not acquiring_write.done() + assert not (await asyncio.wait((acquiring_read,), timeout=0.05))[0] + + await closing.close() + + with pytest.raises(RuntimeError, match="has been closed"): + await asyncio.wait_for(acquiring_write, 1) + await asyncio.wait_for(acquiring_read, 1) + assert not await asyncio.to_thread(_writer_gets_in, tmp_path) + finally: + await holder.close() + await reader.close() + await asyncio.gather(acquiring_write, acquiring_read, return_exceptions=True) + + @pytest.mark.asyncio async def test_async_soft_release_leaves_a_sync_reader_of_the_same_singleton_holding(tmp_path: Path) -> None: async_lock: Final[AsyncSoftReadWriteLock] = AsyncSoftReadWriteLock(str(tmp_path / "foo.lock")) diff --git a/tests/test_async_read_write.py b/tests/test_async_read_write.py index 5b96a9d9a..cf4f5843a 100644 --- a/tests/test_async_read_write.py +++ b/tests/test_async_read_write.py @@ -1049,6 +1049,77 @@ async def test_async_close_waits_out_an_acquire_in_flight_even_when_canceled(loc holder.close() +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("held_mode", "waiting_mode"), + [pytest.param("write", "read", id="reader"), pytest.param("read", "write", id="writer")], +) +async def test_async_close_wakes_its_table_waiter( + lock_file: str, held_mode: Literal["read", "write"], waiting_mode: Literal["read", "write"] +) -> None: + holder, closing = AsyncReadWriteLock(lock_file), AsyncReadWriteLock(lock_file) + await getattr(holder, f"acquire_{held_mode}")() + acquiring = asyncio.create_task(getattr(closing, f"acquire_{waiting_mode}")()) + try: + assert not (await asyncio.wait((acquiring,), timeout=0.05))[0] + + await closing.close() + + assert acquiring in (await asyncio.wait((acquiring,), timeout=1))[0] + with pytest.raises(sqlite3.ProgrammingError, match="closed database"): + await acquiring + finally: + await holder.close() + await asyncio.gather(acquiring, return_exceptions=True) + + +@pytest.mark.asyncio +async def test_async_close_of_waiting_writer_unblocks_other_readers(lock_file: str) -> None: + holder, closing, reader = (AsyncReadWriteLock(lock_file) for _ in range(3)) + await holder.acquire_read() + acquiring_write = asyncio.create_task(closing.acquire_write()) + await asyncio.wait((acquiring_write,), timeout=0.05) + acquiring_read = asyncio.create_task(reader.acquire_read()) + try: + assert not acquiring_write.done() + assert not (await asyncio.wait((acquiring_read,), timeout=0.05))[0] + + await closing.close() + + with pytest.raises(sqlite3.ProgrammingError, match="closed database"): + await asyncio.wait_for(acquiring_write, 1) + await asyncio.wait_for(acquiring_read, 1) + assert not writer_gets_in(lock_file) + finally: + await holder.close() + await reader.close() + await asyncio.gather(acquiring_write, acquiring_read, return_exceptions=True) + + +@pytest.mark.asyncio +async def test_async_failed_close_keeps_pending_acquire_waiting(lock_file: str, mocker: MockerFixture) -> None: + lock = AsyncReadWriteLock(lock_file) + await lock.acquire_read() + acquiring = asyncio.create_task(lock.acquire_write()) + await asyncio.wait((acquiring,), timeout=0.05) + release = mocker.patch.object( + ReadWriteLock, "_release_level_of", autospec=True, side_effect=sqlite3.OperationalError("release failed") + ) + try: + try: + with pytest.raises(sqlite3.OperationalError, match="release failed"): + await lock.close() + finally: + mocker.stop(release) + + assert not (await asyncio.wait((acquiring,), timeout=0.05))[0] + await lock.release() + await asyncio.wait_for(acquiring, 1) + finally: + await lock.close() + await asyncio.gather(acquiring, return_exceptions=True) + + @pytest.mark.asyncio async def test_async_close_that_fails_before_any_acquire_leaves_the_wrapper_closed( lock_file: str, mocker: MockerFixture From 22c79f4f9a867c6131c4f23706cc4313d70a5b83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Fri, 20 Nov 2026 07:23:29 -0800 Subject: [PATCH 2/8] =?UTF-8?q?=F0=9F=90=9B=20fix(async):=20keep=20grants?= =?UTF-8?q?=20on=20failed=20close?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A failed close could restore a backend hold after the waiting acquire had already raised the closed error. The task then had no proxy to release it. Wait for close to settle before resolving the acquire. On failure, the task keeps its hold. Cancellation releases it before reporting cancellation. Refs #1022 --- ...+async-rw-close-waiting-acquire.bugfix.rst | 3 + src/filelock/_async.py | 2 + src/filelock/_async_read_write.py | 41 +++- src/filelock/_soft_rw/_async.py | 26 +++ tests/soft_rw/test_soft_rw_async.py | 172 ++++++++++++++++- tests/test_async_read_write.py | 176 +++++++++++++++++- 6 files changed, 410 insertions(+), 10 deletions(-) create mode 100644 docs/changelog/+async-rw-close-waiting-acquire.bugfix.rst diff --git a/docs/changelog/+async-rw-close-waiting-acquire.bugfix.rst b/docs/changelog/+async-rw-close-waiting-acquire.bugfix.rst new file mode 100644 index 000000000..6a244c453 --- /dev/null +++ b/docs/changelog/+async-rw-close-waiting-acquire.bugfix.rst @@ -0,0 +1,3 @@ +If an async reader/writer lock grants an acquire while its wrapper is closing, the acquiring task waits for the +outcome. A successful close releases the hold and the acquire raises the closed error. If close fails with the lock +still held, the task receives its hold and can release it. diff --git a/src/filelock/_async.py b/src/filelock/_async.py index 0730543bf..7f383ea60 100644 --- a/src/filelock/_async.py +++ b/src/filelock/_async.py @@ -213,6 +213,7 @@ async def acquire( # ruff:ignore[too-many-arguments] # one keyword per piece o enter: Callable[[float], Awaitable[None]], joinable: Callable[[], bool], raise_if_unusable: Callable[[], None], + check_after_enter: Callable[[], Awaitable[None]], ) -> None: task = _current_task() timeout = resolve_read_write_timeout(timeout, blocking=blocking) @@ -255,6 +256,7 @@ async def acquire( # ruff:ignore[too-many-arguments] # one keyword per piece o self._finish_transition(mode=None) raise self._finish_transition(mode=mode, holds={task: _TaskHold(depths={via: 1})}) + await check_after_enter() def _admit( # ruff:ignore[too-many-arguments] # the acquire's state, passed through under the table lock self, diff --git a/src/filelock/_async_read_write.py b/src/filelock/_async_read_write.py index da185e217..b5336d89c 100644 --- a/src/filelock/_async_read_write.py +++ b/src/filelock/_async_read_write.py @@ -25,6 +25,7 @@ import os import sqlite3 # simplint: ignore[missing-lazy-module] # detect builds without SQLite at import time import threading +from concurrent.futures import Future as ConcurrentFuture from concurrent.futures import ThreadPoolExecutor from concurrent.futures import thread as executor_threads from contextlib import asynccontextmanager @@ -100,6 +101,7 @@ def __init__( # ruff:ignore[too-many-arguments] # public constructor: one para self._creator_pid = creator_pid self._fork_invalidated = False self._closed = False + self._closing: ConcurrentFuture[None] | None = None self._owns_backend = not is_singleton #: Marks the task holds taken through this wrapper, which its close() ends. self._via: Final = object() @@ -218,6 +220,22 @@ def joinable() -> bool: self._raise_if_unusable() return self._backend_holds() + async def check_after_enter() -> None: + cancellation: asyncio.CancelledError | None = None + while self._closed and (closing := self._closing) is not None: + try: + await wait_until_done(asyncio.wrap_future(closing)) + except asyncio.CancelledError as error: + cancellation = error + if cancellation is not None: + if not self._closed: + try: + await self.release(force=True) + except BaseException as error: # ruff:ignore[blind-except] # preserve cleanup errors with cancellation + raise_cancelled_error(cancellation, error) + raise cancellation + self._raise_if_unusable() + await self._owners.acquire( mode, timeout=timeout, @@ -227,6 +245,7 @@ def joinable() -> bool: enter=enter, joinable=joinable, raise_if_unusable=self._raise_if_unusable, + check_after_enter=check_after_enter, ) @property @@ -276,14 +295,6 @@ def _backend_holds(self) -> bool: # A sync close() or forced release on a shared singleton ends the tasks' level without the table taking part. return self._lock._holds_level_of(TASKS_THREAD_ID) # ruff:ignore[private-member-access] # the wrapper owns this backend hold - async def _release_in_context(self, body_error: BaseException | None) -> None: - try: - await self.release() - except BaseException as release_error: - if body_error is not None: - append_exception_context(release_error, body_error) - raise - async def release(self, *, force: bool = False) -> None: """ Release one level of the calling task's hold. @@ -307,6 +318,14 @@ async def release(self, *, force: bool = False) -> None: still_held=self._backend_holds, ) + async def _release_in_context(self, body_error: BaseException | None) -> None: + try: + await self.release() + except BaseException as release_error: + if body_error is not None: + append_exception_context(release_error, body_error) + raise + @asynccontextmanager async def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]: """ @@ -365,6 +384,9 @@ async def close(self) -> None: notices a synchronous ``close()`` or forced release of that shared lock. One that lands in the few bytecodes between that check and the admission still admits the task into the ended hold. + An acquire granted by the backend after this method starts raises the closed error if close succeeds. If close + fails with the backend still held, the acquire retains its hold. + """ ensure_current_process() if self._inherited: # pragma: needs fork @@ -372,6 +394,7 @@ async def close(self) -> None: if self._closed: return # Refuse acquires from here on, so none is admitted into a hold the backend is letting go of. + closing = self._closing = ConcurrentFuture() self._closed = True try: await self._owners.retire( @@ -387,6 +410,8 @@ async def close(self) -> None: self._shutdown_owned_executor() raise finally: + self._closing = None + closing.set_result(None) self._owners.wake_via(self._via) # Wait for the worker to exit rather than letting it drain in the background: a caller that forks right # after closing deserves a single-threaded process, and os.fork warns about any surviving thread. diff --git a/src/filelock/_soft_rw/_async.py b/src/filelock/_soft_rw/_async.py index 5a05cdb74..cae871187 100644 --- a/src/filelock/_soft_rw/_async.py +++ b/src/filelock/_soft_rw/_async.py @@ -11,6 +11,7 @@ __lazy_modules__ = [ "asyncio", + "concurrent.futures", "filelock._async", "filelock._error", "functools", @@ -22,6 +23,7 @@ import functools import os import threading +from concurrent.futures import Future as ConcurrentFuture from contextlib import asynccontextmanager from typing import TYPE_CHECKING, Final, Literal, ParamSpec, TypeVar @@ -100,6 +102,7 @@ def __init__( # ruff:ignore[too-many-arguments] # public constructor: one para ) -> None: self._creator_pid = os.getpid() self._closed = False + self._closing: ConcurrentFuture[None] | None = None self._owns_backend = not is_singleton #: Marks the task holds taken through this wrapper, which its close() ends. self._via: Final = object() @@ -230,6 +233,22 @@ def joinable() -> bool: raise lost_hold_error(self.lock_file, mode, compromise) return self._backend_holds() + async def check_after_enter() -> None: + cancellation: asyncio.CancelledError | None = None + while self._closed and (closing := self._closing) is not None: + try: + await wait_until_done(asyncio.wrap_future(closing)) + except asyncio.CancelledError as error: + cancellation = error + if cancellation is not None: + if not self._closed: + try: + await self.release(force=True) + except BaseException as error: # ruff:ignore[blind-except] # preserve cleanup errors with cancellation + raise_cancelled_error(cancellation, error) + raise cancellation + self._raise_if_unusable() + await self._owners.acquire( mode, timeout=self._lock.timeout if timeout is None else timeout, @@ -239,6 +258,7 @@ def joinable() -> bool: enter=enter, joinable=joinable, raise_if_unusable=self._raise_if_unusable, + check_after_enter=check_after_enter, ) async def _run_acquire(self, acquire: functools.partial[AcquireReturnProxy]) -> None: @@ -360,11 +380,15 @@ async def close(self) -> None: notices a synchronous ``close()`` or forced release of that shared lock. One that lands in the few bytecodes between that check and the admission still admits the task into the ended hold. + An acquire granted by the backend after this method starts raises the closed error if close succeeds. If close + fails with the backend still held, the acquire retains its hold. + """ ensure_current_process() if self._creator_pid != os.getpid() or self._closed: return # Refuse acquires from here on, so none is admitted into a hold the backend is letting go of. + closing = self._closing = ConcurrentFuture() self._closed = True try: await self._owners.retire( @@ -378,6 +402,8 @@ async def close(self) -> None: self._closed = False raise finally: + self._closing = None + closing.set_result(None) self._owners.wake_via(self._via) def _reset_after_fork_in_child(self) -> None: # pragma: forked child diff --git a/tests/soft_rw/test_soft_rw_async.py b/tests/soft_rw/test_soft_rw_async.py index 9b7b76ab7..595f52e25 100644 --- a/tests/soft_rw/test_soft_rw_async.py +++ b/tests/soft_rw/test_soft_rw_async.py @@ -25,7 +25,7 @@ from pytest_mock import MockerFixture - from filelock import LeaseCompromise + from filelock import AcquireReturnProxy, LeaseCompromise pytestmark: Final[pytest.MarkDecorator] = pytest.mark.requires_hard_links @@ -656,6 +656,176 @@ async def _read_and_probe(lock: AsyncSoftReadWriteLock) -> bool: return await asyncio.to_thread(_writer_gets_in, Path(lock.lock_file).parent) +@pytest.mark.parametrize("is_singleton", [pytest.param(True, id="singleton"), pytest.param(False, id="owned")]) +@pytest.mark.parametrize("mode", [pytest.param("read", id="read"), pytest.param("write", id="write")]) +@pytest.mark.asyncio +async def test_async_soft_acquire_waiting_in_backend_during_close_is_refused( + tmp_path: Path, is_singleton: bool, mode: Literal["read", "write"], mocker: MockerFixture +) -> None: + holder: Final[SoftReadWriteLock] = _make_sync(tmp_path) + holder.acquire_write() + lock: Final[AsyncSoftReadWriteLock] = _make(tmp_path, is_singleton=is_singleton) + granted, resume = asyncio.Event(), asyncio.Event() + run_acquire = lock._run_acquire + + async def gated_acquire(acquire: functools.partial[AcquireReturnProxy]) -> None: + await run_acquire(acquire) + granted.set() + await resume.wait() + + mocker.patch.object(lock, "_run_acquire", autospec=True, side_effect=gated_acquire) + acquiring = asyncio.create_task(getattr(lock, f"acquire_{mode}")(timeout=_TASK_WAIT)) + holder.release() + await granted.wait() + closing = asyncio.create_task(lock.close()) + await asyncio.sleep(0) + resume.set() + + with pytest.raises(RuntimeError, match="has been closed"): + await acquiring + await closing + + assert _writer_gets_in(tmp_path) + holder.close() + + +@pytest.mark.asyncio +async def test_async_soft_acquire_keeps_its_hold_when_close_fails(tmp_path: Path, mocker: MockerFixture) -> None: + holder: Final[SoftReadWriteLock] = _make_sync(tmp_path) + holder.acquire_write() + lock: Final[AsyncSoftReadWriteLock] = _make(tmp_path) + granted, resume, entered, finish = (asyncio.Event() for _ in range(4)) + run_acquire = lock._run_acquire + + async def gated_acquire(acquire: functools.partial[AcquireReturnProxy]) -> None: + await run_acquire(acquire) + granted.set() + await resume.wait() + + mocker.patch.object(lock, "_run_acquire", autospec=True, side_effect=gated_acquire) + + async def work() -> None: + async with lock.write_lock(timeout=_TASK_WAIT): + entered.set() + await finish.wait() + + acquiring = asyncio.create_task(work()) + holder.release() + await granted.wait() + mocker.patch.object(lock._lock, "close", autospec=True, side_effect=OSError("close failed")) + closing = asyncio.create_task(lock.close()) + await asyncio.sleep(0) + resume.set() + + with pytest.raises(OSError, match="close failed"): + await closing + await entered.wait() + assert not _writer_gets_in(tmp_path) + + finish.set() + await acquiring + assert _writer_gets_in(tmp_path) + mocker.stopall() + await lock.close() + holder.close() + + +@pytest.mark.parametrize( + ("release_error", "expected_error", "available"), + [ + pytest.param(None, asyncio.CancelledError, True, id="release-succeeds"), + pytest.param(OSError("release failed"), OSError, False, id="release-fails"), + ], +) +@pytest.mark.asyncio +async def test_async_soft_cancelled_acquire_after_failed_close_reconciles_hold( + tmp_path: Path, + mocker: MockerFixture, + release_error: OSError | None, + expected_error: type[BaseException], + available: bool, +) -> None: + holder: Final[SoftReadWriteLock] = _make_sync(tmp_path) + holder.acquire_write() + lock: Final[AsyncSoftReadWriteLock] = _make(tmp_path) + granted, resume = asyncio.Event(), asyncio.Event() + close_started, finish_close = threading.Event(), threading.Event() + run_acquire = lock._run_acquire + + async def gated_acquire(acquire: functools.partial[AcquireReturnProxy]) -> None: + await run_acquire(acquire) + granted.set() + await resume.wait() + + def fail_close() -> None: + close_started.set() + assert finish_close.wait(5) + msg = "close failed" + raise OSError(msg) + + mocker.patch.object(lock, "_leave_backend", autospec=True, wraps=lock._leave_backend, side_effect=release_error) + mocker.patch.object(lock, "_run_acquire", autospec=True, side_effect=gated_acquire) + acquiring = asyncio.create_task(lock.acquire_write(timeout=_TASK_WAIT)) + holder.release() + await granted.wait() + mocker.patch.object(lock._lock, "close", autospec=True, side_effect=fail_close) + closing = asyncio.create_task(lock.close()) + await asyncio.sleep(0) + resume.set() + assert await asyncio.to_thread(close_started.wait, 5) + acquiring.cancel() + finish_close.set() + + with pytest.raises(OSError, match="close failed"): + await closing + with pytest.raises(expected_error) as info: + await acquiring + assert isinstance(info.value.__context__, asyncio.CancelledError) is not available + assert _writer_gets_in(tmp_path) is available + mocker.stopall() + await lock.close() + assert _writer_gets_in(tmp_path) + holder.close() + + +@pytest.mark.asyncio +async def test_async_soft_cancelled_acquire_during_close_leaves_no_hold(tmp_path: Path, mocker: MockerFixture) -> None: + holder: Final[SoftReadWriteLock] = _make_sync(tmp_path) + holder.acquire_write() + lock: Final[AsyncSoftReadWriteLock] = _make(tmp_path) + granted, resume = asyncio.Event(), asyncio.Event() + close_started, finish_close = threading.Event(), threading.Event() + run_acquire, close_backend = lock._run_acquire, lock._lock.close + + async def gated_acquire(acquire: functools.partial[AcquireReturnProxy]) -> None: + await run_acquire(acquire) + granted.set() + await resume.wait() + + def paused_close() -> None: + close_started.set() + assert finish_close.wait(5) + close_backend() + + mocker.patch.object(lock, "_run_acquire", autospec=True, side_effect=gated_acquire) + acquiring = asyncio.create_task(lock.acquire_write(timeout=_TASK_WAIT)) + holder.release() + await granted.wait() + mocker.patch.object(lock._lock, "close", autospec=True, side_effect=paused_close) + closing = asyncio.create_task(lock.close()) + await asyncio.sleep(0) + resume.set() + assert await asyncio.to_thread(close_started.wait, 5) + acquiring.cancel() + finish_close.set() + + await closing + with pytest.raises(asyncio.CancelledError): + await acquiring + assert _writer_gets_in(tmp_path) + holder.close() + + @pytest.mark.asyncio async def test_async_soft_read_through_another_wrapper_during_close_holds_the_lock(tmp_path: Path) -> None: closing, other = _make(tmp_path, is_singleton=True), _make(tmp_path, is_singleton=True) diff --git a/tests/test_async_read_write.py b/tests/test_async_read_write.py index cf4f5843a..95ed7dd39 100644 --- a/tests/test_async_read_write.py +++ b/tests/test_async_read_write.py @@ -36,11 +36,14 @@ from filelock import AsyncReadWriteLock, FileLock, ReadWriteLock, Timeout if TYPE_CHECKING: + import functools from collections.abc import AsyncIterator, Callable, Generator from pathlib import Path from pytest_mock import MockerFixture + from filelock import AcquireReturnProxy + # Bounds every wait on another task, so a lock that never admits it fails the test instead of hanging the suite. _TASK_WAIT: Final[float] = 10 @@ -1041,7 +1044,8 @@ async def test_async_close_waits_out_an_acquire_in_flight_even_when_canceled(loc await asyncio.sleep(0) holder.release() - await acquiring + with pytest.raises(sqlite3.ProgrammingError, match="closed database"): + await acquiring with pytest.raises(asyncio.CancelledError): await closing @@ -1049,6 +1053,176 @@ async def test_async_close_waits_out_an_acquire_in_flight_even_when_canceled(loc holder.close() +@pytest.mark.parametrize("is_singleton", [pytest.param(True, id="singleton"), pytest.param(False, id="owned")]) +@pytest.mark.parametrize("mode", [pytest.param("read", id="read"), pytest.param("write", id="write")]) +@pytest.mark.asyncio +async def test_async_acquire_waiting_in_backend_during_close_is_refused( + lock_file: str, is_singleton: bool, mode: Literal["read", "write"], mocker: MockerFixture +) -> None: + holder: Final[ReadWriteLock] = ReadWriteLock(lock_file, is_singleton=False) + holder.acquire_write() + lock: Final[AsyncReadWriteLock] = AsyncReadWriteLock(lock_file, is_singleton=is_singleton) + granted, resume = asyncio.Event(), asyncio.Event() + run_acquire = lock._run_acquire + + async def gated_acquire(acquire: functools.partial[AcquireReturnProxy]) -> None: + await run_acquire(acquire) + granted.set() + await resume.wait() + + mocker.patch.object(lock, "_run_acquire", autospec=True, side_effect=gated_acquire) + acquiring = asyncio.create_task(getattr(lock, f"acquire_{mode}")(timeout=_TASK_WAIT)) + holder.release() + await granted.wait() + closing = asyncio.create_task(lock.close()) + await asyncio.sleep(0) + resume.set() + + with pytest.raises(sqlite3.ProgrammingError, match="closed database"): + await acquiring + await closing + + assert writer_gets_in(lock_file) + holder.close() + + +@pytest.mark.asyncio +async def test_async_acquire_keeps_its_hold_when_close_fails(lock_file: str, mocker: MockerFixture) -> None: + holder: Final[ReadWriteLock] = ReadWriteLock(lock_file, is_singleton=False) + holder.acquire_write() + lock: Final[AsyncReadWriteLock] = AsyncReadWriteLock(lock_file, is_singleton=False) + granted, resume, entered, finish = (asyncio.Event() for _ in range(4)) + run_acquire = lock._run_acquire + + async def gated_acquire(acquire: functools.partial[AcquireReturnProxy]) -> None: + await run_acquire(acquire) + granted.set() + await resume.wait() + + mocker.patch.object(lock, "_run_acquire", autospec=True, side_effect=gated_acquire) + + async def work() -> None: + async with lock.write_lock(timeout=_TASK_WAIT): + entered.set() + await finish.wait() + + acquiring = asyncio.create_task(work()) + holder.release() + await granted.wait() + mocker.patch.object(lock._lock, "close", autospec=True, side_effect=OSError("close failed")) + closing = asyncio.create_task(lock.close()) + await asyncio.sleep(0) + resume.set() + + with pytest.raises(OSError, match="close failed"): + await closing + await entered.wait() + assert not writer_gets_in(lock_file) + + finish.set() + await acquiring + assert writer_gets_in(lock_file) + mocker.stopall() + await lock.close() + holder.close() + + +@pytest.mark.parametrize( + ("release_error", "expected_error", "available"), + [ + pytest.param(None, asyncio.CancelledError, True, id="release-succeeds"), + pytest.param(OSError("release failed"), OSError, False, id="release-fails"), + ], +) +@pytest.mark.asyncio +async def test_async_cancelled_acquire_after_failed_close_reconciles_hold( + lock_file: str, + mocker: MockerFixture, + release_error: OSError | None, + expected_error: type[BaseException], + available: bool, +) -> None: + holder: Final[ReadWriteLock] = ReadWriteLock(lock_file, is_singleton=False) + holder.acquire_write() + lock: Final[AsyncReadWriteLock] = AsyncReadWriteLock(lock_file, is_singleton=False) + granted, resume = asyncio.Event(), asyncio.Event() + close_started, finish_close = threading.Event(), threading.Event() + run_acquire = lock._run_acquire + + async def gated_acquire(acquire: functools.partial[AcquireReturnProxy]) -> None: + await run_acquire(acquire) + granted.set() + await resume.wait() + + def fail_close() -> None: + close_started.set() + assert finish_close.wait(5) + msg = "close failed" + raise OSError(msg) + + mocker.patch.object(lock, "_leave_backend", autospec=True, wraps=lock._leave_backend, side_effect=release_error) + mocker.patch.object(lock, "_run_acquire", autospec=True, side_effect=gated_acquire) + acquiring = asyncio.create_task(lock.acquire_write(timeout=_TASK_WAIT)) + holder.release() + await granted.wait() + mocker.patch.object(lock._lock, "close", autospec=True, side_effect=fail_close) + closing = asyncio.create_task(lock.close()) + await asyncio.sleep(0) + resume.set() + assert await asyncio.to_thread(close_started.wait, 5) + acquiring.cancel() + finish_close.set() + + with pytest.raises(OSError, match="close failed"): + await closing + with pytest.raises(expected_error) as info: + await acquiring + assert isinstance(info.value.__context__, asyncio.CancelledError) is not available + assert writer_gets_in(lock_file) is available + mocker.stopall() + await lock.close() + assert writer_gets_in(lock_file) + holder.close() + + +@pytest.mark.asyncio +async def test_async_cancelled_acquire_during_close_leaves_no_hold(lock_file: str, mocker: MockerFixture) -> None: + holder: Final[ReadWriteLock] = ReadWriteLock(lock_file, is_singleton=False) + holder.acquire_write() + lock: Final[AsyncReadWriteLock] = AsyncReadWriteLock(lock_file, is_singleton=False) + granted, resume = asyncio.Event(), asyncio.Event() + close_started, finish_close = threading.Event(), threading.Event() + run_acquire, close_backend = lock._run_acquire, lock._lock.close + + async def gated_acquire(acquire: functools.partial[AcquireReturnProxy]) -> None: + await run_acquire(acquire) + granted.set() + await resume.wait() + + def paused_close() -> None: + close_started.set() + assert finish_close.wait(5) + close_backend() + + mocker.patch.object(lock, "_run_acquire", autospec=True, side_effect=gated_acquire) + acquiring = asyncio.create_task(lock.acquire_write(timeout=_TASK_WAIT)) + holder.release() + await granted.wait() + mocker.patch.object(lock._lock, "close", autospec=True, side_effect=paused_close) + closing = asyncio.create_task(lock.close()) + await asyncio.sleep(0) + resume.set() + assert await asyncio.to_thread(close_started.wait, 5) + acquiring.cancel() + finish_close.set() + + await closing + with pytest.raises(asyncio.CancelledError): + await acquiring + assert writer_gets_in(lock_file) + holder.close() + + @pytest.mark.asyncio @pytest.mark.parametrize( ("held_mode", "waiting_mode"), From 0c67d70e41feecd55e9e42858b10878d33c435ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Fri, 20 Nov 2026 07:24:31 -0800 Subject: [PATCH 3/8] =?UTF-8?q?=F0=9F=90=9B=20fix(async):=20interrupt=20ba?= =?UTF-8?q?ckend=20waits=20on=20close?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A close could wait indefinitely behind a task waiting for another process to release the lock. Stop pending SQLite and soft lock acquires on their next backend poll. Fixes #1016 --- .../+async-soft-close-wait.bugfix.rst | 1 + src/filelock/_async_read_write.py | 9 ++++- src/filelock/_soft_rw/_async.py | 9 ++++- tests/soft_rw/test_soft_rw_async.py | 39 +++++++++++++++++++ tests/test_async_read_write.py | 20 ++++++++++ 5 files changed, 74 insertions(+), 4 deletions(-) create mode 100644 docs/changelog/+async-soft-close-wait.bugfix.rst diff --git a/docs/changelog/+async-soft-close-wait.bugfix.rst b/docs/changelog/+async-soft-close-wait.bugfix.rst new file mode 100644 index 000000000..be591e753 --- /dev/null +++ b/docs/changelog/+async-soft-close-wait.bugfix.rst @@ -0,0 +1 @@ +Closing an ``AsyncReadWriteLock`` or ``AsyncSoftReadWriteLock`` stops its contended backend acquires on their next poll. diff --git a/src/filelock/_async_read_write.py b/src/filelock/_async_read_write.py index b5336d89c..00c35a956 100644 --- a/src/filelock/_async_read_write.py +++ b/src/filelock/_async_read_write.py @@ -260,7 +260,7 @@ def blocking(self) -> bool: async def _run_acquire(self, acquire: functools.partial[AcquireReturnProxy]) -> None: abandoned = threading.Event() - acquire_future = self._submit(acquire, cancel_check=abandoned.is_set) + acquire_future = self._submit(acquire, cancel_check=lambda: abandoned.is_set() or self._closed) try: await wait_until_done(acquire_future) except asyncio.CancelledError as cancellation: @@ -278,7 +278,11 @@ async def _run_acquire(self, acquire: functools.partial[AcquireReturnProxy]) -> except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below raise_cancelled_error(cancellation, error) raise - future_result(acquire_future) + try: + future_result(acquire_future) + except Timeout: + self._raise_if_unusable() + raise def _submit( self, func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs @@ -376,6 +380,7 @@ async def acquire_write( async def close(self) -> None: """ End the holds of the tasks that acquired through this instance and release the lock once no task holds it. + A contended backend acquire stops on its next poll after close starts. A successful close wakes tasks waiting for this wrapper's turn in the shared ownership table. After calling this method, the lock instance is no longer usable. With ``is_singleton=False`` it also closes the diff --git a/src/filelock/_soft_rw/_async.py b/src/filelock/_soft_rw/_async.py index cae871187..a8457a138 100644 --- a/src/filelock/_soft_rw/_async.py +++ b/src/filelock/_soft_rw/_async.py @@ -266,7 +266,7 @@ async def _run_acquire(self, acquire: functools.partial[AcquireReturnProxy]) -> # the cancellation has published its claim and started the heartbeat, which keeps the record fresh so no peer # evicts it. Wait the call out and hand the claim back, as AsyncReadWriteLock does. abandoned = threading.Event() - acquire_future = self._submit(acquire, cancel_check=abandoned.is_set) + acquire_future = self._submit(acquire, cancel_check=lambda: abandoned.is_set() or self._closed) try: await wait_until_done(acquire_future) except asyncio.CancelledError as cancellation: @@ -284,7 +284,11 @@ async def _run_acquire(self, acquire: functools.partial[AcquireReturnProxy]) -> except BaseException as error: # ruff:ignore[blind-except] # reported with the cancellation below raise_cancelled_error(cancellation, error) raise - future_result(acquire_future) + try: + future_result(acquire_future) + except Timeout: + self._raise_if_unusable() + raise def _submit( self, func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs @@ -379,6 +383,7 @@ async def close(self) -> None: that acquired through another wrapper and synchronous users of the same path keep their holds. The next acquire notices a synchronous ``close()`` or forced release of that shared lock. One that lands in the few bytecodes between that check and the admission still admits the task into the ended hold. + An acquire polling in the soft backend stops at its next contended poll when close starts. An acquire granted by the backend after this method starts raises the closed error if close succeeds. If close fails with the backend still held, the acquire retains its hold. diff --git a/tests/soft_rw/test_soft_rw_async.py b/tests/soft_rw/test_soft_rw_async.py index 595f52e25..21397e386 100644 --- a/tests/soft_rw/test_soft_rw_async.py +++ b/tests/soft_rw/test_soft_rw_async.py @@ -1052,6 +1052,45 @@ async def test_async_soft_close_of_waiting_writer_unblocks_other_readers(tmp_pat await asyncio.gather(acquiring_write, acquiring_read, return_exceptions=True) +@pytest.mark.asyncio +@pytest.mark.parametrize("is_singleton", [False, True]) +async def test_async_soft_close_stops_a_pending_acquire( + tmp_path: Path, is_singleton: bool, mocker: MockerFixture +) -> None: + holder = _make_sync(tmp_path) + holder.acquire_write(timeout=5) + lock = _make(tmp_path, is_singleton=is_singleton) + started = threading.Event() + create = OsFiles.create + + def observe_create( + files: OsFiles, + path: str, + data: bytes, + *, + durable: bool = False, + ) -> tuple[int, int]: + started.set() + return create(files, path, data, durable=durable) + + mocker.patch.object(OsFiles, "create", autospec=True, side_effect=observe_create) + acquiring = asyncio.create_task(lock.acquire_write()) + try: + assert await asyncio.to_thread(started.wait, 5) + assert not acquiring.done() + + closing = asyncio.create_task(lock.close()) + done, _ = await asyncio.wait((closing,), timeout=1) + assert closing in done + await closing + with pytest.raises(RuntimeError, match="has been closed"): + await acquiring + finally: + holder.close() + await asyncio.gather(acquiring, return_exceptions=True) + await lock.close() + + @pytest.mark.asyncio async def test_async_soft_release_leaves_a_sync_reader_of_the_same_singleton_holding(tmp_path: Path) -> None: async_lock: Final[AsyncSoftReadWriteLock] = AsyncSoftReadWriteLock(str(tmp_path / "foo.lock")) diff --git a/tests/test_async_read_write.py b/tests/test_async_read_write.py index 95ed7dd39..b421e6855 100644 --- a/tests/test_async_read_write.py +++ b/tests/test_async_read_write.py @@ -1053,6 +1053,26 @@ async def test_async_close_waits_out_an_acquire_in_flight_even_when_canceled(loc holder.close() +@pytest.mark.asyncio +@pytest.mark.parametrize("is_singleton", [pytest.param(False, id="owned"), pytest.param(True, id="singleton")]) +async def test_close_interrupts_backend_wait_while_peer_holds(lock_file: str, *, is_singleton: bool) -> None: + holder = ReadWriteLock(lock_file, is_singleton=False) + holder.acquire_write() + lock = AsyncReadWriteLock(lock_file, is_singleton=is_singleton) + acquiring = asyncio.create_task(lock.acquire_write()) + try: + await asyncio.sleep(0) + async with asyncio.timeout(2): + await lock.close() + with pytest.raises(sqlite3.ProgrammingError, match="closed database"): + await acquiring + assert not writer_gets_in(lock_file) + finally: + holder.close() + await asyncio.gather(acquiring, return_exceptions=True) + await lock.close() + + @pytest.mark.parametrize("is_singleton", [pytest.param(True, id="singleton"), pytest.param(False, id="owned")]) @pytest.mark.parametrize("mode", [pytest.param("read", id="read"), pytest.param("write", id="write")]) @pytest.mark.asyncio From 657b9579ee417dc4c055a2e552c1fb51065d69d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Fri, 20 Nov 2026 07:25:51 -0800 Subject: [PATCH 4/8] =?UTF-8?q?=F0=9F=90=9B=20fix(async):=20grant=20queued?= =?UTF-8?q?=20writers=20in=20order?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wake the first waiting writer when the lock is free. Keep its place until it enters or cancels so a returning writer cannot pass it. --- .../+async-rw-writer-wake.bugfix.rst | 2 + src/filelock/_async.py | 68 ++++++++++-------- tests/test_async_read_write.py | 70 +++++++++++++++++++ 3 files changed, 111 insertions(+), 29 deletions(-) create mode 100644 docs/changelog/+async-rw-writer-wake.bugfix.rst diff --git a/docs/changelog/+async-rw-writer-wake.bugfix.rst b/docs/changelog/+async-rw-writer-wake.bugfix.rst new file mode 100644 index 000000000..c0eb4caec --- /dev/null +++ b/docs/changelog/+async-rw-writer-wake.bugfix.rst @@ -0,0 +1,2 @@ +Async reader/writer wrappers that share a lock instance in one process grant queued writers access in arrival order. +Returning writers join the back of the queue, and new readers wait until queued writers have had their turn. diff --git a/src/filelock/_async.py b/src/filelock/_async.py index 7f383ea60..1a326f2e6 100644 --- a/src/filelock/_async.py +++ b/src/filelock/_async.py @@ -197,10 +197,12 @@ def __init__(self) -> None: asyncio.Task[object], _TaskHold # simplint: ignore[imprecise-annotation] # task results vary ] = {} self._transitioning = False - self._waiting_writers = 0 - #: One ticket per waiting call, settled on the next state change. A call that stops waiting takes its own out, - #: so one that times out or is canceled leaves nothing behind. - self._waiters: dict[ConcurrentFuture[None], Hashable | None] = {} + self._read_waiters: dict[ConcurrentFuture[None], Hashable] = {} + self._write_queue: dict[ + asyncio.Task[object], # simplint: ignore[imprecise-annotation] # task results vary + tuple[ConcurrentFuture[None], Hashable], + ] = {} + self._transition_waiters: set[ConcurrentFuture[None]] = set() async def acquire( # ruff:ignore[too-many-arguments] # one keyword per piece of wrapper state the table consults self, @@ -218,7 +220,6 @@ async def acquire( # ruff:ignore[too-many-arguments] # one keyword per piece o task = _current_task() timeout = resolve_read_write_timeout(timeout, blocking=blocking) deadline = None if not blocking or timeout < 0 else time.perf_counter() + timeout - waiting_writer = False try: while isinstance( admission := self._admit( @@ -227,7 +228,6 @@ async def acquire( # ruff:ignore[too-many-arguments] # one keyword per piece o lock_file, via=via, joinable=joinable, - waiting_writer=waiting_writer, raise_if_unusable=raise_if_unusable, ), ConcurrentFuture, @@ -235,18 +235,14 @@ async def acquire( # ruff:ignore[too-many-arguments] # one keyword per piece o try: if not blocking or (deadline is not None and time.perf_counter() >= deadline): raise Timeout(lock_file) - if mode == "write" and not waiting_writer: - waiting_writer = True - with self._lock: - self._waiting_writers += 1 wait = None if deadline is None else deadline - time.perf_counter() await asyncio.wait((asyncio.wrap_future(admission),), timeout=wait) finally: self._forget(admission) finally: - if waiting_writer: + if mode == "write": with self._lock: - self._waiting_writers -= 1 + self._write_queue.pop(task, None) self._notify() if admission == "held": return @@ -266,7 +262,6 @@ def _admit( # ruff:ignore[too-many-arguments] # the acquire's state, passed th *, via: Hashable, joinable: Callable[[], bool], - waiting_writer: bool, raise_if_unusable: Callable[[], None], ) -> Literal["held", "enter"] | ConcurrentFuture[None]: with self._lock: @@ -276,6 +271,7 @@ def _admit( # ruff:ignore[too-many-arguments] # the acquire's state, passed th if self._mode is not None and not self._transitioning and not joinable(): self._holds.clear() self._mode = None + self._notify() if (hold := self._holds.get(task)) is not None: if self._mode != mode: msg = ( @@ -286,30 +282,39 @@ def _admit( # ruff:ignore[too-many-arguments] # the acquire's state, passed th raise RuntimeError(msg) hold.depths[via] = hold.depths.get(via, 0) + 1 return "held" - writers_ahead = self._waiting_writers - waiting_writer if not self._transitioning: - if mode == "read" and self._mode == "read" and not writers_ahead: + if mode == "read" and self._mode == "read" and not self._write_queue: self._holds[task] = _TaskHold(depths={via: 1}) return "held" - if not self._holds and (mode == "write" or not writers_ahead): + if not self._holds and next(iter(self._write_queue), task) is task: self._transitioning, self._mode = True, mode return "enter" - return self._ticket(via) - - def _ticket(self, via: Hashable | None) -> ConcurrentFuture[None]: - # Called under the table lock, in the section that decided to wait, so no state change slips in between. - ticket: ConcurrentFuture[None] = ConcurrentFuture() - self._waiters[ticket] = via - return ticket + ticket: ConcurrentFuture[None] = ConcurrentFuture() + if mode == "write": + self._write_queue[task] = ticket, via + else: + self._read_waiters[ticket] = via + return ticket def _forget(self, ticket: ConcurrentFuture[None]) -> None: with self._lock: - self._waiters.pop(ticket, None) + self._read_waiters.pop(ticket, None) + self._transition_waiters.discard(ticket) def _notify(self) -> None: - waiters, self._waiters = self._waiters, {} - for ticket in waiters: + if self._transitioning: + return + for ticket in self._transition_waiters: ticket.set_result(None) + self._transition_waiters.clear() + if self._write_queue: + ticket, _ = next(iter(self._write_queue.values())) + if not self._holds and not ticket.done(): + ticket.set_result(None) + elif self._mode != "write": + for ticket in self._read_waiters: + ticket.set_result(None) + self._read_waiters.clear() def _finish_transition( self, @@ -327,9 +332,12 @@ def _finish_transition( def wake_via(self, via: Hashable) -> None: with self._lock: - for ticket, waiting_via in tuple(self._waiters.items()): + for ticket, waiting_via in tuple(self._read_waiters.items()): if waiting_via is via: - del self._waiters[ticket] + del self._read_waiters[ticket] + ticket.set_result(None) + for ticket, waiting_via in self._write_queue.values(): + if waiting_via is via and not ticket.done(): ticket.set_result(None) async def release( @@ -426,7 +434,9 @@ def _drop_holds_via( # backend level) and the dropped holds. The table stays transitioning while that mode is left. with self._lock: if self._transitioning: - return self._ticket(None) + ticket: ConcurrentFuture[None] = ConcurrentFuture() + self._transition_waiters.add(ticket) + return ticket if via is None: dropped = dict(self._holds) self._holds.clear() diff --git a/tests/test_async_read_write.py b/tests/test_async_read_write.py index b421e6855..436b9fdb0 100644 --- a/tests/test_async_read_write.py +++ b/tests/test_async_read_write.py @@ -515,6 +515,54 @@ async def _write_once(lock: AsyncReadWriteLock) -> None: pass +@pytest.mark.asyncio +async def test_many_waiting_writers_drain_after_reader_releases(lock_file: str) -> None: + lock = AsyncReadWriteLock(lock_file, is_singleton=False) + await lock.acquire_read() + started = 0 + all_started = asyncio.Event() + completed: list[int] = [] + writer_count = 1200 + + async def write(position: int) -> None: + nonlocal started + started += 1 + if started == writer_count: + all_started.set() + async with lock.write_lock(timeout=_TASK_WAIT): + completed.append(position) + + tasks = [asyncio.create_task(write(index)) for index in range(writer_count)] + await asyncio.wait_for(all_started.wait(), _TASK_WAIT) + await asyncio.sleep(0) + assert not any(task.done() for task in tasks) + await lock.release() + await asyncio.wait_for(asyncio.gather(*tasks), 5) + await lock.close() + + assert completed == list(range(writer_count)) + + +@pytest.mark.asyncio +async def test_queued_writer_precedes_a_reacquiring_writer(lock_file: str) -> None: + lock = AsyncReadWriteLock(lock_file, is_singleton=False) + order: list[str] = [] + + async def queued() -> None: + async with lock.write_lock(timeout=_TASK_WAIT): + order.append("queued") + + async with lock.write_lock(): + waiting = asyncio.create_task(queued()) + await asyncio.sleep(0) + async with lock.write_lock(timeout=_TASK_WAIT): + order.append("returning") + await waiting + await lock.close() + + assert order == ["queued", "returning"] + + @pytest.mark.asyncio @XFAIL_WITHOUT_COROUTINE_CANCELLATION async def test_a_canceled_waiting_writer_lets_readers_in(lock_file: str) -> None: @@ -1267,6 +1315,28 @@ async def test_async_close_wakes_its_table_waiter( await asyncio.gather(acquiring, return_exceptions=True) +@pytest.mark.asyncio +async def test_closing_first_writer_preserves_next_writer(lock_file: str) -> None: + holder, first, second = (AsyncReadWriteLock(lock_file) for _ in range(3)) + await holder.acquire_read() + first_wait = asyncio.create_task(_write_once(first)) + second_wait = asyncio.create_task(_write_once(second)) + try: + await asyncio.sleep(0) + await first.close() + with pytest.raises(sqlite3.ProgrammingError, match="closed database"): + await first_wait + assert not second_wait.done() + await holder.release() + await asyncio.wait_for(second_wait, _TASK_WAIT) + assert writer_gets_in(lock_file) + finally: + await holder.close() + await first.close() + await second.close() + await asyncio.gather(first_wait, second_wait, return_exceptions=True) + + @pytest.mark.asyncio async def test_async_close_of_waiting_writer_unblocks_other_readers(lock_file: str) -> None: holder, closing, reader = (AsyncReadWriteLock(lock_file) for _ in range(3)) From 6077dc89b848c38502333fdc315fd6a400b3ab1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Fri, 20 Nov 2026 07:26:19 -0800 Subject: [PATCH 5/8] =?UTF-8?q?=F0=9F=90=9B=20fix(soft-rw):=20isolate=20as?= =?UTF-8?q?ync=20lock=20workers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A wait on one async soft read/write lock could occupy the event loop's default pool while another lock's release remained queued. Give each default wrapper an owned worker so the blocked wait cannot delay that release. Caller-supplied executors remain caller-owned and need enough capacity for concurrent waits and releases. --- .../+async-soft-rw-executor.security.rst | 1 + docs/how-to.rst | 14 ++-- src/filelock/_soft_rw/_async.py | 35 ++++++++-- tests/soft_rw/test_soft_rw_async.py | 67 ++++++++++++++++++- 4 files changed, 105 insertions(+), 12 deletions(-) create mode 100644 docs/changelog/+async-soft-rw-executor.security.rst diff --git a/docs/changelog/+async-soft-rw-executor.security.rst b/docs/changelog/+async-soft-rw-executor.security.rst new file mode 100644 index 000000000..177f445c0 --- /dev/null +++ b/docs/changelog/+async-soft-rw-executor.security.rst @@ -0,0 +1 @@ +Give each default ``AsyncSoftReadWriteLock`` its own worker so waits on shared locks cannot delay releases of unrelated locks. diff --git a/docs/how-to.rst b/docs/how-to.rst index 728d0fab0..cad44dd4b 100644 --- a/docs/how-to.rst +++ b/docs/how-to.rst @@ -824,11 +824,15 @@ For a shared filesystem whose marker and cache behavior has been verified, use async with rw.read_lock(): data = await get_shared_data() -It takes the same tuning as its synchronous peer plus the async pair, so the full signature is -``AsyncSoftReadWriteLock(lock_file, timeout=-1, *, blocking=True, is_singleton=True, heartbeat_interval=30.0, -stale_threshold=None, poll_interval=0.25, on_compromise=None, loop=None, executor=None)``. It has no SQLite thread -affinity to respect, so ``executor=None`` means the loop's default executor: it creates nothing and owns nothing. Its -``close()`` ends this wrapper's holds and wakes acquires waiting for another async wrapper's hold. +By default, each wrapper starts a worker thread on its first backend call. Call ``await rw.close()`` when you finish +with the wrapper to shut down its executor. If you pass an executor, reserve capacity for releases while acquires are +waiting, and shut it down yourself. + +When async wrappers share a lock instance in one process, they serve queued writers in arrival order before admitting +new readers. Closing a wrapper wakes tasks waiting through it and interrupts a contended backend acquire on its next +poll. If an acquire obtains the +lock while close is in progress, it waits for the outcome. A successful close releases the hold. If close fails with +the lock still held, the acquiring task keeps it and can release it. ************************************** Detect stale locks (soft locks only) diff --git a/src/filelock/_soft_rw/_async.py b/src/filelock/_soft_rw/_async.py index a8457a138..42f026c8f 100644 --- a/src/filelock/_soft_rw/_async.py +++ b/src/filelock/_soft_rw/_async.py @@ -24,6 +24,8 @@ import os import threading from concurrent.futures import Future as ConcurrentFuture +from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import thread as executor_threads from contextlib import asynccontextmanager from typing import TYPE_CHECKING, Final, Literal, ParamSpec, TypeVar @@ -47,7 +49,7 @@ ) if TYPE_CHECKING: - from collections.abc import AsyncGenerator, Callable + from collections.abc import AsyncGenerator, Callable, MutableMapping from concurrent import futures from types import TracebackType @@ -80,7 +82,9 @@ class AsyncSoftReadWriteLock: :param on_compromise: called from the heartbeat thread with a :class:`~filelock.LeaseCompromise` when the hold is lost :param loop: event loop for ``run_in_executor``; ``None`` uses the running loop - :param executor: executor for ``run_in_executor``; ``None`` uses the default executor + :param executor: executor for ``run_in_executor``. When ``None`` this lock creates and owns a dedicated + single-thread executor and shuts it down in :meth:`close`. A caller-supplied executor is not shut down and + needs enough workers for each concurrent wait and release. .. versionadded:: 3.27.0 @@ -118,9 +122,15 @@ def __init__( # ruff:ignore[too-many-arguments] # public constructor: one para ) self._owners = task_owners_for(self._lock) self._loop = loop - self._executor = executor + self._owns_executor = executor is None + self._executor = ThreadPoolExecutor(max_workers=1) if executor is None else executor register_fork_object(self) + def __del__(self, _getpid: Callable[[], int] = os.getpid) -> None: + # Keep getpid available after module globals are cleared during interpreter shutdown. + if _getpid() == getattr(self, "_creator_pid", None) and getattr(self, "_owns_executor", False): + self._executor.shutdown(wait=False) + @property def timeout(self) -> float: """The default timeout applied when ``acquire_read`` / ``acquire_write`` is called without one.""" @@ -147,8 +157,8 @@ def loop(self) -> asyncio.AbstractEventLoop | None: return self._loop @property - def executor(self) -> futures.Executor | None: - """The executor used for ``run_in_executor``, or ``None`` for the default executor.""" + def executor(self) -> futures.Executor: + """The executor used for ``run_in_executor`` (a dedicated single-thread one if none was supplied).""" return self._executor @asynccontextmanager @@ -405,14 +415,27 @@ async def close(self) -> None: # Only a failed backend call can leave the level held, and then a retried close() has to find it. if not isinstance(error, asyncio.CancelledError) and self._backend_holds(): self._closed = False + elif self._owns_executor: + self._executor.shutdown(wait=False) raise finally: self._closing = None closing.set_result(None) self._owners.wake_via(self._via) + if self._owns_executor: + self._executor.shutdown(wait=False) - def _reset_after_fork_in_child(self) -> None: # pragma: forked child + # The fork registry calls this method by name. + def _reset_after_fork_in_child(self) -> None: # pragma: forked child # simplint: ignore[unused-definition] self._creator_pid = -1 + if self._owns_executor: + # The worker did not survive the fork, but older runtimes still try to wake it at child exit. + registry = cast( + "MutableMapping[threading.Thread, object]", + executor_threads._threads_queues, # ruff:ignore[private-member-access] # the exit hook's registry + ) + for worker in cast("ThreadPoolExecutor", self._executor)._threads: # ruff:ignore[private-member-access] # only the executor lists its workers + registry.pop(worker, None) class AsyncAcquireSoftReadWriteReturnProxy: diff --git a/tests/soft_rw/test_soft_rw_async.py b/tests/soft_rw/test_soft_rw_async.py index 21397e386..886cd359f 100644 --- a/tests/soft_rw/test_soft_rw_async.py +++ b/tests/soft_rw/test_soft_rw_async.py @@ -90,7 +90,7 @@ async def test_async_exposes_configuration(tmp_path: Path) -> None: assert lock.timeout == 5 assert lock.blocking is False assert lock.loop is None - assert lock.executor is None + assert isinstance(lock.executor, ThreadPoolExecutor) assert lock.generation is None assert lock.compromise is None finally: @@ -211,6 +211,71 @@ async def test_async_custom_loop_and_executor(tmp_path: Path) -> None: pass finally: await lock.close() + assert await loop.run_in_executor(executor, lambda: True) + + +@pytest.mark.asyncio +async def test_async_owned_executor_stops_after_close(tmp_path: Path) -> None: + lock = _make(tmp_path) + async with lock.write_lock(timeout=2): + pass + executor = lock.executor + await lock.close() + + with pytest.raises(RuntimeError, match="shutdown"): + executor.submit(lambda: None) + + +def test_async_close_after_default_executor_shutdown(tmp_path: Path) -> None: + async def run() -> None: + lock = _make(tmp_path) + async with lock.write_lock(timeout=2): + pass + await asyncio.get_running_loop().shutdown_default_executor() + await lock.close() + + with pytest.raises(RuntimeError, match="shutdown"): + lock.executor.submit(lambda: None) + + asyncio.run(run()) + + +def test_async_default_executor_wait_does_not_block_another_release(tmp_path: Path, mocker: MockerFixture) -> None: + async def run() -> None: + with ThreadPoolExecutor(max_workers=1) as worker: + asyncio.get_running_loop().set_default_executor(worker) + holder = _make(tmp_path, "private.lock") + waiter = _make(tmp_path, "shared.lock") + holding = asyncio.Event() + release_requested = asyncio.Event() + + async def hold() -> None: + await holder.acquire_write(timeout=2) + holding.set() + await release_requested.wait() + await holder.release() + + holder_task = asyncio.create_task(hold()) + await holding.wait() + gate = _Gate(mocker, "_acquire_level_of", SoftReadWriteLock._acquire_level_of) + + async def wait() -> None: + await waiter.acquire_write(timeout=5) + await waiter.release() + + waiting = asyncio.create_task(wait()) + await gate.started.wait() + release_requested.set() + try: + await asyncio.wait_for(asyncio.shield(holder_task), 0.5) + finally: + gate.resume() + await holder_task + await waiting + await holder.close() + await waiter.close() + + asyncio.run(run()) @pytest.mark.asyncio From 1145f0431558f87f8fe027fae88066831b0c01c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Fri, 20 Nov 2026 11:35:11 -0800 Subject: [PATCH 6/8] =?UTF-8?q?=F0=9F=90=9B=20fix(async):=20close=20past?= =?UTF-8?q?=20a=20sibling's=20acquire?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A pending backend acquire owns no task holds. Let another singleton wrapper close without waiting for that acquire. Keep waiting when the closing wrapper started the acquire or owns the backend. --- .../+async-soft-close-wait.bugfix.rst | 1 + docs/how-to.rst | 10 +++++--- src/filelock/_async.py | 13 +++++----- tests/test_async_read_write.py | 25 ++++++++++++++++++- 4 files changed, 38 insertions(+), 11 deletions(-) diff --git a/docs/changelog/+async-soft-close-wait.bugfix.rst b/docs/changelog/+async-soft-close-wait.bugfix.rst index be591e753..63e0c7338 100644 --- a/docs/changelog/+async-soft-close-wait.bugfix.rst +++ b/docs/changelog/+async-soft-close-wait.bugfix.rst @@ -1 +1,2 @@ Closing an ``AsyncReadWriteLock`` or ``AsyncSoftReadWriteLock`` stops its contended backend acquires on their next poll. +A singleton wrapper can close while another wrapper waits to acquire the backend. diff --git a/docs/how-to.rst b/docs/how-to.rst index cad44dd4b..e0d589efc 100644 --- a/docs/how-to.rst +++ b/docs/how-to.rst @@ -829,10 +829,12 @@ with the wrapper to shut down its executor. If you pass an executor, reserve cap waiting, and shut it down yourself. When async wrappers share a lock instance in one process, they serve queued writers in arrival order before admitting -new readers. Closing a wrapper wakes tasks waiting through it and interrupts a contended backend acquire on its next -poll. If an acquire obtains the -lock while close is in progress, it waits for the outcome. A successful close releases the hold. If close fails with -the lock still held, the acquiring task keeps it and can release it. +new readers. If the first writer's event loop pauses, later writers and new readers wait until that loop runs again. + +Closing a wrapper wakes tasks waiting through it and interrupts its own contended backend acquire on the next poll. +A singleton wrapper can close while another wrapper waits to acquire the backend. If an acquire obtains the lock while +its wrapper is closing, it waits for the outcome. A successful close releases the hold. If close fails with the lock +still held, the acquiring task keeps it and can release it. ************************************** Detect stale locks (soft locks only) diff --git a/src/filelock/_async.py b/src/filelock/_async.py index 1a326f2e6..77ee18b91 100644 --- a/src/filelock/_async.py +++ b/src/filelock/_async.py @@ -197,6 +197,7 @@ def __init__(self) -> None: asyncio.Task[object], _TaskHold # simplint: ignore[imprecise-annotation] # task results vary ] = {} self._transitioning = False + self._entering_via: Hashable | None = None self._read_waiters: dict[ConcurrentFuture[None], Hashable] = {} self._write_queue: dict[ asyncio.Task[object], # simplint: ignore[imprecise-annotation] # task results vary @@ -287,7 +288,7 @@ def _admit( # ruff:ignore[too-many-arguments] # the acquire's state, passed th self._holds[task] = _TaskHold(depths={via: 1}) return "held" if not self._holds and next(iter(self._write_queue), task) is task: - self._transitioning, self._mode = True, mode + self._transitioning, self._mode, self._entering_via = True, mode, via return "enter" ticket: ConcurrentFuture[None] = ConcurrentFuture() if mode == "write": @@ -324,7 +325,7 @@ def _finish_transition( | None = None, ) -> None: with self._lock: - self._transitioning, self._mode = False, mode + self._transitioning, self._mode, self._entering_via = False, mode, None if mode is not None and holds: for task, hold in holds.items(): self._holds.setdefault(task, _TaskHold(depths={})).depths.update(hold.depths) @@ -394,10 +395,8 @@ async def retire( # End the holds taken through *via*, or every hold when it is ``None``, as one transition. # # Leaves the backend through *leave* when that ends the last hold, and always when *via* is ``None``. Arrivals - # wait while it runs, so none joins a hold the backend is letting go of. A transition already under way is - # waited - # out first: a task entering through *via* must not get a hold after the wrapper is gone. A cancellation is - # raised once the holds are settled. + # wait while it runs, so none joins a hold the backend is letting go of. A singleton wrapper can close while + # another wrapper enters the backend: the entering wrapper owns the only prospective hold. cancellation: asyncio.CancelledError | None = None while isinstance(settled := self._drop_holds_via(via), ConcurrentFuture): try: @@ -434,6 +433,8 @@ def _drop_holds_via( # backend level) and the dropped holds. The table stays transitioning while that mode is left. with self._lock: if self._transitioning: + if via is not None and self._entering_via is not None and self._entering_via is not via: + return None, {} ticket: ConcurrentFuture[None] = ConcurrentFuture() self._transition_waiters.add(ticket) return ticket diff --git a/tests/test_async_read_write.py b/tests/test_async_read_write.py index 436b9fdb0..032bb4892 100644 --- a/tests/test_async_read_write.py +++ b/tests/test_async_read_write.py @@ -33,7 +33,7 @@ import sqlite3 -from filelock import AsyncReadWriteLock, FileLock, ReadWriteLock, Timeout +from filelock import AsyncReadWriteLock, AsyncSoftReadWriteLock, FileLock, ReadWriteLock, Timeout if TYPE_CHECKING: import functools @@ -1101,6 +1101,29 @@ async def test_async_close_waits_out_an_acquire_in_flight_even_when_canceled(loc holder.close() +@pytest.mark.parametrize( + "lock_type", [pytest.param(AsyncReadWriteLock, id="sqlite"), pytest.param(AsyncSoftReadWriteLock, id="soft")] +) +@pytest.mark.asyncio +async def test_singleton_close_returns_while_another_wrapper_enters( + lock_file: str, lock_type: type[AsyncReadWriteLock | AsyncSoftReadWriteLock] +) -> None: + holder = lock_type(lock_file, is_singleton=False) + waiting, idle = lock_type(lock_file), lock_type(lock_file) + async with holder.write_lock(): + acquiring = asyncio.create_task(waiting.acquire_write()) + await asyncio.sleep(0) + closing = asyncio.create_task(idle.close()) + done, _ = await asyncio.wait({closing}, timeout=2) + try: + await acquiring + await closing + assert closing in done + finally: + await waiting.close() + await holder.close() + + @pytest.mark.asyncio @pytest.mark.parametrize("is_singleton", [pytest.param(False, id="owned"), pytest.param(True, id="singleton")]) async def test_close_interrupts_backend_wait_while_peer_holds(lock_file: str, *, is_singleton: bool) -> None: From e8b6b4b3123d7ec2d99ae03cca1dc3dc4f623e41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Fri, 20 Nov 2026 11:36:00 -0800 Subject: [PATCH 7/8] =?UTF-8?q?=F0=9F=90=9B=20fix(soft-rw):=20join=20the?= =?UTF-8?q?=20worker=20on=20close?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../changelog/+async-soft-rw-executor.bugfix.rst | 2 ++ .../+async-soft-rw-executor.security.rst | 1 - src/filelock/_soft_rw/_async.py | 9 ++++++++- tests/soft_rw/test_soft_rw_async.py | 16 ++++++++++++---- 4 files changed, 22 insertions(+), 6 deletions(-) create mode 100644 docs/changelog/+async-soft-rw-executor.bugfix.rst delete mode 100644 docs/changelog/+async-soft-rw-executor.security.rst diff --git a/docs/changelog/+async-soft-rw-executor.bugfix.rst b/docs/changelog/+async-soft-rw-executor.bugfix.rst new file mode 100644 index 000000000..daea8085d --- /dev/null +++ b/docs/changelog/+async-soft-rw-executor.bugfix.rst @@ -0,0 +1,2 @@ +Each default ``AsyncSoftReadWriteLock`` uses a private worker so a contended acquire cannot delay releases on unrelated +locks. Awaiting ``close()`` waits for that worker to exit. diff --git a/docs/changelog/+async-soft-rw-executor.security.rst b/docs/changelog/+async-soft-rw-executor.security.rst deleted file mode 100644 index 177f445c0..000000000 --- a/docs/changelog/+async-soft-rw-executor.security.rst +++ /dev/null @@ -1 +0,0 @@ -Give each default ``AsyncSoftReadWriteLock`` its own worker so waits on shared locks cannot delay releases of unrelated locks. diff --git a/src/filelock/_soft_rw/_async.py b/src/filelock/_soft_rw/_async.py index 42f026c8f..946453778 100644 --- a/src/filelock/_soft_rw/_async.py +++ b/src/filelock/_soft_rw/_async.py @@ -386,7 +386,7 @@ async def acquire_write( async def close(self) -> None: """ End the holds of the tasks that acquired through this instance and release the lock once no task holds it. - A successful close wakes tasks waiting for this wrapper's turn in the shared ownership table. + Closing wakes tasks waiting to acquire through this wrapper and joins the worker if the wrapper owns it. Idempotent. After calling this method the instance can no longer acquire locks. With ``is_singleton=False`` it also closes the underlying :class:`SoftReadWriteLock`. A singleton wrapper leaves the shared one open, so tasks @@ -423,7 +423,14 @@ async def close(self) -> None: closing.set_result(None) self._owners.wake_via(self._via) if self._owns_executor: + # Jobs on the lock's executor may need the loop to finish, even after the loop's default pool shuts down. self._executor.shutdown(wait=False) + joiner = ThreadPoolExecutor(max_workers=1) + joined = joiner.submit(self._executor.shutdown) + try: + await asyncio.shield(asyncio.wrap_future(joined)) + finally: + joiner.shutdown(wait=joined.done()) # The fork registry calls this method by name. def _reset_after_fork_in_child(self) -> None: # pragma: forked child # simplint: ignore[unused-definition] diff --git a/tests/soft_rw/test_soft_rw_async.py b/tests/soft_rw/test_soft_rw_async.py index 886cd359f..f04d9e0ce 100644 --- a/tests/soft_rw/test_soft_rw_async.py +++ b/tests/soft_rw/test_soft_rw_async.py @@ -216,12 +216,20 @@ async def test_async_custom_loop_and_executor(tmp_path: Path) -> None: @pytest.mark.asyncio async def test_async_owned_executor_stops_after_close(tmp_path: Path) -> None: - lock = _make(tmp_path) - async with lock.write_lock(timeout=2): - pass + lock = _make(tmp_path, is_singleton=True) executor = lock.executor - await lock.close() + worker = await asyncio.wrap_future(executor.submit(threading.current_thread)) + resume = threading.Event() + executor.submit(resume.wait, _TASK_WAIT) + closing = asyncio.create_task(lock.close()) + try: + await asyncio.sleep(0) + assert not closing.done() + finally: + resume.set() + await closing + assert not worker.is_alive() with pytest.raises(RuntimeError, match="shutdown"): executor.submit(lambda: None) From 00834b933889ff9c3ae11a03e3a8c63f2d88524c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Fri, 20 Nov 2026 11:55:52 -0800 Subject: [PATCH 8/8] =?UTF-8?q?=F0=9F=A7=AA=20test(async):=20exercise=20bo?= =?UTF-8?q?th=20singleton=20backends?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_async_read_write.py | 25 +--------------------- tests/test_async_read_write_cancel_wait.py | 20 +++++++++++++++++ 2 files changed, 21 insertions(+), 24 deletions(-) diff --git a/tests/test_async_read_write.py b/tests/test_async_read_write.py index 032bb4892..436b9fdb0 100644 --- a/tests/test_async_read_write.py +++ b/tests/test_async_read_write.py @@ -33,7 +33,7 @@ import sqlite3 -from filelock import AsyncReadWriteLock, AsyncSoftReadWriteLock, FileLock, ReadWriteLock, Timeout +from filelock import AsyncReadWriteLock, FileLock, ReadWriteLock, Timeout if TYPE_CHECKING: import functools @@ -1101,29 +1101,6 @@ async def test_async_close_waits_out_an_acquire_in_flight_even_when_canceled(loc holder.close() -@pytest.mark.parametrize( - "lock_type", [pytest.param(AsyncReadWriteLock, id="sqlite"), pytest.param(AsyncSoftReadWriteLock, id="soft")] -) -@pytest.mark.asyncio -async def test_singleton_close_returns_while_another_wrapper_enters( - lock_file: str, lock_type: type[AsyncReadWriteLock | AsyncSoftReadWriteLock] -) -> None: - holder = lock_type(lock_file, is_singleton=False) - waiting, idle = lock_type(lock_file), lock_type(lock_file) - async with holder.write_lock(): - acquiring = asyncio.create_task(waiting.acquire_write()) - await asyncio.sleep(0) - closing = asyncio.create_task(idle.close()) - done, _ = await asyncio.wait({closing}, timeout=2) - try: - await acquiring - await closing - assert closing in done - finally: - await waiting.close() - await holder.close() - - @pytest.mark.asyncio @pytest.mark.parametrize("is_singleton", [pytest.param(False, id="owned"), pytest.param(True, id="singleton")]) async def test_close_interrupts_backend_wait_while_peer_holds(lock_file: str, *, is_singleton: bool) -> None: diff --git a/tests/test_async_read_write_cancel_wait.py b/tests/test_async_read_write_cancel_wait.py index da0854027..72785139a 100644 --- a/tests/test_async_read_write_cancel_wait.py +++ b/tests/test_async_read_write_cancel_wait.py @@ -209,3 +209,23 @@ def write_once() -> None: holder.release() await asyncio.to_thread(waiting.join, _HOLD * 2) await lock.close() + + +@_FAMILIES +@pytest.mark.asyncio +async def test_singleton_close_returns_while_another_wrapper_enters(tmp_path: Path, make: _Make) -> None: + holder, waiting = make(tmp_path, is_singleton=False) + shared, idle = make(tmp_path, is_singleton=True) + with holder.write_lock(): + acquiring = asyncio.create_task(waiting.acquire_write()) + await asyncio.sleep(0) + closing = asyncio.create_task(idle.close()) + done, _ = await asyncio.wait({closing}, timeout=2) + try: + await acquiring + await closing + assert closing in done + finally: + await waiting.close() + shared.close() + holder.close()