# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-epsilon-budget-laundering-across-federated-memory-enclaves-when-differentially-private-summaries-are-re-shared.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-epsilon-budget-laundering-across-federated-memory-enclaves-when-differentially-private-summaries-are-re-shared.warrant.json
# Markdown SHA-256:   383cec188f766f0a66c3146106cc2b0892374bb890a25c842284979964e5dd40
# Code AST SHA-256:   a9177acd88fe94c9baba9b9e8c051e99337fae95bd108d4dc7672f18e3ff8a8e
# Verified Classes:   EpsilonLaunderingError, DPPublication
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class EpsilonLaunderingError(RuntimeError):
    """Raised when correlated cross-enclave DP publications exceed the source bound."""
    pass


@dataclass
class DPPublication:
    publisher_id: str
    epsilon: float
    delta: float
    # source enclave -> declared epsilon contribution against that source
    lineage: Dict[str, float] = field(default_factory=dict)
    # estimated correlation against each ingested upstream summary
    correlation: Dict[str, float] = field(default_factory=dict)


RHO_THRESHOLD = 0.3
INFLATION_COEFF = 1.7  # empirical multiplier at rho ~ 0.7


def composed_epsilon_against(source_id: str, pubs: list[DPPublication]) -> float:
    """Correlated-composition bound against a single source enclave."""
    total = 0.0
    for pub in pubs:
        contrib = pub.lineage.get(source_id, 0.0)
        if contrib == 0.0:
            continue
        rho = pub.correlation.get(source_id, 0.0)
        if rho > RHO_THRESHOLD:
            contrib *= 1.0 + (INFLATION_COEFF - 1.0) * (rho - RHO_THRESHOLD) / (1.0 - RHO_THRESHOLD)
        total += contrib
    return total


def enforce_source_bound(
    source_id: str,
    declared_ceiling: float,
    pubs: list[DPPublication],
) -> float:
    bound = composed_epsilon_against(source_id, pubs)
    if bound > declared_ceiling + 1e-9:
        raise EpsilonLaunderingError(
            f"composed epsilon {bound:.3f} against source {source_id} "
            f"exceeds declared ceiling {declared_ceiling:.3f}; "
            f"publishers={[p.publisher_id for p in pubs]}"
        )
    return bound


def ingest_and_gate(
    candidate: DPPublication,
    existing: list[DPPublication],
    ceilings: Dict[str, float],
) -> Set[str]:
    """Gate a new publication against every source enclave in its lineage."""
    touched: Set[str] = set(candidate.lineage.keys())
    for source_id in touched:
        enforce_source_bound(source_id, ceilings[source_id], existing + [candidate])
    return touched
