# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-sever-a-causal-trace-link-when-a-federated-hop-returns-a-plausible-but-unwitnessed-span.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-sever-a-causal-trace-link-when-a-federated-hop-returns-a-plausible-but-unwitnessed-span.warrant.json
# Markdown SHA-256:   0aa11b0c2a606388ea96cf5f16a676e4bb3983434515afd61f628861627b468d
# Code AST SHA-256:   48abe52af7ddb065c50a0c15c16613f5f793e675127ae732687c1bc390840b0a
# Verified Classes:   CausalLinkSevered, SpanAttestation, IncomingChild
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CausalLinkSevered(RuntimeError):
    """Raised when a federated hop cannot witness its asserted parent span."""
    pass


@dataclass(frozen=True)
class SpanAttestation:
    """Signed statement from the emitting domain about a span it owns."""
    trace_id: str
    span_id: str
    emitting_domain: str
    terminal_status: str          # "OK" | "ERROR" | "ABORTED"
    start_mono: int               # reconciled monotonic ticks
    end_mono: Optional[int]
    emission_seq: int             # disambiguates re-emissions; unique per span_id
    signature_valid: bool


@dataclass(frozen=True)
class IncomingChild:
    trace_id: str
    parent_span_id: str           # asserted by the header, NOT trusted
    child_start_mono: int
    child_claims_ok: bool
    recovered_from_abort: bool = False


def resolve_link(child: IncomingChild,
                 attestations: list[SpanAttestation]) -> SpanAttestation:
    """
    Decide whether a cross-trust hop may extend the asserted parent trace.
    Returns the witnessed parent attestation on success.
    Raises CausalLinkSevered when the link must be forked instead of joined.
    """
    matches = [a for a in attestations
               if a.trace_id == child.trace_id
               and a.span_id == child.parent_span_id]

    if not matches:
        raise CausalLinkSevered(
            f"no attested parent {child.parent_span_id} for trace "
            f"{child.trace_id}; fork as CAUSAL_ORPHAN"
        )

    if len(matches) > 1:
        # same (trace_id, span_id) emitted more than once -> non-deterministic
        # join; quarantine rather than pick one.
        raise CausalLinkSevered(
            f"ambiguous emission of {child.parent_span_id} "
            f"({len(matches)} physical spans); quarantine trace"
        )

    parent = matches[0]

    if not parent.signature_valid:
        raise CausalLinkSevered(
            f"parent {parent.span_id} attestation unsigned by "
            f"{parent.emitting_domain}; default-deny cross-trust link"
        )

    if (parent.terminal_status in ("ABORTED", "ERROR")
            and child.child_claims_ok
            and not child.recovered_from_abort):
        raise CausalLinkSevered(
            f"child claims OK but parent {parent.span_id} terminal="
            f"{parent.terminal_status}; sever and emit provenance_fault"
        )

    if parent.end_mono is not None and child.child_start_mono < parent.end_mono:
        # child began before parent closed: enclosure violated, likely a
        # re-emission or a fabricated parent.
        raise CausalLinkSevered(
            f"temporal enclosure violated: child start "
            f"{child.child_start_mono} < parent end {parent.end_mono}"
        )

    return parent


def extend_or_fork(child: IncomingChild,
                   attestations: list[SpanAttestation]) -> dict:
    try:
        parent = resolve_link(child, attestations)
        return {"link": "EXTEND", "parent_span_id": parent.span_id,
                "emission_seq": parent.emission_seq}
    except CausalLinkSevered as exc:
        # severance is a first-class event, not a silent repair
        return {"link": "FORK", "link_type": "CAUSAL_ORPHAN",
                "rejected_parent": child.parent_span_id,
                "provenance_fault": str(exc)}
