# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-trace-to-eval-correlation-as-a-join-over-an-unstable-key-and-halt-score-attribution-when-the-span-identity-gr.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-trace-to-eval-correlation-as-a-join-over-an-unstable-key-and-halt-score-attribution-when-the-span-identity-gr.warrant.json
# Markdown SHA-256:   24c63ad2b097e2bab54b8a1fbfaa0f1796c9655593e56d1e526c559a1630db2d
# Code AST SHA-256:   0d963ba21e36d18c9de75185142c0ceced14c8ec9b0cee5f2b369ca4df3a77d9
# Verified Classes:   AttributionAmbiguity
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AttributionAmbiguity(RuntimeError):
    """Raised when a score and a safety flag cannot be attributed to a common,
    stable span under a single graph epoch."""
    pass


def correlate(score_event: dict, flag_event: dict, churn_threshold: int = 1) -> str:
    """
    Join an eval score and a safety flag onto a common span, or refuse.

    score_event: {"trace_id", "span_id", "graph_epoch", "span_set", "value"}
    flag_event:  {"trace_id", "span_set", "graph_epoch", "severity"}
    Returns the attributed span_id on success.
    """
    if score_event["trace_id"] != flag_event["trace_id"]:
        raise AttributionAmbiguity(
            f"cross-trace join refused: {score_event['trace_id']} vs {flag_event['trace_id']}"
        )

    s_epoch = score_event["graph_epoch"]
    f_epoch = flag_event["graph_epoch"]
    s_spans = set(score_event["span_set"])
    f_spans = set(flag_event["span_set"])

    if s_epoch != f_epoch:
        churn = len(s_spans.symmetric_difference(f_spans))
        if churn > churn_threshold:
            raise AttributionAmbiguity(
                f"epoch mismatch {s_epoch}->{f_epoch} with span churn {churn} "
                f"(threshold {churn_threshold}) on trace {score_event['trace_id']}"
            )

    scored_span = score_event["span_id"]
    if scored_span not in f_spans:
        # Disjoint-attribution signature: flag landed on leaves, score on parent.
        raise AttributionAmbiguity(
            f"score span {scored_span} not in flagged span set "
            f"{sorted(f_spans)} on trace {score_event['trace_id']}"
        )

    return scored_span
