# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-cross-domain-attestation-whose-reputation-weight-exceeds-its-own-local-trust-ceiling-and-how-does-sybi.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-cross-domain-attestation-whose-reputation-weight-exceeds-its-own-local-trust-ceiling-and-how-does-sybi.warrant.json
# Markdown SHA-256:   39593c16b42ef97f90d5b787a8a8a7f8974698bc66b4e1c6b05c2b84fe79ff36
# Code AST SHA-256:   0809570c8912ed665134ee44873a0f01e0f4dd4d6be30c3b070ec654895e0b2b
# Verified Classes:   TrustCeilingViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class TrustCeilingViolation(RuntimeError):
    """Raised when a cross-domain attestation set cannot be safely folded
    into local reputation because provenance deduplication fails the floor
    or the ceiling is being applied to an attacker-controlled aggregate."""
    pass


def fold_cross_domain_reputation(
    attestations: list[dict],
    local_ceiling: float,
    local_identity_cost: float,
    provenance_floor: int = 3,
    straddle_margin: float = 0.1,
) -> float:
    """
    attestation = {
        "issuer_domain": str,
        "weight": float,            # 0..1 remote belief
        "controller_id": str,       # post signature-clustering controller
        "issuer_identity_cost": float,
    }
    Order of operations is the invariant:
      dedup by controller -> discount by cost ratio -> apply ceiling -> aggregate.
    """
    if not attestations:
        raise TrustCeilingViolation("empty attestation set: cannot establish provenance")

    # 1. Deduplicate to independent controllers.
    by_controller: dict[str, list[dict]] = {}
    for a in attestations:
        if a["weight"] < 0.0 or a["weight"] > 1.0:
            raise TrustCeilingViolation(f"weight out of range: {a['weight']}")
        by_controller.setdefault(a["controller_id"], []).append(a)

    independent = len(by_controller)

    # 2. Cost-ratio discount: cheap identities must not inflate count.
    raw_count = len(attestations)
    min_cost = min(a["issuer_identity_cost"] for a in attestations)
    cost_ratio = min_cost / local_identity_cost if local_identity_cost > 0 else 1.0
    admissible = independent >= provenance_floor and independent >= raw_count * cost_ratio

    if not admissible:
        raise TrustCeilingViolation(
            f"provenance floor failed: {independent} independent controllers "
            f"for {raw_count} attestations (cost_ratio={cost_ratio:.2f}, "
            f"floor={provenance_floor})"
        )

    # 3. Per-controller representative weight, then ceiling, then mean.
    per_controller = [max(a["weight"] for a in group) for group in by_controller.values()]
    clamped = [min(w, local_ceiling) for w in per_controller]
    aggregate = sum(clamped) / len(clamped)

    # 4. Straddle band requires quorum re-verification, not local resolution.
    if abs(aggregate - local_ceiling) <= straddle_margin:
        raise TrustCeilingViolation(
            f"aggregate {aggregate:.3f} straddles ceiling {local_ceiling:.3f} "
            f"within {straddle_margin}; escalate to quorum re-verification"
        )

    return aggregate
