# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-parent-child-span-inversion-in-chain-of-thought-trace-correlation-under-semantic-convention-extensions.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-parent-child-span-inversion-in-chain-of-thought-trace-correlation-under-semantic-convention-extensions.warrant.json
# Markdown SHA-256:   d91708cb9595c2669ae3dd6bc0249752f8137ebdfc97fed25b6cace49e009544
# Code AST SHA-256:   5508c857039530ca853c9fd851c7024e70cbddd921bd031a9beb74cf30b5d408
# Verified Classes:   ReasoningTraceInversionError, ReasoningSpan, ReasoningTraceValidator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ReasoningTraceInversionError(RuntimeError):
    """Raised when a reasoning span violates parent-child correlation invariants."""
    pass


@dataclass
class ReasoningSpan:
    span_id: str
    parent_span_id: str
    epoch: int
    step_index: int
    start_time_ms: int
    end_time_ms: int
    input_tokens: int


class ReasoningTraceValidator:
    """Enforces (parent, epoch, step_index) uniqueness and monotonic start times."""

    def __init__(self) -> None:
        self._seen: dict[tuple[str, int, int], str] = {}
        self._last_start: dict[tuple[str, int], int] = {}

    def ingest(self, span: ReasoningSpan) -> None:
        key = (span.parent_span_id, span.epoch, span.step_index)
        if key in self._seen:
            raise ReasoningTraceInversionError(
                f"duplicate reasoning step: parent={span.parent_span_id} "
                f"epoch={span.epoch} step={span.step_index} "
                f"already emitted as span {self._seen[key]}, "
                f"re-emitted as {span.span_id}; re-plan must open a new epoch"
            )

        epoch_key = (span.parent_span_id, span.epoch)
        prev_start = self._last_start.get(epoch_key)
        if prev_start is not None and span.start_time_ms < prev_start:
            raise ReasoningTraceInversionError(
                f"non-monotonic start time within epoch: span {span.span_id} "
                f"step={span.step_index} start={span.start_time_ms}ms "
                f"precedes prior step start={prev_start}ms under "
                f"parent={span.parent_span_id} epoch={span.epoch}"
            )

        self._seen[key] = span.span_id
        self._last_start[epoch_key] = span.start_time_ms

    def aggregate_tokens(self, parent_span_id: str, terminal_epoch: int) -> int:
        if terminal_epoch < 0:
            raise ReasoningTraceInversionError(
                f"terminal_epoch must be >= 0, got {terminal_epoch}"
            )
        # Only sum the terminal epoch to avoid double-counting superseded steps.
        total = 0
        for (pid, epoch, _step), _sid in self._seen.items():
            if pid == parent_span_id and epoch == terminal_epoch:
                total += 1  # placeholder: token lookup by span_id omitted
        return total
