Skip to content

Commit cfe7550

Browse files
updated design for isolate + added devdocs
1 parent 8dc1b24 commit cfe7550

5 files changed

Lines changed: 291 additions & 81 deletions

File tree

devdocs/isolate.md

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# `tinyio.isolate`
2+
3+
I went back-and-forth on various designs for `tinyio.isolate`.
4+
5+
## Scheduling on the main loop vs scheduling on the isolated loop.
6+
7+
The key issue is around the coroutines spawned by the isolated coroutine (and any coroutines that they transitively spawn, and so on...). Are these part of the isolated loop or not? That is, if they crash, should they only crash the isolated loop, or the whole loop?
8+
9+
Note that we definitely need some means of placing things on the main loop (not just the isolated loop), as e.g. we may want an isolated coroutine to consume some input made available by the main loop... a dependency typically expressed as `yield some_coroutine`.
10+
11+
In terms of what this means under-the-hood:
12+
- if they are on the isolated loop then they are just normal coroutines scheduled there;
13+
- if they are on the main loop then we can still access their results from within the isolated loop by proxying their results over in a new coroutine; e.g. the following allows you to create a new coroutine that yields the results of the first:
14+
15+
```python
16+
# Usage: coro2 = yield copy(coro) whilst within the main loop. `coro2` is fresh and can be placed on a new loop.
17+
18+
def copy(coro: tinyio.Coro[_T]) -> tinyio.Coro[tinyio.Coro[_T]]:
19+
pipe = []
20+
done = tinyio.Event()
21+
failed = tinyio.Event()
22+
23+
def put_on_old_loop():
24+
try:
25+
out = yield coro
26+
except BaseException as e:
27+
pipe.append(e)
28+
failed.set()
29+
done.set()
30+
raise
31+
else:
32+
pipe.append(out)
33+
done.set()
34+
35+
def put_on_new_loop() -> tinyio.Coro[_T]:
36+
yield done.wait()
37+
if failed.is_set():
38+
raise pipe[0]
39+
else:
40+
return pipe[0]
41+
42+
yield {put_on_old_loop()}
43+
return put_on_new_loop()
44+
```
45+
46+
After some thought, I realised that this question of placement cannot be determined automatically.
47+
48+
Here's a thought experiment:
49+
```python
50+
def foo():
51+
yield [bar, baz]
52+
53+
def main():
54+
yield [isolate(foo()), some_other_coro]
55+
```
56+
now let's suppose that `bar` crashes. Should `baz` also be crashed as well? If it is scheduled exclusively on the isolated loop, then yes. If it is scheduled on the main loop – or will be scheduled there in the future! – then no. And we have no way of telling which scenario we are in.
57+
58+
## Points to recall
59+
60+
1. a coroutine can be yielded in multiple places. Recall that `tinyio` allows you to yield previously-seen coroutines to get their result. In particular it is completely possible that the same coroutine will be yielded both inside and outside of the isolated region.
61+
62+
2. because we are in an asynchronous context, then we cannot rely on the order in which coroutines are yielded. For example supposing the isolated coroutine runs `yield coro`, then we might naively have a check of the form
63+
64+
```python
65+
if inspect.getgeneratorstate(coro) == inspect.GEN_CREATED:
66+
# brand-new coroutine, include it in the isolate
67+
else:
68+
# existing coroutine, keep it outside
69+
```
70+
71+
but in practice this just introduces a race condition; what if the coroutine is *going* to be yielded in the main loop later, but hasn't yet? We'd get different behaviour depending on the order in which things are scheduled.
72+
73+
In light of this, we might still imagine a design where fresh coroutines are stored on the isolated loop, until they appear on the main loop, at which point they transfer over (by some mechanism). This would also introduce an issue, however: what if some third coroutine within the isolated loop crashes? The order of that, relative to the transfer to the main loop, will determine whether the shared coroutine is also crashed. (Either not crashed on the main loop, or crashed within the isolated loop... which would then presumably leak out into crashing the main loop too, once it gets yielded there.) And in an async context, we can't make guarantees about the order in which things happen, so both are always possible.
74+
75+
# Rejected design 1
76+
77+
API of `tinyio.isolate(coro)`, intercept all coroutines yielded by `coro`, automatically detect whether that coroutine has started using `inspect.getgeneratorstate`, and pick the loop appropriately. This does not work for the reasons described above.
78+
79+
# Rejected design 2
80+
81+
API of `tinyio.isolate(coro)`, intercept all coroutines yielded by `coro`, and wrap all of them in a `tinyio.isolate` as well. (Plus unwrapping their results when sending.) This is essentially the maximalist answer to this choice by having the answer be 'never crash the other coroutines on the isolated loop, let them run to completion'.
82+
83+
We reject this because it does not fit `tinyio`'s crash-all-coroutines model – instead we're basically just back in the bad old days of `asyncio`'s edge-triggered exceptions. This is not easy to reason about.
84+
85+
# Rejected design 3
86+
87+
API of `tinyio.isolate(make_coro: Callable[..., tinyio.Coro], *args: tinyio.Coro)`, have `*args` be placed on the main loop, and assume/require that all coroutines directly yielded by `make_coro(*args)` are exclusively on the isolated loop.
88+
89+
This API is based around the observation that major use-case for (?) the isolated-on-main dependence is in consuming arguments from coroutines on the main loop.
90+
91+
This is 'fine', but suffers from (a) some API inconsistency with the rest of `tinyio` (which operates on coroutines directly, not functions-returning-coroutines), and (b) is not very explicit about the purpose of separating out those `*args`. A user may be surprised that `isolate(lambda: coro(x, y))` does not work equivalently to `isolate(coro, x, y)`.
92+
93+
# Rejected design 4
94+
95+
API of `tinyio.isolate(coro: tinyio.Coro, put_on_isolated_loop: Callable[[tinyio.Coro], bool])`, and call `put_on_isolated_loop(x)` on each `yield x` that occurs within the isolated region (directly from `coro` or transitively), and let a user explicitly decide.
96+
97+
This is also 'fine' but realistically almost all users are not going to be educated on the contents of this document, and may attempt to write out a rule (such as 'has the coroutine started') that are going to be flaky down the line.
98+
99+
# Accepted design
100+
101+
API of `tinyio.isolate(coro)`, and assume/require that all yielded coroutines from `coro` are exclusively on the isolated loop.
102+
103+
In order to consume the result of arguments from the main loop, then also publicly expose `tinyio.copy` for creating a fresh coroutine to place on the isolated loop:
104+
```python
105+
x = yield tinyio.copy(x)
106+
out = yield tinyio.isolate(my_coro(x))
107+
```
108+
109+
This suffers from the major issue that using this is easy to misuse: forgetting the `copy` will probably raise an error when `x` tries to be placed on both loops; placing the `copy` inside of `my_coro` will simply do nothing.
110+
111+
Relative to design 3, this does have the advantage of making it clear that `x` is being copied.
112+
113+
Still, this has probably the simplest semantics to explain to a user: it runs the provided coroutine in an isolated loop. If you want to bridge that isolation, use `tinyio.copy`.
114+
115+
I still don't love this, and would be open to other designs.

tests/test_core.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -569,3 +569,15 @@ def g():
569569

570570
with pytest.raises(RuntimeError, match="whilst the loop is currently running"):
571571
loop.run(f())
572+
573+
574+
def test_runtime_leave_without_finishing():
575+
def coro():
576+
yield
577+
578+
def foo():
579+
with tinyio.Loop().runtime(coro(), exception_group=None) as gen:
580+
return 3
581+
582+
with pytest.raises(RuntimeError, match="only partially completed"):
583+
foo()

tests/test_isolate.py

Lines changed: 43 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,31 @@
1+
import warnings
12
from collections.abc import Callable
23

34
import pytest
45
import tinyio
56

67

8+
_sentinel = object()
9+
10+
711
class SingleElementQueue:
812
def __init__(self):
913
self._event = tinyio.Event()
10-
self._elem = None
14+
self._elem = _sentinel
1115

1216
def put(self, x):
13-
if self._elem is not None:
17+
if self._elem is not _sentinel:
1418
raise ValueError("Queue is full")
1519

1620
self._elem = x
1721
self._event.set()
1822

1923
def get(self):
20-
while self._elem is None:
21-
yield self._event.wait()
24+
yield self._event.wait()
25+
self._event.clear()
26+
assert self._elem is not _sentinel
2227
x = self._elem
23-
self._elem = None
28+
self._elem = _sentinel
2429
return x
2530

2631

@@ -49,7 +54,7 @@ def h() -> tinyio.Coro[int]:
4954

5055
def maybe_isolate(c: Callable[[], tinyio.Coro[int]], isolate: bool) -> tinyio.Coro[int]:
5156
if isolate:
52-
x, _ = yield tinyio.isolate(c)
57+
x, _ = yield tinyio.isolate(c())
5358
return x
5459
else:
5560
return (yield c())
@@ -98,7 +103,7 @@ def isolated() -> tinyio.Coro[list[int]]:
98103
return (yield [h(), i()])
99104

100105
def try_isolated() -> tinyio.Coro[list[int]]:
101-
x, success = yield tinyio.isolate(isolated)
106+
x, success = yield tinyio.isolate(isolated())
102107
if not success:
103108
x = [-1, -1]
104109

@@ -131,7 +136,8 @@ def unreliable_add_two(get_x: tinyio.Coro[int]) -> tinyio.Coro[int]:
131136
return z
132137

133138
def try_add_three(x: int) -> tinyio.Coro[tuple[int, bool]]:
134-
return (yield tinyio.isolate(unreliable_add_two, slow_add_one(x)))
139+
arg = yield tinyio.copy(slow_add_one(x))
140+
return (yield tinyio.isolate(unreliable_add_two(arg)))
135141

136142
assert tinyio.Loop().run(try_add_three(0)) == (3, True)
137143
assert tinyio.Loop().run(try_add_three(1)) == (4, True)
@@ -142,3 +148,32 @@ def try_add_three(x: int) -> tinyio.Coro[tuple[int, bool]]:
142148
assert not success
143149
assert type(result) is RuntimeError
144150
assert str(result) == "That is too hard."
151+
152+
153+
def test_copy_identity():
154+
def foo():
155+
yield
156+
return object()
157+
158+
def bar():
159+
f = foo()
160+
g = yield tinyio.copy(f)
161+
assert (yield f) is (yield g)
162+
return 3
163+
164+
assert tinyio.Loop().run(bar()) == 3
165+
166+
167+
def test_isolate_respects_cancellation():
168+
def foo():
169+
while True:
170+
yield
171+
172+
def bar():
173+
yield {tinyio.isolate(foo())}
174+
raise RuntimeError("Kaboom")
175+
176+
with warnings.catch_warnings():
177+
warnings.simplefilter("error")
178+
with pytest.raises(RuntimeError, match="Kaboom"):
179+
tinyio.Loop().run(bar())

tinyio/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
to_asyncio as to_asyncio,
1212
to_trio as to_trio,
1313
)
14-
from ._isolate import isolate as isolate
14+
from ._isolate import copy as copy, isolate as isolate
1515
from ._sync import Barrier as Barrier, Lock as Lock, Semaphore as Semaphore
1616
from ._thread import ThreadPool as ThreadPool, run_in_thread as run_in_thread
1717
from ._time import TimeoutError as TimeoutError, sleep as sleep, timeout as timeout

0 commit comments

Comments
 (0)