# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-cumulative-token-counters-against-per-step-deltas-when-observability-spans-are-retried-and-merged.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-cumulative-token-counters-against-per-step-deltas-when-observability-spans-are-retried-and-merged.warrant.json
# Markdown SHA-256:   cdc5181d24af559a6f6608a9f8559b999cb70d9c1c777dfc0cee877e24adcd8f
# Code AST SHA-256:   46f512a9efae6edc57382ecbb5831bc302e52d959622e448ce521bc107017ec4
# Verified Classes:   TokenReconciliationError, Span, Session
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TokenReconciliationError(RuntimeError):
    """Raised when merged per-step token deltas cannot be reconciled to the
    single-authority cumulative counter, proving a double-count."""


@dataclass
class Span:
    span_id: str
    trace_id: str
    retry_of: str | None
    delta_input_tokens: int
    delta_output_tokens: int
    start_ms: int
    end_ms: int

    @property
    def duration_ms(self) -> int:
        return self.end_ms - self.start_ms


@dataclass
class Session:
    trace_id: str
    cumulative_tokens: int          # single authority, emitted at close
    cumulative_observed_at_ms: int
    spans: list[Span] = field(default_factory=list)


def reconcile(session: Session, in_flight_token_allowance: int,
              jitter_allowance_ms: int) -> tuple[int, int]:
    """Return (reconciled_tokens, reconciled_step_latency_ms).

    Token axis: deltas are a lower bound; a sum exceeding the cumulative
    counter past the in-flight allowance is a proven double-count.
    Latency axis: children that overlap the parent interval are summed into
    a wall-clock figure only if they are disjoint; otherwise the envelope
    (parent interval) is authoritative.
    """
    # Deduplicate retries by lineage: a span whose retry_of is already
    # present must not contribute its delta a second time.
    seen: set[str] = set()
    effective: list[Span] = []
    for s in session.spans:
        key = s.retry_of or s.span_id
        if key in seen:
            continue
        seen.add(key)
        effective.append(s)

    delta_sum = sum(s.delta_input_tokens + s.delta_output_tokens
                    for s in effective)

    if delta_sum > session.cumulative_tokens + in_flight_token_allowance:
        raise TokenReconciliationError(
            f"trace={session.trace_id} delta_sum={delta_sum} exceeds "
            f"cumulative={session.cumulative_tokens} by more than "
            f"allowance={in_flight_token_allowance}; "
            f"offending_spans={[s.span_id for s in effective]}"
        )

    # Token truth is the cumulative counter, never the delta sum.
    reconciled_tokens = session.cumulative_tokens

    # Latency: detect overlap among effective child intervals.
    intervals = sorted((s.start_ms, s.end_ms) for s in effective)
    overlap = any(intervals[i][1] > intervals[i + 1][0]
                  for i in range(len(intervals) - 1))
    summed = sum(s.duration_ms for s in effective)
    parent = max(s.end_ms for s in effective) - min(s.start_ms for s in effective)

    if overlap and summed > parent + jitter_allowance_ms:
        reconciled_latency = parent          # wall-clock envelope
    else:
        reconciled_latency = summed

    return reconciled_tokens, reconciled_latency


def publish_metric(session: Session, in_flight_token_allowance: int,
                   jitter_allowance_ms: int) -> dict:
    tokens, latency = reconcile(session, in_flight_token_allowance,
                                jitter_allowance_ms)
    if tokens < 0 or latency < 0:
        raise TokenReconciliationError(
            f"trace={session.trace_id} produced non-physical metric "
            f"tokens={tokens} latency={latency}"
        )
    return {"trace_id": session.trace_id, "tokens": tokens,
            "step_latency_ms": latency, "verified": True}
