# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-span-attribute-lineage-collapse-when-genai-semantic-conventions-meet-multi-turn-tool-call-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-span-attribute-lineage-collapse-when-genai-semantic-conventions-meet-multi-turn-tool-call-fan-out.warrant.json
# Markdown SHA-256:   4663e4d8813fdc5821d0282b4f10ee75e441573e931602c75e5e9cbfc8940ddd
# Code AST SHA-256:   4997469e97b187b76591bf2be7d3c753376c5106c0452c6e2691a1d8d8745e58
# Verified Classes:   LineageCollapseError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class LineageCollapseError(RuntimeError):
    """Raised when a token-accounting decision is requested over a trace
    whose GenAI spans exhibit cumulative-prefix overlap but no turn boundary
    attribute, making sum-vs-max ambiguous."""


@dataclass(frozen=True)
class GenAISpan:
    span_id: str
    parent_id: str | None
    kind: str  # "chat" | "tool"
    start_ns: int
    end_ns: int
    input_tokens: int
    output_tokens: int
    turn_index: int | None  # gen_ai.conversation.turn_index if present


def reconcile_turn_tokens(spans: Sequence[GenAISpan]) -> dict[int, int]:
    """Return per-turn terminal context occupancy.

    Collapses chained chat spans to their terminal prefix per turn rather
    than summing input_tokens across the loop.
    """
    chat_spans = [s for s in spans if s.kind == "chat"]
    if not chat_spans:
        raise LineageCollapseError("no gen_ai.chat spans present; cannot reconcile")

    # Detect chained cumulative prefixes without turn_index.
    missing_turn = [s for s in chat_spans if s.turn_index is None]
    if missing_turn:
        # Chained chat spans ordered by time with monotonic input growth
        # cannot be safely summed; refuse rather than guess.
        ordered = sorted(chat_spans, key=lambda s: s.start_ns)
        monotonic = all(
            ordered[i + 1].input_tokens >= ordered[i].input_tokens
            for i in range(len(ordered) - 1)
        )
        if monotonic and len(ordered) > 1:
            raise LineageCollapseError(
                "chained gen_ai.chat spans show monotonic prefix growth but "
                "carry no gen_ai.conversation.turn_index; sum-vs-max is "
                "ambiguous and additive accounting would double-count the prefix"
            )

    occupancy: dict[int, int] = {}
    for s in chat_spans:
        if s.turn_index is None:
            continue
        # Terminal span of a turn wins; later start_ns overrides.
        prev = occupancy.get(s.turn_index)
        candidate = s.input_tokens + s.output_tokens
        if prev is None or candidate > prev:
            occupancy[s.turn_index] = candidate
    return occupancy


def guard_context_budget(spans: Sequence[GenAISpan], ceiling: int) -> None:
    occupancy = reconcile_turn_tokens(spans)
    if not occupancy:
        raise LineageCollapseError("reconciliation produced no turn occupancy")
    peak = max(occupancy.values())
    if peak > ceiling:
        raise LineageCollapseError(
            f"terminal context occupancy {peak} exceeds ceiling {ceiling}; "
            f"do not fall back to summed input_tokens"
        )
