# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-inherit-a-parent-agent-span-s-token-budget-but-not-its-exhausted-budget-signal-under-opentelemetry-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-inherit-a-parent-agent-span-s-token-budget-but-not-its-exhausted-budget-signal-under-opentelemetry-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   022bc5f56ea20635f17cf447a67d42a02b233999ee5d5083c08478267505374e
# Code AST SHA-256:   148e0aaa0a80b17d26b574ec5cee0c70b4ee9a7fa95dc85d51c8b918bce331f8
# Verified Classes:   BudgetReconstructionError, ParentSpanUnusable
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class BudgetReconstructionError(RuntimeError):
    """Raised when a child agent attempts to derive budget authority from
    parent span telemetry under OTel GenAI semantic conventions."""


class ParentSpanUnusable(BudgetReconstructionError):
    """Parent span is missing, stale, or not closed with a terminal status."""


def derive_remaining_budget(
    parent_span: dict | None,
    task_budget: int,
    *,
    parent_terminated_voluntarily: bool,
    collector_flushed: bool,
    same_counter: bool,
) -> int:
    """Attempt to reconstruct a child's remaining budget from the parent's
    exported gen_ai.usage.* attributes. This is the anti-pattern; the function
    exists only to demonstrate why it must not be used in production."""
    if parent_span is None:
        raise ParentSpanUnusable(
            "parent span absent from collector; child would default to full budget"
        )
    if not collector_flushed:
        raise ParentSpanUnusable(
            "parent span not yet flushed (BatchSpanProcessor delay); read is stale"
        )
    if not parent_terminated_voluntarily:
        raise ParentSpanUnusable(
            "parent terminated by supervisor; span status does not encode exhaustion"
        )
    if not same_counter:
        raise BudgetReconstructionError(
            "supervisor counter and gen_ai.usage.* counter diverge; subtraction invalid"
        )
    usage = parent_span.get("attributes", {}).get("gen_ai.usage.input_tokens")
    if usage is None:
        raise ParentSpanUnusable("gen_ai.usage.input_tokens missing on parent span")
    remaining = task_budget - int(usage)
    if remaining < 0:
        raise BudgetReconstructionError(
            f"derived remaining budget negative ({remaining}); parent already overspent"
        )
    return remaining


def request_budget_lease(budget_service_url: str, trace_id: str, agent_id: str) -> dict:
    """Correct path: control-plane lease, not telemetry derivation."""
    raise BudgetReconstructionError(
        "budget authority must come from the budget service with an explicit lease; "
        "do not reconstruct from gen_ai.usage.* span attributes"
    )
