# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-preserve-causal-span-linkage-across-an-agent-hop-when-the-downstream-trace-clock-is-skewed-and-the-trajectory-is-replayed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-preserve-causal-span-linkage-across-an-agent-hop-when-the-downstream-trace-clock-is-skewed-and-the-trajectory-is-replayed.warrant.json
# Markdown SHA-256:   247e902993054a0fe72e6c71e55173e4ebb828155db596ff6f9f4b8b41e0f5ce
# Code AST SHA-256:   58444e09054ddee845062c6c2490d1906bb80d6fc979f8c246536ea14d9ec086
# Verified Classes:   ReplayDivergence, CausalOrderViolation, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ReplayDivergence(RuntimeError):
    """Raised when a replayed trajectory would diverge from the recorded one."""


class CausalOrderViolation(RuntimeError):
    """Raised when a parent-child edge is temporally inconsistent after reconciliation."""


@dataclass
class Span:
    span_id: str
    parent_span_id: str | None
    start_ts: float          # reconciled, seconds
    end_ts: float
    content_hash: str | None  # hash of exact handoff bytes, if this span is a handoff
    content_blob: bytes | None


def reconcile_edge(parent: Span, child: Span, clock_offset_s: float) -> None:
    """Validate that child causally follows parent after applying child's clock offset."""
    adjusted_child_start = child.start_ts + clock_offset_s
    if adjusted_child_start < parent.end_ts:
        raise CausalOrderViolation(
            f"child {child.span_id} starts {parent.end_ts - adjusted_child_start:.3f}s "
            f"before parent {parent.span_id} ends; edge is structural, not causal"
        )


def replay_handoff(span: Span, replayed_bytes: bytes) -> bytes:
    """Re-inject recorded handoff bytes; fail closed on content mismatch."""
    if span.content_hash is None or span.content_blob is None:
        raise ReplayDivergence(
            f"handoff span {span.span_id} has no recorded content; cannot replay causally"
        )
    if hashlib.sha256(replayed_bytes).hexdigest() != span.content_hash:
        raise ReplayDivergence(
            f"replayed bytes for {span.span_id} do not match recorded hash; "
            f"trajectory branch must be marked non-replayable"
        )
    return span.content_blob


def replay_trajectory(spans: list[Span], offsets: dict[str, float]) -> list[Span]:
    by_id = {s.span_id: s for s in spans}
    ordered = sorted(spans, key=lambda s: s.start_ts + offsets.get(s.span_id, 0.0))
    for s in ordered:
        if s.parent_span_id is None:
            continue
        parent = by_id.get(s.parent_span_id)
        if parent is None:
            raise ReplayDivergence(f"orphan span {s.span_id}")
        reconcile_edge(parent, s, offsets.get(s.span_id, 0.0))
    return ordered
