"""PC-05: ``set_request_id`` / ``reset_request_id`` overhead pin.

PEP 567 contextvars are fast (sub-µs per op on CPython) but not
free. The `MgfRequestIdMiddleware` per-request critical section
calls `set_request_id(request_id)` + `reset_request_id(token)`
once per request (federation public surface, since PAPER-61). For
a 1000 req/s app, that's 2000 contextvar ops per second on this
code path; a regression that adds even 1 µs each compounds.

The budget allows a small overhead for the wrapper-function call
indirection vs. the raw ContextVar fast path — the wrappers are
one-line passthroughs, so the cost is one Python function call
on each side.

Pin: set+reset combined stays under 5 µs/iteration. Local: sub-µs.

Marker: ``perf``. Run via ``pytest -m perf``.
"""

from __future__ import annotations

import time

import pytest
from mgf.common import reset_request_id, set_request_id

pytestmark = pytest.mark.perf

_ITERATIONS = 100_000
_SET_RESET_BUDGET_US = 5.0


def test_contextvar_set_reset_under_budget() -> None:
    # Warm-up: prime any CPython internals.
    token = set_request_id("warmup")
    reset_request_id(token)

    start = time.perf_counter()
    for i in range(_ITERATIONS):
        token = set_request_id(f"req-{i}")
        reset_request_id(token)
    elapsed_s = time.perf_counter() - start
    per_iter_us = (elapsed_s / _ITERATIONS) * 1e6

    assert per_iter_us < _SET_RESET_BUDGET_US, (
        f"PC-05: set_request_id+reset_request_id overhead is "
        f"{per_iter_us:.2f} µs/iter (budget {_SET_RESET_BUDGET_US:.1f} µs). "
        f"At 1000 req/s this is {per_iter_us * 1000:.0f} µs of per-second "
        f"context overhead. A regression here usually means a CPython "
        f"upgrade flipped the contextvar fast path off, or the public "
        f"wrappers gained a layer (e.g. validation, instrumentation). "
        f"Investigate."
    )
