# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-trace-continuity-when-a-federated-a2a-task-graph-is-reconstructed-from-per-agent-span-logs-after-a-mid-task-re-delega.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-trace-continuity-when-a-federated-a2a-task-graph-is-reconstructed-from-per-agent-span-logs-after-a-mid-task-re-delega.warrant.json
# Markdown SHA-256:   388243fce89de83d91d4f8413a546322f4538d399ca4113b76bb4a4496d38b22
# Code AST SHA-256:   97ede7e0d5a1f915bd84d29ff28f13a762017915609a77cffd9a3269ef39797e
# Verified Classes:   CausalIndeterminateError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

SKEW_TOLERANCE_S = 0.005  # 5ms: NTP drift + one-way latency budget


class CausalIndeterminateError(RuntimeError):
    """Raised when a federated edge cannot be certified as causal."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    start: float
    end: float
    corroborated: bool = False   # independent signal confirms the parent link
    completion_echo: bool = False  # sender received back-reference on close


def certify_edge(parent: Span, child: Span) -> str:
    """Return provenance strength for a parent->child edge, or raise."""
    if child.parent_span_id != parent.span_id:
        raise CausalIndeterminateError(
            f"child {child.span_id} does not name {parent.span_id} as parent"
        )

    # Corroborated links dominate timestamps entirely.
    if child.corroborated:
        return "strong"

    skew = child.start - parent.start
    outlives = child.end - parent.end

    if skew < -SKEW_TOLERANCE_S:
        raise CausalIndeterminateError(
            f"negative skew {skew*1000:.1f}ms on {parent.span_id}->{child.span_id}: "
            f"child began before parent; uncorroborated link rejected"
        )

    if outlives > SKEW_TOLERANCE_S and not child.completion_echo:
        raise CausalIndeterminateError(
            f"{child.span_id} outlives parent {parent.span_id} by "
            f"{outlives*1000:.1f}ms with no completion echo; "
            f"cannot distinguish fire-and-forget from dropped context"
        )

    return "weak"


def reconstruct(edges: list[tuple[Span, Span]]) -> dict[str, str]:
    """Certify every edge; fail closed on any indeterminate causal claim."""
    result: dict[str, str] = {}
    for parent, child in edges:
        try:
            result[child.span_id] = certify_edge(parent, child)
        except CausalIndeterminateError as exc:
            # Surface indeterminacy to downstream auditors; never re-parent.
            result[child.span_id] = f"causally_indeterminate: {exc}"
    return result
