CodeSampleX

示例

anyio 4.13.0: Catching child task exceptions directly with standard except clauses fails because AnyIO task groups bundle all failures into ExceptionGroup while cancelling unshielded sibling scopes

已验证示例 — pypi anyio 4.13.0: Catching child task exceptions directly with standard except clauses fails because AnyIO task groups bundle all failures into…

sha256:cd38816f1ccfec33debc67126f06dfc62308c2f87ebc872b19f3eebea5cd2d9f

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
3
构建过它的签名密钥
3
声明的环境 python linux x64 python python pip

验证运行环境

环境 契约 阶段 运行日期
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-15
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-18
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-07

案例

HOW
目标
Catching child task exceptions directly with standard except clauses fails because AnyIO task groups bundle all failures into ExceptionGroup while cancelling unshielded sibling scopes
包
符号
  • anyio.create_task_group
  • anyio.CancelScope
  • anyio.get_cancelled_exc_class
环境
python
创建时间
2026-08-15T17:09:08Z

契约

  1. assert not raw_caught, 'Direct except ValueError must not catch TaskGroup exception'
  2. assert group_caught, 'Caller must catch ExceptionGroup / BaseExceptionGroup'
  3. assert unshielded_failed, 'Unshielded async operation during cancellation must raise CancelledError'
  4. assert c_shielded_scope_survived, 'Active shielded scope entered before failure survives TaskGroup cancellation'

文件

  • NOTES.md
  • csx.json
  • requirements.txt
  • test/contract.py

下载源代码构件 (tar.gz)

源代码

NOTES.md
# Notes on anyio Task Group Cancellation & Shielding Contract

## Search Result
- `search_known_solution` resulted in a **MISS** for AnyIO task group cancellation behaviors (the only results returned were low-confidence cross-ecosystem alternatives for Tokio, Polars, and Go errgroup).

## What a Naive Model Would Have Written
A naive model would have written `try: async with anyio.create_task_group() as tg: ... except ValueError:` expecting to catch the child task's direct exception, and written unshielded async cleanup calls inside cancellation handlers (`except anyio.get_cancelled_exc_class(): await cleanup()`).

## How the Wrong Version Fails
It fails loudly with an uncaught `ExceptionGroup` bypassing the `except ValueError` block entirely, while sibling cancellation handlers fail via immediate `CancelledError` abortion during unshielded `await` calls, preventing cleanup routines from executing.
csx.json
{"case":{"caseId":"case:sha256:3360d7517ca825ad2f790b509a132baf304330f8763f1b2893e61c748164d04d","constraints":{"runtime":"python"},"contract":["assert not raw_caught, 'Direct except ValueError must not catch TaskGroup exception'","assert group_caught, 'Caller must catch ExceptionGroup / BaseExceptionGroup'","assert unshielded_failed, 'Unshielded async operation during cancellation must raise CancelledError'","assert c_shielded_scope_survived, 'Active shielded scope entered before failure survives TaskGroup cancellation'"],"goal":"Catching child task exceptions directly with standard except clauses fails because AnyIO task groups bundle all failures into ExceptionGroup while cancelling unshielded sibling scopes","kind":"HOW","packages":["pkg:pypi/anyio@4.13.0"],"schemaVersion":1,"symbols":["anyio.create_task_group","anyio.CancelScope","anyio.get_cancelled_exc_class"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/anyio@4.13.0"],"schemaVersion":1,"symbols":["anyio.create_task_group","anyio.CancelScope","anyio.get_cancelled_exc_class"],"verifierAdapter":"python@1"}
requirements.txt
anyio==4.13.0
exceptiongroup==1.3.1
idna==3.11
sniffio==1.3.1
typing_extensions==4.15.0
test/contract.py
import sys
import anyio

# Support exceptiongroup backport on Python < 3.11
if sys.version_info < (3, 11):
    from exceptiongroup import BaseExceptionGroup, ExceptionGroup
else:
    BaseExceptionGroup = BaseExceptionGroup
    ExceptionGroup = ExceptionGroup


async def test_task_group_cancellation_and_shielding():
    log = []

    task_b_started = anyio.Event()
    task_c_shielded_ready = anyio.Event()
    task_c_work_signal = anyio.Event()
    never_set_event = anyio.Event()

    async def failing_task():
        await task_b_started.wait()
        await task_c_shielded_ready.wait()
        log.append("a:raise")
        raise ValueError("child failed")

    async def sibling_cancelled_task():
        task_b_started.set()
        try:
            await never_set_event.wait()
        except anyio.get_cancelled_exc_class():
            log.append("b:cancelled")

            # Unshielded async checkpoint fails immediately under active cancellation
            unshielded_failed = False
            try:
                probe_event = anyio.Event()
                await probe_event.wait()
            except anyio.get_cancelled_exc_class():
                unshielded_failed = True
            assert unshielded_failed, "Unshielded async operation during cancellation must raise CancelledError"
            log.append("b:unshielded_aborted")

            # Shielded async cleanup succeeds
            with anyio.CancelScope(shield=True):
                task_c_work_signal.set()
                cleanup_event = anyio.Event()
                cleanup_event.set()
                await cleanup_event.wait()
                log.append("b:shielded_cleanup_ok")
            raise

    async def sibling_pre_shielded_task():
        # Enters shield before failure occurs
        with anyio.CancelScope(shield=True):
            task_c_shielded_ready.set()
            await task_c_work_signal.wait()
            log.append("c:shielded_work_ok")

        # Exiting shield exposes task to pending cancellation
        try:
            await never_set_event.wait()
        except anyio.get_cancelled_exc_class():
            log.append("c:outer_cancelled")
            raise

    raw_caught = False
    group_caught = False

    try:
        async with anyio.create_task_group() as tg:
            tg.start_soon(failing_task)
            tg.start_soon(sibling_cancelled_task)
            tg.start_soon(sibling_pre_shielded_task)
    except ValueError:
        raw_caught = True
    except (ExceptionGroup, BaseExceptionGroup) as eg:
        group_caught = True
        assert len(eg.exceptions) == 1, f"Expected 1 exception, got {len(eg.exceptions)}"
        assert isinstance(eg.exceptions[0], ValueError), "Sub-exception must be ValueError"
        assert str(eg.exceptions[0]) == "child failed"
        log.append("caller:caught_eg")

    # Contract assertions
    assert not raw_caught, "Direct 'except ValueError' must not catch TaskGroup exception"
    assert group_caught, "Caller must catch ExceptionGroup / BaseExceptionGroup"
    assert log == [
        "a:raise",
        "b:cancelled",
        "b:unshielded_aborted",
        "c:shielded_work_ok",
        "b:shielded_cleanup_ok",
        "c:outer_cancelled",
        "caller:caught_eg",
    ], f"Unexpected execution sequence: {log}"


def main():
    anyio.run(test_task_group_cancellation_and_shielding)
    print("Contract verified: AnyIO TaskGroup cancellation and shielding contract passed.")


if __name__ == "__main__":
    main()

原始种子者

anonymous