Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/changelog/+async-close-table-wait.bugfix.rst
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 3 additions & 0 deletions docs/changelog/+async-rw-close-waiting-acquire.bugfix.rst
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions docs/changelog/+async-rw-writer-wake.bugfix.rst
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions docs/changelog/+async-soft-close-wait.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +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.
2 changes: 2 additions & 0 deletions docs/changelog/+async-soft-rw-executor.bugfix.rst
Original file line number Diff line number Diff line change
@@ -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.
19 changes: 13 additions & 6 deletions docs/how-to.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down Expand Up @@ -823,11 +824,17 @@ 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, and its ``close()`` only
delegates to the synchronous lock.
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. 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)
Expand Down
95 changes: 62 additions & 33 deletions src/filelock/_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,10 +197,13 @@ 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], None] = {}
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
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,
Expand All @@ -212,33 +215,35 @@ 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],
check_after_enter: Callable[[], Awaitable[None]],
) -> None:
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(
task, mode, lock_file, via=via, joinable=joinable, waiting_writer=waiting_writer
task,
mode,
lock_file,
via=via,
joinable=joinable,
raise_if_unusable=raise_if_unusable,
),
ConcurrentFuture,
):
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
Expand All @@ -248,6 +253,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,
Expand All @@ -257,14 +263,16 @@ 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():
self._holds.clear()
self._mode = None
self._notify()
if (hold := self._holds.get(task)) is not None:
if self._mode != mode:
msg = (
Expand All @@ -275,30 +283,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):
self._transitioning, self._mode = True, mode
if not self._holds and next(iter(self._write_queue), task) is task:
self._transitioning, self._mode, self._entering_via = True, mode, via
return "enter"
return self._ticket()

def _ticket(self) -> 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
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,
Expand All @@ -308,12 +325,22 @@ 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)
self._notify()

def wake_via(self, via: Hashable) -> None:
with self._lock:
for ticket, waiting_via in tuple(self._read_waiters.items()):
if waiting_via is via:
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(
self,
*,
Expand Down Expand Up @@ -368,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:
Expand Down Expand Up @@ -408,7 +433,11 @@ 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()
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
if via is None:
dropped = dict(self._holds)
self._holds.clear()
Expand Down
54 changes: 44 additions & 10 deletions src/filelock/_async_read_write.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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,
Expand All @@ -226,6 +244,8 @@ def joinable() -> bool:
via=self._via,
enter=enter,
joinable=joinable,
raise_if_unusable=self._raise_if_unusable,
check_after_enter=check_after_enter,
)

@property
Expand All @@ -240,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:
Expand All @@ -258,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
Expand All @@ -275,14 +299,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.
Expand All @@ -306,6 +322,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]:
"""
Expand Down Expand Up @@ -356,20 +380,26 @@ 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
underlying SQLite connection. A singleton wrapper leaves the shared :class:`ReadWriteLock` open, so tasks 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 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
return
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(
Expand All @@ -384,6 +414,10 @@ async def close(self) -> None:
else:
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.
if self._owns_executor:
Expand Down
Loading
Loading