# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-otel-span-graph-replay-divergence-as-a-hard-stop-rather-than-a-tolerable-observability-artifact.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-otel-span-graph-replay-divergence-as-a-hard-stop-rather-than-a-tolerable-observability-artifact.warrant.json
# Markdown SHA-256:   11620ac3286ef10acee405ae0d5773a96caae6a3deb878fa6e9a13e98db2688e
# Code AST SHA-256:   21fc3c5af0a6162d30143b7b3b1adb3e7e5c1eaba6e4a4ba3f16bc758f68db8b
# Verified Classes:   UnsoundReplayError, Span, Conflict
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class UnsoundReplayError(RuntimeError):
    """Raised when a span graph cannot be faithfully linearized for replay."""


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_id: str | None
    start_ns: int
    end_ns: int
    attributes: dict = field(default_factory=dict)


@dataclass(frozen=True)
class Conflict:
    key: str
    span_a: str
    span_b: str
    downstream: tuple[str, ...]


def _has_happens_before_witness(a: Span, b: Span) -> bool:
    # A witness is an explicit link edge or a monotonic version attribute
    # carried by both spans over the same key.
    link_a = a.attributes.get("link.happens_before")
    link_b = b.attributes.get("link.happens_before")
    if link_a in (b.span_id, "*") or link_b in (a.span_id, "*"):
        return True
    va = a.attributes.get("state.version")
    vb = b.attributes.get("state.version")
    if va is not None and vb is not None and va != vb:
        return True
    return False


def audit_concurrent_writes(spans: Iterable[Span]) -> list[Conflict]:
    spans = list(spans)
    by_key: dict[str, list[Span]] = {}
    for s in spans:
        key = s.attributes.get("state.key")
        if key is not None and "state.value_after" in s.attributes:
            by_key.setdefault(key, []).append(s)

    conflicts: list[Conflict] = []
    for key, writers in by_key.items():
        for i, a in enumerate(writers):
            for b in writers[i + 1:]:
                if _has_happens_before_witness(a, b):
                    continue
                downstream = tuple(
                    s.span_id
                    for s in spans
                    if s.attributes.get("depends_on_key") == key
                    and s.span_id not in (a.span_id, b.span_id)
                )
                if downstream:
                    conflicts.append(
                        Conflict(key=key, span_a=a.span_id,
                                 span_b=b.span_id, downstream=downstream)
                    )
    return conflicts


def reconstruct_state(spans: Iterable[Span]) -> dict:
    conflicts = audit_concurrent_writes(spans)
    if conflicts:
        c = conflicts[0]
        raise UnsoundReplayError(
            f"shared-key '{c.key}' has concurrent writers "
            f"{c.span_a} and {c.span_b} with no happens-before witness, "
            f"but downstream spans {c.downstream} depend on it; "
            f"refusing to linearize"
        )
    ordered = sorted(spans, key=lambda s: (s.start_ns, s.span_id))
    state: dict = {}
    for s in ordered:
        key = s.attributes.get("state.key")
        if key is not None and "state.value_after" in s.attributes:
            state[key] = s.attributes["state.value_after"]
    return state
