# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-peer-s-translated-policy-without-re-validating-its-data-boundary-predicates.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-peer-s-translated-policy-without-re-validating-its-data-boundary-predicates.warrant.json
# Markdown SHA-256:   1d8a6c613e6eaaceca75b7f9c7cbcada7c50b4a8da0f0db1f2aa0d843d0bd243
# Code AST SHA-256:   8e625882faa95f49df8e9a5cedabbd9607cecb3fe2a41f4f6da7a541bc57494a
# Verified Classes:   PolicyTranslationRefinementError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PolicyTranslationRefinementError(RuntimeError):
    """Raised when a peer's translated policy is not a certified refinement of its source."""
    pass


def admit_federated_policy(source_policy: dict, translated_policy: dict,
                           translator_certificate: dict | None) -> dict:
    # Trust envelope already verified upstream; this gate is ONLY about equivalence.
    if translator_certificate is None:
        # No refinement proof: we may not enforce the peer's artifact directly.
        unmappable = _find_unmappable_constructs(source_policy, translated_policy)
        if unmappable:
            raise PolicyTranslationRefinementError(
                f"translated policy elides source constructs {unmappable}; "
                f"refusing to enforce a lossy projection at the data boundary"
            )
        # No certificate and no detected loss: re-derive locally, fail closed.
        return _locally_derive_conservative_policy(source_policy)

    if not _verify_refinement(source_policy, translated_policy, translator_certificate):
        raise PolicyTranslationRefinementError(
            "translator certificate does not prove translated(op)=deny wherever source(op)=deny"
        )
    return translated_policy


def _find_unmappable_constructs(source: dict, translated: dict) -> list[str]:
    # Exclusions expressed declaratively in source but imperatively in target
    # are the canonical loss site; a structural diff cannot see them.
    src_exclusions = {c for c in source.get("predicates", []) if c.get("op") in ("not_in", "subset_of")}
    tgt_masks = {m.get("field") for m in translated.get("masks", [])}
    return [c["field"] for c in src_exclusions if c["field"] not in tgt_masks]


def _verify_refinement(source: dict, translated: dict, cert: dict) -> bool:
    return cert.get("direction") == "refinement" and cert.get("verified") is True


def _locally_derive_conservative_policy(source: dict) -> dict:
    # Local derivation: every source exclusion becomes an explicit local mask.
    masks = [{"field": c["field"], "action": "deny"}
             for c in source.get("predicates", []) if c.get("op") in ("not_in", "subset_of")]
    return {"derived_locally": True, "masks": masks}
