"""Bounded observations of open-loop drain and caller-cancellation cleanup."""

import asyncio
import json

from telemetry.performance import ServingPlan, run_serving


async def scenario(*, cancel_caller: bool) -> None:
    entered = asyncio.Event()

    async def client(_request):
        entered.set()
        await asyncio.Event().wait()

    task = asyncio.create_task(run_serving(
        client,
        plan=ServingPlan(
            duration_seconds=0.002,
            rate_per_second=1_000,
            max_in_flight=2,
            queue_capacity=1,
            drain_seconds=1 if cancel_caller else 0,
        ),
    ))
    if cancel_caller:
        await asyncio.wait_for(entered.wait(), timeout=1)
        task.cancel()
    done, _pending = await asyncio.wait((task,), timeout=0.1)
    print(json.dumps({
        "scenario": "caller_cancel" if cancel_caller else "drain_timeout",
        "finished_within_100ms": bool(done),
        "unfinished_children": sum(
            item is not task and item is not asyncio.current_task() and not item.done()
            for item in asyncio.all_tasks()
        ),
    }, sort_keys=True))
    # Independent experiment cleanup: cancel the blocked coordinator and workers.
    remaining = tuple(item for item in asyncio.all_tasks() if item is not asyncio.current_task())
    for item in remaining:
        item.cancel()
    await asyncio.gather(*remaining, return_exceptions=True)


def main() -> None:
    for cancel_caller in (False, True):
        asyncio.run(scenario(cancel_caller=cancel_caller))


if __name__ == "__main__":
    main()
