Skip to content

Add ability to break parking lots, stop locks from stalling #3081

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 23 commits into from
Oct 9, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
3bd67a5
initial implementation of lot breaking
jakkdl Sep 6, 2024
4dfa1ad
fix import cycle
jakkdl Sep 6, 2024
543a087
fix re-export for verifytypes visibility
jakkdl Sep 6, 2024
c36cdad
update docstrings
jakkdl Sep 6, 2024
127c5fc
fixes after review by TeamSpen210
jakkdl Sep 6, 2024
1f75d44
add tests
jakkdl Sep 6, 2024
6835e87
add lock handover test
jakkdl Sep 6, 2024
3b86e80
clean up breaker dict
jakkdl Sep 6, 2024
94ff9a2
clean up GLOBAL_PARKING_LOT_BREAKER when task releases or exits
jakkdl Sep 6, 2024
eb7a451
add newsfragments, add StalledLockError, reraise BrokenResourceError …
jakkdl Sep 10, 2024
e7d7205
add test for default argument of break_lot
jakkdl Sep 10, 2024
c89fb2a
Merge branch 'main' into break_the_lot
jakkdl Sep 10, 2024
277c7da
various fixes after review
jakkdl Sep 18, 2024
21cf0d6
Merge remote-tracking branch 'origin/main' into break_the_lot
jakkdl Sep 18, 2024
45f78f4
break lots before other checks, minor phrasing improvement in docstring
jakkdl Sep 19, 2024
ec48863
docstring updates after A5rocks review
jakkdl Sep 27, 2024
c742a52
Merge branch 'main' into break_the_lot
jakkdl Sep 27, 2024
7a1ce5b
raise brokenresourceerror if registering an already exited task. fix …
jakkdl Oct 2, 2024
cc97cca
remove warning on task exit
jakkdl Oct 7, 2024
b81e297
Merge remote-tracking branch 'origin/main' into break_the_lot
jakkdl Oct 7, 2024
1d7ece3
make broken_by attribute a list, clean up tests
jakkdl Oct 8, 2024
b826210
Merge branch 'main' into break_the_lot
jakkdl Oct 8, 2024
92f9799
fix test. polish comments and tests
jakkdl Oct 8, 2024
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
7 changes: 6 additions & 1 deletion src/trio/_core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,12 @@
from ._ki import currently_ki_protected, disable_ki_protection, enable_ki_protection
from ._local import RunVar, RunVarToken
from ._mock_clock import MockClock
from ._parking_lot import ParkingLot, ParkingLotStatistics
from ._parking_lot import (
ParkingLot,
ParkingLotStatistics,
add_parking_lot_breaker,
remove_parking_lot_breaker,
)

# Imports that always exist
from ._run import (
Expand Down
52 changes: 52 additions & 0 deletions src/trio/_core/_parking_lot.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
from typing import TYPE_CHECKING

import attrs
import outcome

from .. import _core
from .._util import final
Expand All @@ -86,6 +87,31 @@
from ._run import Task


GLOBAL_PARKING_LOT_BREAKER: dict[Task, list[ParkingLot]] = {}


def add_parking_lot_breaker(task: Task, lot: ParkingLot) -> None:
"""Register a task as a breaker for a lot. This means that if the task exits without
having unparked from the lot, then the lot will break and raise an error for all tasks
parked in the lot, as well as any future task that attempt to park in it."""
if task not in GLOBAL_PARKING_LOT_BREAKER:
GLOBAL_PARKING_LOT_BREAKER[task] = [lot]
else:
GLOBAL_PARKING_LOT_BREAKER[task].append(lot)


def remove_parking_lot_breaker(task: Task, lot: ParkingLot) -> None:
"""Deregister a task as a breaker for a lot. See :func:`add_parking_lot_breaker`."""
try:
GLOBAL_PARKING_LOT_BREAKER[task].remove(lot)
except (KeyError, ValueError):
raise RuntimeError(
"Attempted to remove task as breaker for a lot it is not registered for",
) from None
if not GLOBAL_PARKING_LOT_BREAKER[task]:
del GLOBAL_PARKING_LOT_BREAKER[task]


@attrs.frozen
class ParkingLotStatistics:
"""An object containing debugging information for a ParkingLot.
Expand Down Expand Up @@ -118,6 +144,7 @@ class ParkingLot:
# {task: None}, we just want a deque where we can quickly delete random
# items
_parked: OrderedDict[Task, None] = attrs.field(factory=OrderedDict, init=False)
broken_by: Task | None = None

def __len__(self) -> int:
"""Returns the number of parked tasks."""
Expand All @@ -136,7 +163,15 @@ async def park(self) -> None:
"""Park the current task until woken by a call to :meth:`unpark` or
:meth:`unpark_all`.

Raises:
BrokenResourceError: if attempting to park in a broken lot, or the lot
breaks before we get to unpark.

"""
if self.broken_by is not None:
raise _core.BrokenResourceError(
f"Attempted to park in parking lot broken by {self.broken_by}",
)
task = _core.current_task()
self._parked[task] = None
task.custom_sleep_data = self
Expand Down Expand Up @@ -234,6 +269,23 @@ def repark_all(self, new_lot: ParkingLot) -> None:
"""
return self.repark(new_lot, count=len(self))

def break_lot(self, task: Task) -> None:
"""Break this lot, causing all parked tasks to raise an error, and any
future tasks attempting to park (and unpark? repark?) to error. The error
contains a reference to the task sent as a parameter."""
self.broken_by = task
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm just now realizing that this relationship is a bit flawed. Lots can only be marked as broken by one task, but multiple tasks could be marked as a parking lot breaker and exit (or a task multiple times, but that's handled already). I'm not sure what's a good idea. We can't raise any error because there's no good place to raise errors, but I suppose we could warn? Or maybe broken_by should be a list.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having a list feels overkill, and only really being useful in the case of multiple independent coding errors all leading to them wanting to break a lot. It feels like what would more commonly happen is multiple instances of the same task breaking a lot for the same reason, in which case the list would just fill up with tons of duplicates. Or cases where once one task has broken a lot it causes multiple subsequent tasks to re-break it.
So I feel like the first breaker is ""special"" in most cases, and we'd rarely care about the others.
But raising a warning sounds good, maybe RuntimeWarning?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should warning be raised if the same task breaks a lot multiple times?

Copy link
Contributor

@A5rocks A5rocks Sep 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah that sounds like a fine warning and a task breaking a lot multiple times is probably fine. After all we allow nesting add/remove_parking_lot_breaker


# TODO: is there any reason to use self._pop_several?
Copy link
Contributor

@A5rocks A5rocks Sep 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably some thin veneer of thread safety? Or guaranteeing that we'll remove every task we raise an error in, even if somehow _core.reschedule raises an error (... well, we'll remove the task where this happens too. Oh well, still better behavior).

Neither is really something we care about but probably worth using cause it's a simple drop in replacement anyways.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unpark() above would have the same theoretical issue, if reschedule() failed it could drop tasks too. Probably not something to worry about, if that fails we've got bigger problems.

for parked_task in self._parked:
# TODO: weird to phrase this one, we maybe should reraise this error in Lock?
_core.reschedule(
parked_task,
outcome.Error(
_core.BrokenResourceError(f"Parking lot broken by {task}"),
),
)
self._parked.clear()

def statistics(self) -> ParkingLotStatistics:
"""Return an object containing debugging information.

Expand Down
7 changes: 7 additions & 0 deletions src/trio/_core/_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
from ._exceptions import Cancelled, RunFinishedError, TrioInternalError
from ._instrumentation import Instruments
from ._ki import LOCALS_KEY_KI_PROTECTION_ENABLED, KIManager, enable_ki_protection
from ._parking_lot import GLOBAL_PARKING_LOT_BREAKER
from ._thread_cache import start_thread_soon
from ._traps import (
Abort,
Expand Down Expand Up @@ -1859,6 +1860,12 @@ def task_exited(self, task: Task, outcome: Outcome[Any]) -> None:
assert task._parent_nursery is not None, task
task._parent_nursery._child_finished(task, outcome)

# before or after the other stuff in this function?
if task in GLOBAL_PARKING_LOT_BREAKER:
for lot in GLOBAL_PARKING_LOT_BREAKER[task]:
lot.break_lot(task)
del GLOBAL_PARKING_LOT_BREAKER[task]

if "task_exited" in self.instruments:
self.instruments.call("task_exited", task)

Expand Down
70 changes: 70 additions & 0 deletions src/trio/_core/_tests/test_parking_lot.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

import pytest

import trio.lowlevel
from trio.testing import Matcher, RaisesGroup

from ... import _core
from ...testing import wait_all_tasks_blocked
from .._parking_lot import ParkingLot
Expand Down Expand Up @@ -215,3 +218,70 @@ async def test_parking_lot_repark_with_count() -> None:
"wake 2",
]
lot1.unpark_all()


async def test_parking_lot_breaker_basic() -> None:
lot = ParkingLot()
task = trio.lowlevel.current_task()

with pytest.raises(
RuntimeError,
match="Attempted to remove task as breaker for a lot it is not registered for",
):
trio.lowlevel.remove_parking_lot_breaker(task, lot)
trio.lowlevel.add_parking_lot_breaker(task, lot)
trio.lowlevel.add_parking_lot_breaker(task, lot)
trio.lowlevel.remove_parking_lot_breaker(task, lot)
trio.lowlevel.remove_parking_lot_breaker(task, lot)

with pytest.raises(
RuntimeError,
match="Attempted to remove task as breaker for a lot it is not registered for",
):
trio.lowlevel.remove_parking_lot_breaker(task, lot)


async def test_parking_lot_breaker() -> None:
async def bad_parker(lot: ParkingLot, scope: _core.CancelScope) -> None:
trio.lowlevel.add_parking_lot_breaker(trio.lowlevel.current_task(), lot)
with scope:
await trio.sleep_forever()

lot = ParkingLot()
cs = _core.CancelScope()

# check that parked task errors
with RaisesGroup(
Matcher(_core.BrokenResourceError, match="^Parking lot broken by"),
):
async with _core.open_nursery() as nursery:
nursery.start_soon(bad_parker, lot, cs)
await wait_all_tasks_blocked()

nursery.start_soon(lot.park)
await wait_all_tasks_blocked()

cs.cancel()

# check that trying to park in brokena lot errors
with pytest.raises(_core.BrokenResourceError):
await lot.park()


async def test_parking_lot_weird() -> None:
"""break a parking lot, where the breakee is parked. Doing this is weird, but should probably be supported??
Although the message makes less sense"""

async def return_me_and_park(
lot: ParkingLot,
*,
task_status: _core.TaskStatus[_core.Task] = trio.TASK_STATUS_IGNORED,
) -> None:
task_status.started(_core.current_task())
await lot.park()

lot = ParkingLot()
with RaisesGroup(Matcher(_core.BrokenResourceError, match="Parking lot broken by")):
async with _core.open_nursery() as nursery:
task = await nursery.start(return_me_and_park, lot)
lot.break_lot(task)
10 changes: 9 additions & 1 deletion src/trio/_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from . import _core
from ._core import Abort, ParkingLot, RaiseCancelT, enable_ki_protection
from ._core._parking_lot import add_parking_lot_breaker, remove_parking_lot_breaker
from ._util import final

if TYPE_CHECKING:
Expand Down Expand Up @@ -576,12 +577,17 @@ def acquire_nowait(self) -> None:
elif self._owner is None and not self._lot:
# No-one owns it
self._owner = task
add_parking_lot_breaker(task, self._lot)
else:
raise trio.WouldBlock

@enable_ki_protection
async def acquire(self) -> None:
"""Acquire the lock, blocking if necessary."""
"""Acquire the lock, blocking if necessary.

Raises:
BrokenResourceError: if the owner of the lock exits without releasing.
"""
await trio.lowlevel.checkpoint_if_cancelled()
try:
self.acquire_nowait()
Expand All @@ -604,8 +610,10 @@ def release(self) -> None:
task = trio.lowlevel.current_task()
if task is not self._owner:
raise RuntimeError("can't release a Lock you don't own")
remove_parking_lot_breaker(self._owner, self._lot)
if self._lot:
(self._owner,) = self._lot.unpark(count=1)
add_parking_lot_breaker(self._owner, self._lot)
else:
self._owner = None

Expand Down
54 changes: 54 additions & 0 deletions src/trio/_tests/test_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@

import pytest

from trio.testing import Matcher, RaisesGroup

from .. import _core
from .._core._parking_lot import GLOBAL_PARKING_LOT_BREAKER
from .._sync import *
from .._timeouts import sleep_forever
from ..testing import assert_checkpoints, wait_all_tasks_blocked
Expand Down Expand Up @@ -586,3 +589,54 @@ async def lock_taker() -> None:
await wait_all_tasks_blocked()
assert record == ["started"]
lock_like.release()


async def test_lock_acquire_unowned_lock() -> None:
"""Test that trying to acquire a lock whose owner has exited raises an error.
Partial fix for https://github.com/python-trio/trio/issues/3035
"""
assert not GLOBAL_PARKING_LOT_BREAKER
lock = trio.Lock()
async with trio.open_nursery() as nursery:
nursery.start_soon(lock.acquire)
with pytest.raises(
trio.BrokenResourceError,
match="^Attempted to park in parking lot broken by",
):
await lock.acquire()
assert not GLOBAL_PARKING_LOT_BREAKER


async def test_lock_multiple_acquire() -> None:
assert not GLOBAL_PARKING_LOT_BREAKER
lock = trio.Lock()
with RaisesGroup(Matcher(trio.BrokenResourceError, match="Parking lot broken by")):
async with trio.open_nursery() as nursery:
nursery.start_soon(lock.acquire)
nursery.start_soon(lock.acquire)
assert not GLOBAL_PARKING_LOT_BREAKER


async def test_lock_handover() -> None:
assert not GLOBAL_PARKING_LOT_BREAKER
lock = trio.Lock()
lock.acquire_nowait()
child_task: Task | None = None
assert GLOBAL_PARKING_LOT_BREAKER == {
_core.current_task(): [
lock._lot,
],
}

async with trio.open_nursery() as nursery:
nursery.start_soon(lock.acquire)
await wait_all_tasks_blocked()

lock.release()

assert len(GLOBAL_PARKING_LOT_BREAKER) == 1
child_task = next(iter(GLOBAL_PARKING_LOT_BREAKER))
assert GLOBAL_PARKING_LOT_BREAKER[child_task] == [lock._lot]

assert lock._lot.broken_by == child_task
assert not GLOBAL_PARKING_LOT_BREAKER
2 changes: 2 additions & 0 deletions src/trio/lowlevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
UnboundedQueue as UnboundedQueue,
UnboundedQueueStatistics as UnboundedQueueStatistics,
add_instrument as add_instrument,
add_parking_lot_breaker as add_parking_lot_breaker,
cancel_shielded_checkpoint as cancel_shielded_checkpoint,
checkpoint as checkpoint,
checkpoint_if_cancelled as checkpoint_if_cancelled,
Expand All @@ -40,6 +41,7 @@
permanently_detach_coroutine_object as permanently_detach_coroutine_object,
reattach_detached_coroutine_object as reattach_detached_coroutine_object,
remove_instrument as remove_instrument,
remove_parking_lot_breaker as remove_parking_lot_breaker,
reschedule as reschedule,
spawn_system_task as spawn_system_task,
start_guest_run as start_guest_run,
Expand Down
Loading