# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-causally-complete-tool-call-graph-reconstructed-across-federated-runtimes.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-causally-complete-tool-call-graph-reconstructed-across-federated-runtimes.warrant.json
# Markdown SHA-256:   b6765b8c39480e02c267ac1ed6990ce82012f8357d7aa3f421a130051cf76fa4
# Code AST SHA-256:   f9f94ef1a3a0f7cd5c6a39d220d1043fe349b10ff9544c88c1309938d5cd2135
# Verified Classes:   CausalityUnverifiedError, Span, Edge
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class CausalityUnverifiedError(RuntimeError):
    """Raised when a cross-runtime causal edge cannot be corroborated
    by a non-clock signal and must not be used to seed replay or attribution."""


@dataclass
class Span:
    runtime: str
    span_id: str
    parent_span_id: Optional[str]
    start: float          # runtime-local wall clock
    end: float
    seq: Optional[int] = None          # runtime-local monotonic counter
    input_hash: Optional[str] = None   # hash of consumed tool input
    output_hash: Optional[str] = None  # hash of produced tool output


@dataclass
class Edge:
    src: Span
    dst: Span
    verified: bool = field(default=False)


def _hash_payload(payload: str) -> str:
    return hashlib.sha256(payload.encode()).hexdigest()


def corroborate_edge(edge: Edge, offset_bound: float) -> Edge:
    """Decide whether a cross-runtime edge is causally trustworthy.

    Accepts on: explicit parent linkage within the parent's own clock interval,
    a payload hash chain, or a runtime-local sequence number.
    Rejects (raises) on timestamp-only ordering across runtimes.
    """
    src, dst = edge.src, edge.dst

    # Same-runtime parent linkage: trust the runtime's own clock.
    if src.runtime == dst.runtime and dst.parent_span_id == src.span_id:
        if src.start <= dst.start <= src.end:
            edge.verified = True
            return edge

    # Payload hash chain: strongest cross-runtime signal.
    if src.output_hash is not None and dst.input_hash is not None:
        if src.output_hash == dst.input_hash:
            edge.verified = True
            return edge

    # Runtime-local monotonic sequence: corroborates order without clocks.
    if src.runtime == dst.runtime and src.seq is not None and dst.seq is not None:
        if src.seq < dst.seq:
            edge.verified = True
            return edge

    # Timestamp-only cross-runtime ordering: only valid if the offset bound
    # is strictly smaller than the observed inter-span gap.
    gap = dst.start - src.start
    if src.runtime != dst.runtime and gap > offset_bound > 0:
        edge.verified = True
        return edge

    raise CausalityUnverifiedError(
        f"edge {src.span_id}({src.runtime}) -> {dst.span_id}({dst.runtime}) "
        f"is timestamp-only with gap={gap:.3f}s and offset_bound={offset_bound:.3f}s; "
        f"refusing to treat as causal"
    )


def seed_replay(graph_edges: list[Edge], offset_bound: float) -> list[Edge]:
    """Replay may only consume verified edges; unverified edges abort seeding."""
    verified = []
    for edge in graph_edges:
        try:
            verified.append(corroborate_edge(edge, offset_bound))
        except CausalityUnverifiedError:
            # Fail closed: do not silently drop, do not silently accept.
            raise
    return verified
