# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-stake-slashing-reputation-invariant-has-silently-inverted-under-sybil-pressure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-stake-slashing-reputation-invariant-has-silently-inverted-under-sybil-pressure.warrant.json
# Markdown SHA-256:   59c8b36e0c12999348eddb7cfc454d9689c04c88b5e6ea3ddf05ecc1403ff57f
# Code AST SHA-256:   0e764874b41bf421b50c13a5de4d605da48ec3ea1460440cc330c8f552e71a24
# Verified Classes:   ReputationInvariantInversion
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ReputationInvariantInversion(RuntimeError):
    """Raised when per-identity slashing checks pass but the cluster-aggregate invariant is violated."""
    pass


def check_cluster_slashing_invariant(
    cluster_id: str,
    attestation_weights: list[float],
    slashable_stakes: list[float],
    total_network_weight: float,
    value_at_risk: float,
    gamma: float = 2.0,
    min_cluster_size: int = 5,
) -> None:
    if len(attestation_weights) != len(slashable_stakes):
        raise ReputationInvariantInversion(
            f"cluster {cluster_id}: weight/stake length mismatch"
        )
    if len(attestation_weights) < min_cluster_size:
        # Below the clustering boundary: per-identity scoring is safe.
        return

    aggregate_weight = sum(attestation_weights)
    aggregate_stake = sum(slashable_stakes)
    influence_fraction = aggregate_weight / max(total_network_weight, 1e-9)
    required_stake = gamma * influence_fraction * value_at_risk

    if aggregate_stake < required_stake:
        raise ReputationInvariantInversion(
            f"cluster {cluster_id}: aggregate slashable stake {aggregate_stake:.3f} "
            f"< required {required_stake:.3f} (influence {influence_fraction:.3f}, "
            f"value_at_risk {value_at_risk:.1f}); per-identity checks may have passed "
            f"while the cluster invariant is inverted"
        )


def apply_reputation_update(
    cluster_id: str,
    attestation_weights: list[float],
    slashable_stakes: list[float],
    total_network_weight: float,
    value_at_risk: float,
) -> float:
    check_cluster_slashing_invariant(
        cluster_id, attestation_weights, slashable_stakes,
        total_network_weight, value_at_risk,
    )
    return sum(attestation_weights) / max(total_network_weight, 1e-9)
