# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-parent-span-link-the-dangling-context-invariant-in-genai-semantic-convention-span-linking-across-agent-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-parent-span-link-the-dangling-context-invariant-in-genai-semantic-convention-span-linking-across-agent-hops.warrant.json
# Markdown SHA-256:   7730c4831c0cbb3ae39df2d89930c6c1f82f1cda8a6cc0edf3ea4218ef81719a
# Code AST SHA-256:   b5d955871c0cb4778b2d97acf7d8f7b474cffe833907d2421e60dc9bed62dd39
# Verified Classes:   LinkEntailment, DanglingLinkError, HandoffContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class LinkEntailment(Enum):
    SAMPLING = "sampling"
    EXPORT = "export"
    IDENTITY = "identity"


class DanglingLinkError(RuntimeError):
    """Raised when an instance attempts to emit a parent span link whose
    target span is not guaranteed to be exported and resolvable."""


@dataclass(frozen=True)
class HandoffContext:
    upstream_trace_id: str
    upstream_span_id: str
    upstream_sampled: bool          # sampled bit from propagated traceparent
    export_ack_received: bool       # upstream confirmed flush before handoff
    identity_verified: bool         # span_id is the real one, not reconstructed
    same_trust_domain: bool         # trace-joining permitted across hops


def resolve_relationship(ctx: HandoffContext) -> str:
    """Decide whether to link, continue, or demote for a downstream hop.

    Returns one of: "link", "continue", "attribute_only".
    Raises DanglingLinkError if a bare link would be emitted without
    full entailment, and the caller has not authorized a fallback.
    """
    sampling_ok = ctx.upstream_sampled
    export_ok = ctx.export_ack_received
    identity_ok = ctx.identity_verified

    if sampling_ok and export_ok and identity_ok:
        return "link"

    # A bare link would be dangling. We must fall back, but only if the
    # fallback is itself valid for the trust topology.
    if not ctx.same_trust_domain:
        # Cross-domain: cannot join traces; record as inert attributes.
        return "attribute_only"

    # Same domain: promote to continuation with synthesized parent.
    # Continuation tolerates a missing upstream span (backend renders a
    # root gap), so a sampled-out upstream is safe here.
    if not sampling_ok:
        return "continue"

    # Sampling is fine but export or identity entailment failed. Emitting a
    # link here would be a transient or permanent dangling edge. Refuse.
    missing = []
    if not export_ok:
        missing.append(LinkEntailment.EXPORT.value)
    if not identity_ok:
        missing.append(LinkEntailment.IDENTITY.value)
    raise DanglingLinkError(
        "refusing to emit parent span link: entailment(s) unsatisfied: "
        f"{missing}; upstream_span_id={ctx.upstream_span_id!r} "
        f"trace_id={ctx.upstream_trace_id!r}. "
        "Require export_ack or verified identity before linking."
    )


def emit_hop_span(ctx: HandoffContext) -> str:
    try:
        relationship = resolve_relationship(ctx)
    except DanglingLinkError as exc:
        # Fail closed: degrade to attribute-only rather than corrupt the graph.
        # The caller may still choose to abort the hop entirely.
        relationship = "attribute_only"
        # Re-raise if policy forbids silent degradation.
        raise DanglingLinkError(str(exc)) from exc
    return relationship
