# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-preserve-causal-trace-chains-when-head-based-sampling-drops-the-parent-span-at-a-federated-agent-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-preserve-causal-trace-chains-when-head-based-sampling-drops-the-parent-span-at-a-federated-agent-hop.warrant.json
# Markdown SHA-256:   8cb7f205ac630d000f7768dac0a5e58ed2c0cd3a37ba8b148e65e1bb69f76559
# Code AST SHA-256:   a3e42fb96c7453c57b8246dc0e29d73b645f83fb19458cf22258a84144e1ec83
# Verified Classes:   CausalChainViolation, Span, Hop
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalChainViolation(RuntimeError):
    """Raised when a hop breaks ancestor-closure by exporting a span
    whose causal parent was never emitted, without an explicit orphan marker."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    sampled: bool
    sampled_override: bool = False
    orphan: bool = False
    gap_at_hop: Optional[int] = None
    expected_sibling_count: Optional[int] = None
    retained_sibling_count: Optional[int] = None


@dataclass
class Hop:
    index: int
    retains_inbound_traceparent: bool
    local_tail_rule_fires: bool = False


def decide_export(
    span: Span,
    hop: Hop,
    inherited_sampled: bool,
    emitted_span_ids: set,
) -> Optional[Span]:
    """Apply head-based inherited decision, with a bounded override path.

    Returns the span to export, or None to suppress.
    Raises CausalChainViolation if the override would break ancestor-closure
    without metadata.
    """
    if inherited_sampled:
        return span

    if not hop.local_tail_rule_fires:
        return None  # honor head-based drop; ancestor-closure preserved

    # Override path: hop wants to keep a span on a dropped trace.
    if not hop.retains_inbound_traceparent:
        # Cannot reconstruct ancestor context -> must tag as orphan with gap.
        span.sampled_override = True
        span.orphan = True
        span.gap_at_hop = hop.index
        # still export, but the marker makes the gap visible to the collector
        return span

    # Retains context: emit ancestor stub for the immediate parent if absent.
    if span.parent_span_id is not None and span.parent_span_id not in emitted_span_ids:
        span.sampled_override = True
        # stub for parent would be emitted by caller; here we assert the contract
        # that the parent stub is registered before this child is exported.
        if span.parent_span_id not in emitted_span_ids:
            raise CausalChainViolation(
                f"hop {hop.index}: overriding sampled=0->1 for span "
                f"{span.span_id} on trace {span.trace_id} but parent "
                f"{span.parent_span_id} has no emitted stub; ancestor-closure "
                f"would be violated. Emit parent stub or set orphan=true."
            )
    span.sampled_override = True
    return span


def check_fanout_integrity(span: Span) -> None:
    if (
        span.expected_sibling_count is not None
        and span.retained_sibling_count is not None
        and span.retained_sibling_count < span.expected_sibling_count
        and not span.orphan
    ):
        raise CausalChainViolation(
            f"span {span.span_id}: retained {span.retained_sibling_count}/"
            f"{span.expected_sibling_count} siblings on a sampled trace with no "
            f"orphan marker; fan-out truncation is invisible to attribution."
        )
