# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-non-deterministic-otel-genai-span-replay-when-sampling-decisions-diverge-from-the-audit-trace-s-decision-log.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-non-deterministic-otel-genai-span-replay-when-sampling-decisions-diverge-from-the-audit-trace-s-decision-log.warrant.json
# Markdown SHA-256:   bee4080e5cd369f838aa8526ddf9fb5e7d273dd0809baa1fd52bbe2f974f0182
# Code AST SHA-256:   513af43ec81e31924f4e6b47a009a72671fefa01bb6bcb677f0aa150454ea6fe
# Verified Classes:   ReplayUnsoundError, ChatSpan, DecisionLogEntry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass
from typing import Any


class ReplayUnsoundError(RuntimeError):
    """Raised when a span tree is structurally valid but not replayable
    because nondeterministic branch points were dropped by sampling."""


@dataclass
class ChatSpan:
    span_id: str
    attributes: dict[str, Any]
    child_tool_calls: list[str]


@dataclass
class DecisionLogEntry:
    span_id: str
    selected_branches: list[str]
    discarded_branches: list[str]
    seed: int


def assert_replay_soundness(
    spans: list[ChatSpan],
    decision_log: list[DecisionLogEntry],
) -> None:
    """Verify that every branch point in the decision log is represented
    on the retained span tree. Abort replay on any mismatch."""
    log_by_span = {e.span_id: e for e in decision_log}

    for span in spans:
        entry = log_by_span.get(span.span_id)
        if entry is None:
            # A chat span with no decision-log entry means the log was
            # truncated or the span was synthesized — cannot replay.
            raise ReplayUnsoundError(
                f"chat span {span.span_id} has no decision-log entry; "
                f"replay substrate is incomplete"
            )

        expected_total = len(entry.selected_branches) + len(entry.discarded_branches)
        recorded_candidates = span.attributes.get("replay.branch_candidates")
        recorded_dropped = span.attributes.get("replay.dropped_branches", 0)

        if recorded_candidates is None:
            raise ReplayUnsoundError(
                f"chat span {span.span_id} missing replay.branch_candidates "
                f"attribute; branch selection was not committed to a "
                f"sampling-retained span"
            )

        candidates = json.loads(recorded_candidates)
        if len(candidates) != expected_total:
            raise ReplayUnsoundError(
                f"chat span {span.span_id}: span records {len(candidates)} "
                f"candidates but decision log records {expected_total}; "
                f"sampling dropped branch evidence"
            )

        if len(entry.discarded_branches) > 0 and recorded_dropped == 0:
            raise ReplayUnsoundError(
                f"chat span {span.span_id}: decision log shows "
                f"{len(entry.discarded_branches)} discarded branches but span "
                f"records replay.dropped_branches=0; replay would reconstruct "
                f"a linear execution that never occurred"
            )

        if len(span.child_tool_calls) != len(entry.selected_branches):
            raise ReplayUnsoundError(
                f"chat span {span.span_id}: {len(span.child_tool_calls)} "
                f"retained tool-call children vs "
                f"{len(entry.selected_branches)} selected in decision log"
            )
