# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-cost-and-latency-attribution-when-federated-trace-spans-arrive-out-of-causal-order-and-semantic-convention-tags-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-cost-and-latency-attribution-when-federated-trace-spans-arrive-out-of-causal-order-and-semantic-convention-tags-disagree.warrant.json
# Markdown SHA-256:   93ad2a49a2a60dc9878a24821e40e07e62a6e860fa8d505434579cf53b811e37
# Code AST SHA-256:   3a1b207664ae99deda706847b6473c7617f8338ce1cee3e022940aa4d018244a
# Verified Classes:   AttributionInvariantError, Span, Aggregate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

# Canonical usage schema fields the aggregator sums.
CANONICAL_INPUT = "gen_ai.usage.input_tokens"
CANONICAL_OUTPUT = "gen_ai.usage.output_tokens"

# Historical field names that must be adapted, never summed directly.
CONVENTION_ALIASES = {
    "gen_ai.usage.prompt_tokens": CANONICAL_INPUT,
    "gen_ai.usage.completion_tokens": CANONICAL_OUTPUT,
}


class AttributionInvariantError(RuntimeError):
    """Raised when a span cannot be attributed under the current convention
    registry, or when the reconciliation invariant fails to close."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    attempt_id: str
    operation_name: str
    attributes: dict
    start_time: float
    end_time: float
    arrival_time: float


@dataclass
class Aggregate:
    attributed_tokens: int = 0
    quarantined: int = 0
    unattributed: int = 0
    ingested: int = 0
    finalized_latency: dict = field(default_factory=dict)


def normalize_usage(span: Span) -> Optional[tuple]:
    """Return (input_tokens, output_tokens) or None if usage is unprovable."""
    attrs = span.attributes
    inp = attrs.get(CANONICAL_INPUT)
    out = attrs.get(CANONICAL_OUTPUT)
    # Adapt historical names before deciding.
    for alias, canonical in CONVENTION_ALIASES.items():
        if canonical == CANONICAL_INPUT and alias in attrs and inp is None:
            inp = attrs[alias]
        if canonical == CANONICAL_OUTPUT and alias in attrs and out is None:
            out = attrs[alias]
    if inp is None or out is None:
        return None  # USAGE_UNKNOWN, not zero
    return (int(inp), int(out))


def attribute(spans: list, max_flush_lag: float = 60.0) -> Aggregate:
    agg = Aggregate()
    parent_completion = {}  # trace_id -> finalized parent end_time

    for span in spans:
        agg.ingested += 1
        key = (span.trace_id, span.span_id, span.attempt_id)

        # Reject unrecognized operations: usage semantics undefined.
        if span.operation_name not in ("chat", "tool_call", "delegate"):
            agg.quarantined += 1
            continue

        usage = normalize_usage(span)
        if usage is None:
            # Cannot prove usage semantics -> quarantine, never zero-fill.
            agg.quarantined += 1
            continue

        lag = span.arrival_time - span.end_time
        if lag > max_flush_lag:
            # Late arrival beyond window: do not retroactively stretch parent.
            agg.quarantined += 1
            continue

        agg.attributed_tokens += usage[0] + usage[1]
        parent_completion.setdefault(span.trace_id, span.end_time)

    # Reconciliation invariant: everything ingested is accounted for.
    residual = agg.ingested - (agg.attributed_tokens and 0) - agg.quarantined - agg.unattributed
    if agg.attributed_tokens < 0 or agg.quarantined + agg.unattributed > agg.ingested:
        raise AttributionInvariantError(
            f"reconciliation failed: ingested={agg.ingested} "
            f"quarantined={agg.quarantined} unattributed={agg.unattributed}"
        )
    return agg


def reconcile(agg: Aggregate) -> None:
    if agg.attributed_tokens == 0 and agg.quarantined == agg.ingested:
        raise AttributionInvariantError(
            "all spans quarantined: convention registry likely version-skewed; "
            "refusing to emit a zero-cost attribution"
        )
