# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-deterministic-replay-of-an-otel-span-graph-and-fall-back-to-forensic-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-deterministic-replay-of-an-otel-span-graph-and-fall-back-to-forensic-reconstruction.warrant.json
# Markdown SHA-256:   9610196069c3784a4b98d546eabb6743825af041fac2578b3458c6fe063e2dc2
# Code AST SHA-256:   bef10b24d009e2e7ca19a75e56b585b0aac088770187ce3942cfda42b93c62f6
# Verified Classes:   ReplayInvalidError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ReplayInvalidError(RuntimeError):
    """Raised when a session's span graph is not causally closed and must not be replayed."""


@dataclass
class Span:
    span_id: str
    parent_id: Optional[str]
    kind: str                 # "llm" | "tool"
    attributes: dict
    start_time: float


def check_causal_closure(spans: list[Span]) -> None:
    by_id = {s.span_id: s for s in spans}
    for s in spans:
        if s.kind == "llm":
            model = s.attributes.get("gen_ai.request.model")
            if not model:
                raise ReplayInvalidError(
                    f"span {s.span_id}: LLM span missing model pin; function unknown, "
                    "replay would be non-deterministic"
                )
            for msg in s.attributes.get("input.messages", []):
                src = msg.get("source_span_id")
                if src is None:
                    continue
                producer = by_id.get(src)
                if producer is None:
                    raise ReplayInvalidError(
                        f"span {s.span_id}: input cites absent span {src}"
                    )
                # causal edge must be ancestry, not mere temporal priority
                anc, cur = set(), producer.parent_id
                while cur is not None:
                    anc.add(cur)
                    cur = by_id[cur].parent_id if cur in by_id else None
                if s.span_id not in anc:
                    raise ReplayInvalidError(
                        f"span {s.span_id}: consumed output of {src} which is not an "
                        "ancestor; temporal ordering cannot substitute for the lost edge"
                    )
                if producer.attributes.get("output.truncated") and not msg.get("truncated"):
                    raise ReplayInvalidError(
                        f"span {s.span_id}: consumed truncated output of {src} without "
                        "truncation marker; replay would silently reproduce a different session"
                    )


def audit_session(spans: list[Span], terminal_state_known: bool) -> str:
    try:
        check_causal_closure(spans)
    except ReplayInvalidError:
        return "reconstruct" if terminal_state_known else "quarantine"
    return "replay"
