# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-span-attributes-before-the-token-accounting-closes-the-mid-stream-usage-gap-and-its-downstream-attribution-c.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-span-attributes-before-the-token-accounting-closes-the-mid-stream-usage-gap-and-its-downstream-attribution-c.warrant.json
# Markdown SHA-256:   c88dea951306b52fd152d4a2a02e0dc666a25e99e4610d4760a03661b83882df
# Code AST SHA-256:   0af80d081dd6a1f4f7270638a4b1fb6285f53666344bfebcf7a6100b2d19d282
# Verified Classes:   ProvisionalUsageExportError, GenAIInvocationSpan
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass, field
from typing import Optional


class ProvisionalUsageExportError(RuntimeError):
    """Raised when a GenAI invocation span would be exported with
    non-authoritative usage attributes or with absent usage silently
    coerced to zero. This is the invariant violation that corrupts
    downstream cost attribution."""


@dataclass
class GenAIInvocationSpan:
    span_id: str
    operation: str = "chat"
    input_tokens: Optional[int] = None
    output_tokens: Optional[int] = None
    usage_authoritative: bool = False
    estimated_output: Optional[int] = None
    estimator_method: Optional[str] = None
    events: list[str] = field(default_factory=list)
    ended: bool = False

    def record_usage(self, input_tokens: int, output_tokens: int) -> None:
        if self.ended:
            raise ProvisionalUsageExportError(
                f"span {self.span_id}: usage arrived after span end; "
                "authoritative counts cannot be applied to an exported span"
            )
        self.input_tokens = input_tokens
        self.output_tokens = output_tokens
        self.usage_authoritative = True

    def record_estimate(self, estimated_output: int, method: str) -> None:
        # Estimates are quarantined into an event, never into gen_ai.usage.*
        if self.ended:
            raise ProvisionalUsageExportError(
                f"span {self.span_id}: estimate arrived after span end"
            )
        self.estimated_output = estimated_output
        self.estimator_method = method
        self.events.append(
            f"gen_ai.usage.estimated value={estimated_output} method={method}"
        )

    def end(self) -> None:
        if self.ended:
            return
        # Invariant: authoritative usage must be present, OR usage attributes
        # must be absent (None) with an estimation event recorded.
        if self.usage_authoritative:
            if self.output_tokens is None or self.input_tokens is None:
                raise ProvisionalUsageExportError(
                    f"span {self.span_id}: usage_authoritative set but counts missing"
                )
        else:
            if self.output_tokens is not None or self.input_tokens is not None:
                raise ProvisionalUsageExportError(
                    f"span {self.span_id}: non-authoritative counts present on "
                    "gen_ai.usage.*; must be absent to avoid attribution corruption"
                )
            if self.estimated_output is not None and not any(
                e.startswith("gen_ai.usage.estimated") for e in self.events
            ):
                raise ProvisionalUsageExportError(
                    f"span {self.span_id}: estimate present without quarantine event"
                )
            self.events.append("gen_ai.usage.absent reason=usage_chunk_timeout")
        self.ended = True


def finalize_invocation(
    span: GenAIInvocationSpan,
    usage_future: Optional[dict],
    content_done_at: float,
    timeout_s: float = 0.5,
) -> GenAIInvocationSpan:
    """Bind span-end to usage completion, not content completion."""
    if usage_future is not None and "input_tokens" in usage_future:
        span.record_usage(
            usage_future["input_tokens"], usage_future["output_tokens"]
        )
        span.end()
        return span

    # Usage did not arrive with the terminal content event. Wait, bounded.
    deadline = content_done_at + timeout_s
    while time.monotonic() < deadline:
        if usage_future is not None and "input_tokens" in usage_future:
            span.record_usage(
                usage_future["input_tokens"], usage_future["output_tokens"]
            )
            span.end()
            return span
        time.sleep(0.01)

    # Timeout branch: quarantine any estimate, leave gen_ai.usage.* absent.
    if span.estimated_output is not None:
        span.record_estimate(span.estimated_output, span.estimator_method or "unknown")
    span.end()
    return span


def governor_decrement(
    span: GenAIInvocationSpan, remaining_budget: int
) -> int:
    """A budget governor MUST NOT coerce absent usage to zero."""
    if span.output_tokens is None:
        raise ProvisionalUsageExportError(
            f"span {span.span_id}: governor cannot decrement on absent usage; "
            "refusing to convert unknown into a budget credit"
        )
    return remaining_budget - (span.input_tokens or 0) - span.output_tokens


if __name__ == "__main__":
    # Reproduce the observed failure: usage arrives after content end.
    span = GenAIInvocationSpan(span_id="inv-0001")
    span.record_estimate(225, "len(deltas)/4")
    finalize_invocation(span, usage_future=None, content_done_at=time.monotonic(), timeout_s=0.05)
    try:
        governor_decrement(span, remaining_budget=100_000)
    except ProvisionalUsageExportError as exc:
        print(f"guardrail fired: {exc}")
    print("span events:", span.events)
    print("gen_ai.usage.output_tokens:", span.output_tokens)  # None, not 0
