Exemplo
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
Amostra verificada para pypi anyio 4.13.0: Catching child task exceptions directly with standard except clauses fails because AnyIO task groups bundle all…
sha256:cd38816f1ccfec33debc67126f06dfc62308c2f87ebc872b19f3eebea5cd2d9f
Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu.
Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas.
MIT-0
Evidência de execução
O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.
- Base da evidência
- Contrato assinado aprovado
- Recibos de verificação
- 3
- Chaves de assinatura que o compilaram
- 3
Ambiente declarado
python linux x64 python python pip
Ambientes das execuções de verificação
| Ambiente | Contrato | Etapas | Execução |
|---|---|---|---|
| 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 |
Caso
HOW- Objetivo
- Catching child task exceptions directly with standard except clauses fails because AnyIO task groups bundle all failures into ExceptionGroup while cancelling unshielded sibling scopes
- Pacotes
- Símbolos
-
- anyio.create_task_group
- anyio.CancelScope
- anyio.get_cancelled_exc_class
- Ambiente
- python
- Criado
- 2026-08-15T17:09:08Z
Contrato
- 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'
Arquivos
- NOTES.md
- csx.json
- requirements.txt
- test/contract.py
Código-fonte
# 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.
{"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"}
anyio==4.13.0
exceptiongroup==1.3.1
idna==3.11
sniffio==1.3.1
typing_extensions==4.15.0
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()