# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-brokered-capability-whose-policy-translation-is-semantically-lossy-across-federated-trust-domains.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-brokered-capability-whose-policy-translation-is-semantically-lossy-across-federated-trust-domains.warrant.json
# Markdown SHA-256:   3c7a922c695ca48255a16c295d07bd640fed8d631a8aa3042254f4f9618f57de
# Code AST SHA-256:   36b12bb5dc36a3661164f0371445e8b215e6814bdd5ebdea9044ca72911c52ad
# Verified Classes:   UnsoundTranslationError, Grant, Broker
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class UnsoundTranslationError(RuntimeError):
    """Raised when a brokered capability translation is complete but not sound."""
    pass


@dataclass(frozen=True)
class Grant:
    capability: str
    predicates: FrozenSet[str]  # e.g. {"jurisdiction:EU", "retention<=30d", "purpose:fraud"}


@dataclass
class Broker:
    ontology_map: dict  # source predicate -> target predicate or None
    strategy: str = "sound"  # "sound" | "best_effort"

    def translate(self, g_a: Grant) -> tuple[Grant, list[str]]:
        mapped, unmapped = set(), []
        for p in g_a.predicates:
            target = self.ontology_map.get(p)
            if target is None:
                unmapped.append(p)
            else:
                mapped.add(target)
        return Grant(g_a.capability, frozenset(mapped)), unmapped

    def broker(self, g_a: Grant) -> Grant:
        g_b, unmapped = self.translate(g_a)
        if unmapped:
            if self.strategy == "best_effort":
                # silently widens: drops constraints, emits grant anyway
                return g_b
            raise UnsoundTranslationError(
                f"translation of {g_a.capability!r} is complete but unsound: "
                f"unmapped predicates {unmapped} would be dropped, widening the grant"
            )
        # soundness check: every source predicate must be entailed by target
        for p in g_a.predicates:
            target = self.ontology_map[p]
            if target not in g_b.predicates:
                raise UnsoundTranslationError(
                    f"predicate {p!r} mapped to {target!r} but absent from translated grant"
                )
        return g_b


def consume(grant: Grant, execution_scope: int, max_scope: int) -> None:
    if execution_scope > max_scope:
        raise UnsoundTranslationError(
            f"execution scope {execution_scope} exceeds grant-derived bound {max_scope}; "
            "capability was widened by an unsound brokered translation"
        )


if __name__ == "__main__":
    g_a = Grant("read(records)", frozenset({"jurisdiction:EU", "retention<=30d", "purpose:fraud"}))
    broker = Broker(
        ontology_map={"jurisdiction:EU": "jurisdiction:EU", "retention<=30d": None, "purpose:fraud": None},
        strategy="best_effort",
    )
    g_b = broker.broker(g_a)  # returns widened grant, no error under best_effort
    # consumer applies its own bound (records cap) and detects the widening
    consume(g_b, execution_scope=300_000, max_scope=1_000)
