# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-residency-violations-in-cross-org-agent-federation-when-policy-negotiation-succeeds-on-the-control-plane-but-data-plan.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-residency-violations-in-cross-org-agent-federation-when-policy-negotiation-succeeds-on-the-control-plane-but-data-plan.warrant.json
# Markdown SHA-256:   1f93156811c06886adc3e0e7ffedecf5f966a8291eddc143a9c08b854de72fc5
# Code AST SHA-256:   58807c4ca4cf6de5d4d0dccecaa43be72724646b8954aa361e06d466e8ce8ecd
# Verified Classes:   ResidencyInvariantViolation, Policy, PlacementAttestation, CacheEntry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import FrozenSet


class ResidencyInvariantViolation(RuntimeError):
    """Raised when an artifact's effective placement is not permitted by the
    policy identity that authorized the current request."""


@dataclass(frozen=True)
class Policy:
    policy_id: str
    allowed_regions: FrozenSet[str]
    retention_days: int
    forbid_cross_border: bool = True

    def permits_region(self, region: str) -> bool:
        return region in self.allowed_regions


@dataclass(frozen=True)
class PlacementAttestation:
    """Signed claim from the storage layer about where bytes actually rest."""
    artifact_id: str
    region: str
    authorizing_policy_id: str
    signature: str


@dataclass
class CacheEntry:
    artifact_id: str
    region: str
    authorizing_policy: Policy
    payload: bytes = field(repr=False, default=b"")


def resolve_placement(
    request_policy: Policy,
    cache: dict[str, CacheEntry],
    artifact_id: str,
) -> PlacementAttestation:
    """Resolve placement for an artifact under the *current* request policy.

    Reuses a cached placement only if the cached entry's authorizing policy is
    at least as permissive on the residency dimension AND the cached region is
    permitted by the current policy. Otherwise re-places or raises.
    """
    cached = cache.get(artifact_id)
    if cached is not None:
        region_ok = request_policy.permits_region(cached.region)
        policy_ok = (
            cached.authorizing_policy.retention_days >= request_policy.retention_days
            and (
                not request_policy.forbid_cross_border
                or not cached.authorizing_policy.forbid_cross_border
                or cached.region in request_policy.allowed_regions
            )
        )
        if region_ok and policy_ok:
            return PlacementAttestation(
                artifact_id=artifact_id,
                region=cached.region,
                authorizing_policy_id=request_policy.policy_id,
                signature=f"attest:{artifact_id}:{cached.region}:{request_policy.policy_id}",
            )
        # Stricter current policy: do not reuse. Re-place or fail closed.
        if not region_ok:
            raise ResidencyInvariantViolation(
                f"artifact {artifact_id} cached in {cached.region} under policy "
                f"{cached.authorizing_policy.policy_id}; current policy "
                f"{request_policy.policy_id} permits only "
                f"{sorted(request_policy.allowed_regions)}. Re-placement required."
            )
        raise ResidencyInvariantViolation(
            f"artifact {artifact_id} cached under policy "
            f"{cached.authorizing_policy.policy_id} whose retention "
            f"({cached.authorizing_policy.retention_days}d) is not a superset of "
            f"current policy {request_policy.policy_id} "
            f"({request_policy.retention_days}d). Artifact lifecycle bound to wrong agreement."
        )

    # Cold path: place in the first permitted region, attest to it.
    target = next(iter(sorted(request_policy.allowed_regions)), None)
    if target is None:
        raise ResidencyInvariantViolation(
            f"policy {request_policy.policy_id} has empty allowed_regions; "
            f"cannot place artifact {artifact_id}."
        )
    cache[artifact_id] = CacheEntry(
        artifact_id=artifact_id,
        region=target,
        authorizing_policy=request_policy,
    )
    return PlacementAttestation(
        artifact_id=artifact_id,
        region=target,
        authorizing_policy_id=request_policy.policy_id,
        signature=f"attest:{artifact_id}:{target}:{request_policy.policy_id}",
    )


def audit_event(attestation: PlacementAttestation, request_policy: Policy) -> dict:
    """Audit reads the *attestation* (observed placement), never the policy
    alone. If attestation region is not permitted, the audit must fail closed."""
    if not request_policy.permits_region(attestation.region):
        raise ResidencyInvariantViolation(
            f"audit refused: attested region {attestation.region} for "
            f"{attestation.artifact_id} not in policy {request_policy.policy_id}"
        )
    return {
        "artifact_id": attestation.artifact_id,
        "observed_region": attestation.region,
        "authorizing_policy_id": attestation.authorizing_policy_id,
        "signature": attestation.signature,
        "compliant": True,
    }


# --- reproduction of the observed failure ---
eu_policy = Policy("eu-tenant", frozenset({"eu-central-1"}), retention_days=30)
us_policy = Policy("us-tenant", frozenset({"us-east-1"}), retention_days=30)

cache: dict[str, CacheEntry] = {}

# US tenant warms the cache first (permitted under its own agreement).
resolve_placement(us_policy, cache, "artifact-x")

# EU tenant now requests the same artifact. A naive system reuses the cache
# entry and stamps metadata from the agreement -> silent violation.
# The invariant-bearing resolver raises instead:
try:
    resolve_placement(eu_policy, cache, "artifact-x")
    raise AssertionError("expected ResidencyInvariantViolation")
except ResidencyInvariantViolation as e:
    print("caught as designed:", e)
