# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-merge-a-remote-trace-context-the-sampling-probability-inversion-in-cross-org-span-export.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-merge-a-remote-trace-context-the-sampling-probability-inversion-in-cross-org-span-export.warrant.json
# Markdown SHA-256:   1f858e35edad3401231002fa9363676232c106cf2697306a8d8f74e8fec7f56e
# Code AST SHA-256:   bac24ea64de80082789c692b3151e9859b3a41b7d961b14137cbcfa8c087db5a
# Verified Classes:   SamplingProvenanceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SamplingProvenanceError(RuntimeError):
    """Raised when an inbound federated span cannot be admitted to a representative partition."""
    pass


REQUIRED_TRACESTATE_KEYS = ("rate_success", "rate_error", "retention")


def admit_remote_span(span: dict, local_partition: str) -> str:
    """
    Decide the destination partition for an inbound cross-org span.

    span: {"trace_id", "span_id", "class": "success"|"error"|"other",
           "tracestate": dict, "sampled": bool}
    Returns the partition name. Raises SamplingProvenanceError when the
    span claims sampled=1 but its effective rate is not carried in-band.
    """
    if not span.get("sampled", False):
        # Unsampled contexts are never merged; they are dropped at the edge.
        return "dropped"

    ts = span.get("tracestate") or {}
    missing = [k for k in REQUIRED_TRACESTATE_KEYS if k not in ts]

    if missing:
        # sampled=1 with no rate disclosure: cannot be weighted, cannot be
        # representative. Quarantine, and surface the provenance gap.
        raise SamplingProvenanceError(
            f"trace {span['trace_id']} span {span['span_id']} class={span['class']} "
            f"sampled=1 but tracestate missing {missing}; "
            f"refusing representative admission into {local_partition}"
        )

    rate_key = "rate_error" if span["class"] == "error" else "rate_success"
    try:
        rate = float(ts[rate_key])
    except (TypeError, ValueError) as exc:
        raise SamplingProvenanceError(
            f"trace {span['trace_id']} carries non-numeric {rate_key}={ts[rate_key]!r}"
        ) from exc

    if not (0.0 < rate <= 1.0):
        raise SamplingProvenanceError(
            f"trace {span['trace_id']} carries out-of-range {rate_key}={rate}"
        )

    if ts["retention"] == "tail":
        # Tail-retained spans are class-conditional and must not be pooled
        # with head-admitted spans without a weight.
        return "quarantine_tail_retained"

    span["sampling_weight"] = 1.0 / rate
    return "representative"
