Debian Codegraph @

src/trio/_core/_tests/test_ki.py

raw
1 from __future__ import annotations
2
3 import contextlib
4 import inspect
5 import signal
6 import sys
7 import threading
8 import weakref
9 from typing import TYPE_CHECKING, TypeVar
10
11 import outcome
12 import pytest
13
14 from .tutil import gc_collect_harder
15
16 try:
17 from async_generator import async_generator, yield_
18 except ImportError: # pragma: no cover
19 async_generator = yield_ = None
20
21 from ... import _core
22 from ..._abc import Instrument
23 from ..._core import _ki
24 from ..._timeouts import sleep
25 from ...testing import wait_all_tasks_blocked
26
27 if TYPE_CHECKING:
28 from collections.abc import (
29 AsyncGenerator,
30 AsyncIterator,
31 Callable,
32 Generator,
33 Iterator,
34 )
35 from types import AsyncGeneratorType
36
37 from typing_extensions import Never
38
39 from ..._core import Abort, RaiseCancelT
40
41
42 def ki_self() -> None:
43 signal.raise_signal(signal.SIGINT)
44
45
46 def test_ki_self() -> None:
47 with pytest.raises(KeyboardInterrupt):
48 ki_self()
49
50
51 async def test_ki_enabled() -> None:
52 # Regular tasks aren't KI-protected
53 assert not _core.currently_ki_protected()
54
55 # Low-level call-soon callbacks are KI-protected
56 token = _core.current_trio_token()
57 record = []
58
59 def check() -> None:
60 record.append(_core.currently_ki_protected())
61
62 token.run_sync_soon(check)
63 await wait_all_tasks_blocked()
64 assert record == [True]
65
66 @_core.enable_ki_protection
67 def protected() -> None:
68 assert _core.currently_ki_protected()
69 unprotected()
70
71 @_core.disable_ki_protection
72 def unprotected() -> None:
73 assert not _core.currently_ki_protected()
74
75 protected()
76
77 @_core.enable_ki_protection
78 async def aprotected() -> None:
79 assert _core.currently_ki_protected()
80 await aunprotected()
81
82 @_core.disable_ki_protection
83 async def aunprotected() -> None:
84 assert not _core.currently_ki_protected()
85
86 await aprotected()
87
88 # make sure that the decorator here overrides the automatic manipulation
89 # that start_soon() does:
90 async with _core.open_nursery() as nursery:
91 nursery.start_soon(aprotected)
92 nursery.start_soon(aunprotected)
93
94 @_core.enable_ki_protection
95 def gen_protected() -> Iterator[None]:
96 assert _core.currently_ki_protected()
97 yield
98
99 for _ in gen_protected():
100 pass
101
102 @_core.disable_ki_protection
103 def gen_unprotected() -> Iterator[None]:
104 assert not _core.currently_ki_protected()
105 yield
106
107 for _ in gen_unprotected():
108 pass
109
110
111 # This used to be broken due to
112 #
113 # https://bugs.python.org/issue29590
114 #
115 # Specifically, after a coroutine is resumed with .throw(), then the stack
116 # makes it look like the immediate caller is the function that called
117 # .throw(), not the actual caller. So child() here would have a caller deep in
118 # the guts of the run loop, and always be protected, even when it shouldn't
119 # have been. (Solution: we don't use .throw() anymore.)
120 async def test_ki_enabled_after_yield_briefly() -> None:
121 @_core.enable_ki_protection
122 async def protected() -> None:
123 await child(True)
124
125 @_core.disable_ki_protection
126 async def unprotected() -> None:
127 await child(False)
128
129 async def child(expected: bool) -> None:
130 import traceback
131
132 traceback.print_stack()
133 assert _core.currently_ki_protected() == expected
134 await _core.checkpoint()
135 traceback.print_stack()
136 assert _core.currently_ki_protected() == expected
137
138 await protected()
139 await unprotected()
140
141
142 # This also used to be broken due to
143 # https://bugs.python.org/issue29590
144 async def test_generator_based_context_manager_throw() -> None:
145 @contextlib.contextmanager
146 @_core.enable_ki_protection
147 def protected_manager() -> Iterator[None]:
148 assert _core.currently_ki_protected()
149 try:
150 yield
151 finally:
152 assert _core.currently_ki_protected()
153
154 with protected_manager():
155 assert not _core.currently_ki_protected()
156
157 with pytest.raises(KeyError):
158 # This is the one that used to fail
159 with protected_manager():
160 raise KeyError
161
162
163 # the async_generator package isn't typed, hence all the type: ignores
164 @pytest.mark.skipif(async_generator is None, reason="async_generator not installed")
165 async def test_async_generator_agen_protection() -> None:
166 @_core.enable_ki_protection
167 @async_generator # type: ignore[untyped-decorator]
168 async def agen_protected1() -> None: # type: ignore[misc] # untyped generator
169 assert _core.currently_ki_protected()
170 try:
171 await yield_()
172 finally:
173 assert _core.currently_ki_protected()
174
175 @_core.disable_ki_protection
176 @async_generator # type: ignore[untyped-decorator]
177 async def agen_unprotected1() -> None: # type: ignore[misc] # untyped generator
178 assert not _core.currently_ki_protected()
179 try:
180 await yield_()
181 finally:
182 assert not _core.currently_ki_protected()
183
184 # Swap the order of the decorators:
185 @async_generator # type: ignore[untyped-decorator]
186 @_core.enable_ki_protection
187 async def agen_protected2() -> None: # type: ignore[misc] # untyped generator
188 assert _core.currently_ki_protected()
189 try:
190 await yield_()
191 finally:
192 assert _core.currently_ki_protected()
193
194 @async_generator # type: ignore[untyped-decorator]
195 @_core.disable_ki_protection
196 async def agen_unprotected2() -> None: # type: ignore[misc] # untyped generator
197 assert not _core.currently_ki_protected()
198 try:
199 await yield_()
200 finally:
201 assert not _core.currently_ki_protected()
202
203 await _check_agen(agen_protected1)
204 await _check_agen(agen_protected2)
205 await _check_agen(agen_unprotected1)
206 await _check_agen(agen_unprotected2)
207
208
209 async def test_native_agen_protection() -> None:
210 # Native async generators
211 @_core.enable_ki_protection
212 async def agen_protected() -> AsyncIterator[None]:
213 assert _core.currently_ki_protected()
214 try:
215 yield
216 finally:
217 assert _core.currently_ki_protected()
218
219 @_core.disable_ki_protection
220 async def agen_unprotected() -> AsyncIterator[None]:
221 assert not _core.currently_ki_protected()
222 try:
223 yield
224 finally:
225 assert not _core.currently_ki_protected()
226
227 await _check_agen(agen_protected)
228 await _check_agen(agen_unprotected)
229
230
231 async def _check_agen(agen_fn: Callable[[], AsyncIterator[None]]) -> None:
232 async for _ in agen_fn():
233 assert not _core.currently_ki_protected()
234
235 # asynccontextmanager insists that the function passed must itself be an
236 # async gen function, not a wrapper around one
237 if inspect.isasyncgenfunction(agen_fn):
238 async with contextlib.asynccontextmanager(agen_fn)():
239 assert not _core.currently_ki_protected()
240
241 # Another case that's tricky due to:
242 # https://bugs.python.org/issue29590
243 with pytest.raises(KeyError):
244 async with contextlib.asynccontextmanager(agen_fn)():
245 raise KeyError
246
247
248 # Test the case where there's no magic local anywhere in the call stack
249 def test_ki_disabled_out_of_context() -> None:
250 assert _core.currently_ki_protected()
251
252
253 def test_ki_disabled_in_del() -> None:
254 def nestedfunction() -> bool:
255 return _core.currently_ki_protected()
256
257 def __del__() -> None:
258 assert _core.currently_ki_protected()
259 assert nestedfunction()
260
261 @_core.disable_ki_protection
262 def outerfunction() -> None:
263 assert not _core.currently_ki_protected()
264 assert not nestedfunction()
265 __del__()
266
267 __del__()
268 outerfunction()
269 assert nestedfunction()
270
271
272 def test_ki_protection_works() -> None:
273 async def sleeper(name: str, record: set[str]) -> None:
274 try:
275 while True:
276 await _core.checkpoint()
277 except _core.Cancelled:
278 record.add(name + " ok")
279
280 async def raiser(name: str, record: set[str]) -> None:
281 try:
282 # os.kill runs signal handlers before returning, so we don't need
283 # to worry that the handler will be delayed
284 print("killing, protection =", _core.currently_ki_protected())
285 ki_self()
286 except KeyboardInterrupt:
287 print("raised!")
288 # Make sure we aren't getting cancelled as well as siginted
289 await _core.checkpoint()
290 record.add(name + " raise ok")
291 raise
292 else:
293 print("didn't raise!")
294 # If we didn't raise (b/c protected), then we *should* get
295 # cancelled at the next opportunity
296 try:
297 await _core.wait_task_rescheduled(lambda _: _core.Abort.SUCCEEDED)
298 except _core.Cancelled:
299 record.add(name + " cancel ok")
300
301 # simulated control-C during raiser, which is *unprotected*
302 print("check 1")
303 record_set: set[str] = set()
304
305 async def check_unprotected_kill() -> None:
306 async with _core.open_nursery() as nursery:
307 nursery.start_soon(sleeper, "s1", record_set)
308 nursery.start_soon(sleeper, "s2", record_set)
309 nursery.start_soon(raiser, "r1", record_set)
310
311 # raises inside a nursery, so the KeyboardInterrupt is wrapped in an ExceptionGroup
312 with pytest.RaisesGroup(KeyboardInterrupt):
313 _core.run(check_unprotected_kill)
314 assert record_set == {"s1 ok", "s2 ok", "r1 raise ok"}
315
316 # simulated control-C during raiser, which is *protected*, so the KI gets
317 # delivered to the main task instead
318 print("check 2")
319 record_set = set()
320
321 async def check_protected_kill() -> None:
322 async with _core.open_nursery() as nursery:
323 nursery.start_soon(sleeper, "s1", record_set)
324 nursery.start_soon(sleeper, "s2", record_set)
325 nursery.start_soon(_core.enable_ki_protection(raiser), "r1", record_set)
326 # __aexit__ blocks, and then receives the KI
327
328 # raises inside a nursery, so the KeyboardInterrupt is wrapped in an ExceptionGroup
329 with pytest.RaisesGroup(KeyboardInterrupt):
330 _core.run(check_protected_kill)
331 assert record_set == {"s1 ok", "s2 ok", "r1 cancel ok"}
332
333 # kill at last moment still raises (run_sync_soon until it raises an
334 # error, then kill)
335 print("check 3")
336
337 async def check_kill_during_shutdown() -> None:
338 token = _core.current_trio_token()
339
340 def kill_during_shutdown() -> None:
341 assert _core.currently_ki_protected()
342 try:
343 token.run_sync_soon(kill_during_shutdown)
344 except _core.RunFinishedError:
345 # it's too late for regular handling! handle this!
346 print("kill! kill!")
347 ki_self()
348
349 token.run_sync_soon(kill_during_shutdown)
350
351 # no nurseries involved, so the KeyboardInterrupt isn't wrapped
352 with pytest.raises(KeyboardInterrupt):
353 _core.run(check_kill_during_shutdown)
354
355 # KI arrives very early, before main is even spawned
356 print("check 4")
357
358 class InstrumentOfDeath(Instrument):
359 def before_run(self) -> None:
360 ki_self()
361
362 async def main_1() -> None:
363 await _core.checkpoint()
364
365 # no nurseries involved, so the KeyboardInterrupt isn't wrapped
366 with pytest.raises(KeyboardInterrupt):
367 _core.run(main_1, instruments=[InstrumentOfDeath()])
368
369 # checkpoint_if_cancelled notices pending KI
370 print("check 5")
371
372 @_core.enable_ki_protection
373 async def main_2() -> None:
374 assert _core.currently_ki_protected()
375 ki_self()
376 with pytest.raises(KeyboardInterrupt):
377 await _core.checkpoint_if_cancelled()
378
379 _core.run(main_2)
380
381 # KI arrives while main task is not abortable, b/c already scheduled
382 print("check 6")
383
384 @_core.enable_ki_protection
385 async def main_3() -> None:
386 assert _core.currently_ki_protected()
387 ki_self()
388 await _core.cancel_shielded_checkpoint()
389 await _core.cancel_shielded_checkpoint()
390 await _core.cancel_shielded_checkpoint()
391 with pytest.raises(KeyboardInterrupt):
392 await _core.checkpoint()
393
394 _core.run(main_3)
395
396 # KI arrives while main task is not abortable, b/c refuses to be aborted
397 print("check 7")
398
399 @_core.enable_ki_protection
400 async def main_4() -> None:
401 assert _core.currently_ki_protected()
402 ki_self()
403 task = _core.current_task()
404
405 def abort(_: RaiseCancelT) -> Abort:
406 _core.reschedule(task, outcome.Value(1))
407 return _core.Abort.FAILED
408
409 assert await _core.wait_task_rescheduled(abort) == 1
410 with pytest.raises(KeyboardInterrupt):
411 await _core.checkpoint()
412
413 _core.run(main_4)
414
415 # KI delivered via slow abort
416 print("check 8")
417
418 @_core.enable_ki_protection
419 async def main_5() -> None:
420 assert _core.currently_ki_protected()
421 ki_self()
422 task = _core.current_task()
423
424 def abort(raise_cancel: RaiseCancelT) -> Abort:
425 result = outcome.capture(raise_cancel)
426 _core.reschedule(task, result)
427 return _core.Abort.FAILED
428
429 with pytest.raises(KeyboardInterrupt):
430 assert await _core.wait_task_rescheduled(abort)
431 await _core.checkpoint()
432
433 _core.run(main_5)
434
435 # KI arrives just before main task exits, so the run_sync_soon machinery
436 # is still functioning and will accept the callback to deliver the KI, but
437 # by the time the callback is actually run, main has exited and can't be
438 # aborted.
439 print("check 9")
440
441 @_core.enable_ki_protection
442 async def main_6() -> None:
443 ki_self()
444
445 with pytest.raises(KeyboardInterrupt):
446 _core.run(main_6)
447
448 print("check 10")
449 # KI in unprotected code, with
450 # restrict_keyboard_interrupt_to_checkpoints=True
451 record_list = []
452
453 async def main_7() -> None:
454 # We're not KI protected...
455 assert not _core.currently_ki_protected()
456 ki_self()
457 # ...but even after the KI, we keep running uninterrupted...
458 record_list.append("ok")
459 # ...until we hit a checkpoint:
460 with pytest.raises(KeyboardInterrupt):
461 await sleep(10)
462
463 _core.run(main_7, restrict_keyboard_interrupt_to_checkpoints=True)
464 assert record_list == ["ok"]
465 record_list = []
466 # Exact same code raises KI early if we leave off the argument, doesn't
467 # even reach the record.append call:
468 with pytest.raises(KeyboardInterrupt):
469 _core.run(main_7)
470 assert record_list == []
471
472 # KI arrives while main task is inside a cancelled cancellation scope
473 # the KeyboardInterrupt should take priority
474 print("check 11")
475
476 @_core.enable_ki_protection
477 async def main_8() -> None:
478 assert _core.currently_ki_protected()
479 with _core.CancelScope() as cancel_scope:
480 cancel_scope.cancel()
481 with pytest.raises(_core.Cancelled):
482 await _core.checkpoint()
483 ki_self()
484 with pytest.raises(KeyboardInterrupt):
485 await _core.checkpoint()
486 with pytest.raises(_core.Cancelled):
487 await _core.checkpoint()
488
489 _core.run(main_8)
490
491
492 def test_ki_is_good_neighbor() -> None:
493 # in the unlikely event someone overwrites our signal handler, we leave
494 # the overwritten one be
495 try:
496 orig = signal.getsignal(signal.SIGINT)
497
498 def my_handler(signum: object, frame: object) -> None: # pragma: no cover
499 pass
500
501 async def main() -> None:
502 signal.signal(signal.SIGINT, my_handler)
503
504 _core.run(main)
505
506 assert signal.getsignal(signal.SIGINT) is my_handler
507 finally:
508 signal.signal(signal.SIGINT, orig)
509
510
511 # Regression test for #461
512 # don't know if _active not being visible is a problem
513 def test_ki_with_broken_threads() -> None:
514 thread = threading.main_thread()
515
516 # scary!
517 original = threading._active[thread.ident] # type: ignore[attr-defined]
518
519 # put this in a try finally so we don't have a chance of cascading a
520 # breakage down to everything else
521 try:
522 del threading._active[thread.ident] # type: ignore[attr-defined]
523
524 @_core.enable_ki_protection
525 async def inner() -> None:
526 assert signal.getsignal(signal.SIGINT) != signal.default_int_handler
527
528 _core.run(inner)
529 finally:
530 threading._active[thread.ident] = original # type: ignore[attr-defined]
531
532
533 _T = TypeVar("_T")
534
535
536 def _identity(v: _T) -> _T:
537 return v
538
539
540 @pytest.mark.xfail(
541 strict=True,
542 raises=AssertionError,
543 reason=(
544 "it was decided not to protect against this case, see discussion in: "
545 "https://github.com/python-trio/trio/pull/3110#discussion_r1802123644"
546 ),
547 )
548 async def test_ki_does_not_leak_across_different_calls_to_inner_functions() -> None:
549 assert not _core.currently_ki_protected()
550
551 def factory(enabled: bool) -> Callable[[], bool]:
552 @_core.enable_ki_protection if enabled else _identity
553 def decorated() -> bool:
554 return _core.currently_ki_protected()
555
556 return decorated
557
558 decorated_enabled = factory(True)
559 decorated_disabled = factory(False)
560 assert decorated_enabled()
561 assert not decorated_disabled()
562
563
564 async def test_ki_protection_check_does_not_freeze_locals() -> None:
565 class A:
566 pass
567
568 a = A()
569 wr_a = weakref.ref(a)
570 assert not _core.currently_ki_protected()
571 del a
572 if sys.implementation.name == "pypy":
573 gc_collect_harder()
574 assert wr_a() is None
575
576
577 def test_identity_weakref_internals() -> None:
578 """To cover the parts WeakKeyIdentityDictionary won't ever reach."""
579
580 class A:
581 def __eq__(self, other: object) -> bool:
582 return False
583
584 a = A()
585 assert a != a
586 wr = _ki._IdRef(a)
587 wr_other_is_self = wr
588
589 # dict always checks identity before equality so we need to do it here
590 # to cover `if self is other`
591 assert wr == wr_other_is_self
592
593 # we want to cover __ne__ and `return NotImplemented`
594 assert wr != object()
595
596
597 def test_weak_key_identity_dict_remove_callback_keyerror() -> None:
598 """We need to cover the KeyError in self._remove."""
599
600 class A:
601 def __eq__(self, other: object) -> bool:
602 return False
603
604 a = A()
605 assert a != a
606 d: _ki.WeakKeyIdentityDictionary[A, bool] = _ki.WeakKeyIdentityDictionary()
607
608 d[a] = True
609
610 data_copy = d._data.copy()
611 d._data.clear()
612 del a
613
614 gc_collect_harder() # would call sys.unraisablehook if there's a problem
615 assert data_copy
616
617
618 def test_weak_key_identity_dict_remove_callback_selfref_expired() -> None:
619 """We need to cover the KeyError in self._remove."""
620
621 class A:
622 def __eq__(self, other: object) -> bool:
623 return False
624
625 a = A()
626 assert a != a
627 d: _ki.WeakKeyIdentityDictionary[A, bool] = _ki.WeakKeyIdentityDictionary()
628
629 d[a] = True
630
631 data_copy = d._data.copy()
632 wr_d = weakref.ref(d)
633 del d
634 gc_collect_harder() # would call sys.unraisablehook if there's a problem
635 assert wr_d() is None
636 del a
637 gc_collect_harder()
638 assert data_copy
639
640
641 @_core.enable_ki_protection
642 async def _protected_async_gen_fn() -> AsyncGenerator[None, None]:
643 yield
644
645
646 @_core.enable_ki_protection
647 async def _protected_async_fn() -> None:
648 pass
649
650
651 @_core.enable_ki_protection
652 def _protected_gen_fn() -> Generator[None, None, None]:
653 yield
654
655
656 @_core.disable_ki_protection
657 async def _unprotected_async_gen_fn() -> AsyncGenerator[None, None]:
658 yield
659
660
661 @_core.disable_ki_protection
662 async def _unprotected_async_fn() -> None:
663 pass
664
665
666 @_core.disable_ki_protection
667 def _unprotected_gen_fn() -> Generator[None, None, None]:
668 yield
669
670
671 async def _consume_async_generator(agen: AsyncGeneratorType[object, Never]) -> None:
672 try:
673 with pytest.raises(StopAsyncIteration):
674 while True:
675 await agen.asend(None) # type: ignore[arg-type]
676 finally:
677 await agen.aclose()
678
679
680 def _consume_function_for_coverage(
681 fn: Callable[[], object],
682 ) -> None:
683 result = fn()
684 if inspect.isasyncgen(result):
685 result = _consume_async_generator(result)
686
687 assert inspect.isgenerator(result) or inspect.iscoroutine(result)
688 with pytest.raises(StopIteration):
689 while True:
690 result.send(None) # type: ignore[arg-type]
691
692
693 def test_enable_disable_ki_protection_passes_on_inspect_flags() -> None:
694 assert inspect.isasyncgenfunction(_protected_async_gen_fn)
695 _consume_function_for_coverage(_protected_async_gen_fn)
696 assert inspect.iscoroutinefunction(_protected_async_fn)
697 _consume_function_for_coverage(_protected_async_fn)
698 assert inspect.isgeneratorfunction(_protected_gen_fn)
699 _consume_function_for_coverage(_protected_gen_fn)
700 assert inspect.isasyncgenfunction(_unprotected_async_gen_fn)
701 _consume_function_for_coverage(_unprotected_async_gen_fn)
702 assert inspect.iscoroutinefunction(_unprotected_async_fn)
703 _consume_function_for_coverage(_unprotected_async_fn)
704 assert inspect.isgeneratorfunction(_unprotected_gen_fn)
705 _consume_function_for_coverage(_unprotected_gen_fn)