# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-an-otel-span-graph-drift-score-when-the-baseline-was-itself-collected-from-a-non-stationary-agent-populati.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-an-otel-span-graph-drift-score-when-the-baseline-was-itself-collected-from-a-non-stationary-agent-populati.warrant.json
# Markdown SHA-256:   75d98814807478927883f08fa310fe5118957f370dd6db36478ded61e08444d3
# Code AST SHA-256:   9a64180130763c98019bb0496e89f7251cc90ddfb304a14e5b53943bfebeb2c5
# Verified Classes:   BaselineInvalidError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class BaselineInvalidError(RuntimeError):
    """Raised when a span-graph drift score cannot be interpreted as an anomaly signal."""
    pass


def score_trace_drift(
    trace_graph,
    trace_version_tuple,
    baseline_partitions,
    stationarity_threshold=0.05,
    min_cohort_size=500,
):
    # Step 1: locate a version-matched baseline partition.
    partition = baseline_partitions.get(trace_version_tuple)
    if partition is None or partition.size < min_cohort_size:
        raise BaselineInvalidError(
            f"no version-matched cohort for {trace_version_tuple} "
            f"(size={0 if partition is None else partition.size}, "
            f"required={min_cohort_size}); drift score is uninterpretable"
        )

    # Step 2: verify the partition is internally stationary.
    # Pairwise kernel MMD across disjoint sub-windows; if the baseline
    # disagrees with itself more than with live traffic, it is a mixture.
    sub_windows = partition.split_into_windows(k=5)
    max_pairwise_mmd = max(
        graph_kernel_mmd(a, b)
        for i, a in enumerate(sub_windows)
        for b in sub_windows[i + 1:]
    )
    if max_pairwise_mmd > stationarity_threshold:
        raise BaselineInvalidError(
            f"baseline partition {trace_version_tuple} is non-stationary "
            f"(max pairwise MMD={max_pairwise_mmd:.4f} > "
            f"tau={stationarity_threshold}); refusing to score"
        )

    # Step 3: only now does the distance carry anomaly semantics.
    return graph_kernel_distance(trace_graph, partition.mean_embedding())
