# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-dp-budget-exhaustion-from-context-divergence-in-federated-shared-memory-and-why-the-two-are-operationally-indisting.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-dp-budget-exhaustion-from-context-divergence-in-federated-shared-memory-and-why-the-two-are-operationally-indisting.warrant.json
# Markdown SHA-256:   121d68744e572c3e2b98aa63bc46c7db89f05298db56b34395f386dcd38e817c
# Code AST SHA-256:   188bccfee34e3fec1662d91c3360872638c8d5da720bcaf76a93b24015fccc2a
# Verified Classes:   AttributionError, ContributorState, DeltaEnvelope
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class AttributionError(RuntimeError):
    """Raised when merge degradation cannot be soundly attributed."""
    pass


class ContributorState(Enum):
    HEALTHY = "healthy"
    EXHAUSTED = "exhausted"
    DIVERGED = "diverged"
    UNKNOWN = "unknown"


@dataclass
class DeltaEnvelope:
    contributor_id: str
    budget_nonce: float | None      # remaining epsilon, signed; None if absent
    expected_key_overlap: float     # overlap with receiver's expected support
    mutual_info_with_local: float   # only computable if contributor cooperates


def attribute_merge_degradation(
    envelopes: list[DeltaEnvelope],
    overlap_threshold: float = 0.15,
    exhaustion_epsilon: float = 1e-3,
) -> dict[str, ContributorState]:
    """
    Classify each contributor. Refuses to attribute per-contributor when
    budget nonces are absent, because exhaustion and divergence are
    observationally identical at the merge point (see article).
    """
    if any(e.budget_nonce is None for e in envelopes):
        if not all(e.budget_nonce is None for e in envelopes):
            raise AttributionError(
                "Mixed nonce availability: partial ledger cannot soundly "
                "separate exhaustion from divergence for nonce-less "
                "contributors. Refusing partial attribution."
            )
        # No ledger at all: only a global verdict is sound.
        verdict = (
            ContributorState.UNKNOWN
            if any(e.expected_key_overlap < overlap_threshold for e in envelopes)
            else ContributorState.HEALTHY
        )
        return {e.contributor_id: verdict for e in envelopes}

    states: dict[str, ContributorState] = {}
    for e in envelopes:
        if e.budget_nonce <= exhaustion_epsilon:
            states[e.contributor_id] = ContributorState.EXHAUSTED
        elif e.expected_key_overlap < overlap_threshold:
            states[e.contributor_id] = ContributorState.DIVERGED
        else:
            states[e.contributor_id] = ContributorState.HEALTHY
    return states


def assert_attribution_sound(envelopes: list[DeltaEnvelope]) -> None:
    """Guard called before any per-contributor remediation is applied."""
    states = attribute_merge_degradation(envelopes)
    if any(s is ContributorState.UNKNOWN for s in states.values()):
        raise AttributionError(
            "Per-contributor remediation attempted under UNKNOWN attribution; "
            "add signed budget nonces before re-tuning merge heuristics."
        )
