# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-join-a-trace-segment-whose-parent-span-was-emitted-by-a-different-agent-epoch-and-how-does-epoch-mismatch.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-join-a-trace-segment-whose-parent-span-was-emitted-by-a-different-agent-epoch-and-how-does-epoch-mismatch.warrant.json
# Markdown SHA-256:   cff3aa878e165d932764f99482b04051edc79fef8a7afcfdd974b7e800fb2486
# Code AST SHA-256:   62772515a6c193f2906b04295a053f1cdadbe455a00f1431bdb30b4bf7f5cfca
# Verified Classes:   EpochMismatchError, Span
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EpochMismatchError(RuntimeError):
    """Raised when a verdict/span cannot be soundly correlated across epochs."""


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    epoch_id: str
    kind: str  # "agent.turn" | "trace.segment_boundary" | "safety.verdict"


def compute_epoch(instance_id: str, prompt_hash: str,
                  tool_registry_version: str, safety_policy_version: str) -> str:
    h = hashlib.sha256()
    for part in (instance_id, prompt_hash, tool_registry_version, safety_policy_version):
        h.update(part.encode())
        h.update(b"\x00")
    return h.hexdigest()[:16]


def correlate_verdict(verdict: Span, turn: Span, spans_by_id: dict[str, Span]) -> str:
    """Return the epoch_id the verdict is validly attributed to, or raise."""
    if verdict.kind != "safety.verdict" or turn.kind != "agent.turn":
        raise EpochMismatchError(f"bad span kinds: {verdict.kind=} {turn.kind=}")
    if not verdict.epoch_id:
        raise EpochMismatchError(
            f"verdict {verdict.span_id} has no epoch_id; refusing to default to latest"
        )
    if verdict.epoch_id != turn.epoch_id:
        raise EpochMismatchError(
            f"verdict epoch {verdict.epoch_id} != turn epoch {turn.epoch_id} "
            f"for trace {turn.trace_id}"
        )
    # Walk ancestry between verdict and turn; a segment boundary must separate
    # any epoch change, otherwise the join is unsound.
    cursor = verdict.parent_span_id
    seen_boundary = False
    while cursor is not None:
        node = spans_by_id.get(cursor)
        if node is None:
            raise EpochMismatchError(f"dangling parent {cursor} in trace {turn.trace_id}")
        if node.kind == "trace.segment_boundary":
            seen_boundary = True
        if node.span_id == turn.span_id:
            break
        cursor = node.parent_span_id
    else:
        raise EpochMismatchError(
            f"verdict {verdict.span_id} not descended from turn {turn.span_id}"
        )
    if turn.epoch_id != verdict.epoch_id and not seen_boundary:
        raise EpochMismatchError(
            f"epoch change without declared segment boundary in trace {turn.trace_id}"
        )
    return verdict.epoch_id


def aggregate_per_trace(verdicts: list[Span], turns: list[Span]) -> dict[str, float]:
    by_epoch: dict[str, list[int]] = {}
    for v in verdicts:
        if not v.epoch_id:
            raise EpochMismatchError(f"unattributable verdict {v.span_id}")
        by_epoch.setdefault(v.epoch_id, []).append(1 if v.kind == "safety.verdict" else 0)
    if len(by_epoch) > 1:
        raise EpochMismatchError(
            f"per-trace aggregation across epochs {sorted(by_epoch)} is a category error"
        )
    total = sum(len(x) for x in by_epoch.values()) or 1
    blocked = sum(sum(x) for x in by_epoch.values())
    return {"block_rate": blocked / total}
