# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-propagates-a-parent-span-id-across-an-agent-hop-but-never-emits-the-corresponding-child-span.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-propagates-a-parent-span-id-across-an-agent-hop-but-never-emits-the-corresponding-child-span.warrant.json
# Markdown SHA-256:   de31be53330e96bba1e090eb4665e6defef2037fd4e3a0f2eadbf224c1c17651
# Code AST SHA-256:   1fd4f6808e94d5c4d783c624c8f8c43cdd43789f43e25d9ecec9aedf0bdf4e81
# Verified Classes:   DanglingParentError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class DanglingParentError(RuntimeError):
    """Raised when a span is about to be exported with an unresolvable,
    unmarked parent reference, which would corrupt causal reconstruction."""
    pass


def validate_span_for_export(span, known_exported_span_ids, sampled_out_span_ids):
    """
    span: dict with keys span_id, trace_id, parent_span_id (may be None),
          attributes (dict).
    known_exported_span_ids: set of span_ids already confirmed exported in
          this trace segment.
    sampled_out_span_ids: set of span_ids known to have been dropped by the
          sampler (carried via traceparent trace_flags).
    """
    parent = span.get("parent_span_id")
    if parent is None:
        return  # genuine root

    if parent in known_exported_span_ids:
        return  # resolves within segment

    if parent in sampled_out_span_ids:
        # Absent by design: record the marker so reconstruction treats this
        # as a valid terminus rather than a dangling edge.
        span["attributes"]["parent_sampled_out"] = True
        return

    # Parent is neither exported nor known-sampled-out. The span must not be
    # exported with a live parent reference; doing so silently promotes a
    # mid-chain span to root at query time.
    raise DanglingParentError(
        f"span {span['span_id']} in trace {span['trace_id']} references "
        f"parent {parent} that is neither exported nor marked sampled-out; "
        f"refusing export to preserve causal integrity"
    )
