| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import contextlib |
| 5 |
import queue |
| 6 |
import signal |
| 7 |
import socket |
| 8 |
import sys |
| 9 |
import threading |
| 10 |
import time |
| 11 |
import traceback |
| 12 |
import warnings |
| 13 |
import weakref |
| 14 |
from collections.abc import AsyncGenerator, Awaitable, Callable, Sequence |
| 15 |
from functools import partial |
| 16 |
from math import inf |
| 17 |
from typing import ( |
| 18 |
TYPE_CHECKING, |
| 19 |
NoReturn, |
| 20 |
TypeAlias, |
| 21 |
TypeVar, |
| 22 |
cast, |
| 23 |
) |
| 24 |
|
| 25 |
import pytest |
| 26 |
import sniffio |
| 27 |
from outcome import Outcome |
| 28 |
|
| 29 |
import trio |
| 30 |
import trio.testing |
| 31 |
from trio.abc import Clock, Instrument |
| 32 |
|
| 33 |
from .tutil import gc_collect_harder, restore_unraisablehook |
| 34 |
|
| 35 |
if TYPE_CHECKING: |
| 36 |
from trio._channel import MemorySendChannel |
| 37 |
|
| 38 |
T = TypeVar("T") |
| 39 |
InHost: TypeAlias = Callable[[Callable[[], object]], None] |
| 40 |
|
| 41 |
|
| 42 |
# The simplest possible "host" loop. |
| 43 |
# Nice features: |
| 44 |
# - we can run code "outside" of trio using the schedule function passed to |
| 45 |
# our main |
| 46 |
# - final result is returned |
| 47 |
# - any unhandled exceptions cause an immediate crash |
| 48 |
def trivial_guest_run( |
| 49 |
trio_fn: Callable[[InHost], Awaitable[T]], |
| 50 |
*, |
| 51 |
in_host_after_start: Callable[[], None] | None = None, |
| 52 |
host_uses_signal_set_wakeup_fd: bool = False, |
| 53 |
clock: Clock | None = None, |
| 54 |
instruments: Sequence[Instrument] = (), |
| 55 |
restrict_keyboard_interrupt_to_checkpoints: bool = False, |
| 56 |
strict_exception_groups: bool = True, |
| 57 |
) -> T: |
| 58 |
todo: queue.Queue[tuple[str, Outcome[T] | Callable[[], object]]] = queue.Queue() |
| 59 |
|
| 60 |
host_thread = threading.current_thread() |
| 61 |
|
| 62 |
def run_sync_soon_threadsafe(fn: Callable[[], object]) -> None: |
| 63 |
nonlocal todo |
| 64 |
if host_thread is threading.current_thread(): # pragma: no cover |
| 65 |
crash = partial( |
| 66 |
pytest.fail, |
| 67 |
"run_sync_soon_threadsafe called from host thread", |
| 68 |
) |
| 69 |
todo.put(("run", crash)) |
| 70 |
todo.put(("run", fn)) |
| 71 |
|
| 72 |
def run_sync_soon_not_threadsafe(fn: Callable[[], object]) -> None: |
| 73 |
nonlocal todo |
| 74 |
if host_thread is not threading.current_thread(): # pragma: no cover |
| 75 |
crash = partial( |
| 76 |
pytest.fail, |
| 77 |
"run_sync_soon_not_threadsafe called from worker thread", |
| 78 |
) |
| 79 |
todo.put(("run", crash)) |
| 80 |
todo.put(("run", fn)) |
| 81 |
|
| 82 |
def done_callback(outcome: Outcome[T]) -> None: |
| 83 |
nonlocal todo |
| 84 |
todo.put(("unwrap", outcome)) |
| 85 |
|
| 86 |
trio.lowlevel.start_guest_run( |
| 87 |
trio_fn, |
| 88 |
run_sync_soon_not_threadsafe, |
| 89 |
run_sync_soon_threadsafe=run_sync_soon_threadsafe, |
| 90 |
run_sync_soon_not_threadsafe=run_sync_soon_not_threadsafe, |
| 91 |
done_callback=done_callback, |
| 92 |
host_uses_signal_set_wakeup_fd=host_uses_signal_set_wakeup_fd, |
| 93 |
clock=clock, |
| 94 |
instruments=instruments, |
| 95 |
restrict_keyboard_interrupt_to_checkpoints=restrict_keyboard_interrupt_to_checkpoints, |
| 96 |
strict_exception_groups=strict_exception_groups, |
| 97 |
) |
| 98 |
if in_host_after_start is not None: |
| 99 |
in_host_after_start() |
| 100 |
|
| 101 |
try: |
| 102 |
while True: |
| 103 |
op, obj = todo.get() |
| 104 |
if op == "run": |
| 105 |
assert not isinstance(obj, Outcome) |
| 106 |
obj() |
| 107 |
elif op == "unwrap": |
| 108 |
assert isinstance(obj, Outcome) |
| 109 |
return obj.unwrap() |
| 110 |
else: # pragma: no cover |
| 111 |
raise NotImplementedError(f"{op!r} not handled") |
| 112 |
finally: |
| 113 |
# Make sure that exceptions raised here don't capture these, so that |
| 114 |
# if an exception does cause us to abandon a run then the Trio state |
| 115 |
# has a chance to be GC'ed and warn about it. |
| 116 |
del todo, run_sync_soon_threadsafe, done_callback |
| 117 |
|
| 118 |
|
| 119 |
def test_guest_trivial() -> None: |
| 120 |
async def trio_return(in_host: InHost) -> str: |
| 121 |
await trio.lowlevel.checkpoint() |
| 122 |
return "ok" |
| 123 |
|
| 124 |
assert trivial_guest_run(trio_return) == "ok" |
| 125 |
|
| 126 |
async def trio_fail(in_host: InHost) -> NoReturn: |
| 127 |
raise KeyError("whoopsiedaisy") |
| 128 |
|
| 129 |
with pytest.raises(KeyError, match="whoopsiedaisy"): |
| 130 |
trivial_guest_run(trio_fail) |
| 131 |
|
| 132 |
|
| 133 |
def test_guest_can_do_io() -> None: |
| 134 |
async def trio_main(in_host: InHost) -> None: |
| 135 |
record = [] |
| 136 |
a, b = trio.socket.socketpair() |
| 137 |
with a, b: |
| 138 |
async with trio.open_nursery() as nursery: |
| 139 |
|
| 140 |
async def do_receive() -> None: |
| 141 |
record.append(await a.recv(1)) |
| 142 |
|
| 143 |
nursery.start_soon(do_receive) |
| 144 |
await trio.testing.wait_all_tasks_blocked() |
| 145 |
|
| 146 |
await b.send(b"x") |
| 147 |
|
| 148 |
assert record == [b"x"] |
| 149 |
|
| 150 |
trivial_guest_run(trio_main) |
| 151 |
|
| 152 |
|
| 153 |
def test_guest_is_initialized_when_start_returns() -> None: |
| 154 |
trio_token = None |
| 155 |
record = [] |
| 156 |
|
| 157 |
async def trio_main(in_host: InHost) -> str: |
| 158 |
record.append("main task ran") |
| 159 |
await trio.lowlevel.checkpoint() |
| 160 |
assert trio.lowlevel.current_trio_token() is trio_token |
| 161 |
return "ok" |
| 162 |
|
| 163 |
def after_start() -> None: |
| 164 |
# We should get control back before the main task executes any code |
| 165 |
assert record == [] |
| 166 |
|
| 167 |
nonlocal trio_token |
| 168 |
trio_token = trio.lowlevel.current_trio_token() |
| 169 |
trio_token.run_sync_soon(record.append, "run_sync_soon cb ran") |
| 170 |
|
| 171 |
@trio.lowlevel.spawn_system_task |
| 172 |
async def early_task() -> None: |
| 173 |
record.append("system task ran") |
| 174 |
await trio.lowlevel.checkpoint() |
| 175 |
|
| 176 |
res = trivial_guest_run(trio_main, in_host_after_start=after_start) |
| 177 |
assert res == "ok" |
| 178 |
assert set(record) == {"system task ran", "main task ran", "run_sync_soon cb ran"} |
| 179 |
|
| 180 |
class BadClock(Clock): |
| 181 |
def start_clock(self) -> NoReturn: |
| 182 |
raise ValueError("whoops") |
| 183 |
|
| 184 |
def current_time(self) -> float: |
| 185 |
raise NotImplementedError() |
| 186 |
|
| 187 |
def deadline_to_sleep_time(self, deadline: float) -> float: |
| 188 |
raise NotImplementedError() |
| 189 |
|
| 190 |
def after_start_never_runs() -> None: # pragma: no cover |
| 191 |
pytest.fail("shouldn't get here") |
| 192 |
|
| 193 |
# Errors during initialization (which can only be TrioInternalErrors) |
| 194 |
# are raised out of start_guest_run, not out of the done_callback |
| 195 |
with pytest.raises(trio.TrioInternalError): |
| 196 |
trivial_guest_run( |
| 197 |
trio_main, |
| 198 |
clock=BadClock(), |
| 199 |
in_host_after_start=after_start_never_runs, |
| 200 |
) |
| 201 |
|
| 202 |
|
| 203 |
def test_host_can_directly_wake_trio_task() -> None: |
| 204 |
async def trio_main(in_host: InHost) -> str: |
| 205 |
ev = trio.Event() |
| 206 |
in_host(ev.set) |
| 207 |
await ev.wait() |
| 208 |
return "ok" |
| 209 |
|
| 210 |
assert trivial_guest_run(trio_main) == "ok" |
| 211 |
|
| 212 |
|
| 213 |
def test_host_altering_deadlines_wakes_trio_up() -> None: |
| 214 |
def set_deadline(cscope: trio.CancelScope, new_deadline: float) -> None: |
| 215 |
cscope.deadline = new_deadline |
| 216 |
|
| 217 |
async def trio_main(in_host: InHost) -> str: |
| 218 |
with trio.CancelScope() as cscope: |
| 219 |
in_host(lambda: set_deadline(cscope, -inf)) |
| 220 |
await trio.sleep_forever() |
| 221 |
assert cscope.cancelled_caught |
| 222 |
|
| 223 |
with trio.CancelScope() as cscope: |
| 224 |
# also do a change that doesn't affect the next deadline, just to |
| 225 |
# exercise that path |
| 226 |
in_host(lambda: set_deadline(cscope, 1e6)) |
| 227 |
in_host(lambda: set_deadline(cscope, -inf)) |
| 228 |
await trio.sleep(999) |
| 229 |
assert cscope.cancelled_caught |
| 230 |
|
| 231 |
return "ok" |
| 232 |
|
| 233 |
assert trivial_guest_run(trio_main) == "ok" |
| 234 |
|
| 235 |
|
| 236 |
def test_guest_mode_sniffio_integration() -> None: |
| 237 |
current_async_library = sniffio.current_async_library |
| 238 |
sniffio_library = sniffio.thread_local |
| 239 |
|
| 240 |
async def trio_main(in_host: InHost) -> str: |
| 241 |
async def synchronize() -> None: |
| 242 |
"""Wait for all in_host() calls issued so far to complete.""" |
| 243 |
evt = trio.Event() |
| 244 |
in_host(evt.set) |
| 245 |
await evt.wait() |
| 246 |
|
| 247 |
# Host and guest have separate sniffio_library contexts |
| 248 |
in_host(partial(setattr, sniffio_library, "name", "nullio")) |
| 249 |
await synchronize() |
| 250 |
assert current_async_library() == "trio" |
| 251 |
|
| 252 |
record = [] |
| 253 |
in_host(lambda: record.append(current_async_library())) |
| 254 |
await synchronize() |
| 255 |
assert record == ["nullio"] |
| 256 |
assert current_async_library() == "trio" |
| 257 |
|
| 258 |
return "ok" |
| 259 |
|
| 260 |
try: |
| 261 |
assert trivial_guest_run(trio_main) == "ok" |
| 262 |
finally: |
| 263 |
sniffio_library.name = None |
| 264 |
|
| 265 |
|
| 266 |
def test_guest_mode_trio_context_detection() -> None: |
| 267 |
def check(thing: bool) -> None: |
| 268 |
assert thing |
| 269 |
|
| 270 |
assert not trio.lowlevel.in_trio_run() |
| 271 |
assert not trio.lowlevel.in_trio_task() |
| 272 |
|
| 273 |
async def trio_main(in_host: InHost) -> None: |
| 274 |
for _ in range(2): |
| 275 |
assert trio.lowlevel.in_trio_run() |
| 276 |
assert trio.lowlevel.in_trio_task() |
| 277 |
|
| 278 |
in_host(lambda: check(trio.lowlevel.in_trio_run())) |
| 279 |
in_host(lambda: check(not trio.lowlevel.in_trio_task())) |
| 280 |
|
| 281 |
trivial_guest_run(trio_main) |
| 282 |
assert not trio.lowlevel.in_trio_run() |
| 283 |
assert not trio.lowlevel.in_trio_task() |
| 284 |
|
| 285 |
|
| 286 |
def test_warn_set_wakeup_fd_overwrite() -> None: |
| 287 |
assert signal.set_wakeup_fd(-1) == -1 |
| 288 |
|
| 289 |
async def trio_main(in_host: InHost) -> str: |
| 290 |
return "ok" |
| 291 |
|
| 292 |
a, b = socket.socketpair() |
| 293 |
with a, b: |
| 294 |
a.setblocking(False) |
| 295 |
|
| 296 |
# Warn if there's already a wakeup fd |
| 297 |
signal.set_wakeup_fd(a.fileno()) |
| 298 |
try: |
| 299 |
with pytest.warns(RuntimeWarning, match="signal handling code.*collided"): |
| 300 |
assert trivial_guest_run(trio_main) == "ok" |
| 301 |
finally: |
| 302 |
assert signal.set_wakeup_fd(-1) == a.fileno() |
| 303 |
|
| 304 |
signal.set_wakeup_fd(a.fileno()) |
| 305 |
try: |
| 306 |
with pytest.warns(RuntimeWarning, match="signal handling code.*collided"): |
| 307 |
assert ( |
| 308 |
trivial_guest_run(trio_main, host_uses_signal_set_wakeup_fd=False) |
| 309 |
== "ok" |
| 310 |
) |
| 311 |
finally: |
| 312 |
assert signal.set_wakeup_fd(-1) == a.fileno() |
| 313 |
|
| 314 |
# Don't warn if there isn't already a wakeup fd |
| 315 |
with warnings.catch_warnings(): |
| 316 |
warnings.simplefilter("error") |
| 317 |
assert trivial_guest_run(trio_main) == "ok" |
| 318 |
|
| 319 |
with warnings.catch_warnings(): |
| 320 |
warnings.simplefilter("error") |
| 321 |
assert ( |
| 322 |
trivial_guest_run(trio_main, host_uses_signal_set_wakeup_fd=True) |
| 323 |
== "ok" |
| 324 |
) |
| 325 |
|
| 326 |
# If there's already a wakeup fd, but we've been told to trust it, |
| 327 |
# then it's left alone and there's no warning |
| 328 |
signal.set_wakeup_fd(a.fileno()) |
| 329 |
try: |
| 330 |
|
| 331 |
async def trio_check_wakeup_fd_unaltered(in_host: InHost) -> str: |
| 332 |
fd = signal.set_wakeup_fd(-1) |
| 333 |
assert fd == a.fileno() |
| 334 |
signal.set_wakeup_fd(fd) |
| 335 |
return "ok" |
| 336 |
|
| 337 |
with warnings.catch_warnings(): |
| 338 |
warnings.simplefilter("error") |
| 339 |
assert ( |
| 340 |
trivial_guest_run( |
| 341 |
trio_check_wakeup_fd_unaltered, |
| 342 |
host_uses_signal_set_wakeup_fd=True, |
| 343 |
) |
| 344 |
== "ok" |
| 345 |
) |
| 346 |
finally: |
| 347 |
assert signal.set_wakeup_fd(-1) == a.fileno() |
| 348 |
|
| 349 |
|
| 350 |
def test_host_wakeup_doesnt_trigger_wait_all_tasks_blocked() -> None: |
| 351 |
# This is designed to hit the branch in unrolled_run where: |
| 352 |
# idle_primed=True |
| 353 |
# runner.runq is empty |
| 354 |
# events is Truth-y |
| 355 |
# ...and confirm that in this case, wait_all_tasks_blocked does not get |
| 356 |
# triggered. |
| 357 |
def set_deadline(cscope: trio.CancelScope, new_deadline: float) -> None: |
| 358 |
print(f"setting deadline {new_deadline}") |
| 359 |
cscope.deadline = new_deadline |
| 360 |
|
| 361 |
async def trio_main(in_host: InHost) -> str: |
| 362 |
async def sit_in_wait_all_tasks_blocked(watb_cscope: trio.CancelScope) -> None: |
| 363 |
with watb_cscope: |
| 364 |
# Overall point of this test is that this |
| 365 |
# wait_all_tasks_blocked should *not* return normally, but |
| 366 |
# only by cancellation. |
| 367 |
await trio.testing.wait_all_tasks_blocked(cushion=9999) |
| 368 |
raise AssertionError( # pragma: no cover |
| 369 |
"wait_all_tasks_blocked should *not* return normally, " |
| 370 |
"only by cancellation.", |
| 371 |
) |
| 372 |
assert watb_cscope.cancelled_caught |
| 373 |
|
| 374 |
async def get_woken_by_host_deadline(watb_cscope: trio.CancelScope) -> None: |
| 375 |
with trio.CancelScope() as cscope: |
| 376 |
print("scheduling stuff to happen") |
| 377 |
|
| 378 |
# Altering the deadline from the host, to something in the |
| 379 |
# future, will cause the run loop to wake up, but then |
| 380 |
# discover that there is nothing to do and go back to sleep. |
| 381 |
# This should *not* trigger wait_all_tasks_blocked. |
| 382 |
# |
| 383 |
# So the 'before_io_wait' here will wait until we're blocking |
| 384 |
# with the wait_all_tasks_blocked primed, and then schedule a |
| 385 |
# deadline change. The critical test is that this should *not* |
| 386 |
# wake up 'sit_in_wait_all_tasks_blocked'. |
| 387 |
# |
| 388 |
# The after we've had a chance to wake up |
| 389 |
# 'sit_in_wait_all_tasks_blocked', we want the test to |
| 390 |
# actually end. So in after_io_wait we schedule a second host |
| 391 |
# call to tear things down. |
| 392 |
class InstrumentHelper(Instrument): |
| 393 |
def __init__(self) -> None: |
| 394 |
self.primed = False |
| 395 |
|
| 396 |
def before_io_wait(self, timeout: float) -> None: |
| 397 |
print(f"before_io_wait({timeout})") |
| 398 |
if timeout == 9999: # pragma: no branch |
| 399 |
assert not self.primed |
| 400 |
in_host(lambda: set_deadline(cscope, 1e9)) |
| 401 |
self.primed = True |
| 402 |
|
| 403 |
def after_io_wait(self, timeout: float) -> None: |
| 404 |
if self.primed: # pragma: no branch |
| 405 |
print("instrument triggered") |
| 406 |
in_host(lambda: cscope.cancel()) |
| 407 |
trio.lowlevel.remove_instrument(self) |
| 408 |
|
| 409 |
trio.lowlevel.add_instrument(InstrumentHelper()) |
| 410 |
await trio.sleep_forever() |
| 411 |
assert cscope.cancelled_caught |
| 412 |
watb_cscope.cancel() |
| 413 |
|
| 414 |
async with trio.open_nursery() as nursery: |
| 415 |
watb_cscope = trio.CancelScope() |
| 416 |
nursery.start_soon(sit_in_wait_all_tasks_blocked, watb_cscope) |
| 417 |
await trio.testing.wait_all_tasks_blocked() |
| 418 |
nursery.start_soon(get_woken_by_host_deadline, watb_cscope) |
| 419 |
|
| 420 |
return "ok" |
| 421 |
|
| 422 |
assert trivial_guest_run(trio_main) == "ok" |
| 423 |
|
| 424 |
|
| 425 |
@restore_unraisablehook() |
| 426 |
def test_guest_warns_if_abandoned() -> None: |
| 427 |
# This warning is emitted from the garbage collector. So we have to make |
| 428 |
# sure that our abandoned run is garbage. The easiest way to do this is to |
| 429 |
# put it into a function, so that we're sure all the local state, |
| 430 |
# traceback frames, etc. are garbage once it returns. |
| 431 |
def do_abandoned_guest_run() -> None: |
| 432 |
async def abandoned_main(in_host: InHost) -> None: |
| 433 |
in_host(lambda: 1 / 0) |
| 434 |
while True: |
| 435 |
await trio.lowlevel.checkpoint() |
| 436 |
|
| 437 |
with pytest.raises(ZeroDivisionError): |
| 438 |
trivial_guest_run(abandoned_main) |
| 439 |
|
| 440 |
with pytest.warns( # noqa: PT031 |
| 441 |
RuntimeWarning, |
| 442 |
match="Trio guest run got abandoned", |
| 443 |
): |
| 444 |
do_abandoned_guest_run() |
| 445 |
gc_collect_harder() |
| 446 |
|
| 447 |
# If you have problems some day figuring out what's holding onto a |
| 448 |
# reference to the unrolled_run generator and making this test fail, |
| 449 |
# then this might be useful to help track it down. (It assumes you |
| 450 |
# also hack start_guest_run so that it does 'global W; W = |
| 451 |
# weakref(unrolled_run_gen)'.) |
| 452 |
# |
| 453 |
# import gc |
| 454 |
# print(trio._core._run.W) |
| 455 |
# targets = [trio._core._run.W()] |
| 456 |
# for i in range(15): |
| 457 |
# new_targets = [] |
| 458 |
# for target in targets: |
| 459 |
# new_targets += gc.get_referrers(target) |
| 460 |
# new_targets.remove(targets) |
| 461 |
# print("#####################") |
| 462 |
# print(f"depth {i}: {len(new_targets)}") |
| 463 |
# print(new_targets) |
| 464 |
# targets = new_targets |
| 465 |
|
| 466 |
with pytest.raises(RuntimeError): |
| 467 |
trio.current_time() |
| 468 |
|
| 469 |
|
| 470 |
def aiotrio_run( |
| 471 |
trio_fn: Callable[[], Awaitable[T]], |
| 472 |
*, |
| 473 |
pass_not_threadsafe: bool = True, |
| 474 |
run_sync_soon_not_threadsafe: InHost | None = None, |
| 475 |
host_uses_signal_set_wakeup_fd: bool = False, |
| 476 |
clock: Clock | None = None, |
| 477 |
instruments: Sequence[Instrument] = (), |
| 478 |
restrict_keyboard_interrupt_to_checkpoints: bool = False, |
| 479 |
strict_exception_groups: bool = True, |
| 480 |
) -> T: |
| 481 |
loop = asyncio.new_event_loop() |
| 482 |
|
| 483 |
async def aio_main() -> T: |
| 484 |
nonlocal run_sync_soon_not_threadsafe |
| 485 |
trio_done_fut: asyncio.Future[Outcome[T]] = loop.create_future() |
| 486 |
|
| 487 |
def trio_done_callback(main_outcome: Outcome[T]) -> None: |
| 488 |
print(f"trio_fn finished: {main_outcome!r}") |
| 489 |
trio_done_fut.set_result(main_outcome) |
| 490 |
|
| 491 |
if pass_not_threadsafe: |
| 492 |
run_sync_soon_not_threadsafe = cast("InHost", loop.call_soon) |
| 493 |
|
| 494 |
trio.lowlevel.start_guest_run( |
| 495 |
trio_fn, |
| 496 |
run_sync_soon_threadsafe=loop.call_soon_threadsafe, |
| 497 |
done_callback=trio_done_callback, |
| 498 |
run_sync_soon_not_threadsafe=run_sync_soon_not_threadsafe, |
| 499 |
host_uses_signal_set_wakeup_fd=host_uses_signal_set_wakeup_fd, |
| 500 |
clock=clock, |
| 501 |
instruments=instruments, |
| 502 |
restrict_keyboard_interrupt_to_checkpoints=restrict_keyboard_interrupt_to_checkpoints, |
| 503 |
strict_exception_groups=strict_exception_groups, |
| 504 |
) |
| 505 |
|
| 506 |
return (await trio_done_fut).unwrap() |
| 507 |
|
| 508 |
try: |
| 509 |
# can't use asyncio.run because that fails on Windows (3.10, x64, with |
| 510 |
# Komodia LSP) |
| 511 |
return loop.run_until_complete(aio_main()) |
| 512 |
finally: |
| 513 |
loop.close() |
| 514 |
|
| 515 |
|
| 516 |
def test_guest_mode_on_asyncio() -> None: |
| 517 |
async def trio_main() -> str: |
| 518 |
print("trio_main!") |
| 519 |
|
| 520 |
to_trio, from_aio = trio.open_memory_channel[int](float("inf")) |
| 521 |
from_trio: asyncio.Queue[int] = asyncio.Queue() |
| 522 |
|
| 523 |
aio_task = asyncio.ensure_future(aio_pingpong(from_trio, to_trio)) |
| 524 |
|
| 525 |
# Make sure we have at least one tick where we don't need to go into |
| 526 |
# the thread |
| 527 |
await trio.lowlevel.checkpoint() |
| 528 |
|
| 529 |
from_trio.put_nowait(0) |
| 530 |
|
| 531 |
async for n in from_aio: |
| 532 |
print(f"trio got: {n}") |
| 533 |
from_trio.put_nowait(n + 1) |
| 534 |
if n >= 10: |
| 535 |
aio_task.cancel() |
| 536 |
return "trio-main-done" |
| 537 |
|
| 538 |
raise AssertionError("should never be reached") # pragma: no cover |
| 539 |
|
| 540 |
async def aio_pingpong( |
| 541 |
from_trio: asyncio.Queue[int], |
| 542 |
to_trio: MemorySendChannel[int], |
| 543 |
) -> None: |
| 544 |
print("aio_pingpong!") |
| 545 |
|
| 546 |
try: |
| 547 |
while True: |
| 548 |
n = await from_trio.get() |
| 549 |
print(f"aio got: {n}") |
| 550 |
to_trio.send_nowait(n + 1) |
| 551 |
except asyncio.CancelledError: |
| 552 |
raise |
| 553 |
except: # pragma: no cover |
| 554 |
traceback.print_exc() |
| 555 |
raise |
| 556 |
|
| 557 |
assert ( |
| 558 |
aiotrio_run( |
| 559 |
trio_main, |
| 560 |
# Not all versions of asyncio we test on can actually be trusted, |
| 561 |
# but this test doesn't care about signal handling, and it's |
| 562 |
# easier to just avoid the warnings. |
| 563 |
host_uses_signal_set_wakeup_fd=True, |
| 564 |
) |
| 565 |
== "trio-main-done" |
| 566 |
) |
| 567 |
|
| 568 |
assert ( |
| 569 |
aiotrio_run( |
| 570 |
trio_main, |
| 571 |
# Also check that passing only call_soon_threadsafe works, via the |
| 572 |
# fallback path where we use it for everything. |
| 573 |
pass_not_threadsafe=False, |
| 574 |
host_uses_signal_set_wakeup_fd=True, |
| 575 |
) |
| 576 |
== "trio-main-done" |
| 577 |
) |
| 578 |
|
| 579 |
|
| 580 |
def test_guest_mode_internal_errors( |
| 581 |
monkeypatch: pytest.MonkeyPatch, |
| 582 |
recwarn: pytest.WarningsRecorder, |
| 583 |
) -> None: |
| 584 |
with monkeypatch.context() as m: |
| 585 |
|
| 586 |
async def crash_in_run_loop(in_host: InHost) -> None: |
| 587 |
m.setattr("trio._core._run.GLOBAL_RUN_CONTEXT.runner.runq", "HI") |
| 588 |
await trio.sleep(1) |
| 589 |
|
| 590 |
with pytest.raises(trio.TrioInternalError): |
| 591 |
trivial_guest_run(crash_in_run_loop) |
| 592 |
|
| 593 |
with monkeypatch.context() as m: |
| 594 |
|
| 595 |
async def crash_in_io(in_host: InHost) -> None: |
| 596 |
m.setattr("trio._core._run.TheIOManager.get_events", None) |
| 597 |
await trio.lowlevel.checkpoint() |
| 598 |
|
| 599 |
with pytest.raises(trio.TrioInternalError): |
| 600 |
trivial_guest_run(crash_in_io) |
| 601 |
|
| 602 |
with monkeypatch.context() as m: |
| 603 |
|
| 604 |
async def crash_in_worker_thread_io(in_host: InHost) -> None: |
| 605 |
t = threading.current_thread() |
| 606 |
old_get_events = trio._core._run.TheIOManager.get_events |
| 607 |
|
| 608 |
def bad_get_events( |
| 609 |
self: trio._core._run.TheIOManager, |
| 610 |
timeout: float, |
| 611 |
) -> trio._core._run.EventResult: |
| 612 |
if threading.current_thread() is not t: |
| 613 |
raise ValueError("oh no!") |
| 614 |
else: |
| 615 |
return old_get_events(self, timeout) |
| 616 |
|
| 617 |
m.setattr("trio._core._run.TheIOManager.get_events", bad_get_events) |
| 618 |
|
| 619 |
await trio.sleep(1) |
| 620 |
|
| 621 |
with pytest.raises(trio.TrioInternalError): |
| 622 |
trivial_guest_run(crash_in_worker_thread_io) |
| 623 |
|
| 624 |
gc_collect_harder() |
| 625 |
|
| 626 |
|
| 627 |
def test_guest_mode_ki() -> None: |
| 628 |
assert signal.getsignal(signal.SIGINT) is signal.default_int_handler |
| 629 |
|
| 630 |
# Check SIGINT in Trio func and in host func |
| 631 |
async def trio_main(in_host: InHost) -> None: |
| 632 |
with pytest.raises(KeyboardInterrupt): |
| 633 |
signal.raise_signal(signal.SIGINT) |
| 634 |
|
| 635 |
# Host SIGINT should get injected into Trio |
| 636 |
in_host(partial(signal.raise_signal, signal.SIGINT)) |
| 637 |
await trio.sleep(10) |
| 638 |
|
| 639 |
with pytest.raises(KeyboardInterrupt) as excinfo: |
| 640 |
trivial_guest_run(trio_main) |
| 641 |
assert excinfo.value.__context__ is None |
| 642 |
# Signal handler should be restored properly on exit |
| 643 |
assert signal.getsignal(signal.SIGINT) is signal.default_int_handler |
| 644 |
|
| 645 |
# Also check chaining in the case where KI is injected after main exits |
| 646 |
final_exc = KeyError("whoa") |
| 647 |
|
| 648 |
async def trio_main_raising(in_host: InHost) -> NoReturn: |
| 649 |
in_host(partial(signal.raise_signal, signal.SIGINT)) |
| 650 |
raise final_exc |
| 651 |
|
| 652 |
with pytest.raises(KeyboardInterrupt) as excinfo: |
| 653 |
trivial_guest_run(trio_main_raising) |
| 654 |
assert excinfo.value.__context__ is final_exc |
| 655 |
|
| 656 |
assert signal.getsignal(signal.SIGINT) is signal.default_int_handler |
| 657 |
|
| 658 |
|
| 659 |
def test_guest_mode_autojump_clock_threshold_changing() -> None: |
| 660 |
# This is super obscure and probably no-one will ever notice, but |
| 661 |
# technically mutating the MockClock.autojump_threshold from the host |
| 662 |
# should wake up the guest, so let's test it. |
| 663 |
|
| 664 |
clock = trio.testing.MockClock() |
| 665 |
|
| 666 |
DURATION = 120 |
| 667 |
|
| 668 |
async def trio_main(in_host: InHost) -> None: |
| 669 |
assert trio.current_time() == 0 |
| 670 |
in_host(lambda: setattr(clock, "autojump_threshold", 0)) |
| 671 |
await trio.sleep(DURATION) |
| 672 |
assert trio.current_time() == DURATION |
| 673 |
|
| 674 |
start = time.monotonic() |
| 675 |
trivial_guest_run(trio_main, clock=clock) |
| 676 |
end = time.monotonic() |
| 677 |
# Should be basically instantaneous, but we'll leave a generous buffer to |
| 678 |
# account for any CI weirdness |
| 679 |
assert end - start < DURATION / 2 |
| 680 |
|
| 681 |
|
| 682 |
@restore_unraisablehook() |
| 683 |
def test_guest_mode_asyncgens() -> None: |
| 684 |
record = set() |
| 685 |
|
| 686 |
async def agen(label: str) -> AsyncGenerator[int, None]: |
| 687 |
assert sniffio.current_async_library() == label |
| 688 |
try: |
| 689 |
yield 1 |
| 690 |
finally: |
| 691 |
library = sniffio.current_async_library() |
| 692 |
with contextlib.suppress(trio.Cancelled): |
| 693 |
await sys.modules[library].sleep(0) |
| 694 |
record.add((label, library)) |
| 695 |
|
| 696 |
async def iterate_in_aio() -> None: |
| 697 |
await agen("asyncio").asend(None) |
| 698 |
|
| 699 |
async def trio_main() -> None: |
| 700 |
task = asyncio.ensure_future(iterate_in_aio()) |
| 701 |
done_evt = trio.Event() |
| 702 |
task.add_done_callback(lambda _: done_evt.set()) |
| 703 |
with trio.fail_after(1): |
| 704 |
await done_evt.wait() |
| 705 |
|
| 706 |
await agen("trio").asend(None) |
| 707 |
|
| 708 |
gc_collect_harder() |
| 709 |
|
| 710 |
aiotrio_run(trio_main, host_uses_signal_set_wakeup_fd=True) |
| 711 |
|
| 712 |
assert record == {("asyncio", "asyncio"), ("trio", "trio")} |
| 713 |
|
| 714 |
|
| 715 |
@restore_unraisablehook() |
| 716 |
def test_guest_mode_asyncgens_garbage_collection() -> None: |
| 717 |
record: set[tuple[str, str, bool]] = set() |
| 718 |
|
| 719 |
async def agen(label: str) -> AsyncGenerator[int, None]: |
| 720 |
class A: |
| 721 |
pass |
| 722 |
|
| 723 |
a = A() |
| 724 |
a_wr = weakref.ref(a) |
| 725 |
assert sniffio.current_async_library() == label |
| 726 |
try: |
| 727 |
yield 1 |
| 728 |
finally: |
| 729 |
library = sniffio.current_async_library() |
| 730 |
with contextlib.suppress(trio.Cancelled): |
| 731 |
await sys.modules[library].sleep(0) |
| 732 |
|
| 733 |
del a |
| 734 |
if sys.implementation.name == "pypy": |
| 735 |
gc_collect_harder() |
| 736 |
|
| 737 |
record.add((label, library, a_wr() is None)) |
| 738 |
|
| 739 |
async def iterate_in_aio() -> None: |
| 740 |
await agen("asyncio").asend(None) |
| 741 |
|
| 742 |
async def trio_main() -> None: |
| 743 |
task = asyncio.ensure_future(iterate_in_aio()) |
| 744 |
done_evt = trio.Event() |
| 745 |
task.add_done_callback(lambda _: done_evt.set()) |
| 746 |
with trio.fail_after(1): |
| 747 |
await done_evt.wait() |
| 748 |
|
| 749 |
await agen("trio").asend(None) |
| 750 |
|
| 751 |
gc_collect_harder() |
| 752 |
|
| 753 |
aiotrio_run(trio_main, host_uses_signal_set_wakeup_fd=True) |
| 754 |
|
| 755 |
assert record == {("asyncio", "asyncio", True), ("trio", "trio", True)} |