# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-federated-memory-shard-it-just-reconstructed-from-noisy-deltas.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-federated-memory-shard-it-just-reconstructed-from-noisy-deltas.warrant.json
# Markdown SHA-256:   e34fab9a0ac1cab0ed9b8cf3c388d01f9c76e6f7a5035a27691313f0b75626bd
# Code AST SHA-256:   040ceea88bca3ece685e00e0dd326ec5b5a4a896ea30eec37491b09b5cc8c926
# Verified Classes:   ProvenanceContentDivergence, FederatedShard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Mapping


class ProvenanceContentDivergence(RuntimeError):
    """Raised when a federated shard's realized content mass exceeds the
    noise floor attributable to its attested provenance for a given tenant."""


@dataclass
class FederatedShard:
    shard_id: str
    provenance_tags: frozenset[str]          # tenants the aggregator *claims* contributed
    realized_contribution: Mapping[str, float]  # tenant -> fraction of fused L2 norm
    realized_epsilon: float
    noise_floor_fraction: float              # DP noise mass as fraction of norm

    def unauthorized_mass(self, authorized: frozenset[str]) -> float:
        return sum(
            mass for tenant, mass in self.realized_contribution.items()
            if tenant not in authorized
        )


def verify_tenant_isolation(
    shard: FederatedShard,
    requesting_tenant: str,
    remaining_budget: float,
) -> None:
    authorized = frozenset({requesting_tenant})

    # Tag check alone is insufficient: a dominating unauthorized tenant is
    # still a legitimate member of the tag set.
    if requesting_tenant not in shard.provenance_tags:
        raise ProvenanceContentDivergence(
            f"shard {shard.shard_id} not tagged for {requesting_tenant}"
        )

    # Read-time budget coupling: realized epsilon, not write-time estimate.
    if shard.realized_epsilon > remaining_budget:
        raise ProvenanceContentDivergence(
            f"shard {shard.shard_id} realized_epsilon={shard.realized_epsilon} "
            f"exceeds remaining_budget={remaining_budget}"
        )

    # Content-mass verification: unauthorized contribution must sit below the
    # DP noise floor, otherwise the tag is a false provenance claim.
    leaked = shard.unauthorized_mass(authorized)
    if leaked > shard.noise_floor_fraction:
        raise ProvenanceContentDivergence(
            f"shard {shard.shard_id} carries unauthorized mass {leaked:.3f} "
            f"above noise floor {shard.noise_floor_fraction:.3f}; "
            f"provenance tags {sorted(shard.provenance_tags)} understate content"
        )
