# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-causal-trace-graph-as-authoritative-when-replay-diverges-from-the-recorded-trajectory.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-causal-trace-graph-as-authoritative-when-replay-diverges-from-the-recorded-trajectory.warrant.json
# Markdown SHA-256:   14e62edcbf9df2b1113b46635f123bab08f4fc8d720ac18405e4aa99ecef55b0
# Code AST SHA-256:   d5eadc02be25a68baf56ed531d04dbc8568073bb0aa2a9f59a1ad5388f5c28eb
# Verified Classes:   DivergenceVerdict, ReplayAdjudicationError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class DivergenceVerdict(Enum):
    IN_MODEL = "in_model"                  # harness may fault the span
    OUT_OF_MODEL = "out_of_model"          # harness must not fault any span
    GRAPH_INCOMPLETE = "graph_incomplete"  # trace authoritative, replay non-adjudicating


class ReplayAdjudicationError(RuntimeError):
    pass


@dataclass
class Span:
    span_id: str
    tool_version: Optional[str]
    sampler_seed: Optional[int]
    ordering_pinned: bool
    upstream_edges: list[str] = field(default_factory=list)
    output_hash: str = ""


def _all_sources_pinned(span: Span) -> bool:
    return (
        span.tool_version is not None
        and span.sampler_seed is not None
        and span.ordering_pinned
    )


def adjudicate_divergence(
    first_divergent_span: Span,
    graph_span_ids: set[str],
) -> DivergenceVerdict:
    # Structural check first: if an upstream dependency is missing from the
    # graph, the trace cannot be faithfully replayed regardless of pins.
    for edge in first_divergent_span.upstream_edges:
        if edge not in graph_span_ids:
            return DivergenceVerdict.GRAPH_INCOMPLETE

    # Only a fully pinned span licenses the harness to fault the trace.
    if not _all_sources_pinned(first_divergent_span):
        return DivergenceVerdict.OUT_OF_MODEL

    return DivergenceVerdict.IN_MODEL


def assert_replay_may_fault(span: Span, graph_span_ids: set[str]) -> None:
    verdict = adjudicate_divergence(span, graph_span_ids)
    if verdict is not DivergenceVerdict.IN_MODEL:
        # The harness must not attribute corruption to the trace here.
        raise ReplayAdjudicationError(
            f"replay cannot fault span {span.span_id!r}: verdict={verdict.value}; "
            f"trace graph remains authoritative for the executed run"
        )
