# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-trace-mutation-divergence-when-observability-correlation-windows-decouple-memory-writes-from-the-spans-that-justified-them.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-trace-mutation-divergence-when-observability-correlation-windows-decouple-memory-writes-from-the-spans-that-justified-them.warrant.json
# Markdown SHA-256:   a1b9bdb7396214d3a66671d0d3a2e37e8bb256fdee069c45ac1e114780e5ae8b
# Code AST SHA-256:   f9073a150c7ec722a47b12f1cf3c9e3157561fca22cf1c28f93c4f1d53a1cb0b
# Verified Classes:   UnattributableAlert, ProvenanceTokenInvalid
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnattributableAlert(RuntimeError):
    """Raised when an injection alert cannot be causally tied to a memory mutation
    by provenance token. The pipeline must refuse auto-remediation rather than
    fall back to temporal proximity."""
    pass


class ProvenanceTokenInvalid(RuntimeError):
    """Raised when a mutation's caused_by_span token fails round-trip validation
    (missing, stripped by backend, or not a known span ID)."""
    pass


def resolve_alert(alert, mutations, known_spans):
    """
    alert:      {span_id, taint_set: set[span_id]}
    mutations:  list of {mutation_id, caused_by_span, timestamp}
    known_spans: set of valid span IDs emitted this session
    """
    tainted = alert["taint_set"] | {alert["span_id"]}
    candidates = []

    for m in mutations:
        token = m.get("caused_by_span")
        if token is None:
            # Backend stripped the token: cannot attribute, must not guess.
            raise ProvenanceTokenInvalid(
                f"mutation {m['mutation_id']} has no provenance token; "
                f"temporal correlation is not causation"
            )
        if token not in known_spans:
            raise ProvenanceTokenInvalid(
                f"mutation {m['mutation_id']} cites unknown span {token}"
            )
        if token in tainted:
            candidates.append(m["mutation_id"])

    if not candidates:
        # No mutation traces to the alert's taint set. Do NOT attach to the
        # nearest-timestamp mutation. Refuse and escalate.
        raise UnattributableAlert(
            f"alert on {alert['span_id']} has no provenance-linked mutation; "
            f"refusing temporal fallback"
        )

    # Fan-out quarantine: roll back every tainted mutation, never just one.
    return {"action": "quarantine", "mutation_ids": candidates}
