# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-nested-span-token-accounting-before-cache-hit-telemetry-can-be-trusted-across-an-agentic-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-nested-span-token-accounting-before-cache-hit-telemetry-can-be-trusted-across-an-agentic-loop.warrant.json
# Markdown SHA-256:   40ffe40e7d2d7aa2011b2e56ac65fb9fe45a3fdce638f43ab77145ce12eb1f49
# Code AST SHA-256:   77dacee4f51fa2d098c0a024d6bb638ac094d9adb441728944b2417ec3009834
# Verified Classes:   AggregationScope, CacheRatioUnderivable, GenAISpan
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass
from enum import Enum


class AggregationScope(Enum):
    INCLUSIVE = "inclusive"
    EXCLUSIVE = "exclusive"
    UNSPECIFIED = "unspecified"


class CacheRatioUnderivable(RuntimeError):
    """Raised when a cache-hit ratio cannot be reconstructed because the
    numerator and denominator do not share an explicit aggregation scope,
    or because attempt multiplicity is unencoded and would corrupt the
    denominator."""
    pass


@dataclass(frozen=True)
class GenAISpan:
    span_id: str
    name: str
    input_tokens: int
    cache_read_input_tokens: int
    aggregation: AggregationScope
    attempt_group: str | None = None


def cache_hit_ratio(span: GenAISpan) -> float:
    """Compute the cache-hit ratio for a single genai.chat span.

    The ratio is only meaningful on a leaf model-call span whose
    cache_read and input_tokens share one aggregation scope and whose
    prompt is the provider's cache key. It must never be computed
    against a parent roll-up total.
    """
    if span.name != "genai.chat":
        raise CacheRatioUnderivable(
            f"span {span.span_id} ({span.name}) is not a model-call span; "
            f"cache_read/input ratio is undefined for aggregated parents"
        )
    if span.aggregation is AggregationScope.UNSPECIFIED:
        raise CacheRatioUnderivable(
            f"span {span.span_id} has no aggregation scope marker; "
            f"numerator/denominator convention unknown, refusing ratio"
        )
    if span.attempt_group is None:
        raise CacheRatioUnderivable(
            f"span {span.span_id} has no attempt_group; a retry sibling "
            f"would be indistinguishable from fan-out, corrupting topology"
        )
    if span.input_tokens <= 0:
        raise CacheRatioUnderivable(
            f"span {span.span_id} has non-positive input_tokens; ratio undefined"
        )
    if span.cache_read_input_tokens > span.input_tokens:
        raise CacheRatioUnderivable(
            f"span {span.span_id} cache_read exceeds input; "
            f"scopes are mismatched across numerator/denominator"
        )
    return span.cache_read_input_tokens / span.input_tokens


def weighted_turn_cache_rate(chat_spans: list[GenAISpan]) -> float:
    """Aggregate per-span ratios weighted by each span's own input_tokens,
    never by a parent roll-up. Groups by attempt_group so retries are
    counted as attempts, not as parallel branches."""
    if not chat_spans:
        raise CacheRatioUnderivable("no genai.chat spans to aggregate")
    groups: dict[str, list[GenAISpan]] = {}
    for s in chat_spans:
        if s.attempt_group is None:
            raise CacheRatioUnderivable(
                f"span {s.span_id} missing attempt_group; cannot separate "
                f"retry from fan-out during topology reconstruction"
            )
        groups.setdefault(s.attempt_group, []).append(s)
    total_in = 0
    total_cached = 0
    for group_spans in groups.values():
        # Use the final successful attempt per group for the ratio; earlier
        # attempts are cost, not cache signal.
        final = group_spans[-1]
        ratio = cache_hit_ratio(final)
        total_in += final.input_tokens
        total_cached += int(round(ratio * final.input_tokens))
    if total_in == 0:
        raise CacheRatioUnderivable("aggregate input_tokens is zero")
    return total_cached / total_in


def reconstruct(spans: list[GenAISpan]) -> dict:
    chats = [s for s in spans if s.name == "genai.chat"]
    if any(s.aggregation is AggregationScope.INCLUSIVE for s in chats):
        raise CacheRatioUnderivable(
            "inclusive-scoped chat span present; subtree token totals are "
            "cost-correct but ratio-unsafe, refusing reconstruction"
        )
    return {
        "turn_cache_rate": weighted_turn_cache_rate(chats),
        "fanout_width": len({s.attempt_group for s in chats}),
        "attempts": len(chats),
    }
