Compare commits
265 Commits
2b02977cf7
...
f8563bad72
Author | SHA1 | Date |
---|---|---|
|
f8563bad72 | |
|
3562a4173a | |
|
83ce2275b9 | |
|
9f757ffa63 | |
|
0c6d512ba4 | |
|
fc130d06b8 | |
|
73423ef2b7 | |
|
b1f2a6b394 | |
|
9489a2f84d | |
|
92eaed6fec | |
|
217d54b9d1 | |
|
34ca02ed11 | |
|
62a364a1d3 | |
|
07781e38cd | |
|
9c6b90ef04 | |
|
542d4c7840 | |
|
9aebe7d8f9 | |
|
04c3d5e239 | |
|
759174729c | |
|
e9f3689191 | |
|
93aa39db07 | |
|
5ab642bdf0 | |
|
ed18ecd064 | |
|
cec0282953 | |
|
25c5847f2e | |
|
ba793fadd9 | |
|
d17864a432 | |
|
6c361a9564 | |
|
34ca7429c7 | |
|
c9a55c2d46 | |
|
548855b4f5 | |
|
5322861d6d | |
|
46a2fa7074 | |
|
bfe5b2dde6 | |
|
a9f06df3fb | |
|
ee32bc433c | |
|
561954594e | |
|
28a6354e81 | |
|
d1599449e7 | |
|
2d27c94dec | |
|
6e4c76245b | |
|
a6f599901c | |
|
0fafd25f0d | |
|
b74e93ee55 | |
|
961504b657 | |
|
bd148300c5 | |
|
4a7491bda4 | |
|
62415518fc | |
|
5c7d930a9a | |
|
c46986504d | |
|
e05a4d3cac | |
|
a9aa5ec04e | |
|
5021514a6a | |
|
79f502034f | |
|
331921f612 | |
|
df0d00abf4 | |
|
a72d1e6c48 | |
|
5931c59aef | |
|
ba08052ddf | |
|
00112edd58 | |
|
1d706bddda | |
|
3c30c559d5 | |
|
599020c2c5 | |
|
50f6543ee7 | |
|
c0854fd221 | |
|
e875b62869 | |
|
3ab7498893 | |
|
dd041b0a01 | |
|
4e252526b5 | |
|
4ba3590450 | |
|
f1ff79a4e6 | |
|
70664b98de | |
|
1c425cbd22 | |
|
edc2211444 | |
|
b05abea51e | |
|
88c1c083bd | |
|
b096867d40 | |
|
a3c9822602 | |
|
e3a542f2b5 | |
|
0ffcea1033 | |
|
a7bdf0486c | |
|
d2ac9ecf95 | |
|
dcb1062bb8 | |
|
05d865c0f1 | |
|
8218f0f51f | |
|
8f19f5d3a8 | |
|
64c27a914b | |
|
d9c8d543b3 | |
|
048b154f00 | |
|
88828e9f99 | |
|
25ff195c17 | |
|
f60cc646ff | |
|
a2b754b5f5 | |
|
5e13588aed | |
|
0a56f40bab | |
|
f776c47cb4 | |
|
7f584d4f54 | |
|
d650dda0fa | |
|
f6598e8400 | |
|
59822ff093 | |
|
ca427aec7e | |
|
f53aa992af | |
|
69e0afccf0 | |
|
e275c49b23 | |
|
48fbf38c1d | |
|
defd6e28d2 | |
|
414b0e2bae | |
|
d34fb54f7c | |
|
5d87f63377 | |
|
0ca3d50602 | |
|
8880a80e3e | |
|
7be713ee1e | |
|
4bd8211abb | |
|
a23a98886c | |
|
31544c862c | |
|
7d320c4e1e | |
|
38944ad1d2 | |
|
9260909fe1 | |
|
c00b3c86ea | |
|
808a336508 | |
|
679d999185 | |
|
a8428d7de3 | |
|
e9f2fecd66 | |
|
547cf5a210 | |
|
b5e3fa7370 | |
|
cd16748598 | |
|
1af35f8170 | |
|
4569d11052 | |
|
6ba76ab700 | |
|
734dda35e9 | |
|
b7e04525cc | |
|
35977dcebb | |
|
e1f26f9611 | |
|
63c5b7696a | |
|
5f94f52226 | |
|
6bf571a124 | |
|
f5056cdd02 | |
|
9ff448faa3 | |
|
760b9890c4 | |
|
d000642462 | |
|
dd69948744 | |
|
5b69975f81 | |
|
6b474743f9 | |
|
5ac229244a | |
|
bbd2ea3e4f | |
|
6b903f7746 | |
|
2280bad135 | |
|
8d506796ec | |
|
02d03ce700 | |
|
9786e2c404 | |
|
116137d066 | |
|
7f87b4e717 | |
|
bb17d39c4e | |
|
fba6edfe9a | |
|
e4758550f7 | |
|
a7efbfdbc2 | |
|
1c6660c497 | |
|
202befa360 | |
|
c24708b273 | |
|
3aee702733 | |
|
a573c3c9a8 | |
|
6a352fee87 | |
|
6cb361352c | |
|
7807ffaabe | |
|
65b795612c | |
|
a42c1761a8 | |
|
359d732633 | |
|
b09e35f3dc | |
|
6618b004f4 | |
|
fc57a4d639 | |
|
2248ffb74f | |
|
1eb0d785a8 | |
|
98d0ca88e5 | |
|
37f843a128 | |
|
29cd2ddbac | |
|
295b06511b | |
|
1e6b5b3f0a | |
|
36ddb85197 | |
|
d6b0ddecd7 | |
|
9e5475391c | |
|
ef7ed7ac6f | |
|
d8094f4420 | |
|
d7b12735a8 | |
|
47107e44ed | |
|
ba384ca83d | |
|
ad9833a73a | |
|
161884fbf1 | |
|
c2e7dc7407 | |
|
309360daa2 | |
|
cbfb0d0144 | |
|
c0eef3bac3 | |
|
27e6ad18ee | |
|
28e32b8f85 | |
|
05df634d62 | |
|
6d2f4d108d | |
|
ae2687b381 | |
|
a331f6dab3 | |
|
9c0de24899 | |
|
1f3cef5ed6 | |
|
8538a9c591 | |
|
7533e93b0f | |
|
f67b0639b8 | |
|
26fedec6a1 | |
|
0711576678 | |
|
0477a62ac3 | |
|
01d6f111f6 | |
|
56ef4cba23 | |
|
52b5efd78d | |
|
a7d4bcdfb9 | |
|
79d0c17f6b | |
|
98c4614a36 | |
|
61df10b333 | |
|
094447787e | |
|
ba45c03e14 | |
|
00d8a2a099 | |
|
bedde076d9 | |
|
be1d8bf6fa | |
|
d9aee98db2 | |
|
708ce4a051 | |
|
d6d0112d95 | |
|
0fcbedd2be | |
|
412c66d000 | |
|
3cc835c215 | |
|
f15bbb30cc | |
|
ad211f8c2c | |
|
acac605c37 | |
|
078e507774 | |
|
81bf810fbb | |
|
7d1512e03a | |
|
1c85338ff8 | |
|
7a3c9d0458 | |
|
31196b9cb4 | |
|
44c9da1c91 | |
|
b4ce618e33 | |
|
a504d92536 | |
|
8c0d9614bc | |
|
a6fefcc2a8 | |
|
abdaf7bf1f | |
|
7b3324b240 | |
|
bbae2c91fd | |
|
2540d1f9e0 | |
|
63fac5a809 | |
|
568fb18d01 | |
|
f67e19a852 | |
|
0be9f5f907 | |
|
5e2d456029 | |
|
c7d5b021db | |
|
6f1f198fb1 | |
|
26fef82d33 | |
|
84d25b5727 | |
|
1ed0c861b5 | |
|
2dd3a682c8 | |
|
881813e61e | |
|
566a11c00d | |
|
af69272d16 | |
|
8e3f581d3f | |
|
eceb292415 | |
|
9921ea3cae | |
|
414a8c5b75 | |
|
eeb0516017 | |
|
d6eeddef4e | |
|
d478dbfcfe | |
|
ef6094a650 | |
|
4e8404bb09 | |
|
bbb3484ae9 |
|
@ -8,46 +8,70 @@ on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
# ------ sdist ------
|
||||||
mypy:
|
|
||||||
name: 'MyPy'
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v2
|
|
||||||
|
|
||||||
- name: Setup python
|
|
||||||
uses: actions/setup-python@v2
|
|
||||||
with:
|
|
||||||
python-version: '3.11'
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: pip install -U . --upgrade-strategy eager -r requirements-test.txt
|
|
||||||
|
|
||||||
- name: Run MyPy check
|
|
||||||
run: mypy tractor/ --ignore-missing-imports --show-traceback
|
|
||||||
|
|
||||||
# test that we can generate a software distribution and install it
|
# test that we can generate a software distribution and install it
|
||||||
# thus avoid missing file issues after packaging.
|
# thus avoid missing file issues after packaging.
|
||||||
|
#
|
||||||
|
# -[x] produce sdist with uv
|
||||||
|
# ------ - ------
|
||||||
sdist-linux:
|
sdist-linux:
|
||||||
name: 'sdist'
|
name: 'sdist'
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Setup python
|
- name: Install latest uv
|
||||||
uses: actions/setup-python@v2
|
uses: astral-sh/setup-uv@v6
|
||||||
with:
|
|
||||||
python-version: '3.11'
|
|
||||||
|
|
||||||
- name: Build sdist
|
- name: Build sdist as tar.gz
|
||||||
run: python setup.py sdist --formats=zip
|
run: uv build --sdist --python=3.13
|
||||||
|
|
||||||
- name: Install sdist from .zips
|
- name: Install sdist from .tar.gz
|
||||||
run: python -m pip install dist/*.zip
|
run: python -m pip install dist/*.tar.gz
|
||||||
|
|
||||||
|
# ------ type-check ------
|
||||||
|
# mypy:
|
||||||
|
# name: 'MyPy'
|
||||||
|
# runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
# steps:
|
||||||
|
# - name: Checkout
|
||||||
|
# uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# - name: Install latest uv
|
||||||
|
# uses: astral-sh/setup-uv@v6
|
||||||
|
|
||||||
|
# # faster due to server caching?
|
||||||
|
# # https://docs.astral.sh/uv/guides/integration/github/#setting-up-python
|
||||||
|
# - name: "Set up Python"
|
||||||
|
# uses: actions/setup-python@v6
|
||||||
|
# with:
|
||||||
|
# python-version-file: "pyproject.toml"
|
||||||
|
|
||||||
|
# # w uv
|
||||||
|
# # - name: Set up Python
|
||||||
|
# # run: uv python install
|
||||||
|
|
||||||
|
# - name: Setup uv venv
|
||||||
|
# run: uv venv .venv --python=3.13
|
||||||
|
|
||||||
|
# - name: Install
|
||||||
|
# run: uv sync --dev
|
||||||
|
|
||||||
|
# # TODO, ty cmd over repo
|
||||||
|
# # - name: type check with ty
|
||||||
|
# # run: ty ./tractor/
|
||||||
|
|
||||||
|
# # - uses: actions/cache@v3
|
||||||
|
# # name: Cache uv virtenv as default .venv
|
||||||
|
# # with:
|
||||||
|
# # path: ./.venv
|
||||||
|
# # key: venv-${{ hashFiles('uv.lock') }}
|
||||||
|
|
||||||
|
# - name: Run MyPy check
|
||||||
|
# run: mypy tractor/ --ignore-missing-imports --show-traceback
|
||||||
|
|
||||||
|
|
||||||
testing-linux:
|
testing-linux:
|
||||||
|
@ -59,32 +83,45 @@ jobs:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
os: [ubuntu-latest]
|
os: [ubuntu-latest]
|
||||||
python: ['3.11']
|
python-version: ['3.13']
|
||||||
spawn_backend: [
|
spawn_backend: [
|
||||||
'trio',
|
'trio',
|
||||||
'mp_spawn',
|
# 'mp_spawn',
|
||||||
'mp_forkserver',
|
# 'mp_forkserver',
|
||||||
]
|
]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
|
|
||||||
- name: Checkout
|
- uses: actions/checkout@v4
|
||||||
uses: actions/checkout@v2
|
|
||||||
|
|
||||||
- name: Setup python
|
- name: 'Install uv + py-${{ matrix.python-version }}'
|
||||||
uses: actions/setup-python@v2
|
uses: astral-sh/setup-uv@v6
|
||||||
with:
|
with:
|
||||||
python-version: '${{ matrix.python }}'
|
python-version: ${{ matrix.python-version }}
|
||||||
|
|
||||||
- name: Install dependencies
|
# GH way.. faster?
|
||||||
run: pip install -U . -r requirements-test.txt -r requirements-docs.txt --upgrade-strategy eager
|
# - name: setup-python@v6
|
||||||
|
# uses: actions/setup-python@v6
|
||||||
|
# with:
|
||||||
|
# python-version: '${{ matrix.python-version }}'
|
||||||
|
|
||||||
- name: List dependencies
|
# consider caching for speedups?
|
||||||
run: pip list
|
# https://docs.astral.sh/uv/guides/integration/github/#caching
|
||||||
|
|
||||||
|
- name: Install the project w uv
|
||||||
|
run: uv sync --all-extras --dev
|
||||||
|
|
||||||
|
# - name: Install dependencies
|
||||||
|
# run: pip install -U . -r requirements-test.txt -r requirements-docs.txt --upgrade-strategy eager
|
||||||
|
|
||||||
|
- name: List deps tree
|
||||||
|
run: uv tree
|
||||||
|
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: pytest tests/ --spawn-backend=${{ matrix.spawn_backend }} -rsx
|
run: uv run pytest tests/ --spawn-backend=${{ matrix.spawn_backend }} -rsx
|
||||||
|
|
||||||
|
# XXX legacy NOTE XXX
|
||||||
|
#
|
||||||
# We skip 3.10 on windows for now due to not having any collabs to
|
# We skip 3.10 on windows for now due to not having any collabs to
|
||||||
# debug the CI failures. Anyone wanting to hack and solve them is very
|
# debug the CI failures. Anyone wanting to hack and solve them is very
|
||||||
# welcome, but our primary user base is not using that OS.
|
# welcome, but our primary user base is not using that OS.
|
||||||
|
|
|
@ -1,8 +1,5 @@
|
||||||
|logo| ``tractor``: distributed structurred concurrency
|
|logo| ``tractor``: distributed structurred concurrency
|
||||||
|
|
||||||
|gh_actions|
|
|
||||||
|docs|
|
|
||||||
|
|
||||||
``tractor`` is a `structured concurrency`_ (SC), multi-processing_ runtime built on trio_.
|
``tractor`` is a `structured concurrency`_ (SC), multi-processing_ runtime built on trio_.
|
||||||
|
|
||||||
Fundamentally, ``tractor`` provides parallelism via
|
Fundamentally, ``tractor`` provides parallelism via
|
||||||
|
@ -66,6 +63,13 @@ Features
|
||||||
- (WIP) a ``TaskMngr``: one-cancels-one style nursery supervisor.
|
- (WIP) a ``TaskMngr``: one-cancels-one style nursery supervisor.
|
||||||
|
|
||||||
|
|
||||||
|
Status of `main` / infra
|
||||||
|
------------------------
|
||||||
|
|
||||||
|
- |gh_actions|
|
||||||
|
- |docs|
|
||||||
|
|
||||||
|
|
||||||
Install
|
Install
|
||||||
-------
|
-------
|
||||||
``tractor`` is still in a *alpha-near-beta-stage* for many
|
``tractor`` is still in a *alpha-near-beta-stage* for many
|
||||||
|
@ -689,9 +693,11 @@ channel`_!
|
||||||
.. _msgspec: https://jcristharif.com/msgspec/
|
.. _msgspec: https://jcristharif.com/msgspec/
|
||||||
.. _guest: https://trio.readthedocs.io/en/stable/reference-lowlevel.html?highlight=guest%20mode#using-guest-mode-to-run-trio-on-top-of-other-event-loops
|
.. _guest: https://trio.readthedocs.io/en/stable/reference-lowlevel.html?highlight=guest%20mode#using-guest-mode-to-run-trio-on-top-of-other-event-loops
|
||||||
|
|
||||||
|
..
|
||||||
.. |gh_actions| image:: https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fgoodboy%2Ftractor%2Fbadge&style=popout-square
|
NOTE, on generating badge links from the UI
|
||||||
:target: https://actions-badge.atrox.dev/goodboy/tractor/goto
|
https://docs.github.com/en/actions/how-tos/monitoring-and-troubleshooting-workflows/monitoring-workflows/adding-a-workflow-status-badge?ref=gitguardian-blog-automated-secrets-detection#using-the-ui
|
||||||
|
.. |gh_actions| image:: https://github.com/goodboy/tractor/actions/workflows/ci.yml/badge.svg?branch=main
|
||||||
|
:target: https://github.com/goodboy/tractor/actions/workflows/ci.yml
|
||||||
|
|
||||||
.. |docs| image:: https://readthedocs.org/projects/tractor/badge/?version=latest
|
.. |docs| image:: https://readthedocs.org/projects/tractor/badge/?version=latest
|
||||||
:target: https://tractor.readthedocs.io/en/latest/?badge=latest
|
:target: https://tractor.readthedocs.io/en/latest/?badge=latest
|
||||||
|
|
|
@ -16,6 +16,7 @@ from tractor import (
|
||||||
ContextCancelled,
|
ContextCancelled,
|
||||||
MsgStream,
|
MsgStream,
|
||||||
_testing,
|
_testing,
|
||||||
|
trionics,
|
||||||
)
|
)
|
||||||
import trio
|
import trio
|
||||||
import pytest
|
import pytest
|
||||||
|
@ -62,9 +63,8 @@ async def recv_and_spawn_net_killers(
|
||||||
await ctx.started()
|
await ctx.started()
|
||||||
async with (
|
async with (
|
||||||
ctx.open_stream() as stream,
|
ctx.open_stream() as stream,
|
||||||
trio.open_nursery(
|
trionics.collapse_eg(),
|
||||||
strict_exception_groups=False,
|
trio.open_nursery() as tn,
|
||||||
) as tn,
|
|
||||||
):
|
):
|
||||||
async for i in stream:
|
async for i in stream:
|
||||||
print(f'child echoing {i}')
|
print(f'child echoing {i}')
|
||||||
|
|
|
@ -0,0 +1,35 @@
|
||||||
|
import trio
|
||||||
|
import tractor
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
async with tractor.open_root_actor(
|
||||||
|
debug_mode=True,
|
||||||
|
loglevel='cancel',
|
||||||
|
) as _root:
|
||||||
|
|
||||||
|
# manually trigger self-cancellation and wait
|
||||||
|
# for it to fully trigger.
|
||||||
|
_root.cancel_soon()
|
||||||
|
await _root._cancel_complete.wait()
|
||||||
|
print('root cancelled')
|
||||||
|
|
||||||
|
# now ensure we can still use the REPL
|
||||||
|
try:
|
||||||
|
await tractor.pause()
|
||||||
|
except trio.Cancelled as _taskc:
|
||||||
|
assert (root_cs := _root._root_tn.cancel_scope).cancel_called
|
||||||
|
# NOTE^^ above logic but inside `open_root_actor()` and
|
||||||
|
# passed to the `shield=` expression is effectively what
|
||||||
|
# we're testing here!
|
||||||
|
await tractor.pause(shield=root_cs.cancel_called)
|
||||||
|
|
||||||
|
# XXX, if shield logic *is wrong* inside `open_root_actor()`'s
|
||||||
|
# crash-handler block this should never be interacted,
|
||||||
|
# instead `trio.Cancelled` would be bubbled up: the original
|
||||||
|
# BUG.
|
||||||
|
assert 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
trio.run(main)
|
|
@ -23,9 +23,8 @@ async def main():
|
||||||
modules=[__name__]
|
modules=[__name__]
|
||||||
) as portal_map,
|
) as portal_map,
|
||||||
|
|
||||||
trio.open_nursery(
|
tractor.trionics.collapse_eg(),
|
||||||
strict_exception_groups=False,
|
trio.open_nursery() as tn,
|
||||||
) as tn,
|
|
||||||
):
|
):
|
||||||
|
|
||||||
for (name, portal) in portal_map.items():
|
for (name, portal) in portal_map.items():
|
||||||
|
|
|
@ -0,0 +1,85 @@
|
||||||
|
from contextlib import (
|
||||||
|
asynccontextmanager as acm,
|
||||||
|
)
|
||||||
|
from functools import partial
|
||||||
|
|
||||||
|
import tractor
|
||||||
|
import trio
|
||||||
|
|
||||||
|
|
||||||
|
log = tractor.log.get_logger(
|
||||||
|
name=__name__
|
||||||
|
)
|
||||||
|
|
||||||
|
_lock: trio.Lock|None = None
|
||||||
|
|
||||||
|
|
||||||
|
@acm
|
||||||
|
async def acquire_singleton_lock(
|
||||||
|
) -> None:
|
||||||
|
global _lock
|
||||||
|
if _lock is None:
|
||||||
|
log.info('Allocating LOCK')
|
||||||
|
_lock = trio.Lock()
|
||||||
|
|
||||||
|
log.info('TRYING TO LOCK ACQUIRE')
|
||||||
|
async with _lock:
|
||||||
|
log.info('ACQUIRED')
|
||||||
|
yield _lock
|
||||||
|
|
||||||
|
log.info('RELEASED')
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
async def hold_lock_forever(
|
||||||
|
task_status=trio.TASK_STATUS_IGNORED
|
||||||
|
):
|
||||||
|
async with (
|
||||||
|
tractor.trionics.maybe_raise_from_masking_exc(),
|
||||||
|
acquire_singleton_lock() as lock,
|
||||||
|
):
|
||||||
|
task_status.started(lock)
|
||||||
|
await trio.sleep_forever()
|
||||||
|
|
||||||
|
|
||||||
|
async def main(
|
||||||
|
ignore_special_cases: bool,
|
||||||
|
loglevel: str = 'info',
|
||||||
|
debug_mode: bool = True,
|
||||||
|
):
|
||||||
|
async with (
|
||||||
|
trio.open_nursery() as tn,
|
||||||
|
|
||||||
|
# tractor.trionics.maybe_raise_from_masking_exc()
|
||||||
|
# ^^^ XXX NOTE, interestingly putting the unmasker
|
||||||
|
# here does not exhibit the same behaviour ??
|
||||||
|
):
|
||||||
|
if not ignore_special_cases:
|
||||||
|
from tractor.trionics import _taskc
|
||||||
|
_taskc._mask_cases.clear()
|
||||||
|
|
||||||
|
_lock = await tn.start(
|
||||||
|
hold_lock_forever,
|
||||||
|
)
|
||||||
|
with trio.move_on_after(0.2):
|
||||||
|
await tn.start(
|
||||||
|
hold_lock_forever,
|
||||||
|
)
|
||||||
|
|
||||||
|
tn.cancel_scope.cancel()
|
||||||
|
|
||||||
|
|
||||||
|
# XXX, manual test as script
|
||||||
|
if __name__ == '__main__':
|
||||||
|
tractor.log.get_console_log(level='info')
|
||||||
|
for case in [True, False]:
|
||||||
|
log.info(
|
||||||
|
f'\n'
|
||||||
|
f'------ RUNNING SCRIPT TRIAL ------\n'
|
||||||
|
f'ignore_special_cases: {case!r}\n'
|
||||||
|
)
|
||||||
|
trio.run(partial(
|
||||||
|
main,
|
||||||
|
ignore_special_cases=case,
|
||||||
|
loglevel='info',
|
||||||
|
))
|
|
@ -0,0 +1,195 @@
|
||||||
|
from contextlib import (
|
||||||
|
contextmanager as cm,
|
||||||
|
# TODO, any diff in async case(s)??
|
||||||
|
# asynccontextmanager as acm,
|
||||||
|
)
|
||||||
|
from functools import partial
|
||||||
|
|
||||||
|
import tractor
|
||||||
|
import trio
|
||||||
|
|
||||||
|
|
||||||
|
log = tractor.log.get_logger(
|
||||||
|
name=__name__
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@cm
|
||||||
|
def teardown_on_exc(
|
||||||
|
raise_from_handler: bool = False,
|
||||||
|
):
|
||||||
|
'''
|
||||||
|
You could also have a teardown handler which catches any exc and
|
||||||
|
does some required teardown. In this case the problem is
|
||||||
|
compounded UNLESS you ensure the handler's scope is OUTSIDE the
|
||||||
|
`ux.aclose()`.. that is in the caller's enclosing scope.
|
||||||
|
|
||||||
|
'''
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
except BaseException as _berr:
|
||||||
|
berr = _berr
|
||||||
|
log.exception(
|
||||||
|
f'Handling termination teardown in child due to,\n'
|
||||||
|
f'{berr!r}\n'
|
||||||
|
)
|
||||||
|
if raise_from_handler:
|
||||||
|
# XXX teardown ops XXX
|
||||||
|
# on termination these steps say need to be run to
|
||||||
|
# ensure wider system consistency (like the state of
|
||||||
|
# remote connections/services).
|
||||||
|
#
|
||||||
|
# HOWEVER, any bug in this teardown code is also
|
||||||
|
# masked by the `tx.aclose()`!
|
||||||
|
# this is also true if `_tn.cancel_scope` is
|
||||||
|
# `.cancel_called` by the parent in a graceful
|
||||||
|
# request case..
|
||||||
|
|
||||||
|
# simulate a bug in teardown handler.
|
||||||
|
raise RuntimeError(
|
||||||
|
'woopsie teardown bug!'
|
||||||
|
)
|
||||||
|
|
||||||
|
raise # no teardown bug.
|
||||||
|
|
||||||
|
|
||||||
|
async def finite_stream_to_rent(
|
||||||
|
tx: trio.abc.SendChannel,
|
||||||
|
child_errors_mid_stream: bool,
|
||||||
|
raise_unmasked: bool,
|
||||||
|
|
||||||
|
task_status: trio.TaskStatus[
|
||||||
|
trio.CancelScope,
|
||||||
|
] = trio.TASK_STATUS_IGNORED,
|
||||||
|
):
|
||||||
|
async with (
|
||||||
|
# XXX without this unmasker the mid-streaming RTE is never
|
||||||
|
# reported since it is masked by the `tx.aclose()`
|
||||||
|
# call which in turn raises `Cancelled`!
|
||||||
|
#
|
||||||
|
# NOTE, this is WITHOUT doing any exception handling
|
||||||
|
# inside the child task!
|
||||||
|
#
|
||||||
|
# TODO, uncomment next LoC to see the supprsessed beg[RTE]!
|
||||||
|
tractor.trionics.maybe_raise_from_masking_exc(
|
||||||
|
raise_unmasked=raise_unmasked,
|
||||||
|
),
|
||||||
|
|
||||||
|
tx as tx, # .aclose() is the guilty masker chkpt!
|
||||||
|
|
||||||
|
# XXX, this ONLY matters in the
|
||||||
|
# `child_errors_mid_stream=False` case oddly!?
|
||||||
|
# THAT IS, if no tn is opened in that case then the
|
||||||
|
# test will not fail; it raises the RTE correctly?
|
||||||
|
#
|
||||||
|
# -> so it seems this new scope somehow affects the form of
|
||||||
|
# eventual in the parent EG?
|
||||||
|
tractor.trionics.maybe_open_nursery(
|
||||||
|
nursery=(
|
||||||
|
None
|
||||||
|
if not child_errors_mid_stream
|
||||||
|
else True
|
||||||
|
),
|
||||||
|
) as _tn,
|
||||||
|
):
|
||||||
|
# pass our scope back to parent for supervision\
|
||||||
|
# control.
|
||||||
|
cs: trio.CancelScope|None = (
|
||||||
|
None
|
||||||
|
if _tn is True
|
||||||
|
else _tn.cancel_scope
|
||||||
|
)
|
||||||
|
task_status.started(cs)
|
||||||
|
|
||||||
|
with teardown_on_exc(
|
||||||
|
raise_from_handler=not child_errors_mid_stream,
|
||||||
|
):
|
||||||
|
for i in range(100):
|
||||||
|
log.debug(
|
||||||
|
f'Child tx {i!r}\n'
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
child_errors_mid_stream
|
||||||
|
and
|
||||||
|
i == 66
|
||||||
|
):
|
||||||
|
# oh wait but WOOPS there's a bug
|
||||||
|
# in that teardown code!?
|
||||||
|
raise RuntimeError(
|
||||||
|
'woopsie, a mid-streaming bug!?'
|
||||||
|
)
|
||||||
|
|
||||||
|
await tx.send(i)
|
||||||
|
|
||||||
|
|
||||||
|
async def main(
|
||||||
|
# TODO! toggle this for the 2 cases!
|
||||||
|
# 1. child errors mid-stream while parent is also requesting
|
||||||
|
# (graceful) cancel of that child streamer.
|
||||||
|
#
|
||||||
|
# 2. child contains a teardown handler which contains a
|
||||||
|
# bug and raises.
|
||||||
|
#
|
||||||
|
child_errors_mid_stream: bool,
|
||||||
|
|
||||||
|
raise_unmasked: bool = False,
|
||||||
|
loglevel: str = 'info',
|
||||||
|
):
|
||||||
|
tractor.log.get_console_log(level=loglevel)
|
||||||
|
|
||||||
|
# the `.aclose()` being checkpoints on these
|
||||||
|
# is the source of the problem..
|
||||||
|
tx, rx = trio.open_memory_channel(1)
|
||||||
|
|
||||||
|
async with (
|
||||||
|
tractor.trionics.collapse_eg(),
|
||||||
|
trio.open_nursery() as tn,
|
||||||
|
rx as rx,
|
||||||
|
):
|
||||||
|
_child_cs = await tn.start(
|
||||||
|
partial(
|
||||||
|
finite_stream_to_rent,
|
||||||
|
child_errors_mid_stream=child_errors_mid_stream,
|
||||||
|
raise_unmasked=raise_unmasked,
|
||||||
|
tx=tx,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
async for msg in rx:
|
||||||
|
log.debug(
|
||||||
|
f'Rent rx {msg!r}\n'
|
||||||
|
)
|
||||||
|
|
||||||
|
# simulate some external cancellation
|
||||||
|
# request **JUST BEFORE** the child errors.
|
||||||
|
if msg == 65:
|
||||||
|
log.cancel(
|
||||||
|
f'Cancelling parent on,\n'
|
||||||
|
f'msg={msg}\n'
|
||||||
|
f'\n'
|
||||||
|
f'Simulates OOB cancel request!\n'
|
||||||
|
)
|
||||||
|
tn.cancel_scope.cancel()
|
||||||
|
|
||||||
|
|
||||||
|
# XXX, manual test as script
|
||||||
|
if __name__ == '__main__':
|
||||||
|
tractor.log.get_console_log(level='info')
|
||||||
|
for case in [True, False]:
|
||||||
|
log.info(
|
||||||
|
f'\n'
|
||||||
|
f'------ RUNNING SCRIPT TRIAL ------\n'
|
||||||
|
f'child_errors_midstream: {case!r}\n'
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
trio.run(partial(
|
||||||
|
main,
|
||||||
|
child_errors_mid_stream=case,
|
||||||
|
# raise_unmasked=True,
|
||||||
|
loglevel='info',
|
||||||
|
))
|
||||||
|
except Exception as _exc:
|
||||||
|
exc = _exc
|
||||||
|
log.exception(
|
||||||
|
'Should have raised an RTE or Cancelled?\n'
|
||||||
|
)
|
||||||
|
breakpoint()
|
|
@ -61,7 +61,9 @@ dev = [
|
||||||
# `tractor.devx` tooling
|
# `tractor.devx` tooling
|
||||||
"greenback>=1.2.1,<2",
|
"greenback>=1.2.1,<2",
|
||||||
"stackscope>=0.2.2,<0.3",
|
"stackscope>=0.2.2,<0.3",
|
||||||
"typing-extensions>=4.13.2", # needed for stackscope
|
# ^ requires this?
|
||||||
|
"typing-extensions>=4.14.1",
|
||||||
|
|
||||||
"pyperclip>=1.9.0",
|
"pyperclip>=1.9.0",
|
||||||
"prompt-toolkit>=3.0.50",
|
"prompt-toolkit>=3.0.50",
|
||||||
"xonsh>=0.19.2",
|
"xonsh>=0.19.2",
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
"""
|
"""
|
||||||
That "native" debug mode better work!
|
That "native" debug mode better work!
|
||||||
|
|
||||||
All these tests can be understood (somewhat) by running the equivalent
|
All these tests can be understood (somewhat) by running the
|
||||||
`examples/debugging/` scripts manually.
|
equivalent `examples/debugging/` scripts manually.
|
||||||
|
|
||||||
TODO:
|
TODO:
|
||||||
- none of these tests have been run successfully on windows yet but
|
- none of these tests have been run successfully on windows yet but
|
||||||
|
@ -925,6 +925,7 @@ def test_post_mortem_api(
|
||||||
"<Task 'name_error'",
|
"<Task 'name_error'",
|
||||||
"NameError",
|
"NameError",
|
||||||
"('child'",
|
"('child'",
|
||||||
|
'getattr(doggypants)', # exc-LoC
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
if ctlc:
|
if ctlc:
|
||||||
|
@ -941,8 +942,8 @@ def test_post_mortem_api(
|
||||||
"<Task '__main__.main'",
|
"<Task '__main__.main'",
|
||||||
"('root'",
|
"('root'",
|
||||||
"NameError",
|
"NameError",
|
||||||
"tractor.post_mortem()",
|
|
||||||
"src_uid=('child'",
|
"src_uid=('child'",
|
||||||
|
"tractor.post_mortem()", # in `main()`-LoC
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
if ctlc:
|
if ctlc:
|
||||||
|
@ -960,6 +961,10 @@ def test_post_mortem_api(
|
||||||
"('root'",
|
"('root'",
|
||||||
"NameError",
|
"NameError",
|
||||||
"src_uid=('child'",
|
"src_uid=('child'",
|
||||||
|
|
||||||
|
# raising line in `main()` but from crash-handling
|
||||||
|
# in `tractor.open_nursery()`.
|
||||||
|
'async with p.open_context(name_error) as (ctx, first):',
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
if ctlc:
|
if ctlc:
|
||||||
|
@ -1151,6 +1156,54 @@ def test_ctxep_pauses_n_maybe_ipc_breaks(
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_crash_handling_within_cancelled_root_actor(
|
||||||
|
spawn: PexpectSpawner,
|
||||||
|
):
|
||||||
|
'''
|
||||||
|
Ensure that when only a root-actor is started via `open_root_actor()`
|
||||||
|
we can crash-handle in debug-mode despite self-cancellation.
|
||||||
|
|
||||||
|
More-or-less ensures we conditionally shield the pause in
|
||||||
|
`._root.open_root_actor()`'s `await debug._maybe_enter_pm()`
|
||||||
|
call.
|
||||||
|
|
||||||
|
'''
|
||||||
|
child = spawn('root_self_cancelled_w_error')
|
||||||
|
child.expect(PROMPT)
|
||||||
|
|
||||||
|
assert_before(
|
||||||
|
child,
|
||||||
|
[
|
||||||
|
"Actor.cancel_soon()` was called!",
|
||||||
|
"root cancelled",
|
||||||
|
_pause_msg,
|
||||||
|
"('root'", # actor name
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
child.sendline('c')
|
||||||
|
child.expect(PROMPT)
|
||||||
|
assert_before(
|
||||||
|
child,
|
||||||
|
[
|
||||||
|
_crash_msg,
|
||||||
|
"('root'", # actor name
|
||||||
|
"AssertionError",
|
||||||
|
"assert 0",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
child.sendline('c')
|
||||||
|
child.expect(EOF)
|
||||||
|
assert_before(
|
||||||
|
child,
|
||||||
|
[
|
||||||
|
"AssertionError",
|
||||||
|
"assert 0",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# TODO: better error for "non-ideal" usage from the root actor.
|
# TODO: better error for "non-ideal" usage from the root actor.
|
||||||
# -[ ] if called from an async scope emit a message that suggests
|
# -[ ] if called from an async scope emit a message that suggests
|
||||||
# using `await tractor.pause()` instead since it's less overhead
|
# using `await tractor.pause()` instead since it's less overhead
|
||||||
|
|
|
@ -14,6 +14,9 @@ TODO:
|
||||||
|
|
||||||
'''
|
'''
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
from contextlib import (
|
||||||
|
contextmanager as cm,
|
||||||
|
)
|
||||||
import os
|
import os
|
||||||
import signal
|
import signal
|
||||||
import time
|
import time
|
||||||
|
@ -28,6 +31,8 @@ from .conftest import (
|
||||||
PROMPT,
|
PROMPT,
|
||||||
_pause_msg,
|
_pause_msg,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
import pytest
|
||||||
from pexpect.exceptions import (
|
from pexpect.exceptions import (
|
||||||
# TIMEOUT,
|
# TIMEOUT,
|
||||||
EOF,
|
EOF,
|
||||||
|
@ -185,3 +190,117 @@ def test_breakpoint_hook_restored(
|
||||||
)
|
)
|
||||||
child.sendline('c')
|
child.sendline('c')
|
||||||
child.expect(EOF)
|
child.expect(EOF)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
_to_raise = Exception('Triggering a crash')
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
'to_raise',
|
||||||
|
[
|
||||||
|
None,
|
||||||
|
_to_raise,
|
||||||
|
RuntimeError('Never crash handle this!'),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
'raise_on_exit',
|
||||||
|
[
|
||||||
|
True,
|
||||||
|
[type(_to_raise)],
|
||||||
|
False,
|
||||||
|
]
|
||||||
|
)
|
||||||
|
def test_crash_handler_cms(
|
||||||
|
debug_mode: bool,
|
||||||
|
to_raise: Exception,
|
||||||
|
raise_on_exit: bool|list[Exception],
|
||||||
|
):
|
||||||
|
'''
|
||||||
|
Verify the `.devx.open_crash_handler()` API(s) by also
|
||||||
|
(conveniently enough) tesing its `repl_fixture: ContextManager`
|
||||||
|
param support which for this suite allows use to avoid use of
|
||||||
|
a `pexpect`-style-test since we use the fixture to avoid actually
|
||||||
|
entering `PdbpREPL.iteract()` :smirk:
|
||||||
|
|
||||||
|
'''
|
||||||
|
import tractor
|
||||||
|
# import trio
|
||||||
|
|
||||||
|
# state flags
|
||||||
|
repl_acquired: bool = False
|
||||||
|
repl_released: bool = False
|
||||||
|
|
||||||
|
@cm
|
||||||
|
def block_repl_ux(
|
||||||
|
repl: tractor.devx.debug.PdbREPL,
|
||||||
|
maybe_bxerr: (
|
||||||
|
tractor.devx._debug.BoxedMaybeException
|
||||||
|
|None
|
||||||
|
) = None,
|
||||||
|
enter_repl: bool = True,
|
||||||
|
|
||||||
|
) -> bool:
|
||||||
|
'''
|
||||||
|
Set pre/post-REPL state vars and bypass actual conole
|
||||||
|
interaction.
|
||||||
|
|
||||||
|
'''
|
||||||
|
nonlocal repl_acquired, repl_released
|
||||||
|
|
||||||
|
# task: trio.Task = trio.lowlevel.current_task()
|
||||||
|
# print(f'pre-REPL active_task={task.name}')
|
||||||
|
|
||||||
|
print('pre-REPL')
|
||||||
|
repl_acquired = True
|
||||||
|
yield False # never actually .interact()
|
||||||
|
print('post-REPL')
|
||||||
|
repl_released = True
|
||||||
|
|
||||||
|
try:
|
||||||
|
# TODO, with runtime's `debug_mode` setting
|
||||||
|
# -[ ] need to open runtime tho obvi..
|
||||||
|
#
|
||||||
|
# with tractor.devx.maybe_open_crash_handler(
|
||||||
|
# pdb=True,
|
||||||
|
|
||||||
|
with tractor.devx.open_crash_handler(
|
||||||
|
raise_on_exit=raise_on_exit,
|
||||||
|
repl_fixture=block_repl_ux
|
||||||
|
) as bxerr:
|
||||||
|
if to_raise is not None:
|
||||||
|
raise to_raise
|
||||||
|
|
||||||
|
except Exception as _exc:
|
||||||
|
exc = _exc
|
||||||
|
if (
|
||||||
|
raise_on_exit is True
|
||||||
|
or
|
||||||
|
type(to_raise) in raise_on_exit
|
||||||
|
):
|
||||||
|
assert (
|
||||||
|
exc
|
||||||
|
is
|
||||||
|
to_raise
|
||||||
|
is
|
||||||
|
bxerr.value
|
||||||
|
)
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise
|
||||||
|
else:
|
||||||
|
assert (
|
||||||
|
to_raise is None
|
||||||
|
or
|
||||||
|
not raise_on_exit
|
||||||
|
or
|
||||||
|
type(to_raise) not in raise_on_exit
|
||||||
|
)
|
||||||
|
assert bxerr.value is to_raise
|
||||||
|
|
||||||
|
assert bxerr.raise_on_exit == raise_on_exit
|
||||||
|
|
||||||
|
if to_raise is not None:
|
||||||
|
assert repl_acquired
|
||||||
|
assert repl_released
|
||||||
|
|
|
@ -0,0 +1,114 @@
|
||||||
|
'''
|
||||||
|
Unit-ish tests for specific IPC transport protocol backends.
|
||||||
|
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
import trio
|
||||||
|
import tractor
|
||||||
|
from tractor import (
|
||||||
|
Actor,
|
||||||
|
_state,
|
||||||
|
_addr,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def bindspace_dir_str() -> str:
|
||||||
|
|
||||||
|
rt_dir: Path = tractor._state.get_rt_dir()
|
||||||
|
bs_dir: Path = rt_dir / 'doggy'
|
||||||
|
bs_dir_str: str = str(bs_dir)
|
||||||
|
assert not bs_dir.is_dir()
|
||||||
|
|
||||||
|
yield bs_dir_str
|
||||||
|
|
||||||
|
# delete it on suite teardown.
|
||||||
|
# ?TODO? should we support this internally
|
||||||
|
# or is leaking it ok?
|
||||||
|
if bs_dir.is_dir():
|
||||||
|
bs_dir.rmdir()
|
||||||
|
|
||||||
|
|
||||||
|
def test_uds_bindspace_created_implicitly(
|
||||||
|
debug_mode: bool,
|
||||||
|
bindspace_dir_str: str,
|
||||||
|
):
|
||||||
|
registry_addr: tuple = (
|
||||||
|
f'{bindspace_dir_str}',
|
||||||
|
'registry@doggy.sock',
|
||||||
|
)
|
||||||
|
bs_dir_str: str = registry_addr[0]
|
||||||
|
|
||||||
|
# XXX, ensure bindspace-dir DNE beforehand!
|
||||||
|
assert not Path(bs_dir_str).is_dir()
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
async with tractor.open_nursery(
|
||||||
|
enable_transports=['uds'],
|
||||||
|
registry_addrs=[registry_addr],
|
||||||
|
debug_mode=debug_mode,
|
||||||
|
) as _an:
|
||||||
|
|
||||||
|
# XXX MUST be created implicitly by
|
||||||
|
# `.ipc._uds.start_listener()`!
|
||||||
|
assert Path(bs_dir_str).is_dir()
|
||||||
|
|
||||||
|
root: Actor = tractor.current_actor()
|
||||||
|
assert root.is_registrar
|
||||||
|
|
||||||
|
assert registry_addr in root.reg_addrs
|
||||||
|
assert (
|
||||||
|
registry_addr
|
||||||
|
in
|
||||||
|
_state._runtime_vars['_registry_addrs']
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
_addr.wrap_address(registry_addr)
|
||||||
|
in
|
||||||
|
root.registry_addrs
|
||||||
|
)
|
||||||
|
|
||||||
|
trio.run(main)
|
||||||
|
|
||||||
|
|
||||||
|
def test_uds_double_listen_raises_connerr(
|
||||||
|
debug_mode: bool,
|
||||||
|
bindspace_dir_str: str,
|
||||||
|
):
|
||||||
|
registry_addr: tuple = (
|
||||||
|
f'{bindspace_dir_str}',
|
||||||
|
'registry@doggy.sock',
|
||||||
|
)
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
async with tractor.open_nursery(
|
||||||
|
enable_transports=['uds'],
|
||||||
|
registry_addrs=[registry_addr],
|
||||||
|
debug_mode=debug_mode,
|
||||||
|
) as _an:
|
||||||
|
|
||||||
|
# runtime up
|
||||||
|
root: Actor = tractor.current_actor()
|
||||||
|
|
||||||
|
from tractor.ipc._uds import (
|
||||||
|
start_listener,
|
||||||
|
UDSAddress,
|
||||||
|
)
|
||||||
|
ya_bound_addr: UDSAddress = root.registry_addrs[0]
|
||||||
|
try:
|
||||||
|
await start_listener(
|
||||||
|
addr=ya_bound_addr,
|
||||||
|
)
|
||||||
|
except ConnectionError as connerr:
|
||||||
|
assert type(src_exc := connerr.__context__) is OSError
|
||||||
|
assert 'Address already in use' in src_exc.args
|
||||||
|
# complete, exit test.
|
||||||
|
|
||||||
|
else:
|
||||||
|
pytest.fail('It dint raise a connerr !?')
|
||||||
|
|
||||||
|
|
||||||
|
trio.run(main)
|
|
@ -0,0 +1,95 @@
|
||||||
|
'''
|
||||||
|
Verify the `enable_transports` param drives various
|
||||||
|
per-root/sub-actor IPC endpoint/server settings.
|
||||||
|
|
||||||
|
'''
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
import trio
|
||||||
|
import tractor
|
||||||
|
from tractor import (
|
||||||
|
Actor,
|
||||||
|
Portal,
|
||||||
|
ipc,
|
||||||
|
msg,
|
||||||
|
_state,
|
||||||
|
_addr,
|
||||||
|
)
|
||||||
|
|
||||||
|
@tractor.context
|
||||||
|
async def chk_tpts(
|
||||||
|
ctx: tractor.Context,
|
||||||
|
tpt_proto_key: str,
|
||||||
|
):
|
||||||
|
rtvars = _state._runtime_vars
|
||||||
|
assert (
|
||||||
|
tpt_proto_key
|
||||||
|
in
|
||||||
|
rtvars['_enable_tpts']
|
||||||
|
)
|
||||||
|
actor: Actor = tractor.current_actor()
|
||||||
|
spec: msg.types.SpawnSpec = actor._spawn_spec
|
||||||
|
assert spec._runtime_vars == rtvars
|
||||||
|
|
||||||
|
# ensure individual IPC ep-addr types
|
||||||
|
serv: ipc._server.Server = actor.ipc_server
|
||||||
|
addr: ipc._types.Address
|
||||||
|
for addr in serv.addrs:
|
||||||
|
assert addr.proto_key == tpt_proto_key
|
||||||
|
|
||||||
|
# Actor delegate-props enforcement
|
||||||
|
assert (
|
||||||
|
actor.accept_addrs
|
||||||
|
==
|
||||||
|
serv.accept_addrs
|
||||||
|
)
|
||||||
|
|
||||||
|
await ctx.started(serv.accept_addrs)
|
||||||
|
|
||||||
|
|
||||||
|
# TODO, parametrize over mis-matched-proto-typed `registry_addrs`
|
||||||
|
# since i seems to work in `piker` but not exactly sure if both tcp
|
||||||
|
# & uds are being deployed then?
|
||||||
|
#
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
'tpt_proto_key',
|
||||||
|
['tcp', 'uds'],
|
||||||
|
ids=lambda item: f'ipc_tpt={item!r}'
|
||||||
|
)
|
||||||
|
def test_root_passes_tpt_to_sub(
|
||||||
|
tpt_proto_key: str,
|
||||||
|
reg_addr: tuple,
|
||||||
|
debug_mode: bool,
|
||||||
|
):
|
||||||
|
async def main():
|
||||||
|
async with tractor.open_nursery(
|
||||||
|
enable_transports=[tpt_proto_key],
|
||||||
|
registry_addrs=[reg_addr],
|
||||||
|
debug_mode=debug_mode,
|
||||||
|
) as an:
|
||||||
|
|
||||||
|
assert (
|
||||||
|
tpt_proto_key
|
||||||
|
in
|
||||||
|
_state._runtime_vars['_enable_tpts']
|
||||||
|
)
|
||||||
|
|
||||||
|
ptl: Portal = await an.start_actor(
|
||||||
|
name='sub',
|
||||||
|
enable_modules=[__name__],
|
||||||
|
)
|
||||||
|
async with ptl.open_context(
|
||||||
|
chk_tpts,
|
||||||
|
tpt_proto_key=tpt_proto_key,
|
||||||
|
) as (ctx, accept_addrs):
|
||||||
|
|
||||||
|
uw_addr: tuple
|
||||||
|
for uw_addr in accept_addrs:
|
||||||
|
addr = _addr.wrap_address(uw_addr)
|
||||||
|
assert addr.is_valid
|
||||||
|
|
||||||
|
# shudown sub-actor(s)
|
||||||
|
await an.cancel()
|
||||||
|
|
||||||
|
trio.run(main)
|
|
@ -313,9 +313,8 @@ async def inf_streamer(
|
||||||
# `trio.EndOfChannel` doesn't propagate directly to the above
|
# `trio.EndOfChannel` doesn't propagate directly to the above
|
||||||
# .open_stream() parent, resulting in it also raising instead
|
# .open_stream() parent, resulting in it also raising instead
|
||||||
# of gracefully absorbing as normal.. so how to handle?
|
# of gracefully absorbing as normal.. so how to handle?
|
||||||
trio.open_nursery(
|
tractor.trionics.collapse_eg(),
|
||||||
strict_exception_groups=False,
|
trio.open_nursery() as tn,
|
||||||
) as tn,
|
|
||||||
):
|
):
|
||||||
async def close_stream_on_sentinel():
|
async def close_stream_on_sentinel():
|
||||||
async for msg in stream:
|
async for msg in stream:
|
||||||
|
|
|
@ -236,7 +236,10 @@ async def stream_forever():
|
||||||
async def test_cancel_infinite_streamer(start_method):
|
async def test_cancel_infinite_streamer(start_method):
|
||||||
|
|
||||||
# stream for at most 1 seconds
|
# stream for at most 1 seconds
|
||||||
with trio.move_on_after(1) as cancel_scope:
|
with (
|
||||||
|
trio.fail_after(4),
|
||||||
|
trio.move_on_after(1) as cancel_scope
|
||||||
|
):
|
||||||
async with tractor.open_nursery() as n:
|
async with tractor.open_nursery() as n:
|
||||||
portal = await n.start_actor(
|
portal = await n.start_actor(
|
||||||
'donny',
|
'donny',
|
||||||
|
@ -284,20 +287,32 @@ async def test_cancel_infinite_streamer(start_method):
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
@tractor_test
|
@tractor_test
|
||||||
async def test_some_cancels_all(num_actors_and_errs, start_method, loglevel):
|
async def test_some_cancels_all(
|
||||||
"""Verify a subset of failed subactors causes all others in
|
num_actors_and_errs: tuple,
|
||||||
|
start_method: str,
|
||||||
|
loglevel: str,
|
||||||
|
):
|
||||||
|
'''
|
||||||
|
Verify a subset of failed subactors causes all others in
|
||||||
the nursery to be cancelled just like the strategy in trio.
|
the nursery to be cancelled just like the strategy in trio.
|
||||||
|
|
||||||
This is the first and only supervisory strategy at the moment.
|
This is the first and only supervisory strategy at the moment.
|
||||||
"""
|
|
||||||
num_actors, first_err, err_type, ria_func, da_func = num_actors_and_errs
|
'''
|
||||||
|
(
|
||||||
|
num_actors,
|
||||||
|
first_err,
|
||||||
|
err_type,
|
||||||
|
ria_func,
|
||||||
|
da_func,
|
||||||
|
) = num_actors_and_errs
|
||||||
try:
|
try:
|
||||||
async with tractor.open_nursery() as n:
|
async with tractor.open_nursery() as an:
|
||||||
|
|
||||||
# spawn the same number of deamon actors which should be cancelled
|
# spawn the same number of deamon actors which should be cancelled
|
||||||
dactor_portals = []
|
dactor_portals = []
|
||||||
for i in range(num_actors):
|
for i in range(num_actors):
|
||||||
dactor_portals.append(await n.start_actor(
|
dactor_portals.append(await an.start_actor(
|
||||||
f'deamon_{i}',
|
f'deamon_{i}',
|
||||||
enable_modules=[__name__],
|
enable_modules=[__name__],
|
||||||
))
|
))
|
||||||
|
@ -307,7 +322,7 @@ async def test_some_cancels_all(num_actors_and_errs, start_method, loglevel):
|
||||||
for i in range(num_actors):
|
for i in range(num_actors):
|
||||||
# start actor(s) that will fail immediately
|
# start actor(s) that will fail immediately
|
||||||
riactor_portals.append(
|
riactor_portals.append(
|
||||||
await n.run_in_actor(
|
await an.run_in_actor(
|
||||||
func,
|
func,
|
||||||
name=f'actor_{i}',
|
name=f'actor_{i}',
|
||||||
**kwargs
|
**kwargs
|
||||||
|
@ -337,7 +352,8 @@ async def test_some_cancels_all(num_actors_and_errs, start_method, loglevel):
|
||||||
|
|
||||||
# should error here with a ``RemoteActorError`` or ``MultiError``
|
# should error here with a ``RemoteActorError`` or ``MultiError``
|
||||||
|
|
||||||
except first_err as err:
|
except first_err as _err:
|
||||||
|
err = _err
|
||||||
if isinstance(err, BaseExceptionGroup):
|
if isinstance(err, BaseExceptionGroup):
|
||||||
assert len(err.exceptions) == num_actors
|
assert len(err.exceptions) == num_actors
|
||||||
for exc in err.exceptions:
|
for exc in err.exceptions:
|
||||||
|
@ -348,8 +364,8 @@ async def test_some_cancels_all(num_actors_and_errs, start_method, loglevel):
|
||||||
elif isinstance(err, tractor.RemoteActorError):
|
elif isinstance(err, tractor.RemoteActorError):
|
||||||
assert err.boxed_type == err_type
|
assert err.boxed_type == err_type
|
||||||
|
|
||||||
assert n.cancelled is True
|
assert an.cancelled is True
|
||||||
assert not n._children
|
assert not an._children
|
||||||
else:
|
else:
|
||||||
pytest.fail("Should have gotten a remote assertion error?")
|
pytest.fail("Should have gotten a remote assertion error?")
|
||||||
|
|
||||||
|
@ -519,10 +535,15 @@ def test_cancel_via_SIGINT_other_task(
|
||||||
async def main():
|
async def main():
|
||||||
# should never timeout since SIGINT should cancel the current program
|
# should never timeout since SIGINT should cancel the current program
|
||||||
with trio.fail_after(timeout):
|
with trio.fail_after(timeout):
|
||||||
async with trio.open_nursery(
|
async with (
|
||||||
|
|
||||||
|
# XXX ?TODO? why no work!?
|
||||||
|
# tractor.trionics.collapse_eg(),
|
||||||
|
trio.open_nursery(
|
||||||
strict_exception_groups=False,
|
strict_exception_groups=False,
|
||||||
) as n:
|
) as tn,
|
||||||
await n.start(spawn_and_sleep_forever)
|
):
|
||||||
|
await tn.start(spawn_and_sleep_forever)
|
||||||
if 'mp' in spawn_backend:
|
if 'mp' in spawn_backend:
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
os.kill(pid, signal.SIGINT)
|
os.kill(pid, signal.SIGINT)
|
||||||
|
@ -533,38 +554,123 @@ def test_cancel_via_SIGINT_other_task(
|
||||||
|
|
||||||
async def spin_for(period=3):
|
async def spin_for(period=3):
|
||||||
"Sync sleep."
|
"Sync sleep."
|
||||||
|
print(f'sync sleeping in sub-sub for {period}\n')
|
||||||
time.sleep(period)
|
time.sleep(period)
|
||||||
|
|
||||||
|
|
||||||
async def spawn():
|
async def spawn_sub_with_sync_blocking_task():
|
||||||
async with tractor.open_nursery() as tn:
|
async with tractor.open_nursery() as an:
|
||||||
await tn.run_in_actor(
|
print('starting sync blocking subactor..\n')
|
||||||
|
await an.run_in_actor(
|
||||||
spin_for,
|
spin_for,
|
||||||
name='sleeper',
|
name='sleeper',
|
||||||
)
|
)
|
||||||
|
print('exiting first subactor layer..\n')
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
'man_cancel_outer',
|
||||||
|
[
|
||||||
|
False, # passes if delay != 2
|
||||||
|
|
||||||
|
# always causes an unexpected eg-w-embedded-assert-err?
|
||||||
|
pytest.param(True,
|
||||||
|
marks=pytest.mark.xfail(
|
||||||
|
reason=(
|
||||||
|
'always causes an unexpected eg-w-embedded-assert-err?'
|
||||||
|
)
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
@no_windows
|
@no_windows
|
||||||
def test_cancel_while_childs_child_in_sync_sleep(
|
def test_cancel_while_childs_child_in_sync_sleep(
|
||||||
loglevel,
|
loglevel: str,
|
||||||
start_method,
|
start_method: str,
|
||||||
spawn_backend,
|
spawn_backend: str,
|
||||||
|
debug_mode: bool,
|
||||||
|
reg_addr: tuple,
|
||||||
|
man_cancel_outer: bool,
|
||||||
):
|
):
|
||||||
"""Verify that a child cancelled while executing sync code is torn
|
'''
|
||||||
|
Verify that a child cancelled while executing sync code is torn
|
||||||
down even when that cancellation is triggered by the parent
|
down even when that cancellation is triggered by the parent
|
||||||
2 nurseries "up".
|
2 nurseries "up".
|
||||||
"""
|
|
||||||
|
Though the grandchild should stay blocking its actor runtime, its
|
||||||
|
parent should issue a "zombie reaper" to hard kill it after
|
||||||
|
sufficient timeout.
|
||||||
|
|
||||||
|
'''
|
||||||
if start_method == 'forkserver':
|
if start_method == 'forkserver':
|
||||||
pytest.skip("Forksever sux hard at resuming from sync sleep...")
|
pytest.skip("Forksever sux hard at resuming from sync sleep...")
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
with trio.fail_after(2):
|
#
|
||||||
async with tractor.open_nursery() as tn:
|
# XXX BIG TODO NOTE XXX
|
||||||
await tn.run_in_actor(
|
#
|
||||||
spawn,
|
# it seems there's a strange race that can happen
|
||||||
name='spawn',
|
# where where the fail-after will trigger outer scope
|
||||||
|
# .cancel() which then causes the inner scope to raise,
|
||||||
|
#
|
||||||
|
# BaseExceptionGroup('Exceptions from Trio nursery', [
|
||||||
|
# BaseExceptionGroup('Exceptions from Trio nursery',
|
||||||
|
# [
|
||||||
|
# Cancelled(),
|
||||||
|
# Cancelled(),
|
||||||
|
# ]
|
||||||
|
# ),
|
||||||
|
# AssertionError('assert 0')
|
||||||
|
# ])
|
||||||
|
#
|
||||||
|
# WHY THIS DOESN'T MAKE SENSE:
|
||||||
|
# ---------------------------
|
||||||
|
# - it should raise too-slow-error when too slow..
|
||||||
|
# * verified that using simple-cs and manually cancelling
|
||||||
|
# you get same outcome -> indicates that the fail-after
|
||||||
|
# can have its TooSlowError overriden!
|
||||||
|
# |_ to check this it's easy, simplly decrease the timeout
|
||||||
|
# as per the var below.
|
||||||
|
#
|
||||||
|
# - when using the manual simple-cs the outcome is different
|
||||||
|
# DESPITE the `assert 0` which means regardless of the
|
||||||
|
# inner scope effectively failing in the same way, the
|
||||||
|
# bubbling up **is NOT the same**.
|
||||||
|
#
|
||||||
|
# delays trigger diff outcomes..
|
||||||
|
# ---------------------------
|
||||||
|
# as seen by uncommenting various lines below there is from
|
||||||
|
# my POV an unexpected outcome due to the delay=2 case.
|
||||||
|
#
|
||||||
|
# delay = 1 # no AssertionError in eg, TooSlowError raised.
|
||||||
|
# delay = 2 # is AssertionError in eg AND no TooSlowError !?
|
||||||
|
delay = 4 # is AssertionError in eg AND no _cs cancellation.
|
||||||
|
|
||||||
|
with trio.fail_after(delay) as _cs:
|
||||||
|
# with trio.CancelScope() as cs:
|
||||||
|
# ^XXX^ can be used instead to see same outcome.
|
||||||
|
|
||||||
|
async with (
|
||||||
|
# tractor.trionics.collapse_eg(), # doesn't help
|
||||||
|
tractor.open_nursery(
|
||||||
|
hide_tb=False,
|
||||||
|
debug_mode=debug_mode,
|
||||||
|
registry_addrs=[reg_addr],
|
||||||
|
) as an,
|
||||||
|
):
|
||||||
|
await an.run_in_actor(
|
||||||
|
spawn_sub_with_sync_blocking_task,
|
||||||
|
name='sync_blocking_sub',
|
||||||
)
|
)
|
||||||
await trio.sleep(1)
|
await trio.sleep(1)
|
||||||
|
|
||||||
|
if man_cancel_outer:
|
||||||
|
print('Cancelling manually in root')
|
||||||
|
_cs.cancel()
|
||||||
|
|
||||||
|
# trigger exc-srced taskc down
|
||||||
|
# the actor tree.
|
||||||
|
print('RAISING IN ROOT')
|
||||||
assert 0
|
assert 0
|
||||||
|
|
||||||
with pytest.raises(AssertionError):
|
with pytest.raises(AssertionError):
|
||||||
|
|
|
@ -117,9 +117,10 @@ async def open_actor_local_nursery(
|
||||||
ctx: tractor.Context,
|
ctx: tractor.Context,
|
||||||
):
|
):
|
||||||
global _nursery
|
global _nursery
|
||||||
async with trio.open_nursery(
|
async with (
|
||||||
strict_exception_groups=False,
|
tractor.trionics.collapse_eg(),
|
||||||
) as tn:
|
trio.open_nursery() as tn
|
||||||
|
):
|
||||||
_nursery = tn
|
_nursery = tn
|
||||||
await ctx.started()
|
await ctx.started()
|
||||||
await trio.sleep(10)
|
await trio.sleep(10)
|
||||||
|
|
|
@ -13,26 +13,24 @@ MESSAGE = 'tractoring at full speed'
|
||||||
def test_empty_mngrs_input_raises() -> None:
|
def test_empty_mngrs_input_raises() -> None:
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
with trio.fail_after(1):
|
with trio.fail_after(3):
|
||||||
async with (
|
async with (
|
||||||
open_actor_cluster(
|
open_actor_cluster(
|
||||||
modules=[__name__],
|
modules=[__name__],
|
||||||
|
|
||||||
# NOTE: ensure we can passthrough runtime opts
|
# NOTE: ensure we can passthrough runtime opts
|
||||||
loglevel='info',
|
loglevel='cancel',
|
||||||
# debug_mode=True,
|
debug_mode=False,
|
||||||
|
|
||||||
) as portals,
|
) as portals,
|
||||||
|
|
||||||
gather_contexts(
|
gather_contexts(mngrs=()),
|
||||||
# NOTE: it's the use of inline-generator syntax
|
|
||||||
# here that causes the empty input.
|
|
||||||
mngrs=(
|
|
||||||
p.open_context(worker) for p in portals.values()
|
|
||||||
),
|
|
||||||
),
|
|
||||||
):
|
):
|
||||||
assert 0
|
# should fail before this?
|
||||||
|
assert portals
|
||||||
|
|
||||||
|
# test should fail if we mk it here!
|
||||||
|
assert 0, 'Should have raised val-err !?'
|
||||||
|
|
||||||
with pytest.raises(ValueError):
|
with pytest.raises(ValueError):
|
||||||
trio.run(main)
|
trio.run(main)
|
||||||
|
|
|
@ -11,6 +11,7 @@ import psutil
|
||||||
import pytest
|
import pytest
|
||||||
import subprocess
|
import subprocess
|
||||||
import tractor
|
import tractor
|
||||||
|
from tractor.trionics import collapse_eg
|
||||||
from tractor._testing import tractor_test
|
from tractor._testing import tractor_test
|
||||||
import trio
|
import trio
|
||||||
|
|
||||||
|
@ -193,10 +194,10 @@ async def spawn_and_check_registry(
|
||||||
|
|
||||||
try:
|
try:
|
||||||
async with tractor.open_nursery() as an:
|
async with tractor.open_nursery() as an:
|
||||||
async with trio.open_nursery(
|
async with (
|
||||||
strict_exception_groups=False,
|
collapse_eg(),
|
||||||
) as trion:
|
trio.open_nursery() as trion,
|
||||||
|
):
|
||||||
portals = {}
|
portals = {}
|
||||||
for i in range(3):
|
for i in range(3):
|
||||||
name = f'a{i}'
|
name = f'a{i}'
|
||||||
|
@ -338,11 +339,12 @@ async def close_chans_before_nursery(
|
||||||
async with portal2.open_stream_from(
|
async with portal2.open_stream_from(
|
||||||
stream_forever
|
stream_forever
|
||||||
) as agen2:
|
) as agen2:
|
||||||
async with trio.open_nursery(
|
async with (
|
||||||
strict_exception_groups=False,
|
collapse_eg(),
|
||||||
) as n:
|
trio.open_nursery() as tn,
|
||||||
n.start_soon(streamer, agen1)
|
):
|
||||||
n.start_soon(cancel, use_signal, .5)
|
tn.start_soon(streamer, agen1)
|
||||||
|
tn.start_soon(cancel, use_signal, .5)
|
||||||
try:
|
try:
|
||||||
await streamer(agen2)
|
await streamer(agen2)
|
||||||
finally:
|
finally:
|
||||||
|
|
|
@ -95,6 +95,7 @@ def run_example_in_subproc(
|
||||||
and 'integration' not in p[0]
|
and 'integration' not in p[0]
|
||||||
and 'advanced_faults' not in p[0]
|
and 'advanced_faults' not in p[0]
|
||||||
and 'multihost' not in p[0]
|
and 'multihost' not in p[0]
|
||||||
|
and 'trio' not in p[0]
|
||||||
)
|
)
|
||||||
],
|
],
|
||||||
ids=lambda t: t[1],
|
ids=lambda t: t[1],
|
||||||
|
|
|
@ -234,10 +234,8 @@ async def trio_ctx(
|
||||||
with trio.fail_after(1 + delay):
|
with trio.fail_after(1 + delay):
|
||||||
try:
|
try:
|
||||||
async with (
|
async with (
|
||||||
trio.open_nursery(
|
tractor.trionics.collapse_eg(),
|
||||||
# TODO, for new `trio` / py3.13
|
trio.open_nursery() as tn,
|
||||||
# strict_exception_groups=False,
|
|
||||||
) as tn,
|
|
||||||
tractor.to_asyncio.open_channel_from(
|
tractor.to_asyncio.open_channel_from(
|
||||||
sleep_and_err,
|
sleep_and_err,
|
||||||
) as (first, chan),
|
) as (first, chan),
|
||||||
|
@ -573,6 +571,8 @@ def test_basic_interloop_channel_stream(
|
||||||
fan_out: bool,
|
fan_out: bool,
|
||||||
):
|
):
|
||||||
async def main():
|
async def main():
|
||||||
|
# TODO, figure out min timeout here!
|
||||||
|
with trio.fail_after(6):
|
||||||
async with tractor.open_nursery() as an:
|
async with tractor.open_nursery() as an:
|
||||||
portal = await an.run_in_actor(
|
portal = await an.run_in_actor(
|
||||||
stream_from_aio,
|
stream_from_aio,
|
||||||
|
@ -1088,6 +1088,108 @@ def test_sigint_closes_lifetime_stack(
|
||||||
trio.run(main)
|
trio.run(main)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# ?TODO asyncio.Task fn-deco?
|
||||||
|
# -[ ] do sig checkingat import time like @context?
|
||||||
|
# -[ ] maybe name it @aio_task ??
|
||||||
|
# -[ ] chan: to_asyncio.InterloopChannel ??
|
||||||
|
async def raise_before_started(
|
||||||
|
# from_trio: asyncio.Queue,
|
||||||
|
# to_trio: trio.abc.SendChannel,
|
||||||
|
chan: to_asyncio.LinkedTaskChannel,
|
||||||
|
|
||||||
|
) -> None:
|
||||||
|
'''
|
||||||
|
`asyncio.Task` entry point which RTEs before calling
|
||||||
|
`to_trio.send_nowait()`.
|
||||||
|
|
||||||
|
'''
|
||||||
|
await asyncio.sleep(0.2)
|
||||||
|
raise RuntimeError('Some shite went wrong before `.send_nowait()`!!')
|
||||||
|
|
||||||
|
# to_trio.send_nowait('Uhh we shouldve RTE-d ^^ ??')
|
||||||
|
chan.started_nowait('Uhh we shouldve RTE-d ^^ ??')
|
||||||
|
await asyncio.sleep(float('inf'))
|
||||||
|
|
||||||
|
|
||||||
|
@tractor.context
|
||||||
|
async def caching_ep(
|
||||||
|
ctx: tractor.Context,
|
||||||
|
):
|
||||||
|
|
||||||
|
log = tractor.log.get_logger('caching_ep')
|
||||||
|
log.info('syncing via `ctx.started()`')
|
||||||
|
await ctx.started()
|
||||||
|
|
||||||
|
# XXX, allocate the `open_channel_from()` inside
|
||||||
|
# a `.trionics.maybe_open_context()`.
|
||||||
|
chan: to_asyncio.LinkedTaskChannel
|
||||||
|
async with (
|
||||||
|
tractor.trionics.maybe_open_context(
|
||||||
|
acm_func=tractor.to_asyncio.open_channel_from,
|
||||||
|
kwargs={
|
||||||
|
'target': raise_before_started,
|
||||||
|
# ^XXX, kwarg to `open_channel_from()`
|
||||||
|
},
|
||||||
|
|
||||||
|
# lock around current actor task access
|
||||||
|
key=tractor.current_actor().uid,
|
||||||
|
|
||||||
|
) as (cache_hit, (clients, chan)),
|
||||||
|
):
|
||||||
|
if cache_hit:
|
||||||
|
log.error(
|
||||||
|
'Re-using cached `.open_from_channel()` call!\n'
|
||||||
|
)
|
||||||
|
|
||||||
|
else:
|
||||||
|
log.info(
|
||||||
|
'Allocating SHOULD-FAIL `.open_from_channel()`\n'
|
||||||
|
)
|
||||||
|
|
||||||
|
await trio.sleep_forever()
|
||||||
|
|
||||||
|
|
||||||
|
def test_aio_side_raises_before_started(
|
||||||
|
reg_addr: tuple[str, int],
|
||||||
|
debug_mode: bool,
|
||||||
|
loglevel: str,
|
||||||
|
):
|
||||||
|
'''
|
||||||
|
Simulates connection-err from `piker.brokers.ib.api`..
|
||||||
|
|
||||||
|
Ensure any error raised by child-`asyncio.Task` BEFORE
|
||||||
|
`chan.started()`
|
||||||
|
|
||||||
|
'''
|
||||||
|
# delay = 999 if debug_mode else 1
|
||||||
|
async def main():
|
||||||
|
with trio.fail_after(3):
|
||||||
|
an: tractor.ActorNursery
|
||||||
|
async with tractor.open_nursery(
|
||||||
|
debug_mode=debug_mode,
|
||||||
|
loglevel=loglevel,
|
||||||
|
) as an:
|
||||||
|
p: tractor.Portal = await an.start_actor(
|
||||||
|
'lchan_cacher_that_raises_fast',
|
||||||
|
enable_modules=[__name__],
|
||||||
|
infect_asyncio=True,
|
||||||
|
)
|
||||||
|
async with p.open_context(
|
||||||
|
caching_ep,
|
||||||
|
) as (ctx, first):
|
||||||
|
assert not first
|
||||||
|
|
||||||
|
with pytest.raises(
|
||||||
|
expected_exception=(RemoteActorError),
|
||||||
|
) as excinfo:
|
||||||
|
trio.run(main)
|
||||||
|
|
||||||
|
# ensure `asyncio.Task` exception is bubbled
|
||||||
|
# allll the way erp!!
|
||||||
|
rae = excinfo.value
|
||||||
|
assert rae.boxed_type is RuntimeError
|
||||||
|
|
||||||
# TODO: debug_mode tests once we get support for `asyncio`!
|
# TODO: debug_mode tests once we get support for `asyncio`!
|
||||||
#
|
#
|
||||||
# -[ ] need tests to wrap both scripts:
|
# -[ ] need tests to wrap both scripts:
|
||||||
|
|
|
@ -24,14 +24,10 @@ from tractor._testing import (
|
||||||
)
|
)
|
||||||
|
|
||||||
# XXX TODO cases:
|
# XXX TODO cases:
|
||||||
# - [ ] peer cancelled itself - so other peers should
|
|
||||||
# get errors reflecting that the peer was itself the .canceller?
|
|
||||||
|
|
||||||
# - [x] WE cancelled the peer and thus should not see any raised
|
# - [x] WE cancelled the peer and thus should not see any raised
|
||||||
# `ContextCancelled` as it should be reaped silently?
|
# `ContextCancelled` as it should be reaped silently?
|
||||||
# => pretty sure `test_context_stream_semantics::test_caller_cancels()`
|
# => pretty sure `test_context_stream_semantics::test_caller_cancels()`
|
||||||
# already covers this case?
|
# already covers this case?
|
||||||
|
|
||||||
# - [x] INTER-PEER: some arbitrary remote peer cancels via
|
# - [x] INTER-PEER: some arbitrary remote peer cancels via
|
||||||
# Portal.cancel_actor().
|
# Portal.cancel_actor().
|
||||||
# => all other connected peers should get that cancel requesting peer's
|
# => all other connected peers should get that cancel requesting peer's
|
||||||
|
@ -44,16 +40,6 @@ from tractor._testing import (
|
||||||
# that also spawned a remote task task in that same peer-parent.
|
# that also spawned a remote task task in that same peer-parent.
|
||||||
|
|
||||||
|
|
||||||
# def test_self_cancel():
|
|
||||||
# '''
|
|
||||||
# 2 cases:
|
|
||||||
# - calls `Actor.cancel()` locally in some task
|
|
||||||
# - calls LocalPortal.cancel_actor()` ?
|
|
||||||
|
|
||||||
# '''
|
|
||||||
# ...
|
|
||||||
|
|
||||||
|
|
||||||
@tractor.context
|
@tractor.context
|
||||||
async def open_stream_then_sleep_forever(
|
async def open_stream_then_sleep_forever(
|
||||||
ctx: Context,
|
ctx: Context,
|
||||||
|
@ -806,7 +792,7 @@ async def basic_echo_server(
|
||||||
ctx: Context,
|
ctx: Context,
|
||||||
peer_name: str = 'wittle_bruv',
|
peer_name: str = 'wittle_bruv',
|
||||||
|
|
||||||
err_after: int|None = None,
|
err_after_imsg: int|None = None,
|
||||||
|
|
||||||
) -> None:
|
) -> None:
|
||||||
'''
|
'''
|
||||||
|
@ -835,8 +821,9 @@ async def basic_echo_server(
|
||||||
await ipc.send(resp)
|
await ipc.send(resp)
|
||||||
|
|
||||||
if (
|
if (
|
||||||
err_after
|
err_after_imsg
|
||||||
and i > err_after
|
and
|
||||||
|
i > err_after_imsg
|
||||||
):
|
):
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
f'Simulated error in `{peer_name}`'
|
f'Simulated error in `{peer_name}`'
|
||||||
|
@ -978,7 +965,8 @@ async def tell_little_bro(
|
||||||
actor_name: str,
|
actor_name: str,
|
||||||
|
|
||||||
caller: str = '',
|
caller: str = '',
|
||||||
err_after: int|None = None,
|
err_after: float|None = None,
|
||||||
|
rng_seed: int = 50,
|
||||||
):
|
):
|
||||||
# contact target actor, do a stream dialog.
|
# contact target actor, do a stream dialog.
|
||||||
async with (
|
async with (
|
||||||
|
@ -989,14 +977,18 @@ async def tell_little_bro(
|
||||||
basic_echo_server,
|
basic_echo_server,
|
||||||
|
|
||||||
# XXX proxy any delayed err condition
|
# XXX proxy any delayed err condition
|
||||||
err_after=err_after,
|
err_after_imsg=(
|
||||||
|
err_after * rng_seed
|
||||||
|
if err_after is not None
|
||||||
|
else None
|
||||||
|
),
|
||||||
) as (sub_ctx, first),
|
) as (sub_ctx, first),
|
||||||
|
|
||||||
sub_ctx.open_stream() as echo_ipc,
|
sub_ctx.open_stream() as echo_ipc,
|
||||||
):
|
):
|
||||||
actor: Actor = current_actor()
|
actor: Actor = current_actor()
|
||||||
uid: tuple = actor.uid
|
uid: tuple = actor.uid
|
||||||
for i in range(100):
|
for i in range(rng_seed):
|
||||||
msg: tuple = (
|
msg: tuple = (
|
||||||
uid,
|
uid,
|
||||||
i,
|
i,
|
||||||
|
@ -1021,13 +1013,13 @@ async def tell_little_bro(
|
||||||
)
|
)
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
'raise_sub_spawn_error_after',
|
'raise_sub_spawn_error_after',
|
||||||
[None, 50],
|
[None, 0.5],
|
||||||
)
|
)
|
||||||
def test_peer_spawns_and_cancels_service_subactor(
|
def test_peer_spawns_and_cancels_service_subactor(
|
||||||
debug_mode: bool,
|
debug_mode: bool,
|
||||||
raise_client_error: str,
|
raise_client_error: str,
|
||||||
reg_addr: tuple[str, int],
|
reg_addr: tuple[str, int],
|
||||||
raise_sub_spawn_error_after: int|None,
|
raise_sub_spawn_error_after: float|None,
|
||||||
):
|
):
|
||||||
# NOTE: this tests for the modden `mod wks open piker` bug
|
# NOTE: this tests for the modden `mod wks open piker` bug
|
||||||
# discovered as part of implementing workspace ctx
|
# discovered as part of implementing workspace ctx
|
||||||
|
@ -1041,6 +1033,7 @@ def test_peer_spawns_and_cancels_service_subactor(
|
||||||
# and the server's spawned child should cancel and terminate!
|
# and the server's spawned child should cancel and terminate!
|
||||||
peer_name: str = 'little_bro'
|
peer_name: str = 'little_bro'
|
||||||
|
|
||||||
|
|
||||||
def check_inner_rte(rae: RemoteActorError):
|
def check_inner_rte(rae: RemoteActorError):
|
||||||
'''
|
'''
|
||||||
Validate the little_bro's relayed inception!
|
Validate the little_bro's relayed inception!
|
||||||
|
@ -1134,8 +1127,7 @@ def test_peer_spawns_and_cancels_service_subactor(
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
res = await client_ctx.result(hide_tb=False)
|
res = await client_ctx.wait_for_result(hide_tb=False)
|
||||||
|
|
||||||
# in remote (relayed inception) error
|
# in remote (relayed inception) error
|
||||||
# case, we should error on the line above!
|
# case, we should error on the line above!
|
||||||
if raise_sub_spawn_error_after:
|
if raise_sub_spawn_error_after:
|
||||||
|
@ -1146,6 +1138,23 @@ def test_peer_spawns_and_cancels_service_subactor(
|
||||||
assert isinstance(res, ContextCancelled)
|
assert isinstance(res, ContextCancelled)
|
||||||
assert client_ctx.cancel_acked
|
assert client_ctx.cancel_acked
|
||||||
assert res.canceller == root.uid
|
assert res.canceller == root.uid
|
||||||
|
assert not raise_sub_spawn_error_after
|
||||||
|
|
||||||
|
# cancelling the spawner sub should
|
||||||
|
# transitively cancel it's sub, the little
|
||||||
|
# bruv.
|
||||||
|
print('root cancelling server/client sub-actors')
|
||||||
|
await spawn_ctx.cancel()
|
||||||
|
async with tractor.find_actor(
|
||||||
|
name=peer_name,
|
||||||
|
) as sub:
|
||||||
|
assert not sub
|
||||||
|
|
||||||
|
# XXX, only for tracing
|
||||||
|
# except BaseException as _berr:
|
||||||
|
# berr = _berr
|
||||||
|
# await tractor.pause(shield=True)
|
||||||
|
# raise berr
|
||||||
|
|
||||||
except RemoteActorError as rae:
|
except RemoteActorError as rae:
|
||||||
_err = rae
|
_err = rae
|
||||||
|
@ -1174,19 +1183,8 @@ def test_peer_spawns_and_cancels_service_subactor(
|
||||||
raise
|
raise
|
||||||
# await tractor.pause()
|
# await tractor.pause()
|
||||||
|
|
||||||
else:
|
|
||||||
assert not raise_sub_spawn_error_after
|
|
||||||
|
|
||||||
# cancelling the spawner sub should
|
|
||||||
# transitively cancel it's sub, the little
|
|
||||||
# bruv.
|
|
||||||
print('root cancelling server/client sub-actors')
|
|
||||||
await spawn_ctx.cancel()
|
|
||||||
async with tractor.find_actor(
|
|
||||||
name=peer_name,
|
|
||||||
) as sub:
|
|
||||||
assert not sub
|
|
||||||
|
|
||||||
|
# await tractor.pause()
|
||||||
# await server.cancel_actor()
|
# await server.cancel_actor()
|
||||||
|
|
||||||
except RemoteActorError as rae:
|
except RemoteActorError as rae:
|
||||||
|
@ -1199,7 +1197,7 @@ def test_peer_spawns_and_cancels_service_subactor(
|
||||||
|
|
||||||
# since we called `.cancel_actor()`, `.cancel_ack`
|
# since we called `.cancel_actor()`, `.cancel_ack`
|
||||||
# will not be set on the ctx bc `ctx.cancel()` was not
|
# will not be set on the ctx bc `ctx.cancel()` was not
|
||||||
# called directly fot this confext.
|
# called directly for this confext.
|
||||||
except ContextCancelled as ctxc:
|
except ContextCancelled as ctxc:
|
||||||
_ctxc = ctxc
|
_ctxc = ctxc
|
||||||
print(
|
print(
|
||||||
|
@ -1239,12 +1237,19 @@ def test_peer_spawns_and_cancels_service_subactor(
|
||||||
|
|
||||||
# assert spawn_ctx.cancelled_caught
|
# assert spawn_ctx.cancelled_caught
|
||||||
|
|
||||||
|
async def _main():
|
||||||
|
with trio.fail_after(
|
||||||
|
3 if not debug_mode
|
||||||
|
else 999
|
||||||
|
):
|
||||||
|
await main()
|
||||||
|
|
||||||
if raise_sub_spawn_error_after:
|
if raise_sub_spawn_error_after:
|
||||||
with pytest.raises(RemoteActorError) as excinfo:
|
with pytest.raises(RemoteActorError) as excinfo:
|
||||||
trio.run(main)
|
trio.run(_main)
|
||||||
|
|
||||||
rae: RemoteActorError = excinfo.value
|
rae: RemoteActorError = excinfo.value
|
||||||
check_inner_rte(rae)
|
check_inner_rte(rae)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
trio.run(main)
|
trio.run(_main)
|
||||||
|
|
|
@ -235,10 +235,16 @@ async def cancel_after(wait, reg_addr):
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope='module')
|
@pytest.fixture(scope='module')
|
||||||
def time_quad_ex(reg_addr, ci_env, spawn_backend):
|
def time_quad_ex(
|
||||||
|
reg_addr: tuple,
|
||||||
|
ci_env: bool,
|
||||||
|
spawn_backend: str,
|
||||||
|
):
|
||||||
if spawn_backend == 'mp':
|
if spawn_backend == 'mp':
|
||||||
"""no idea but the mp *nix runs are flaking out here often...
|
'''
|
||||||
"""
|
no idea but the mp *nix runs are flaking out here often...
|
||||||
|
|
||||||
|
'''
|
||||||
pytest.skip("Test is too flaky on mp in CI")
|
pytest.skip("Test is too flaky on mp in CI")
|
||||||
|
|
||||||
timeout = 7 if platform.system() in ('Windows', 'Darwin') else 4
|
timeout = 7 if platform.system() in ('Windows', 'Darwin') else 4
|
||||||
|
@ -249,12 +255,24 @@ def time_quad_ex(reg_addr, ci_env, spawn_backend):
|
||||||
return results, diff
|
return results, diff
|
||||||
|
|
||||||
|
|
||||||
def test_a_quadruple_example(time_quad_ex, ci_env, spawn_backend):
|
def test_a_quadruple_example(
|
||||||
"""This also serves as a kind of "we'd like to be this fast test"."""
|
time_quad_ex: tuple,
|
||||||
|
ci_env: bool,
|
||||||
|
spawn_backend: str,
|
||||||
|
):
|
||||||
|
'''
|
||||||
|
This also serves as a kind of "we'd like to be this fast test".
|
||||||
|
|
||||||
|
'''
|
||||||
results, diff = time_quad_ex
|
results, diff = time_quad_ex
|
||||||
assert results
|
assert results
|
||||||
this_fast = 6 if platform.system() in ('Windows', 'Darwin') else 3
|
this_fast = (
|
||||||
|
6 if platform.system() in (
|
||||||
|
'Windows',
|
||||||
|
'Darwin',
|
||||||
|
)
|
||||||
|
else 3
|
||||||
|
)
|
||||||
assert diff < this_fast
|
assert diff < this_fast
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,239 @@
|
||||||
|
'''
|
||||||
|
Define the details of inter-actor "out-of-band" (OoB) cancel
|
||||||
|
semantics, that is how cancellation works when a cancel request comes
|
||||||
|
from the different concurrency (primitive's) "layer" then where the
|
||||||
|
eventual `trio.Task` actually raises a signal.
|
||||||
|
|
||||||
|
'''
|
||||||
|
from functools import partial
|
||||||
|
# from contextlib import asynccontextmanager as acm
|
||||||
|
# import itertools
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
import trio
|
||||||
|
import tractor
|
||||||
|
from tractor import ( # typing
|
||||||
|
ActorNursery,
|
||||||
|
Portal,
|
||||||
|
Context,
|
||||||
|
# ContextCancelled,
|
||||||
|
# RemoteActorError,
|
||||||
|
)
|
||||||
|
# from tractor._testing import (
|
||||||
|
# tractor_test,
|
||||||
|
# expect_ctxc,
|
||||||
|
# )
|
||||||
|
|
||||||
|
# XXX TODO cases:
|
||||||
|
# - [ ] peer cancelled itself - so other peers should
|
||||||
|
# get errors reflecting that the peer was itself the .canceller?
|
||||||
|
|
||||||
|
# def test_self_cancel():
|
||||||
|
# '''
|
||||||
|
# 2 cases:
|
||||||
|
# - calls `Actor.cancel()` locally in some task
|
||||||
|
# - calls LocalPortal.cancel_actor()` ?
|
||||||
|
#
|
||||||
|
# things to ensure!
|
||||||
|
# -[ ] the ctxc raised in a child should ideally show the tb of the
|
||||||
|
# underlying `Cancelled` checkpoint, i.e.
|
||||||
|
# `raise scope_error from ctxc`?
|
||||||
|
#
|
||||||
|
# -[ ] a self-cancelled context, if not allowed to block on
|
||||||
|
# `ctx.result()` at some point will hang since the `ctx._scope`
|
||||||
|
# is never `.cancel_called`; cases for this include,
|
||||||
|
# - an `open_ctx()` which never starteds before being OoB actor
|
||||||
|
# cancelled.
|
||||||
|
# |_ parent task will be blocked in `.open_context()` for the
|
||||||
|
# `Started` msg, and when the OoB ctxc arrives `ctx._scope`
|
||||||
|
# will never have been signalled..
|
||||||
|
|
||||||
|
# '''
|
||||||
|
# ...
|
||||||
|
|
||||||
|
# TODO, sanity test against the case in `/examples/trio/lockacquire_not_unmasked.py`
|
||||||
|
# but with the `Lock.acquire()` from a `@context` to ensure the
|
||||||
|
# implicit ignore-case-non-unmasking.
|
||||||
|
#
|
||||||
|
# @tractor.context
|
||||||
|
# async def acquire_actor_global_lock(
|
||||||
|
# ctx: tractor.Context,
|
||||||
|
# ignore_special_cases: bool,
|
||||||
|
# ):
|
||||||
|
|
||||||
|
# async with maybe_unmask_excs(
|
||||||
|
# ignore_special_cases=ignore_special_cases,
|
||||||
|
# ):
|
||||||
|
# await ctx.started('locked')
|
||||||
|
|
||||||
|
# # block til cancelled
|
||||||
|
# await trio.sleep_forever()
|
||||||
|
|
||||||
|
|
||||||
|
@tractor.context
|
||||||
|
async def sleep_forever(
|
||||||
|
ctx: tractor.Context,
|
||||||
|
# ignore_special_cases: bool,
|
||||||
|
do_started: bool,
|
||||||
|
):
|
||||||
|
|
||||||
|
# async with maybe_unmask_excs(
|
||||||
|
# ignore_special_cases=ignore_special_cases,
|
||||||
|
# ):
|
||||||
|
# await ctx.started('locked')
|
||||||
|
if do_started:
|
||||||
|
await ctx.started()
|
||||||
|
|
||||||
|
# block til cancelled
|
||||||
|
print('sleepin on child-side..')
|
||||||
|
await trio.sleep_forever()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
'cancel_ctx',
|
||||||
|
[True, False],
|
||||||
|
)
|
||||||
|
def test_cancel_ctx_with_parent_side_entered_in_bg_task(
|
||||||
|
debug_mode: bool,
|
||||||
|
loglevel: str,
|
||||||
|
cancel_ctx: bool,
|
||||||
|
):
|
||||||
|
'''
|
||||||
|
The most "basic" out-of-band-task self-cancellation case where
|
||||||
|
`Portal.open_context()` is entered in a bg task and the
|
||||||
|
parent-task (of the containing nursery) calls `Context.cancel()`
|
||||||
|
without the child knowing; the `Context._scope` should be
|
||||||
|
`.cancel_called` when the IPC ctx's child-side relays
|
||||||
|
a `ContextCancelled` with a `.canceller` set to the parent
|
||||||
|
actor('s task).
|
||||||
|
|
||||||
|
'''
|
||||||
|
async def main():
|
||||||
|
with trio.fail_after(
|
||||||
|
2 if not debug_mode else 999,
|
||||||
|
):
|
||||||
|
an: ActorNursery
|
||||||
|
async with (
|
||||||
|
tractor.open_nursery(
|
||||||
|
debug_mode=debug_mode,
|
||||||
|
loglevel='devx',
|
||||||
|
enable_stack_on_sig=True,
|
||||||
|
) as an,
|
||||||
|
trio.open_nursery() as tn,
|
||||||
|
):
|
||||||
|
ptl: Portal = await an.start_actor(
|
||||||
|
'sub',
|
||||||
|
enable_modules=[__name__],
|
||||||
|
)
|
||||||
|
|
||||||
|
async def _open_ctx_async(
|
||||||
|
do_started: bool = True,
|
||||||
|
task_status=trio.TASK_STATUS_IGNORED,
|
||||||
|
):
|
||||||
|
# do we expect to never enter the
|
||||||
|
# `.open_context()` below.
|
||||||
|
if not do_started:
|
||||||
|
task_status.started()
|
||||||
|
|
||||||
|
async with ptl.open_context(
|
||||||
|
sleep_forever,
|
||||||
|
do_started=do_started,
|
||||||
|
) as (ctx, first):
|
||||||
|
task_status.started(ctx)
|
||||||
|
await trio.sleep_forever()
|
||||||
|
|
||||||
|
# XXX, this is the key OoB part!
|
||||||
|
#
|
||||||
|
# - start the `.open_context()` in a bg task which
|
||||||
|
# blocks inside the embedded scope-body,
|
||||||
|
#
|
||||||
|
# - when we call `Context.cancel()` it **is
|
||||||
|
# not** from the same task which eventually runs
|
||||||
|
# `.__aexit__()`,
|
||||||
|
#
|
||||||
|
# - since the bg "opener" task will be in
|
||||||
|
# a `trio.sleep_forever()`, it must be interrupted
|
||||||
|
# by the `ContextCancelled` delivered from the
|
||||||
|
# child-side; `Context._scope: CancelScope` MUST
|
||||||
|
# be `.cancel_called`!
|
||||||
|
#
|
||||||
|
print('ASYNC opening IPC context in subtask..')
|
||||||
|
maybe_ctx: Context|None = await tn.start(partial(
|
||||||
|
_open_ctx_async,
|
||||||
|
))
|
||||||
|
|
||||||
|
if (
|
||||||
|
maybe_ctx
|
||||||
|
and
|
||||||
|
cancel_ctx
|
||||||
|
):
|
||||||
|
print('cancelling first IPC ctx!')
|
||||||
|
await maybe_ctx.cancel()
|
||||||
|
|
||||||
|
# XXX, note that despite `maybe_context.cancel()`
|
||||||
|
# being called above, it's the parent (bg) task
|
||||||
|
# which was originally never interrupted in
|
||||||
|
# the `ctx._scope` body due to missing case logic in
|
||||||
|
# `ctx._maybe_cancel_and_set_remote_error()`.
|
||||||
|
#
|
||||||
|
# It didn't matter that the subactor process was
|
||||||
|
# already terminated and reaped, nothing was
|
||||||
|
# cancelling the ctx-parent task's scope!
|
||||||
|
#
|
||||||
|
print('cancelling subactor!')
|
||||||
|
await ptl.cancel_actor()
|
||||||
|
|
||||||
|
if maybe_ctx:
|
||||||
|
try:
|
||||||
|
await maybe_ctx.wait_for_result()
|
||||||
|
except tractor.ContextCancelled as ctxc:
|
||||||
|
assert not cancel_ctx
|
||||||
|
assert (
|
||||||
|
ctxc.canceller
|
||||||
|
==
|
||||||
|
tractor.current_actor().aid.uid
|
||||||
|
)
|
||||||
|
# don't re-raise since it'll trigger
|
||||||
|
# an EG from the above tn.
|
||||||
|
|
||||||
|
if cancel_ctx:
|
||||||
|
# graceful self-cancel
|
||||||
|
trio.run(main)
|
||||||
|
|
||||||
|
else:
|
||||||
|
# ctx parent task should see OoB ctxc due to
|
||||||
|
# `ptl.cancel_actor()`.
|
||||||
|
with pytest.raises(tractor.ContextCancelled) as excinfo:
|
||||||
|
trio.run(main)
|
||||||
|
|
||||||
|
assert 'root' in excinfo.value.canceller[0]
|
||||||
|
|
||||||
|
|
||||||
|
# def test_parent_actor_cancels_subactor_with_gt1_ctxs_open_to_it(
|
||||||
|
# debug_mode: bool,
|
||||||
|
# loglevel: str,
|
||||||
|
# ):
|
||||||
|
# '''
|
||||||
|
# Demos OoB cancellation from the perspective of a ctx opened with
|
||||||
|
# a child subactor where the parent cancels the child at the "actor
|
||||||
|
# layer" using `Portal.cancel_actor()` and thus the
|
||||||
|
# `ContextCancelled.canceller` received by the ctx's parent-side
|
||||||
|
# task will appear to be a "self cancellation" even though that
|
||||||
|
# specific task itself was not cancelled and thus
|
||||||
|
# `Context.cancel_called ==False`.
|
||||||
|
# '''
|
||||||
|
# TODO, do we have an existing implied ctx
|
||||||
|
# cancel test like this?
|
||||||
|
# with trio.move_on_after(0.5):# as cs:
|
||||||
|
# await _open_ctx_async(
|
||||||
|
# do_started=False,
|
||||||
|
# )
|
||||||
|
|
||||||
|
|
||||||
|
# in-line ctx scope should definitely raise
|
||||||
|
# a ctxc with `.canceller = 'root'`
|
||||||
|
# async with ptl.open_context(
|
||||||
|
# sleep_forever,
|
||||||
|
# do_started=True,
|
||||||
|
# ) as pair:
|
||||||
|
|
|
@ -1,5 +1,6 @@
|
||||||
'''
|
'''
|
||||||
Async context manager cache api testing: ``trionics.maybe_open_context():``
|
Suites for our `.trionics.maybe_open_context()` multi-task
|
||||||
|
shared-cached `@acm` API.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
from contextlib import asynccontextmanager as acm
|
from contextlib import asynccontextmanager as acm
|
||||||
|
@ -9,6 +10,15 @@ from typing import Awaitable
|
||||||
import pytest
|
import pytest
|
||||||
import trio
|
import trio
|
||||||
import tractor
|
import tractor
|
||||||
|
from tractor.trionics import (
|
||||||
|
maybe_open_context,
|
||||||
|
)
|
||||||
|
from tractor.log import (
|
||||||
|
get_console_log,
|
||||||
|
get_logger,
|
||||||
|
)
|
||||||
|
log = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
_resource: int = 0
|
_resource: int = 0
|
||||||
|
@ -52,7 +62,7 @@ def test_resource_only_entered_once(key_on):
|
||||||
# different task names per task will be used
|
# different task names per task will be used
|
||||||
kwargs = {'task_name': name}
|
kwargs = {'task_name': name}
|
||||||
|
|
||||||
async with tractor.trionics.maybe_open_context(
|
async with maybe_open_context(
|
||||||
maybe_increment_counter,
|
maybe_increment_counter,
|
||||||
kwargs=kwargs,
|
kwargs=kwargs,
|
||||||
key=key,
|
key=key,
|
||||||
|
@ -72,11 +82,13 @@ def test_resource_only_entered_once(key_on):
|
||||||
with trio.move_on_after(0.5):
|
with trio.move_on_after(0.5):
|
||||||
async with (
|
async with (
|
||||||
tractor.open_root_actor(),
|
tractor.open_root_actor(),
|
||||||
trio.open_nursery() as n,
|
trio.open_nursery() as tn,
|
||||||
):
|
):
|
||||||
|
|
||||||
for i in range(10):
|
for i in range(10):
|
||||||
n.start_soon(enter_cached_mngr, f'task_{i}')
|
tn.start_soon(
|
||||||
|
enter_cached_mngr,
|
||||||
|
f'task_{i}',
|
||||||
|
)
|
||||||
await trio.sleep(0.001)
|
await trio.sleep(0.001)
|
||||||
|
|
||||||
trio.run(main)
|
trio.run(main)
|
||||||
|
@ -98,21 +110,32 @@ async def streamer(
|
||||||
|
|
||||||
|
|
||||||
@acm
|
@acm
|
||||||
async def open_stream() -> Awaitable[tractor.MsgStream]:
|
async def open_stream() -> Awaitable[
|
||||||
|
tuple[
|
||||||
|
tractor.ActorNursery,
|
||||||
|
tractor.MsgStream,
|
||||||
|
]
|
||||||
|
]:
|
||||||
try:
|
try:
|
||||||
async with tractor.open_nursery() as an:
|
async with tractor.open_nursery() as an:
|
||||||
portal = await an.start_actor(
|
portal = await an.start_actor(
|
||||||
'streamer',
|
'streamer',
|
||||||
enable_modules=[__name__],
|
enable_modules=[__name__],
|
||||||
)
|
)
|
||||||
|
try:
|
||||||
async with (
|
async with (
|
||||||
portal.open_context(streamer) as (ctx, first),
|
portal.open_context(streamer) as (ctx, first),
|
||||||
ctx.open_stream() as stream,
|
ctx.open_stream() as stream,
|
||||||
):
|
):
|
||||||
yield stream
|
print('Entered open_stream() caller')
|
||||||
|
yield an, stream
|
||||||
|
print('Exited open_stream() caller')
|
||||||
|
|
||||||
print('Cancelling streamer')
|
finally:
|
||||||
|
print(
|
||||||
|
'Cancelling streamer with,\n'
|
||||||
|
'=> `Portal.cancel_actor()`'
|
||||||
|
)
|
||||||
await portal.cancel_actor()
|
await portal.cancel_actor()
|
||||||
print('Cancelled streamer')
|
print('Cancelled streamer')
|
||||||
|
|
||||||
|
@ -127,11 +150,15 @@ async def open_stream() -> Awaitable[tractor.MsgStream]:
|
||||||
|
|
||||||
@acm
|
@acm
|
||||||
async def maybe_open_stream(taskname: str):
|
async def maybe_open_stream(taskname: str):
|
||||||
async with tractor.trionics.maybe_open_context(
|
async with maybe_open_context(
|
||||||
# NOTE: all secondary tasks should cache hit on the same key
|
# NOTE: all secondary tasks should cache hit on the same key
|
||||||
acm_func=open_stream,
|
acm_func=open_stream,
|
||||||
) as (cache_hit, stream):
|
) as (
|
||||||
|
cache_hit,
|
||||||
|
(an, stream)
|
||||||
|
):
|
||||||
|
# when the actor + portal + ctx + stream has already been
|
||||||
|
# allocated we want to just bcast to this task.
|
||||||
if cache_hit:
|
if cache_hit:
|
||||||
print(f'{taskname} loaded from cache')
|
print(f'{taskname} loaded from cache')
|
||||||
|
|
||||||
|
@ -139,10 +166,43 @@ async def maybe_open_stream(taskname: str):
|
||||||
# if this feed is already allocated by the first
|
# if this feed is already allocated by the first
|
||||||
# task that entereed
|
# task that entereed
|
||||||
async with stream.subscribe() as bstream:
|
async with stream.subscribe() as bstream:
|
||||||
yield bstream
|
yield an, bstream
|
||||||
|
print(
|
||||||
|
f'cached task exited\n'
|
||||||
|
f')>\n'
|
||||||
|
f' |_{taskname}\n'
|
||||||
|
)
|
||||||
|
|
||||||
|
# we should always unreg the "cloned" bcrc for this
|
||||||
|
# consumer-task
|
||||||
|
assert id(bstream) not in bstream._state.subs
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# yield the actual stream
|
# yield the actual stream
|
||||||
yield stream
|
try:
|
||||||
|
yield an, stream
|
||||||
|
finally:
|
||||||
|
print(
|
||||||
|
f'NON-cached task exited\n'
|
||||||
|
f')>\n'
|
||||||
|
f' |_{taskname}\n'
|
||||||
|
)
|
||||||
|
|
||||||
|
first_bstream = stream._broadcaster
|
||||||
|
bcrx_state = first_bstream._state
|
||||||
|
subs: dict[int, int] = bcrx_state.subs
|
||||||
|
if len(subs) == 1:
|
||||||
|
assert id(first_bstream) in subs
|
||||||
|
# ^^TODO! the bcrx should always de-allocate all subs,
|
||||||
|
# including the implicit first one allocated on entry
|
||||||
|
# by the first subscribing peer task, no?
|
||||||
|
#
|
||||||
|
# -[ ] adjust `MsgStream.subscribe()` to do this mgmt!
|
||||||
|
# |_ allows reverting `MsgStream.receive()` to the
|
||||||
|
# non-bcaster method.
|
||||||
|
# |_ we can decide whether to reset `._broadcaster`?
|
||||||
|
#
|
||||||
|
# await tractor.pause(shield=True)
|
||||||
|
|
||||||
|
|
||||||
def test_open_local_sub_to_stream(
|
def test_open_local_sub_to_stream(
|
||||||
|
@ -159,16 +219,24 @@ def test_open_local_sub_to_stream(
|
||||||
|
|
||||||
if debug_mode:
|
if debug_mode:
|
||||||
timeout = 999
|
timeout = 999
|
||||||
|
print(f'IN debug_mode, setting large timeout={timeout!r}..')
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
|
|
||||||
full = list(range(1000))
|
full = list(range(1000))
|
||||||
|
an: tractor.ActorNursery|None = None
|
||||||
|
num_tasks: int = 10
|
||||||
|
|
||||||
async def get_sub_and_pull(taskname: str):
|
async def get_sub_and_pull(taskname: str):
|
||||||
|
|
||||||
|
nonlocal an
|
||||||
|
|
||||||
stream: tractor.MsgStream
|
stream: tractor.MsgStream
|
||||||
async with (
|
async with (
|
||||||
maybe_open_stream(taskname) as stream,
|
maybe_open_stream(taskname) as (
|
||||||
|
an,
|
||||||
|
stream,
|
||||||
|
),
|
||||||
):
|
):
|
||||||
if '0' in taskname:
|
if '0' in taskname:
|
||||||
assert isinstance(stream, tractor.MsgStream)
|
assert isinstance(stream, tractor.MsgStream)
|
||||||
|
@ -180,34 +248,159 @@ def test_open_local_sub_to_stream(
|
||||||
|
|
||||||
first = await stream.receive()
|
first = await stream.receive()
|
||||||
print(f'{taskname} started with value {first}')
|
print(f'{taskname} started with value {first}')
|
||||||
seq = []
|
seq: list[int] = []
|
||||||
async for msg in stream:
|
async for msg in stream:
|
||||||
seq.append(msg)
|
seq.append(msg)
|
||||||
|
|
||||||
assert set(seq).issubset(set(full))
|
assert set(seq).issubset(set(full))
|
||||||
|
|
||||||
|
# end of @acm block
|
||||||
print(f'{taskname} finished')
|
print(f'{taskname} finished')
|
||||||
|
|
||||||
|
root: tractor.Actor
|
||||||
with trio.fail_after(timeout) as cs:
|
with trio.fail_after(timeout) as cs:
|
||||||
# TODO: turns out this isn't multi-task entrant XD
|
# TODO: turns out this isn't multi-task entrant XD
|
||||||
# We probably need an indepotent entry semantic?
|
# We probably need an indepotent entry semantic?
|
||||||
async with tractor.open_root_actor(
|
async with tractor.open_root_actor(
|
||||||
debug_mode=debug_mode,
|
debug_mode=debug_mode,
|
||||||
):
|
# maybe_enable_greenback=True,
|
||||||
|
#
|
||||||
|
# ^TODO? doesn't seem to mk breakpoint() usage work
|
||||||
|
# bc each bg task needs to open a portal??
|
||||||
|
# - [ ] we should consider making this part of
|
||||||
|
# our taskman defaults?
|
||||||
|
# |_see https://github.com/goodboy/tractor/pull/363
|
||||||
|
#
|
||||||
|
) as root:
|
||||||
|
assert root.is_registrar
|
||||||
|
|
||||||
async with (
|
async with (
|
||||||
trio.open_nursery() as tn,
|
trio.open_nursery() as tn,
|
||||||
):
|
):
|
||||||
for i in range(10):
|
for i in range(num_tasks):
|
||||||
tn.start_soon(
|
tn.start_soon(
|
||||||
get_sub_and_pull,
|
get_sub_and_pull,
|
||||||
f'task_{i}',
|
f'task_{i}',
|
||||||
)
|
)
|
||||||
await trio.sleep(0.001)
|
await trio.sleep(0.001)
|
||||||
|
|
||||||
print('all consumer tasks finished')
|
print('all consumer tasks finished!')
|
||||||
|
|
||||||
|
# ?XXX, ensure actor-nursery is shutdown or we might
|
||||||
|
# hang here due to a minor task deadlock/race-condition?
|
||||||
|
#
|
||||||
|
# - seems that all we need is a checkpoint to ensure
|
||||||
|
# the last suspended task, which is inside
|
||||||
|
# `.maybe_open_context()`, can do the
|
||||||
|
# `Portal.cancel_actor()` call?
|
||||||
|
#
|
||||||
|
# - if that bg task isn't resumed, then this blocks
|
||||||
|
# timeout might hit before that?
|
||||||
|
#
|
||||||
|
if root.ipc_server.has_peers():
|
||||||
|
await trio.lowlevel.checkpoint()
|
||||||
|
|
||||||
|
# alt approach, cancel the entire `an`
|
||||||
|
# await tractor.pause()
|
||||||
|
# await an.cancel()
|
||||||
|
|
||||||
|
# end of runtime scope
|
||||||
|
print('root actor terminated.')
|
||||||
|
|
||||||
if cs.cancelled_caught:
|
if cs.cancelled_caught:
|
||||||
pytest.fail(
|
pytest.fail(
|
||||||
'Should NOT time out in `open_root_actor()` ?'
|
'Should NOT time out in `open_root_actor()` ?'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
print('exiting main.')
|
||||||
|
|
||||||
|
trio.run(main)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@acm
|
||||||
|
async def cancel_outer_cs(
|
||||||
|
cs: trio.CancelScope|None = None,
|
||||||
|
delay: float = 0,
|
||||||
|
):
|
||||||
|
# on first task delay this enough to block
|
||||||
|
# the 2nd task but then cancel it mid sleep
|
||||||
|
# so that the tn.start() inside the key-err handler block
|
||||||
|
# is cancelled and would previously corrupt the
|
||||||
|
# mutext state.
|
||||||
|
log.info(f'task entering sleep({delay})')
|
||||||
|
await trio.sleep(delay)
|
||||||
|
if cs:
|
||||||
|
log.info('task calling cs.cancel()')
|
||||||
|
cs.cancel()
|
||||||
|
trio.lowlevel.checkpoint()
|
||||||
|
yield
|
||||||
|
await trio.sleep_forever()
|
||||||
|
|
||||||
|
|
||||||
|
def test_lock_not_corrupted_on_fast_cancel(
|
||||||
|
debug_mode: bool,
|
||||||
|
loglevel: str,
|
||||||
|
):
|
||||||
|
'''
|
||||||
|
Verify that if the caching-task (the first to enter
|
||||||
|
`maybe_open_context()`) is cancelled mid-cache-miss, the embedded
|
||||||
|
mutex can never be left in a corrupted state.
|
||||||
|
|
||||||
|
That is, the lock is always eventually released ensuring a peer
|
||||||
|
(cache-hitting) task will never,
|
||||||
|
|
||||||
|
- be left to inf-block/hang on the `lock.acquire()`.
|
||||||
|
- try to release the lock when still owned by the caching-task
|
||||||
|
due to it having erronously exited without calling
|
||||||
|
`lock.release()`.
|
||||||
|
|
||||||
|
|
||||||
|
'''
|
||||||
|
delay: float = 1.
|
||||||
|
|
||||||
|
async def use_moc(
|
||||||
|
cs: trio.CancelScope|None,
|
||||||
|
delay: float,
|
||||||
|
):
|
||||||
|
log.info('task entering moc')
|
||||||
|
async with maybe_open_context(
|
||||||
|
cancel_outer_cs,
|
||||||
|
kwargs={
|
||||||
|
'cs': cs,
|
||||||
|
'delay': delay,
|
||||||
|
},
|
||||||
|
) as (cache_hit, _null):
|
||||||
|
if cache_hit:
|
||||||
|
log.info('2nd task entered')
|
||||||
|
else:
|
||||||
|
log.info('1st task entered')
|
||||||
|
|
||||||
|
await trio.sleep_forever()
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
with trio.fail_after(delay + 2):
|
||||||
|
async with (
|
||||||
|
tractor.open_root_actor(
|
||||||
|
debug_mode=debug_mode,
|
||||||
|
loglevel=loglevel,
|
||||||
|
),
|
||||||
|
trio.open_nursery() as tn,
|
||||||
|
):
|
||||||
|
get_console_log('info')
|
||||||
|
log.info('yo starting')
|
||||||
|
cs = tn.cancel_scope
|
||||||
|
tn.start_soon(
|
||||||
|
use_moc,
|
||||||
|
cs,
|
||||||
|
delay,
|
||||||
|
name='child',
|
||||||
|
)
|
||||||
|
with trio.CancelScope() as rent_cs:
|
||||||
|
await use_moc(
|
||||||
|
cs=rent_cs,
|
||||||
|
delay=delay,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
trio.run(main)
|
trio.run(main)
|
||||||
|
|
|
@ -147,8 +147,7 @@ def test_trio_prestarted_task_bubbles(
|
||||||
await trio.sleep_forever()
|
await trio.sleep_forever()
|
||||||
|
|
||||||
async def _trio_main():
|
async def _trio_main():
|
||||||
# with trio.fail_after(2):
|
with trio.fail_after(2 if not debug_mode else 999):
|
||||||
with trio.fail_after(999):
|
|
||||||
first: str
|
first: str
|
||||||
chan: to_asyncio.LinkedTaskChannel
|
chan: to_asyncio.LinkedTaskChannel
|
||||||
aio_ev = asyncio.Event()
|
aio_ev = asyncio.Event()
|
||||||
|
@ -217,32 +216,25 @@ def test_trio_prestarted_task_bubbles(
|
||||||
):
|
):
|
||||||
aio_ev.set()
|
aio_ev.set()
|
||||||
|
|
||||||
with pytest.raises(
|
|
||||||
expected_exception=ExceptionGroup,
|
|
||||||
) as excinfo:
|
|
||||||
tractor.to_asyncio.run_as_asyncio_guest(
|
|
||||||
trio_main=_trio_main,
|
|
||||||
)
|
|
||||||
|
|
||||||
eg = excinfo.value
|
|
||||||
rte_eg, rest_eg = eg.split(RuntimeError)
|
|
||||||
|
|
||||||
# ensure the trio-task's error bubbled despite the aio-side
|
# ensure the trio-task's error bubbled despite the aio-side
|
||||||
# having (maybe) errored first.
|
# having (maybe) errored first.
|
||||||
if aio_err_trigger in (
|
if aio_err_trigger in (
|
||||||
'after_trio_task_starts',
|
'after_trio_task_starts',
|
||||||
'after_start_point',
|
'after_start_point',
|
||||||
):
|
):
|
||||||
assert len(errs := rest_eg.exceptions) == 1
|
patt: str = 'trio-side'
|
||||||
typerr = errs[0]
|
expect_exc = TypeError
|
||||||
assert (
|
|
||||||
type(typerr) is TypeError
|
|
||||||
and
|
|
||||||
'trio-side' in typerr.args
|
|
||||||
)
|
|
||||||
|
|
||||||
# when aio errors BEFORE (last) trio task is scheduled, we should
|
# when aio errors BEFORE (last) trio task is scheduled, we should
|
||||||
# never see anythinb but the aio-side.
|
# never see anythinb but the aio-side.
|
||||||
else:
|
else:
|
||||||
assert len(rtes := rte_eg.exceptions) == 1
|
patt: str = 'asyncio-side'
|
||||||
assert 'asyncio-side' in rtes[0].args[0]
|
expect_exc = RuntimeError
|
||||||
|
|
||||||
|
with pytest.raises(expect_exc) as excinfo:
|
||||||
|
tractor.to_asyncio.run_as_asyncio_guest(
|
||||||
|
trio_main=_trio_main,
|
||||||
|
)
|
||||||
|
|
||||||
|
caught_exc = excinfo.value
|
||||||
|
assert patt in caught_exc.args
|
||||||
|
|
|
@ -6,10 +6,18 @@ want to see changed.
|
||||||
from contextlib import (
|
from contextlib import (
|
||||||
asynccontextmanager as acm,
|
asynccontextmanager as acm,
|
||||||
)
|
)
|
||||||
|
from types import ModuleType
|
||||||
|
|
||||||
|
from functools import partial
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
from _pytest import pathlib
|
||||||
|
from tractor.trionics import collapse_eg
|
||||||
import trio
|
import trio
|
||||||
from trio import TaskStatus
|
from trio import TaskStatus
|
||||||
|
from tractor._testing import (
|
||||||
|
examples_dir,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
|
@ -64,9 +72,8 @@ def test_stashed_child_nursery(use_start_soon):
|
||||||
async def main():
|
async def main():
|
||||||
|
|
||||||
async with (
|
async with (
|
||||||
trio.open_nursery(
|
collapse_eg(),
|
||||||
strict_exception_groups=False,
|
trio.open_nursery() as pn,
|
||||||
) as pn,
|
|
||||||
):
|
):
|
||||||
cn = await pn.start(mk_child_nursery)
|
cn = await pn.start(mk_child_nursery)
|
||||||
assert cn
|
assert cn
|
||||||
|
@ -106,8 +113,9 @@ def test_acm_embedded_nursery_propagates_enter_err(
|
||||||
debug_mode: bool,
|
debug_mode: bool,
|
||||||
):
|
):
|
||||||
'''
|
'''
|
||||||
Demo how a masking `trio.Cancelled` could be handled by unmasking from the
|
Demo how a masking `trio.Cancelled` could be handled by unmasking
|
||||||
`.__context__` field when a user (by accident) re-raises from a `finally:`.
|
from the `.__context__` field when a user (by accident) re-raises
|
||||||
|
from a `finally:`.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
import tractor
|
import tractor
|
||||||
|
@ -117,11 +125,9 @@ def test_acm_embedded_nursery_propagates_enter_err(
|
||||||
async with (
|
async with (
|
||||||
trio.open_nursery() as tn,
|
trio.open_nursery() as tn,
|
||||||
tractor.trionics.maybe_raise_from_masking_exc(
|
tractor.trionics.maybe_raise_from_masking_exc(
|
||||||
tn=tn,
|
|
||||||
unmask_from=(
|
unmask_from=(
|
||||||
trio.Cancelled
|
(trio.Cancelled,) if unmask_from_canc
|
||||||
if unmask_from_canc
|
else ()
|
||||||
else None
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
):
|
):
|
||||||
|
@ -136,7 +142,6 @@ def test_acm_embedded_nursery_propagates_enter_err(
|
||||||
with tractor.devx.maybe_open_crash_handler(
|
with tractor.devx.maybe_open_crash_handler(
|
||||||
pdb=debug_mode,
|
pdb=debug_mode,
|
||||||
) as bxerr:
|
) as bxerr:
|
||||||
if bxerr:
|
|
||||||
assert not bxerr.value
|
assert not bxerr.value
|
||||||
|
|
||||||
async with (
|
async with (
|
||||||
|
@ -145,6 +150,7 @@ def test_acm_embedded_nursery_propagates_enter_err(
|
||||||
assert not tn.cancel_scope.cancel_called
|
assert not tn.cancel_scope.cancel_called
|
||||||
assert 0
|
assert 0
|
||||||
|
|
||||||
|
if debug_mode:
|
||||||
assert (
|
assert (
|
||||||
(err := bxerr.value)
|
(err := bxerr.value)
|
||||||
and
|
and
|
||||||
|
@ -160,13 +166,13 @@ def test_acm_embedded_nursery_propagates_enter_err(
|
||||||
assert len(assert_eg.exceptions) == 1
|
assert len(assert_eg.exceptions) == 1
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_gatherctxs_with_memchan_breaks_multicancelled(
|
def test_gatherctxs_with_memchan_breaks_multicancelled(
|
||||||
debug_mode: bool,
|
debug_mode: bool,
|
||||||
):
|
):
|
||||||
'''
|
'''
|
||||||
Demo how a using an `async with sndchan` inside a `.trionics.gather_contexts()` task
|
Demo how a using an `async with sndchan` inside
|
||||||
will break a strict-eg-tn's multi-cancelled absorption..
|
a `.trionics.gather_contexts()` task will break a strict-eg-tn's
|
||||||
|
multi-cancelled absorption..
|
||||||
|
|
||||||
'''
|
'''
|
||||||
from tractor import (
|
from tractor import (
|
||||||
|
@ -192,15 +198,12 @@ def test_gatherctxs_with_memchan_breaks_multicancelled(
|
||||||
f'Closed {task!r}\n'
|
f'Closed {task!r}\n'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
async with (
|
async with (
|
||||||
# XXX should ensure ONLY the KBI
|
# XXX should ensure ONLY the KBI
|
||||||
# is relayed upward
|
# is relayed upward
|
||||||
trionics.collapse_eg(),
|
collapse_eg(),
|
||||||
trio.open_nursery(
|
trio.open_nursery(), # as tn,
|
||||||
# strict_exception_groups=False,
|
|
||||||
), # as tn,
|
|
||||||
|
|
||||||
trionics.gather_contexts([
|
trionics.gather_contexts([
|
||||||
open_memchan(),
|
open_memchan(),
|
||||||
|
@ -215,3 +218,85 @@ def test_gatherctxs_with_memchan_breaks_multicancelled(
|
||||||
|
|
||||||
with pytest.raises(KeyboardInterrupt):
|
with pytest.raises(KeyboardInterrupt):
|
||||||
trio.run(main)
|
trio.run(main)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
'raise_unmasked', [
|
||||||
|
True,
|
||||||
|
pytest.param(
|
||||||
|
False,
|
||||||
|
marks=pytest.mark.xfail(
|
||||||
|
reason="see examples/trio/send_chan_aclose_masks.py"
|
||||||
|
)
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
'child_errors_mid_stream',
|
||||||
|
[True, False],
|
||||||
|
)
|
||||||
|
def test_unmask_aclose_as_checkpoint_on_aexit(
|
||||||
|
raise_unmasked: bool,
|
||||||
|
child_errors_mid_stream: bool,
|
||||||
|
debug_mode: bool,
|
||||||
|
):
|
||||||
|
'''
|
||||||
|
Verify that our unmasker util works over the common case where
|
||||||
|
a mem-chan's `.aclose()` is included in an `@acm` stack
|
||||||
|
and it being currently a checkpoint, can `trio.Cancelled`-mask an embedded
|
||||||
|
exception from user code resulting in a silent failure which
|
||||||
|
appears like graceful cancellation.
|
||||||
|
|
||||||
|
This test suite is mostly implemented as an example script so it
|
||||||
|
could more easily be shared with `trio`-core peeps as `tractor`-less
|
||||||
|
minimum reproducing example.
|
||||||
|
|
||||||
|
'''
|
||||||
|
mod: ModuleType = pathlib.import_path(
|
||||||
|
examples_dir()
|
||||||
|
/ 'trio'
|
||||||
|
/ 'send_chan_aclose_masks_beg.py',
|
||||||
|
root=examples_dir(),
|
||||||
|
consider_namespace_packages=False,
|
||||||
|
)
|
||||||
|
with pytest.raises(RuntimeError):
|
||||||
|
trio.run(partial(
|
||||||
|
mod.main,
|
||||||
|
raise_unmasked=raise_unmasked,
|
||||||
|
child_errors_mid_stream=child_errors_mid_stream,
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
'ignore_special_cases', [
|
||||||
|
True,
|
||||||
|
pytest.param(
|
||||||
|
False,
|
||||||
|
marks=pytest.mark.xfail(
|
||||||
|
reason="see examples/trio/lockacquire_not_umasked.py"
|
||||||
|
)
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
def test_cancelled_lockacquire_in_ipctx_not_unmasked(
|
||||||
|
ignore_special_cases: bool,
|
||||||
|
loglevel: str,
|
||||||
|
debug_mode: bool,
|
||||||
|
):
|
||||||
|
mod: ModuleType = pathlib.import_path(
|
||||||
|
examples_dir()
|
||||||
|
/ 'trio'
|
||||||
|
/ 'lockacquire_not_unmasked.py',
|
||||||
|
root=examples_dir(),
|
||||||
|
consider_namespace_packages=False,
|
||||||
|
)
|
||||||
|
async def _main():
|
||||||
|
with trio.fail_after(2):
|
||||||
|
await mod.main(
|
||||||
|
ignore_special_cases=ignore_special_cases,
|
||||||
|
loglevel=loglevel,
|
||||||
|
debug_mode=debug_mode,
|
||||||
|
)
|
||||||
|
|
||||||
|
trio.run(_main)
|
||||||
|
|
|
@ -55,10 +55,17 @@ async def open_actor_cluster(
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
'Number of names is {len(names)} but count it {count}')
|
'Number of names is {len(names)} but count it {count}')
|
||||||
|
|
||||||
async with tractor.open_nursery(
|
async with (
|
||||||
|
# tractor.trionics.collapse_eg(),
|
||||||
|
tractor.open_nursery(
|
||||||
**runtime_kwargs,
|
**runtime_kwargs,
|
||||||
) as an:
|
) as an
|
||||||
async with trio.open_nursery() as n:
|
):
|
||||||
|
async with (
|
||||||
|
# tractor.trionics.collapse_eg(),
|
||||||
|
trio.open_nursery() as tn,
|
||||||
|
tractor.trionics.maybe_raise_from_masking_exc()
|
||||||
|
):
|
||||||
uid = tractor.current_actor().uid
|
uid = tractor.current_actor().uid
|
||||||
|
|
||||||
async def _start(name: str) -> None:
|
async def _start(name: str) -> None:
|
||||||
|
@ -69,9 +76,8 @@ async def open_actor_cluster(
|
||||||
)
|
)
|
||||||
|
|
||||||
for name in names:
|
for name in names:
|
||||||
n.start_soon(_start, name)
|
tn.start_soon(_start, name)
|
||||||
|
|
||||||
assert len(portals) == count
|
assert len(portals) == count
|
||||||
yield portals
|
yield portals
|
||||||
|
|
||||||
await an.cancel(hard_kill=hard_kill)
|
await an.cancel(hard_kill=hard_kill)
|
||||||
|
|
|
@ -154,7 +154,7 @@ class Context:
|
||||||
2 cancel-scope-linked, communicating and parallel executing
|
2 cancel-scope-linked, communicating and parallel executing
|
||||||
`Task`s. Contexts are allocated on each side of any task
|
`Task`s. Contexts are allocated on each side of any task
|
||||||
RPC-linked msg dialog, i.e. for every request to a remote
|
RPC-linked msg dialog, i.e. for every request to a remote
|
||||||
actor from a `Portal`. On the "callee" side a context is
|
actor from a `Portal`. On the "child" side a context is
|
||||||
always allocated inside `._rpc._invoke()`.
|
always allocated inside `._rpc._invoke()`.
|
||||||
|
|
||||||
TODO: more detailed writeup on cancellation, error and
|
TODO: more detailed writeup on cancellation, error and
|
||||||
|
@ -222,8 +222,8 @@ class Context:
|
||||||
# `._runtime.invoke()`.
|
# `._runtime.invoke()`.
|
||||||
_remote_func_type: str | None = None
|
_remote_func_type: str | None = None
|
||||||
|
|
||||||
# NOTE: (for now) only set (a portal) on the caller side since
|
# NOTE: (for now) only set (a portal) on the parent side since
|
||||||
# the callee doesn't generally need a ref to one and should
|
# the child doesn't generally need a ref to one and should
|
||||||
# normally need to explicitly ask for handle to its peer if
|
# normally need to explicitly ask for handle to its peer if
|
||||||
# more the the `Context` is needed?
|
# more the the `Context` is needed?
|
||||||
_portal: Portal | None = None
|
_portal: Portal | None = None
|
||||||
|
@ -252,12 +252,12 @@ class Context:
|
||||||
_outcome_msg: Return|Error|ContextCancelled = Unresolved
|
_outcome_msg: Return|Error|ContextCancelled = Unresolved
|
||||||
|
|
||||||
# on a clean exit there should be a final value
|
# on a clean exit there should be a final value
|
||||||
# delivered from the far end "callee" task, so
|
# delivered from the far end "child" task, so
|
||||||
# this value is only set on one side.
|
# this value is only set on one side.
|
||||||
# _result: Any | int = None
|
# _result: Any | int = None
|
||||||
_result: PayloadT|Unresolved = Unresolved
|
_result: PayloadT|Unresolved = Unresolved
|
||||||
|
|
||||||
# if the local "caller" task errors this value is always set
|
# if the local "parent" task errors this value is always set
|
||||||
# to the error that was captured in the
|
# to the error that was captured in the
|
||||||
# `Portal.open_context().__aexit__()` teardown block OR, in
|
# `Portal.open_context().__aexit__()` teardown block OR, in
|
||||||
# 2 special cases when an (maybe) expected remote error
|
# 2 special cases when an (maybe) expected remote error
|
||||||
|
@ -293,7 +293,7 @@ class Context:
|
||||||
# a `ContextCancelled` due to a call to `.cancel()` triggering
|
# a `ContextCancelled` due to a call to `.cancel()` triggering
|
||||||
# "graceful closure" on either side:
|
# "graceful closure" on either side:
|
||||||
# - `._runtime._invoke()` will check this flag before engaging
|
# - `._runtime._invoke()` will check this flag before engaging
|
||||||
# the crash handler REPL in such cases where the "callee"
|
# the crash handler REPL in such cases where the "child"
|
||||||
# raises the cancellation,
|
# raises the cancellation,
|
||||||
# - `.devx.debug.lock_stdio_for_peer()` will set it to `False` if
|
# - `.devx.debug.lock_stdio_for_peer()` will set it to `False` if
|
||||||
# the global tty-lock has been configured to filter out some
|
# the global tty-lock has been configured to filter out some
|
||||||
|
@ -307,8 +307,8 @@ class Context:
|
||||||
_stream_opened: bool = False
|
_stream_opened: bool = False
|
||||||
_stream: MsgStream|None = None
|
_stream: MsgStream|None = None
|
||||||
|
|
||||||
# caller of `Portal.open_context()` for
|
# the parent-task's calling-fn's frame-info, the frame above
|
||||||
# logging purposes mostly
|
# `Portal.open_context()`, for introspection/logging.
|
||||||
_caller_info: CallerInfo|None = None
|
_caller_info: CallerInfo|None = None
|
||||||
|
|
||||||
# overrun handling machinery
|
# overrun handling machinery
|
||||||
|
@ -442,25 +442,25 @@ class Context:
|
||||||
'''
|
'''
|
||||||
Records whether cancellation has been requested for this context
|
Records whether cancellation has been requested for this context
|
||||||
by a call to `.cancel()` either due to,
|
by a call to `.cancel()` either due to,
|
||||||
- either an explicit call by some local task,
|
- an explicit call by some local task,
|
||||||
- or an implicit call due to an error caught inside
|
- or an implicit call due to an error caught inside
|
||||||
the ``Portal.open_context()`` block.
|
the `Portal.open_context()` block.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
return self._cancel_called
|
return self._cancel_called
|
||||||
|
|
||||||
@cancel_called.setter
|
# XXX, to debug who frickin sets it..
|
||||||
def cancel_called(self, val: bool) -> None:
|
# @cancel_called.setter
|
||||||
'''
|
# def cancel_called(self, val: bool) -> None:
|
||||||
Set the self-cancelled request `bool` value.
|
# '''
|
||||||
|
# Set the self-cancelled request `bool` value.
|
||||||
|
|
||||||
'''
|
# '''
|
||||||
# to debug who frickin sets it..
|
|
||||||
# if val:
|
# if val:
|
||||||
# from .devx import pause_from_sync
|
# from .devx import pause_from_sync
|
||||||
# pause_from_sync()
|
# pause_from_sync()
|
||||||
|
|
||||||
self._cancel_called = val
|
# self._cancel_called = val
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def canceller(self) -> tuple[str, str]|None:
|
def canceller(self) -> tuple[str, str]|None:
|
||||||
|
@ -529,11 +529,11 @@ class Context:
|
||||||
'''
|
'''
|
||||||
Exactly the value of `self._scope.cancelled_caught`
|
Exactly the value of `self._scope.cancelled_caught`
|
||||||
(delegation) and should only be (able to be read as)
|
(delegation) and should only be (able to be read as)
|
||||||
`True` for a `.side == "caller"` ctx wherein the
|
`True` for a `.side == "parent"` ctx wherein the
|
||||||
`Portal.open_context()` block was exited due to a call to
|
`Portal.open_context()` block was exited due to a call to
|
||||||
`._scope.cancel()` - which should only ocurr in 2 cases:
|
`._scope.cancel()` - which should only ocurr in 2 cases:
|
||||||
|
|
||||||
- a caller side calls `.cancel()`, the far side cancels
|
- a parent side calls `.cancel()`, the far side cancels
|
||||||
and delivers back a `ContextCancelled` (making
|
and delivers back a `ContextCancelled` (making
|
||||||
`.cancel_acked == True`) and `._scope.cancel()` is
|
`.cancel_acked == True`) and `._scope.cancel()` is
|
||||||
called by `._maybe_cancel_and_set_remote_error()` which
|
called by `._maybe_cancel_and_set_remote_error()` which
|
||||||
|
@ -542,20 +542,20 @@ class Context:
|
||||||
=> `._scope.cancelled_caught == True` by normal `trio`
|
=> `._scope.cancelled_caught == True` by normal `trio`
|
||||||
cs semantics.
|
cs semantics.
|
||||||
|
|
||||||
- a caller side is delivered a `._remote_error:
|
- a parent side is delivered a `._remote_error:
|
||||||
RemoteActorError` via `._deliver_msg()` and a transitive
|
RemoteActorError` via `._deliver_msg()` and a transitive
|
||||||
call to `_maybe_cancel_and_set_remote_error()` calls
|
call to `_maybe_cancel_and_set_remote_error()` calls
|
||||||
`._scope.cancel()` and that cancellation eventually
|
`._scope.cancel()` and that cancellation eventually
|
||||||
results in `trio.Cancelled`(s) caught in the
|
results in `trio.Cancelled`(s) caught in the
|
||||||
`.open_context()` handling around the @acm's `yield`.
|
`.open_context()` handling around the @acm's `yield`.
|
||||||
|
|
||||||
Only as an FYI, in the "callee" side case it can also be
|
Only as an FYI, in the "child" side case it can also be
|
||||||
set but never is readable by any task outside the RPC
|
set but never is readable by any task outside the RPC
|
||||||
machinery in `._invoke()` since,:
|
machinery in `._invoke()` since,:
|
||||||
- when a callee side calls `.cancel()`, `._scope.cancel()`
|
- when a child side calls `.cancel()`, `._scope.cancel()`
|
||||||
is called immediately and handled specially inside
|
is called immediately and handled specially inside
|
||||||
`._invoke()` to raise a `ContextCancelled` which is then
|
`._invoke()` to raise a `ContextCancelled` which is then
|
||||||
sent to the caller side.
|
sent to the parent side.
|
||||||
|
|
||||||
However, `._scope.cancelled_caught` can NEVER be
|
However, `._scope.cancelled_caught` can NEVER be
|
||||||
accessed/read as `True` by any RPC invoked task since it
|
accessed/read as `True` by any RPC invoked task since it
|
||||||
|
@ -635,6 +635,71 @@ class Context:
|
||||||
'''
|
'''
|
||||||
await self.chan.send(Stop(cid=self.cid))
|
await self.chan.send(Stop(cid=self.cid))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def parent_task(self) -> trio.Task:
|
||||||
|
'''
|
||||||
|
This IPC context's "owning task" which is a `trio.Task`
|
||||||
|
on one of the "sides" of the IPC.
|
||||||
|
|
||||||
|
Note that the "parent_" prefix here refers to the local
|
||||||
|
`trio` task tree using the same interface as
|
||||||
|
`trio.Nursery.parent_task` whereas for IPC contexts,
|
||||||
|
a different cross-actor task hierarchy exists:
|
||||||
|
|
||||||
|
- a "parent"-side which originally entered
|
||||||
|
`Portal.open_context()`,
|
||||||
|
|
||||||
|
- the "child"-side which was spawned and scheduled to invoke
|
||||||
|
a function decorated with `@tractor.context`.
|
||||||
|
|
||||||
|
This task is thus a handle to mem-domain-distinct/per-process
|
||||||
|
`Nursery.parent_task` depending on in which of the above
|
||||||
|
"sides" this context exists.
|
||||||
|
|
||||||
|
'''
|
||||||
|
return self._task
|
||||||
|
|
||||||
|
def _is_blocked_on_rx_chan(self) -> bool:
|
||||||
|
'''
|
||||||
|
Predicate to indicate whether the owner `._task: trio.Task` is
|
||||||
|
currently blocked (by `.receive()`-ing) on its underlying RPC
|
||||||
|
feeder `._rx_chan`.
|
||||||
|
|
||||||
|
This knowledge is highly useful when handling so called
|
||||||
|
"out-of-band" (OoB) cancellation conditions where a peer
|
||||||
|
actor's task transmitted some remote error/cancel-msg and we
|
||||||
|
must know whether to signal-via-cancel currently executing
|
||||||
|
"user-code" (user defined code embedded in `ctx._scope`) or
|
||||||
|
simply to forward the IPC-msg-as-error **without calling**
|
||||||
|
`._scope.cancel()`.
|
||||||
|
|
||||||
|
In the latter case it is presumed that if the owner task is
|
||||||
|
blocking for the next IPC msg, it will eventually receive,
|
||||||
|
process and raise the equivalent local error **without**
|
||||||
|
requiring `._scope.cancel()` to be explicitly called by the
|
||||||
|
*delivering OoB RPC-task* (via `_deliver_msg()`).
|
||||||
|
|
||||||
|
'''
|
||||||
|
# NOTE, see the mem-chan meth-impls for *why* this
|
||||||
|
# logic works,
|
||||||
|
# `trio._channel.MemoryReceiveChannel.receive[_nowait]()`
|
||||||
|
#
|
||||||
|
# XXX realize that this is NOT an
|
||||||
|
# official/will-be-loudly-deprecated API:
|
||||||
|
# - https://trio.readthedocs.io/en/stable/reference-lowlevel.html#trio.lowlevel.Task.custom_sleep_data
|
||||||
|
# |_https://trio.readthedocs.io/en/stable/reference-lowlevel.html#trio.lowlevel.wait_task_rescheduled
|
||||||
|
#
|
||||||
|
# orig repo intro in the mem-chan change over patch:
|
||||||
|
# - https://github.com/python-trio/trio/pull/586#issuecomment-414039117
|
||||||
|
# |_https://github.com/python-trio/trio/pull/616
|
||||||
|
# |_https://github.com/njsmith/trio/commit/98c38cef6f62e731bf8c7190e8756976bface8f0
|
||||||
|
#
|
||||||
|
return (
|
||||||
|
self._task.custom_sleep_data
|
||||||
|
is
|
||||||
|
self._rx_chan
|
||||||
|
)
|
||||||
|
|
||||||
def _maybe_cancel_and_set_remote_error(
|
def _maybe_cancel_and_set_remote_error(
|
||||||
self,
|
self,
|
||||||
error: BaseException,
|
error: BaseException,
|
||||||
|
@ -666,7 +731,7 @@ class Context:
|
||||||
when called/closed by actor local task(s).
|
when called/closed by actor local task(s).
|
||||||
|
|
||||||
NOTEs:
|
NOTEs:
|
||||||
- It is expected that the caller has previously unwrapped
|
- It is expected that the parent has previously unwrapped
|
||||||
the remote error using a call to `unpack_error()` and
|
the remote error using a call to `unpack_error()` and
|
||||||
provides that output exception value as the input
|
provides that output exception value as the input
|
||||||
`error` argument *here*.
|
`error` argument *here*.
|
||||||
|
@ -676,7 +741,7 @@ class Context:
|
||||||
`Portal.open_context()` (ideally) we want to interrupt
|
`Portal.open_context()` (ideally) we want to interrupt
|
||||||
any ongoing local tasks operating within that
|
any ongoing local tasks operating within that
|
||||||
`Context`'s cancel-scope so as to be notified ASAP of
|
`Context`'s cancel-scope so as to be notified ASAP of
|
||||||
the remote error and engage any caller handling (eg.
|
the remote error and engage any parent handling (eg.
|
||||||
for cross-process task supervision).
|
for cross-process task supervision).
|
||||||
|
|
||||||
- In some cases we may want to raise the remote error
|
- In some cases we may want to raise the remote error
|
||||||
|
@ -787,13 +852,27 @@ class Context:
|
||||||
if self._canceller is None:
|
if self._canceller is None:
|
||||||
log.error('Ctx has no canceller set!?')
|
log.error('Ctx has no canceller set!?')
|
||||||
|
|
||||||
|
cs: trio.CancelScope = self._scope
|
||||||
|
|
||||||
|
# ?TODO? see comment @ .start_remote_task()`
|
||||||
|
#
|
||||||
|
# if not cs:
|
||||||
|
# from .devx import mk_pdb
|
||||||
|
# mk_pdb().set_trace()
|
||||||
|
# raise RuntimeError(
|
||||||
|
# f'IPC ctx was not be opened prior to remote error delivery !?\n'
|
||||||
|
# f'{self}\n'
|
||||||
|
# f'\n'
|
||||||
|
# f'`Portal.open_context()` must be entered (somewhere) beforehand!\n'
|
||||||
|
# )
|
||||||
|
|
||||||
# Cancel the local `._scope`, catch that
|
# Cancel the local `._scope`, catch that
|
||||||
# `._scope.cancelled_caught` and re-raise any remote error
|
# `._scope.cancelled_caught` and re-raise any remote error
|
||||||
# once exiting (or manually calling `.wait_for_result()`) the
|
# once exiting (or manually calling `.wait_for_result()`) the
|
||||||
# `.open_context()` block.
|
# `.open_context()` block.
|
||||||
cs: trio.CancelScope = self._scope
|
|
||||||
if (
|
if (
|
||||||
cs
|
cs
|
||||||
|
and not cs.cancel_called
|
||||||
|
|
||||||
# XXX this is an expected cancel request response
|
# XXX this is an expected cancel request response
|
||||||
# message and we **don't need to raise it** in the
|
# message and we **don't need to raise it** in the
|
||||||
|
@ -802,8 +881,7 @@ class Context:
|
||||||
# if `._cancel_called` then `.cancel_acked and .cancel_called`
|
# if `._cancel_called` then `.cancel_acked and .cancel_called`
|
||||||
# always should be set.
|
# always should be set.
|
||||||
and not self._is_self_cancelled()
|
and not self._is_self_cancelled()
|
||||||
and not cs.cancel_called
|
# and not cs.cancelled_caught
|
||||||
and not cs.cancelled_caught
|
|
||||||
):
|
):
|
||||||
if (
|
if (
|
||||||
msgerr
|
msgerr
|
||||||
|
@ -814,7 +892,7 @@ class Context:
|
||||||
not self._cancel_on_msgerr
|
not self._cancel_on_msgerr
|
||||||
):
|
):
|
||||||
message: str = (
|
message: str = (
|
||||||
'NOT Cancelling `Context._scope` since,\n'
|
f'NOT Cancelling `Context._scope` since,\n'
|
||||||
f'Context._cancel_on_msgerr = {self._cancel_on_msgerr}\n\n'
|
f'Context._cancel_on_msgerr = {self._cancel_on_msgerr}\n\n'
|
||||||
f'AND we got a msg-type-error!\n'
|
f'AND we got a msg-type-error!\n'
|
||||||
f'{error}\n'
|
f'{error}\n'
|
||||||
|
@ -824,13 +902,43 @@ class Context:
|
||||||
# `trio.Cancelled` subtype here ;)
|
# `trio.Cancelled` subtype here ;)
|
||||||
# https://github.com/goodboy/tractor/issues/368
|
# https://github.com/goodboy/tractor/issues/368
|
||||||
message: str = 'Cancelling `Context._scope` !\n\n'
|
message: str = 'Cancelling `Context._scope` !\n\n'
|
||||||
# from .devx import pause_from_sync
|
cs.cancel()
|
||||||
# pause_from_sync()
|
|
||||||
self._scope.cancel()
|
# TODO, explicit condition for OoB (self-)cancellation?
|
||||||
else:
|
# - we called `Portal.cancel_actor()` from this actor
|
||||||
message: str = 'NOT cancelling `Context._scope` !\n\n'
|
# and the peer ctx task delivered ctxc due to it.
|
||||||
|
# - currently `self._is_self_cancelled()` will be true
|
||||||
|
# since the ctxc.canceller check will match us even though it
|
||||||
|
# wasn't from this ctx specifically!
|
||||||
|
elif (
|
||||||
|
cs
|
||||||
|
and self._is_self_cancelled()
|
||||||
|
and not cs.cancel_called
|
||||||
|
):
|
||||||
|
message: str = (
|
||||||
|
'Cancelling `ctx._scope` due to OoB self-cancel ?!\n'
|
||||||
|
'\n'
|
||||||
|
)
|
||||||
# from .devx import mk_pdb
|
# from .devx import mk_pdb
|
||||||
# mk_pdb().set_trace()
|
# mk_pdb().set_trace()
|
||||||
|
# TODO XXX, required to fix timeout failure in
|
||||||
|
# `test_cancelled_lockacquire_in_ipctx_not_unmaskeed`
|
||||||
|
#
|
||||||
|
|
||||||
|
# XXX NOTE XXX, this is SUPER SUBTLE!
|
||||||
|
# we only want to cancel our embedded `._scope`
|
||||||
|
# if the ctx's current/using task is NOT blocked
|
||||||
|
# on `._rx_chan.receive()` and on some other
|
||||||
|
# `trio`-checkpoint since in the former case
|
||||||
|
# any `._remote_error` will be relayed through
|
||||||
|
# the rx-chan and appropriately raised by the owning
|
||||||
|
# `._task` directly. IF the owner task is however
|
||||||
|
# blocking elsewhere we need to interrupt it **now**.
|
||||||
|
if not self._is_blocked_on_rx_chan():
|
||||||
|
cs.cancel()
|
||||||
|
else:
|
||||||
|
# rx_stats = self._rx_chan.statistics()
|
||||||
|
message: str = 'NOT cancelling `Context._scope` !\n\n'
|
||||||
|
|
||||||
fmt_str: str = 'No `self._scope: CancelScope` was set/used ?\n'
|
fmt_str: str = 'No `self._scope: CancelScope` was set/used ?\n'
|
||||||
if (
|
if (
|
||||||
|
@ -854,6 +962,7 @@ class Context:
|
||||||
+
|
+
|
||||||
cs_fmt
|
cs_fmt
|
||||||
)
|
)
|
||||||
|
|
||||||
log.cancel(
|
log.cancel(
|
||||||
message
|
message
|
||||||
+
|
+
|
||||||
|
@ -886,6 +995,11 @@ class Context:
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def repr_caller(self) -> str:
|
def repr_caller(self) -> str:
|
||||||
|
'''
|
||||||
|
Render a "namespace-path" style representation of the calling
|
||||||
|
task-fn.
|
||||||
|
|
||||||
|
'''
|
||||||
ci: CallerInfo|None = self._caller_info
|
ci: CallerInfo|None = self._caller_info
|
||||||
if ci:
|
if ci:
|
||||||
return (
|
return (
|
||||||
|
@ -899,7 +1013,7 @@ class Context:
|
||||||
def repr_api(self) -> str:
|
def repr_api(self) -> str:
|
||||||
return 'Portal.open_context()'
|
return 'Portal.open_context()'
|
||||||
|
|
||||||
# TODO: use `.dev._frame_stack` scanning to find caller!
|
# TODO: use `.dev._frame_stack` scanning to find caller fn!
|
||||||
# ci: CallerInfo|None = self._caller_info
|
# ci: CallerInfo|None = self._caller_info
|
||||||
# if ci:
|
# if ci:
|
||||||
# return (
|
# return (
|
||||||
|
@ -934,15 +1048,16 @@ class Context:
|
||||||
=> That is, an IPC `Context` (this) **does not**
|
=> That is, an IPC `Context` (this) **does not**
|
||||||
have the same semantics as a `trio.CancelScope`.
|
have the same semantics as a `trio.CancelScope`.
|
||||||
|
|
||||||
If the caller (who entered the `Portal.open_context()`)
|
If the parent (who entered the `Portal.open_context()`)
|
||||||
desires that the internal block's cancel-scope be
|
desires that the internal block's cancel-scope be
|
||||||
cancelled it should open its own `trio.CancelScope` and
|
cancelled it should open its own `trio.CancelScope` and
|
||||||
manage it as needed.
|
manage it as needed.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
side: str = self.side
|
side: str = self.side
|
||||||
# XXX for debug via the `@.setter`
|
self._cancel_called = True
|
||||||
self.cancel_called = True
|
# ^ XXX for debug via the `@.setter`
|
||||||
|
# self.cancel_called = True
|
||||||
|
|
||||||
header: str = (
|
header: str = (
|
||||||
f'Cancelling ctx from {side!r}-side\n'
|
f'Cancelling ctx from {side!r}-side\n'
|
||||||
|
@ -1006,7 +1121,6 @@ class Context:
|
||||||
else:
|
else:
|
||||||
log.cancel(
|
log.cancel(
|
||||||
f'Timed out on cancel request of remote task?\n'
|
f'Timed out on cancel request of remote task?\n'
|
||||||
f'\n'
|
|
||||||
f'{reminfo}'
|
f'{reminfo}'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -1017,7 +1131,7 @@ class Context:
|
||||||
# `_invoke()` RPC task.
|
# `_invoke()` RPC task.
|
||||||
#
|
#
|
||||||
# NOTE: on this side we ALWAYS cancel the local scope
|
# NOTE: on this side we ALWAYS cancel the local scope
|
||||||
# since the caller expects a `ContextCancelled` to be sent
|
# since the parent expects a `ContextCancelled` to be sent
|
||||||
# from `._runtime._invoke()` back to the other side. The
|
# from `._runtime._invoke()` back to the other side. The
|
||||||
# logic for catching the result of the below
|
# logic for catching the result of the below
|
||||||
# `._scope.cancel()` is inside the `._runtime._invoke()`
|
# `._scope.cancel()` is inside the `._runtime._invoke()`
|
||||||
|
@ -1190,8 +1304,8 @@ class Context:
|
||||||
|
|
||||||
) -> Any|Exception:
|
) -> Any|Exception:
|
||||||
'''
|
'''
|
||||||
From some (caller) side task, wait for and return the final
|
From some (parent) side task, wait for and return the final
|
||||||
result from the remote (callee) side's task.
|
result from the remote (child) side's task.
|
||||||
|
|
||||||
This provides a mechanism for one task running in some actor to wait
|
This provides a mechanism for one task running in some actor to wait
|
||||||
on another task at the other side, in some other actor, to terminate.
|
on another task at the other side, in some other actor, to terminate.
|
||||||
|
@ -1487,6 +1601,12 @@ class Context:
|
||||||
):
|
):
|
||||||
status = 'peer-cancelled'
|
status = 'peer-cancelled'
|
||||||
|
|
||||||
|
case (
|
||||||
|
Unresolved,
|
||||||
|
trio.Cancelled(), # any error-type
|
||||||
|
) if self.canceller:
|
||||||
|
status = 'actor-cancelled'
|
||||||
|
|
||||||
# (remote) error condition
|
# (remote) error condition
|
||||||
case (
|
case (
|
||||||
Unresolved,
|
Unresolved,
|
||||||
|
@ -1600,7 +1720,7 @@ class Context:
|
||||||
raise err
|
raise err
|
||||||
|
|
||||||
# TODO: maybe a flag to by-pass encode op if already done
|
# TODO: maybe a flag to by-pass encode op if already done
|
||||||
# here in caller?
|
# here in parent?
|
||||||
await self.chan.send(started_msg)
|
await self.chan.send(started_msg)
|
||||||
|
|
||||||
# set msg-related internal runtime-state
|
# set msg-related internal runtime-state
|
||||||
|
@ -1676,7 +1796,7 @@ class Context:
|
||||||
|
|
||||||
XXX RULES XXX
|
XXX RULES XXX
|
||||||
------ - ------
|
------ - ------
|
||||||
- NEVER raise remote errors from this method; a runtime task caller.
|
- NEVER raise remote errors from this method; a calling runtime-task.
|
||||||
An error "delivered" to a ctx should always be raised by
|
An error "delivered" to a ctx should always be raised by
|
||||||
the corresponding local task operating on the
|
the corresponding local task operating on the
|
||||||
`Portal`/`Context` APIs.
|
`Portal`/`Context` APIs.
|
||||||
|
@ -1752,7 +1872,7 @@ class Context:
|
||||||
|
|
||||||
else:
|
else:
|
||||||
report = (
|
report = (
|
||||||
'Queueing OVERRUN msg on caller task:\n\n'
|
'Queueing OVERRUN msg on parent task:\n\n'
|
||||||
+ report
|
+ report
|
||||||
)
|
)
|
||||||
log.debug(report)
|
log.debug(report)
|
||||||
|
@ -1948,12 +2068,12 @@ async def open_context_from_portal(
|
||||||
IPC protocol.
|
IPC protocol.
|
||||||
|
|
||||||
The yielded `tuple` is a pair delivering a `tractor.Context`
|
The yielded `tuple` is a pair delivering a `tractor.Context`
|
||||||
and any first value "sent" by the "callee" task via a call
|
and any first value "sent" by the "child" task via a call
|
||||||
to `Context.started(<value: Any>)`; this side of the
|
to `Context.started(<value: Any>)`; this side of the
|
||||||
context does not unblock until the "callee" task calls
|
context does not unblock until the "child" task calls
|
||||||
`.started()` in similar style to `trio.Nursery.start()`.
|
`.started()` in similar style to `trio.Nursery.start()`.
|
||||||
When the "callee" (side that is "called"/started by a call
|
When the "child" (side that is "called"/started by a call
|
||||||
to *this* method) returns, the caller side (this) unblocks
|
to *this* method) returns, the parent side (this) unblocks
|
||||||
and any final value delivered from the other end can be
|
and any final value delivered from the other end can be
|
||||||
retrieved using the `Contex.wait_for_result()` api.
|
retrieved using the `Contex.wait_for_result()` api.
|
||||||
|
|
||||||
|
@ -1966,7 +2086,7 @@ async def open_context_from_portal(
|
||||||
__tracebackhide__: bool = hide_tb
|
__tracebackhide__: bool = hide_tb
|
||||||
|
|
||||||
# denote this frame as a "runtime frame" for stack
|
# denote this frame as a "runtime frame" for stack
|
||||||
# introspection where we report the caller code in logging
|
# introspection where we report the parent code in logging
|
||||||
# and error message content.
|
# and error message content.
|
||||||
# NOTE: 2 bc of the wrapping `@acm`
|
# NOTE: 2 bc of the wrapping `@acm`
|
||||||
__runtimeframe__: int = 2 # noqa
|
__runtimeframe__: int = 2 # noqa
|
||||||
|
@ -2001,6 +2121,9 @@ async def open_context_from_portal(
|
||||||
f'|_{portal.actor}\n'
|
f'|_{portal.actor}\n'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# ?TODO? could we move this to inside the `tn` block?
|
||||||
|
# -> would allow doing `ctx.parent_task = tn.parent_task` ?
|
||||||
|
# -> would allow a `if not ._scope: => raise RTE` ?
|
||||||
ctx: Context = await portal.actor.start_remote_task(
|
ctx: Context = await portal.actor.start_remote_task(
|
||||||
portal.channel,
|
portal.channel,
|
||||||
nsf=nsf,
|
nsf=nsf,
|
||||||
|
@ -2025,8 +2148,9 @@ async def open_context_from_portal(
|
||||||
# placeholder for any exception raised in the runtime
|
# placeholder for any exception raised in the runtime
|
||||||
# or by user tasks which cause this context's closure.
|
# or by user tasks which cause this context's closure.
|
||||||
scope_err: BaseException|None = None
|
scope_err: BaseException|None = None
|
||||||
ctxc_from_callee: ContextCancelled|None = None
|
ctxc_from_child: ContextCancelled|None = None
|
||||||
try:
|
try:
|
||||||
|
# from .devx import pause
|
||||||
async with (
|
async with (
|
||||||
collapse_eg(),
|
collapse_eg(),
|
||||||
trio.open_nursery() as tn,
|
trio.open_nursery() as tn,
|
||||||
|
@ -2049,6 +2173,10 @@ async def open_context_from_portal(
|
||||||
# the dialog, the `Error` msg should be raised from the `msg`
|
# the dialog, the `Error` msg should be raised from the `msg`
|
||||||
# handling block below.
|
# handling block below.
|
||||||
try:
|
try:
|
||||||
|
log.runtime(
|
||||||
|
f'IPC ctx parent waiting on Started msg..\n'
|
||||||
|
f'ctx.cid: {ctx.cid!r}\n'
|
||||||
|
)
|
||||||
started_msg, first = await ctx._pld_rx.recv_msg(
|
started_msg, first = await ctx._pld_rx.recv_msg(
|
||||||
ipc=ctx,
|
ipc=ctx,
|
||||||
expect_msg=Started,
|
expect_msg=Started,
|
||||||
|
@ -2057,16 +2185,16 @@ async def open_context_from_portal(
|
||||||
)
|
)
|
||||||
except trio.Cancelled as taskc:
|
except trio.Cancelled as taskc:
|
||||||
ctx_cs: trio.CancelScope = ctx._scope
|
ctx_cs: trio.CancelScope = ctx._scope
|
||||||
|
log.cancel(
|
||||||
|
f'IPC ctx was cancelled during "child" task sync due to\n\n'
|
||||||
|
f'.cid: {ctx.cid!r}\n'
|
||||||
|
f'.maybe_error: {ctx.maybe_error!r}\n'
|
||||||
|
)
|
||||||
|
# await pause(shield=True)
|
||||||
|
|
||||||
if not ctx_cs.cancel_called:
|
if not ctx_cs.cancel_called:
|
||||||
raise
|
raise
|
||||||
|
|
||||||
# from .devx import pause
|
|
||||||
# await pause(shield=True)
|
|
||||||
|
|
||||||
log.cancel(
|
|
||||||
'IPC ctx was cancelled during "child" task sync due to\n\n'
|
|
||||||
f'{ctx.maybe_error}\n'
|
|
||||||
)
|
|
||||||
# OW if the ctx's scope was cancelled manually,
|
# OW if the ctx's scope was cancelled manually,
|
||||||
# likely the `Context` was cancelled via a call to
|
# likely the `Context` was cancelled via a call to
|
||||||
# `._maybe_cancel_and_set_remote_error()` so ensure
|
# `._maybe_cancel_and_set_remote_error()` so ensure
|
||||||
|
@ -2104,7 +2232,7 @@ async def open_context_from_portal(
|
||||||
# that we can re-use it around the `yield` ^ here
|
# that we can re-use it around the `yield` ^ here
|
||||||
# or vice versa?
|
# or vice versa?
|
||||||
#
|
#
|
||||||
# maybe TODO NOTE: between the caller exiting and
|
# maybe TODO NOTE: between the parent exiting and
|
||||||
# arriving here the far end may have sent a ctxc-msg or
|
# arriving here the far end may have sent a ctxc-msg or
|
||||||
# other error, so the quetion is whether we should check
|
# other error, so the quetion is whether we should check
|
||||||
# for it here immediately and maybe raise so as to engage
|
# for it here immediately and maybe raise so as to engage
|
||||||
|
@ -2170,16 +2298,16 @@ async def open_context_from_portal(
|
||||||
# request in which case we DO let the error bubble to the
|
# request in which case we DO let the error bubble to the
|
||||||
# opener.
|
# opener.
|
||||||
#
|
#
|
||||||
# 2-THIS "caller" task somewhere invoked `Context.cancel()`
|
# 2-THIS "parent" task somewhere invoked `Context.cancel()`
|
||||||
# and received a `ContextCanclled` from the "callee"
|
# and received a `ContextCanclled` from the "child"
|
||||||
# task, in which case we mask the `ContextCancelled` from
|
# task, in which case we mask the `ContextCancelled` from
|
||||||
# bubbling to this "caller" (much like how `trio.Nursery`
|
# bubbling to this "parent" (much like how `trio.Nursery`
|
||||||
# swallows any `trio.Cancelled` bubbled by a call to
|
# swallows any `trio.Cancelled` bubbled by a call to
|
||||||
# `Nursery.cancel_scope.cancel()`)
|
# `Nursery.cancel_scope.cancel()`)
|
||||||
except ContextCancelled as ctxc:
|
except ContextCancelled as ctxc:
|
||||||
scope_err = ctxc
|
scope_err = ctxc
|
||||||
ctx._local_error: BaseException = scope_err
|
ctx._local_error: BaseException = scope_err
|
||||||
ctxc_from_callee = ctxc
|
ctxc_from_child = ctxc
|
||||||
|
|
||||||
# XXX TODO XXX: FIX THIS debug_mode BUGGGG!!!
|
# XXX TODO XXX: FIX THIS debug_mode BUGGGG!!!
|
||||||
# using this code and then resuming the REPL will
|
# using this code and then resuming the REPL will
|
||||||
|
@ -2216,11 +2344,11 @@ async def open_context_from_portal(
|
||||||
# the above `._scope` can be cancelled due to:
|
# the above `._scope` can be cancelled due to:
|
||||||
# 1. an explicit self cancel via `Context.cancel()` or
|
# 1. an explicit self cancel via `Context.cancel()` or
|
||||||
# `Actor.cancel()`,
|
# `Actor.cancel()`,
|
||||||
# 2. any "callee"-side remote error, possibly also a cancellation
|
# 2. any "child"-side remote error, possibly also a cancellation
|
||||||
# request by some peer,
|
# request by some peer,
|
||||||
# 3. any "caller" (aka THIS scope's) local error raised in the above `yield`
|
# 3. any "parent" (aka THIS scope's) local error raised in the above `yield`
|
||||||
except (
|
except (
|
||||||
# CASE 3: standard local error in this caller/yieldee
|
# CASE 3: standard local error in this parent/yieldee
|
||||||
Exception,
|
Exception,
|
||||||
|
|
||||||
# CASES 1 & 2: can manifest as a `ctx._scope_nursery`
|
# CASES 1 & 2: can manifest as a `ctx._scope_nursery`
|
||||||
|
@ -2234,9 +2362,9 @@ async def open_context_from_portal(
|
||||||
# any `Context._maybe_raise_remote_err()` call.
|
# any `Context._maybe_raise_remote_err()` call.
|
||||||
#
|
#
|
||||||
# 2.-`BaseExceptionGroup[ContextCancelled | RemoteActorError]`
|
# 2.-`BaseExceptionGroup[ContextCancelled | RemoteActorError]`
|
||||||
# from any error delivered from the "callee" side
|
# from any error delivered from the "child" side
|
||||||
# AND a group-exc is only raised if there was > 1
|
# AND a group-exc is only raised if there was > 1
|
||||||
# tasks started *here* in the "caller" / opener
|
# tasks started *here* in the "parent" / opener
|
||||||
# block. If any one of those tasks calls
|
# block. If any one of those tasks calls
|
||||||
# `.wait_for_result()` or `MsgStream.receive()`
|
# `.wait_for_result()` or `MsgStream.receive()`
|
||||||
# `._maybe_raise_remote_err()` will be transitively
|
# `._maybe_raise_remote_err()` will be transitively
|
||||||
|
@ -2249,8 +2377,8 @@ async def open_context_from_portal(
|
||||||
trio.Cancelled, # NOTE: NOT from inside the ctx._scope
|
trio.Cancelled, # NOTE: NOT from inside the ctx._scope
|
||||||
KeyboardInterrupt,
|
KeyboardInterrupt,
|
||||||
|
|
||||||
) as caller_err:
|
) as rent_err:
|
||||||
scope_err = caller_err
|
scope_err = rent_err
|
||||||
ctx._local_error: BaseException = scope_err
|
ctx._local_error: BaseException = scope_err
|
||||||
|
|
||||||
# XXX: ALWAYS request the context to CANCEL ON any ERROR.
|
# XXX: ALWAYS request the context to CANCEL ON any ERROR.
|
||||||
|
@ -2260,15 +2388,18 @@ async def open_context_from_portal(
|
||||||
# await debug.pause()
|
# await debug.pause()
|
||||||
# log.cancel(
|
# log.cancel(
|
||||||
match scope_err:
|
match scope_err:
|
||||||
case trio.Cancelled:
|
case trio.Cancelled():
|
||||||
logmeth = log.cancel
|
logmeth = log.cancel
|
||||||
|
cause: str = 'cancelled'
|
||||||
|
|
||||||
# XXX explicitly report on any non-graceful-taskc cases
|
# XXX explicitly report on any non-graceful-taskc cases
|
||||||
case _:
|
case _:
|
||||||
|
cause: str = 'errored'
|
||||||
logmeth = log.exception
|
logmeth = log.exception
|
||||||
|
|
||||||
logmeth(
|
logmeth(
|
||||||
f'ctx {ctx.side!r}-side exited with {ctx.repr_outcome()}\n'
|
f'ctx {ctx.side!r}-side {cause!r} with,\n'
|
||||||
|
f'{ctx.repr_outcome()!r}\n'
|
||||||
)
|
)
|
||||||
|
|
||||||
if debug_mode():
|
if debug_mode():
|
||||||
|
@ -2289,10 +2420,11 @@ async def open_context_from_portal(
|
||||||
'Calling `ctx.cancel()`!\n'
|
'Calling `ctx.cancel()`!\n'
|
||||||
)
|
)
|
||||||
|
|
||||||
# we don't need to cancel the callee if it already
|
# we don't need to cancel the child if it already
|
||||||
# told us it's cancelled ;p
|
# told us it's cancelled ;p
|
||||||
if ctxc_from_callee is None:
|
if ctxc_from_child is None:
|
||||||
try:
|
try:
|
||||||
|
# await pause(shield=True)
|
||||||
await ctx.cancel()
|
await ctx.cancel()
|
||||||
except (
|
except (
|
||||||
trio.BrokenResourceError,
|
trio.BrokenResourceError,
|
||||||
|
@ -2322,8 +2454,8 @@ async def open_context_from_portal(
|
||||||
# via a call to
|
# via a call to
|
||||||
# `Context._maybe_cancel_and_set_remote_error()`.
|
# `Context._maybe_cancel_and_set_remote_error()`.
|
||||||
# As per `Context._deliver_msg()`, that error IS
|
# As per `Context._deliver_msg()`, that error IS
|
||||||
# ALWAYS SET any time "callee" side fails and causes "caller
|
# ALWAYS SET any time "child" side fails and causes
|
||||||
# side" cancellation via a `ContextCancelled` here.
|
# "parent side" cancellation via a `ContextCancelled` here.
|
||||||
try:
|
try:
|
||||||
result_or_err: Exception|Any = await ctx.wait_for_result()
|
result_or_err: Exception|Any = await ctx.wait_for_result()
|
||||||
except BaseException as berr:
|
except BaseException as berr:
|
||||||
|
@ -2359,7 +2491,7 @@ async def open_context_from_portal(
|
||||||
)
|
)
|
||||||
case (None, _):
|
case (None, _):
|
||||||
log.runtime(
|
log.runtime(
|
||||||
'Context returned final result from callee task:\n'
|
'Context returned final result from child task:\n'
|
||||||
f'<= peer: {uid}\n'
|
f'<= peer: {uid}\n'
|
||||||
f' |_ {nsf}()\n\n'
|
f' |_ {nsf}()\n\n'
|
||||||
|
|
||||||
|
@ -2449,12 +2581,14 @@ async def open_context_from_portal(
|
||||||
log.cancel(
|
log.cancel(
|
||||||
f'Context cancelled by local {ctx.side!r}-side task\n'
|
f'Context cancelled by local {ctx.side!r}-side task\n'
|
||||||
f'c)>\n'
|
f'c)>\n'
|
||||||
f' |_{ctx._task}\n\n'
|
f' |_{ctx.parent_task}\n'
|
||||||
f'{repr(scope_err)}\n'
|
f' .cid={ctx.cid!r}\n'
|
||||||
|
f'\n'
|
||||||
|
f'{scope_err!r}\n'
|
||||||
)
|
)
|
||||||
|
|
||||||
# TODO: should we add a `._cancel_req_received`
|
# TODO: should we add a `._cancel_req_received`
|
||||||
# flag to determine if the callee manually called
|
# flag to determine if the child manually called
|
||||||
# `ctx.cancel()`?
|
# `ctx.cancel()`?
|
||||||
# -[ ] going to need a cid check no?
|
# -[ ] going to need a cid check no?
|
||||||
|
|
||||||
|
@ -2510,7 +2644,7 @@ def mk_context(
|
||||||
recv_chan: trio.MemoryReceiveChannel
|
recv_chan: trio.MemoryReceiveChannel
|
||||||
send_chan, recv_chan = trio.open_memory_channel(msg_buffer_size)
|
send_chan, recv_chan = trio.open_memory_channel(msg_buffer_size)
|
||||||
|
|
||||||
# TODO: only scan caller-info if log level so high!
|
# TODO: only scan parent-info if log level so high!
|
||||||
from .devx._frame_stack import find_caller_info
|
from .devx._frame_stack import find_caller_info
|
||||||
caller_info: CallerInfo|None = find_caller_info()
|
caller_info: CallerInfo|None = find_caller_info()
|
||||||
|
|
||||||
|
|
|
@ -51,7 +51,6 @@ from ._state import (
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from ._runtime import Actor
|
from ._runtime import Actor
|
||||||
from .ipc._server import IPCServer
|
|
||||||
|
|
||||||
|
|
||||||
log = get_logger(__name__)
|
log = get_logger(__name__)
|
||||||
|
@ -83,7 +82,7 @@ async def get_registry(
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# TODO: try to look pre-existing connection from
|
# TODO: try to look pre-existing connection from
|
||||||
# `IPCServer._peers` and use it instead?
|
# `Server._peers` and use it instead?
|
||||||
async with (
|
async with (
|
||||||
_connect_chan(addr) as chan,
|
_connect_chan(addr) as chan,
|
||||||
open_portal(chan) as regstr_ptl,
|
open_portal(chan) as regstr_ptl,
|
||||||
|
@ -114,18 +113,23 @@ def get_peer_by_name(
|
||||||
) -> list[Channel]|None: # at least 1
|
) -> list[Channel]|None: # at least 1
|
||||||
'''
|
'''
|
||||||
Scan for an existing connection (set) to a named actor
|
Scan for an existing connection (set) to a named actor
|
||||||
and return any channels from `IPCServer._peers: dict`.
|
and return any channels from `Server._peers: dict`.
|
||||||
|
|
||||||
This is an optimization method over querying the registrar for
|
This is an optimization method over querying the registrar for
|
||||||
the same info.
|
the same info.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
actor: Actor = current_actor()
|
actor: Actor = current_actor()
|
||||||
server: IPCServer = actor.ipc_server
|
to_scan: dict[tuple, list[Channel]] = actor.ipc_server._peers.copy()
|
||||||
to_scan: dict[tuple, list[Channel]] = server._peers.copy()
|
|
||||||
pchan: Channel|None = actor._parent_chan
|
# TODO: is this ever needed? creates a duplicate channel on actor._peers
|
||||||
if pchan:
|
# when multiple find_actor calls are made to same actor from a single ctx
|
||||||
to_scan[pchan.uid].append(pchan)
|
# which causes actor exit to hang waiting forever on
|
||||||
|
# `actor._no_more_peers.wait()` in `_runtime.async_main`
|
||||||
|
|
||||||
|
# pchan: Channel|None = actor._parent_chan
|
||||||
|
# if pchan and pchan.uid not in to_scan:
|
||||||
|
# to_scan[pchan.uid].append(pchan)
|
||||||
|
|
||||||
for aid, chans in to_scan.items():
|
for aid, chans in to_scan.items():
|
||||||
_, peer_name = aid
|
_, peer_name = aid
|
||||||
|
|
|
@ -300,7 +300,7 @@ class Portal:
|
||||||
)
|
)
|
||||||
|
|
||||||
# XXX the one spot we set it?
|
# XXX the one spot we set it?
|
||||||
self.channel._cancel_called: bool = True
|
chan._cancel_called: bool = True
|
||||||
try:
|
try:
|
||||||
# send cancel cmd - might not get response
|
# send cancel cmd - might not get response
|
||||||
# XXX: sure would be nice to make this work with
|
# XXX: sure would be nice to make this work with
|
||||||
|
|
|
@ -97,7 +97,7 @@ async def maybe_block_bp(
|
||||||
):
|
):
|
||||||
logger.info(
|
logger.info(
|
||||||
f'Found `greenback` installed @ {maybe_mod}\n'
|
f'Found `greenback` installed @ {maybe_mod}\n'
|
||||||
'Enabling `tractor.pause_from_sync()` support!\n'
|
f'Enabling `tractor.pause_from_sync()` support!\n'
|
||||||
)
|
)
|
||||||
os.environ['PYTHONBREAKPOINT'] = (
|
os.environ['PYTHONBREAKPOINT'] = (
|
||||||
'tractor.devx.debug._sync_pause_from_builtin'
|
'tractor.devx.debug._sync_pause_from_builtin'
|
||||||
|
@ -471,7 +471,7 @@ async def open_root_actor(
|
||||||
'-> Opening new registry @ '
|
'-> Opening new registry @ '
|
||||||
+
|
+
|
||||||
'\n'.join(
|
'\n'.join(
|
||||||
f'@{addr}' for addr in reg_addrs
|
f'{addr}' for addr in reg_addrs
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
logger.info(f'{report}\n')
|
logger.info(f'{report}\n')
|
||||||
|
@ -481,10 +481,11 @@ async def open_root_actor(
|
||||||
collapse_eg(),
|
collapse_eg(),
|
||||||
trio.open_nursery() as root_tn,
|
trio.open_nursery() as root_tn,
|
||||||
|
|
||||||
# XXX, finally-footgun below?
|
# ?TODO? finally-footgun below?
|
||||||
# -> see note on why shielding.
|
# -> see note on why shielding.
|
||||||
# maybe_raise_from_masking_exc(),
|
# maybe_raise_from_masking_exc(),
|
||||||
):
|
):
|
||||||
|
actor._root_tn = root_tn
|
||||||
# `_runtime.async_main()` creates an internal nursery
|
# `_runtime.async_main()` creates an internal nursery
|
||||||
# and blocks here until any underlying actor(-process)
|
# and blocks here until any underlying actor(-process)
|
||||||
# tree has terminated thereby conducting so called
|
# tree has terminated thereby conducting so called
|
||||||
|
@ -523,6 +524,11 @@ async def open_root_actor(
|
||||||
err,
|
err,
|
||||||
api_frame=inspect.currentframe(),
|
api_frame=inspect.currentframe(),
|
||||||
debug_filter=debug_filter,
|
debug_filter=debug_filter,
|
||||||
|
|
||||||
|
# XXX NOTE, required to debug root-actor
|
||||||
|
# crashes under cancellation conditions; so
|
||||||
|
# most of them!
|
||||||
|
shield=root_tn.cancel_scope.cancel_called,
|
||||||
)
|
)
|
||||||
|
|
||||||
if (
|
if (
|
||||||
|
@ -543,7 +549,7 @@ async def open_root_actor(
|
||||||
raise
|
raise
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
# NOTE: not sure if we'll ever need this but it's
|
# NOTE/TODO?, not sure if we'll ever need this but it's
|
||||||
# possibly better for even more determinism?
|
# possibly better for even more determinism?
|
||||||
# logger.cancel(
|
# logger.cancel(
|
||||||
# f'Waiting on {len(nurseries)} nurseries in root..')
|
# f'Waiting on {len(nurseries)} nurseries in root..')
|
||||||
|
@ -562,6 +568,7 @@ async def open_root_actor(
|
||||||
f'{op_nested_actor_repr}'
|
f'{op_nested_actor_repr}'
|
||||||
)
|
)
|
||||||
# XXX, THIS IS A *finally-footgun*!
|
# XXX, THIS IS A *finally-footgun*!
|
||||||
|
# (also mentioned in with-block above)
|
||||||
# -> though already shields iternally it can
|
# -> though already shields iternally it can
|
||||||
# taskc here and mask underlying errors raised in
|
# taskc here and mask underlying errors raised in
|
||||||
# the try-block above?
|
# the try-block above?
|
||||||
|
|
|
@ -384,7 +384,7 @@ async def _errors_relayed_via_ipc(
|
||||||
|
|
||||||
# RPC task bookeeping.
|
# RPC task bookeeping.
|
||||||
# since RPC tasks are scheduled inside a flat
|
# since RPC tasks are scheduled inside a flat
|
||||||
# `Actor._service_n`, we add "handles" to each such that
|
# `Actor._service_tn`, we add "handles" to each such that
|
||||||
# they can be individually ccancelled.
|
# they can be individually ccancelled.
|
||||||
finally:
|
finally:
|
||||||
|
|
||||||
|
@ -462,7 +462,7 @@ async def _invoke(
|
||||||
connected IPC channel.
|
connected IPC channel.
|
||||||
|
|
||||||
This is the core "RPC" `trio.Task` scheduling machinery used to start every
|
This is the core "RPC" `trio.Task` scheduling machinery used to start every
|
||||||
remotely invoked function, normally in `Actor._service_n: Nursery`.
|
remotely invoked function, normally in `Actor._service_tn: Nursery`.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
__tracebackhide__: bool = hide_tb
|
__tracebackhide__: bool = hide_tb
|
||||||
|
@ -642,7 +642,7 @@ async def _invoke(
|
||||||
tn: Nursery
|
tn: Nursery
|
||||||
rpc_ctx_cs: CancelScope
|
rpc_ctx_cs: CancelScope
|
||||||
async with (
|
async with (
|
||||||
collapse_eg(),
|
collapse_eg(hide_tb=False),
|
||||||
trio.open_nursery() as tn,
|
trio.open_nursery() as tn,
|
||||||
msgops.maybe_limit_plds(
|
msgops.maybe_limit_plds(
|
||||||
ctx=ctx,
|
ctx=ctx,
|
||||||
|
@ -654,8 +654,7 @@ async def _invoke(
|
||||||
# scope ensures unasking of the `await coro` below
|
# scope ensures unasking of the `await coro` below
|
||||||
# *should* never be interfered with!!
|
# *should* never be interfered with!!
|
||||||
maybe_raise_from_masking_exc(
|
maybe_raise_from_masking_exc(
|
||||||
tn=tn,
|
unmask_from=(Cancelled,),
|
||||||
unmask_from=Cancelled,
|
|
||||||
) as _mbme, # maybe boxed masked exc
|
) as _mbme, # maybe boxed masked exc
|
||||||
):
|
):
|
||||||
ctx._scope_nursery = tn
|
ctx._scope_nursery = tn
|
||||||
|
@ -823,24 +822,44 @@ async def _invoke(
|
||||||
f'after having {ctx.repr_state!r}\n'
|
f'after having {ctx.repr_state!r}\n'
|
||||||
)
|
)
|
||||||
if merr:
|
if merr:
|
||||||
|
|
||||||
logmeth: Callable = log.error
|
logmeth: Callable = log.error
|
||||||
if isinstance(merr, ContextCancelled):
|
if (
|
||||||
logmeth: Callable = log.runtime
|
# ctxc: by `Context.cancel()`
|
||||||
|
isinstance(merr, ContextCancelled)
|
||||||
|
|
||||||
if not isinstance(merr, RemoteActorError):
|
# out-of-layer cancellation, one of:
|
||||||
tb_str: str = ''.join(traceback.format_exception(merr))
|
# - actorc: by `Portal.cancel_actor()`
|
||||||
|
# - OSc: by SIGINT or `Process.signal()`
|
||||||
|
or (
|
||||||
|
isinstance(merr, trio.Cancelled)
|
||||||
|
and
|
||||||
|
ctx.canceller
|
||||||
|
)
|
||||||
|
):
|
||||||
|
logmeth: Callable = log.cancel
|
||||||
|
descr_str += (
|
||||||
|
f' with {merr!r}\n'
|
||||||
|
)
|
||||||
|
|
||||||
|
elif (
|
||||||
|
not isinstance(merr, RemoteActorError)
|
||||||
|
):
|
||||||
|
tb_str: str = ''.join(
|
||||||
|
traceback.format_exception(merr)
|
||||||
|
)
|
||||||
descr_str += (
|
descr_str += (
|
||||||
f'\n{merr!r}\n' # needed?
|
f'\n{merr!r}\n' # needed?
|
||||||
f'{tb_str}\n'
|
f'{tb_str}\n'
|
||||||
f'\n'
|
|
||||||
f'scope_error:\n'
|
|
||||||
f'{scope_err!r}\n'
|
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
descr_str += f'\n{merr!r}\n'
|
descr_str += (
|
||||||
|
f'{merr!r}\n'
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
descr_str += f'\nwith final result {ctx.outcome!r}\n'
|
descr_str += (
|
||||||
|
f'\n'
|
||||||
|
f'with final result {ctx.outcome!r}\n'
|
||||||
|
)
|
||||||
|
|
||||||
logmeth(
|
logmeth(
|
||||||
f'{message}\n'
|
f'{message}\n'
|
||||||
|
@ -916,7 +935,7 @@ async def process_messages(
|
||||||
|
|
||||||
Receive (multiplexed) per-`Channel` RPC requests as msgs from
|
Receive (multiplexed) per-`Channel` RPC requests as msgs from
|
||||||
remote processes; schedule target async funcs as local
|
remote processes; schedule target async funcs as local
|
||||||
`trio.Task`s inside the `Actor._service_n: Nursery`.
|
`trio.Task`s inside the `Actor._service_tn: Nursery`.
|
||||||
|
|
||||||
Depending on msg type, non-`cmd` (task spawning/starting)
|
Depending on msg type, non-`cmd` (task spawning/starting)
|
||||||
request payloads (eg. `started`, `yield`, `return`, `error`)
|
request payloads (eg. `started`, `yield`, `return`, `error`)
|
||||||
|
@ -941,7 +960,7 @@ async def process_messages(
|
||||||
|
|
||||||
'''
|
'''
|
||||||
actor: Actor = _state.current_actor()
|
actor: Actor = _state.current_actor()
|
||||||
assert actor._service_n # runtime state sanity
|
assert actor._service_tn # runtime state sanity
|
||||||
|
|
||||||
# TODO: once `trio` get's an "obvious way" for req/resp we
|
# TODO: once `trio` get's an "obvious way" for req/resp we
|
||||||
# should use it?
|
# should use it?
|
||||||
|
@ -1152,7 +1171,7 @@ async def process_messages(
|
||||||
start_status += '->( scheduling new task..\n'
|
start_status += '->( scheduling new task..\n'
|
||||||
log.runtime(start_status)
|
log.runtime(start_status)
|
||||||
try:
|
try:
|
||||||
ctx: Context = await actor._service_n.start(
|
ctx: Context = await actor._service_tn.start(
|
||||||
partial(
|
partial(
|
||||||
_invoke,
|
_invoke,
|
||||||
actor,
|
actor,
|
||||||
|
@ -1292,7 +1311,7 @@ async def process_messages(
|
||||||
) as err:
|
) as err:
|
||||||
|
|
||||||
if nursery_cancelled_before_task:
|
if nursery_cancelled_before_task:
|
||||||
sn: Nursery = actor._service_n
|
sn: Nursery = actor._service_tn
|
||||||
assert sn and sn.cancel_scope.cancel_called # sanity
|
assert sn and sn.cancel_scope.cancel_called # sanity
|
||||||
log.cancel(
|
log.cancel(
|
||||||
f'Service nursery cancelled before it handled {funcname}'
|
f'Service nursery cancelled before it handled {funcname}'
|
||||||
|
|
|
@ -35,6 +35,15 @@ for running all lower level spawning, supervision and msging layers:
|
||||||
SC-transitive RPC via scheduling of `trio` tasks.
|
SC-transitive RPC via scheduling of `trio` tasks.
|
||||||
- registration of newly spawned actors with the discovery sys.
|
- registration of newly spawned actors with the discovery sys.
|
||||||
|
|
||||||
|
Glossary:
|
||||||
|
--------
|
||||||
|
- tn: a `trio.Nursery` or "task nursery".
|
||||||
|
- an: an `ActorNursery` or "actor nursery".
|
||||||
|
- root: top/parent-most scope/task/process/actor (or other runtime
|
||||||
|
primitive) in a hierarchical tree.
|
||||||
|
- parent-ish: "higher-up" in the runtime-primitive hierarchy.
|
||||||
|
- child-ish: "lower-down" in the runtime-primitive hierarchy.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from contextlib import (
|
from contextlib import (
|
||||||
|
@ -76,6 +85,7 @@ from tractor.msg import (
|
||||||
)
|
)
|
||||||
from .trionics import (
|
from .trionics import (
|
||||||
collapse_eg,
|
collapse_eg,
|
||||||
|
maybe_open_nursery,
|
||||||
)
|
)
|
||||||
from .ipc import (
|
from .ipc import (
|
||||||
Channel,
|
Channel,
|
||||||
|
@ -173,10 +183,11 @@ class Actor:
|
||||||
|
|
||||||
msg_buffer_size: int = 2**6
|
msg_buffer_size: int = 2**6
|
||||||
|
|
||||||
# nursery placeholders filled in by `async_main()` after fork
|
# nursery placeholders filled in by `async_main()`,
|
||||||
_root_n: Nursery|None = None
|
# - after fork for subactors.
|
||||||
_service_n: Nursery|None = None
|
# - during boot for the root actor.
|
||||||
|
_root_tn: Nursery|None = None
|
||||||
|
_service_tn: Nursery|None = None
|
||||||
_ipc_server: _server.IPCServer|None = None
|
_ipc_server: _server.IPCServer|None = None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
|
@ -552,6 +563,14 @@ class Actor:
|
||||||
)
|
)
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
# ?TODO, factor this meth-iface into a new `.rpc` subsys primitive?
|
||||||
|
# - _get_rpc_func(),
|
||||||
|
# - _deliver_ctx_payload(),
|
||||||
|
# - get_context(),
|
||||||
|
# - start_remote_task(),
|
||||||
|
# - cancel_rpc_tasks(),
|
||||||
|
# - _cancel_task(),
|
||||||
|
#
|
||||||
def _get_rpc_func(self, ns, funcname):
|
def _get_rpc_func(self, ns, funcname):
|
||||||
'''
|
'''
|
||||||
Try to lookup and return a target RPC func from the
|
Try to lookup and return a target RPC func from the
|
||||||
|
@ -1002,12 +1021,48 @@ class Actor:
|
||||||
the RPC service nursery.
|
the RPC service nursery.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
assert self._service_n
|
actor_repr: str = _pformat.nest_from_op(
|
||||||
self._service_n.start_soon(
|
input_op='>c(',
|
||||||
|
text=self.pformat(),
|
||||||
|
nest_indent=1,
|
||||||
|
)
|
||||||
|
log.cancel(
|
||||||
|
'Actor.cancel_soon()` was called!\n'
|
||||||
|
f'>> scheduling `Actor.cancel()`\n'
|
||||||
|
f'{actor_repr}'
|
||||||
|
)
|
||||||
|
assert self._service_tn
|
||||||
|
self._service_tn.start_soon(
|
||||||
self.cancel,
|
self.cancel,
|
||||||
None, # self cancel all rpc tasks
|
None, # self cancel all rpc tasks
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# schedule a "canceller task" in the `._root_tn` once the
|
||||||
|
# `._service_tn` is fully shutdown; task waits for child-ish
|
||||||
|
# scopes to fully exit then finally cancels its parent,
|
||||||
|
# root-most, scope.
|
||||||
|
async def cancel_root_tn_after_services():
|
||||||
|
log.runtime(
|
||||||
|
'Waiting on service-tn to cancel..\n'
|
||||||
|
f'c>)\n'
|
||||||
|
f'|_{self._service_tn.cancel_scope!r}\n'
|
||||||
|
)
|
||||||
|
await self._cancel_complete.wait()
|
||||||
|
log.cancel(
|
||||||
|
f'`._service_tn` cancelled\n'
|
||||||
|
f'>c)\n'
|
||||||
|
f'|_{self._service_tn.cancel_scope!r}\n'
|
||||||
|
f'\n'
|
||||||
|
f'>> cancelling `._root_tn`\n'
|
||||||
|
f'c>(\n'
|
||||||
|
f' |_{self._root_tn.cancel_scope!r}\n'
|
||||||
|
)
|
||||||
|
self._root_tn.cancel_scope.cancel()
|
||||||
|
|
||||||
|
self._root_tn.start_soon(
|
||||||
|
cancel_root_tn_after_services
|
||||||
|
)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def cancel_complete(self) -> bool:
|
def cancel_complete(self) -> bool:
|
||||||
return self._cancel_complete.is_set()
|
return self._cancel_complete.is_set()
|
||||||
|
@ -1112,21 +1167,13 @@ class Actor:
|
||||||
await ipc_server.wait_for_shutdown()
|
await ipc_server.wait_for_shutdown()
|
||||||
|
|
||||||
# cancel all rpc tasks permanently
|
# cancel all rpc tasks permanently
|
||||||
if self._service_n:
|
if self._service_tn:
|
||||||
self._service_n.cancel_scope.cancel()
|
self._service_tn.cancel_scope.cancel()
|
||||||
|
|
||||||
log_meth(msg)
|
log_meth(msg)
|
||||||
self._cancel_complete.set()
|
self._cancel_complete.set()
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# XXX: hard kill logic if needed?
|
|
||||||
# def _hard_mofo_kill(self):
|
|
||||||
# # If we're the root actor or zombied kill everything
|
|
||||||
# if self._parent_chan is None: # TODO: more robust check
|
|
||||||
# root = trio.lowlevel.current_root_task()
|
|
||||||
# for n in root.child_nurseries:
|
|
||||||
# n.cancel_scope.cancel()
|
|
||||||
|
|
||||||
async def _cancel_task(
|
async def _cancel_task(
|
||||||
self,
|
self,
|
||||||
cid: str,
|
cid: str,
|
||||||
|
@ -1258,7 +1305,7 @@ class Actor:
|
||||||
'''
|
'''
|
||||||
Cancel all ongoing RPC tasks owned/spawned for a given
|
Cancel all ongoing RPC tasks owned/spawned for a given
|
||||||
`parent_chan: Channel` or simply all tasks (inside
|
`parent_chan: Channel` or simply all tasks (inside
|
||||||
`._service_n`) when `parent_chan=None`.
|
`._service_tn`) when `parent_chan=None`.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
tasks: dict = self._rpc_tasks
|
tasks: dict = self._rpc_tasks
|
||||||
|
@ -1361,25 +1408,13 @@ class Actor:
|
||||||
'''
|
'''
|
||||||
return self.accept_addrs[0]
|
return self.accept_addrs[0]
|
||||||
|
|
||||||
def get_parent(self) -> Portal:
|
# TODO, this should delegate ONLY to the
|
||||||
'''
|
# `._spawn_spec._runtime_vars: dict` / `._state` APIs?
|
||||||
Return a `Portal` to our parent.
|
#
|
||||||
|
# XXX, AH RIGHT that's why..
|
||||||
'''
|
# it's bc we pass this as a CLI flag to the child.py precisely
|
||||||
assert self._parent_chan, "No parent channel for this actor?"
|
# bc we need the bootstrapping pre `async_main()`.. but maybe
|
||||||
return Portal(self._parent_chan)
|
# keep this as an impl deat and not part of the pub iface impl?
|
||||||
|
|
||||||
def get_chans(
|
|
||||||
self,
|
|
||||||
uid: tuple[str, str],
|
|
||||||
|
|
||||||
) -> list[Channel]:
|
|
||||||
'''
|
|
||||||
Return all IPC channels to the actor with provided `uid`.
|
|
||||||
|
|
||||||
'''
|
|
||||||
return self._ipc_server._peers[uid]
|
|
||||||
|
|
||||||
def is_infected_aio(self) -> bool:
|
def is_infected_aio(self) -> bool:
|
||||||
'''
|
'''
|
||||||
If `True`, this actor is running `trio` in guest mode on
|
If `True`, this actor is running `trio` in guest mode on
|
||||||
|
@ -1390,6 +1425,23 @@ class Actor:
|
||||||
'''
|
'''
|
||||||
return self._infected_aio
|
return self._infected_aio
|
||||||
|
|
||||||
|
# ?TODO, is this the right type for this method?
|
||||||
|
def get_parent(self) -> Portal:
|
||||||
|
'''
|
||||||
|
Return a `Portal` to our parent.
|
||||||
|
|
||||||
|
'''
|
||||||
|
assert self._parent_chan, "No parent channel for this actor?"
|
||||||
|
return Portal(self._parent_chan)
|
||||||
|
|
||||||
|
# XXX: hard kill logic if needed?
|
||||||
|
# def _hard_mofo_kill(self):
|
||||||
|
# # If we're the root actor or zombied kill everything
|
||||||
|
# if self._parent_chan is None: # TODO: more robust check
|
||||||
|
# root = trio.lowlevel.current_root_task()
|
||||||
|
# for n in root.child_nurseries:
|
||||||
|
# n.cancel_scope.cancel()
|
||||||
|
|
||||||
|
|
||||||
async def async_main(
|
async def async_main(
|
||||||
actor: Actor,
|
actor: Actor,
|
||||||
|
@ -1465,46 +1517,55 @@ async def async_main(
|
||||||
accept_addrs.append(addr.unwrap())
|
accept_addrs.append(addr.unwrap())
|
||||||
|
|
||||||
assert accept_addrs
|
assert accept_addrs
|
||||||
# The "root" nursery ensures the channel with the immediate
|
|
||||||
# parent is kept alive as a resilient service until
|
ya_root_tn: bool = bool(actor._root_tn)
|
||||||
# cancellation steps have (mostly) occurred in
|
ya_service_tn: bool = bool(actor._service_tn)
|
||||||
# a deterministic way.
|
|
||||||
|
# NOTE, a top-most "root" nursery in each actor-process
|
||||||
|
# enables a lifetime priority for the IPC-channel connection
|
||||||
|
# with a sub-actor's immediate parent. I.e. this connection
|
||||||
|
# is kept alive as a resilient service connection until all
|
||||||
|
# other machinery has exited, cancellation of all
|
||||||
|
# embedded/child scopes have completed. This helps ensure
|
||||||
|
# a deterministic (and thus "graceful")
|
||||||
|
# first-class-supervision style teardown where a parent actor
|
||||||
|
# (vs. say peers) is always the last to be contacted before
|
||||||
|
# disconnect.
|
||||||
root_tn: trio.Nursery
|
root_tn: trio.Nursery
|
||||||
async with (
|
async with (
|
||||||
collapse_eg(),
|
collapse_eg(),
|
||||||
trio.open_nursery() as root_tn,
|
maybe_open_nursery(
|
||||||
|
nursery=actor._root_tn,
|
||||||
|
) as root_tn,
|
||||||
):
|
):
|
||||||
actor._root_n = root_tn
|
if ya_root_tn:
|
||||||
assert actor._root_n
|
assert root_tn is actor._root_tn
|
||||||
|
else:
|
||||||
|
actor._root_tn = root_tn
|
||||||
|
|
||||||
ipc_server: _server.IPCServer
|
ipc_server: _server.IPCServer
|
||||||
async with (
|
async with (
|
||||||
collapse_eg(),
|
collapse_eg(),
|
||||||
trio.open_nursery() as service_nursery,
|
maybe_open_nursery(
|
||||||
|
nursery=actor._service_tn,
|
||||||
|
) as service_tn,
|
||||||
_server.open_ipc_server(
|
_server.open_ipc_server(
|
||||||
parent_tn=service_nursery,
|
parent_tn=service_tn, # ?TODO, why can't this be the root-tn
|
||||||
stream_handler_tn=service_nursery,
|
stream_handler_tn=service_tn,
|
||||||
) as ipc_server,
|
) as ipc_server,
|
||||||
# ) as actor._ipc_server,
|
|
||||||
# ^TODO? prettier?
|
|
||||||
|
|
||||||
):
|
):
|
||||||
|
if ya_service_tn:
|
||||||
|
assert service_tn is actor._service_tn
|
||||||
|
else:
|
||||||
# This nursery is used to handle all inbound
|
# This nursery is used to handle all inbound
|
||||||
# connections to us such that if the TCP server
|
# connections to us such that if the TCP server
|
||||||
# is killed, connections can continue to process
|
# is killed, connections can continue to process
|
||||||
# in the background until this nursery is cancelled.
|
# in the background until this nursery is cancelled.
|
||||||
actor._service_n = service_nursery
|
actor._service_tn = service_tn
|
||||||
|
|
||||||
|
# set after allocate
|
||||||
actor._ipc_server = ipc_server
|
actor._ipc_server = ipc_server
|
||||||
assert (
|
|
||||||
actor._service_n
|
|
||||||
and (
|
|
||||||
actor._service_n
|
|
||||||
is
|
|
||||||
actor._ipc_server._parent_tn
|
|
||||||
is
|
|
||||||
ipc_server._stream_handler_tn
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
# load exposed/allowed RPC modules
|
# load exposed/allowed RPC modules
|
||||||
# XXX: do this **after** establishing a channel to the parent
|
# XXX: do this **after** establishing a channel to the parent
|
||||||
|
@ -1530,10 +1591,11 @@ async def async_main(
|
||||||
# - root actor: the ``accept_addr`` passed to this method
|
# - root actor: the ``accept_addr`` passed to this method
|
||||||
|
|
||||||
# TODO: why is this not with the root nursery?
|
# TODO: why is this not with the root nursery?
|
||||||
|
# - see above that the `._service_tn` is what's used?
|
||||||
try:
|
try:
|
||||||
eps: list = await ipc_server.listen_on(
|
eps: list = await ipc_server.listen_on(
|
||||||
accept_addrs=accept_addrs,
|
accept_addrs=accept_addrs,
|
||||||
stream_handler_nursery=service_nursery,
|
stream_handler_nursery=service_tn,
|
||||||
)
|
)
|
||||||
log.runtime(
|
log.runtime(
|
||||||
f'Booted IPC server\n'
|
f'Booted IPC server\n'
|
||||||
|
@ -1541,7 +1603,7 @@ async def async_main(
|
||||||
)
|
)
|
||||||
assert (
|
assert (
|
||||||
(eps[0].listen_tn)
|
(eps[0].listen_tn)
|
||||||
is not service_nursery
|
is not service_tn
|
||||||
)
|
)
|
||||||
|
|
||||||
except OSError as oserr:
|
except OSError as oserr:
|
||||||
|
@ -1703,7 +1765,7 @@ async def async_main(
|
||||||
|
|
||||||
# XXX TODO but hard XXX
|
# XXX TODO but hard XXX
|
||||||
# we can't actually do this bc the debugger uses the
|
# we can't actually do this bc the debugger uses the
|
||||||
# _service_n to spawn the lock task, BUT, in theory if we had
|
# _service_tn to spawn the lock task, BUT, in theory if we had
|
||||||
# the root nursery surround this finally block it might be
|
# the root nursery surround this finally block it might be
|
||||||
# actually possible to debug THIS machinery in the same way
|
# actually possible to debug THIS machinery in the same way
|
||||||
# as user task code?
|
# as user task code?
|
||||||
|
@ -1755,9 +1817,7 @@ async def async_main(
|
||||||
f' {pformat(ipc_server._peers)}'
|
f' {pformat(ipc_server._peers)}'
|
||||||
)
|
)
|
||||||
log.runtime(teardown_report)
|
log.runtime(teardown_report)
|
||||||
await ipc_server.wait_for_no_more_peers(
|
await ipc_server.wait_for_no_more_peers()
|
||||||
shield=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
teardown_report += (
|
teardown_report += (
|
||||||
'-]> all peer channels are complete.\n'
|
'-]> all peer channels are complete.\n'
|
||||||
|
|
|
@ -236,10 +236,6 @@ async def hard_kill(
|
||||||
# whilst also hacking on it XD
|
# whilst also hacking on it XD
|
||||||
# terminate_after: int = 99999,
|
# terminate_after: int = 99999,
|
||||||
|
|
||||||
# NOTE: for mucking with `.pause()`-ing inside the runtime
|
|
||||||
# whilst also hacking on it XD
|
|
||||||
# terminate_after: int = 99999,
|
|
||||||
|
|
||||||
) -> None:
|
) -> None:
|
||||||
'''
|
'''
|
||||||
Un-gracefully terminate an OS level `trio.Process` after timeout.
|
Un-gracefully terminate an OS level `trio.Process` after timeout.
|
||||||
|
@ -301,6 +297,23 @@ async def hard_kill(
|
||||||
# zombies (as a feature) we ask the OS to do send in the
|
# zombies (as a feature) we ask the OS to do send in the
|
||||||
# removal swad as the last resort.
|
# removal swad as the last resort.
|
||||||
if cs.cancelled_caught:
|
if cs.cancelled_caught:
|
||||||
|
|
||||||
|
# TODO? attempt at intermediary-rent-sub
|
||||||
|
# with child in debug lock?
|
||||||
|
# |_https://github.com/goodboy/tractor/issues/320
|
||||||
|
#
|
||||||
|
# if not is_root_process():
|
||||||
|
# log.warning(
|
||||||
|
# 'Attempting to acquire debug-REPL-lock before zombie reap!'
|
||||||
|
# )
|
||||||
|
# with trio.CancelScope(shield=True):
|
||||||
|
# async with debug.acquire_debug_lock(
|
||||||
|
# subactor_uid=current_actor().uid,
|
||||||
|
# ) as _ctx:
|
||||||
|
# log.warning(
|
||||||
|
# 'Acquired debug lock, child ready to be killed ??\n'
|
||||||
|
# )
|
||||||
|
|
||||||
# TODO: toss in the skynet-logo face as ascii art?
|
# TODO: toss in the skynet-logo face as ascii art?
|
||||||
log.critical(
|
log.critical(
|
||||||
# 'Well, the #ZOMBIE_LORD_IS_HERE# to collect\n'
|
# 'Well, the #ZOMBIE_LORD_IS_HERE# to collect\n'
|
||||||
|
|
|
@ -117,7 +117,6 @@ class ActorNursery:
|
||||||
]
|
]
|
||||||
] = {}
|
] = {}
|
||||||
|
|
||||||
self.cancelled: bool = False
|
|
||||||
self._join_procs = trio.Event()
|
self._join_procs = trio.Event()
|
||||||
self._at_least_one_child_in_debug: bool = False
|
self._at_least_one_child_in_debug: bool = False
|
||||||
self.errors = errors
|
self.errors = errors
|
||||||
|
@ -135,10 +134,53 @@ class ActorNursery:
|
||||||
# TODO: remove the `.run_in_actor()` API and thus this 2ndary
|
# TODO: remove the `.run_in_actor()` API and thus this 2ndary
|
||||||
# nursery when that API get's moved outside this primitive!
|
# nursery when that API get's moved outside this primitive!
|
||||||
self._ria_nursery = ria_nursery
|
self._ria_nursery = ria_nursery
|
||||||
|
|
||||||
|
# TODO, factor this into a .hilevel api!
|
||||||
|
#
|
||||||
# portals spawned with ``run_in_actor()`` are
|
# portals spawned with ``run_in_actor()`` are
|
||||||
# cancelled when their "main" result arrives
|
# cancelled when their "main" result arrives
|
||||||
self._cancel_after_result_on_exit: set = set()
|
self._cancel_after_result_on_exit: set = set()
|
||||||
|
|
||||||
|
# trio.Nursery-like cancel (request) statuses
|
||||||
|
self._cancelled_caught: bool = False
|
||||||
|
self._cancel_called: bool = False
|
||||||
|
|
||||||
|
@property
|
||||||
|
def cancel_called(self) -> bool:
|
||||||
|
'''
|
||||||
|
Records whether cancellation has been requested for this
|
||||||
|
actor-nursery by a call to `.cancel()` either due to,
|
||||||
|
- an explicit call by some actor-local-task,
|
||||||
|
- an implicit call due to an error/cancel emited inside
|
||||||
|
the `tractor.open_nursery()` block.
|
||||||
|
|
||||||
|
'''
|
||||||
|
return self._cancel_called
|
||||||
|
|
||||||
|
@property
|
||||||
|
def cancelled_caught(self) -> bool:
|
||||||
|
'''
|
||||||
|
Set when this nursery was able to cance all spawned subactors
|
||||||
|
gracefully via an (implicit) call to `.cancel()`.
|
||||||
|
|
||||||
|
'''
|
||||||
|
return self._cancelled_caught
|
||||||
|
|
||||||
|
# TODO! remove internal/test-suite usage!
|
||||||
|
@property
|
||||||
|
def cancelled(self) -> bool:
|
||||||
|
warnings.warn(
|
||||||
|
"`ActorNursery.cancelled` is now deprecated, use "
|
||||||
|
" `.cancel_called` instead.",
|
||||||
|
DeprecationWarning,
|
||||||
|
stacklevel=2,
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
self._cancel_called
|
||||||
|
# and
|
||||||
|
# self._cancelled_caught
|
||||||
|
)
|
||||||
|
|
||||||
async def start_actor(
|
async def start_actor(
|
||||||
self,
|
self,
|
||||||
name: str,
|
name: str,
|
||||||
|
@ -316,7 +358,7 @@ class ActorNursery:
|
||||||
|
|
||||||
'''
|
'''
|
||||||
__runtimeframe__: int = 1 # noqa
|
__runtimeframe__: int = 1 # noqa
|
||||||
self.cancelled = True
|
self._cancel_called = True
|
||||||
|
|
||||||
# TODO: impl a repr for spawn more compact
|
# TODO: impl a repr for spawn more compact
|
||||||
# then `._children`..
|
# then `._children`..
|
||||||
|
@ -394,6 +436,8 @@ class ActorNursery:
|
||||||
) in children.values():
|
) in children.values():
|
||||||
log.warning(f"Hard killing process {proc}")
|
log.warning(f"Hard killing process {proc}")
|
||||||
proc.terminate()
|
proc.terminate()
|
||||||
|
else:
|
||||||
|
self._cancelled_caught
|
||||||
|
|
||||||
# mark ourselves as having (tried to have) cancelled all subactors
|
# mark ourselves as having (tried to have) cancelled all subactors
|
||||||
self._join_procs.set()
|
self._join_procs.set()
|
||||||
|
@ -402,12 +446,12 @@ class ActorNursery:
|
||||||
@acm
|
@acm
|
||||||
async def _open_and_supervise_one_cancels_all_nursery(
|
async def _open_and_supervise_one_cancels_all_nursery(
|
||||||
actor: Actor,
|
actor: Actor,
|
||||||
tb_hide: bool = False,
|
hide_tb: bool = True,
|
||||||
|
|
||||||
) -> typing.AsyncGenerator[ActorNursery, None]:
|
) -> typing.AsyncGenerator[ActorNursery, None]:
|
||||||
|
|
||||||
# normally don't need to show user by default
|
# normally don't need to show user by default
|
||||||
__tracebackhide__: bool = tb_hide
|
__tracebackhide__: bool = hide_tb
|
||||||
|
|
||||||
outer_err: BaseException|None = None
|
outer_err: BaseException|None = None
|
||||||
inner_err: BaseException|None = None
|
inner_err: BaseException|None = None
|
||||||
|
@ -599,8 +643,9 @@ _shutdown_msg: str = (
|
||||||
'Actor-runtime-shutdown'
|
'Actor-runtime-shutdown'
|
||||||
)
|
)
|
||||||
|
|
||||||
# @api_frame
|
|
||||||
@acm
|
@acm
|
||||||
|
# @api_frame
|
||||||
async def open_nursery(
|
async def open_nursery(
|
||||||
*, # named params only!
|
*, # named params only!
|
||||||
hide_tb: bool = True,
|
hide_tb: bool = True,
|
||||||
|
|
|
@ -237,9 +237,9 @@ def enable_stack_on_sig(
|
||||||
try:
|
try:
|
||||||
import stackscope
|
import stackscope
|
||||||
except ImportError:
|
except ImportError:
|
||||||
log.error(
|
log.warning(
|
||||||
'`stackscope` not installed for use in debug mode!\n'
|
'The `stackscope` lib is not installed!\n'
|
||||||
'`Ignoring {enable_stack_on_sig!r} call!\n'
|
'`Ignoring enable_stack_on_sig() call!\n'
|
||||||
)
|
)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
|
@ -148,7 +148,9 @@ def _post_mortem(
|
||||||
repl_fixture=repl_fixture,
|
repl_fixture=repl_fixture,
|
||||||
boxed_maybe_exc=boxed_maybe_exc,
|
boxed_maybe_exc=boxed_maybe_exc,
|
||||||
)
|
)
|
||||||
|
try:
|
||||||
if not enter_repl:
|
if not enter_repl:
|
||||||
|
# XXX, trigger `.release()` below immediately!
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
actor: Actor = current_actor()
|
actor: Actor = current_actor()
|
||||||
|
@ -194,7 +196,7 @@ def _post_mortem(
|
||||||
# frame=None,
|
# frame=None,
|
||||||
traceback=tb,
|
traceback=tb,
|
||||||
)
|
)
|
||||||
|
finally:
|
||||||
# XXX NOTE XXX: this is abs required to avoid hangs!
|
# XXX NOTE XXX: this is abs required to avoid hangs!
|
||||||
#
|
#
|
||||||
# Since we presume the post-mortem was enaged to
|
# Since we presume the post-mortem was enaged to
|
||||||
|
@ -248,7 +250,7 @@ async def _maybe_enter_pm(
|
||||||
*,
|
*,
|
||||||
tb: TracebackType|None = None,
|
tb: TracebackType|None = None,
|
||||||
api_frame: FrameType|None = None,
|
api_frame: FrameType|None = None,
|
||||||
hide_tb: bool = False,
|
hide_tb: bool = True,
|
||||||
|
|
||||||
# only enter debugger REPL when returns `True`
|
# only enter debugger REPL when returns `True`
|
||||||
debug_filter: Callable[
|
debug_filter: Callable[
|
||||||
|
|
|
@ -58,6 +58,7 @@ from tractor._context import Context
|
||||||
from tractor import _state
|
from tractor import _state
|
||||||
from tractor._exceptions import (
|
from tractor._exceptions import (
|
||||||
NoRuntime,
|
NoRuntime,
|
||||||
|
InternalError,
|
||||||
)
|
)
|
||||||
from tractor._state import (
|
from tractor._state import (
|
||||||
current_actor,
|
current_actor,
|
||||||
|
@ -79,6 +80,9 @@ from ._sigint import (
|
||||||
sigint_shield as sigint_shield,
|
sigint_shield as sigint_shield,
|
||||||
_ctlc_ignore_header as _ctlc_ignore_header
|
_ctlc_ignore_header as _ctlc_ignore_header
|
||||||
)
|
)
|
||||||
|
from ..pformat import (
|
||||||
|
ppfmt,
|
||||||
|
)
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from trio.lowlevel import Task
|
from trio.lowlevel import Task
|
||||||
|
@ -477,12 +481,12 @@ async def _pause(
|
||||||
# we have to figure out how to avoid having the service nursery
|
# we have to figure out how to avoid having the service nursery
|
||||||
# cancel on this task start? I *think* this works below:
|
# cancel on this task start? I *think* this works below:
|
||||||
# ```python
|
# ```python
|
||||||
# actor._service_n.cancel_scope.shield = shield
|
# actor._service_tn.cancel_scope.shield = shield
|
||||||
# ```
|
# ```
|
||||||
# but not entirely sure if that's a sane way to implement it?
|
# but not entirely sure if that's a sane way to implement it?
|
||||||
|
|
||||||
# NOTE currently we spawn the lock request task inside this
|
# NOTE currently we spawn the lock request task inside this
|
||||||
# subactor's global `Actor._service_n` so that the
|
# subactor's global `Actor._service_tn` so that the
|
||||||
# lifetime of the lock-request can outlive the current
|
# lifetime of the lock-request can outlive the current
|
||||||
# `._pause()` scope while the user steps through their
|
# `._pause()` scope while the user steps through their
|
||||||
# application code and when they finally exit the
|
# application code and when they finally exit the
|
||||||
|
@ -506,7 +510,7 @@ async def _pause(
|
||||||
f'|_{task}\n'
|
f'|_{task}\n'
|
||||||
)
|
)
|
||||||
with trio.CancelScope(shield=shield):
|
with trio.CancelScope(shield=shield):
|
||||||
req_ctx: Context = await actor._service_n.start(
|
req_ctx: Context = await actor._service_tn.start(
|
||||||
partial(
|
partial(
|
||||||
request_root_stdio_lock,
|
request_root_stdio_lock,
|
||||||
actor_uid=actor.uid,
|
actor_uid=actor.uid,
|
||||||
|
@ -540,7 +544,7 @@ async def _pause(
|
||||||
_repl_fail_report = None
|
_repl_fail_report = None
|
||||||
|
|
||||||
# when the actor is mid-runtime cancellation the
|
# when the actor is mid-runtime cancellation the
|
||||||
# `Actor._service_n` might get closed before we can spawn
|
# `Actor._service_tn` might get closed before we can spawn
|
||||||
# the request task, so just ignore expected RTE.
|
# the request task, so just ignore expected RTE.
|
||||||
elif (
|
elif (
|
||||||
isinstance(pause_err, RuntimeError)
|
isinstance(pause_err, RuntimeError)
|
||||||
|
@ -985,7 +989,7 @@ def pause_from_sync(
|
||||||
# that output and assign the `repl` created above!
|
# that output and assign the `repl` created above!
|
||||||
bg_task, _ = trio.from_thread.run(
|
bg_task, _ = trio.from_thread.run(
|
||||||
afn=partial(
|
afn=partial(
|
||||||
actor._service_n.start,
|
actor._service_tn.start,
|
||||||
partial(
|
partial(
|
||||||
_pause_from_bg_root_thread,
|
_pause_from_bg_root_thread,
|
||||||
behalf_of_thread=thread,
|
behalf_of_thread=thread,
|
||||||
|
@ -1153,9 +1157,10 @@ def pause_from_sync(
|
||||||
'use_greenback',
|
'use_greenback',
|
||||||
False,
|
False,
|
||||||
):
|
):
|
||||||
raise RuntimeError(
|
raise InternalError(
|
||||||
'`greenback` was never initialized in this actor!?\n\n'
|
f'`greenback` was never initialized in this actor?\n'
|
||||||
f'{_state._runtime_vars}\n'
|
f'\n'
|
||||||
|
f'{ppfmt(_state._runtime_vars)}\n'
|
||||||
) from rte
|
) from rte
|
||||||
|
|
||||||
raise
|
raise
|
||||||
|
|
|
@ -846,9 +846,9 @@ class DebugStatus:
|
||||||
|
|
||||||
'''
|
'''
|
||||||
if not (
|
if not (
|
||||||
repl_fixture
|
|
||||||
or
|
|
||||||
(rt_repl_fixture := _state._runtime_vars.get('repl_fixture'))
|
(rt_repl_fixture := _state._runtime_vars.get('repl_fixture'))
|
||||||
|
or
|
||||||
|
repl_fixture
|
||||||
):
|
):
|
||||||
return True # YES always enter
|
return True # YES always enter
|
||||||
|
|
||||||
|
|
|
@ -101,11 +101,27 @@ class Channel:
|
||||||
# ^XXX! ONLY set if a remote actor sends an `Error`-msg
|
# ^XXX! ONLY set if a remote actor sends an `Error`-msg
|
||||||
self._closed: bool = False
|
self._closed: bool = False
|
||||||
|
|
||||||
# flag set by ``Portal.cancel_actor()`` indicating remote
|
# flag set by `Portal.cancel_actor()` indicating remote
|
||||||
# (possibly peer) cancellation of the far end actor
|
# (possibly peer) cancellation of the far end actor runtime.
|
||||||
# runtime.
|
|
||||||
self._cancel_called: bool = False
|
self._cancel_called: bool = False
|
||||||
|
|
||||||
|
@property
|
||||||
|
def closed(self) -> bool:
|
||||||
|
'''
|
||||||
|
Was `.aclose()` successfully called?
|
||||||
|
|
||||||
|
'''
|
||||||
|
return self._closed
|
||||||
|
|
||||||
|
@property
|
||||||
|
def cancel_called(self) -> bool:
|
||||||
|
'''
|
||||||
|
Set when `Portal.cancel_actor()` is called on a portal which
|
||||||
|
wraps this IPC channel.
|
||||||
|
|
||||||
|
'''
|
||||||
|
return self._cancel_called
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def uid(self) -> tuple[str, str]:
|
def uid(self) -> tuple[str, str]:
|
||||||
'''
|
'''
|
||||||
|
@ -169,7 +185,9 @@ class Channel:
|
||||||
addr,
|
addr,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
)
|
)
|
||||||
assert transport.raddr == addr
|
# XXX, for UDS *no!* since we recv the peer-pid and build out
|
||||||
|
# a new addr..
|
||||||
|
# assert transport.raddr == addr
|
||||||
chan = Channel(transport=transport)
|
chan = Channel(transport=transport)
|
||||||
|
|
||||||
# ?TODO, compact this into adapter level-methods?
|
# ?TODO, compact this into adapter level-methods?
|
||||||
|
@ -285,7 +303,7 @@ class Channel:
|
||||||
self,
|
self,
|
||||||
payload: Any,
|
payload: Any,
|
||||||
|
|
||||||
hide_tb: bool = True,
|
hide_tb: bool = False,
|
||||||
|
|
||||||
) -> None:
|
) -> None:
|
||||||
'''
|
'''
|
||||||
|
|
|
@ -17,20 +17,38 @@
|
||||||
Utils to tame mp non-SC madeness
|
Utils to tame mp non-SC madeness
|
||||||
|
|
||||||
'''
|
'''
|
||||||
|
import platform
|
||||||
|
|
||||||
|
|
||||||
# !TODO! in 3.13 this can be disabled (the-same/similarly) using
|
|
||||||
# a flag,
|
|
||||||
# - [ ] soo if it works like this, drop this module entirely for
|
|
||||||
# 3.13+ B)
|
|
||||||
# |_https://docs.python.org/3/library/multiprocessing.shared_memory.html
|
|
||||||
#
|
|
||||||
def disable_mantracker():
|
def disable_mantracker():
|
||||||
'''
|
'''
|
||||||
Disable all `multiprocessing` "resource tracking" machinery since
|
Disable all `multiprocessing` "resource tracking" machinery since
|
||||||
it's an absolute multi-threaded mess of non-SC madness.
|
it's an absolute multi-threaded mess of non-SC madness.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
from multiprocessing import resource_tracker as mantracker
|
from multiprocessing.shared_memory import SharedMemory
|
||||||
|
|
||||||
|
|
||||||
|
# 3.13+ only.. can pass `track=False` to disable
|
||||||
|
# all the resource tracker bs.
|
||||||
|
# https://docs.python.org/3/library/multiprocessing.shared_memory.html
|
||||||
|
if (_py_313 := (
|
||||||
|
platform.python_version_tuple()[:-1]
|
||||||
|
>=
|
||||||
|
('3', '13')
|
||||||
|
)
|
||||||
|
):
|
||||||
|
from functools import partial
|
||||||
|
return partial(
|
||||||
|
SharedMemory,
|
||||||
|
track=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# !TODO, once we drop 3.12- we can obvi remove all this!
|
||||||
|
else:
|
||||||
|
from multiprocessing import (
|
||||||
|
resource_tracker as mantracker,
|
||||||
|
)
|
||||||
|
|
||||||
# Tell the "resource tracker" thing to fuck off.
|
# Tell the "resource tracker" thing to fuck off.
|
||||||
class ManTracker(mantracker.ResourceTracker):
|
class ManTracker(mantracker.ResourceTracker):
|
||||||
|
@ -50,3 +68,8 @@ def disable_mantracker():
|
||||||
mantracker.ensure_running = mantracker._resource_tracker.ensure_running
|
mantracker.ensure_running = mantracker._resource_tracker.ensure_running
|
||||||
mantracker.unregister = mantracker._resource_tracker.unregister
|
mantracker.unregister = mantracker._resource_tracker.unregister
|
||||||
mantracker.getfd = mantracker._resource_tracker.getfd
|
mantracker.getfd = mantracker._resource_tracker.getfd
|
||||||
|
|
||||||
|
# use std type verbatim
|
||||||
|
shmT = SharedMemory
|
||||||
|
|
||||||
|
return shmT
|
||||||
|
|
|
@ -814,10 +814,14 @@ class Server(Struct):
|
||||||
|
|
||||||
async def wait_for_no_more_peers(
|
async def wait_for_no_more_peers(
|
||||||
self,
|
self,
|
||||||
shield: bool = False,
|
# XXX, should this even be allowed?
|
||||||
|
# -> i've seen it cause hangs on teardown
|
||||||
|
# in `test_resource_cache.py`
|
||||||
|
# _shield: bool = False,
|
||||||
) -> None:
|
) -> None:
|
||||||
with trio.CancelScope(shield=shield):
|
|
||||||
await self._no_more_peers.wait()
|
await self._no_more_peers.wait()
|
||||||
|
# with trio.CancelScope(shield=_shield):
|
||||||
|
# await self._no_more_peers.wait()
|
||||||
|
|
||||||
async def wait_for_peer(
|
async def wait_for_peer(
|
||||||
self,
|
self,
|
||||||
|
@ -997,7 +1001,11 @@ class Server(Struct):
|
||||||
partial(
|
partial(
|
||||||
_serve_ipc_eps,
|
_serve_ipc_eps,
|
||||||
server=self,
|
server=self,
|
||||||
stream_handler_tn=stream_handler_nursery,
|
stream_handler_tn=(
|
||||||
|
stream_handler_nursery
|
||||||
|
or
|
||||||
|
self._stream_handler_tn
|
||||||
|
),
|
||||||
listen_addrs=accept_addrs,
|
listen_addrs=accept_addrs,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
@ -1141,13 +1149,17 @@ async def open_ipc_server(
|
||||||
|
|
||||||
async with maybe_open_nursery(
|
async with maybe_open_nursery(
|
||||||
nursery=parent_tn,
|
nursery=parent_tn,
|
||||||
) as rent_tn:
|
) as parent_tn:
|
||||||
no_more_peers = trio.Event()
|
no_more_peers = trio.Event()
|
||||||
no_more_peers.set()
|
no_more_peers.set()
|
||||||
|
|
||||||
ipc_server = IPCServer(
|
ipc_server = IPCServer(
|
||||||
_parent_tn=rent_tn,
|
_parent_tn=parent_tn,
|
||||||
_stream_handler_tn=stream_handler_tn or rent_tn,
|
_stream_handler_tn=(
|
||||||
|
stream_handler_tn
|
||||||
|
or
|
||||||
|
parent_tn
|
||||||
|
),
|
||||||
_no_more_peers=no_more_peers,
|
_no_more_peers=no_more_peers,
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
|
|
|
@ -23,14 +23,15 @@ considered optional within the context of this runtime-library.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
from multiprocessing import shared_memory as shm
|
||||||
|
from multiprocessing.shared_memory import (
|
||||||
|
# SharedMemory,
|
||||||
|
ShareableList,
|
||||||
|
)
|
||||||
|
import platform
|
||||||
from sys import byteorder
|
from sys import byteorder
|
||||||
import time
|
import time
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from multiprocessing import shared_memory as shm
|
|
||||||
from multiprocessing.shared_memory import (
|
|
||||||
SharedMemory,
|
|
||||||
ShareableList,
|
|
||||||
)
|
|
||||||
|
|
||||||
from msgspec import (
|
from msgspec import (
|
||||||
Struct,
|
Struct,
|
||||||
|
@ -61,7 +62,7 @@ except ImportError:
|
||||||
log = get_logger(__name__)
|
log = get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
disable_mantracker()
|
SharedMemory = disable_mantracker()
|
||||||
|
|
||||||
|
|
||||||
class SharedInt:
|
class SharedInt:
|
||||||
|
@ -789,10 +790,22 @@ def open_shm_list(
|
||||||
readonly=readonly,
|
readonly=readonly,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# TODO, factor into a @actor_fixture acm-API?
|
||||||
|
# -[ ] also `@maybe_actor_fixture()` which inludes
|
||||||
|
# the .current_actor() convenience check?
|
||||||
|
# |_ orr can that just be in the sin-maybe-version?
|
||||||
|
#
|
||||||
# "close" attached shm on actor teardown
|
# "close" attached shm on actor teardown
|
||||||
try:
|
try:
|
||||||
actor = tractor.current_actor()
|
actor = tractor.current_actor()
|
||||||
|
|
||||||
actor.lifetime_stack.callback(shml.shm.close)
|
actor.lifetime_stack.callback(shml.shm.close)
|
||||||
|
|
||||||
|
# XXX on 3.13+ we don't need to call this?
|
||||||
|
# -> bc we pass `track=False` for `SharedMemeory` orr?
|
||||||
|
if (
|
||||||
|
platform.python_version_tuple()[:-1] < ('3', '13')
|
||||||
|
):
|
||||||
actor.lifetime_stack.callback(shml.shm.unlink)
|
actor.lifetime_stack.callback(shml.shm.unlink)
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
log.warning('tractor runtime not active, skipping teardown steps')
|
log.warning('tractor runtime not active, skipping teardown steps')
|
||||||
|
|
|
@ -18,6 +18,7 @@ TCP implementation of tractor.ipc._transport.MsgTransport protocol
|
||||||
|
|
||||||
'''
|
'''
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
import ipaddress
|
||||||
from typing import (
|
from typing import (
|
||||||
ClassVar,
|
ClassVar,
|
||||||
)
|
)
|
||||||
|
@ -50,13 +51,45 @@ class TCPAddress(
|
||||||
_host: str
|
_host: str
|
||||||
_port: int
|
_port: int
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
try:
|
||||||
|
ipaddress.ip_address(self._host)
|
||||||
|
except ValueError as valerr:
|
||||||
|
raise ValueError(
|
||||||
|
'Invalid {type(self).__name__}._host = {self._host!r}\n'
|
||||||
|
) from valerr
|
||||||
|
|
||||||
proto_key: ClassVar[str] = 'tcp'
|
proto_key: ClassVar[str] = 'tcp'
|
||||||
unwrapped_type: ClassVar[type] = tuple[str, int]
|
unwrapped_type: ClassVar[type] = tuple[str, int]
|
||||||
def_bindspace: ClassVar[str] = '127.0.0.1'
|
def_bindspace: ClassVar[str] = '127.0.0.1'
|
||||||
|
|
||||||
|
# ?TODO, actually validate ipv4/6 with stdlib's `ipaddress`
|
||||||
@property
|
@property
|
||||||
def is_valid(self) -> bool:
|
def is_valid(self) -> bool:
|
||||||
return self._port != 0
|
'''
|
||||||
|
Predicate to ensure a valid socket-address pair.
|
||||||
|
|
||||||
|
'''
|
||||||
|
return (
|
||||||
|
self._port != 0
|
||||||
|
and
|
||||||
|
(ipaddr := ipaddress.ip_address(self._host))
|
||||||
|
and not (
|
||||||
|
ipaddr.is_reserved
|
||||||
|
or
|
||||||
|
ipaddr.is_unspecified
|
||||||
|
or
|
||||||
|
ipaddr.is_link_local
|
||||||
|
or
|
||||||
|
ipaddr.is_link_local
|
||||||
|
or
|
||||||
|
ipaddr.is_multicast
|
||||||
|
or
|
||||||
|
ipaddr.is_global
|
||||||
|
)
|
||||||
|
)
|
||||||
|
# ^XXX^ see various properties of invalid addrs here,
|
||||||
|
# https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Address
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def bindspace(self) -> str:
|
def bindspace(self) -> str:
|
||||||
|
|
|
@ -430,20 +430,25 @@ class MsgpackTransport(MsgTransport):
|
||||||
return await self.stream.send_all(size + bytes_data)
|
return await self.stream.send_all(size + bytes_data)
|
||||||
except (
|
except (
|
||||||
trio.BrokenResourceError,
|
trio.BrokenResourceError,
|
||||||
) as bre:
|
trio.ClosedResourceError,
|
||||||
trans_err = bre
|
) as _re:
|
||||||
|
trans_err = _re
|
||||||
tpt_name: str = f'{type(self).__name__!r}'
|
tpt_name: str = f'{type(self).__name__!r}'
|
||||||
|
|
||||||
match trans_err:
|
match trans_err:
|
||||||
case trio.BrokenResourceError() if (
|
|
||||||
'[Errno 32] Broken pipe' in trans_err.args[0]
|
# XXX, specifc to UDS transport and its,
|
||||||
# ^XXX, specifc to UDS transport and its,
|
|
||||||
# well, "speediness".. XD
|
# well, "speediness".. XD
|
||||||
# |_ likely todo with races related to how fast
|
# |_ likely todo with races related to how fast
|
||||||
# the socket is setup/torn-down on linux
|
# the socket is setup/torn-down on linux
|
||||||
# as it pertains to rando pings from the
|
# as it pertains to rando pings from the
|
||||||
# `.discovery` subsys and protos.
|
# `.discovery` subsys and protos.
|
||||||
|
case trio.BrokenResourceError() if (
|
||||||
|
'[Errno 32] Broken pipe'
|
||||||
|
in
|
||||||
|
trans_err.args[0]
|
||||||
):
|
):
|
||||||
raise TransportClosed.from_src_exc(
|
tpt_closed = TransportClosed.from_src_exc(
|
||||||
message=(
|
message=(
|
||||||
f'{tpt_name} already closed by peer\n'
|
f'{tpt_name} already closed by peer\n'
|
||||||
),
|
),
|
||||||
|
@ -451,14 +456,31 @@ class MsgpackTransport(MsgTransport):
|
||||||
src_exc=trans_err,
|
src_exc=trans_err,
|
||||||
raise_on_report=True,
|
raise_on_report=True,
|
||||||
loglevel='transport',
|
loglevel='transport',
|
||||||
) from bre
|
)
|
||||||
|
raise tpt_closed from trans_err
|
||||||
|
|
||||||
|
# case trio.ClosedResourceError() if (
|
||||||
|
# 'this socket was already closed'
|
||||||
|
# in
|
||||||
|
# trans_err.args[0]
|
||||||
|
# ):
|
||||||
|
# tpt_closed = TransportClosed.from_src_exc(
|
||||||
|
# message=(
|
||||||
|
# f'{tpt_name} already closed by peer\n'
|
||||||
|
# ),
|
||||||
|
# body=f'{self}\n',
|
||||||
|
# src_exc=trans_err,
|
||||||
|
# raise_on_report=True,
|
||||||
|
# loglevel='transport',
|
||||||
|
# )
|
||||||
|
# raise tpt_closed from trans_err
|
||||||
|
|
||||||
# unless the disconnect condition falls under "a
|
# unless the disconnect condition falls under "a
|
||||||
# normal operation breakage" we usualy console warn
|
# normal operation breakage" we usualy console warn
|
||||||
# about it.
|
# about it.
|
||||||
case _:
|
case _:
|
||||||
log.exception(
|
log.exception(
|
||||||
'{tpt_name} layer failed pre-send ??\n'
|
f'{tpt_name} layer failed pre-send ??\n'
|
||||||
)
|
)
|
||||||
raise trans_err
|
raise trans_err
|
||||||
|
|
||||||
|
@ -503,7 +525,7 @@ class MsgpackTransport(MsgTransport):
|
||||||
def pformat(self) -> str:
|
def pformat(self) -> str:
|
||||||
return (
|
return (
|
||||||
f'<{type(self).__name__}(\n'
|
f'<{type(self).__name__}(\n'
|
||||||
f' |_peers: 2\n'
|
f' |_peers: 1\n'
|
||||||
f' laddr: {self._laddr}\n'
|
f' laddr: {self._laddr}\n'
|
||||||
f' raddr: {self._raddr}\n'
|
f' raddr: {self._raddr}\n'
|
||||||
# f'\n'
|
# f'\n'
|
||||||
|
|
|
@ -18,6 +18,9 @@ Unix Domain Socket implementation of tractor.ipc._transport.MsgTransport protoco
|
||||||
|
|
||||||
'''
|
'''
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
from contextlib import (
|
||||||
|
contextmanager as cm,
|
||||||
|
)
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import os
|
import os
|
||||||
from socket import (
|
from socket import (
|
||||||
|
@ -29,6 +32,7 @@ from socket import (
|
||||||
)
|
)
|
||||||
import struct
|
import struct
|
||||||
from typing import (
|
from typing import (
|
||||||
|
Type,
|
||||||
TYPE_CHECKING,
|
TYPE_CHECKING,
|
||||||
ClassVar,
|
ClassVar,
|
||||||
)
|
)
|
||||||
|
@ -99,8 +103,6 @@ class UDSAddress(
|
||||||
self.filedir
|
self.filedir
|
||||||
or
|
or
|
||||||
self.def_bindspace
|
self.def_bindspace
|
||||||
# or
|
|
||||||
# get_rt_dir()
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
|
@ -205,12 +207,35 @@ class UDSAddress(
|
||||||
f']'
|
f']'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@cm
|
||||||
|
def _reraise_as_connerr(
|
||||||
|
src_excs: tuple[Type[Exception]],
|
||||||
|
addr: UDSAddress,
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
except src_excs as src_exc:
|
||||||
|
raise ConnectionError(
|
||||||
|
f'Bad UDS socket-filepath-as-address ??\n'
|
||||||
|
f'{addr}\n'
|
||||||
|
f' |_sockpath: {addr.sockpath}\n'
|
||||||
|
f'\n'
|
||||||
|
f'from src: {src_exc!r}\n'
|
||||||
|
) from src_exc
|
||||||
|
|
||||||
|
|
||||||
async def start_listener(
|
async def start_listener(
|
||||||
addr: UDSAddress,
|
addr: UDSAddress,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
) -> SocketListener:
|
) -> SocketListener:
|
||||||
# sock = addr._sock = socket.socket(
|
'''
|
||||||
|
Start listening for inbound connections via
|
||||||
|
a `trio.SocketListener` (task) which `socket.bind()`s on `addr`.
|
||||||
|
|
||||||
|
Note, if the `UDSAddress.bindspace: Path` directory dne it is
|
||||||
|
implicitly created.
|
||||||
|
|
||||||
|
'''
|
||||||
sock = socket.socket(
|
sock = socket.socket(
|
||||||
socket.AF_UNIX,
|
socket.AF_UNIX,
|
||||||
socket.SOCK_STREAM
|
socket.SOCK_STREAM
|
||||||
|
@ -221,17 +246,25 @@ async def start_listener(
|
||||||
f'|_{addr}\n'
|
f'|_{addr}\n'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# ?TODO? should we use the `actor.lifetime_stack`
|
||||||
|
# to rm on shutdown?
|
||||||
bindpath: Path = addr.sockpath
|
bindpath: Path = addr.sockpath
|
||||||
try:
|
if not (bs := addr.bindspace).is_dir():
|
||||||
await sock.bind(str(bindpath))
|
log.info(
|
||||||
except (
|
'Creating bindspace dir in file-sys\n'
|
||||||
|
f'>{{\n'
|
||||||
|
f'|_{bs!r}\n'
|
||||||
|
)
|
||||||
|
bs.mkdir()
|
||||||
|
|
||||||
|
with _reraise_as_connerr(
|
||||||
|
src_excs=(
|
||||||
FileNotFoundError,
|
FileNotFoundError,
|
||||||
) as fdne:
|
OSError,
|
||||||
raise ConnectionError(
|
),
|
||||||
f'Bad UDS socket-filepath-as-address ??\n'
|
addr=addr
|
||||||
f'{addr}\n'
|
):
|
||||||
f' |_sockpath: {addr.sockpath}\n'
|
await sock.bind(str(bindpath))
|
||||||
) from fdne
|
|
||||||
|
|
||||||
sock.listen(1)
|
sock.listen(1)
|
||||||
log.info(
|
log.info(
|
||||||
|
@ -356,27 +389,30 @@ class MsgpackUDSStream(MsgpackTransport):
|
||||||
# `.setsockopt()` call tells the OS provide it; the client
|
# `.setsockopt()` call tells the OS provide it; the client
|
||||||
# pid can then be read on server/listen() side via
|
# pid can then be read on server/listen() side via
|
||||||
# `get_peer_info()` above.
|
# `get_peer_info()` above.
|
||||||
try:
|
|
||||||
|
with _reraise_as_connerr(
|
||||||
|
src_excs=(
|
||||||
|
FileNotFoundError,
|
||||||
|
),
|
||||||
|
addr=addr
|
||||||
|
):
|
||||||
stream = await open_unix_socket_w_passcred(
|
stream = await open_unix_socket_w_passcred(
|
||||||
str(sockpath),
|
str(sockpath),
|
||||||
**kwargs
|
**kwargs
|
||||||
)
|
)
|
||||||
except (
|
|
||||||
FileNotFoundError,
|
|
||||||
) as fdne:
|
|
||||||
raise ConnectionError(
|
|
||||||
f'Bad UDS socket-filepath-as-address ??\n'
|
|
||||||
f'{addr}\n'
|
|
||||||
f' |_sockpath: {sockpath}\n'
|
|
||||||
) from fdne
|
|
||||||
|
|
||||||
stream = MsgpackUDSStream(
|
tpt_stream = MsgpackUDSStream(
|
||||||
stream,
|
stream,
|
||||||
prefix_size=prefix_size,
|
prefix_size=prefix_size,
|
||||||
codec=codec
|
codec=codec
|
||||||
)
|
)
|
||||||
stream._raddr = addr
|
# XXX assign from new addrs after peer-PID extract!
|
||||||
return stream
|
(
|
||||||
|
tpt_stream._laddr,
|
||||||
|
tpt_stream._raddr,
|
||||||
|
) = cls.get_stream_addrs(stream)
|
||||||
|
|
||||||
|
return tpt_stream
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get_stream_addrs(
|
def get_stream_addrs(
|
||||||
|
|
|
@ -210,12 +210,14 @@ class PldRx(Struct):
|
||||||
match msg:
|
match msg:
|
||||||
case Return()|Error():
|
case Return()|Error():
|
||||||
log.runtime(
|
log.runtime(
|
||||||
f'Rxed final outcome msg\n'
|
f'Rxed final-outcome msg\n'
|
||||||
|
f'\n'
|
||||||
f'{msg}\n'
|
f'{msg}\n'
|
||||||
)
|
)
|
||||||
case Stop():
|
case Stop():
|
||||||
log.runtime(
|
log.runtime(
|
||||||
f'Rxed stream stopped msg\n'
|
f'Rxed stream stopped msg\n'
|
||||||
|
f'\n'
|
||||||
f'{msg}\n'
|
f'{msg}\n'
|
||||||
)
|
)
|
||||||
if passthrough_non_pld_msgs:
|
if passthrough_non_pld_msgs:
|
||||||
|
@ -261,8 +263,9 @@ class PldRx(Struct):
|
||||||
if (
|
if (
|
||||||
type(msg) is Return
|
type(msg) is Return
|
||||||
):
|
):
|
||||||
log.info(
|
log.runtime(
|
||||||
f'Rxed final result msg\n'
|
f'Rxed final result msg\n'
|
||||||
|
f'\n'
|
||||||
f'{msg}\n'
|
f'{msg}\n'
|
||||||
)
|
)
|
||||||
return self.decode_pld(
|
return self.decode_pld(
|
||||||
|
@ -304,10 +307,13 @@ class PldRx(Struct):
|
||||||
try:
|
try:
|
||||||
pld: PayloadT = self._pld_dec.decode(pld)
|
pld: PayloadT = self._pld_dec.decode(pld)
|
||||||
log.runtime(
|
log.runtime(
|
||||||
'Decoded msg payload\n\n'
|
f'Decoded payload for\n'
|
||||||
|
# f'\n'
|
||||||
f'{msg}\n'
|
f'{msg}\n'
|
||||||
f'where payload decoded as\n'
|
# ^TODO?, ideally just render with `,
|
||||||
f'|_pld={pld!r}\n'
|
# pld={decode}` in the `msg.pformat()`??
|
||||||
|
f'where, '
|
||||||
|
f'{type(msg).__name__}.pld={pld!r}\n'
|
||||||
)
|
)
|
||||||
return pld
|
return pld
|
||||||
except TypeError as typerr:
|
except TypeError as typerr:
|
||||||
|
@ -494,7 +500,8 @@ def limit_plds(
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
log.runtime(
|
log.runtime(
|
||||||
'Reverted to previous payload-decoder\n\n'
|
f'Reverted to previous payload-decoder\n'
|
||||||
|
f'\n'
|
||||||
f'{orig_pldec}\n'
|
f'{orig_pldec}\n'
|
||||||
)
|
)
|
||||||
# sanity on orig settings
|
# sanity on orig settings
|
||||||
|
@ -606,10 +613,9 @@ async def drain_to_final_msg(
|
||||||
# msg: dict = await ctx._rx_chan.receive()
|
# msg: dict = await ctx._rx_chan.receive()
|
||||||
# if res_cs.cancelled_caught:
|
# if res_cs.cancelled_caught:
|
||||||
#
|
#
|
||||||
# -[ ] make sure pause points work here for REPLing
|
# -[x] make sure pause points work here for REPLing
|
||||||
# the runtime itself; i.e. ensure there's no hangs!
|
# the runtime itself; i.e. ensure there's no hangs!
|
||||||
# |_from tractor.devx.debug import pause
|
# |_see masked code below in .cancel_called path
|
||||||
# await pause()
|
|
||||||
|
|
||||||
# NOTE: we get here if the far end was
|
# NOTE: we get here if the far end was
|
||||||
# `ContextCancelled` in 2 cases:
|
# `ContextCancelled` in 2 cases:
|
||||||
|
@ -629,7 +635,8 @@ async def drain_to_final_msg(
|
||||||
(local_cs := rent_n.cancel_scope).cancel_called
|
(local_cs := rent_n.cancel_scope).cancel_called
|
||||||
):
|
):
|
||||||
log.cancel(
|
log.cancel(
|
||||||
'RPC-ctx cancelled by local-parent scope during drain!\n\n'
|
f'RPC-ctx cancelled by local-parent scope during drain!\n'
|
||||||
|
f'\n'
|
||||||
f'c}}>\n'
|
f'c}}>\n'
|
||||||
f' |_{rent_n}\n'
|
f' |_{rent_n}\n'
|
||||||
f' |_.cancel_scope = {local_cs}\n'
|
f' |_.cancel_scope = {local_cs}\n'
|
||||||
|
@ -644,6 +651,10 @@ async def drain_to_final_msg(
|
||||||
f'IPC ctx cancelled externally during result drain ?\n'
|
f'IPC ctx cancelled externally during result drain ?\n'
|
||||||
f'{ctx}'
|
f'{ctx}'
|
||||||
)
|
)
|
||||||
|
# XXX, for tracing `Cancelled`..
|
||||||
|
# from tractor.devx.debug import pause
|
||||||
|
# await pause(shield=True)
|
||||||
|
|
||||||
# CASE 2: mask the local cancelled-error(s)
|
# CASE 2: mask the local cancelled-error(s)
|
||||||
# only when we are sure the remote error is
|
# only when we are sure the remote error is
|
||||||
# the source cause of this local task's
|
# the source cause of this local task's
|
||||||
|
@ -663,7 +674,8 @@ async def drain_to_final_msg(
|
||||||
# final result arrived!
|
# final result arrived!
|
||||||
case Return():
|
case Return():
|
||||||
log.runtime(
|
log.runtime(
|
||||||
'Context delivered final draining msg:\n'
|
f'Context delivered final draining msg\n'
|
||||||
|
f'\n'
|
||||||
f'{pretty_struct.pformat(msg)}'
|
f'{pretty_struct.pformat(msg)}'
|
||||||
)
|
)
|
||||||
ctx._result: Any = pld
|
ctx._result: Any = pld
|
||||||
|
@ -697,12 +709,14 @@ async def drain_to_final_msg(
|
||||||
):
|
):
|
||||||
log.cancel(
|
log.cancel(
|
||||||
'Cancelling `MsgStream` drain since '
|
'Cancelling `MsgStream` drain since '
|
||||||
f'{reason}\n\n'
|
f'{reason}\n'
|
||||||
|
f'\n'
|
||||||
f'<= {ctx.chan.uid}\n'
|
f'<= {ctx.chan.uid}\n'
|
||||||
f' |_{ctx._nsf}()\n\n'
|
f' |_{ctx._nsf}()\n'
|
||||||
|
f'\n'
|
||||||
f'=> {ctx._task}\n'
|
f'=> {ctx._task}\n'
|
||||||
f' |_{ctx._stream}\n\n'
|
f' |_{ctx._stream}\n'
|
||||||
|
f'\n'
|
||||||
f'{pretty_struct.pformat(msg)}\n'
|
f'{pretty_struct.pformat(msg)}\n'
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
|
@ -739,7 +753,8 @@ async def drain_to_final_msg(
|
||||||
case Stop():
|
case Stop():
|
||||||
pre_result_drained.append(msg)
|
pre_result_drained.append(msg)
|
||||||
log.runtime( # normal/expected shutdown transaction
|
log.runtime( # normal/expected shutdown transaction
|
||||||
'Remote stream terminated due to "stop" msg:\n\n'
|
f'Remote stream terminated due to "stop" msg\n'
|
||||||
|
f'\n'
|
||||||
f'{pretty_struct.pformat(msg)}\n'
|
f'{pretty_struct.pformat(msg)}\n'
|
||||||
)
|
)
|
||||||
continue
|
continue
|
||||||
|
@ -814,7 +829,8 @@ async def drain_to_final_msg(
|
||||||
|
|
||||||
else:
|
else:
|
||||||
log.cancel(
|
log.cancel(
|
||||||
'Skipping `MsgStream` drain since final outcome is set\n\n'
|
f'Skipping `MsgStream` drain since final outcome is set\n'
|
||||||
|
f'\n'
|
||||||
f'{ctx.outcome}\n'
|
f'{ctx.outcome}\n'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
@ -130,6 +130,7 @@ class LinkedTaskChannel(
|
||||||
_trio_task: trio.Task
|
_trio_task: trio.Task
|
||||||
_aio_task_complete: trio.Event
|
_aio_task_complete: trio.Event
|
||||||
|
|
||||||
|
_closed_by_aio_task: bool = False
|
||||||
_suppress_graceful_exits: bool = True
|
_suppress_graceful_exits: bool = True
|
||||||
|
|
||||||
_trio_err: BaseException|None = None
|
_trio_err: BaseException|None = None
|
||||||
|
@ -208,10 +209,15 @@ class LinkedTaskChannel(
|
||||||
async def aclose(self) -> None:
|
async def aclose(self) -> None:
|
||||||
await self._from_aio.aclose()
|
await self._from_aio.aclose()
|
||||||
|
|
||||||
def started(
|
# ?TODO? async version of this?
|
||||||
|
def started_nowait(
|
||||||
self,
|
self,
|
||||||
val: Any = None,
|
val: Any = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
|
'''
|
||||||
|
Synchronize aio-side with its trio-parent.
|
||||||
|
|
||||||
|
'''
|
||||||
self._aio_started_val = val
|
self._aio_started_val = val
|
||||||
return self._to_trio.send_nowait(val)
|
return self._to_trio.send_nowait(val)
|
||||||
|
|
||||||
|
@ -242,6 +248,7 @@ class LinkedTaskChannel(
|
||||||
# cycle on the trio side?
|
# cycle on the trio side?
|
||||||
# await trio.lowlevel.checkpoint()
|
# await trio.lowlevel.checkpoint()
|
||||||
return await self._from_aio.receive()
|
return await self._from_aio.receive()
|
||||||
|
|
||||||
except BaseException as err:
|
except BaseException as err:
|
||||||
async with translate_aio_errors(
|
async with translate_aio_errors(
|
||||||
chan=self,
|
chan=self,
|
||||||
|
@ -319,7 +326,7 @@ def _run_asyncio_task(
|
||||||
qsize: int = 1,
|
qsize: int = 1,
|
||||||
provide_channels: bool = False,
|
provide_channels: bool = False,
|
||||||
suppress_graceful_exits: bool = True,
|
suppress_graceful_exits: bool = True,
|
||||||
hide_tb: bool = False,
|
hide_tb: bool = True,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
|
|
||||||
) -> LinkedTaskChannel:
|
) -> LinkedTaskChannel:
|
||||||
|
@ -347,18 +354,6 @@ def _run_asyncio_task(
|
||||||
# value otherwise it would just return ;P
|
# value otherwise it would just return ;P
|
||||||
assert qsize > 1
|
assert qsize > 1
|
||||||
|
|
||||||
if provide_channels:
|
|
||||||
assert 'to_trio' in args
|
|
||||||
|
|
||||||
# allow target func to accept/stream results manually by name
|
|
||||||
if 'to_trio' in args:
|
|
||||||
kwargs['to_trio'] = to_trio
|
|
||||||
|
|
||||||
if 'from_trio' in args:
|
|
||||||
kwargs['from_trio'] = from_trio
|
|
||||||
|
|
||||||
coro = func(**kwargs)
|
|
||||||
|
|
||||||
trio_task: trio.Task = trio.lowlevel.current_task()
|
trio_task: trio.Task = trio.lowlevel.current_task()
|
||||||
trio_cs = trio.CancelScope()
|
trio_cs = trio.CancelScope()
|
||||||
aio_task_complete = trio.Event()
|
aio_task_complete = trio.Event()
|
||||||
|
@ -373,6 +368,25 @@ def _run_asyncio_task(
|
||||||
_suppress_graceful_exits=suppress_graceful_exits,
|
_suppress_graceful_exits=suppress_graceful_exits,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# allow target func to accept/stream results manually by name
|
||||||
|
if 'to_trio' in args:
|
||||||
|
kwargs['to_trio'] = to_trio
|
||||||
|
|
||||||
|
if 'from_trio' in args:
|
||||||
|
kwargs['from_trio'] = from_trio
|
||||||
|
|
||||||
|
if 'chan' in args:
|
||||||
|
kwargs['chan'] = chan
|
||||||
|
|
||||||
|
if provide_channels:
|
||||||
|
assert (
|
||||||
|
'to_trio' in args
|
||||||
|
or
|
||||||
|
'chan' in args
|
||||||
|
)
|
||||||
|
|
||||||
|
coro = func(**kwargs)
|
||||||
|
|
||||||
async def wait_on_coro_final_result(
|
async def wait_on_coro_final_result(
|
||||||
to_trio: trio.MemorySendChannel,
|
to_trio: trio.MemorySendChannel,
|
||||||
coro: Awaitable,
|
coro: Awaitable,
|
||||||
|
@ -445,9 +459,23 @@ def _run_asyncio_task(
|
||||||
f'Task exited with final result: {result!r}\n'
|
f'Task exited with final result: {result!r}\n'
|
||||||
)
|
)
|
||||||
|
|
||||||
# only close the sender side which will relay
|
# XXX ALWAYS close the child-`asyncio`-task-side's
|
||||||
# a `trio.EndOfChannel` to the trio (consumer) side.
|
# `to_trio` handle which will in turn relay
|
||||||
|
# a `trio.EndOfChannel` to the `trio`-parent.
|
||||||
|
# Consequently the parent `trio` task MUST ALWAYS
|
||||||
|
# check for any `chan._aio_err` to be raised when it
|
||||||
|
# receives an EoC.
|
||||||
|
#
|
||||||
|
# NOTE, there are 2 EoC cases,
|
||||||
|
# - normal/graceful EoC due to the aio-side actually
|
||||||
|
# terminating its "streaming", but the task did not
|
||||||
|
# error and is not yet complete.
|
||||||
|
#
|
||||||
|
# - the aio-task terminated and we specially mark the
|
||||||
|
# closure as due to the `asyncio.Task`'s exit.
|
||||||
|
#
|
||||||
to_trio.close()
|
to_trio.close()
|
||||||
|
chan._closed_by_aio_task = True
|
||||||
|
|
||||||
aio_task_complete.set()
|
aio_task_complete.set()
|
||||||
log.runtime(
|
log.runtime(
|
||||||
|
@ -645,8 +673,9 @@ def _run_asyncio_task(
|
||||||
not trio_cs.cancel_called
|
not trio_cs.cancel_called
|
||||||
):
|
):
|
||||||
log.cancel(
|
log.cancel(
|
||||||
f'Cancelling `trio` side due to aio-side src exc\n'
|
f'Cancelling trio-side due to aio-side src exc\n'
|
||||||
f'{curr_aio_err}\n'
|
f'\n'
|
||||||
|
f'{curr_aio_err!r}\n'
|
||||||
f'\n'
|
f'\n'
|
||||||
f'(c>\n'
|
f'(c>\n'
|
||||||
f' |_{trio_task}\n'
|
f' |_{trio_task}\n'
|
||||||
|
@ -758,6 +787,7 @@ async def translate_aio_errors(
|
||||||
aio_done_before_trio: bool = aio_task.done()
|
aio_done_before_trio: bool = aio_task.done()
|
||||||
assert aio_task
|
assert aio_task
|
||||||
trio_err: BaseException|None = None
|
trio_err: BaseException|None = None
|
||||||
|
eoc: trio.EndOfChannel|None = None
|
||||||
try:
|
try:
|
||||||
yield # back to one of the cross-loop apis
|
yield # back to one of the cross-loop apis
|
||||||
except trio.Cancelled as taskc:
|
except trio.Cancelled as taskc:
|
||||||
|
@ -789,12 +819,48 @@ async def translate_aio_errors(
|
||||||
# )
|
# )
|
||||||
# raise
|
# raise
|
||||||
|
|
||||||
# XXX always passthrough EoC since this translator is often
|
# XXX EoC is a special SIGNAL from the aio-side here!
|
||||||
# called from `LinkedTaskChannel.receive()` which we want
|
# There are 2 cases to handle:
|
||||||
# passthrough and further we have no special meaning for it in
|
# 1. the "EoC passthrough" case.
|
||||||
# terms of relaying errors or signals from the aio side!
|
# - the aio-task actually closed the channel "gracefully" and
|
||||||
except trio.EndOfChannel as eoc:
|
# the trio-task should unwind any ongoing channel
|
||||||
|
# iteration/receiving,
|
||||||
|
# |_this exc-translator wraps calls to `LinkedTaskChannel.receive()`
|
||||||
|
# in which case we want to relay the actual "end-of-chan" for
|
||||||
|
# iteration purposes.
|
||||||
|
#
|
||||||
|
# 2. relaying the "asyncio.Task termination" case.
|
||||||
|
# - if the aio-task terminates, maybe with an error, AND the
|
||||||
|
# `open_channel_from()` API was used, it will always signal
|
||||||
|
# that termination.
|
||||||
|
# |_`wait_on_coro_final_result()` always calls
|
||||||
|
# `to_trio.close()` when `provide_channels=True` so we need to
|
||||||
|
# always check if there is an aio-side exc which needs to be
|
||||||
|
# relayed to the parent trio side!
|
||||||
|
# |_in this case the special `chan._closed_by_aio_task` is
|
||||||
|
# ALWAYS set.
|
||||||
|
#
|
||||||
|
except trio.EndOfChannel as _eoc:
|
||||||
|
eoc = _eoc
|
||||||
|
if (
|
||||||
|
chan._closed_by_aio_task
|
||||||
|
and
|
||||||
|
aio_err
|
||||||
|
):
|
||||||
|
log.cancel(
|
||||||
|
f'The asyncio-child task terminated due to error\n'
|
||||||
|
f'{aio_err!r}\n'
|
||||||
|
)
|
||||||
|
chan._trio_to_raise = aio_err
|
||||||
trio_err = chan._trio_err = eoc
|
trio_err = chan._trio_err = eoc
|
||||||
|
#
|
||||||
|
# ?TODO?, raise something like a,
|
||||||
|
# chan._trio_to_raise = AsyncioErrored()
|
||||||
|
# BUT, with the tb rewritten to reflect the underlying
|
||||||
|
# call stack?
|
||||||
|
else:
|
||||||
|
trio_err = chan._trio_err = eoc
|
||||||
|
|
||||||
raise eoc
|
raise eoc
|
||||||
|
|
||||||
# NOTE ALSO SEE the matching note in the `cancel_trio()` asyncio
|
# NOTE ALSO SEE the matching note in the `cancel_trio()` asyncio
|
||||||
|
@ -1047,7 +1113,7 @@ async def translate_aio_errors(
|
||||||
#
|
#
|
||||||
if wait_on_aio_task:
|
if wait_on_aio_task:
|
||||||
await chan._aio_task_complete.wait()
|
await chan._aio_task_complete.wait()
|
||||||
log.info(
|
log.debug(
|
||||||
'asyncio-task is done and unblocked trio-side!\n'
|
'asyncio-task is done and unblocked trio-side!\n'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -1064,11 +1130,17 @@ async def translate_aio_errors(
|
||||||
trio_to_raise: (
|
trio_to_raise: (
|
||||||
AsyncioCancelled|
|
AsyncioCancelled|
|
||||||
AsyncioTaskExited|
|
AsyncioTaskExited|
|
||||||
|
Exception| # relayed from aio-task
|
||||||
None
|
None
|
||||||
) = chan._trio_to_raise
|
) = chan._trio_to_raise
|
||||||
|
|
||||||
|
raise_from: Exception = (
|
||||||
|
trio_err if (aio_err is trio_to_raise)
|
||||||
|
else aio_err
|
||||||
|
)
|
||||||
|
|
||||||
if not suppress_graceful_exits:
|
if not suppress_graceful_exits:
|
||||||
raise trio_to_raise from (aio_err or trio_err)
|
raise trio_to_raise from raise_from
|
||||||
|
|
||||||
if trio_to_raise:
|
if trio_to_raise:
|
||||||
match (
|
match (
|
||||||
|
@ -1101,7 +1173,7 @@ async def translate_aio_errors(
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
case _:
|
case _:
|
||||||
raise trio_to_raise from (aio_err or trio_err)
|
raise trio_to_raise from raise_from
|
||||||
|
|
||||||
# Check if the asyncio-side is the cause of the trio-side
|
# Check if the asyncio-side is the cause of the trio-side
|
||||||
# error.
|
# error.
|
||||||
|
@ -1167,7 +1239,6 @@ async def run_task(
|
||||||
|
|
||||||
@acm
|
@acm
|
||||||
async def open_channel_from(
|
async def open_channel_from(
|
||||||
|
|
||||||
target: Callable[..., Any],
|
target: Callable[..., Any],
|
||||||
suppress_graceful_exits: bool = True,
|
suppress_graceful_exits: bool = True,
|
||||||
**target_kwargs,
|
**target_kwargs,
|
||||||
|
@ -1201,7 +1272,6 @@ async def open_channel_from(
|
||||||
# deliver stream handle upward
|
# deliver stream handle upward
|
||||||
yield first, chan
|
yield first, chan
|
||||||
except trio.Cancelled as taskc:
|
except trio.Cancelled as taskc:
|
||||||
# await tractor.pause(shield=True) # ya it worx ;)
|
|
||||||
if cs.cancel_called:
|
if cs.cancel_called:
|
||||||
if isinstance(chan._trio_to_raise, AsyncioCancelled):
|
if isinstance(chan._trio_to_raise, AsyncioCancelled):
|
||||||
log.cancel(
|
log.cancel(
|
||||||
|
|
|
@ -31,7 +31,7 @@ from ._broadcast import (
|
||||||
)
|
)
|
||||||
from ._beg import (
|
from ._beg import (
|
||||||
collapse_eg as collapse_eg,
|
collapse_eg as collapse_eg,
|
||||||
maybe_collapse_eg as maybe_collapse_eg,
|
get_collapsed_eg as get_collapsed_eg,
|
||||||
is_multi_cancelled as is_multi_cancelled,
|
is_multi_cancelled as is_multi_cancelled,
|
||||||
)
|
)
|
||||||
from ._taskc import (
|
from ._taskc import (
|
||||||
|
|
|
@ -15,8 +15,9 @@
|
||||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
`BaseExceptionGroup` related utils and helpers pertaining to
|
`BaseExceptionGroup` utils and helpers pertaining to
|
||||||
first-class-`trio` from a historical perspective B)
|
first-class-`trio` from a "historical" perspective, like "loose
|
||||||
|
exception group" task-nurseries.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
from contextlib import (
|
from contextlib import (
|
||||||
|
@ -24,28 +25,83 @@ from contextlib import (
|
||||||
)
|
)
|
||||||
from typing import (
|
from typing import (
|
||||||
Literal,
|
Literal,
|
||||||
|
Type,
|
||||||
)
|
)
|
||||||
|
|
||||||
import trio
|
import trio
|
||||||
|
# from trio._core._concat_tb import (
|
||||||
|
# concat_tb,
|
||||||
|
# )
|
||||||
|
|
||||||
|
|
||||||
def maybe_collapse_eg(
|
# XXX NOTE
|
||||||
|
# taken verbatim from `trio._core._run` except,
|
||||||
|
# - remove the NONSTRICT_EXCEPTIONGROUP_NOTE deprecation-note
|
||||||
|
# guard-check; we know we want an explicit collapse.
|
||||||
|
# - mask out tb rewriting in collapse case, i don't think it really
|
||||||
|
# matters?
|
||||||
|
#
|
||||||
|
def collapse_exception_group(
|
||||||
|
excgroup: BaseExceptionGroup[BaseException],
|
||||||
|
) -> BaseException:
|
||||||
|
"""Recursively collapse any single-exception groups into that single contained
|
||||||
|
exception.
|
||||||
|
|
||||||
|
"""
|
||||||
|
exceptions = list(excgroup.exceptions)
|
||||||
|
modified = False
|
||||||
|
for i, exc in enumerate(exceptions):
|
||||||
|
if isinstance(exc, BaseExceptionGroup):
|
||||||
|
new_exc = collapse_exception_group(exc)
|
||||||
|
if new_exc is not exc:
|
||||||
|
modified = True
|
||||||
|
exceptions[i] = new_exc
|
||||||
|
|
||||||
|
if (
|
||||||
|
len(exceptions) == 1
|
||||||
|
and isinstance(excgroup, BaseExceptionGroup)
|
||||||
|
|
||||||
|
# XXX trio's loose-setting condition..
|
||||||
|
# and NONSTRICT_EXCEPTIONGROUP_NOTE in getattr(excgroup, "__notes__", ())
|
||||||
|
):
|
||||||
|
# exceptions[0].__traceback__ = concat_tb(
|
||||||
|
# excgroup.__traceback__,
|
||||||
|
# exceptions[0].__traceback__,
|
||||||
|
# )
|
||||||
|
return exceptions[0]
|
||||||
|
elif modified:
|
||||||
|
return excgroup.derive(exceptions)
|
||||||
|
else:
|
||||||
|
return excgroup
|
||||||
|
|
||||||
|
|
||||||
|
def get_collapsed_eg(
|
||||||
beg: BaseExceptionGroup,
|
beg: BaseExceptionGroup,
|
||||||
) -> BaseException|bool:
|
|
||||||
|
) -> BaseException|None:
|
||||||
'''
|
'''
|
||||||
If the input beg can collapse to a single non-eg sub-exception,
|
If the input beg can collapse to a single sub-exception which is
|
||||||
return it instead.
|
itself **not** an eg, return it.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
if len(excs := beg.exceptions) == 1:
|
maybe_exc = collapse_exception_group(beg)
|
||||||
return excs[0]
|
if maybe_exc is beg:
|
||||||
|
return None
|
||||||
|
|
||||||
return False
|
return maybe_exc
|
||||||
|
|
||||||
|
|
||||||
@acm
|
@acm
|
||||||
async def collapse_eg(
|
async def collapse_eg(
|
||||||
hide_tb: bool = True,
|
hide_tb: bool = True,
|
||||||
|
|
||||||
|
# XXX, for ex. will always show begs containing single taskc
|
||||||
|
ignore: set[Type[BaseException]] = {
|
||||||
|
# trio.Cancelled,
|
||||||
|
},
|
||||||
|
add_notes: bool = True,
|
||||||
|
|
||||||
|
bp: bool = False,
|
||||||
):
|
):
|
||||||
'''
|
'''
|
||||||
If `BaseExceptionGroup` raised in the body scope is
|
If `BaseExceptionGroup` raised in the body scope is
|
||||||
|
@ -57,16 +113,55 @@ async def collapse_eg(
|
||||||
__tracebackhide__: bool = hide_tb
|
__tracebackhide__: bool = hide_tb
|
||||||
try:
|
try:
|
||||||
yield
|
yield
|
||||||
except* BaseException as beg:
|
except BaseExceptionGroup as _beg:
|
||||||
|
beg = _beg
|
||||||
|
|
||||||
if (
|
if (
|
||||||
exc := maybe_collapse_eg(beg)
|
bp
|
||||||
|
and
|
||||||
|
len(beg.exceptions) > 1
|
||||||
):
|
):
|
||||||
|
import tractor
|
||||||
|
if tractor.current_actor(
|
||||||
|
err_on_no_runtime=False,
|
||||||
|
):
|
||||||
|
await tractor.pause(shield=True)
|
||||||
|
else:
|
||||||
|
breakpoint()
|
||||||
|
|
||||||
|
if (
|
||||||
|
(exc := get_collapsed_eg(beg))
|
||||||
|
and
|
||||||
|
type(exc) not in ignore
|
||||||
|
):
|
||||||
|
|
||||||
|
# TODO? report number of nested groups it was collapsed
|
||||||
|
# *from*?
|
||||||
|
if add_notes:
|
||||||
|
from_group_note: str = (
|
||||||
|
'( ^^^ this exc was collapsed from a group ^^^ )\n'
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
from_group_note
|
||||||
|
not in
|
||||||
|
getattr(exc, "__notes__", ())
|
||||||
|
):
|
||||||
|
exc.add_note(from_group_note)
|
||||||
|
|
||||||
|
# raise exc
|
||||||
|
# ^^ this will leave the orig beg tb above with the
|
||||||
|
# "during the handling of <beg> the following.."
|
||||||
|
# So, instead do..
|
||||||
|
#
|
||||||
if cause := exc.__cause__:
|
if cause := exc.__cause__:
|
||||||
raise exc from cause
|
raise exc from cause
|
||||||
|
else:
|
||||||
|
# suppress "during handling of <the beg>"
|
||||||
|
# output in tb/console.
|
||||||
|
raise exc from None
|
||||||
|
|
||||||
raise exc
|
# keep original
|
||||||
|
raise # beg
|
||||||
raise beg
|
|
||||||
|
|
||||||
|
|
||||||
def is_multi_cancelled(
|
def is_multi_cancelled(
|
||||||
|
|
|
@ -31,7 +31,6 @@ from typing import (
|
||||||
AsyncIterator,
|
AsyncIterator,
|
||||||
Callable,
|
Callable,
|
||||||
Hashable,
|
Hashable,
|
||||||
Optional,
|
|
||||||
Sequence,
|
Sequence,
|
||||||
TypeVar,
|
TypeVar,
|
||||||
TYPE_CHECKING,
|
TYPE_CHECKING,
|
||||||
|
@ -40,7 +39,10 @@ from typing import (
|
||||||
import trio
|
import trio
|
||||||
from tractor._state import current_actor
|
from tractor._state import current_actor
|
||||||
from tractor.log import get_logger
|
from tractor.log import get_logger
|
||||||
from ._beg import collapse_eg
|
# from ._beg import collapse_eg
|
||||||
|
# from ._taskc import (
|
||||||
|
# maybe_raise_from_masking_exc,
|
||||||
|
# )
|
||||||
|
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
|
@ -72,6 +74,7 @@ async def maybe_open_nursery(
|
||||||
yield nursery
|
yield nursery
|
||||||
else:
|
else:
|
||||||
async with lib.open_nursery(**kwargs) as nursery:
|
async with lib.open_nursery(**kwargs) as nursery:
|
||||||
|
if lib == trio:
|
||||||
nursery.cancel_scope.shield = shield
|
nursery.cancel_scope.shield = shield
|
||||||
yield nursery
|
yield nursery
|
||||||
|
|
||||||
|
@ -105,6 +108,9 @@ async def _enter_and_wait(
|
||||||
async def gather_contexts(
|
async def gather_contexts(
|
||||||
mngrs: Sequence[AsyncContextManager[T]],
|
mngrs: Sequence[AsyncContextManager[T]],
|
||||||
|
|
||||||
|
# caller can provide their own scope
|
||||||
|
tn: trio.Nursery|None = None,
|
||||||
|
|
||||||
) -> AsyncGenerator[
|
) -> AsyncGenerator[
|
||||||
tuple[
|
tuple[
|
||||||
T | None,
|
T | None,
|
||||||
|
@ -147,12 +153,22 @@ async def gather_contexts(
|
||||||
'`.trionics.gather_contexts()` input mngrs is empty?\n'
|
'`.trionics.gather_contexts()` input mngrs is empty?\n'
|
||||||
'\n'
|
'\n'
|
||||||
'Did try to use inline generator syntax?\n'
|
'Did try to use inline generator syntax?\n'
|
||||||
'Use a non-lazy iterator or sequence-type intead!\n'
|
'Check that list({mngrs}) works!\n'
|
||||||
|
# 'or sequence-type intead!\n'
|
||||||
|
# 'Use a non-lazy iterator or sequence-type intead!\n'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
async with (
|
async with (
|
||||||
collapse_eg(),
|
#
|
||||||
trio.open_nursery() as tn,
|
# ?TODO, does including these (eg-collapsing,
|
||||||
|
# taskc-unmasking) improve tb noise-reduction/legibility?
|
||||||
|
#
|
||||||
|
# collapse_eg(),
|
||||||
|
maybe_open_nursery(
|
||||||
|
nursery=tn,
|
||||||
|
) as tn,
|
||||||
|
# maybe_raise_from_masking_exc(),
|
||||||
):
|
):
|
||||||
for mngr in mngrs:
|
for mngr in mngrs:
|
||||||
tn.start_soon(
|
tn.start_soon(
|
||||||
|
@ -164,11 +180,12 @@ async def gather_contexts(
|
||||||
seed,
|
seed,
|
||||||
)
|
)
|
||||||
|
|
||||||
# deliver control once all managers have started up
|
# deliver control to caller once all ctx-managers have
|
||||||
|
# started (yielded back to us).
|
||||||
await all_entered.wait()
|
await all_entered.wait()
|
||||||
|
|
||||||
try:
|
|
||||||
yield tuple(unwrapped.values())
|
yield tuple(unwrapped.values())
|
||||||
|
parent_exit.set()
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
# XXX NOTE: this is ABSOLUTELY REQUIRED to avoid
|
# XXX NOTE: this is ABSOLUTELY REQUIRED to avoid
|
||||||
# the following wacky bug:
|
# the following wacky bug:
|
||||||
|
@ -186,7 +203,7 @@ class _Cache:
|
||||||
a kept-alive-while-in-use async resource.
|
a kept-alive-while-in-use async resource.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
service_n: Optional[trio.Nursery] = None
|
service_tn: trio.Nursery|None = None
|
||||||
locks: dict[Hashable, trio.Lock] = {}
|
locks: dict[Hashable, trio.Lock] = {}
|
||||||
users: int = 0
|
users: int = 0
|
||||||
values: dict[Any, Any] = {}
|
values: dict[Any, Any] = {}
|
||||||
|
@ -195,7 +212,7 @@ class _Cache:
|
||||||
tuple[trio.Nursery, trio.Event]
|
tuple[trio.Nursery, trio.Event]
|
||||||
] = {}
|
] = {}
|
||||||
# nurseries: dict[int, trio.Nursery] = {}
|
# nurseries: dict[int, trio.Nursery] = {}
|
||||||
no_more_users: Optional[trio.Event] = None
|
no_more_users: trio.Event|None = None
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def run_ctx(
|
async def run_ctx(
|
||||||
|
@ -205,15 +222,17 @@ class _Cache:
|
||||||
task_status: trio.TaskStatus[T] = trio.TASK_STATUS_IGNORED,
|
task_status: trio.TaskStatus[T] = trio.TASK_STATUS_IGNORED,
|
||||||
|
|
||||||
) -> None:
|
) -> None:
|
||||||
|
try:
|
||||||
async with mng as value:
|
async with mng as value:
|
||||||
_, no_more_users = cls.resources[ctx_key]
|
_, no_more_users = cls.resources[ctx_key]
|
||||||
|
try:
|
||||||
cls.values[ctx_key] = value
|
cls.values[ctx_key] = value
|
||||||
task_status.started(value)
|
task_status.started(value)
|
||||||
try:
|
|
||||||
await no_more_users.wait()
|
await no_more_users.wait()
|
||||||
finally:
|
finally:
|
||||||
# discard nursery ref so it won't be re-used (an error)?
|
|
||||||
value = cls.values.pop(ctx_key)
|
value = cls.values.pop(ctx_key)
|
||||||
|
finally:
|
||||||
|
# discard nursery ref so it won't be re-used (an error)?
|
||||||
cls.resources.pop(ctx_key)
|
cls.resources.pop(ctx_key)
|
||||||
|
|
||||||
|
|
||||||
|
@ -227,6 +246,9 @@ async def maybe_open_context(
|
||||||
kwargs: dict = {},
|
kwargs: dict = {},
|
||||||
key: Hashable | Callable[..., Hashable] = None,
|
key: Hashable | Callable[..., Hashable] = None,
|
||||||
|
|
||||||
|
# caller can provide their own scope
|
||||||
|
tn: trio.Nursery|None = None,
|
||||||
|
|
||||||
) -> AsyncIterator[tuple[bool, T]]:
|
) -> AsyncIterator[tuple[bool, T]]:
|
||||||
'''
|
'''
|
||||||
Maybe open an async-context-manager (acm) if there is not already
|
Maybe open an async-context-manager (acm) if there is not already
|
||||||
|
@ -259,40 +281,94 @@ async def maybe_open_context(
|
||||||
# have it not be closed until all consumers have exited (which is
|
# have it not be closed until all consumers have exited (which is
|
||||||
# currently difficult to implement any other way besides using our
|
# currently difficult to implement any other way besides using our
|
||||||
# pre-allocated runtime instance..)
|
# pre-allocated runtime instance..)
|
||||||
service_n: trio.Nursery = current_actor()._service_n
|
if tn:
|
||||||
|
# TODO, assert tn is eventual parent of this task!
|
||||||
|
task: trio.Task = trio.lowlevel.current_task()
|
||||||
|
task_tn: trio.Nursery = task.parent_nursery
|
||||||
|
if not tn._cancel_status.encloses(
|
||||||
|
task_tn._cancel_status
|
||||||
|
):
|
||||||
|
raise RuntimeError(
|
||||||
|
f'Mis-nesting of task under provided {tn} !?\n'
|
||||||
|
f'Current task is NOT a child(-ish)!!\n'
|
||||||
|
f'\n'
|
||||||
|
f'task: {task}\n'
|
||||||
|
f'task_tn: {task_tn}\n'
|
||||||
|
)
|
||||||
|
service_tn = tn
|
||||||
|
else:
|
||||||
|
service_tn: trio.Nursery = current_actor()._service_tn
|
||||||
|
|
||||||
# TODO: is there any way to allocate
|
# TODO: is there any way to allocate
|
||||||
# a 'stays-open-till-last-task-finshed nursery?
|
# a 'stays-open-till-last-task-finshed nursery?
|
||||||
# service_n: trio.Nursery
|
# service_tn: trio.Nursery
|
||||||
# async with maybe_open_nursery(_Cache.service_n) as service_n:
|
# async with maybe_open_nursery(_Cache.service_tn) as service_tn:
|
||||||
# _Cache.service_n = service_n
|
# _Cache.service_tn = service_tn
|
||||||
|
|
||||||
|
cache_miss_ke: KeyError|None = None
|
||||||
|
maybe_taskc: trio.Cancelled|None = None
|
||||||
try:
|
try:
|
||||||
# **critical section** that should prevent other tasks from
|
# **critical section** that should prevent other tasks from
|
||||||
# checking the _Cache until complete otherwise the scheduler
|
# checking the _Cache until complete otherwise the scheduler
|
||||||
# may switch and by accident we create more then one resource.
|
# may switch and by accident we create more then one resource.
|
||||||
yielded = _Cache.values[ctx_key]
|
yielded = _Cache.values[ctx_key]
|
||||||
|
|
||||||
except KeyError:
|
except KeyError as _ke:
|
||||||
log.debug(f'Allocating new {acm_func} for {ctx_key}')
|
# XXX, stay mutexed up to cache-miss yield
|
||||||
|
try:
|
||||||
|
cache_miss_ke = _ke
|
||||||
|
log.debug(
|
||||||
|
f'Allocating new @acm-func entry\n'
|
||||||
|
f'ctx_key={ctx_key}\n'
|
||||||
|
f'acm_func={acm_func}\n'
|
||||||
|
)
|
||||||
mngr = acm_func(**kwargs)
|
mngr = acm_func(**kwargs)
|
||||||
resources = _Cache.resources
|
resources = _Cache.resources
|
||||||
assert not resources.get(ctx_key), f'Resource exists? {ctx_key}'
|
assert not resources.get(ctx_key), f'Resource exists? {ctx_key}'
|
||||||
resources[ctx_key] = (service_n, trio.Event())
|
resources[ctx_key] = (service_tn, trio.Event())
|
||||||
|
yielded: Any = await service_tn.start(
|
||||||
# sync up to the mngr's yielded value
|
|
||||||
yielded = await service_n.start(
|
|
||||||
_Cache.run_ctx,
|
_Cache.run_ctx,
|
||||||
mngr,
|
mngr,
|
||||||
ctx_key,
|
ctx_key,
|
||||||
)
|
)
|
||||||
_Cache.users += 1
|
_Cache.users += 1
|
||||||
|
finally:
|
||||||
|
# XXX, since this runs from an `except` it's a checkpoint
|
||||||
|
# whih can be `trio.Cancelled`-masked.
|
||||||
|
#
|
||||||
|
# NOTE, in that case the mutex is never released by the
|
||||||
|
# (first and) caching task and **we can't** simply shield
|
||||||
|
# bc that will inf-block on the `await
|
||||||
|
# no_more_users.wait()`.
|
||||||
|
#
|
||||||
|
# SO just always unlock!
|
||||||
lock.release()
|
lock.release()
|
||||||
yield False, yielded
|
|
||||||
|
try:
|
||||||
|
yield (
|
||||||
|
False, # cache_hit = "no"
|
||||||
|
yielded,
|
||||||
|
)
|
||||||
|
except trio.Cancelled as taskc:
|
||||||
|
maybe_taskc = taskc
|
||||||
|
log.cancel(
|
||||||
|
f'Cancelled from cache-miss entry\n'
|
||||||
|
f'\n'
|
||||||
|
f'ctx_key: {ctx_key!r}\n'
|
||||||
|
f'mngr: {mngr!r}\n'
|
||||||
|
)
|
||||||
|
# XXX, always unset ke from cancelled context
|
||||||
|
# since we never consider it a masked exc case!
|
||||||
|
# - bc this can be called directly ty `._rpc._invoke()`?
|
||||||
|
#
|
||||||
|
if maybe_taskc.__context__ is cache_miss_ke:
|
||||||
|
maybe_taskc.__context__ = None
|
||||||
|
|
||||||
|
raise taskc
|
||||||
|
|
||||||
else:
|
else:
|
||||||
_Cache.users += 1
|
_Cache.users += 1
|
||||||
log.runtime(
|
log.debug(
|
||||||
f'Re-using cached resource for user {_Cache.users}\n\n'
|
f'Re-using cached resource for user {_Cache.users}\n\n'
|
||||||
f'{ctx_key!r} -> {type(yielded)}\n'
|
f'{ctx_key!r} -> {type(yielded)}\n'
|
||||||
|
|
||||||
|
@ -302,9 +378,19 @@ async def maybe_open_context(
|
||||||
# f'{ctx_key!r} -> {yielded!r}\n'
|
# f'{ctx_key!r} -> {yielded!r}\n'
|
||||||
)
|
)
|
||||||
lock.release()
|
lock.release()
|
||||||
yield True, yielded
|
yield (
|
||||||
|
True, # cache_hit = "yes"
|
||||||
|
yielded,
|
||||||
|
)
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
|
if lock.locked():
|
||||||
|
stats: trio.LockStatistics = lock.statistics()
|
||||||
|
log.error(
|
||||||
|
f'Lock left locked by last owner !?\n'
|
||||||
|
f'{stats}\n'
|
||||||
|
)
|
||||||
|
|
||||||
_Cache.users -= 1
|
_Cache.users -= 1
|
||||||
|
|
||||||
if yielded is not None:
|
if yielded is not None:
|
||||||
|
|
|
@ -22,7 +22,14 @@ from __future__ import annotations
|
||||||
from contextlib import (
|
from contextlib import (
|
||||||
asynccontextmanager as acm,
|
asynccontextmanager as acm,
|
||||||
)
|
)
|
||||||
from typing import TYPE_CHECKING
|
import inspect
|
||||||
|
from types import (
|
||||||
|
TracebackType,
|
||||||
|
)
|
||||||
|
from typing import (
|
||||||
|
Type,
|
||||||
|
TYPE_CHECKING,
|
||||||
|
)
|
||||||
|
|
||||||
import trio
|
import trio
|
||||||
from tractor.log import get_logger
|
from tractor.log import get_logger
|
||||||
|
@ -60,12 +67,71 @@ def find_masked_excs(
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
# XXX, relevant ish discussion @ `trio`-core,
|
_mask_cases: dict[
|
||||||
# https://github.com/python-trio/trio/issues/455#issuecomment-2785122216
|
Type[Exception], # masked exc type
|
||||||
|
dict[
|
||||||
|
int, # inner-frame index into `inspect.getinnerframes()`
|
||||||
|
# `FrameInfo.function/filename: str`s to match
|
||||||
|
dict[str, str],
|
||||||
|
],
|
||||||
|
] = {
|
||||||
|
trio.WouldBlock: {
|
||||||
|
# `trio.Lock.acquire()` has a checkpoint inside the
|
||||||
|
# `WouldBlock`-no_wait path's handler..
|
||||||
|
-5: { # "5th frame up" from checkpoint
|
||||||
|
'filename': 'trio/_sync.py',
|
||||||
|
'function': 'acquire',
|
||||||
|
# 'lineno': 605, # matters?
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def is_expected_masking_case(
|
||||||
|
cases: dict,
|
||||||
|
exc_ctx: Exception,
|
||||||
|
exc_match: BaseException,
|
||||||
|
|
||||||
|
) -> bool|inspect.FrameInfo:
|
||||||
|
'''
|
||||||
|
Determine whether the provided masked exception is from a known
|
||||||
|
bug/special/unintentional-`trio`-impl case which we do not wish
|
||||||
|
to unmask.
|
||||||
|
|
||||||
|
Return any guilty `inspect.FrameInfo` ow `False`.
|
||||||
|
|
||||||
|
'''
|
||||||
|
exc_tb: TracebackType = exc_match.__traceback__
|
||||||
|
if cases := _mask_cases.get(type(exc_ctx)):
|
||||||
|
inner: list[inspect.FrameInfo] = inspect.getinnerframes(exc_tb)
|
||||||
|
|
||||||
|
# from tractor.devx.debug import mk_pdb
|
||||||
|
# mk_pdb().set_trace()
|
||||||
|
for iframe, matchon in cases.items():
|
||||||
|
try:
|
||||||
|
masker_frame: inspect.FrameInfo = inner[iframe]
|
||||||
|
except IndexError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for field, in_field in matchon.items():
|
||||||
|
val = getattr(
|
||||||
|
masker_frame,
|
||||||
|
field,
|
||||||
|
)
|
||||||
|
if in_field not in val:
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
return masker_frame
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# XXX, relevant discussion @ `trio`-core,
|
||||||
|
# https://github.com/python-trio/trio/issues/455
|
||||||
#
|
#
|
||||||
@acm
|
@acm
|
||||||
async def maybe_raise_from_masking_exc(
|
async def maybe_raise_from_masking_exc(
|
||||||
tn: trio.Nursery|None = None,
|
|
||||||
unmask_from: (
|
unmask_from: (
|
||||||
BaseException|
|
BaseException|
|
||||||
tuple[BaseException]
|
tuple[BaseException]
|
||||||
|
@ -74,18 +140,30 @@ async def maybe_raise_from_masking_exc(
|
||||||
raise_unmasked: bool = True,
|
raise_unmasked: bool = True,
|
||||||
extra_note: str = (
|
extra_note: str = (
|
||||||
'This can occurr when,\n'
|
'This can occurr when,\n'
|
||||||
' - a `trio.Nursery` scope embeds a `finally:`-block '
|
'\n'
|
||||||
'which executes a checkpoint!'
|
' - a `trio.Nursery/CancelScope` embeds a `finally/except:`-block '
|
||||||
|
'which execs an un-shielded checkpoint!'
|
||||||
#
|
#
|
||||||
# ^TODO? other cases?
|
# ^TODO? other cases?
|
||||||
),
|
),
|
||||||
|
|
||||||
always_warn_on: tuple[BaseException] = (
|
always_warn_on: tuple[Type[BaseException]] = (
|
||||||
trio.Cancelled,
|
trio.Cancelled,
|
||||||
),
|
),
|
||||||
|
|
||||||
|
# don't ever unmask or warn on any masking pair,
|
||||||
|
# {<masked-excT-key> -> <masking-excT-value>}
|
||||||
|
never_warn_on: dict[
|
||||||
|
Type[BaseException],
|
||||||
|
Type[BaseException],
|
||||||
|
] = {
|
||||||
|
KeyboardInterrupt: trio.Cancelled,
|
||||||
|
trio.Cancelled: trio.Cancelled,
|
||||||
|
},
|
||||||
# ^XXX, special case(s) where we warn-log bc likely
|
# ^XXX, special case(s) where we warn-log bc likely
|
||||||
# there will be no operational diff since the exc
|
# there will be no operational diff since the exc
|
||||||
# is always expected to be consumed.
|
# is always expected to be consumed.
|
||||||
|
|
||||||
) -> BoxedMaybeException:
|
) -> BoxedMaybeException:
|
||||||
'''
|
'''
|
||||||
Maybe un-mask and re-raise exception(s) suppressed by a known
|
Maybe un-mask and re-raise exception(s) suppressed by a known
|
||||||
|
@ -104,82 +182,112 @@ async def maybe_raise_from_masking_exc(
|
||||||
individual sub-excs but maintain the eg-parent's form right?
|
individual sub-excs but maintain the eg-parent's form right?
|
||||||
|
|
||||||
'''
|
'''
|
||||||
|
if not isinstance(unmask_from, tuple):
|
||||||
|
raise ValueError(
|
||||||
|
f'Invalid unmask_from = {unmask_from!r}\n'
|
||||||
|
f'Must be a `tuple[Type[BaseException]]`.\n'
|
||||||
|
)
|
||||||
|
|
||||||
from tractor.devx.debug import (
|
from tractor.devx.debug import (
|
||||||
BoxedMaybeException,
|
BoxedMaybeException,
|
||||||
pause,
|
|
||||||
)
|
)
|
||||||
boxed_maybe_exc = BoxedMaybeException(
|
boxed_maybe_exc = BoxedMaybeException(
|
||||||
raise_on_exit=raise_unmasked,
|
raise_on_exit=raise_unmasked,
|
||||||
)
|
)
|
||||||
matching: list[BaseException]|None = None
|
matching: list[BaseException]|None = None
|
||||||
maybe_eg: ExceptionGroup|None
|
try:
|
||||||
maybe_eg: ExceptionGroup|None
|
|
||||||
|
|
||||||
if tn:
|
|
||||||
try: # handle egs
|
|
||||||
yield boxed_maybe_exc
|
yield boxed_maybe_exc
|
||||||
return
|
return
|
||||||
except* unmask_from as _maybe_eg:
|
except BaseException as _bexc:
|
||||||
maybe_eg = _maybe_eg
|
bexc = _bexc
|
||||||
|
if isinstance(bexc, BaseExceptionGroup):
|
||||||
matches: ExceptionGroup
|
matches: ExceptionGroup
|
||||||
matches, _ = maybe_eg.split(
|
matches, _ = bexc.split(unmask_from)
|
||||||
|
if matches:
|
||||||
|
matching = matches.exceptions
|
||||||
|
|
||||||
|
elif (
|
||||||
unmask_from
|
unmask_from
|
||||||
)
|
and
|
||||||
if not matches:
|
type(bexc) in unmask_from
|
||||||
raise
|
):
|
||||||
|
matching = [bexc]
|
||||||
matching: list[BaseException] = matches.exceptions
|
|
||||||
else:
|
|
||||||
try: # handle non-egs
|
|
||||||
yield boxed_maybe_exc
|
|
||||||
return
|
|
||||||
except unmask_from as _maybe_exc:
|
|
||||||
maybe_exc = _maybe_exc
|
|
||||||
matching: list[BaseException] = [
|
|
||||||
maybe_exc
|
|
||||||
]
|
|
||||||
|
|
||||||
# XXX, only unmask-ed for debuggin!
|
|
||||||
# TODO, remove eventually..
|
|
||||||
except BaseException as _berr:
|
|
||||||
berr = _berr
|
|
||||||
await pause(shield=True)
|
|
||||||
raise berr
|
|
||||||
|
|
||||||
if matching is None:
|
if matching is None:
|
||||||
raise
|
raise
|
||||||
|
|
||||||
masked: list[tuple[BaseException, BaseException]] = []
|
masked: list[tuple[BaseException, BaseException]] = []
|
||||||
for exc_match in matching:
|
for exc_match in matching:
|
||||||
|
|
||||||
if exc_ctx := find_masked_excs(
|
if exc_ctx := find_masked_excs(
|
||||||
maybe_masker=exc_match,
|
maybe_masker=exc_match,
|
||||||
unmask_from={unmask_from},
|
unmask_from=set(unmask_from),
|
||||||
):
|
):
|
||||||
masked.append((exc_ctx, exc_match))
|
masked.append((
|
||||||
|
exc_ctx,
|
||||||
|
exc_match,
|
||||||
|
))
|
||||||
boxed_maybe_exc.value = exc_match
|
boxed_maybe_exc.value = exc_match
|
||||||
note: str = (
|
note: str = (
|
||||||
f'\n'
|
f'\n'
|
||||||
f'^^WARNING^^ the above {exc_ctx!r} was masked by a {unmask_from!r}\n'
|
f'^^WARNING^^\n'
|
||||||
|
f'the above {type(exc_ctx)!r} was masked by a {type(exc_match)!r}\n'
|
||||||
)
|
)
|
||||||
if extra_note:
|
if extra_note:
|
||||||
note += (
|
note += (
|
||||||
f'\n'
|
f'\n'
|
||||||
f'{extra_note}\n'
|
f'{extra_note}\n'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
do_warn: bool = (
|
||||||
|
never_warn_on.get(
|
||||||
|
type(exc_ctx) # masking type
|
||||||
|
)
|
||||||
|
is not
|
||||||
|
type(exc_match) # masked type
|
||||||
|
)
|
||||||
|
|
||||||
|
if do_warn:
|
||||||
exc_ctx.add_note(note)
|
exc_ctx.add_note(note)
|
||||||
|
|
||||||
if type(exc_match) in always_warn_on:
|
if (
|
||||||
|
do_warn
|
||||||
|
and
|
||||||
|
type(exc_match) in always_warn_on
|
||||||
|
):
|
||||||
log.warning(note)
|
log.warning(note)
|
||||||
|
|
||||||
# await tractor.pause(shield=True)
|
if (
|
||||||
if raise_unmasked:
|
do_warn
|
||||||
|
and
|
||||||
|
raise_unmasked
|
||||||
|
):
|
||||||
if len(masked) < 2:
|
if len(masked) < 2:
|
||||||
|
# don't unmask already known "special" cases..
|
||||||
|
if (
|
||||||
|
_mask_cases
|
||||||
|
and
|
||||||
|
(cases := _mask_cases.get(type(exc_ctx)))
|
||||||
|
and
|
||||||
|
(masker_frame := is_expected_masking_case(
|
||||||
|
cases,
|
||||||
|
exc_ctx,
|
||||||
|
exc_match,
|
||||||
|
))
|
||||||
|
):
|
||||||
|
log.warning(
|
||||||
|
f'Ignoring already-known, non-ideal-but-valid '
|
||||||
|
f'masker code @\n'
|
||||||
|
f'{masker_frame}\n'
|
||||||
|
f'\n'
|
||||||
|
f'NOT raising {exc_ctx} from masker {exc_match!r}\n'
|
||||||
|
)
|
||||||
|
raise exc_match
|
||||||
|
|
||||||
raise exc_ctx from exc_match
|
raise exc_ctx from exc_match
|
||||||
else:
|
|
||||||
# ?TODO, see above but, possibly unmasking sub-exc
|
# ??TODO, see above but, possibly unmasking sub-exc
|
||||||
# entries if there are > 1
|
# entries if there are > 1
|
||||||
await pause(shield=True)
|
# else:
|
||||||
|
# await pause(shield=True)
|
||||||
else:
|
else:
|
||||||
raise
|
raise
|
||||||
|
|
8
uv.lock
8
uv.lock
|
@ -417,7 +417,7 @@ dev = [
|
||||||
{ name = "pyperclip", specifier = ">=1.9.0" },
|
{ name = "pyperclip", specifier = ">=1.9.0" },
|
||||||
{ name = "pytest", specifier = ">=8.3.5" },
|
{ name = "pytest", specifier = ">=8.3.5" },
|
||||||
{ name = "stackscope", specifier = ">=0.2.2,<0.3" },
|
{ name = "stackscope", specifier = ">=0.2.2,<0.3" },
|
||||||
{ name = "typing-extensions", specifier = ">=4.13.2" },
|
{ name = "typing-extensions", specifier = ">=4.14.1" },
|
||||||
{ name = "xonsh", specifier = ">=0.19.2" },
|
{ name = "xonsh", specifier = ">=0.19.2" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
@ -452,11 +452,11 @@ wheels = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "typing-extensions"
|
name = "typing-extensions"
|
||||||
version = "4.13.2"
|
version = "4.14.1"
|
||||||
source = { registry = "https://pypi.org/simple" }
|
source = { registry = "https://pypi.org/simple" }
|
||||||
sdist = { url = "https://files.pythonhosted.org/packages/f6/37/23083fcd6e35492953e8d2aaaa68b860eb422b34627b13f2ce3eb6106061/typing_extensions-4.13.2.tar.gz", hash = "sha256:e6c81219bd689f51865d9e372991c540bda33a0379d5573cddb9a3a23f7caaef", size = 106967, upload-time = "2025-04-10T14:19:05.416Z" }
|
sdist = { url = "https://files.pythonhosted.org/packages/98/5a/da40306b885cc8c09109dc2e1abd358d5684b1425678151cdaed4731c822/typing_extensions-4.14.1.tar.gz", hash = "sha256:38b39f4aeeab64884ce9f74c94263ef78f3c22467c8724005483154c26648d36", size = 107673, upload-time = "2025-07-04T13:28:34.16Z" }
|
||||||
wheels = [
|
wheels = [
|
||||||
{ url = "https://files.pythonhosted.org/packages/8b/54/b1ae86c0973cc6f0210b53d508ca3641fb6d0c56823f288d108bc7ab3cc8/typing_extensions-4.13.2-py3-none-any.whl", hash = "sha256:a439e7c04b49fec3e5d3e2beaa21755cadbbdc391694e28ccdd36ca4a1408f8c", size = 45806, upload-time = "2025-04-10T14:19:03.967Z" },
|
{ url = "https://files.pythonhosted.org/packages/b5/00/d631e67a838026495268c2f6884f3711a15a9a2a96cd244fdaea53b823fb/typing_extensions-4.14.1-py3-none-any.whl", hash = "sha256:d1e1e3b58374dc93031d6eda2420a48ea44a36c2b4766a4fdeb3710755731d76", size = 43906, upload-time = "2025-07-04T13:28:32.743Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
Loading…
Reference in New Issue