# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-replay-a-trajectory-that-otel-telemetry-claims-is-complete.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-replay-a-trajectory-that-otel-telemetry-claims-is-complete.warrant.json
# Markdown SHA-256:   b599287c99f0434ef0df1f1cc63149c3d901f4235ba308c91fb68e8da83c5f14
# Code AST SHA-256:   cff8f39025a457ffdb42422ee691d4d1a7206d96b665978937cdcdda06f2ab64
# Verified Classes:   DeterminismClass, Span, ReplayNotClosedError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum
from typing import Optional


class DeterminismClass(Enum):
    AUTHORITATIVE = "authoritative"  # output captured byte-exact
    SEEDED = "seeded"                # reproducible via recorded seed
    LIVE = "live"                    # non-deterministic, not captured
    OPAQUE = "opaque"                # excluded from causal attribution
    UNKNOWN = "unknown"              # not declared; treated as unsafe


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    determinism: DeterminismClass
    captured_output_hash: Optional[str] = None
    captured_output_body: Optional[bytes] = None
    seed: Optional[int] = None


class ReplayNotClosedError(RuntimeError):
    """Raised when a trace is span-complete but not replay-closed."""


def causal_chain(spans: dict[str, Span], leaf_id: str) -> list[Span]:
    chain, cursor = [], leaf_id
    while cursor is not None:
        if cursor not in spans:
            raise ReplayNotClosedError(
                f"causal chain broken: span {cursor!r} referenced but absent"
            )
        span = spans[cursor]
        chain.append(span)
        cursor = span.parent_span_id
    return list(reversed(chain))


def assert_replay_closed(spans: dict[str, Span], leaf_id: str) -> None:
    for span in causal_chain(spans, leaf_id):
        if span.determinism is DeterminismClass.LIVE:
            raise ReplayNotClosedError(
                f"span {span.span_id!r} is determinism=live and was not "
                f"byte-captured; replay would re-issue a live call"
            )
        if span.determinism is DeterminismClass.UNKNOWN:
            raise ReplayNotClosedError(
                f"span {span.span_id!r} has undeclared determinism class; "
                f"replay cannot bound its non-determinism"
            )
        if span.determinism is DeterminismClass.SEEDED and span.seed is None:
            raise ReplayNotClosedError(
                f"span {span.span_id!r} is determinism=seeded but no seed "
                f"was recorded; replay would diverge silently"
            )
        if span.determinism is DeterminismClass.AUTHORITATIVE:
            if span.captured_output_body is None:
                raise ReplayNotClosedError(
                    f"span {span.span_id!r} is authoritative but only a hash "
                    f"was captured; replay cannot reproduce the output body"
                )
            recomputed = hashlib.sha256(span.captured_output_body).hexdigest()
            if span.captured_output_hash and recomputed != span.captured_output_hash:
                raise ReplayNotClosedError(
                    f"span {span.span_id!r} authoritative hash mismatch: "
                    f"recorded={span.captured_output_hash!r} "
                    f"recomputed={recomputed!r}"
                )


def replay_counterfactual(spans: dict[str, Span], leaf_id: str) -> None:
    assert_replay_closed(spans, leaf_id)
    # ... re-execute using captured bodies / seeds only ...
